Files
PaperClipAI/ui/src/pages/SkillStudio.test.tsx
T
DottaandPaperclip 0e15c92073 feat(skills): make managed content independent of web-server disk (#18334)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agents use installed skills and exact version pins during execution.
> - Managed skills still depended on mutable directories on the web
server.
> - A replacement server could lose acknowledged edits or remove an
unassigned skill whose directory was absent.
> - This pull request makes immutable versions the authority for managed
content and installed repository reads.
> - The server can rebuild delivery files from durable content after
replacement.
> - This establishes skills readiness for ephemeral web servers. General
server draining and workspace recovery remain separate work.

## Linked Issues or Issue Description

**Subsystem affected**

Skills services, shared contracts, database receipts, Skill Studio, and
runtime delivery.

**Problem or motivation**

A fresh web server must discover, read, edit, and deliver protected
installed skills using the same database, object storage, secrets, and
supported application artifacts. It must not need its predecessor's
files or process memory.

**Proposed solution**

Use `managed` ownership with a null source locator. Read installed
content by immutable version. Prepare packages before a short
publication transaction. Persist execution selections before
materialization. Recover exact pinned runtime assets and reject deletion
while active or recovering pins exist.

**Alternatives considered**

Reconstructing a mutable installed directory preserves the old
source-of-truth ambiguity. Permanent dual writes create two competing
authorities. This change uses one managed model after a bounded legacy
conversion.

**Roadmap alignment**

This improves the existing Skills Manager, Studio, version history, and
Cloud execution capabilities. The maintainer supplied the implementation
contract. This does not add a separate skills product or deploy fleet
changes.

Related work: #18082 supplies immutable package storage. #17273
addresses edits outside the API for linked local skills; this PR keeps
that source category separate. #2648 is a closed earlier
ephemeral-filesystem proposal.

## What Changed

- Add managed ownership and focused content publication and execution
materialization modules. Keep the archive format and package storage
tables.
- Publish managed create, save, delete, fork, rename, restore, and
catalog content with version checks. Add durable create receipts.
Preserve file-save receipt responses.
- Return file version identities. Keep Studio drafts after a conflict
and provide an explicit reload action. A delayed reload cannot overwrite
newer typing or navigation.
- Persist exact runtime selections, including empty selections. Rebuild
pinned assets and verify their admitted digests on a replacement server.
- Preserve source access on forks and disconnected copies. Keep the
existing workspace policy category for managed skills.
- Add bounded conversion, eligibility, and independent verification
phases. Load persisted Cloud configuration in the standalone CLI without
seeding or changing it. Reject partial current versions against
installed inventories; recover only complete saved content or the exact
source. Document storage migration blockers and the compatible rollback
floor.
- Add separate-process PostgreSQL/S3 qualification and update domain,
retention, policy, and UI regressions.
- Pass the plugin worker manager into Studio execution, admit restricted
`skill_test` mode through native Runner contracts, and preserve admitted
scope across native and REST tools. Native tests cannot create ordinary
tasks, browse company data, or use external tools.
- Select the exact durable Studio revision even when unassigned or Beta
skills is off. Persist Studio output and audit atomically with native
task completion, preserving the result on replay.

## Verification

- Final revision `13e8af480b88ba6fea5737bac4bd81104d604792` passed full
CI: all 49 workflow jobs completed successfully ([run
41127396098](https://github.com/paperclipai/paperclip/actions/runs/41127396098)).
This includes typecheck, test suites, Runner checks, browser checks and
build. Greptile review 15 is 5/5 on that same revision, with zero
unresolved threads. The PR is ready for review.
- Local workspace typecheck and build passed after integrating master.
Focused checks passed: 33 execution/completion cases, 52 Runner HTTP
cases, 16 managed-content cases, 17 Studio cases, the new real-process
CLI regression, map checks and UI token gates. The CLI regression proves
inspection does not seed missing Cloud configuration. Server typecheck
passed after that fix.
- The independent-process PostgreSQL/S3 matrix passed through normal
HTTP skill routes. It covers A → B → C replacement, lost commit
responses, upload crashes, concurrent saves, binary contents and
executable delivery. Metadata listing and warm selected delivery retain
zero object downloads. Local timing measurements are recorded; they do
not establish hosted latency.
- Hosted A → B → C passed on the owned disposable test tenant with
external Postgres, S3 and a real remote Paperclip Computer. Predecessor
temporary homes were absent. C read and executed B's acknowledged
managed save. New runs used repository v1 while v2 was installed. Hashes
matched an independently checked exact upstream commit.
- Compatible image rollback to `6518b323` passed. Studio retained the
unassigned fork's C save. A fresh remote run executed the newer managed
content and historical repository pin. The actual shell event confirmed
expected hashes, stdout, exit 0 and mode 0555.
- Runtime candidate `9200e3fcb4` deployed successfully ([Cloud run
41124147876](https://github.com/paperclipai/paperclip-cloud/actions/runs/41124147876)).
The final Studio test delivered only the unassigned fork's exact v3,
executed its script and persisted a successful output snapshot.
Independent command-event inspection confirmed all three hashes, stdout,
exit 0 and mode 0555. All 14 installations were version-backed.
Independent verification checked all 25 versions: 23 remote objects, two
bundled database snapshots, zero blockers.
- The deployed image is `9200e3fcb4`. Later master integration, the
client-only delayed-reload draft guard and the CLI bootstrap have
separate automated proof. The CLI bootstrap was also exercised against
the tenant's stored configuration and storage through the same read-only
services. This PR does not claim that the deployed image is the final PR
revision.
- Live Studio checks exposed worker wiring, admission, access scope,
exact selection and completion-publication gaps. They are fixed. Failed
attempts remain in the evidence. The full local suite exceeded 80
minutes under host contention and was stopped. Later combined/isolated
local attempts also timed out; they are not counted as passes. Full CI
covers the integrated suites. Earlier CI found an obsolete restart-scope
fixture, which was corrected and passed all 52 HTTP cases.
- Reproduction and migration:
[`doc/skill-ephemeral-web-servers.md`](doc/skill-ephemeral-web-servers.md).
Source revisions, deployments, versions, run IDs, hashes and failure
history:
[`doc/plans/2026-10-30-ephemeral-web-skills.md`](doc/plans/2026-10-30-ephemeral-web-skills.md).

## Risks

- Legacy conversion requires stopped admission and retired
filesystem-authoritative writers. Pre-conversion binaries are not
supported rollback targets afterward.
- Cloud readiness requires remote object storage. Local provider
receipts and provider mismatches remain blockers until objects are
copied and verified.
- Linked local sources retain filesystem semantics and are outside the
cloud guarantee.
- Cold reads still fetch the existing archive format. Warm runtime
preparation retains the verified-cache path.
- Bundled reconciliation preserves an installed head. Existing release
snapshots remain selectable. An older server must not replace a newer
head with its shipped files.
- No production volumes, fleet defaults, or general deployment
coordination change in this PR.

## Model Used

OpenAI Codex, GPT-6 family, with reasoning, repository tools, code
execution, and browser use. The exact backend model ID and
context-window size are not exposed in this session. No subagents were
used.

## 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
- [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: Paperclip <noreply@paperclip.ing>
2026-10-30 16:18:27 -05:00

764 lines
27 KiB
TypeScript

// @vitest-environment jsdom
import type { ReactNode } from "react";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type {
CompanySkillDetail,
CompanySkillLastEditor,
CompanySkillListItem,
} from "@paperclipai/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SkillStudio } from "./SkillStudio";
import { ApiError } from "@/api/client";
const routeState = vi.hoisted(() => ({
pathname: "/skills/studio/new",
search: "",
skillId: "new" as string | undefined,
}));
const mockNavigate = vi.hoisted(() => vi.fn());
const mockSetBreadcrumbs = vi.hoisted(() => vi.fn());
const mockCompanySkillsApi = vi.hoisted(() => ({
list: vi.fn(),
detail: vi.fn(),
create: vi.fn(),
file: vi.fn(),
updateFile: vi.fn(),
deleteFile: vi.fn(),
testInputs: vi.fn(),
updateTestInput: vi.fn(),
deleteTestInput: vi.fn(),
createTestInput: vi.fn(),
testRunTemplates: vi.fn(),
testRuns: vi.fn(),
createTestRunTemplate: vi.fn(),
updateTestRunTemplate: vi.fn(),
deleteTestRunTemplate: vi.fn(),
createTestRun: vi.fn(),
testRunDetail: vi.fn(),
cancelTestRun: vi.fn(),
deleteTestRun: vi.fn(),
versions: vi.fn(),
version: vi.fn(),
createVersion: vi.fn(),
}));
const mockAgentsApi = vi.hoisted(() => ({
list: vi.fn(),
}));
const mockIssuesApi = vi.hoisted(() => ({
listInteractions: vi.fn(),
acceptInteraction: vi.fn(),
respondToInteraction: vi.fn(),
rejectInteraction: vi.fn(),
}));
vi.mock("@/lib/router", () => ({
Link: ({ children, to, ...props }: { children: ReactNode; to: string }) => (
<a href={to} {...props}>{children}</a>
),
useLocation: () => ({ pathname: routeState.pathname, search: routeState.search, hash: "" }),
useNavigate: () => mockNavigate,
useParams: () => ({ skillId: routeState.skillId }),
useSearchParams: () => [new URLSearchParams(routeState.search), vi.fn()],
}));
vi.mock("@/context/BreadcrumbContext", () => ({
useBreadcrumbs: () => ({ setBreadcrumbs: mockSetBreadcrumbs }),
}));
vi.mock("../context/CompanyContext", () => ({
useCompany: () => ({ selectedCompanyId: "company-1" }),
}));
vi.mock("@/api/companySkills", () => ({
companySkillsApi: mockCompanySkillsApi,
}));
vi.mock("@/api/agents", () => ({
agentsApi: mockAgentsApi,
}));
vi.mock("@/api/issues", () => ({
issuesApi: mockIssuesApi,
}));
vi.mock("@/components/SearchableSelect", () => ({
SearchableSelect: ({
placeholder,
renderValue,
}: {
placeholder: string;
renderValue?: (option: null) => ReactNode;
}) => <button type="button">{renderValue ? renderValue(null) : placeholder}</button>,
}));
vi.mock("@/components/MarkdownEditor", () => ({
MarkdownEditor: ({
value,
onChange,
readOnly,
}: {
value: string;
onChange: (value: string) => void;
readOnly?: boolean;
}) => (
<textarea
data-testid="markdown-editor"
readOnly={readOnly}
value={value}
onChange={(event) => {
if (!readOnly) onChange(event.target.value);
}}
onKeyDown={(event) => {
if (!readOnly && event.key === "E") {
onChange(`${value}\n\nEdited body\n`);
}
}}
/>
),
}));
vi.mock("@/components/MarkdownBody", () => ({
MarkdownBody: ({ children }: { children: ReactNode }) => <div>{children}</div>,
}));
vi.mock("@/components/ui/resizable-panels", () => ({
ResizablePanelGroup: ({ children }: { children: ReactNode }) => <div>{children}</div>,
ResizablePanel: ({ children }: { children: ReactNode }) => <div>{children}</div>,
ResizableHandle: () => <div />,
}));
vi.mock("./CompanySkills", () => ({
SkillCardIcon: ({ card }: { card: { name: string } }) => (
<div data-testid="skill-card-icon">{card.name}</div>
),
}));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
let root: Root | null = null;
let container: HTMLDivElement | null = null;
async function act(callback: () => void | Promise<void>) {
let result: void | Promise<void> = undefined;
flushSync(() => {
result = callback();
});
await result;
}
/**
* Waits on the condition, not on a fixed number of turns. A hand-rolled retry
* loop is ample on an idle machine and not when the suite runs many workers in
* parallel: it gives up after N turns and reports a failure on behaviour that
* works. `vi.waitFor` retries against a time budget, so a loaded worker gets
* more turns instead.
*
* Same replacement as #11499 and #11521, which fixed the shorter-budget
* instances of this in the routing tests.
*
* This was a reimplementation of `vi.waitFor` down to rethrowing the last
* error, differing only in bounding on turns rather than on time.
*/
async function waitFor(assertion: () => void) {
await vi.waitFor(assertion);
}
async function renderStudio() {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
});
await act(async () => {
root?.render(
<QueryClientProvider client={queryClient}>
<SkillStudio />
</QueryClientProvider>,
);
});
return container;
}
async function inputValue(input: HTMLInputElement | HTMLTextAreaElement, value: string) {
await act(async () => {
const proto = input instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
const setter = Object.getOwnPropertyDescriptor(proto, "value")?.set;
setter?.call(input, value);
input.dispatchEvent(new Event("input", { bubbles: true }));
});
}
async function click(button: HTMLButtonElement) {
await act(async () => {
button.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
}
async function keyDown(element: HTMLElement, key: string) {
await act(async () => {
element.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key }));
});
}
function makeSkill(overrides: Partial<CompanySkillDetail> = {}): CompanySkillDetail {
return {
id: "source-skill",
companyId: "company-1",
key: "paperclip/demo-skill",
slug: "demo-skill",
name: "Demo Skill",
description: "A demo skill.",
markdown: "---\nname: Demo Skill\ndescription: Existing\n---\n\n# Demo Skill\n",
sourceType: "local_path",
sourceLocator: null,
sourceRef: null,
trustLevel: "markdown_only",
compatibility: "compatible",
fileInventory: [{ path: "SKILL.md", kind: "skill" }],
iconUrl: null,
color: null,
tagline: "Existing tagline",
authorName: null,
homepageUrl: null,
categories: ["engineering"],
sharingScope: "company",
publicShareToken: null,
forkedFromSkillId: null,
forkedFromCompanyId: null,
starCount: 0,
installCount: 0,
forkCount: 0,
currentVersionId: null,
metadata: null,
createdAt: new Date("2026-01-01T00:00:00Z"),
updatedAt: new Date("2026-01-02T00:00:00Z"),
attachedAgentCount: 0,
usedByAgents: [],
editable: true,
editableReason: null,
sourceLabel: "Local",
sourceBadge: "local",
sourcePath: null,
currentVersion: null,
starredByCurrentActor: false,
existingForks: [],
...overrides,
};
}
function buttonsNamed(node: ParentNode, name: string) {
return Array.from(node.querySelectorAll("button")).filter((button) =>
button.textContent?.trim() === name,
);
}
beforeEach(() => {
routeState.pathname = "/skills/studio/new";
routeState.search = "";
routeState.skillId = "new";
mockNavigate.mockReset();
mockSetBreadcrumbs.mockReset();
mockCompanySkillsApi.list.mockResolvedValue([]);
mockCompanySkillsApi.detail.mockResolvedValue(makeSkill());
mockCompanySkillsApi.create.mockResolvedValue({
id: "created-skill",
name: "Code Review",
forkedFromSkillId: null,
});
mockCompanySkillsApi.file.mockResolvedValue({
versionId: "read-version",
path: "SKILL.md",
content: "---\nname: Demo Skill\ndescription: Existing\n---\n\n# Demo Skill\n",
markdown: true,
editable: true,
editableReason: null,
});
mockCompanySkillsApi.updateFile.mockResolvedValue({
path: "SKILL.md",
content: "---\nname: Demo Skill\ndescription: Existing\n---\n\n# Demo Skill\n",
markdown: true,
editable: true,
editableReason: null,
});
mockCompanySkillsApi.deleteFile.mockResolvedValue({ deletedPaths: [] });
mockCompanySkillsApi.testInputs.mockResolvedValue([]);
mockCompanySkillsApi.updateTestInput.mockResolvedValue({ id: "input-1", name: "input.md", content: "" });
mockCompanySkillsApi.deleteTestInput.mockResolvedValue({ id: "input-1" });
mockCompanySkillsApi.createTestInput.mockResolvedValue({ id: "input-1", name: "input.md", content: "" });
mockCompanySkillsApi.testRunTemplates.mockResolvedValue([]);
mockCompanySkillsApi.testRuns.mockResolvedValue([]);
mockCompanySkillsApi.createTestRunTemplate.mockResolvedValue({ id: "template-1", name: "Template" });
mockCompanySkillsApi.updateTestRunTemplate.mockResolvedValue({ id: "template-1", name: "Template" });
mockCompanySkillsApi.deleteTestRunTemplate.mockResolvedValue({ id: "template-1", name: "Template" });
mockCompanySkillsApi.createTestRun.mockResolvedValue({ id: "run-1", status: "queued" });
mockCompanySkillsApi.testRunDetail.mockResolvedValue(null);
mockCompanySkillsApi.cancelTestRun.mockResolvedValue({ id: "run-1", status: "cancelled" });
mockCompanySkillsApi.deleteTestRun.mockResolvedValue({ id: "run-1" });
mockCompanySkillsApi.versions.mockResolvedValue([]);
mockCompanySkillsApi.createVersion.mockResolvedValue({ id: "version-1" });
mockAgentsApi.list.mockResolvedValue([]);
mockIssuesApi.listInteractions.mockResolvedValue([]);
mockIssuesApi.acceptInteraction.mockResolvedValue({});
mockIssuesApi.respondToInteraction.mockResolvedValue({});
mockIssuesApi.rejectInteraction.mockResolvedValue({});
});
afterEach(() => {
root?.unmount();
root = null;
container?.remove();
container = null;
document.body.innerHTML = "";
vi.clearAllMocks();
});
describe("SkillStudio create mode", () => {
it("renders /skills/studio/new as create mode instead of loading skill id new", async () => {
const node = await renderStudio();
await waitFor(() => expect(node.textContent).toContain("Create a new skill"));
expect(node.textContent).not.toContain("Skill not found.");
expect(mockCompanySkillsApi.detail).not.toHaveBeenCalledWith("company-1", "new");
expect(mockSetBreadcrumbs).toHaveBeenCalledWith([
{ label: "Skills", href: "/skills" },
{ label: "Studio", href: "/skills/studio" },
{ label: "New skill" },
]);
});
it("prefills fork drafts from the forkFrom query param", async () => {
routeState.search = "?forkFrom=source-skill";
const node = await renderStudio();
await waitFor(() => expect(node.textContent).toContain("Forking Demo Skill"));
expect(mockCompanySkillsApi.detail).toHaveBeenCalledWith("company-1", "source-skill");
expect((node.querySelector("#skill-name") as HTMLInputElement).value).toBe("Demo Skill Fork");
expect((node.querySelector("#skill-slug") as HTMLInputElement).value).toBe("demo-skill-fork");
});
it("creates a skill and navigates to the Studio editor for the new id", async () => {
const node = await renderStudio();
await waitFor(() => expect(node.querySelector("#skill-name")).toBeTruthy());
await inputValue(node.querySelector("#skill-name") as HTMLInputElement, "Code Review");
await click(buttonsNamed(node, "Create skill")[0] as HTMLButtonElement);
await waitFor(() => expect(mockCompanySkillsApi.create).toHaveBeenCalled());
expect(mockCompanySkillsApi.create).toHaveBeenCalledWith(
"company-1",
expect.objectContaining({
name: "Code Review",
slug: "code-review",
sharingScope: "company",
forkedFromSkillId: null,
}),
);
await waitFor(() => expect(mockNavigate).toHaveBeenCalledWith("/skills/studio/created-skill"));
});
it("forwards the folderId query param so the new skill is filed there (PAP-14086)", async () => {
routeState.search = "?folderId=folder-my-skills";
const node = await renderStudio();
await waitFor(() => expect(node.querySelector("#skill-name")).toBeTruthy());
await inputValue(node.querySelector("#skill-name") as HTMLInputElement, "Code Review");
await click(buttonsNamed(node, "Create skill")[0] as HTMLButtonElement);
await waitFor(() => expect(mockCompanySkillsApi.create).toHaveBeenCalled());
expect(mockCompanySkillsApi.create).toHaveBeenCalledWith(
"company-1",
expect.objectContaining({
name: "Code Review",
folderId: "folder-my-skills",
}),
);
});
it("keeps category commas and spaces editable while creating a skill", async () => {
const node = await renderStudio();
await waitFor(() => expect(node.querySelector("#skill-categories")).toBeTruthy());
await inputValue(node.querySelector("#skill-name") as HTMLInputElement, "Code Review");
await inputValue(node.querySelector("#skill-categories") as HTMLInputElement, "AI Tools, Developer Experience, ");
expect((node.querySelector("#skill-categories") as HTMLInputElement).value).toBe("AI Tools, Developer Experience, ");
await click(buttonsNamed(node, "Create skill")[0] as HTMLButtonElement);
await waitFor(() => expect(mockCompanySkillsApi.create).toHaveBeenCalled());
expect(mockCompanySkillsApi.create).toHaveBeenCalledWith(
"company-1",
expect.objectContaining({
categories: ["AI Tools", "Developer Experience"],
}),
);
});
});
function makeListItem(
overrides: Partial<CompanySkillListItem> & { id: string },
): CompanySkillListItem {
return {
companyId: "company-1",
key: overrides.id,
slug: overrides.id,
name: overrides.id,
description: null,
sourceType: "local_path",
sourceLocator: null,
sourceRef: null,
trustLevel: "markdown_only",
compatibility: "compatible",
fileInventory: [],
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: null,
createdAt: new Date("2026-01-01T00:00:00Z"),
updatedAt: new Date("2026-01-01T00:00:00Z"),
attachedAgentCount: 0,
editable: true,
editableReason: null,
sourceLabel: null,
sourceBadge: "local",
sourcePath: null,
catalogKind: null,
originHash: null,
packageName: null,
packageVersion: null,
...overrides,
};
}
const userEditor = (name: string): CompanySkillLastEditor => ({
kind: "user",
id: `user-${name}`,
name,
imageUrl: null,
});
const agentEditor: CompanySkillLastEditor = {
kind: "agent",
id: "agent-1",
name: "Bot",
imageUrl: null,
};
function findRowButton(node: ParentNode, name: string): HTMLButtonElement | undefined {
return Array.from(node.querySelectorAll("button")).find((button) =>
button.textContent?.includes(name),
) as HTMLButtonElement | undefined;
}
describe("SkillStudio landing", () => {
beforeEach(() => {
routeState.pathname = "/skills/studio";
routeState.search = "";
routeState.skillId = undefined;
localStorage.clear();
});
it("renders recently-visited and recently-updated sections, gating avatars to humans", async () => {
localStorage.setItem("paperclip:recent-studio-skills", JSON.stringify(["visited-1"]));
mockCompanySkillsApi.list.mockResolvedValue([
makeListItem({
id: "visited-1",
name: "Visited One",
updatedAt: new Date("2026-01-01T00:00:00Z"),
lastEditor: userEditor("Ada Lovelace"),
}),
makeListItem({
id: "agent-updated",
name: "Agent Updated",
updatedAt: new Date("2026-03-01T00:00:00Z"),
lastEditor: agentEditor,
}),
makeListItem({
id: "user-updated",
name: "User Updated",
updatedAt: new Date("2026-02-01T00:00:00Z"),
lastEditor: userEditor("Grace Hopper"),
}),
]);
const node = await renderStudio();
await waitFor(() => expect(node.textContent).toContain("Recently visited"));
expect(node.textContent).toContain("Recently updated");
// Visited section surfaces the visited skill; updated section excludes it.
const visitedSection = Array.from(node.querySelectorAll("section")).find((s) =>
s.querySelector("h2")?.textContent === "Recently visited",
)!;
const updatedSection = Array.from(node.querySelectorAll("section")).find((s) =>
s.querySelector("h2")?.textContent === "Recently updated",
)!;
expect(visitedSection.textContent).toContain("Visited One");
expect(updatedSection.textContent).not.toContain("Visited One");
expect(updatedSection.textContent).toContain("Agent Updated");
expect(updatedSection.textContent).toContain("User Updated");
// Only the two human-edited rows render an avatar (initials fallback); the
// agent-edited row renders none.
const initials = Array.from(node.querySelectorAll('[data-slot="avatar-fallback"]')).map(
(el) => el.textContent,
);
expect(initials).toEqual(["AL", "GH"]);
});
it("opens the clicked skill in Studio", async () => {
mockCompanySkillsApi.list.mockResolvedValue([
makeListItem({ id: "user-updated", name: "User Updated", lastEditor: userEditor("Grace Hopper") }),
]);
const node = await renderStudio();
await waitFor(() => expect(node.textContent).toContain("User Updated"));
const row = findRowButton(node, "User Updated")!;
await click(row);
expect(mockNavigate).toHaveBeenCalledWith(expect.stringContaining("user-updated"));
});
it("falls back to the empty state when there are no skills", async () => {
mockCompanySkillsApi.list.mockResolvedValue([]);
const node = await renderStudio();
await waitFor(() => expect(node.textContent).toContain("Select a skill to open Studio."));
expect(node.textContent).toContain("Create a new skill");
expect(node.textContent).not.toContain("Recently updated");
});
it("shows the loading fallback while skills load", async () => {
mockCompanySkillsApi.list.mockReturnValue(new Promise(() => {}));
const node = await renderStudio();
await waitFor(() => expect(node.textContent).toContain("Loading skills..."));
});
});
describe("SkillStudio editor frontmatter", () => {
beforeEach(() => {
routeState.pathname = "/skills/studio/source-skill";
routeState.search = "";
routeState.skillId = "source-skill";
});
it.each(["local_path", "managed"] as const)("restores %s history through its supported authoring path", async (sourceType) => {
mockCompanySkillsApi.detail.mockResolvedValue(makeSkill({ sourceType, currentVersionId: "head-version" }));
mockCompanySkillsApi.versions.mockResolvedValue([{ id: "old-version", revisionNumber: 1, createdAt: new Date() }]);
mockCompanySkillsApi.version.mockResolvedValue({ revisionNumber: 1, fileInventory: [
{ path: "SKILL.md", content: "# Restored" }, { path: "support.txt", content: "support" },
] });
if (sourceType === "local_path") {
mockCompanySkillsApi.updateFile.mockResolvedValueOnce({ versionId: "first-save" }).mockResolvedValueOnce({ versionId: "second-save" });
}
const node = await renderStudio();
await waitFor(() => expect(buttonsNamed(node, "Version history")[0]).toBeTruthy());
await click(buttonsNamed(node, "Version history")[0]!);
await waitFor(() => expect(buttonsNamed(document, "Restore as v2")[0]).toBeTruthy());
await click(buttonsNamed(document, "Restore as v2")[0]!);
await waitFor(() => expect(mockCompanySkillsApi.createVersion).toHaveBeenCalled());
if (sourceType === "managed") {
expect(mockCompanySkillsApi.updateFile).not.toHaveBeenCalled();
expect(mockCompanySkillsApi.createVersion).toHaveBeenCalledWith("company-1", "source-skill", {
sourceVersionId: "old-version", expectedVersionId: "head-version", label: "Restored saved version",
});
} else {
expect(mockCompanySkillsApi.updateFile).toHaveBeenNthCalledWith(1, "company-1", "source-skill", "SKILL.md", "# Restored", {
executable: false, expectedVersionId: "head-version",
});
expect(mockCompanySkillsApi.updateFile).toHaveBeenNthCalledWith(2, "company-1", "source-skill", "support.txt", "support", {
executable: false, expectedVersionId: "first-save",
});
expect(mockCompanySkillsApi.createVersion).toHaveBeenCalledWith("company-1", "source-skill", {
label: "Restore of v1", expectedVersionId: "second-save",
});
}
});
it("does not show the frontmatter section when the selected markdown file has no frontmatter", async () => {
mockCompanySkillsApi.file.mockResolvedValueOnce({
path: "SKILL.md",
content: "# Demo Skill\n\nNo YAML block here.\n",
markdown: true,
editable: true,
editableReason: null,
});
const node = await renderStudio();
await waitFor(() => {
expect(mockCompanySkillsApi.file).toHaveBeenCalledWith("company-1", "source-skill", "SKILL.md");
});
await waitFor(() => {
const textareas = Array.from(node.querySelectorAll("textarea"));
expect(textareas.some((textarea) => textarea.value.includes("No YAML block here."))).toBe(true);
});
expect(node.querySelector('[data-testid="frontmatter-panel"]')).toBeNull();
expect(node.textContent).not.toContain("Add frontmatter");
});
it("shows existing frontmatter collapsed by default", async () => {
const node = await renderStudio();
await waitFor(() => {
expect(node.querySelector('[data-testid="frontmatter-panel"]')).toBeTruthy();
});
const toggle = node.querySelector<HTMLButtonElement>('button[aria-controls="frontmatter-panel-body"]');
expect(toggle?.getAttribute("aria-expanded")).toBe("false");
expect(node.querySelector("#fm-name")).toBeNull();
});
it("marks rich markdown body edits dirty and saves the edited markdown", async () => {
mockCompanySkillsApi.updateFile.mockImplementationOnce((
_companyId: string,
_skillId: string,
path: string,
content: string,
) => Promise.resolve({
path,
content,
markdown: true,
editable: true,
editableReason: null,
}));
const node = await renderStudio();
let bodyEditor: HTMLTextAreaElement | undefined;
await waitFor(() => {
bodyEditor = Array.from(node.querySelectorAll<HTMLTextAreaElement>('[data-testid="markdown-editor"]')).find(
(editor) => editor.value.includes("# Demo Skill"),
);
expect(bodyEditor).toBeTruthy();
});
await keyDown(bodyEditor as HTMLElement, "E");
await waitFor(() => expect(node.textContent).toContain("Unsaved"));
const saveButton = buttonsNamed(node, "Save").find((button) => !button.disabled);
expect(saveButton).toBeTruthy();
await click(saveButton as HTMLButtonElement);
await waitFor(() => {
expect(mockCompanySkillsApi.updateFile).toHaveBeenCalledWith(
"company-1",
"source-skill",
"SKILL.md",
expect.stringContaining("Edited body"),
{ expectedVersionId: "read-version" },
);
});
expect(mockCompanySkillsApi.updateFile).toHaveBeenCalledWith(
"company-1",
"source-skill",
"SKILL.md",
expect.stringContaining("---\nname: Demo Skill"),
{ expectedVersionId: "read-version" },
);
});
it("keeps unsaved text on a version conflict and reloads only after confirmation", async () => {
mockCompanySkillsApi.updateFile.mockRejectedValueOnce(new ApiError("Skill version changed", 409, {}));
const node = await renderStudio();
let editor: HTMLTextAreaElement;
await waitFor(() => {
editor = Array.from(node.querySelectorAll<HTMLTextAreaElement>('[data-testid="markdown-editor"]'))
.find(candidate => candidate.value.includes("# Demo Skill"))!;
expect(editor).toBeTruthy();
});
await keyDown(editor!, "E");
await click(buttonsNamed(node, "Save").find(button => !button.disabled)!);
await waitFor(() => expect(node.textContent).toContain("This skill changed since you opened it"));
expect(editor!.value).toContain("Edited body");
mockCompanySkillsApi.file.mockResolvedValue({ path: "SKILL.md", content: "# New saved version", versionId: "new-version", markdown: true, editable: true });
const confirm = vi.spyOn(window, "confirm").mockReturnValueOnce(false).mockReturnValueOnce(true);
await click(buttonsNamed(node, "Load latest saved file")[0]!);
expect(editor!.value).toContain("Edited body");
await click(buttonsNamed(node, "Load latest saved file")[0]!);
await waitFor(() => expect(node.textContent).not.toContain("This skill changed since you opened it"));
expect(Array.from(node.querySelectorAll<HTMLTextAreaElement>('[data-testid="markdown-editor"]')).some(candidate => candidate.value.includes("# New saved version"))).toBe(true);
confirm.mockRestore();
});
it("preserves text typed while a confirmed latest-file reload is pending", async () => {
mockCompanySkillsApi.updateFile.mockRejectedValueOnce(new ApiError("Skill version changed", 409, {}));
const node = await renderStudio();
let editor: HTMLTextAreaElement;
await waitFor(() => {
editor = Array.from(node.querySelectorAll<HTMLTextAreaElement>('[data-testid="markdown-editor"]'))
.find(candidate => candidate.value.includes("# Demo Skill"))!;
expect(editor).toBeTruthy();
});
await keyDown(editor!, "E");
await click(buttonsNamed(node, "Save").find(button => !button.disabled)!);
await waitFor(() => expect(node.textContent).toContain("This skill changed since you opened it"));
const latest = { path: "SKILL.md", content: "# New saved version", versionId: "new-version", markdown: true, editable: true };
let resolveReload!: (value: typeof latest) => void;
mockCompanySkillsApi.file.mockImplementationOnce(() => new Promise(resolve => { resolveReload = resolve; }));
const confirm = vi.spyOn(window, "confirm").mockReturnValue(true);
await click(buttonsNamed(node, "Load latest saved file")[0]!);
await waitFor(() => expect(resolveReload).toBeTypeOf("function"));
await keyDown(editor!, "E");
const editedDuringReload = editor!.value;
resolveReload(latest);
await waitFor(() => expect(buttonsNamed(node, "Load latest saved file")[0]!.disabled).toBe(false));
expect(editor!.value).toBe(editedDuringReload);
expect(node.textContent).toContain("Unsaved");
expect(node.textContent).toContain("This skill changed since you opened it");
confirm.mockRestore();
});
it("offers a 'Make a copy' CTA on the read-only banner (PAP-13112)", async () => {
mockCompanySkillsApi.detail.mockResolvedValueOnce(makeSkill({
editable: false,
editableReason: "Bundled skill.",
}));
const node = await renderStudio();
await waitFor(() => expect(node.textContent).toContain("Bundled skill."));
// The dead-end "Fork" text link is replaced by a primary "Make a copy"
// button that opens the fork-confirm dialog (agent-switch flow).
const editCopy = Array.from(node.querySelectorAll("button")).find(
(button) => button.textContent?.trim() === "Make a copy",
);
expect(editCopy).toBeTruthy();
const staleForkLink = Array.from(node.querySelectorAll("a")).find((link) =>
link.getAttribute("href")?.includes("/skills/studio/new?forkFrom"),
);
expect(staleForkLink).toBeUndefined();
});
});