Files
PaperClipAI/ui/src/pages/CompanySkills.test.tsx
f4337bb5fb test(evals): land the chat catalog eval harness on master (#19614)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The chat-feature evals measure whether agents complete real chat
requests through the product
> - The chat catalog eval harness and its repairs live on the
`chat-eval/master-candidate` branch, not on master
> - Today's work made 139 of 242 chat evals pass in verified single-case
live runs. Each product fix landed on master as its own pull request
> - The eval-side changes (setups, graders, fault seams, evidence
capture) still exist only on the candidate
> - This pull request lands the harness on master. Master stays the
source of truth for product behavior
> - The benefit is one tree: evals run against master commits, and
product fixes reach the evals as soon as they merge

## Linked Issues or Issue Description

Refs #19441, Refs #19599, Refs #20270, Refs #20334, Refs #20342, Refs
#20344, Refs #20354, Refs #20360, Refs #20373, Refs #20382, Refs #20409

**What existing behavior does this improve?**
The chat catalog eval harness and the product it evaluates live on a
long-running branch outside master. Eval fixes do not reach master, so
master-based eval runs use old setups and graders.

**Subsystem affected**
`tests/runner-e2e` chat catalog harness, plus a small set of product
changes that exist only on the candidate.

**Proposed change**
Land the harness on master. Every product fix from this eval work
already merged to master as its own pull request. Conflicts keep
master's product behavior.

## What Changed

- Most of the diff (808 of 851 files) is under `tests/runner-e2e/`:
chat-catalog domains, scenarios, descriptors, the TestOps manifest,
private evidence tooling, and their tests.
- Graders now check saved state, setup literals and rendered or clicked
links. Many keyword and regex checks on free-form replies are removed.
Each changed grader has a bumped `oracleVersion` and calibration tests
(a valid reply, a reworded valid reply, and broken variants that must
fail).
- The shared link helper `hasLink` no longer treats a list link (for
example `/COM/issues?view=mine`) as a link to every task without a URL
key.
- Setup fixes build real state through supported product routes: routine
history, agent grants through the board grant route, budget holds with a
real cap, and a storage-layer archive fault for
`inbox-search.archive-partial-failure`.
- Browser boundary journeys (sign-in, chat-disabled, onboarding) now
write the standard pass evidence files.
- Retargeted cases, approved by the maintainer:
`agent-chat.chat-disabled` (Conference Room gate),
`agents.restore-instructions` (no saved instruction history),
`access.manage-membership` (member permission edits stay board-only).
- The private evidence trusted files (`manual-private-handoff.ts`,
`manual-private-retention.ts`, `manual-private-report-assets.ts`) are
byte-identical to master.
- Product files outside `tests/` (43 files, +1,328 −49) carry
candidate-only changes that master does not yet have. Most are tests.
The main code changes are in `request-human-input.ts`,
`heartbeat-run-summary.ts`, `native-completion-feedback.ts`,
`native-run-finalizer.ts`, `openapi.ts`, `secrets.ts` and
`IssueChatLongThreadPerf.tsx`.

## Verification

- `pnpm vitest run chat-catalog-domains chat-catalog-contract.test.ts
chat-catalog-consistency.test.ts unit-launcher.test.mjs
--testTimeout=180000` in `tests/runner-e2e`: 269 files pass, 3,550 tests
pass.
- `node --test chat-full-catalog-testops-manifest.test.mjs`: 10 pass.
- `node tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --check`:
no change.
- `tsc` for `server` and `tests/runner-e2e`: clean.
- Live single-case verification: 139 of 242 cases passed on paid runs,
and a person read the saved evidence for each. These are single-case
runs, not one full-cohort run.

## Risks

- Large diff. Most of it is test-only, but the 43 non-test files change
product code paths. Review those files first.
- Some graders are now less strict on reply wording. A person must read
replies for meaning on those cases.
- 42 cases need disposable outside accounts (Notion, Slack, GitHub,
Daytona and others) and stay blocked. `access.invite-teammate` stays
failing until local agent isolation lands, because the runner's durable
state keeps a live invite token.
- The paid workflow compares the trusted private-evidence files with
master. They are unchanged, so this risk is low.

## Model Used

Anthropic Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code
execution, in Claude Code. Subagents used the same model.

## 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 (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-10 08:02:11 -06:00

1433 lines
50 KiB
TypeScript

// @vitest-environment jsdom
import { act as reactAct, type ComponentProps, type ReactNode } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createRoot, type Root } from "react-dom/client";
import type { CatalogSkill, CompanySkillDetail, CompanySkillListItem, CompanySkillVersion, FolderListResult } from "@paperclipai/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
CompanySkills,
DiscoveryGrid,
InstallPreviewDialog,
SkillDetailPage,
buildDiscoveryCards,
defaultInstallAgentSelection,
getSkillVersionDiffSelection,
resolveDiscoveryTab,
withDiscoveryTab,
skillDetailBreadcrumbs,
} from "./CompanySkills";
import { ApiError } from "../api/client";
import { skillStudioNewRoute } from "../lib/company-skill-routes";
import { CompanySkills as ProductionCompanySkills } from "./CompanySkills.production";
import { queryKeys } from "../lib/queryKeys";
const readVersion = vi.hoisted(() => vi.fn());
const editorRoute = vi.hoisted(() => ({ path: undefined as string | undefined, search: "" }));
const mockCompanySkillsApi = vi.hoisted(() => ({
version: readVersion,
list: vi.fn(),
catalogList: vi.fn(),
detail: vi.fn(),
file: vi.fn(),
versions: vi.fn(),
updateStatus: vi.fn(),
catalogDetail: vi.fn(),
catalogFile: vi.fn(),
browseProject: vi.fn(),
updateFile: vi.fn(),
}));
const mockFoldersApi = vi.hoisted(() => ({ list: vi.fn() }));
const mockAgentsApi = vi.hoisted(() => ({ list: vi.fn() }));
vi.mock("../api/companySkills", () => ({ companySkillsApi: mockCompanySkillsApi }));
vi.mock("../api/folders", () => ({ foldersApi: mockFoldersApi }));
vi.mock("../api/agents", () => ({ agentsApi: mockAgentsApi }));
vi.mock("../context/CompanyContext", () => ({
useCompany: () => ({ selectedCompanyId: "company-1", selectedCompany: { id: "company-1", name: "Acme" } }),
}));
vi.mock("../context/BreadcrumbContext", () => ({
useBreadcrumbs: () => ({ setBreadcrumbs: vi.fn() }),
}));
vi.mock("../context/ToastContext", () => ({
useToast: () => ({ pushToast: vi.fn() }),
useToastActions: () => ({ pushToast: vi.fn() }),
}));
vi.mock("../hooks/useStreamlinedUiEnabled", () => ({
useStreamlinedUiEnabled: () => ({ enabled: true, loaded: true }),
}));
vi.mock("../adapters/use-adapter-capabilities", () => ({
useAdapterCapabilities: () => () => ({}),
}));
vi.mock("@/lib/router", () => ({
Link: ({ children, to, ...props }: { children: ReactNode; to: string }) => (
<a href={to} {...props}>{children}</a>
),
useNavigate: () => vi.fn(),
useParams: () => ({ "*": editorRoute.path }),
useSearchParams: () => [new URLSearchParams(editorRoute.search), vi.fn()],
}));
vi.mock("@/components/ui/button", () => ({
Button: ({
children,
type = "button",
variant: _variant,
size: _size,
asChild: _asChild,
...props
}: ComponentProps<"button"> & { asChild?: boolean; variant?: string; size?: string }) => (
<button type={type} {...props}>{children}</button>
),
}));
vi.mock("@/components/ui/dialog", () => ({
Dialog: ({ open, children }: { open?: boolean; children: ReactNode }) => (open ? <div>{children}</div> : null),
DialogContent: ({ children }: { children: ReactNode }) => <div role="dialog">{children}</div>,
DialogDescription: ({ children }: { children: ReactNode }) => <p>{children}</p>,
DialogFooter: ({ children }: { children: ReactNode }) => <div>{children}</div>,
DialogHeader: ({ children }: { children: ReactNode }) => <div>{children}</div>,
DialogTitle: ({ children }: { children: ReactNode }) => <h2>{children}</h2>,
}));
vi.mock("@/components/ui/dropdown-menu", () => ({
DropdownMenu: ({ children }: { children: ReactNode }) => <>{children}</>,
DropdownMenuContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
DropdownMenuItem: ({ children, onSelect }: { children: ReactNode; onSelect?: () => void }) => (
<button type="button" onClick={onSelect}>{children}</button>
),
DropdownMenuLabel: ({ children }: { children: ReactNode }) => <div>{children}</div>,
DropdownMenuRadioGroup: ({ children }: { children: ReactNode }) => <div>{children}</div>,
DropdownMenuRadioItem: ({ children, onSelect }: { children: ReactNode; onSelect?: () => void }) => (
<button type="button" onClick={onSelect}>{children}</button>
),
DropdownMenuSeparator: () => <hr />,
DropdownMenuSub: ({ children }: { children: ReactNode }) => <>{children}</>,
DropdownMenuSubContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
DropdownMenuSubTrigger: ({ children }: { children: ReactNode }) => <button type="button">{children}</button>,
DropdownMenuTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
}));
vi.mock("@/components/ui/popover", () => ({
Popover: ({ children }: { children: ReactNode }) => <>{children}</>,
PopoverContent: () => null,
PopoverTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
}));
vi.mock("@/components/ui/tooltip", () => ({
Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
TooltipContent: ({ children }: { children: ReactNode }) => <span>{children}</span>,
TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
}));
vi.mock("@/components/ui/tabs", () => ({
Tabs: ({ children }: { children: ReactNode }) => <div>{children}</div>,
TabsList: ({ children }: { children: ReactNode }) => <div>{children}</div>,
TabsTrigger: ({ children }: { children: ReactNode }) => <button type="button">{children}</button>,
}));
vi.mock("@/components/ui/checkbox", () => ({
Checkbox: (props: ComponentProps<"input">) => <input type="checkbox" {...props} />,
}));
vi.mock("../components/MarkdownBody", () => ({
MarkdownBody: ({ children }: { children: ReactNode }) => <div>{children}</div>,
}));
vi.mock("../components/MarkdownEditor", () => ({
MarkdownEditor: ({ value, onChange }: { value: string; onChange: (value: string) => void }) => <textarea aria-label="Skill markdown" value={value} onInput={event => onChange(event.currentTarget.value)} onChange={() => {}} />,
}));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
let root: Root | null = null;
let queryClient: QueryClient;
let container: HTMLDivElement | null = null;
async function act(callback: () => void | Promise<void>) {
await reactAct(async () => {
await callback();
});
}
afterEach(() => {
editorRoute.path = undefined;
editorRoute.search = "";
root?.unmount();
root = null;
queryClient?.clear();
container?.remove();
container = null;
});
function makeVersion(revisionNumber: number, content: string): CompanySkillVersion {
return {
id: `version-${revisionNumber}`,
companyId: "company-1",
companySkillId: "skill-1",
revisionNumber,
label: null,
releaseId: null,
releaseName: null,
releasedAt: null,
fileInventory: [
{
path: "SKILL.md",
kind: "skill",
content,
},
],
authorAgentId: null,
authorUserId: null,
createdAt: new Date(`2026-01-0${revisionNumber}T00:00:00Z`),
};
}
function makeDetail(currentVersion: CompanySkillVersion, overrides: Partial<CompanySkillDetail> = {}): CompanySkillDetail {
return {
id: "skill-1",
companyId: "company-1",
key: "demo-skill",
slug: "demo-skill",
name: "Demo Skill",
description: "A demo skill.",
markdown: "# Demo Skill",
sourceType: "local_path",
sourceLocator: null,
sourceRef: null,
trustLevel: "markdown_only",
compatibility: "compatible",
fileInventory: [{ path: "SKILL.md", kind: "skill" }],
iconUrl: null,
color: null,
tagline: null,
authorName: null,
homepageUrl: null,
categories: [],
sharingScope: "private",
publicShareToken: null,
forkedFromSkillId: null,
forkedFromCompanyId: null,
starCount: 0,
installCount: 0,
forkCount: 0,
currentVersionId: currentVersion.id,
metadata: null,
createdAt: new Date("2026-01-01T00:00:00Z"),
updatedAt: new Date("2026-01-02T00:00:00Z"),
attachedAgentCount: 0,
usedByAgents: [],
existingForks: [],
editable: true,
editableReason: null,
sourceLabel: "Local",
sourceBadge: "local",
sourcePath: null,
currentVersion,
starredByCurrentActor: false,
...overrides,
};
}
async function renderSkillDetail(
versions: CompanySkillVersion[],
props: Partial<ComponentProps<typeof SkillDetailPage>> = {},
) {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
readVersion.mockReset().mockImplementation(async (_company: string, _skill: string, id: string) => versions.find(version => version.id === id));
const detail = props.detail ?? makeDetail(versions[0]!);
await act(async () => {
root?.render(
<QueryClientProvider client={queryClient}><SkillDetailPage
detail={detail}
loading={false}
activeTab={props.activeTab ?? "versions"}
onTabChange={vi.fn()}
selectedPath="SKILL.md"
file={null}
fileLoading={false}
viewMode="preview"
editMode={false}
draft=""
setViewMode={vi.fn()}
setEditMode={vi.fn()}
setDraft={vi.fn()}
onSave={vi.fn()}
savePending={false}
versions={versions.map(version => ({ ...version, fileInventory: version.fileInventory.map(({ path, kind }) => ({ path, kind })) }))}
versionsLoading={false}
attachAgents={[]}
onSubmitAttach={vi.fn()}
attachPending={false}
expandedDirs={new Set()}
onToggleDir={vi.fn()}
onSelectPath={vi.fn()}
updateStatus={null}
updateStatusLoading={false}
onCheckUpdates={vi.fn()}
checkUpdatesPending={false}
onInstallUpdate={vi.fn()}
installUpdatePending={false}
onToggleStar={vi.fn()}
starPending={false}
onFork={vi.fn()}
onUpdateSettings={vi.fn()}
updateSettingsPending={false}
onDelete={vi.fn()}
deletePending={false}
{...props}
/></QueryClientProvider>,
);
});
return container;
}
async function renderDiscoveryGrid(props: Partial<ComponentProps<typeof DiscoveryGrid>> = {}) {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
await act(async () => {
root?.render(
<DiscoveryGrid
tab="installed"
categories={[]}
categoryTotal={0}
activeCategory={null}
onCategoryChange={vi.fn()}
search=""
onSearchChange={vi.fn()}
sort="agents"
onSortChange={vi.fn()}
cards={[]}
onOpenCard={vi.fn()}
loading={false}
error={null}
totalCount={0}
onCreate={vi.fn()}
onImport={vi.fn()}
onImportFromProject={vi.fn()}
onBrowseDiscover={vi.fn()}
onScan={vi.fn()}
scanPending={false}
scanStatus={null}
{...props}
/>,
);
});
return container;
}
const projectFolderResult: FolderListResult = {
kind: "skill",
allCount: 1,
unfiledCount: 0,
folders: [
{
id: "projects-root",
companyId: "company-1",
kind: "skill",
parentId: null,
name: "Projects",
slug: "projects",
systemKey: "projects",
path: "projects",
depth: 1,
color: null,
position: 0,
createdAt: new Date("2026-08-01T00:00:00Z"),
updatedAt: new Date("2026-08-01T00:00:00Z"),
itemCount: 1,
},
{
id: "project-folder",
companyId: "company-1",
kind: "skill",
parentId: "projects-root",
name: "Acme",
slug: "acme",
systemKey: "project:project-1",
path: "projects/acme",
depth: 2,
color: null,
position: 0,
createdAt: new Date("2026-08-01T00:00:00Z"),
updatedAt: new Date("2026-08-01T00:00:00Z"),
itemCount: 1,
},
],
};
function projectFolderGridProps() {
return {
folderResult: projectFolderResult,
onFolderSelect: vi.fn(),
onCreateFolder: vi.fn(),
onCreateFolderIn: vi.fn(),
onRenameFolder: vi.fn(),
onEditFolder: vi.fn(),
onMoveFolder: vi.fn(),
onDeleteFolder: vi.fn(),
} satisfies Partial<ComponentProps<typeof DiscoveryGrid>>;
}
function buttonsNamed(node: ParentNode, name: string) {
return Array.from(node.querySelectorAll("button")).filter((button) => button.textContent?.trim() === name);
}
async function click(button: HTMLElement) {
await act(async () => {
button.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
}
async function inputValue(input: HTMLInputElement, value: string) {
await act(async () => {
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
setter?.call(input, value);
input.dispatchEvent(new Event("input", { bubbles: true }));
});
}
async function selectValue(select: HTMLSelectElement, value: string) {
await act(async () => {
const setter = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, "value")?.set;
setter?.call(select, value);
select.dispatchEvent(new Event("change", { bubbles: true }));
});
}
describe("getSkillVersionDiffSelection", () => {
it("selects the previous saved revision or the initial baseline for row diffs", () => {
const v1 = makeVersion(1, "first");
const v2 = makeVersion(2, "second");
expect(getSkillVersionDiffSelection([v2, v1], v2.id)).toEqual({
leftVersionId: v1.id,
rightVersionId: v2.id,
});
expect(getSkillVersionDiffSelection([v2, v1], v1.id)).toEqual({
leftVersionId: null,
rightVersionId: v1.id,
});
});
});
describe("DiscoveryGrid IA presentation", () => {
it("uses the shared cards and toolbar for My Skills and preserves opening and creation actions", async () => {
const onOpenCard = vi.fn();
const onCreate = vi.fn();
const skill: CompanySkillListItem = {
...makeDetail(makeVersion(1, "# My Review Skill"), { id: "my-skill", name: "My Review Skill" }),
catalogKind: null, originHash: null, packageName: null, packageVersion: null,
};
const card = buildDiscoveryCards([skill], [])[0]!;
const node = await renderDiscoveryGrid({ collectionView: "authored", cards: [card], totalCount: 1, onOpenCard, onCreate, showBrowseRails: false });
expect(node.querySelector('input[aria-label="Search my skills"]')).not.toBeNull();
expect(node.querySelector('h1')?.textContent).toBe("My Skills");
const skillButton = Array.from(node.querySelectorAll<HTMLElement>('[role="button"]')).find(button => button.textContent?.includes("My Review Skill"))!;
await click(skillButton);
expect(onOpenCard).toHaveBeenCalledWith(card);
const create = buttonsNamed(node, "Create new skill")[0]!;
await click(create);
expect(onCreate).toHaveBeenCalledOnce();
expect(node.textContent).not.toContain("Recently visited");
});
it("makes the search scope explicit for Installed and Discover", async () => {
let node = await renderDiscoveryGrid({ tab: "installed" });
expect(node.querySelector('input[aria-label="Search installed skills"]')).not.toBeNull();
root?.unmount();
container?.remove();
root = null;
container = null;
node = await renderDiscoveryGrid({ tab: "discover" });
expect(node.querySelector('input[aria-label="Search discoverable skills"]')).not.toBeNull();
expect(node.textContent).not.toContain("Catalog");
});
it("distinguishes installation from agent enablement on cards", async () => {
const installedCard = {
key: "installed",
skillId: "skill-installed",
catalogRef: null,
name: "Installed Skill",
slug: "installed",
author: "Paperclip",
version: null,
tagline: null,
description: null,
categories: [],
iconUrl: null,
color: null,
starCount: 0,
agentCount: 0,
forkCount: 0,
installed: true,
required: false,
forkedFrom: false,
updatedAt: 0,
sourceBadge: "local" as const,
sourceLabel: "Local workspace",
};
const availableCard = {
...installedCard,
key: "available",
skillId: null,
catalogRef: "catalog-available",
name: "Available Skill",
slug: "available",
installed: false,
sourceBadge: "catalog" as const,
sourceLabel: "Paperclip catalog",
};
const node = await renderDiscoveryGrid({
tab: "discover",
cards: [installedCard, availableCard],
totalCount: 2,
});
expect(node.textContent).toContain("Not enabled for any agents");
expect(node.textContent).toContain("Available to install");
expect(node.textContent).toContain("Local workspace");
expect(node.textContent).toContain("Paperclip catalog");
});
it("uses the create callback from the New menu and empty state", async () => {
const onCreate = vi.fn();
const node = await renderDiscoveryGrid({ onCreate });
await click(buttonsNamed(node, "Create new skill")[0] as HTMLButtonElement);
await click(buttonsNamed(node, "Create a skill")[0] as HTMLButtonElement);
expect(onCreate).toHaveBeenCalledTimes(2);
});
it("uses one Discover action instead of Catalog or Bundled navigation", async () => {
const onBrowseDiscover = vi.fn();
const node = await renderDiscoveryGrid({ onBrowseDiscover });
await click(buttonsNamed(node, "Discover skills")[0] as HTMLButtonElement);
expect(onBrowseDiscover).toHaveBeenCalledOnce();
expect(node.textContent).not.toContain("Browse catalog");
expect(node.textContent).not.toContain("Bundled tab");
});
it("keeps folder creation in the compact rail control", async () => {
const props = projectFolderGridProps();
const node = await renderDiscoveryGrid(props);
const compactCreateButton = node.querySelector<HTMLButtonElement>('button[title="New folder"]');
expect(buttonsNamed(node, "New folder")).toHaveLength(0);
expect(compactCreateButton).not.toBeNull();
await click(compactCreateButton!);
expect(props.onCreateFolderIn).toHaveBeenCalledWith(null);
expect(props.onCreateFolder).not.toHaveBeenCalled();
});
it("removes category and folder browse rails while keeping search available", async () => {
const node = await renderDiscoveryGrid({
...projectFolderGridProps(),
categories: [{ slug: "design", count: 1 }],
categoryTotal: 1,
showBrowseRails: false,
});
expect(node.querySelector('nav[aria-label="Skill folders"]')).toBeNull();
expect(node.querySelector("aside")).toBeNull();
expect(node.textContent).not.toContain("Browse by category");
expect(node.querySelector('input[aria-label="Search installed skills"]')).not.toBeNull();
});
it("omits bulk selection when its entry point is not supplied", async () => {
const node = await renderDiscoveryGrid({
...projectFolderGridProps(),
onToggleSelectMode: undefined,
});
expect(buttonsNamed(node, "Select")).toHaveLength(0);
});
it("keeps folder creation available when no folder rail exists", async () => {
const onCreateFolder = vi.fn();
const node = await renderDiscoveryGrid({
...projectFolderGridProps(),
folderResult: { ...projectFolderResult, folders: [] },
onCreateFolder,
});
const createButton = buttonsNamed(node, "New folder")[0] as HTMLButtonElement;
expect(createButton).toBeDefined();
await click(createButton);
expect(onCreateFolder).toHaveBeenCalledOnce();
});
it("refreshes only the project represented by the active project folder", async () => {
const onScan = vi.fn();
const node = await renderDiscoveryGrid({
...projectFolderGridProps(),
folderSelection: "project-folder",
onScan,
});
const refreshButton = node.querySelector<HTMLButtonElement>(
'button[aria-label="Refresh Acme project skills"]',
);
expect(refreshButton).not.toBeNull();
await click(refreshButton!);
expect(onScan).toHaveBeenCalledOnce();
expect(onScan).toHaveBeenCalledWith("project-1");
});
it("does not open a skill when keyboard-activating its actions button", async () => {
const onOpenCard = vi.fn();
const card = {
key: "demo-skill",
skillId: "skill-1",
folderId: null,
catalogRef: null,
name: "Demo Skill",
slug: "demo-skill",
author: "Paperclip",
version: null,
tagline: null,
description: null,
categories: [],
iconUrl: null,
color: null,
starCount: 0,
agentCount: 0,
forkCount: 0,
installed: true,
required: false,
forkedFrom: false,
updatedAt: 0,
};
const node = await renderDiscoveryGrid({
cards: [card],
totalCount: 1,
onOpenCard,
folderResult: { kind: "skill", folders: [], allCount: 1, unfiledCount: 1 },
onMoveCard: vi.fn(),
onCreateFolderAndMoveCard: vi.fn(),
});
const actionsButton = node.querySelector<HTMLButtonElement>('[aria-label="More actions for Demo Skill"]');
await act(async () => {
actionsButton?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
});
expect(onOpenCard).not.toHaveBeenCalled();
});
it("does not offer move actions for skills in the bundled folder", async () => {
const card = {
key: "bundled-skill",
skillId: "skill-1",
folderId: "bundled-folder",
catalogRef: null,
name: "Bundled Skill",
slug: "bundled-skill",
author: "Paperclip",
version: null,
tagline: null,
description: null,
categories: [],
iconUrl: null,
color: null,
starCount: 0,
agentCount: 0,
forkCount: 0,
installed: true,
required: false,
forkedFrom: false,
updatedAt: 0,
};
const node = await renderDiscoveryGrid({
cards: [card],
totalCount: 1,
selectMode: true,
folderResult: {
kind: "skill",
folders: [{
id: "bundled-folder",
companyId: "company-1",
kind: "skill",
parentId: null,
name: "Bundled",
slug: "bundled",
systemKey: "bundled",
path: "bundled",
depth: 1,
color: null,
position: 0,
createdAt: new Date("2026-01-01T00:00:00Z"),
updatedAt: new Date("2026-01-01T00:00:00Z"),
itemCount: 1,
}],
allCount: 1,
unfiledCount: 0,
},
onMoveCard: vi.fn(),
onCreateFolderAndMoveCard: vi.fn(),
onOpenMoveCard: vi.fn(),
});
expect(node.querySelector('[aria-label="More actions for Bundled Skill"]')).toBeNull();
expect(node.querySelector('input[type="checkbox"]')).toBeNull();
expect(node.textContent).not.toContain("Move to folder");
});
});
describe("skills discovery tab routing", () => {
it("opens the folder-first installed view when the URL has no tab", () => {
expect(resolveDiscoveryTab(null)).toBe("installed");
expect(resolveDiscoveryTab("all")).toBe("discover");
expect(resolveDiscoveryTab("catalog")).toBe("discover");
expect(resolveDiscoveryTab("bundled")).toBe("discover");
});
it("uses Discover as the only explicit discovery URL and Installed as the default", () => {
const discoverParams = withDiscoveryTab(new URLSearchParams("folder=my&category=writing"), "discover");
expect(discoverParams.toString()).toBe("tab=discover");
const installedParams = withDiscoveryTab(new URLSearchParams("tab=all&folder=my"), "installed");
expect(installedParams.toString()).toBe("folder=my");
});
});
describe("skills discovery card reconciliation", () => {
it("renders one installed card when installed and catalog data share a key", () => {
const installed = {
id: "installed-new",
key: "PaperclipAI/Review",
name: "Review",
slug: "review",
updatedAt: new Date("2026-08-30T00:00:00Z"),
folderId: null,
authorName: "Paperclip",
packageVersion: "2.0.0",
sourceRef: null,
tagline: null,
description: "Installed copy",
categories: [],
iconUrl: null,
color: null,
starCount: 0,
attachedAgentCount: 2,
forkCount: 0,
catalogKind: "optional",
forkedFromSkillId: null,
sourceBadge: "catalog",
sourceLabel: "Paperclip",
} as unknown as CompanySkillListItem;
const olderDuplicate = {
...installed,
id: "installed-old",
key: "paperclipai/review",
updatedAt: new Date("2026-08-01T00:00:00Z"),
} as CompanySkillListItem;
const catalog = {
id: "catalog-review",
key: "paperclipai/review",
name: "Review",
slug: "review",
kind: "optional",
category: "quality",
description: "Catalog copy",
packageName: "Paperclip",
packageVersion: "2.0.0",
tags: [],
} as unknown as CatalogSkill;
const cards = buildDiscoveryCards([olderDuplicate, installed], [catalog, { ...catalog, id: "catalog-duplicate" }]);
expect(cards).toHaveLength(1);
expect(cards[0]).toMatchObject({
skillId: "installed-new",
catalogRef: "catalog-review",
installed: true,
agentCount: 2,
sourceKind: "optional",
});
});
});
describe("skill detail breadcrumbs", () => {
it("links each folder ancestor back to the installed folder view", () => {
const folders: FolderListResult = {
kind: "skill",
allCount: 1,
unfiledCount: 0,
folders: [
{
id: "my-root",
companyId: "company-1",
kind: "skill",
parentId: null,
name: "My Skills",
slug: "my",
systemKey: "my",
path: "my",
depth: 1,
color: null,
position: 0,
itemCount: 1,
createdAt: new Date("2026-07-16T00:00:00.000Z"),
updatedAt: new Date("2026-07-16T00:00:00.000Z"),
},
{
id: "review-folder",
companyId: "company-1",
kind: "skill",
parentId: "my-root",
name: "Review",
slug: "review",
systemKey: null,
path: "my/review",
depth: 2,
color: null,
position: 0,
itemCount: 1,
createdAt: new Date("2026-07-16T00:00:00.000Z"),
updatedAt: new Date("2026-07-16T00:00:00.000Z"),
},
],
};
expect(skillDetailBreadcrumbs({ name: "Deal with PR", folderId: "review-folder" }, folders)).toEqual([
{ label: "Skills", href: "/skills" },
{ label: "My Skills", href: "/skills?folder=my-root" },
{ label: "Review", href: "/skills?folder=review-folder" },
{ label: "Deal with PR" },
]);
});
});
describe("skillStudioNewRoute", () => {
it("builds a direct fork draft URL for a specific skill", () => {
expect(skillStudioNewRoute("skill 1")).toBe("/skills/studio/new?forkFrom=skill%201");
});
});
describe("SkillDetailPage versions tab", () => {
it("opens per-row version diffs for newest and oldest revisions", async () => {
const v1 = makeVersion(1, "# Demo Skill\n\nFirst line");
const v2 = makeVersion(2, "# Demo Skill\n\nSecond line");
const node = await renderSkillDetail([v2, v1]);
expect(readVersion).not.toHaveBeenCalled();
const viewDiffButtons = buttonsNamed(node, "View diff") as HTMLButtonElement[];
expect(viewDiffButtons).toHaveLength(2);
await click(viewDiffButtons[0]!);
let dialog = node.querySelector('[role="dialog"]') as HTMLElement;
let selects = Array.from(dialog.querySelectorAll("select"));
expect(dialog.textContent).toContain("Diff");
expect(selects[0]?.value).toBe(v1.id);
expect(selects[1]?.value).toBe(v2.id);
await act(() => vi.waitFor(() => expect(dialog.textContent).toContain("Second line")));
expect(readVersion).toHaveBeenCalledTimes(2);
await click(viewDiffButtons[1]!);
dialog = node.querySelector('[role="dialog"]') as HTMLElement;
selects = Array.from(dialog.querySelectorAll("select"));
expect(selects[0]?.value).toBe("");
expect(selects[1]?.value).toBe(v1.id);
expect(dialog.textContent).toContain("Initial");
await act(() => vi.waitFor(() => expect(dialog.textContent).toContain("First line")));
expect(dialog.textContent).not.toContain("Both sides are the same version");
});
});
describe("SkillDetailPage settings", () => {
it("humanizes the server folder path on a cold detail render", async () => {
const v1 = makeVersion(1, "# Demo Skill");
const node = await renderSkillDetail([v1], {
activeTab: "overview",
detail: makeDetail(v1, { folderPath: "engineering/code-review" }),
});
expect(node.textContent).toContain("Organization / Engineering / Code Review");
});
it("shows a direct make-a-copy action for read-only GitHub skills", async () => {
const v1 = makeVersion(1, "# Demo Skill");
const onFork = vi.fn();
const node = await renderSkillDetail([v1], {
activeTab: "overview",
detail: makeDetail(v1, {
editable: false,
editableReason: "Remote GitHub skills are read-only. Fork or import locally to edit them.",
sourceBadge: "github",
sourceLabel: "GitHub",
sourceType: "github",
}),
onFork,
});
expect(node.textContent).not.toContain("Fork or import locally");
const forkButton = buttonsNamed(node, "Make a copy")[0] as HTMLButtonElement;
expect(forkButton).toBeTruthy();
await click(forkButton);
expect(onFork).toHaveBeenCalledOnce();
});
it("renders long source paths in full so they can wrap inside the sidebar", async () => {
const v1 = makeVersion(1, "# Demo Skill");
const longSourcePath = "/srv/paperclip/home/paperclipai/paperclip/.agents/skills/prepare-pr/SKILL.md";
const node = await renderSkillDetail([v1], {
activeTab: "agents",
detail: makeDetail(v1, {
sourcePath: longSourcePath,
sourceLocator: null,
}),
});
const sourceValue = Array.from(node.querySelectorAll("div")).find((element) =>
element.textContent === longSourcePath,
);
expect(sourceValue).toBeTruthy();
expect(sourceValue?.className).toContain("[overflow-wrap:anywhere]");
expect(node.textContent).not.toContain("...");
});
it("saves normalized category edits from the settings dialog", async () => {
const v1 = makeVersion(1, "# Demo Skill");
const onUpdateSettings = vi.fn();
const node = await renderSkillDetail([v1], {
activeTab: "overview",
detail: makeDetail(v1, {
categories: ["engineering"],
sharingScope: "company",
}),
onUpdateSettings,
});
await click(buttonsNamed(node, "Settings")[0] as HTMLButtonElement);
const dialog = node.querySelector('[role="dialog"]') as HTMLElement;
const categoryInput = dialog.querySelector("input") as HTMLInputElement;
const saveButton = buttonsNamed(dialog, "Save settings")[0] as HTMLButtonElement;
expect(categoryInput.value).toBe("engineering");
await inputValue(categoryInput, " Memory Tools, review, memory tools ,,");
await click(saveButton);
expect(onUpdateSettings).toHaveBeenCalledWith({
sharingScope: "company",
categories: ["Memory Tools", "review"],
});
});
it("allows clearing categories and saving sharing together", async () => {
const v1 = makeVersion(1, "# Demo Skill");
const onUpdateSettings = vi.fn();
const node = await renderSkillDetail([v1], {
activeTab: "overview",
detail: makeDetail(v1, {
categories: ["engineering"],
sharingScope: "company",
}),
onUpdateSettings,
});
await click(buttonsNamed(node, "Settings")[0] as HTMLButtonElement);
const dialog = node.querySelector('[role="dialog"]') as HTMLElement;
await inputValue(dialog.querySelector("input") as HTMLInputElement, "");
await selectValue(dialog.querySelector("select") as HTMLSelectElement, "private");
await click(buttonsNamed(dialog, "Save settings")[0] as HTMLButtonElement);
expect(onUpdateSettings).toHaveBeenCalledWith({
sharingScope: "private",
categories: [],
});
});
it("does not treat reordered categories as dirty", async () => {
const v1 = makeVersion(1, "# Demo Skill");
const node = await renderSkillDetail([v1], {
activeTab: "overview",
detail: makeDetail(v1, {
categories: ["memory", "review"],
sharingScope: "company",
}),
});
await click(buttonsNamed(node, "Settings")[0] as HTMLButtonElement);
const dialog = node.querySelector('[role="dialog"]') as HTMLElement;
await inputValue(dialog.querySelector("input") as HTMLInputElement, "review, memory");
expect((buttonsNamed(dialog, "Save settings")[0] as HTMLButtonElement).disabled).toBe(true);
});
it("keeps the category draft visible while a failed save leaves detail unchanged", async () => {
const v1 = makeVersion(1, "# Demo Skill");
const detail = makeDetail(v1, {
categories: ["engineering"],
sharingScope: "company",
});
const onUpdateSettings = vi.fn();
const node = await renderSkillDetail([v1], {
activeTab: "overview",
detail,
onUpdateSettings,
});
await click(buttonsNamed(node, "Settings")[0] as HTMLButtonElement);
const categoryInput = node.querySelector('[role="dialog"] input') as HTMLInputElement;
await inputValue(categoryInput, "memory");
await click(buttonsNamed(node.querySelector('[role="dialog"]') as HTMLElement, "Save settings")[0] as HTMLButtonElement);
await act(async () => {
root?.render(
<QueryClientProvider client={queryClient}><SkillDetailPage
detail={detail}
loading={false}
activeTab="overview"
onTabChange={vi.fn()}
selectedPath="SKILL.md"
file={null}
fileLoading={false}
viewMode="preview"
editMode={false}
draft=""
setViewMode={vi.fn()}
setEditMode={vi.fn()}
setDraft={vi.fn()}
onSave={vi.fn()}
savePending={false}
versions={[v1]}
versionsLoading={false}
attachAgents={[]}
onSubmitAttach={vi.fn()}
attachPending={false}
expandedDirs={new Set()}
onToggleDir={vi.fn()}
onSelectPath={vi.fn()}
updateStatus={null}
updateStatusLoading={false}
onCheckUpdates={vi.fn()}
checkUpdatesPending={false}
onInstallUpdate={vi.fn()}
installUpdatePending={false}
onToggleStar={vi.fn()}
starPending={false}
onFork={vi.fn()}
onUpdateSettings={onUpdateSettings}
updateSettingsPending={false}
onDelete={vi.fn()}
deletePending={false}
/></QueryClientProvider>,
);
});
expect((node.querySelector('[role="dialog"] input') as HTMLInputElement).value).toBe("memory");
});
});
describe("install-time agent enablement", () => {
const agentOptions = [
{ id: "agent-ceo", name: "CEO", adapterType: "claude_local", supportsSkills: true, required: false, icon: null, paused: false },
{ id: "agent-designer", name: "Designer", adapterType: "claude_local", supportsSkills: true, required: false, icon: null, paused: true },
{ id: "agent-gateway", name: "Gateway", adapterType: "openclaw_gateway", supportsSkills: false, required: false, icon: null, paused: false },
{ id: "agent-builtin", name: "Summarizer", adapterType: "claude_local", supportsSkills: true, required: true, icon: null, paused: false },
];
function makeCatalogSkill(): CatalogSkill {
return {
id: "catalog-1",
key: "paperclipai/bundled/product/wireframe",
kind: "bundled",
category: "product",
slug: "wireframe",
name: "wireframe",
description: "Draw wireframes.",
path: "catalog/bundled/product/wireframe",
entrypoint: "SKILL.md",
trustLevel: "markdown_only",
compatibility: "compatible",
defaultInstall: false,
recommendedForRoles: [],
requires: [],
tags: [],
files: [{ path: "SKILL.md", kind: "skill", sizeBytes: 128, sha256: "abc" }],
contentHash: "sha256:abc",
};
}
it("defaults to every skills-capable, non-required agent", () => {
expect(defaultInstallAgentSelection(agentOptions)).toEqual(new Set(["agent-ceo", "agent-designer"]));
});
it("passes the default agent selection through onConfirm for fresh installs", async () => {
const onConfirm = vi.fn();
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
await act(async () => {
root?.render(
<InstallPreviewDialog
open
onOpenChange={vi.fn()}
skill={makeCatalogSkill()}
packageName={null}
packageVersion={null}
conflict={null}
defaultSlug="wireframe"
defaultForce={false}
defaultAction="install"
agents={agentOptions}
isPending={false}
error={null}
onConfirm={onConfirm}
/>,
);
});
const node = container as ParentNode;
expect(node.textContent).toContain("Enable for agents");
await click(buttonsNamed(node, "Install skill")[0] as HTMLButtonElement);
expect(onConfirm).toHaveBeenCalledWith({
slug: "wireframe",
force: false,
agentIds: expect.arrayContaining(["agent-ceo", "agent-designer"]),
});
expect(onConfirm.mock.calls[0][0].agentIds).toHaveLength(2);
});
it("keeps tracking the agent default when agents load after the dialog opens", async () => {
const onConfirm = vi.fn();
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
const renderDialog = (agents: typeof agentOptions) =>
root?.render(
<InstallPreviewDialog
open
onOpenChange={vi.fn()}
skill={makeCatalogSkill()}
packageName={null}
packageVersion={null}
conflict={null}
defaultSlug="wireframe"
defaultForce={false}
defaultAction="install"
agents={agents}
isPending={false}
error={null}
onConfirm={onConfirm}
/>,
);
// Dialog opens before the agents query resolves: nothing to select yet.
await act(async () => renderDialog([]));
// The agents arrive later; the untouched selection must pick them up.
await act(async () => renderDialog(agentOptions));
await click(buttonsNamed(container as ParentNode, "Install skill")[0] as HTMLButtonElement);
expect(onConfirm.mock.calls[0][0].agentIds).toHaveLength(2);
});
it("skips agent enablement for updates and replacements", async () => {
const onConfirm = vi.fn();
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
await act(async () => {
root?.render(
<InstallPreviewDialog
open
onOpenChange={vi.fn()}
skill={makeCatalogSkill()}
packageName={null}
packageVersion={null}
conflict={null}
defaultSlug="wireframe"
defaultForce={false}
defaultAction="update"
agents={agentOptions}
isPending={false}
error={null}
onConfirm={onConfirm}
/>,
);
});
const node = container as ParentNode;
expect(node.textContent).not.toContain("Enable for agents");
await click(buttonsNamed(node, "Install update")[0] as HTMLButtonElement);
expect(onConfirm).toHaveBeenCalledWith({ slug: "wireframe", force: false, agentIds: [] });
});
});
describe("CompanySkills page read resilience", () => {
function makeInstalledSkill(): CompanySkillListItem {
return {
id: "skill-1",
companyId: "company-1",
folderId: null,
folderPath: null,
key: "demo-skill",
slug: "demo-skill",
name: "Demo Skill",
description: "A demo skill.",
sourceType: "local_path",
sourceLocator: null,
sourceRef: null,
trustLevel: "markdown_only",
compatibility: "compatible",
fileInventory: [{ path: "SKILL.md", kind: "skill" }],
iconUrl: null,
color: null,
tagline: null,
authorName: null,
homepageUrl: null,
categories: [],
sharingScope: "private",
publicShareToken: null,
forkedFromSkillId: null,
forkedFromCompanyId: null,
starCount: 0,
installCount: 0,
forkCount: 0,
currentVersionId: "version-1",
createdAt: new Date("2026-01-01T00:00:00Z"),
updatedAt: new Date("2026-01-02T00:00:00Z"),
attachedAgentCount: 0,
editable: true,
editableReason: null,
sourceLabel: "Local",
sourceBadge: "local",
sourcePath: null,
catalogKind: null,
originHash: null,
packageName: null,
packageVersion: null,
};
}
const emptyFolders: FolderListResult = { kind: "skill", folders: [], allCount: 1, unfiledCount: 1 };
let queryClient: QueryClient;
async function settle() {
for (let attempt = 0; attempt < 3; attempt += 1) {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0));
});
}
}
async function renderPage(Page = CompanySkills) {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
await act(async () => {
root?.render(
<QueryClientProvider client={queryClient}>
<Page />
</QueryClientProvider>,
);
});
await settle();
return container;
}
beforeEach(() => {
vi.stubGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} });
queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
mockCompanySkillsApi.list.mockReset().mockResolvedValue([makeInstalledSkill()]);
mockCompanySkillsApi.catalogList.mockReset().mockResolvedValue([]);
mockFoldersApi.list.mockReset().mockResolvedValue(emptyFolders);
mockAgentsApi.list.mockReset().mockResolvedValue([]);
});
afterEach(() => {
queryClient.clear();
vi.unstubAllGlobals();
});
describe.each([["current", CompanySkills], ["production", ProductionCompanySkills]] as const)("%s file editor baseline", (_name, Page) => {
it("opens frontmatter markdown clean without an editor change, preserves edits and resets selection", async () => {
const frontmatter = "---\nname: demo-skill\ndescription: Keep this metadata.\ncustom: stable\n---\n\n";
const body = "# Demo Skill\n\nOriginal body.\n";
const content = frontmatter + body;
const detail = makeDetail(makeVersion(1, content));
detail.fileInventory.push({ path: "references/notes.md", kind: "reference" });
editorRoute.path = "demo-skill";
editorRoute.search = "tab=files";
const files: Record<string, string> = { "SKILL.md": content, "references/notes.md": "Reference body.\n" };
const readFile = (path: string) => ({ path, content: files[path], markdown: true, editable: true, encoding: "utf-8" });
mockCompanySkillsApi.detail.mockResolvedValue(detail);
mockCompanySkillsApi.file.mockImplementation(async (_company, _skill, path) => readFile(path));
mockCompanySkillsApi.versions.mockResolvedValue([]);
mockCompanySkillsApi.updateStatus.mockResolvedValue({ supported: false });
mockCompanySkillsApi.updateFile.mockReset().mockImplementation(async (_company, _skill, path, next) => {
files[path] = next;
return readFile(path);
});
const node = await renderPage(Page);
await vi.waitFor(() => expect(buttonsNamed(node, "Edit")).toHaveLength(1));
await click(buttonsNamed(node, "Edit")[0]!);
expect(node.textContent).not.toContain("Unsaved changes");
expect((buttonsNamed(node, "Save")[0] as HTMLButtonElement).disabled).toBe(true);
const editor = () => node.querySelector<HTMLTextAreaElement>('[aria-label="Skill markdown"]')!;
expect(editor().value).toBe(body);
expect(mockCompanySkillsApi.updateFile).not.toHaveBeenCalled();
const change = async (value: string) => act(() => {
Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(editor(), value);
editor().dispatchEvent(new Event("input", { bubbles: true }));
});
await change(body + "A real edit.\n");
expect(node.textContent).toContain("Unsaved changes");
expect((buttonsNamed(node, "Save")[0] as HTMLButtonElement).disabled).toBe(false);
await click(buttonsNamed(node, "Discard")[0]!);
await click(buttonsNamed(node, "Edit")[0]!);
expect(editor().value).toBe(body);
expect(node.textContent).not.toContain("Unsaved changes");
await change(body + "Saved edit.\n");
await click(buttonsNamed(node, "Save")[0]!);
await vi.waitFor(() => expect(mockCompanySkillsApi.updateFile).toHaveBeenCalledWith("company-1", "skill-1", "SKILL.md", frontmatter + body + "Saved edit.\n"));
expect(detail.description).toBe("A demo skill.");
await settle();
await click(buttonsNamed(node, "Edit")[0]!);
await change(body + "Unsaved prior-file edit.\n");
editorRoute.path = "demo-skill/files/references/notes.md";
await act(() => root?.render(<QueryClientProvider client={queryClient}><Page /></QueryClientProvider>));
await settle();
await click(buttonsNamed(node, "Edit")[0]!);
expect(editor().value).toBe("Reference body.\n");
expect(node.textContent).not.toContain("Unsaved changes");
expect((buttonsNamed(node, "Save")[0] as HTMLButtonElement).disabled).toBe(true);
expect(mockCompanySkillsApi.updateFile).toHaveBeenCalledTimes(1);
});
});
describe.each([["current", CompanySkills], ["production", ProductionCompanySkills]] as const)("%s discovery errors", (_name, Page) => {
it.each([["skills", 403], ["skills", 429], ["catalog", 403], ["catalog", 429]] as const)(
"shows a %s %s failure while the other read pauses and keeps its own Retry usable",
async (failed, status) => {
const failedRead = failed === "skills" ? mockCompanySkillsApi.list : mockCompanySkillsApi.catalogList;
const otherRead = failed === "skills" ? mockCompanySkillsApi.catalogList : mockCompanySkillsApi.list;
const failedResult = failed === "skills" ? [makeInstalledSkill()] : [];
const otherResult = failed === "skills" ? [] : [makeInstalledSkill()];
failedRead.mockRejectedValueOnce(new ApiError("Read rejected", status, null)).mockResolvedValue(failedResult);
let resume!: () => void;
otherRead.mockImplementationOnce(() => new Promise(resolve => { resume = () => resolve(otherResult); }));
const node = await renderPage(Page);
const otherKey = failed === "skills" ? queryKeys.companySkills.catalog() : queryKeys.companySkills.list("company-1");
const otherQuery = queryClient.getQueryCache().find({ queryKey: otherKey, exact: true })!;
await act(() => { otherQuery.setState({ fetchStatus: "paused" }); });
expect(node.querySelector('[data-query-view="error"]')).not.toBeNull();
await act(() => { otherQuery.setState({ fetchStatus: "fetching" }); });
const error = node.querySelector('[data-query-view="error"]')!;
expect(error).not.toBeNull();
const retry = error.querySelector("button");
if (status === 429) {
expect(retry).not.toBeNull();
expect(retry!.disabled).toBe(false);
await click(retry!); await settle();
expect(failedRead).toHaveBeenCalledTimes(2);
expect(otherRead).toHaveBeenCalledOnce();
expect(node.querySelector('[data-query-view="error"]')).toBeNull();
await act(async () => { resume(); }); await settle();
expect(node.textContent).toContain("Demo Skill");
} else {
expect(retry).toBeNull();
await act(async () => { resume(); }); await settle();
expect(node.querySelector('[data-query-view="error"]')).not.toBeNull();
}
},
);
});
it("keeps installed skills visible when a refetch fails during an outage", async () => {
const node = await renderPage();
expect(node.textContent).toContain("Demo Skill");
mockCompanySkillsApi.list.mockRejectedValue(
new ApiError("Paperclip is restarting.", 503, { error: "tenant_app_unavailable" }),
);
await act(async () => {
await queryClient.invalidateQueries({ queryKey: ["company-skills"] });
});
await settle();
expect(mockCompanySkillsApi.list).toHaveBeenCalledTimes(2);
expect(node.textContent).toContain("Demo Skill");
expect(node.querySelector('[data-query-view="error"]')).toBeNull();
expect(node.textContent).not.toContain("Paperclip is restarting.");
});
it("shows readable copy and a Retry button when the skill list fails to load", async () => {
mockCompanySkillsApi.list
.mockReset()
.mockRejectedValueOnce(new ApiError("Boom", 500, { error: "Boom" }))
.mockResolvedValue([makeInstalledSkill()]);
const node = await renderPage();
const errorState = node.querySelector('[data-query-view="error"]');
expect(errorState).not.toBeNull();
expect(errorState?.textContent).toContain("Couldn't load skills");
expect(errorState?.textContent).toContain("Boom");
expect(node.textContent).not.toContain("Demo Skill");
const retryButton = Array.from(errorState?.querySelectorAll("button") ?? []).find((button) =>
button.textContent?.includes("Retry"),
) as HTMLButtonElement | undefined;
expect(retryButton).toBeTruthy();
await act(async () => retryButton?.click());
await settle();
expect(mockCompanySkillsApi.list).toHaveBeenCalledTimes(2);
expect(node.textContent).toContain("Demo Skill");
expect(node.querySelector('[data-query-view="error"]')).toBeNull();
});
});
it.each(["overview", "files"] as const)("exposes the real named Edit control only in the %s tab", async activeTab => {
const version = makeVersion(1, "# Demo skill\n\nSaved body");
const setEditMode = vi.fn();
const node = await renderSkillDetail([version], { activeTab, setEditMode,
file: { skillId: "skill-1", path: "SKILL.md", kind: "skill", content: "# Demo skill\n\nSaved body", language: "markdown", markdown: true, editable: true, encoding: "utf8" } });
expect(buttonsNamed(node, "Files")).toHaveLength(1);
const edit = buttonsNamed(node, "Edit");
expect(edit).toHaveLength(activeTab === "files" ? 1 : 0);
if (activeTab === "files") { await click(edit[0]!); expect(setEditMode).toHaveBeenCalledExactlyOnceWith(true); }
});