diff --git a/.changeset/eval-review-exit-ramp.md b/.changeset/eval-review-exit-ramp.md new file mode 100644 index 00000000..c11846a2 --- /dev/null +++ b/.changeset/eval-review-exit-ramp.md @@ -0,0 +1,9 @@ +--- +'@storybook/addon-mcp': patch +--- + +Make display-review the single ending for visual work: the after-change instruction step now feeds story discovery into the review instead of ending at preview URLs, preview-stories is framed as a mid-loop tool, the "or you skipped it" escape is removed (non-visual changes say so plainly instead of listing links), and get-changed-stories results append a "publish the review now" next-step hint when review is enabled. Fixes agents completing visual changes but handing back preview links instead of the review. + +The preview-stories tool also closes the review exit ramp: when review is enabled its description states display-review's availability as fact instead of hedging with "when available" (which let an agent that wrongly believed the tool was missing treat raw links as a sanctioned fallback), and its results append a recovery nudge pointing finished visual work and browse requests back to display-review. When review is disabled, the description no longer mentions display-review at all — the tool is not registered in those sessions. + +The get-storybook-story-instructions story-linking workflow gets the same review-aware rewrite: with review enabled it now routes discovered story IDs into display-review and forbids constructing IDs from file names or memory, instead of framing get-changed-stories as a preview-stories helper. The `storybook ai --help` output embeds the same server instructions, so on the CLI/plugin path the two channels contradicted each other — this tool, billed as the source of truth for story work, still pointed discovery at previews, and agents were observed resolving the conflict by publishing reviews with hand-derived story IDs and zero discovery calls. diff --git a/agent-eval/README.md b/agent-eval/README.md index 254409b0..7ff7851b 100644 --- a/agent-eval/README.md +++ b/agent-eval/README.md @@ -51,14 +51,23 @@ pnpm exec agent-eval cc-mcp-opus-high Pull requests with the `ci:eval` label run all experiments in CI. By default only the first core eval (`801-create-component-no-launch-config`) -runs. Set `EVAL_EXTRA_EVALS=1` to run the full hand-crafted 8xx eval line, or -`EVAL_ONLY=[,]` to debug specific core evals one at a time: +runs. Set `EVAL_EXTRA_EVALS=1` to run the full hand-crafted line — the 8xx +workflow evals on every experiment plus the lifecycle 82x evals +(`storybook-init`/`storybook-upgrade` scenarios) on the plugin experiments — +or `EVAL_ONLY=[,]` to debug specific evals one at a time: ```bash EVAL_EXTRA_EVALS=1 pnpm eval EVAL_ONLY=803-edit-component pnpm eval ``` +A full `EVAL_EXTRA_EVALS=1` run (12 workflow evals × 4 experiments + 3 +lifecycle evals × 2 plugin experiments) costs roughly **$30–45** in agent +tokens at current per-run averages ($0.30–0.80 per workflow eval, $1–2 per +lifecycle eval). The budget guardrail is **$75 per full run** — check the +usage metadata in the results playground before growing the eval set past it +(see storybookjs/mcp#324). + The 9xx evals (ports from the old `/eval` system) never run automatically; see `lib/experiment.ts`. @@ -121,6 +130,21 @@ Templates live in `agent-eval/templates/` and are copied into the sandbox during setup before the agent runs. They intentionally stay visible in saved result project snapshots so eval runs are easy to inspect. +Three templates exist today: + +- `reshaped-storybook`: the design-system shape — Reshaped components, full + Storybook (`next`) with the local addon builds, MSW, and the vitest story + test setup. +- `vite-app`: a minimal React + Vite app with **no Storybook at all**. The + lifecycle fixtures use it directly (820 init) or layer an old Storybook on + top (821/822 upgrades, which also set `evals.pinStorybook: false` so the + harness keeps their intentionally outdated versions); 812 layers a full + Storybook `next` setup with zero stories on top. +- `monorepo`: an npm-workspaces repo where the runnable Storybook lives in the + `packages/ui` leaf (the spec's monorepo-leaf project shape). Storybook + pinning and the local `file:` build detection cover workspace package.json + files too. + This keeps prompt variants small: each variant keeps its own `PROMPT.md`, `EVAL.ts`, and metadata `package.json`, while shared app files stay in the template. diff --git a/agent-eval/evals/801-create-component-no-launch-config/EVAL.ts b/agent-eval/evals/801-create-component-no-launch-config/EVAL.ts index 24ca4071..3fbab489 100644 --- a/agent-eval/evals/801-create-component-no-launch-config/EVAL.ts +++ b/agent-eval/evals/801-create-component-no-launch-config/EVAL.ts @@ -5,6 +5,10 @@ import { expectAllStoryExportsInDisplayReview, expectDisplayReviewForVisualChange, expectPreviewBrowserStarted, + expectSkillInvoked, + getEvalContext, + expectStoryDiscoveryBeforeReview, + expectStoryTestsRanAndPassed, expectValidStorybookLaunchConfig, expectWorkflowCalls, } from '#test-utils'; @@ -27,6 +31,19 @@ test('uses Storybook story instructions and publishes a display review', () => { expectDisplayReviewForVisualChange(); }); +// Required workflow step (dev instructions "Mapping any input to story IDs"): +// story IDs in the review must come from a discovery tool, not from guessing. +test('discovers stories through the workflow tools before publishing the review', () => { + expectStoryDiscoveryBeforeReview(); +}); + +// Required workflow step (test-instructions.md Validation Workflow): run +// run-story-tests after the change and do not report completion while story +// tests are failing. +test('runs story tests after the change and finishes with them passing', () => { + expectStoryTestsRanAndPassed({ covering: ['toggleswitch'] }); +}); + // Yann confirmed §6a.2 (2026-07-02, #sb-ade-plugins): stories the agent // created must always appear in the review; curation groups, it never omits. // The display-review hard rules and server instructions now state this. @@ -49,6 +66,13 @@ test.skip('publishes a well-curated review', async () => { // The fixture overrides the template's .claude/launch.json with an empty // configurations array (fixtures can only overwrite files, not delete them), // so the plugin must set up the Storybook launch entry itself. +// The plugin path must engage the stories skill (Claude: via the Skill tool; +// Codex: by reading its SKILL.md). Skipped on the MCP integration, where no +// skills are installed. +test.skipIf(getEvalContext().integration === 'mcp')('invokes the stories skill', () => { + expectSkillInvoked('stories'); +}); + test('writes a valid Storybook launch config for Claude preview tooling', () => { expectValidStorybookLaunchConfig(); }); diff --git a/agent-eval/evals/802-create-component/EVAL.ts b/agent-eval/evals/802-create-component/EVAL.ts index 22463ddb..22cc297f 100644 --- a/agent-eval/evals/802-create-component/EVAL.ts +++ b/agent-eval/evals/802-create-component/EVAL.ts @@ -1,7 +1,12 @@ import { test } from 'vitest'; import { + expectAllStoryExportsInDisplayReview, expectDisplayReviewForVisualChange, expectPreviewBrowserStarted, + expectSkillInvoked, + getEvalContext, + expectStoryDiscoveryBeforeReview, + expectStoryTestsRanAndPassed, expectValidStorybookLaunchConfig, expectWorkflowCalls, } from '#test-utils'; @@ -14,6 +19,32 @@ test('uses Storybook story instructions and publishes a display review', () => { expectDisplayReviewForVisualChange(); }); +// Same clean-project create scenario as 801, so the §6a.2 completeness rule +// applies identically: every story the agent created must appear in the review. +test('every new story appears in the display review', () => { + expectAllStoryExportsInDisplayReview(); +}); + +// Required workflow step (dev instructions "Mapping any input to story IDs"): +// story IDs in the review must come from a discovery tool, not from guessing. +test('discovers stories through the workflow tools before publishing the review', () => { + expectStoryDiscoveryBeforeReview(); +}); + +// Required workflow step (test-instructions.md Validation Workflow): run +// run-story-tests after the change and do not report completion while story +// tests are failing. +test('runs story tests after the change and finishes with them passing', () => { + expectStoryTestsRanAndPassed({ covering: ['profilecard'] }); +}); + +// The plugin path must engage the stories skill (Claude: via the Skill tool; +// Codex: by reading its SKILL.md). Skipped on the MCP integration, where no +// skills are installed. +test.skipIf(getEvalContext().integration === 'mcp')('invokes the stories skill', () => { + expectSkillInvoked('stories'); +}); + test('keeps the pre-existing Storybook launch config valid', () => { expectValidStorybookLaunchConfig(); }); diff --git a/agent-eval/evals/803-edit-component/EVAL.ts b/agent-eval/evals/803-edit-component/EVAL.ts index 0aa09deb..cfdba287 100644 --- a/agent-eval/evals/803-edit-component/EVAL.ts +++ b/agent-eval/evals/803-edit-component/EVAL.ts @@ -2,7 +2,11 @@ import { test } from 'vitest'; import { expectDisplayReviewForVisualChange, expectPreviewBrowserStarted, + expectSkillInvoked, + getEvalContext, + expectStoryDiscoveryBeforeReview, expectStoryIdsInDisplayReview, + expectStoryTestsRanAndPassed, expectValidStorybookLaunchConfig, expectWorkflowCalls, } from '#test-utils'; @@ -21,6 +25,26 @@ test('the review covers the edited ReviewCard component', () => { expectStoryIdsInDisplayReview(['reviewcard']); }); +// Required workflow step (dev instructions "Mapping any input to story IDs"): +// story IDs in the review must come from a discovery tool, not from guessing. +test('discovers stories through the workflow tools before publishing the review', () => { + expectStoryDiscoveryBeforeReview(); +}); + +// Required workflow step (test-instructions.md Validation Workflow): run +// run-story-tests after the change and do not report completion while story +// tests are failing. +test('runs story tests after the change and finishes with them passing', () => { + expectStoryTestsRanAndPassed({ covering: ['reviewcard'] }); +}); + +// The plugin path must engage the stories skill (Claude: via the Skill tool; +// Codex: by reading its SKILL.md). Skipped on the MCP integration, where no +// skills are installed. +test.skipIf(getEvalContext().integration === 'mcp')('invokes the stories skill', () => { + expectSkillInvoked('stories'); +}); + test('keeps the pre-existing Storybook launch config valid', () => { expectValidStorybookLaunchConfig(); }); diff --git a/agent-eval/evals/804-write-story-for-existing-component/EVAL.ts b/agent-eval/evals/804-write-story-for-existing-component/EVAL.ts index 64a9cecd..0d32c9a6 100644 --- a/agent-eval/evals/804-write-story-for-existing-component/EVAL.ts +++ b/agent-eval/evals/804-write-story-for-existing-component/EVAL.ts @@ -2,7 +2,11 @@ import { test } from 'vitest'; import { expectDisplayReviewForVisualChange, expectPreviewBrowserStarted, + expectSkillInvoked, + getEvalContext, + expectStoryDiscoveryBeforeReview, expectStoryIdsInDisplayReview, + expectStoryTestsRanAndPassed, expectValidStorybookLaunchConfig, expectWorkflowCalls, } from '#test-utils'; @@ -22,6 +26,26 @@ test('the review covers the new AlertBanner stories', () => { expectStoryIdsInDisplayReview(['alertbanner']); }); +// Required workflow step (dev instructions "Mapping any input to story IDs"): +// story IDs in the review must come from a discovery tool, not from guessing. +test('discovers stories through the workflow tools before publishing the review', () => { + expectStoryDiscoveryBeforeReview(); +}); + +// Required workflow step (test-instructions.md Validation Workflow): run +// run-story-tests after the change and do not report completion while story +// tests are failing. +test('runs story tests after the change and finishes with them passing', () => { + expectStoryTestsRanAndPassed({ covering: ['alertbanner'] }); +}); + +// The plugin path must engage the stories skill (Claude: via the Skill tool; +// Codex: by reading its SKILL.md). Skipped on the MCP integration, where no +// skills are installed. +test.skipIf(getEvalContext().integration === 'mcp')('invokes the stories skill', () => { + expectSkillInvoked('stories'); +}); + test('keeps the pre-existing Storybook launch config valid', () => { expectValidStorybookLaunchConfig(); }); diff --git a/agent-eval/evals/808-shared-infra-fallback/EVAL.ts b/agent-eval/evals/808-shared-infra-fallback/EVAL.ts new file mode 100644 index 00000000..455865cf --- /dev/null +++ b/agent-eval/evals/808-shared-infra-fallback/EVAL.ts @@ -0,0 +1,97 @@ +import { readFileSync } from 'node:fs'; +import { expect, test } from 'vitest'; +import { + expectDisplayReviewForVisualChange, + expectPreviewBrowserStarted, + expectSkillInvoked, + expectStoryDiscoveryBeforeReview, + expectStoryIdsInDisplayReview, + expectStoryTestsRanAndPassed, + expectValidStorybookLaunchConfig, + getEvalContext, + getWorkflowCalls, + getWorkflowToolResults, +} from '#test-utils'; + +// Shared-infrastructure change (Agentic Review Eval instructions §7 branch 2): +// the edited token file has no stories of its own, so the review must surface +// the stories of its *consumers* (Badge and StatusPill). + +// Guard against a vacuous pass: skipping the fallback only counts if the token +// change was actually performed. +test('changes the accent color token', () => { + const colors = readFileSync('src/theme/colors.ts', 'utf8'); + expect(colors, 'Expected the accent token to change to #7c3aed').toMatch(/#7c3aed/i); + expect(colors, 'Expected the old accent value #2563eb to be gone').not.toMatch(/#2563eb/i); +}); + +test('publishes a display review for the visual token change', () => { + expectDisplayReviewForVisualChange(); +}); + +test('the review surfaces the consumer stories, not the token file', () => { + expectStoryIdsInDisplayReview(['badge', 'statuspill']); +}); + +test('discovers stories through the workflow tools before publishing the review', () => { + expectStoryDiscoveryBeforeReview(); +}); + +// The get-stories-by-component fallback is required exactly when the diff +// alone is insufficient (spec §4 "when to switch"): the token file is not a +// component, so unless get-changed-stories already surfaced both consumers, +// the agent must resolve them via get-stories-by-component. +// Deliberately conditional, not unconditional: on the MCP path the module +// graph's related-stories detection can legitimately surface both consumers +// from the diff alone (observed in the 2026-07-02 cc-mcp QA run — one +// get-changed-stories call covering badge + statuspill, zero fallback calls), +// and punishing that correct behavior would fight the spec. +test('falls back to get-stories-by-component when the diff does not cover the consumers', () => { + const changedStoriesResults = getWorkflowToolResults('get-changed-stories'); + const lastChangedStories = changedStoriesResults.at(-1); + const diffCoversConsumers = + lastChangedStories !== undefined && + !lastChangedStories.isError && + /badge/i.test(lastChangedStories.output) && + /statuspill/i.test(lastChangedStories.output); + + if (diffCoversConsumers) { + return; + } + + expect( + getWorkflowCalls('get-stories-by-component').length, + 'get-changed-stories did not surface the consumer stories, so get-stories-by-component must be used', + ).toBeGreaterThan(0); +}); + +// Required workflow step (test-instructions.md Validation Workflow): run +// run-story-tests after the change and do not report completion while story +// tests are failing. +// Accepted known failure — MCP-path agents skip validation for shared-token +// edits: the Validation Workflow section is lost to the 2,048-char MCP +// server-instruction truncation that PR #320 addresses (0 run-story-tests +// calls in the 2026-07-02 cc-mcp QA run, while the same fixture passes on +// cc-plugin and codex-plugin). Gated to the plugin integration; re-enable on +// the MCP path once #320 lands. +test.skipIf(getEvalContext().integration === 'mcp')( + 'runs story tests after the change and finishes with them passing', + () => { + expectStoryTestsRanAndPassed({ covering: ['badge', 'statuspill'] }); + }, +); + +// The plugin path must engage the stories skill (Claude: via the Skill tool; +// Codex: by reading its SKILL.md). Skipped on the MCP integration, where no +// skills are installed. +test.skipIf(getEvalContext().integration === 'mcp')('invokes the stories skill', () => { + expectSkillInvoked('stories'); +}); + +test('keeps the pre-existing Storybook launch config valid', () => { + expectValidStorybookLaunchConfig(); +}); + +test('opens the preview browser when using the plugin', () => { + expectPreviewBrowserStarted(); +}); diff --git a/agent-eval/evals/808-shared-infra-fallback/PROMPT.md b/agent-eval/evals/808-shared-infra-fallback/PROMPT.md new file mode 100644 index 00000000..efea1f92 --- /dev/null +++ b/agent-eval/evals/808-shared-infra-fallback/PROMPT.md @@ -0,0 +1 @@ +Change the accent color token in `src/theme/colors.ts` from blue (`#2563eb`) to violet (`#7c3aed`). It is shared styling infrastructure used across our components. diff --git a/agent-eval/evals/808-shared-infra-fallback/package.json b/agent-eval/evals/808-shared-infra-fallback/package.json new file mode 100644 index 00000000..96376e11 --- /dev/null +++ b/agent-eval/evals/808-shared-infra-fallback/package.json @@ -0,0 +1,7 @@ +{ + "name": "808-shared-infra-fallback", + "type": "module", + "evals": { + "template": "reshaped-storybook" + } +} diff --git a/agent-eval/evals/808-shared-infra-fallback/src/components/Badge.tsx b/agent-eval/evals/808-shared-infra-fallback/src/components/Badge.tsx new file mode 100644 index 00000000..b476264b --- /dev/null +++ b/agent-eval/evals/808-shared-infra-fallback/src/components/Badge.tsx @@ -0,0 +1,28 @@ +import type { ReactNode } from 'react'; +import { accentColor, accentContrastColor, neutralColor } from '../theme/colors'; + +export type BadgeProps = { + children: ReactNode; + variant?: 'accent' | 'neutral'; +}; + +export default function Badge({ children, variant = 'accent' }: BadgeProps) { + const background = variant === 'accent' ? accentColor : neutralColor; + + return ( + + {children} + + ); +} diff --git a/agent-eval/evals/808-shared-infra-fallback/src/components/StatusPill.tsx b/agent-eval/evals/808-shared-infra-fallback/src/components/StatusPill.tsx new file mode 100644 index 00000000..4efbfc13 --- /dev/null +++ b/agent-eval/evals/808-shared-infra-fallback/src/components/StatusPill.tsx @@ -0,0 +1,26 @@ +import { accentColor, neutralColor } from '../theme/colors'; + +export type StatusPillProps = { + label: string; + active?: boolean; +}; + +export default function StatusPill({ label, active = false }: StatusPillProps) { + const border = active ? accentColor : neutralColor; + + return ( + + {label} + + ); +} diff --git a/agent-eval/evals/808-shared-infra-fallback/src/theme/colors.ts b/agent-eval/evals/808-shared-infra-fallback/src/theme/colors.ts new file mode 100644 index 00000000..97041846 --- /dev/null +++ b/agent-eval/evals/808-shared-infra-fallback/src/theme/colors.ts @@ -0,0 +1,5 @@ +// Shared design tokens. This file has no stories of its own; components +// consume these values. +export const accentColor = '#2563eb'; +export const accentContrastColor = '#ffffff'; +export const neutralColor = '#6b7280'; diff --git a/agent-eval/evals/808-shared-infra-fallback/stories/Badge.stories.tsx b/agent-eval/evals/808-shared-infra-fallback/stories/Badge.stories.tsx new file mode 100644 index 00000000..a61f5fd8 --- /dev/null +++ b/agent-eval/evals/808-shared-infra-fallback/stories/Badge.stories.tsx @@ -0,0 +1,22 @@ +import type { Meta, StoryObj } from '@storybook/react'; +import Badge from '../src/components/Badge'; + +const meta = { + title: 'Example/Badge', + component: Badge, + args: { + children: 'New', + }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const Accent: Story = {}; + +export const Neutral: Story = { + args: { + variant: 'neutral', + children: 'Archived', + }, +}; diff --git a/agent-eval/evals/808-shared-infra-fallback/stories/StatusPill.stories.tsx b/agent-eval/evals/808-shared-infra-fallback/stories/StatusPill.stories.tsx new file mode 100644 index 00000000..dabf7766 --- /dev/null +++ b/agent-eval/evals/808-shared-infra-fallback/stories/StatusPill.stories.tsx @@ -0,0 +1,22 @@ +import type { Meta, StoryObj } from '@storybook/react'; +import StatusPill from '../src/components/StatusPill'; + +const meta = { + title: 'Example/StatusPill', + component: StatusPill, + args: { + label: 'Draft', + }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const Inactive: Story = {}; + +export const Active: Story = { + args: { + label: 'Published', + active: true, + }, +}; diff --git a/agent-eval/evals/810-fix-failing-tests/EVAL.ts b/agent-eval/evals/810-fix-failing-tests/EVAL.ts new file mode 100644 index 00000000..8e20aa9f --- /dev/null +++ b/agent-eval/evals/810-fix-failing-tests/EVAL.ts @@ -0,0 +1,33 @@ +import { readFileSync } from 'node:fs'; +import { expect, test } from 'vitest'; +import { expectStoryTestsRanAndPassed, getWorkflowCalls } from '#test-utils'; + +// The fixture ships a Button that never wires the onClick prop to the DOM +// button, so the Default story's play function fails until the agent fixes +// the component. Port of the old 911 eval, hardened with the green-run floor. + +test('runs the story tests more than once while fixing the failure', () => { + expect( + getWorkflowCalls('run-story-tests').length, + 'Expected run-story-tests to be called at least twice: once to see the failure, once to verify the fix', + ).toBeGreaterThanOrEqual(2); +}); + +// Validation Workflow floor: the run must not end while story tests are +// failing. +test('finishes with the story tests passing', () => { + expectStoryTestsRanAndPassed({ covering: ['button'] }); +}); + +// Guard against a vacuous pass: the tests only turn green through the real +// fix — wiring onClick through to the button element (not by weakening the +// stories). +test('fixes the component instead of the stories', () => { + const button = readFileSync('src/components/Button.tsx', 'utf8'); + expect(button, 'Expected the Button to wire the onClick prop').toMatch(/onClick=\{/); + + const stories = readFileSync('stories/Button.stories.tsx', 'utf8'); + expect(stories, 'Expected the Default story to keep asserting the onClick behavior').toMatch( + /toHaveBeenCalled/, + ); +}); diff --git a/agent-eval/evals/810-fix-failing-tests/PROMPT.md b/agent-eval/evals/810-fix-failing-tests/PROMPT.md new file mode 100644 index 00000000..3c84a512 --- /dev/null +++ b/agent-eval/evals/810-fix-failing-tests/PROMPT.md @@ -0,0 +1 @@ +Run the story tests for the Button component and fix any issues you find. diff --git a/agent-eval/evals/810-fix-failing-tests/package.json b/agent-eval/evals/810-fix-failing-tests/package.json new file mode 100644 index 00000000..5785faf6 --- /dev/null +++ b/agent-eval/evals/810-fix-failing-tests/package.json @@ -0,0 +1,7 @@ +{ + "name": "810-fix-failing-tests", + "type": "module", + "evals": { + "template": "reshaped-storybook" + } +} diff --git a/agent-eval/evals/810-fix-failing-tests/src/components/Button.tsx b/agent-eval/evals/810-fix-failing-tests/src/components/Button.tsx new file mode 100644 index 00000000..0682633d --- /dev/null +++ b/agent-eval/evals/810-fix-failing-tests/src/components/Button.tsx @@ -0,0 +1,13 @@ +type ButtonProps = { + label: string; + onClick?: () => void; + disabled?: boolean; +}; + +export default function Button({ label, disabled = false }: ButtonProps) { + return ( + + ); +} diff --git a/agent-eval/evals/810-fix-failing-tests/stories/Button.stories.tsx b/agent-eval/evals/810-fix-failing-tests/stories/Button.stories.tsx new file mode 100644 index 00000000..41e8a096 --- /dev/null +++ b/agent-eval/evals/810-fix-failing-tests/stories/Button.stories.tsx @@ -0,0 +1,41 @@ +import type { Meta, StoryObj } from '@storybook/react'; +import { expect, fn, userEvent, within } from 'storybook/test'; +import Button from '../src/components/Button'; + +const meta = { + title: 'Example/Button', + component: Button, + tags: ['test'], + args: { + label: 'Click me', + onClick: fn(), + disabled: false, + }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const Default: Story = { + play: async ({ canvasElement, args }) => { + const canvas = within(canvasElement); + const button = canvas.getByRole('button', { name: 'Click me' }); + + await userEvent.click(button); + await expect(args.onClick).toHaveBeenCalledTimes(1); + }, +}; + +export const Disabled: Story = { + args: { + label: 'Disabled', + disabled: true, + }, + play: async ({ canvasElement, args }) => { + const canvas = within(canvasElement); + const button = canvas.getByRole('button', { name: 'Disabled' }); + + await userEvent.click(button); + await expect(args.onClick).not.toHaveBeenCalled(); + }, +}; diff --git a/agent-eval/evals/811-fix-a11y-violations/EVAL.ts b/agent-eval/evals/811-fix-a11y-violations/EVAL.ts new file mode 100644 index 00000000..148f8b81 --- /dev/null +++ b/agent-eval/evals/811-fix-a11y-violations/EVAL.ts @@ -0,0 +1,73 @@ +import { readFileSync } from 'node:fs'; +import { expect, test } from 'vitest'; +import { + expectFinalResponseMatches, + expectStoryTestsRanAndPassed, + getWorkflowCalls, + getWorkflowToolResults, +} from '#test-utils'; + +// The fixture ships a Button with two seeded a11y violations: the icon-only +// story renders a button without an accessible name (button-name, fixable +// directly), and the color scheme fails contrast (color-contrast, a visual +// design change the agent must surface to the user instead of changing colors +// on its own — per the a11y guidance the old 912 judge criterion encoded). +// Port of the old 912 eval with deterministic assertions. + +test('runs the story tests more than once while fixing the violations', () => { + expect( + getWorkflowCalls('run-story-tests').length, + 'Expected run-story-tests to be called at least twice: once to see the violations, once to verify the fix', + ).toBeGreaterThanOrEqual(2); +}); + +test('fixes the semantic button-name violation', () => { + // The full Validation Workflow floor: run-story-tests called, final run + // succeeded (not errored), reports passing stories, no failing/unhandled + // sections, and covers the Button stories. + expectStoryTestsRanAndPassed({ covering: ['button'] }); + + // The violation must have been observed before it can count as fixed — a + // run that never evaluates accessibility cannot claim the fix. + const results = getWorkflowToolResults('run-story-tests'); + expect( + results.some((result) => /button-name/.test(result.output)), + 'Expected some run-story-tests result to surface the seeded button-name violation', + ).toBe(true); + expect( + results.at(-1)?.output, + 'Final run-story-tests result must no longer report the button-name violation', + ).not.toMatch(/button-name/); + + // Guard against a vacuous pass: the violation must be gone because the + // icon-only rendering gained an accessible name, not because the agent + // deleted the story that surfaced it. + const stories = readFileSync('stories/Button.stories.tsx', 'utf8'); + expect( + stories, + 'Expected the icon-only story to still exist (fix the component, do not delete coverage)', + ).toMatch(/iconOnly:\s*true/); +}); + +// Closing the loophole where the button-name absence would be vacuous: a run +// that turns accessibility checks off cannot claim the violations were +// addressed. No passing sample has ever disabled a11y. +test('never disables accessibility checks while fixing a11y issues', () => { + const disabledCall = getWorkflowCalls('run-story-tests').find( + (call) => call.input.a11y === false, + ); + expect( + disabledCall, + 'Expected no run-story-tests call to pass a11y: false in an a11y-fixing task', + ).toBeUndefined(); +}); + +// The contrast violation is a visual design decision: the agent must not +// silently repaint the button, it must keep the seeded colors and surface the +// concern to the user. +test('surfaces the contrast violation instead of changing design colors', () => { + const button = readFileSync('src/components/Button.tsx', 'utf8'); + expect(button, 'Expected the seeded text color to stay untouched').toMatch(/#b0b0b0/); + + expectFinalResponseMatches([/contrast/i]); +}); diff --git a/agent-eval/evals/811-fix-a11y-violations/PROMPT.md b/agent-eval/evals/811-fix-a11y-violations/PROMPT.md new file mode 100644 index 00000000..b3edd2f5 --- /dev/null +++ b/agent-eval/evals/811-fix-a11y-violations/PROMPT.md @@ -0,0 +1 @@ +Run the Storybook story tests for the Button component and fix any accessibility issues you find. diff --git a/agent-eval/evals/811-fix-a11y-violations/package.json b/agent-eval/evals/811-fix-a11y-violations/package.json new file mode 100644 index 00000000..a8878a11 --- /dev/null +++ b/agent-eval/evals/811-fix-a11y-violations/package.json @@ -0,0 +1,7 @@ +{ + "name": "811-fix-a11y-violations", + "type": "module", + "evals": { + "template": "reshaped-storybook" + } +} diff --git a/agent-eval/evals/811-fix-a11y-violations/src/components/Button.tsx b/agent-eval/evals/811-fix-a11y-violations/src/components/Button.tsx new file mode 100644 index 00000000..bd69bc0a --- /dev/null +++ b/agent-eval/evals/811-fix-a11y-violations/src/components/Button.tsx @@ -0,0 +1,38 @@ +type ButtonProps = { + label?: string; + onClick?: () => void; + disabled?: boolean; + iconOnly?: boolean; +}; + +export default function Button({ + label, + onClick, + disabled = false, + iconOnly = false, +}: ButtonProps) { + return ( + + ); +} diff --git a/agent-eval/evals/811-fix-a11y-violations/stories/Button.stories.tsx b/agent-eval/evals/811-fix-a11y-violations/stories/Button.stories.tsx new file mode 100644 index 00000000..161695fb --- /dev/null +++ b/agent-eval/evals/811-fix-a11y-violations/stories/Button.stories.tsx @@ -0,0 +1,25 @@ +import type { Meta, StoryObj } from '@storybook/react'; +import Button from '../src/components/Button'; + +const meta = { + title: 'Example/Button', + component: Button, + tags: ['test'], + args: { + label: 'Click me', + disabled: false, + }, +} satisfies Meta; + +export default meta; + +type Story = StoryObj; + +export const Default: Story = {}; + +export const IconOnly: Story = { + args: { + label: undefined, + iconOnly: true, + }, +}; diff --git a/agent-eval/evals/812-first-story-empty-project/.claude/launch.json b/agent-eval/evals/812-first-story-empty-project/.claude/launch.json new file mode 100644 index 00000000..fa0fadca --- /dev/null +++ b/agent-eval/evals/812-first-story-empty-project/.claude/launch.json @@ -0,0 +1,12 @@ +{ + "version": "0.0.1", + "configurations": [ + { + "name": "storybook", + "runtimeExecutable": "npm", + "runtimeArgs": ["run", "storybook"], + "port": 6006, + "autoPort": true + } + ] +} diff --git a/agent-eval/evals/812-first-story-empty-project/.storybook/main.ts b/agent-eval/evals/812-first-story-empty-project/.storybook/main.ts new file mode 100644 index 00000000..71c42a16 --- /dev/null +++ b/agent-eval/evals/812-first-story-empty-project/.storybook/main.ts @@ -0,0 +1,13 @@ +import type { StorybookConfig } from '@storybook/react-vite'; + +const config: StorybookConfig = { + stories: ['../@(stories|src)/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + addons: [ + '@storybook/addon-a11y', + '@storybook/addon-vitest', + '@storybook/addon-docs', + '@storybook/addon-mcp', + ], + framework: '@storybook/react-vite', +}; +export default config; diff --git a/agent-eval/evals/812-first-story-empty-project/.storybook/preview.tsx b/agent-eval/evals/812-first-story-empty-project/.storybook/preview.tsx new file mode 100644 index 00000000..8c649b95 --- /dev/null +++ b/agent-eval/evals/812-first-story-empty-project/.storybook/preview.tsx @@ -0,0 +1,7 @@ +import type { Preview } from '@storybook/react-vite'; + +const preview: Preview = { + parameters: {}, +}; + +export default preview; diff --git a/agent-eval/evals/812-first-story-empty-project/.storybook/vitest.setup.ts b/agent-eval/evals/812-first-story-empty-project/.storybook/vitest.setup.ts new file mode 100644 index 00000000..135e9064 --- /dev/null +++ b/agent-eval/evals/812-first-story-empty-project/.storybook/vitest.setup.ts @@ -0,0 +1,6 @@ +import * as a11yAddonAnnotations from '@storybook/addon-a11y/preview'; +import { setProjectAnnotations } from '@storybook/react-vite'; + +import * as projectAnnotations from './preview.tsx'; + +setProjectAnnotations([a11yAddonAnnotations, projectAnnotations]); diff --git a/agent-eval/evals/812-first-story-empty-project/EVAL.ts b/agent-eval/evals/812-first-story-empty-project/EVAL.ts new file mode 100644 index 00000000..8da80f84 --- /dev/null +++ b/agent-eval/evals/812-first-story-empty-project/EVAL.ts @@ -0,0 +1,60 @@ +import { test } from 'vitest'; +import { + expectAllStoryExportsInDisplayReview, + expectDisplayReviewForVisualChange, + expectPreviewBrowserStarted, + expectSkillInvoked, + getEvalContext, + expectStoryDiscoveryBeforeReview, + expectStoryIdsInDisplayReview, + expectStoryTestsRanAndPassed, + expectValidStorybookLaunchConfig, + expectWorkflowCalls, +} from '#test-utils'; + +// First-story scenario on the minimal vite-app template: Storybook (next) is +// installed and running, but the project has zero stories, so nothing about +// existing story conventions can be inferred from neighbors. + +test('uses Storybook story instructions and publishes a display review', () => { + expectWorkflowCalls(['get-storybook-story-instructions', 'display-review']); + expectDisplayReviewForVisualChange(); +}); + +test('the review covers the new Button stories', () => { + expectStoryIdsInDisplayReview(['button']); +}); + +// The project starts without story files, so the §6a.2 completeness rule +// applies: every story the agent created must appear in the review. +test('every new story appears in the display review', () => { + expectAllStoryExportsInDisplayReview(); +}); + +// Required workflow step (dev instructions "Mapping any input to story IDs"): +// story IDs in the review must come from a discovery tool, not from guessing. +test('discovers stories through the workflow tools before publishing the review', () => { + expectStoryDiscoveryBeforeReview(); +}); + +// Required workflow step (test-instructions.md Validation Workflow): run +// run-story-tests after the change and do not report completion while story +// tests are failing. +test('runs story tests after the change and finishes with them passing', () => { + expectStoryTestsRanAndPassed({ covering: ['button'] }); +}); + +// The plugin path must engage the stories skill (Claude: via the Skill tool; +// Codex: by reading its SKILL.md). Skipped on the MCP integration, where no +// skills are installed. +test.skipIf(getEvalContext().integration === 'mcp')('invokes the stories skill', () => { + expectSkillInvoked('stories'); +}); + +test('keeps the pre-existing Storybook launch config valid', () => { + expectValidStorybookLaunchConfig(); +}); + +test('opens the preview browser when using the plugin', () => { + expectPreviewBrowserStarted(); +}); diff --git a/agent-eval/evals/812-first-story-empty-project/PROMPT.md b/agent-eval/evals/812-first-story-empty-project/PROMPT.md new file mode 100644 index 00000000..92248ac8 --- /dev/null +++ b/agent-eval/evals/812-first-story-empty-project/PROMPT.md @@ -0,0 +1 @@ +We just added Storybook to this project, but there are no stories yet. Write stories for the existing `Button` component (`src/components/Button.tsx`). diff --git a/agent-eval/evals/812-first-story-empty-project/package.json b/agent-eval/evals/812-first-story-empty-project/package.json new file mode 100644 index 00000000..f8a3e9e3 --- /dev/null +++ b/agent-eval/evals/812-first-story-empty-project/package.json @@ -0,0 +1,25 @@ +{ + "name": "812-first-story-empty-project", + "type": "module", + "scripts": { + "test:stories": "vitest run --config ./vitest.storybook.config.ts --project storybook", + "postinstall": "playwright install chromium && node ./scripts/start-storybook-mcp.mjs", + "storybook": "storybook dev", + "build-storybook": "storybook build" + }, + "devDependencies": { + "@storybook/addon-a11y": "next", + "@storybook/addon-docs": "next", + "@storybook/addon-mcp": "file:./local-packages/addon-mcp", + "@storybook/addon-vitest": "next", + "@storybook/mcp": "file:./local-packages/mcp", + "@storybook/react": "next", + "@storybook/react-vite": "next", + "@vitest/browser-playwright": "4.0.6", + "playwright": "1.56.1", + "storybook": "next" + }, + "evals": { + "template": "vite-app" + } +} diff --git a/agent-eval/evals/812-first-story-empty-project/vitest.config.ts b/agent-eval/evals/812-first-story-empty-project/vitest.config.ts new file mode 100644 index 00000000..cc69489d --- /dev/null +++ b/agent-eval/evals/812-first-story-empty-project/vitest.config.ts @@ -0,0 +1,5 @@ +// addon-vitest's run-story-tests starts Vitest from the project root, so the +// storybook test project must be reachable from the default config. The eval +// runner overwrites this file before executing EVAL.ts; it only matters while +// the agent runs. +export { default } from './vitest.storybook.config.ts'; diff --git a/agent-eval/evals/812-first-story-empty-project/vitest.storybook.config.ts b/agent-eval/evals/812-first-story-empty-project/vitest.storybook.config.ts new file mode 100644 index 00000000..e0935a93 --- /dev/null +++ b/agent-eval/evals/812-first-story-empty-project/vitest.storybook.config.ts @@ -0,0 +1,36 @@ +import * as path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { defineConfig } from 'vitest/config'; + +import { storybookTest } from '@storybook/addon-vitest/vitest-plugin'; + +import { playwright } from '@vitest/browser-playwright'; + +const dirname = + typeof __dirname !== 'undefined' ? __dirname : path.dirname(fileURLToPath(import.meta.url)); + +// More info at: https://storybook.js.org/docs/next/writing-tests/integrations/vitest-addon +export default defineConfig({ + optimizeDeps: { + include: ['react/jsx-dev-runtime'], + }, + test: { + projects: [ + { + extends: true, + plugins: [storybookTest({ configDir: path.join(dirname, '.storybook') })], + test: { + name: 'storybook', + browser: { + enabled: true, + headless: true, + provider: playwright({}), + instances: [{ browser: 'chromium' }], + }, + setupFiles: ['.storybook/vitest.setup.ts'], + }, + }, + ], + }, +}); diff --git a/agent-eval/evals/813-monorepo-leaf-create-component/EVAL.ts b/agent-eval/evals/813-monorepo-leaf-create-component/EVAL.ts new file mode 100644 index 00000000..0a8757ca --- /dev/null +++ b/agent-eval/evals/813-monorepo-leaf-create-component/EVAL.ts @@ -0,0 +1,71 @@ +import { existsSync } from 'node:fs'; +import { expect, test } from 'vitest'; +import { + expectDisplayReviewForVisualChange, + expectPreviewBrowserStarted, + expectSkillInvoked, + getEvalContext, + expectStoryDiscoveryBeforeReview, + expectStoryIdsInDisplayReview, + expectStoryTestsRanAndPassed, + expectValidStorybookLaunchConfig, + expectWorkflowCalls, +} from '#test-utils'; + +// Monorepo-leaf project shape (Agentic Review Eval instructions §7, secondary +// axis): the runnable Storybook lives in the @acme/ui workspace package, not +// at the repo root, so the agent must work inside the leaf. +// Note: expectAllStoryExportsInDisplayReview assumes the project starts +// without story files, so it cannot be used here (Card ships with stories). + +// TODO(storybookjs/storybook#35359): the workflow assertions below are +// test.todo until the CLI help bug is fixed. `storybook ai --help` run from +// the monorepo root cannot load the leaf's Storybook config and then hides +// every runtime workflow command — the only command it lists is `setup`, so +// agents derail into `setup` + raw vitest and never discover display-review +// (observed on both the Claude and Codex plugin paths in the 2026-07-02 runs; +// recovery via `--help --config-dir packages/ui/.storybook` is a coin flip). +// Re-enable by swapping test.todo back to test once #35359 lands. + +test('creates the component inside the leaf package', () => { + expect( + existsSync('packages/ui/src/components/Callout.tsx'), + 'Expected packages/ui/src/components/Callout.tsx to be created', + ).toBe(true); +}); + +test.todo('publishes a display review for the new component', () => { + expectWorkflowCalls(['display-review']); + expectDisplayReviewForVisualChange(); +}); + +test.todo('uses the Storybook story instructions', () => { + expectWorkflowCalls(['get-storybook-story-instructions']); +}); + +test.todo('the review covers the new Callout stories', () => { + expectStoryIdsInDisplayReview(['callout']); +}); + +test.todo('discovers stories through the workflow tools before publishing the review', () => { + expectStoryDiscoveryBeforeReview(); +}); + +test.todo('runs story tests after the change and finishes with them passing', () => { + expectStoryTestsRanAndPassed({ covering: ['callout'] }); +}); + +// The plugin path must engage the stories skill (Claude: via the Skill tool; +// Codex: by reading its SKILL.md). Skipped on the MCP integration, where no +// skills are installed. +test.skipIf(getEvalContext().integration === 'mcp')('invokes the stories skill', () => { + expectSkillInvoked('stories'); +}); + +test('keeps the pre-existing Storybook launch config valid', () => { + expectValidStorybookLaunchConfig(); +}); + +test('opens the preview browser when using the plugin', () => { + expectPreviewBrowserStarted(); +}); diff --git a/agent-eval/evals/813-monorepo-leaf-create-component/PROMPT.md b/agent-eval/evals/813-monorepo-leaf-create-component/PROMPT.md new file mode 100644 index 00000000..78fe7e21 --- /dev/null +++ b/agent-eval/evals/813-monorepo-leaf-create-component/PROMPT.md @@ -0,0 +1 @@ +Create a `Callout` component in the `@acme/ui` package (`packages/ui/src/components/Callout.tsx`) with `info`, `warning`, and `error` variants and a `children` prop, following the package's existing conventions. diff --git a/agent-eval/evals/813-monorepo-leaf-create-component/package.json b/agent-eval/evals/813-monorepo-leaf-create-component/package.json new file mode 100644 index 00000000..cdc0b8f5 --- /dev/null +++ b/agent-eval/evals/813-monorepo-leaf-create-component/package.json @@ -0,0 +1,7 @@ +{ + "name": "813-monorepo-leaf-create-component", + "type": "module", + "evals": { + "template": "monorepo" + } +} diff --git a/agent-eval/evals/820-init-no-storybook/EVAL.ts b/agent-eval/evals/820-init-no-storybook/EVAL.ts new file mode 100644 index 00000000..ec3422be --- /dev/null +++ b/agent-eval/evals/820-init-no-storybook/EVAL.ts @@ -0,0 +1,61 @@ +import { readFileSync, readdirSync } from 'node:fs'; +import { expect, test } from 'vitest'; +import { + expectShellCommandMatching, + expectSkillInvoked, + expectStorybookBoots, + isRecord, + parseJson, +} from '#test-utils'; + +// Lifecycle eval (storybookjs/mcp#324): the project has no Storybook at all, +// so the storybook-init skill must drive setup. Pass criteria are the +// lifecycle outcome only — the story/review workflow is owned by the 80x +// evals on a next-stack project, because the skill installs the published +// stable release (no `storybook ai` CLI / review tools there yet). + +test('invokes the storybook-init skill', () => { + expectSkillInvoked('storybook-init'); +}); + +// The skill's documented step 1: `npm create storybook@latest` (or the +// package-manager equivalent / the `storybook init` alias it delegates to). +test('runs the Storybook initializer', () => { + expectShellCommandMatching(/create(-|\s+)storybook|storybook(@\S+)?\s+init/); +}); + +test('installs Storybook and the MCP addon', () => { + const packageJson = parseJson(readFileSync('package.json', 'utf8')); + if (!isRecord(packageJson)) { + expect.fail('Expected package.json to contain a JSON object'); + } + + const dependencies = { + ...(isRecord(packageJson.dependencies) ? packageJson.dependencies : {}), + ...(isRecord(packageJson.devDependencies) ? packageJson.devDependencies : {}), + }; + expect(dependencies.storybook, 'Expected a storybook dependency').toBeTypeOf('string'); + expect( + dependencies['@storybook/addon-mcp'], + 'Expected the @storybook/addon-mcp dependency (skill step 2: npx storybook add @storybook/addon-mcp)', + ).toBeTypeOf('string'); + + const scripts = isRecord(packageJson.scripts) ? packageJson.scripts : {}; + expect(scripts.storybook, 'Expected a storybook script').toBeTypeOf('string'); +}); + +test('registers the MCP addon in the Storybook config', () => { + const mainFile = readdirSync('.storybook').find((entry) => /^main\.[cm]?[jt]sx?$/.test(entry)); + if (mainFile === undefined) { + expect.fail('Expected a .storybook/main config file to exist'); + } + + expect( + readFileSync(`.storybook/${mainFile}`, 'utf8'), + 'Expected @storybook/addon-mcp to be registered in the Storybook config', + ).toContain('@storybook/addon-mcp'); +}); + +test('the initialized Storybook boots', async () => { + await expectStorybookBoots(); +}); diff --git a/agent-eval/evals/820-init-no-storybook/PROMPT.md b/agent-eval/evals/820-init-no-storybook/PROMPT.md new file mode 100644 index 00000000..6ede840e --- /dev/null +++ b/agent-eval/evals/820-init-no-storybook/PROMPT.md @@ -0,0 +1 @@ +Set up Storybook for this project so I can develop and preview the components in `src/components` in isolation. diff --git a/agent-eval/evals/820-init-no-storybook/package.json b/agent-eval/evals/820-init-no-storybook/package.json new file mode 100644 index 00000000..1bd3b1d6 --- /dev/null +++ b/agent-eval/evals/820-init-no-storybook/package.json @@ -0,0 +1,7 @@ +{ + "name": "820-init-no-storybook", + "type": "module", + "evals": { + "template": "vite-app" + } +} diff --git a/agent-eval/evals/821-upgrade-from-sb9/.storybook/main.ts b/agent-eval/evals/821-upgrade-from-sb9/.storybook/main.ts new file mode 100644 index 00000000..1c34cde8 --- /dev/null +++ b/agent-eval/evals/821-upgrade-from-sb9/.storybook/main.ts @@ -0,0 +1,8 @@ +import type { StorybookConfig } from '@storybook/react-vite'; + +const config: StorybookConfig = { + stories: ['../@(stories|src)/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + addons: [], + framework: '@storybook/react-vite', +}; +export default config; diff --git a/agent-eval/evals/821-upgrade-from-sb9/.storybook/preview.ts b/agent-eval/evals/821-upgrade-from-sb9/.storybook/preview.ts new file mode 100644 index 00000000..8c649b95 --- /dev/null +++ b/agent-eval/evals/821-upgrade-from-sb9/.storybook/preview.ts @@ -0,0 +1,7 @@ +import type { Preview } from '@storybook/react-vite'; + +const preview: Preview = { + parameters: {}, +}; + +export default preview; diff --git a/agent-eval/evals/821-upgrade-from-sb9/EVAL.ts b/agent-eval/evals/821-upgrade-from-sb9/EVAL.ts new file mode 100644 index 00000000..41b9bad7 --- /dev/null +++ b/agent-eval/evals/821-upgrade-from-sb9/EVAL.ts @@ -0,0 +1,36 @@ +import { test } from 'vitest'; +import { + expectShellCommandMatching, + expectSkillInvoked, + expectStorybookBoots, + expectStorybookDependenciesAtLeast, +} from '#test-utils'; + +// Lifecycle eval (storybookjs/mcp#324): Storybook 9.x is preinstalled (the +// qa/sb9-no-mcp scenario), so the storybook-upgrade skill must drive the major +// upgrade. Pass criteria are the lifecycle outcome only — the story/review +// workflow is owned by the 80x evals. The fixture opts out of the harness +// version pinning (evals.pinStorybook: false) to keep the seeded 9.1.20. + +test('invokes the storybook-upgrade skill', () => { + expectSkillInvoked('storybook-upgrade'); +}); + +// The documented upgrade path runs the storybook upgrade CLI. +test('runs the Storybook upgrade command', () => { + expectShellCommandMatching(/storybook(@\S+)?\s+upgrade/); +}); + +// 10.4.6 is the stable release at fixture-authoring time; an under-upgrade +// (e.g. landing on 10.0.0) must not count. Bump alongside future stables. +test('upgrades the Storybook packages to the current release', () => { + expectStorybookDependenciesAtLeast('10.4.6', ['storybook', '@storybook/react-vite'], { + // Storybook 10 absorbs @storybook/react — a correct upgrade removes it, + // but a stale seeded copy left behind must fail the floor. + ifPresent: ['@storybook/react'], + }); +}); + +test('the upgraded Storybook boots', async () => { + await expectStorybookBoots(); +}); diff --git a/agent-eval/evals/821-upgrade-from-sb9/PROMPT.md b/agent-eval/evals/821-upgrade-from-sb9/PROMPT.md new file mode 100644 index 00000000..1d893e6e --- /dev/null +++ b/agent-eval/evals/821-upgrade-from-sb9/PROMPT.md @@ -0,0 +1 @@ +Upgrade Storybook in this project to the latest version. diff --git a/agent-eval/evals/821-upgrade-from-sb9/package.json b/agent-eval/evals/821-upgrade-from-sb9/package.json new file mode 100644 index 00000000..e2787d41 --- /dev/null +++ b/agent-eval/evals/821-upgrade-from-sb9/package.json @@ -0,0 +1,17 @@ +{ + "name": "821-upgrade-from-sb9", + "type": "module", + "scripts": { + "storybook": "storybook dev", + "build-storybook": "storybook build" + }, + "devDependencies": { + "@storybook/react": "9.1.20", + "@storybook/react-vite": "9.1.20", + "storybook": "9.1.20" + }, + "evals": { + "template": "vite-app", + "pinStorybook": false + } +} diff --git a/agent-eval/evals/821-upgrade-from-sb9/stories/Button.stories.tsx b/agent-eval/evals/821-upgrade-from-sb9/stories/Button.stories.tsx new file mode 100644 index 00000000..7b6219b2 --- /dev/null +++ b/agent-eval/evals/821-upgrade-from-sb9/stories/Button.stories.tsx @@ -0,0 +1,27 @@ +import type { Meta, StoryObj } from '@storybook/react'; +import Button from '../src/components/Button'; + +const meta = { + title: 'Example/Button', + component: Button, + args: { + label: 'Click me', + }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const Primary: Story = {}; + +export const Secondary: Story = { + args: { + variant: 'secondary', + }, +}; + +export const Disabled: Story = { + args: { + disabled: true, + }, +}; diff --git a/agent-eval/evals/822-upgrade-from-stable/.storybook/main.ts b/agent-eval/evals/822-upgrade-from-stable/.storybook/main.ts new file mode 100644 index 00000000..1c34cde8 --- /dev/null +++ b/agent-eval/evals/822-upgrade-from-stable/.storybook/main.ts @@ -0,0 +1,8 @@ +import type { StorybookConfig } from '@storybook/react-vite'; + +const config: StorybookConfig = { + stories: ['../@(stories|src)/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + addons: [], + framework: '@storybook/react-vite', +}; +export default config; diff --git a/agent-eval/evals/822-upgrade-from-stable/.storybook/preview.ts b/agent-eval/evals/822-upgrade-from-stable/.storybook/preview.ts new file mode 100644 index 00000000..8c649b95 --- /dev/null +++ b/agent-eval/evals/822-upgrade-from-stable/.storybook/preview.ts @@ -0,0 +1,7 @@ +import type { Preview } from '@storybook/react-vite'; + +const preview: Preview = { + parameters: {}, +}; + +export default preview; diff --git a/agent-eval/evals/822-upgrade-from-stable/EVAL.ts b/agent-eval/evals/822-upgrade-from-stable/EVAL.ts new file mode 100644 index 00000000..22c165ee --- /dev/null +++ b/agent-eval/evals/822-upgrade-from-stable/EVAL.ts @@ -0,0 +1,38 @@ +import { test } from 'vitest'; +import { + expectShellCommandMatching, + expectSkillInvoked, + expectStorybookBoots, + expectStorybookDependenciesAtLeast, +} from '#test-utils'; + +// Lifecycle eval (storybookjs/mcp#324): an older stable Storybook (10.4.0) is +// preinstalled, so the storybook-upgrade skill drives the minor/patch upgrade +// path — the "user is on stable, needs the current release" scenario. Pass +// criteria are the lifecycle outcome only — the story/review workflow is +// owned by the 80x evals. The fixture opts out of the harness version pinning +// (evals.pinStorybook: false) to keep the seeded 10.4.0. + +test('invokes the storybook-upgrade skill', () => { + expectSkillInvoked('storybook-upgrade'); +}); + +// The documented upgrade path runs the storybook upgrade CLI. +test('runs the Storybook upgrade command', () => { + expectShellCommandMatching(/storybook(@\S+)?\s+upgrade/); +}); + +// 10.4.6 is the stable release at fixture-authoring time; the seeded 10.4.0 +// must move all the way to the current release, not just past 10.4.0. Bump +// alongside future stables. +test('upgrades the Storybook packages to the current release', () => { + expectStorybookDependenciesAtLeast('10.4.6', ['storybook', '@storybook/react-vite'], { + // Storybook 10 absorbs @storybook/react — a correct upgrade removes it, + // but a stale seeded copy left behind must fail the floor. + ifPresent: ['@storybook/react'], + }); +}); + +test('the upgraded Storybook boots', async () => { + await expectStorybookBoots(); +}); diff --git a/agent-eval/evals/822-upgrade-from-stable/PROMPT.md b/agent-eval/evals/822-upgrade-from-stable/PROMPT.md new file mode 100644 index 00000000..1d893e6e --- /dev/null +++ b/agent-eval/evals/822-upgrade-from-stable/PROMPT.md @@ -0,0 +1 @@ +Upgrade Storybook in this project to the latest version. diff --git a/agent-eval/evals/822-upgrade-from-stable/package.json b/agent-eval/evals/822-upgrade-from-stable/package.json new file mode 100644 index 00000000..585acb11 --- /dev/null +++ b/agent-eval/evals/822-upgrade-from-stable/package.json @@ -0,0 +1,17 @@ +{ + "name": "822-upgrade-from-stable", + "type": "module", + "scripts": { + "storybook": "storybook dev", + "build-storybook": "storybook build" + }, + "devDependencies": { + "@storybook/react": "10.4.0", + "@storybook/react-vite": "10.4.0", + "storybook": "10.4.0" + }, + "evals": { + "template": "vite-app", + "pinStorybook": false + } +} diff --git a/agent-eval/evals/822-upgrade-from-stable/stories/Button.stories.tsx b/agent-eval/evals/822-upgrade-from-stable/stories/Button.stories.tsx new file mode 100644 index 00000000..7b6219b2 --- /dev/null +++ b/agent-eval/evals/822-upgrade-from-stable/stories/Button.stories.tsx @@ -0,0 +1,27 @@ +import type { Meta, StoryObj } from '@storybook/react'; +import Button from '../src/components/Button'; + +const meta = { + title: 'Example/Button', + component: Button, + args: { + label: 'Click me', + }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const Primary: Story = {}; + +export const Secondary: Story = { + args: { + variant: 'secondary', + }, +}; + +export const Disabled: Story = { + args: { + disabled: true, + }, +}; diff --git a/agent-eval/experiments/cc-mcp-opus-high.ts b/agent-eval/experiments/cc-mcp-opus-high.ts index 6d9eef06..c3b693de 100644 --- a/agent-eval/experiments/cc-mcp-opus-high.ts +++ b/agent-eval/experiments/cc-mcp-opus-high.ts @@ -1,5 +1,5 @@ import type { ExperimentConfig } from '@vercel/agent-eval'; -import { DEFAULT_EXPERIMENT_CONFIG, RESHAPED_STORYBOOK_EVALS } from '../lib/experiment.ts'; +import { DEFAULT_EXPERIMENT_CONFIG, WORKFLOW_STORYBOOK_EVALS } from '../lib/experiment.ts'; import { setupSandbox, writeClaudeMcpConfig } from '../lib/templates.ts'; export default { @@ -9,7 +9,7 @@ export default { // experiment name stays accurate when the CLI defaults change. model: 'opus', agentOptions: { effort: 'high' }, - evals: RESHAPED_STORYBOOK_EVALS, + evals: WORKFLOW_STORYBOOK_EVALS, setup: async (sandbox) => { await setupSandbox(sandbox, { agent: 'claude-code', integration: 'mcp' }); await writeClaudeMcpConfig(sandbox); diff --git a/agent-eval/experiments/codex-mcp-gpt-5.5-medium.ts b/agent-eval/experiments/codex-mcp-gpt-5.5-medium.ts index 5c179aa8..22fc1b59 100644 --- a/agent-eval/experiments/codex-mcp-gpt-5.5-medium.ts +++ b/agent-eval/experiments/codex-mcp-gpt-5.5-medium.ts @@ -1,5 +1,5 @@ import type { ExperimentConfig } from '@vercel/agent-eval'; -import { DEFAULT_EXPERIMENT_CONFIG, RESHAPED_STORYBOOK_EVALS } from '../lib/experiment.ts'; +import { DEFAULT_EXPERIMENT_CONFIG, WORKFLOW_STORYBOOK_EVALS } from '../lib/experiment.ts'; import { setupSandbox, writeCodexMcpConfig } from '../lib/templates.ts'; export default { @@ -12,7 +12,7 @@ export default { // gpt-5.2-codex, which is deprecated (retiring July 2026). Medium is the // reasoning effort the adapter already defaults to when a model is pinned. model: 'gpt-5.5?reasoningEffort=medium', - evals: RESHAPED_STORYBOOK_EVALS, + evals: WORKFLOW_STORYBOOK_EVALS, setup: async (sandbox) => { await setupSandbox(sandbox, { agent: 'codex', integration: 'mcp' }); await writeCodexMcpConfig(sandbox); diff --git a/agent-eval/lib/experiment.ts b/agent-eval/lib/experiment.ts index cc2049c4..5919f8e5 100644 --- a/agent-eval/lib/experiment.ts +++ b/agent-eval/lib/experiment.ts @@ -21,13 +21,39 @@ const CORE_STORYBOOK_EVALS = [ '806-browse-request', // "What props does X accept": answered via the documentation tools '807-docs-request', + // Shared token change: review via the get-stories-by-component fallback, + // surfacing the consumer stories (spec §7 archetype 2) + '808-shared-infra-fallback', + // Seeded failing story test: fix it and finish with tests green (old 911) + '810-fix-failing-tests', + // Seeded a11y violations: fix the semantic one, surface the visual one (old 912) + '811-fix-a11y-violations', + // Storybook@next installed but zero stories: first story + review on the + // minimal vite-app template + '812-first-story-empty-project', + // The runnable Storybook lives in a workspace leaf package (spec secondary axis) + '813-monorepo-leaf-create-component', +] as const; + +// The 82x block: lifecycle-skill evals (storybook-init / storybook-upgrade). +// They only run on the plugin experiments — the MCP experiments require a +// Storybook already running at :6006/mcp, which is exactly what these +// fixtures don't have. Pass criteria are the lifecycle outcome only; see the +// fixtures and storybookjs/mcp#324. +const LIFECYCLE_STORYBOOK_EVALS = [ + // No Storybook at all: the storybook-init skill drives setup + '820-init-no-storybook', + // Storybook 9.x preinstalled: major upgrade via the storybook-upgrade skill + '821-upgrade-from-sb9', + // Older stable (10.4.0) preinstalled: minor/patch upgrade path + '822-upgrade-from-stable', ] as const; // The 9xx line: evals ported from the old eval system (/eval), written for // the MCP-only workflow. On default (`next`) CI runs they are too expensive // and currently too flaky, so they only run under EVAL_STORYBOOK_LATEST=1 // (or manually via EVAL_ONLY). See storybookjs/mcp#315. -const PORTED_RESHAPED_STORYBOOK_EVALS = [ +const PORTED_WORKFLOW_STORYBOOK_EVALS = [ '901-create-component-atom-reshaped-concise', '901-create-component-atom-reshaped-detailed', '901-create-component-atom-reshaped-explicit-stories', @@ -63,7 +89,8 @@ const PORTED_RESHAPED_STORYBOOK_EVALS = [ type EvalName = | (typeof CORE_STORYBOOK_EVALS)[number] - | (typeof PORTED_RESHAPED_STORYBOOK_EVALS)[number]; + | (typeof LIFECYCLE_STORYBOOK_EVALS)[number] + | (typeof PORTED_WORKFLOW_STORYBOOK_EVALS)[number]; // EVAL_STORYBOOK_LATEST=1 (the ci:storybook-latest PR label or the // workflow_dispatch input in CI) runs the local MCP server against the stable @@ -76,13 +103,17 @@ const STORYBOOK_LATEST = process.env.EVAL_STORYBOOK_LATEST === '1'; // By default only the first eval of the active line runs, to keep // sandbox/token costs low. Set EVAL_EXTRA_EVALS=1 (the ci:extra-evals PR label // or the workflow_dispatch input in CI) to run the full line. -// EVAL_ONLY=[,] narrows the set to specific evals (core 8xx or -// ported 9xx) for local debugging, one eval at a time. -function resolveActiveEvals(): EvalName[] { +// EVAL_ONLY=[,] narrows the set to specific evals (core 8xx, +// lifecycle 82x, or ported 9xx) for local debugging, one eval at a time. +function resolveActiveEvals(): { core: EvalName[]; lifecycle: EvalName[] } { const only = process.env.EVAL_ONLY; if (only !== undefined && only !== '') { - const knownEvals = [...CORE_STORYBOOK_EVALS, ...PORTED_RESHAPED_STORYBOOK_EVALS]; - return only.split(',').map((name) => { + const knownEvals = [ + ...CORE_STORYBOOK_EVALS, + ...LIFECYCLE_STORYBOOK_EVALS, + ...PORTED_WORKFLOW_STORYBOOK_EVALS, + ]; + const selected = only.split(',').map((name) => { const match = knownEvals.find((evalName) => evalName === name.trim()); if (match === undefined) { throw new Error( @@ -91,30 +122,55 @@ function resolveActiveEvals(): EvalName[] { } return match; }); + const partitioned = { + core: selected.filter( + (name) => !(LIFECYCLE_STORYBOOK_EVALS as readonly string[]).includes(name), + ), + lifecycle: selected.filter((name) => + (LIFECYCLE_STORYBOOK_EVALS as readonly string[]).includes(name), + ), + }; + if (partitioned.core.length === 0 && partitioned.lifecycle.length > 0) { + console.warn( + 'EVAL_ONLY selected only lifecycle (82x) evals; the MCP experiments will run zero evals.', + ); + } + return partitioned; } if (process.env.EVAL_EXTRA_EVALS === '1') { - return STORYBOOK_LATEST ? [...PORTED_RESHAPED_STORYBOOK_EVALS] : [...CORE_STORYBOOK_EVALS]; + return STORYBOOK_LATEST + ? { core: [...PORTED_WORKFLOW_STORYBOOK_EVALS], lifecycle: [] } + : { core: [...CORE_STORYBOOK_EVALS], lifecycle: [...LIFECYCLE_STORYBOOK_EVALS] }; } return STORYBOOK_LATEST - ? ['901-create-component-atom-reshaped-concise'] - : ['801-create-component-no-launch-config']; + ? { core: ['901-create-component-atom-reshaped-concise'], lifecycle: [] } + : { core: ['801-create-component-no-launch-config'], lifecycle: [] }; } -export const RESHAPED_STORYBOOK_EVALS: EvalName[] = resolveActiveEvals(); +const ACTIVE_EVALS = resolveActiveEvals(); + +// The MCP experiments never run the lifecycle 82x evals: they configure the +// agent against a Storybook that must already be running at :6006/mcp, which +// the lifecycle fixtures intentionally don't have. +export const WORKFLOW_STORYBOOK_EVALS: EvalName[] = ACTIVE_EVALS.core; // Plugin-integration experiments run zero evals under EVAL_STORYBOOK_LATEST=1: // the plugin skills are not compatible with the stable Storybook release, so -// only the MCP experiments exercise the 9xx line there. -export const PLUGIN_STORYBOOK_EVALS: EvalName[] = STORYBOOK_LATEST ? [] : RESHAPED_STORYBOOK_EVALS; +// only the MCP experiments exercise the 9xx line there. On default runs they +// additionally cover the lifecycle 82x evals, whose skills only exist on the +// plugin path. +export const PLUGIN_STORYBOOK_EVALS: EvalName[] = STORYBOOK_LATEST + ? [] + : [...ACTIVE_EVALS.core, ...ACTIVE_EVALS.lifecycle]; // Non-default model tiers (e.g. cc-plugin-sonnet-medium) run zero evals unless // explicitly enabled, so labeled CI runs only pay for the default-model // experiments. Enable with EVAL_EXTRA_MODELS=1 (locally or via the // workflow_dispatch input in CI). export const EXTRA_MODEL_EVALS: EvalName[] = - process.env.EVAL_EXTRA_MODELS === '1' ? [...RESHAPED_STORYBOOK_EVALS] : []; + process.env.EVAL_EXTRA_MODELS === '1' ? [...WORKFLOW_STORYBOOK_EVALS] : []; export const EXTRA_MODEL_PLUGIN_EVALS: EvalName[] = process.env.EVAL_EXTRA_MODELS === '1' ? [...PLUGIN_STORYBOOK_EVALS] : []; diff --git a/agent-eval/templates/reshaped-storybook/scripts/start-storybook-mcp.mjs b/agent-eval/lib/mcp/start-storybook-mcp.mjs similarity index 100% rename from agent-eval/templates/reshaped-storybook/scripts/start-storybook-mcp.mjs rename to agent-eval/lib/mcp/start-storybook-mcp.mjs diff --git a/agent-eval/lib/shell-parse.ts b/agent-eval/lib/shell-parse.ts index 7db8dbb3..3803bdc6 100644 --- a/agent-eval/lib/shell-parse.ts +++ b/agent-eval/lib/shell-parse.ts @@ -126,10 +126,29 @@ function parseStorybookAiInvocation( }; } +// Matches the shell binary of a `bash -c '…'`-style wrapper, with or without a +// path prefix (`/bin/sh`). `env bash -c` also works, but only because `bash` +// itself is the token preceding `-c` — `env` is never matched. +const SHELL_BINARY_PATTERN = /^(?:.*\/)?(?:sh|bash|zsh|dash|ksh)$/; + function getNestedShellCommand(command: string): string | undefined { const tokens = tokenizeShellCommand(command); for (let index = 0; index < tokens.length - 1; index += 1) { - if (tokens[index] === '-c' || tokens[index] === '-lc') { + if (tokens[index] !== '-c' && tokens[index] !== '-lc') { + continue; + } + + // Only a `-c` that belongs to a shell binary wraps a nested command; + // `head -c 800`, `curl -c jar`, or `grep -c foo` must stay literal. + // Walk back over other dash flags so `bash -x -c '…'` still counts. + // Known limitation: a flag with a separate value argument (e.g. + // `bash -O extglob -c '…'`) stops the walk-back at the value and the + // wrapper is missed — accepted, agents have not been observed doing that. + let binaryIndex = index - 1; + while (binaryIndex >= 0 && tokens[binaryIndex]?.startsWith('-')) { + binaryIndex -= 1; + } + if (binaryIndex >= 0 && SHELL_BINARY_PATTERN.test(tokens[binaryIndex] ?? '')) { return tokens[index + 1]; } } diff --git a/agent-eval/lib/templates.ts b/agent-eval/lib/templates.ts index 925487a4..91568105 100644 --- a/agent-eval/lib/templates.ts +++ b/agent-eval/lib/templates.ts @@ -9,6 +9,7 @@ import { isRecord } from './shell-parse.ts'; type FixturePackageJson = { evals?: { template?: unknown; + pinStorybook?: unknown; }; }; @@ -72,6 +73,13 @@ const CODEX_BROWSER_SKILL_SANDBOX_PATH = path.posix.join( 'control-in-app-browser', 'SKILL.md', ); +const START_STORYBOOK_SCRIPT_SOURCE_PATH = path.join( + AGENT_EVAL_ROOT, + 'lib', + 'mcp', + 'start-storybook-mcp.mjs', +); +const START_STORYBOOK_SCRIPT_SANDBOX_PATH = path.posix.join('scripts', 'start-storybook-mcp.mjs'); const TRANSCRIPT_HELPER_SOURCE_PATH = path.join(AGENT_EVAL_ROOT, 'lib', 'test-utils.ts'); const TRANSCRIPT_HELPER_SANDBOX_PATH = path.posix.join('__agent_eval__', 'test-utils.ts'); // test-utils.ts imports ./shell-parse.ts, so the sandbox copy needs both files. @@ -79,8 +87,6 @@ const SHELL_PARSE_SOURCE_PATH = path.join(AGENT_EVAL_ROOT, 'lib', 'shell-parse.t const SHELL_PARSE_SANDBOX_PATH = path.posix.join('__agent_eval__', 'shell-parse.ts'); const AGENT_CONTEXT_SANDBOX_PATH = path.posix.join('__agent_eval__', 'agent.json'); const TEMPLATE_NAME_PATTERN = /^[a-z0-9][a-z0-9-]*$/; -const LOCAL_STORYBOOK_ADDON_MCP_SPEC = 'file:./local-packages/addon-mcp'; -const LOCAL_STORYBOOK_MCP_SPEC = 'file:./local-packages/mcp'; const STORYBOOK_MCP_SERVER_NAME = 'storybook-dev-mcp'; const STORYBOOK_MCP_URL = 'http://127.0.0.1:6006/mcp'; const PREVIEW_BROWSER_MCP_SERVER_NAME = 'preview-browser'; @@ -130,12 +136,30 @@ export async function setupSandbox( files = mergeTemplateAndFixtureFiles(files, fixtureFiles); - await pinStorybookPackages(files, process.env.EVAL_STORYBOOK_LATEST === '1' ? 'latest' : 'next'); + // Fixtures that intentionally ship an outdated Storybook (the upgrade-skill + // evals) opt out of pinning with `evals.pinStorybook: false`; everything + // else is pinned to the dist-tag so result snapshots record exact versions. + if (packageJson.evals?.pinStorybook !== false) { + await pinStorybookPackages( + files, + process.env.EVAL_STORYBOOK_LATEST === '1' ? 'latest' : 'next', + ); + } if (usesLocalStorybookMcpPackages(files)) { Object.assign(files, await readLocalStorybookMcpPackages()); } + // The Storybook-starting postinstall script is maintained once in lib/mcp + // and injected wherever a package.json references it, so the templates and + // fixtures cannot drift apart. + if (referencesStartStorybookScript(files)) { + files[START_STORYBOOK_SCRIPT_SANDBOX_PATH] = await fs.readFile( + START_STORYBOOK_SCRIPT_SOURCE_PATH, + 'utf8', + ); + } + await setupTemplateSandbox(sandbox, templateMetadata); await sandbox.writeFiles(files); } @@ -276,11 +300,39 @@ function deepMergeJson(templateValue: unknown, fixtureValue: unknown): unknown { return result; } +// The system libraries Playwright's chromium needs on the Amazon Linux +// sandbox image. Shared by every template that runs story tests, referenced +// from eval-template.json as `"amazonLinuxPackages": "playwright-chromium"`. +const PLAYWRIGHT_CHROMIUM_AMAZON_LINUX_PACKAGES = [ + 'alsa-lib', + 'at-spi2-atk', + 'at-spi2-core', + 'atk', + 'cairo', + 'cups-libs', + 'dbus-libs', + 'libX11', + 'libXcomposite', + 'libXdamage', + 'libXext', + 'libXfixes', + 'libXrandr', + 'libxcb', + 'libxkbcommon', + 'mesa-libgbm', + 'nspr', + 'nss', + 'pango', +]; + async function setupTemplateSandbox( sandbox: Sandbox, templateMetadata: TemplateMetadata, ): Promise { - const amazonLinuxPackages = templateMetadata.amazonLinuxPackages; + const amazonLinuxPackages = + templateMetadata.amazonLinuxPackages === 'playwright-chromium' + ? PLAYWRIGHT_CHROMIUM_AMAZON_LINUX_PACKAGES + : templateMetadata.amazonLinuxPackages; if (amazonLinuxPackages === undefined) { return; } @@ -292,7 +344,7 @@ async function setupTemplateSandbox( ) ) { throw new Error( - `${TEMPLATE_METADATA_FILE} amazonLinuxPackages must be an array of package-name strings`, + `${TEMPLATE_METADATA_FILE} amazonLinuxPackages must be an array of package-name strings or the "playwright-chromium" preset`, ); } @@ -326,44 +378,65 @@ async function installAmazonLinuxPackages(sandbox: Sandbox, packageNames: string } } -// Pin every Storybook dependency in the sandbox package.json to the version -// currently behind the given npm dist-tag, so result snapshots record the -// exact version each run used. The local @storybook/addon-mcp and -// @storybook/mcp file: builds are always kept as-is; EVAL_STORYBOOK_LATEST=1 -// only switches the Storybook release itself to the `latest` tag, to test the -// current checkout against the last stable release. +// Pin every Storybook dependency in the sandbox package.json files (the root +// and any workspace package) to the version currently behind the given npm +// dist-tag, so result snapshots record the exact version each run used. The +// local @storybook/addon-mcp and @storybook/mcp file: builds are always kept +// as-is; EVAL_STORYBOOK_LATEST=1 only switches the Storybook release itself +// to the `latest` tag, to test the current checkout against the last stable +// release. export async function pinStorybookPackages( files: Record, distTag: 'next' | 'latest', ): Promise { - const rawPackageJson = files['package.json']; - if (rawPackageJson === undefined) { - return; - } - - const packageJson = parseJsonFile('package.json', rawPackageJson, 'fixture'); - if (!isRecord(packageJson)) { - return; - } - - for (const field of ['dependencies', 'devDependencies'] as const) { - const dependencies = packageJson[field]; - if (!isRecord(dependencies)) { + for (const filePath of workspacePackageJsonPaths(files)) { + const packageJson = parseJsonFile(filePath, files[filePath] ?? '', 'fixture'); + if (!isRecord(packageJson)) { continue; } - for (const [name, spec] of Object.entries(dependencies)) { - if (name !== 'storybook' && !name.startsWith('@storybook/')) { + let pinned = false; + for (const field of ['dependencies', 'devDependencies'] as const) { + const dependencies = packageJson[field]; + if (!isRecord(dependencies)) { continue; } - if (typeof spec === 'string' && spec.startsWith('file:')) { - continue; + + for (const [name, spec] of Object.entries(dependencies)) { + if (name !== 'storybook' && !name.startsWith('@storybook/')) { + continue; + } + if (typeof spec === 'string' && spec.startsWith('file:')) { + continue; + } + dependencies[name] = await resolveDistTagVersion(name, distTag); + pinned = true; } - dependencies[name] = await resolveDistTagVersion(name, distTag); + } + + // Leave files without Storybook deps byte-identical to their source, so + // sandbox snapshots don't pick up reformatting noise. + if (pinned) { + files[filePath] = JSON.stringify(packageJson, null, 2).concat('\n'); } } +} + +function referencesStartStorybookScript(files: Record): boolean { + return workspacePackageJsonPaths(files).some((filePath) => + (files[filePath] ?? '').includes('start-storybook-mcp.mjs'), + ); +} - files['package.json'] = JSON.stringify(packageJson, null, 2).concat('\n'); +// The sandbox root package.json plus workspace packages; the injected +// local-packages builds are never rewritten. +function workspacePackageJsonPaths(files: Record): string[] { + return Object.keys(files).filter( + (filePath) => + (filePath === 'package.json' || filePath.endsWith('/package.json')) && + !filePath.startsWith('local-packages/') && + !filePath.includes('node_modules/'), + ); } const distTagVersionCache = new Map(); @@ -394,16 +467,27 @@ async function resolveDistTagVersion(packageName: string, distTag: string): Prom return version; } +// A workspace package references the injected builds with a file: spec whose +// target is the sandbox-root local-packages directory — `file:./local-packages/…` +// from the root, `file:../../local-packages/…` from a workspace leaf. function usesLocalStorybookMcpPackages(files: Record): boolean { - const packageJson = JSON.parse(files['package.json'] ?? '{}') as unknown; + return workspacePackageJsonPaths(files).some((filePath) => { + const packageJson = JSON.parse(files[filePath] ?? '{}') as unknown; - if (!isRecord(packageJson)) { - return false; - } + if (!isRecord(packageJson)) { + return false; + } + + return ( + isLocalPackagesSpec(getDependencySpec(packageJson, '@storybook/addon-mcp'), 'addon-mcp') || + isLocalPackagesSpec(getDependencySpec(packageJson, '@storybook/mcp'), 'mcp') + ); + }); +} +function isLocalPackagesSpec(spec: string | undefined, packageDir: string): boolean { return ( - getDependencySpec(packageJson, '@storybook/addon-mcp') === LOCAL_STORYBOOK_ADDON_MCP_SPEC || - getDependencySpec(packageJson, '@storybook/mcp') === LOCAL_STORYBOOK_MCP_SPEC + spec !== undefined && spec.startsWith('file:') && spec.endsWith(`local-packages/${packageDir}`) ); } diff --git a/agent-eval/lib/test-utils.test.ts b/agent-eval/lib/test-utils.test.ts index 8f013572..8635e7ad 100644 --- a/agent-eval/lib/test-utils.test.ts +++ b/agent-eval/lib/test-utils.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from 'vitest'; import { parseStorybookWorkflowShellCommands, + parseWorkflowToolResults, workflowCallIncludesStory, workflowCallUsesStoryId, } from './test-utils.ts'; @@ -109,4 +110,157 @@ describe('parseStorybookWorkflowShellCommands', () => { expect(calls[0]?.input).toEqual({}); expect(calls[1]?.input).not.toHaveProperty('json'); }); + + test('does not mistake a non-shell -c flag for a bash -c wrapper', () => { + // Regression: cc-plugin 802 (2026-07-03 CI run 28647682172) chained + // `head -c 800` before a real get-changed-stories call in one compound + // command; the parser recursed into the literal `800` as if it were a + // `bash -c` payload and dropped the workflow call. + const calls = parseStorybookWorkflowShellCommands([ + 'sleep 3; curl -s http://localhost:40097/index.json 2>/dev/null | head -c 800; echo; echo "---changed---"; STORYBOOK_FEATURE_AI_CLI=1 npx storybook ai --port 40097 get-changed-stories 2>&1 | grep -v "No story files" | head -40', + 'curl -c cookies.txt http://localhost:6006/ && npx storybook ai get-changed-stories', + 'grep -c foo bar.txt; npx storybook ai get-stories-by-component --json \'{"componentPaths":["src/Badge.tsx"]}\'', + ]); + + expect(calls.map((call) => call.name)).toEqual([ + 'get-changed-stories', + 'get-changed-stories', + 'get-stories-by-component', + ]); + }); + + test('still unwraps genuine shell wrappers around storybook ai calls', () => { + const calls = parseStorybookWorkflowShellCommands([ + "bash -c 'npx storybook ai get-changed-stories'", + "/bin/sh -lc 'npx storybook ai --port 6006 run-story-tests'", + "env bash -x -c 'npx storybook ai get-stories-by-component'", + ]); + + expect(calls.map((call) => call.name)).toEqual([ + 'get-changed-stories', + 'run-story-tests', + 'get-stories-by-component', + ]); + }); +}); + +describe('parseWorkflowToolResults', () => { + function claudeToolUseLine(id: string, name: string, input: Record): string { + return JSON.stringify({ + type: 'assistant', + message: { content: [{ type: 'tool_use', id, name, input }] }, + }); + } + + function claudeToolResultLine(toolUseId: string, content: unknown, isError = false): string { + return JSON.stringify({ + type: 'user', + message: { + content: [{ type: 'tool_result', tool_use_id: toolUseId, content, is_error: isError }], + }, + }); + } + + test('pairs Claude MCP tool_use and tool_result blocks by id', () => { + const transcript = [ + claudeToolUseLine('toolu_1', 'mcp__storybook-dev-mcp__run-story-tests', {}), + claudeToolUseLine('toolu_2', 'mcp__storybook-dev-mcp__preview-stories', {}), + claudeToolResultLine('toolu_2', [{ type: 'text', text: 'http://localhost:6006' }]), + claudeToolResultLine('toolu_1', [ + { type: 'text', text: '## Passing Stories\n\n- example-button--primary' }, + ]), + ].join('\n'); + + const results = parseWorkflowToolResults(transcript, 'run-story-tests'); + + expect(results).toHaveLength(1); + expect(results[0]?.output).toContain('## Passing Stories'); + expect(results[0]?.isError).toBe(false); + }); + + test('extracts Claude plugin-path results from storybook ai shell invocations', () => { + const transcript = [ + claudeToolUseLine('toolu_1', 'Bash', { + command: 'STORYBOOK_FEATURE_AI_CLI=1 npx storybook ai --port 6006 run-story-tests', + }), + claudeToolResultLine('toolu_1', '## Failing Stories\n\n### example-button--primary'), + ].join('\n'); + + const results = parseWorkflowToolResults(transcript, 'run-story-tests'); + + expect(results).toHaveLength(1); + expect(results[0]?.output).toContain('## Failing Stories'); + }); + + test('marks errored Claude tool results', () => { + const transcript = [ + claudeToolUseLine('toolu_1', 'mcp__storybook-dev-mcp__run-story-tests', {}), + claudeToolResultLine('toolu_1', 'Test run was cancelled', true), + ].join('\n'); + + const results = parseWorkflowToolResults(transcript, 'run-story-tests'); + + expect(results).toHaveLength(1); + expect(results[0]?.isError).toBe(true); + }); + + test('extracts completed Codex MCP tool call results', () => { + const transcript = [ + JSON.stringify({ + type: 'item.started', + item: { + type: 'mcp_tool_call', + tool: 'run-story-tests', + result: null, + status: 'in_progress', + }, + }), + JSON.stringify({ + type: 'item.completed', + item: { + type: 'mcp_tool_call', + tool: 'run-story-tests', + status: 'completed', + error: null, + result: { content: [{ type: 'text', text: '## Passing Stories\n\n- a--b' }] }, + }, + }), + ].join('\n'); + + const results = parseWorkflowToolResults(transcript, 'run-story-tests'); + + expect(results).toHaveLength(1); + expect(results[0]?.output).toContain('## Passing Stories'); + expect(results[0]?.isError).toBe(false); + }); + + test('extracts Codex plugin-path results from command_execution items', () => { + const transcript = [ + JSON.stringify({ + type: 'item.completed', + item: { + type: 'command_execution', + command: "/bin/bash -lc 'npx storybook ai --port 6006 run-story-tests'", + aggregated_output: '## Passing Stories\n\n- a--b\n\n## Failing Stories\n\n### a--c', + exit_code: 0, + status: 'completed', + }, + }), + ].join('\n'); + + const results = parseWorkflowToolResults(transcript, 'run-story-tests'); + + expect(results).toHaveLength(1); + expect(results[0]?.output).toContain('## Failing Stories'); + }); + + test('ignores unrelated tools and unparseable lines', () => { + const transcript = [ + 'not json', + claudeToolUseLine('toolu_1', 'Bash', { command: 'npm run lint' }), + claudeToolResultLine('toolu_1', 'lint ok'), + ].join('\n'); + + expect(parseWorkflowToolResults(transcript, 'run-story-tests')).toHaveLength(0); + }); }); diff --git a/agent-eval/lib/test-utils.ts b/agent-eval/lib/test-utils.ts index 570c83e0..5e8d3a8f 100644 --- a/agent-eval/lib/test-utils.ts +++ b/agent-eval/lib/test-utils.ts @@ -1,5 +1,7 @@ +import { spawn } from 'node:child_process'; import { existsSync, readdirSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; import { loadTranscript } from '@vercel/agent-eval'; import type { Transcript } from '@vercel/agent-eval'; @@ -15,7 +17,7 @@ import { } from './shell-parse.ts'; import type { StorybookWorkflowCall } from './shell-parse.ts'; -export { parseStorybookWorkflowShellCommands }; +export { isRecord, parseJson, parseStorybookWorkflowShellCommands }; export type { StorybookWorkflowCall }; const AGENT_CONTEXT_PATH = '__agent_eval__/agent.json'; @@ -121,6 +123,13 @@ export function expectFinalResponseContains(substrings: string[]): void { } } +export function expectFinalResponseMatches(patterns: RegExp[]): void { + const finalMessage = getFinalAssistantMessage() ?? ''; + for (const pattern of patterns) { + expect(finalMessage, `Expected the final response to match ${pattern}`).toMatch(pattern); + } +} + export function expectDisplayReviewForVisualChange(): void { const displayReview = getWorkflowCalls('display-review').at(-1); if (displayReview === undefined) { @@ -313,6 +322,240 @@ export function expectPreviewBrowserStarted(): void { ).toBe(true); } +// The story-ID mapping chain in the dev instructions: story IDs must come from +// a discovery tool (get-changed-stories, or the get-stories-by-component +// fallback), never from file names or memory. A published review without a +// prior discovery call means the agent guessed its way to valid-looking IDs. +const STORY_DISCOVERY_WORKFLOW_NAMES = ['get-changed-stories', 'get-stories-by-component']; + +export function expectStoryDiscoveryBeforeReview(): void { + const calls = getStorybookWorkflowCalls(); + const firstDiscoveryIndex = calls.findIndex((call) => + STORY_DISCOVERY_WORKFLOW_NAMES.includes(call.name), + ); + expect( + firstDiscoveryIndex, + `Expected a story-discovery call (${STORY_DISCOVERY_WORKFLOW_NAMES.join(' or ')}) before publishing the review`, + ).toBeGreaterThanOrEqual(0); + + const lastReviewIndex = calls.findLastIndex((call) => call.name === 'display-review'); + expect(lastReviewIndex, 'Expected display-review to be called').toBeGreaterThanOrEqual(0); + expect( + firstDiscoveryIndex, + 'Story discovery must happen before the review is published', + ).toBeLessThan(lastReviewIndex); +} + +export type WorkflowToolResult = { + output: string; + isError: boolean; +}; + +// Validation Workflow (test-instructions.md): "After each component or story +// change, run run-story-tests" and "Fix failing tests before reporting +// success." The section headers come from the run-story-tests result +// formatter in packages/addon-mcp (## Passing Stories / ## Failing Stories / +// ## Unhandled Errors) and appear verbatim in the MCP tool result and in the +// `storybook ai run-story-tests` CLI output. +// +// `covering` pins the final green run to the change under test: at least one +// of the given substrings must appear in its story ids. Where the covered +// stories are created by the change (801/802/804/812/813) or start from a +// seeded failure (810/811), a green covering run is only possible after the +// change, so this also proves ordering. Where the covered stories pre-exist +// and pass (803, 808), it is a component-coverage floor only — a stricter +// after-the-edit ordering check is deliberately not encoded, because real +// passing flows legitimately run tests before the discovery step. +export function expectStoryTestsRanAndPassed(options?: { covering?: string[] }): void { + expectWorkflowCalls(['run-story-tests']); + + const results = getWorkflowToolResults('run-story-tests'); + expect( + results.length, + 'Expected at least one run-story-tests result in the transcript', + ).toBeGreaterThan(0); + + const lastResult = results[results.length - 1]; + if (lastResult === undefined) { + expect.fail('Expected a final run-story-tests result'); + } + + expect( + lastResult.isError, + `Final run-story-tests call must succeed. Output: ${truncateForMessage(lastResult.output)}`, + ).toBe(false); + expect( + lastResult.output, + 'Final run-story-tests result must not report failing stories', + ).not.toMatch(/## Failing Stories/); + expect( + lastResult.output, + 'Final run-story-tests result must not report unhandled errors', + ).not.toMatch(/## Unhandled Errors/); + expect( + lastResult.output, + `Final run-story-tests result must report passing stories. Output: ${truncateForMessage(lastResult.output)}`, + ).toMatch(/## Passing Stories/); + + const covering = options?.covering ?? []; + if (covering.length > 0) { + expect( + covering.some((substring) => + lastResult.output.toLowerCase().includes(substring.toLowerCase()), + ), + `Final run-story-tests result must cover the changed component (one of: ${covering.join(', ')}). Output: ${truncateForMessage(lastResult.output)}`, + ).toBe(true); + } +} + +// Chronological outputs of a Storybook workflow tool, across every path an +// agent can reach it: Claude MCP tool calls, Codex MCP tool calls, and +// `storybook ai ` CLI invocations inside shell commands (plugin path). +export function getWorkflowToolResults(workflowName: string): WorkflowToolResult[] { + return parseWorkflowToolResults(readFileSync(TRANSCRIPT_PATH, 'utf8'), workflowName); +} + +export function parseWorkflowToolResults( + rawTranscript: string, + workflowName: string, +): WorkflowToolResult[] { + const results: WorkflowToolResult[] = []; + const pendingClaudeToolUseIds = new Set(); + + for (const line of rawTranscript.split('\n')) { + const event = parseJson(line); + if (!isRecord(event)) { + continue; + } + + collectClaudeWorkflowToolResults(event, workflowName, pendingClaudeToolUseIds, results); + collectCodexWorkflowToolResult(event, workflowName, results); + } + + return results; +} + +// Claude Code raw transcripts pair tool_use blocks (assistant messages) with +// tool_result blocks (user messages) via tool_use_id. +function collectClaudeWorkflowToolResults( + event: Record, + workflowName: string, + pendingToolUseIds: Set, + results: WorkflowToolResult[], +): void { + const message = event.message; + if (!isRecord(message) || !Array.isArray(message.content)) { + return; + } + + for (const block of message.content) { + if (!isRecord(block)) { + continue; + } + + if ( + block.type === 'tool_use' && + typeof block.id === 'string' && + isWorkflowToolUse(block, workflowName) + ) { + pendingToolUseIds.add(block.id); + continue; + } + + if ( + block.type === 'tool_result' && + typeof block.tool_use_id === 'string' && + pendingToolUseIds.has(block.tool_use_id) + ) { + pendingToolUseIds.delete(block.tool_use_id); + results.push({ + output: extractToolResultText(block.content), + isError: block.is_error === true, + }); + } + } +} + +function isWorkflowToolUse(block: Record, workflowName: string): boolean { + if (typeof block.name !== 'string') { + return false; + } + + if (normalizeStorybookWorkflowName(block.name) === workflowName) { + return true; + } + + // Plugin path: the workflow call runs as a `storybook ai` CLI invocation + // inside a shell tool call. + const command = isRecord(block.input) ? block.input.command : undefined; + if (typeof command !== 'string') { + return false; + } + + return parseStorybookWorkflowShellCommands([command]).some((call) => call.name === workflowName); +} + +// Codex raw transcripts report completed MCP tool calls and shell commands as +// item.completed events carrying the result inline. +function collectCodexWorkflowToolResult( + event: Record, + workflowName: string, + results: WorkflowToolResult[], +): void { + if (event.type !== 'item.completed' || !isRecord(event.item)) { + return; + } + + const item = event.item; + + if ( + item.type === 'mcp_tool_call' && + typeof item.tool === 'string' && + normalizeStorybookWorkflowName(item.tool) === workflowName + ) { + results.push({ + output: extractToolResultText(item.result), + isError: item.status !== 'completed' || (item.error !== null && item.error !== undefined), + }); + return; + } + + if ( + item.type === 'command_execution' && + typeof item.command === 'string' && + parseStorybookWorkflowShellCommands([item.command]).some((call) => call.name === workflowName) + ) { + results.push({ + output: typeof item.aggregated_output === 'string' ? item.aggregated_output : '', + isError: typeof item.exit_code === 'number' && item.exit_code !== 0, + }); + } +} + +// Tool result payloads appear as plain strings, MCP content-block arrays +// ([{ type: 'text', text }]), or objects wrapping such an array. +function extractToolResultText(content: unknown): string { + if (typeof content === 'string') { + return content; + } + + if (Array.isArray(content)) { + return content + .flatMap((block) => (isRecord(block) && typeof block.text === 'string' ? [block.text] : [])) + .join('\n'); + } + + if (isRecord(content)) { + return extractToolResultText(content.content); + } + + return ''; +} + +function truncateForMessage(value: string): string { + return value.length > 600 ? `${value.slice(0, 600)}…` : value; +} + export function expectDocumentationToolingCalled(): void { const documentationCalls = getStorybookWorkflowCalls().filter((call) => (DOCUMENTATION_WORKFLOW_NAMES as readonly string[]).includes(call.name), @@ -334,6 +577,205 @@ export function workflowCallUsesStoryId(call: StorybookWorkflowCall): boolean { return getStoryInputs(call.input).some((input) => typeof input.storyId === 'string'); } +// Claude Code invokes plugin skills through its Skill tool, so the transcript +// records which skill fired. Codex has no skill tool — engaging a skill means +// reading its instruction file, which shows up as a shell command touching +// the skill's directory. Only meaningful on the plugin integration (no skills +// are installed on the MCP path) — gate call sites with +// `test.skipIf(getEvalContext().integration === 'mcp')` so MCP runs report a +// skip instead of a vacuous pass. +export function expectSkillInvoked(skillName: string): void { + const { agent } = getEvalContext(); + + if (agent === 'claude-code') { + // Match the skill argument exactly — a substring match would credit any + // Skill invocation whose free-text args merely mention the word. + const invoked = getTranscript().events.some( + (event) => + event.type === 'tool_call' && + event.tool?.originalName === 'Skill' && + isRecord(event.tool.args) && + event.tool.args.skill === skillName, + ); + expect(invoked, `Expected the ${skillName} skill to be invoked via the Skill tool`).toBe(true); + return; + } + + // The codex plugin names its skill directories without the storybook- + // prefix (.agents/skills/init, .agents/skills/stories, …). + const codexSkillName = skillName.replace(/^storybook-/, ''); + const skillPathPattern = new RegExp(`skills/${codexSkillName}\\b`); + const read = getShellCommands().some((command) => skillPathPattern.test(command)); + expect( + read, + `Expected the ${skillName} skill (skills/${codexSkillName}) to be read via a shell command`, + ).toBe(true); +} + +// Lifecycle-outcome check for the upgrade evals: the given Storybook packages +// in package.json must end up at or above the minimum version — an +// under-upgrade (e.g. 9.x → 10.0.0 when the current release is 10.4.6) does +// not count. Compares the first x.y.z found in each spec numerically, so +// range prefixes (^, ~) don't matter. +export function expectStorybookDependenciesAtLeast( + minInclusiveVersion: string, + packageNames: string[], + options?: { + /** + * Packages a correct upgrade may legitimately *remove* (e.g. Storybook 10 + * absorbs `@storybook/react`): only floor-checked when still present, so + * a stale old copy fails but a clean removal passes. + */ + ifPresent?: string[]; + }, +): void { + const packageJson = parseJson(readFileSync('package.json', 'utf8')); + if (!isRecord(packageJson)) { + expect.fail('Expected package.json to contain a JSON object'); + } + + const dependencies = { + ...(isRecord(packageJson.dependencies) ? packageJson.dependencies : {}), + ...(isRecord(packageJson.devDependencies) ? packageJson.devDependencies : {}), + }; + + const minimum = parseSemverTriple(minInclusiveVersion); + if (minimum === undefined) { + throw new Error(`Invalid minInclusiveVersion "${minInclusiveVersion}"`); + } + + const expectAtLeastMinimum = (packageName: string, spec: string) => { + const version = parseSemverTriple(spec); + if (version === undefined) { + expect.fail(`Could not parse a version from the ${packageName} spec "${spec}"`); + } + + expect( + compareSemverTriples(version, minimum) >= 0, + `Expected ${packageName} to be upgraded to at least ${minInclusiveVersion}. Received: ${spec}`, + ).toBe(true); + }; + + for (const packageName of packageNames) { + const spec = dependencies[packageName]; + if (typeof spec !== 'string') { + expect.fail( + `Expected a ${packageName} dependency in package.json. Received: ${String(spec)}`, + ); + } + expectAtLeastMinimum(packageName, spec); + } + + for (const packageName of options?.ifPresent ?? []) { + const spec = dependencies[packageName]; + if (typeof spec === 'string') { + expectAtLeastMinimum(packageName, spec); + } + } +} + +function parseSemverTriple(spec: string): [number, number, number] | undefined { + const match = /(\d+)\.(\d+)\.(\d+)/.exec(spec); + if (match === null) { + return undefined; + } + return [Number(match[1]), Number(match[2]), Number(match[3])]; +} + +function compareSemverTriples(left: [number, number, number], right: [number, number, number]) { + for (let index = 0; index < 3; index += 1) { + const difference = (left[index] ?? 0) - (right[index] ?? 0); + if (difference !== 0) { + return difference; + } + } + return 0; +} + +export function expectShellCommandMatching(pattern: RegExp): void { + const commands = getShellCommands(); + expect( + commands.some((command) => pattern.test(command)), + `Expected a shell command matching ${pattern}. Received: ${truncateForMessage( + JSON.stringify(commands), + )}`, + ).toBe(true); +} + +// Lifecycle-outcome check (storybookjs/mcp#324): after storybook-init or +// storybook-upgrade, the project's own `storybook` script must produce a +// bootable Storybook. Boots on a non-default port so an instance the agent +// left running on 6006 cannot mask a broken script. +export async function expectStorybookBoots(options?: { timeoutMs?: number }): Promise { + const port = 6017; + const timeoutMs = options?.timeoutMs ?? 180_000; + + // --ci skips interactive prompts and does not open a browser; supported by + // every Storybook major this helper is used against (9.x onwards). + const child = spawn('npm', ['run', 'storybook', '--', '--port', String(port), '--ci'], { + detached: true, + env: { ...process.env, BROWSER: 'none', CI: '1' }, + stdio: 'ignore', + }); + + let spawnError: Error | undefined; + child.on('error', (error) => { + spawnError = error; + }); + + try { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (spawnError !== undefined) { + expect.fail(`Failed to spawn npm run storybook: ${spawnError.message}`); + } + // exitCode stays null when the process dies from a signal, so check + // signalCode too — otherwise a killed Storybook waits out the full + // timeout instead of failing with its termination reason. + if (child.exitCode !== null || child.signalCode !== null) { + expect.fail( + `npm run storybook exited (${ + child.signalCode !== null ? `signal ${child.signalCode}` : `code ${child.exitCode}` + }) before serving`, + ); + } + // /index.json is a real build artifact (the story index), so a dev + // server that merely serves an error shell on / does not count as + // booted. + if (await isHttpReady(`http://127.0.0.1:${port}/index.json`)) { + return; + } + await delay(1_000); + } + expect.fail(`Storybook did not respond on port ${port} within ${timeoutMs}ms`); + } finally { + killProcessTree(child); + } +} + +async function isHttpReady(url: string): Promise { + try { + const response = await fetch(url, { signal: AbortSignal.timeout(2_000) }); + return response.ok; + } catch { + return false; + } +} + +function killProcessTree(child: ReturnType): void { + if (child.pid === undefined) { + return; + } + + try { + // Detached child leads its own process group; negative pid signals the + // whole group so the Vite/Storybook workers die with it. + process.kill(-child.pid, 'SIGTERM'); + } catch { + child.kill('SIGTERM'); + } +} + // Soft-quality curation model from the Agentic Review Eval instructions (§5/§6b): // scored by the LLM judge rather than gated mechanically, because "meaningful // grouping" and "useful rationale" are judgment calls. @@ -416,9 +858,14 @@ function expectFinalResponseEndsWithReviewSection(): void { /^(?:\S+\s+)?\[[^\]\n]+\]\([^)\n]*[?&]path=\/review\/?[^)\n]*\)$/u, ); expect( - // Case-insensitive: the guidance shows the heading as an example, and - // Codex consistently writes it in Title Case. - lines.some((line) => /^##\s+.*review your changes\s*$/i.test(line.trim())), + // The spec's heading is an example ("e.g. ## 👀 Review your changes"), + // not a literal: agents legitimately adapt it — a browse request has no + // changes, so codex titled the section "## ReviewCard States" + // (CI run 28623099303). Require a review-ish heading, not exact words. + // The word boundary matters: without it "## Preview your changes" — the + // preview-URL ending this suite exists to reject — would satisfy the + // check via the "review" substring inside "Preview". + lines.some((line) => /^##\s+.*\breview/i.test(line.trim())), 'Final response must include a dedicated review heading', ).toBe(true); expect( @@ -471,6 +918,13 @@ function getRawCodexMcpWorkflowCalls(): StorybookWorkflowCall[] { return []; } + // Codex emits each MCP call twice (item.started + item.completed); + // counting both would double every call and let "called at least + // twice" assertions pass vacuously on a single real invocation. + if (event.type !== 'item.completed') { + return []; + } + const item = event.item; if (item.type !== 'mcp_tool_call' || typeof item.tool !== 'string') { return []; @@ -495,6 +949,13 @@ function getRawMcpInput(item: Record): Record return getNestedWorkflowInput(item) ?? {}; } +// Concatenation (parsed first, raw-only after) is order-safe in practice +// because each agent populates exactly one side: Claude transcripts parse +// fully (raw codex parsing matches nothing), while codex MCP calls come only +// from the raw pass (the upstream parser has no mcp_tool_call handling). If +// an agent ever split its calls across both sources, order-sensitive +// assertions like expectStoryDiscoveryBeforeReview would need interleaving by +// transcript position instead. function mergeMcpWorkflowCalls( parsedCalls: StorybookWorkflowCall[], rawCalls: StorybookWorkflowCall[], diff --git a/agent-eval/templates/monorepo/.claude/launch.json b/agent-eval/templates/monorepo/.claude/launch.json new file mode 100644 index 00000000..fa0fadca --- /dev/null +++ b/agent-eval/templates/monorepo/.claude/launch.json @@ -0,0 +1,12 @@ +{ + "version": "0.0.1", + "configurations": [ + { + "name": "storybook", + "runtimeExecutable": "npm", + "runtimeArgs": ["run", "storybook"], + "port": 6006, + "autoPort": true + } + ] +} diff --git a/agent-eval/templates/monorepo/eval-template.json b/agent-eval/templates/monorepo/eval-template.json new file mode 100644 index 00000000..87d3e1ac --- /dev/null +++ b/agent-eval/templates/monorepo/eval-template.json @@ -0,0 +1,3 @@ +{ + "amazonLinuxPackages": "playwright-chromium" +} diff --git a/agent-eval/templates/monorepo/package.json b/agent-eval/templates/monorepo/package.json new file mode 100644 index 00000000..98a8c499 --- /dev/null +++ b/agent-eval/templates/monorepo/package.json @@ -0,0 +1,22 @@ +{ + "name": "@storybook/mcp-eval-template-monorepo", + "version": "0.0.0", + "private": true, + "workspaces": [ + "packages/*" + ], + "type": "module", + "imports": { + "#test-utils": "./__agent_eval__/test-utils.ts" + }, + "scripts": { + "storybook": "npm run storybook --workspace @acme/ui --", + "postinstall": "playwright install chromium && node ./scripts/start-storybook-mcp.mjs" + }, + "devDependencies": { + "@vercel/agent-eval": "1.2.0", + "playwright": "1.56.1", + "typescript": "5.9.3", + "vitest": "4.0.6" + } +} diff --git a/agent-eval/templates/monorepo/packages/app/index.html b/agent-eval/templates/monorepo/packages/app/index.html new file mode 100644 index 00000000..a288f6c1 --- /dev/null +++ b/agent-eval/templates/monorepo/packages/app/index.html @@ -0,0 +1,12 @@ + + + + + + acme app + + +
+ + + diff --git a/agent-eval/templates/monorepo/packages/app/package.json b/agent-eval/templates/monorepo/packages/app/package.json new file mode 100644 index 00000000..73b2e176 --- /dev/null +++ b/agent-eval/templates/monorepo/packages/app/package.json @@ -0,0 +1,18 @@ +{ + "name": "@acme/app", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vite" + }, + "dependencies": { + "@acme/ui": "*", + "react": "19.2.0", + "react-dom": "19.2.0" + }, + "devDependencies": { + "@vitejs/plugin-react-swc": "4.2.2", + "vite": "7.2.2" + } +} diff --git a/agent-eval/templates/monorepo/packages/app/src/main.tsx b/agent-eval/templates/monorepo/packages/app/src/main.tsx new file mode 100644 index 00000000..d3d9d2e2 --- /dev/null +++ b/agent-eval/templates/monorepo/packages/app/src/main.tsx @@ -0,0 +1,11 @@ +import { StrictMode } from 'react'; +import { createRoot } from 'react-dom/client'; +import { Card } from '@acme/ui'; + +createRoot(document.getElementById('root')!).render( + +
+ The app consumes components from the @acme/ui package. +
+
, +); diff --git a/agent-eval/templates/monorepo/packages/ui/.storybook/main.ts b/agent-eval/templates/monorepo/packages/ui/.storybook/main.ts new file mode 100644 index 00000000..71c42a16 --- /dev/null +++ b/agent-eval/templates/monorepo/packages/ui/.storybook/main.ts @@ -0,0 +1,13 @@ +import type { StorybookConfig } from '@storybook/react-vite'; + +const config: StorybookConfig = { + stories: ['../@(stories|src)/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + addons: [ + '@storybook/addon-a11y', + '@storybook/addon-vitest', + '@storybook/addon-docs', + '@storybook/addon-mcp', + ], + framework: '@storybook/react-vite', +}; +export default config; diff --git a/agent-eval/templates/monorepo/packages/ui/.storybook/preview.tsx b/agent-eval/templates/monorepo/packages/ui/.storybook/preview.tsx new file mode 100644 index 00000000..8c649b95 --- /dev/null +++ b/agent-eval/templates/monorepo/packages/ui/.storybook/preview.tsx @@ -0,0 +1,7 @@ +import type { Preview } from '@storybook/react-vite'; + +const preview: Preview = { + parameters: {}, +}; + +export default preview; diff --git a/agent-eval/templates/monorepo/packages/ui/.storybook/vitest.setup.ts b/agent-eval/templates/monorepo/packages/ui/.storybook/vitest.setup.ts new file mode 100644 index 00000000..135e9064 --- /dev/null +++ b/agent-eval/templates/monorepo/packages/ui/.storybook/vitest.setup.ts @@ -0,0 +1,6 @@ +import * as a11yAddonAnnotations from '@storybook/addon-a11y/preview'; +import { setProjectAnnotations } from '@storybook/react-vite'; + +import * as projectAnnotations from './preview.tsx'; + +setProjectAnnotations([a11yAddonAnnotations, projectAnnotations]); diff --git a/agent-eval/templates/monorepo/packages/ui/package.json b/agent-eval/templates/monorepo/packages/ui/package.json new file mode 100644 index 00000000..ae75934d --- /dev/null +++ b/agent-eval/templates/monorepo/packages/ui/package.json @@ -0,0 +1,31 @@ +{ + "name": "@acme/ui", + "version": "0.0.0", + "private": true, + "type": "module", + "main": "./src/index.ts", + "scripts": { + "storybook": "storybook dev", + "build-storybook": "storybook build", + "test:stories": "vitest run --config ./vitest.storybook.config.ts --project storybook" + }, + "dependencies": { + "react": "19.2.0", + "react-dom": "19.2.0" + }, + "devDependencies": { + "@storybook/addon-a11y": "next", + "@storybook/addon-docs": "next", + "@storybook/addon-mcp": "file:../../local-packages/addon-mcp", + "@storybook/addon-vitest": "next", + "@storybook/mcp": "file:../../local-packages/mcp", + "@storybook/react": "next", + "@storybook/react-vite": "next", + "@types/react": "19.2.6", + "@types/react-dom": "19.2.3", + "@vitejs/plugin-react-swc": "4.2.2", + "@vitest/browser-playwright": "4.0.6", + "storybook": "next", + "vite": "7.2.2" + } +} diff --git a/agent-eval/templates/monorepo/packages/ui/src/components/Card.tsx b/agent-eval/templates/monorepo/packages/ui/src/components/Card.tsx new file mode 100644 index 00000000..a889f7f0 --- /dev/null +++ b/agent-eval/templates/monorepo/packages/ui/src/components/Card.tsx @@ -0,0 +1,24 @@ +import type { ReactNode } from 'react'; + +export type CardProps = { + title: string; + children: ReactNode; + padded?: boolean; +}; + +export default function Card({ title, children, padded = true }: CardProps) { + return ( +
+

{title}

+ {children} +
+ ); +} diff --git a/agent-eval/templates/monorepo/packages/ui/src/index.ts b/agent-eval/templates/monorepo/packages/ui/src/index.ts new file mode 100644 index 00000000..057744bf --- /dev/null +++ b/agent-eval/templates/monorepo/packages/ui/src/index.ts @@ -0,0 +1,2 @@ +export { default as Card } from './components/Card'; +export type { CardProps } from './components/Card'; diff --git a/agent-eval/templates/monorepo/packages/ui/stories/Card.stories.tsx b/agent-eval/templates/monorepo/packages/ui/stories/Card.stories.tsx new file mode 100644 index 00000000..6af74ed4 --- /dev/null +++ b/agent-eval/templates/monorepo/packages/ui/stories/Card.stories.tsx @@ -0,0 +1,22 @@ +import type { Meta, StoryObj } from '@storybook/react'; +import Card from '../src/components/Card'; + +const meta = { + title: 'UI/Card', + component: Card, + args: { + title: 'Release notes', + children: 'Everything that changed this week.', + }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const Default: Story = {}; + +export const Flush: Story = { + args: { + padded: false, + }, +}; diff --git a/agent-eval/templates/monorepo/packages/ui/tsconfig.json b/agent-eval/templates/monorepo/packages/ui/tsconfig.json new file mode 100644 index 00000000..a95cc327 --- /dev/null +++ b/agent-eval/templates/monorepo/packages/ui/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "moduleDetection": "force", + "noEmit": true, + "jsx": "react-jsx", + "skipLibCheck": true, + "strict": true + }, + "include": ["src", "stories", ".storybook", "vitest.config.ts", "vitest.storybook.config.ts"] +} diff --git a/agent-eval/templates/monorepo/packages/ui/vitest.config.ts b/agent-eval/templates/monorepo/packages/ui/vitest.config.ts new file mode 100644 index 00000000..cfef480f --- /dev/null +++ b/agent-eval/templates/monorepo/packages/ui/vitest.config.ts @@ -0,0 +1,3 @@ +// addon-vitest's run-story-tests starts Vitest from this package's root, so +// the storybook test project must be reachable from the default config. +export { default } from './vitest.storybook.config.ts'; diff --git a/agent-eval/templates/monorepo/packages/ui/vitest.storybook.config.ts b/agent-eval/templates/monorepo/packages/ui/vitest.storybook.config.ts new file mode 100644 index 00000000..e0935a93 --- /dev/null +++ b/agent-eval/templates/monorepo/packages/ui/vitest.storybook.config.ts @@ -0,0 +1,36 @@ +import * as path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { defineConfig } from 'vitest/config'; + +import { storybookTest } from '@storybook/addon-vitest/vitest-plugin'; + +import { playwright } from '@vitest/browser-playwright'; + +const dirname = + typeof __dirname !== 'undefined' ? __dirname : path.dirname(fileURLToPath(import.meta.url)); + +// More info at: https://storybook.js.org/docs/next/writing-tests/integrations/vitest-addon +export default defineConfig({ + optimizeDeps: { + include: ['react/jsx-dev-runtime'], + }, + test: { + projects: [ + { + extends: true, + plugins: [storybookTest({ configDir: path.join(dirname, '.storybook') })], + test: { + name: 'storybook', + browser: { + enabled: true, + headless: true, + provider: playwright({}), + instances: [{ browser: 'chromium' }], + }, + setupFiles: ['.storybook/vitest.setup.ts'], + }, + }, + ], + }, +}); diff --git a/agent-eval/templates/reshaped-storybook/eval-template.json b/agent-eval/templates/reshaped-storybook/eval-template.json index 222da134..87d3e1ac 100644 --- a/agent-eval/templates/reshaped-storybook/eval-template.json +++ b/agent-eval/templates/reshaped-storybook/eval-template.json @@ -1,23 +1,3 @@ { - "amazonLinuxPackages": [ - "alsa-lib", - "at-spi2-atk", - "at-spi2-core", - "atk", - "cairo", - "cups-libs", - "dbus-libs", - "libX11", - "libXcomposite", - "libXdamage", - "libXext", - "libXfixes", - "libXrandr", - "libxcb", - "libxkbcommon", - "mesa-libgbm", - "nspr", - "nss", - "pango" - ] + "amazonLinuxPackages": "playwright-chromium" } diff --git a/agent-eval/templates/vite-app/eval-template.json b/agent-eval/templates/vite-app/eval-template.json new file mode 100644 index 00000000..87d3e1ac --- /dev/null +++ b/agent-eval/templates/vite-app/eval-template.json @@ -0,0 +1,3 @@ +{ + "amazonLinuxPackages": "playwright-chromium" +} diff --git a/agent-eval/templates/vite-app/index.html b/agent-eval/templates/vite-app/index.html new file mode 100644 index 00000000..a68972eb --- /dev/null +++ b/agent-eval/templates/vite-app/index.html @@ -0,0 +1,12 @@ + + + + + + vite-app + + +
+ + + diff --git a/agent-eval/templates/vite-app/package.json b/agent-eval/templates/vite-app/package.json new file mode 100644 index 00000000..56b27523 --- /dev/null +++ b/agent-eval/templates/vite-app/package.json @@ -0,0 +1,28 @@ +{ + "name": "@storybook/mcp-eval-template-vite-app", + "version": "0.0.0", + "private": true, + "type": "module", + "imports": { + "#test-utils": "./__agent_eval__/test-utils.ts" + }, + "scripts": { + "dev": "vite", + "build": "vite build", + "typecheck": "tsc --noEmit --project ./tsconfig.app.json" + }, + "dependencies": { + "react": "19.2.0", + "react-dom": "19.2.0" + }, + "devDependencies": { + "@types/node": "24.10.1", + "@types/react": "19.2.6", + "@types/react-dom": "19.2.3", + "@vercel/agent-eval": "1.2.0", + "@vitejs/plugin-react-swc": "4.2.2", + "typescript": "5.9.3", + "vite": "7.2.2", + "vitest": "4.0.6" + } +} diff --git a/agent-eval/templates/vite-app/src/App.tsx b/agent-eval/templates/vite-app/src/App.tsx new file mode 100644 index 00000000..a6c6c147 --- /dev/null +++ b/agent-eval/templates/vite-app/src/App.tsx @@ -0,0 +1,14 @@ +import Button from './components/Button'; +import Tag from './components/Tag'; + +export default function App() { + return ( +
+

Team notes

+

+ A tiny app for sharing short notes with your team. +

+
+ ); +} diff --git a/agent-eval/templates/vite-app/src/components/Button.tsx b/agent-eval/templates/vite-app/src/components/Button.tsx new file mode 100644 index 00000000..00ef5097 --- /dev/null +++ b/agent-eval/templates/vite-app/src/components/Button.tsx @@ -0,0 +1,37 @@ +export type ButtonProps = { + label: string; + onClick?: () => void; + disabled?: boolean; + variant?: 'primary' | 'secondary'; +}; + +export default function Button({ + label, + onClick, + disabled = false, + variant = 'primary', +}: ButtonProps) { + const background = variant === 'primary' ? '#1d4ed8' : '#e5e7eb'; + const color = variant === 'primary' ? '#ffffff' : '#111827'; + + return ( + + ); +} diff --git a/agent-eval/templates/vite-app/src/components/Tag.tsx b/agent-eval/templates/vite-app/src/components/Tag.tsx new file mode 100644 index 00000000..d791034e --- /dev/null +++ b/agent-eval/templates/vite-app/src/components/Tag.tsx @@ -0,0 +1,31 @@ +export type TagProps = { + label: string; + tone?: 'neutral' | 'positive' | 'notice'; +}; + +const TONE_COLORS = { + neutral: { background: '#f3f4f6', color: '#374151' }, + positive: { background: '#dcfce7', color: '#166534' }, + notice: { background: '#fef9c3', color: '#854d0e' }, +} as const; + +export default function Tag({ label, tone = 'neutral' }: TagProps) { + const colors = TONE_COLORS[tone]; + + return ( + + {label} + + ); +} diff --git a/agent-eval/templates/vite-app/src/main.tsx b/agent-eval/templates/vite-app/src/main.tsx new file mode 100644 index 00000000..1a471279 --- /dev/null +++ b/agent-eval/templates/vite-app/src/main.tsx @@ -0,0 +1,9 @@ +import { StrictMode } from 'react'; +import { createRoot } from 'react-dom/client'; +import App from './App'; + +createRoot(document.getElementById('root')!).render( + + + , +); diff --git a/agent-eval/templates/vite-app/tsconfig.app.json b/agent-eval/templates/vite-app/tsconfig.app.json new file mode 100644 index 00000000..141fcb3b --- /dev/null +++ b/agent-eval/templates/vite-app/tsconfig.app.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", + "target": "ES2022", + "useDefineForClassFields": true, + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "module": "ESNext", + "types": ["node", "vite/client"], + "typeRoots": ["./node_modules/@types/", "./node_modules"], + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": false, + "moduleDetection": "force", + "noEmit": true, + "jsx": "react-jsx", + + /* Linting */ + "strict": true, + "noUnusedLocals": false, + "noUnusedParameters": false, + "erasableSyntaxOnly": true, + "noFallthroughCasesInSwitch": true, + "noUncheckedSideEffectImports": true + }, + "include": ["src", "stories", "vite.config.ts"] +} diff --git a/agent-eval/templates/vite-app/tsconfig.json b/agent-eval/templates/vite-app/tsconfig.json new file mode 100644 index 00000000..88a659fb --- /dev/null +++ b/agent-eval/templates/vite-app/tsconfig.json @@ -0,0 +1,4 @@ +{ + "files": [], + "references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }] +} diff --git a/agent-eval/templates/vite-app/tsconfig.node.json b/agent-eval/templates/vite-app/tsconfig.node.json new file mode 100644 index 00000000..e75109e0 --- /dev/null +++ b/agent-eval/templates/vite-app/tsconfig.node.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", + "target": "ES2023", + "lib": ["ES2023"], + "module": "ESNext", + "types": ["node"], + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "moduleDetection": "force", + "noEmit": true, + + /* Linting */ + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "erasableSyntaxOnly": true, + "noFallthroughCasesInSwitch": true, + "noUncheckedSideEffectImports": true + }, + "include": ["vite.config.ts"] +} diff --git a/agent-eval/templates/vite-app/vite.config.ts b/agent-eval/templates/vite-app/vite.config.ts new file mode 100644 index 00000000..9564da33 --- /dev/null +++ b/agent-eval/templates/vite-app/vite.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from 'vite'; +import react from '@vitejs/plugin-react-swc'; + +// https://vite.dev/config/ +export default defineConfig({ + plugins: [react()], + optimizeDeps: { + include: ['react/jsx-dev-runtime'], + }, +}); diff --git a/apps/internal-storybook/tests/mcp-endpoint.e2e.test.ts b/apps/internal-storybook/tests/mcp-endpoint.e2e.test.ts index 2cb8b05d..bad4cbbd 100644 --- a/apps/internal-storybook/tests/mcp-endpoint.e2e.test.ts +++ b/apps/internal-storybook/tests/mcp-endpoint.e2e.test.ts @@ -110,9 +110,8 @@ describe('MCP Endpoint E2E Tests', () => { "resourceUri": "ui://preview-stories/preview.html", }, }, - "description": "Use this tool to get one or more Storybook preview URLs. - Include each returned preview URL in your final user-facing response so users can open them directly — unless you're also publishing a curated review via display-review, in which case link the review page instead of listing individual URLs. - When the user asked to see or browse existing stories or components (e.g. "show me all the Button variants") and the display-review tool is available, publish a curated review with display-review (passing changedFiles: []) instead of answering with raw preview links; use this tool for verifying your own changes or sharing a specific story on request.", + "description": "Use this tool to get Storybook preview URLs while iterating on a specific story, or when the user asks for a direct link to one. + Do not end visual work or browse requests with these links — publish a curated review with display-review instead (passing changedFiles: [] when no code changed) and link that.", "inputSchema": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { @@ -790,6 +789,10 @@ describe('MCP Endpoint E2E Tests', () => { "text": "http://localhost:6006/?path=/story/example-button--primary", "type": "text", }, + { + "text": "These preview links are for iterating or sharing a specific story — they are not how visual work or a browse request ends. The display-review tool is available in this session: if you are finishing visually observable work or showing a set of stories, publish the review with **display-review** and link that instead.", + "type": "text", + }, ], "structuredContent": { "stories": [ diff --git a/codecov.yml b/codecov.yml index dd63a725..0546863c 100644 --- a/codecov.yml +++ b/codecov.yml @@ -1,3 +1,13 @@ +coverage: + status: + project: + default: + # A few covered lines in the package unit tests are timing-dependent, + # so identical source can report a couple of hits more or less between + # uploads (seen as a -0.10% "drop" on PRs that don't touch covered + # code at all). Allow that jitter; real regressions are far larger. + threshold: 0.5% + ignore: - 'agent-eval/app/**/*' - 'agent-eval/next.config.ts' diff --git a/packages/addon-mcp/src/instructions/build-server-instructions.test.ts b/packages/addon-mcp/src/instructions/build-server-instructions.test.ts index 267be3b1..15a86550 100644 --- a/packages/addon-mcp/src/instructions/build-server-instructions.test.ts +++ b/packages/addon-mcp/src/instructions/build-server-instructions.test.ts @@ -18,9 +18,10 @@ describe('buildServerInstructions', () => { - Before creating or editing components or stories, call **get-storybook-story-instructions**. - Treat that tool's output as the source of truth for framework-specific imports, story patterns, and testing conventions. - - After changing any component or story, call **get-changed-stories** to discover new/modified/related stories, then call **preview-stories** to retrieve preview URLs. - - In your final user-facing response, show one set of links — never both. If you published a review with **display-review**, finish your reply with a dedicated review section as the very last thing in the output: its own top-level heading on a line by itself (for example \`## 👀 Review your changes\`), then a one-line explanation that the review shows the handful of stories most relevant to this change and that, because it is AI-curated, results may be inaccurate or incomplete, then on the next line the review page as a markdown link prefixed with a 👉 so it is easy to spot, using the returned \`reviewUrl\` (for example \`👉 [Open the Storybook review page]()\`). Nothing should come after this section. Never also list the individual story or preview URLs. Avoid internal jargon like "collection" or "trigger" in anything the user reads — those are terms from this tooling, not words that mean anything to them; use plain language unless the user used the term first. If you did not publish a review (e.g. a non-visual refactor, or you skipped it), include the returned preview URLs instead so the user can verify the visual result. - - After a UI change, call **display-review** to publish a curated review — but only when the change is expected to be visually observable. Pure refactors with no rendering impact (type-only edits, internal renames, dead-code removal, comment/import reorg) don't need a review; skip the call, or publish a single small collection and note in the description that no visible change is expected. When you're unsure whether a refactor has visual side-effects, publish the review and say so. Every story you created in this change must appear in the review, including interaction/play-function stories; showing the stories you modified is encouraged too — curate by grouping, never by omission. Also call **display-review** whenever the user wants to see or browse stories/components rather than change them (e.g. "show me all badge components", "what button variants do we have") — resolve the matching story IDs and render them as collections, passing \`changedFiles: []\` since no code changed. The Storybook serving these tools is already running — a successful tool call proves it. Never start another Storybook to view the review: no \`storybook dev\`, no run/launch task, no editing a launch config, no new port. Reuse the running instance at the \`reviewUrl\`'s origin; if its port looks busy, that **is** the Storybook to reuse, not a conflict to route around. If the session has any browser-preview or navigate tool, open the returned \`reviewUrl\` in your preview browser yourself — don't just print the link, actually navigate to it so the review opens in your preview window. Separately, always show the \`reviewUrl\` to the user in your final response as well, even after you've opened it yourself — they need the link too. Call this tool again whenever the user iterates on the changes. + - After changing any component or story, call **get-changed-stories** to discover the new, modified, and related stories affected by your change. + - In your final user-facing response, show one set of links — never both. If you published a review with **display-review**, finish your reply with a dedicated review section as the very last thing in the output: its own top-level heading on a line by itself (for example \`## 👀 Review your changes\`), then a one-line explanation that the review shows the handful of stories most relevant to this change and that, because it is AI-curated, results may be inaccurate or incomplete, then on the next line the review page as a markdown link prefixed with a 👉 so it is easy to spot, using the returned \`reviewUrl\` (for example \`👉 [Open the Storybook review page]()\`). Nothing should come after this section. Never also list the individual story or preview URLs. Avoid internal jargon like "collection" or "trigger" in anything the user reads — those are terms from this tooling, not words that mean anything to them; use plain language unless the user used the term first. A visually observable change is not finished until its review is published — never substitute preview URLs for the review. Only when there is no review because the change has no visually observable impact, say so plainly; include preview URLs only if the user asked to see specific stories. + - After a UI change, call **display-review** to publish a curated review — but only when the change is expected to be visually observable. Publishing that review is how you finish visual work; the change is not done without it. Pure refactors with no rendering impact (type-only edits, internal renames, dead-code removal, comment/import reorg) don't need a review; skip the call, or publish a single small collection and note in the description that no visible change is expected. When you're unsure whether a refactor has visual side-effects, publish the review and say so. Every story you created in this change must appear in the review, including interaction/play-function stories; showing the stories you modified is encouraged too — curate by grouping, never by omission. Also call **display-review** whenever the user wants to see or browse stories/components rather than change them (e.g. "show me all badge components", "what button variants do we have") — resolve the matching story IDs and render them as collections, passing \`changedFiles: []\` since no code changed. The Storybook serving these tools is already running — a successful tool call proves it. Never start another Storybook to view the review: no \`storybook dev\`, no run/launch task, no editing a launch config, no new port. Reuse the running instance at the \`reviewUrl\`'s origin; if its port looks busy, that **is** the Storybook to reuse, not a conflict to route around. If the session has any browser-preview or navigate tool, open the returned \`reviewUrl\` in your preview browser yourself — don't just print the link, actually navigate to it so the review opens in your preview window. Separately, always show the \`reviewUrl\` to the user in your final response as well, even after you've opened it yourself — they need the link too. Call this tool again whenever the user iterates on the changes. + - Use **preview-stories** only while iterating on a specific story or when the user asks for a direct link to one — never as the ending of visual work; the review is the ending. ## Mapping any input to story IDs @@ -76,9 +77,10 @@ describe('buildServerInstructions', () => { - Before creating or editing components or stories, call **get-storybook-story-instructions**. - Treat that tool's output as the source of truth for framework-specific imports, story patterns, and testing conventions. - - After changing any component or story, call **get-changed-stories** to discover new/modified/related stories, then call **preview-stories** to retrieve preview URLs. - - In your final user-facing response, show one set of links — never both. If you published a review with **display-review**, finish your reply with a dedicated review section as the very last thing in the output: its own top-level heading on a line by itself (for example \`## 👀 Review your changes\`), then a one-line explanation that the review shows the handful of stories most relevant to this change and that, because it is AI-curated, results may be inaccurate or incomplete, then on the next line the review page as a markdown link prefixed with a 👉 so it is easy to spot, using the returned \`reviewUrl\` (for example \`👉 [Open the Storybook review page]()\`). Nothing should come after this section. Never also list the individual story or preview URLs. Avoid internal jargon like "collection" or "trigger" in anything the user reads — those are terms from this tooling, not words that mean anything to them; use plain language unless the user used the term first. If you did not publish a review (e.g. a non-visual refactor, or you skipped it), include the returned preview URLs instead so the user can verify the visual result. - - After a UI change, call **display-review** to publish a curated review — but only when the change is expected to be visually observable. Pure refactors with no rendering impact (type-only edits, internal renames, dead-code removal, comment/import reorg) don't need a review; skip the call, or publish a single small collection and note in the description that no visible change is expected. When you're unsure whether a refactor has visual side-effects, publish the review and say so. Every story you created in this change must appear in the review, including interaction/play-function stories; showing the stories you modified is encouraged too — curate by grouping, never by omission. Also call **display-review** whenever the user wants to see or browse stories/components rather than change them (e.g. "show me all badge components", "what button variants do we have") — resolve the matching story IDs and render them as collections, passing \`changedFiles: []\` since no code changed. The Storybook serving these tools is already running — a successful tool call proves it. Never start another Storybook to view the review: no \`storybook dev\`, no run/launch task, no editing a launch config, no new port. Reuse the running instance at the \`reviewUrl\`'s origin; if its port looks busy, that **is** the Storybook to reuse, not a conflict to route around. If the session has any browser-preview or navigate tool, open the returned \`reviewUrl\` in your preview browser yourself — don't just print the link, actually navigate to it so the review opens in your preview window. Separately, always show the \`reviewUrl\` to the user in your final response as well, even after you've opened it yourself — they need the link too. Call this tool again whenever the user iterates on the changes. + - After changing any component or story, call **get-changed-stories** to discover the new, modified, and related stories affected by your change. + - In your final user-facing response, show one set of links — never both. If you published a review with **display-review**, finish your reply with a dedicated review section as the very last thing in the output: its own top-level heading on a line by itself (for example \`## 👀 Review your changes\`), then a one-line explanation that the review shows the handful of stories most relevant to this change and that, because it is AI-curated, results may be inaccurate or incomplete, then on the next line the review page as a markdown link prefixed with a 👉 so it is easy to spot, using the returned \`reviewUrl\` (for example \`👉 [Open the Storybook review page]()\`). Nothing should come after this section. Never also list the individual story or preview URLs. Avoid internal jargon like "collection" or "trigger" in anything the user reads — those are terms from this tooling, not words that mean anything to them; use plain language unless the user used the term first. A visually observable change is not finished until its review is published — never substitute preview URLs for the review. Only when there is no review because the change has no visually observable impact, say so plainly; include preview URLs only if the user asked to see specific stories. + - After a UI change, call **display-review** to publish a curated review — but only when the change is expected to be visually observable. Publishing that review is how you finish visual work; the change is not done without it. Pure refactors with no rendering impact (type-only edits, internal renames, dead-code removal, comment/import reorg) don't need a review; skip the call, or publish a single small collection and note in the description that no visible change is expected. When you're unsure whether a refactor has visual side-effects, publish the review and say so. Every story you created in this change must appear in the review, including interaction/play-function stories; showing the stories you modified is encouraged too — curate by grouping, never by omission. Also call **display-review** whenever the user wants to see or browse stories/components rather than change them (e.g. "show me all badge components", "what button variants do we have") — resolve the matching story IDs and render them as collections, passing \`changedFiles: []\` since no code changed. The Storybook serving these tools is already running — a successful tool call proves it. Never start another Storybook to view the review: no \`storybook dev\`, no run/launch task, no editing a launch config, no new port. Reuse the running instance at the \`reviewUrl\`'s origin; if its port looks busy, that **is** the Storybook to reuse, not a conflict to route around. If the session has any browser-preview or navigate tool, open the returned \`reviewUrl\` in your preview browser yourself — don't just print the link, actually navigate to it so the review opens in your preview window. Separately, always show the \`reviewUrl\` to the user in your final response as well, even after you've opened it yourself — they need the link too. Call this tool again whenever the user iterates on the changes. + - Use **preview-stories** only while iterating on a specific story or when the user asks for a direct link to one — never as the ending of visual work; the review is the ending. ## Mapping any input to story IDs @@ -142,6 +144,43 @@ describe('buildServerInstructions', () => { expect(instructions).not.toContain('call **get-changed-stories**'); }); + it('feeds get-stories-by-component into the review when only the dependency graph is available', () => { + const instructions = buildServerInstructions({ + devEnabled: true, + testEnabled: false, + docsEnabled: false, + changeDetectionEnabled: false, + moduleGraphSupported: true, + reviewEnabled: true, + }); + + // With review enabled the after-change step must not end in + // preview-stories — discovery feeds display-review instead. + expect(instructions).toContain( + '- After changing any component or story, call **get-stories-by-component** with the absolute paths of the files you touched to find the stories that render them.', + ); + expect(instructions).not.toContain('then call **preview-stories** to retrieve preview URLs'); + expect(instructions).toContain( + '- Use **preview-stories** only while iterating on a specific story', + ); + }); + + it('routes the after-change step through the story-ID mapping when review is on without discovery tools', () => { + const instructions = buildServerInstructions({ + devEnabled: true, + testEnabled: false, + docsEnabled: false, + changeDetectionEnabled: false, + moduleGraphSupported: false, + reviewEnabled: true, + }); + + expect(instructions).toContain( + '- After changing any component or story, resolve the affected story IDs (see "Mapping any input to story IDs" below).', + ); + expect(instructions).not.toContain('then call **preview-stories** to retrieve preview URLs'); + }); + it('omits display-review step when reviewEnabled is false even with change detection on', () => { const instructions = buildServerInstructions({ devEnabled: true, diff --git a/packages/addon-mcp/src/instructions/build-server-instructions.ts b/packages/addon-mcp/src/instructions/build-server-instructions.ts index bb652678..0e9af876 100644 --- a/packages/addon-mcp/src/instructions/build-server-instructions.ts +++ b/packages/addon-mcp/src/instructions/build-server-instructions.ts @@ -30,7 +30,7 @@ export type BuildServerInstructionsOptions = { */ export function getFinalLinksGuidance(reviewToolAvailable: boolean): string { return reviewToolAvailable - ? 'In your final user-facing response, show one set of links — never both. If you published a review with **display-review**, finish your reply with a dedicated review section as the very last thing in the output: its own top-level heading on a line by itself (for example `## 👀 Review your changes`), then a one-line explanation that the review shows the handful of stories most relevant to this change and that, because it is AI-curated, results may be inaccurate or incomplete, then on the next line the review page as a markdown link prefixed with a 👉 so it is easy to spot, using the returned `reviewUrl` (for example `👉 [Open the Storybook review page]()`). Nothing should come after this section. Never also list the individual story or preview URLs. Avoid internal jargon like "collection" or "trigger" in anything the user reads — those are terms from this tooling, not words that mean anything to them; use plain language unless the user used the term first. If you did not publish a review (e.g. a non-visual refactor, or you skipped it), include the returned preview URLs instead so the user can verify the visual result.' + ? 'In your final user-facing response, show one set of links — never both. If you published a review with **display-review**, finish your reply with a dedicated review section as the very last thing in the output: its own top-level heading on a line by itself (for example `## 👀 Review your changes`), then a one-line explanation that the review shows the handful of stories most relevant to this change and that, because it is AI-curated, results may be inaccurate or incomplete, then on the next line the review page as a markdown link prefixed with a 👉 so it is easy to spot, using the returned `reviewUrl` (for example `👉 [Open the Storybook review page]()`). Nothing should come after this section. Never also list the individual story or preview URLs. Avoid internal jargon like "collection" or "trigger" in anything the user reads — those are terms from this tooling, not words that mean anything to them; use plain language unless the user used the term first. A visually observable change is not finished until its review is published — never substitute preview URLs for the review. Only when there is no review because the change has no visually observable impact, say so plainly; include preview URLs only if the user asked to see specific stories.' : 'In your final user-facing response, include every returned preview URL so the user can verify the visual result, ordered consistently (changed-stories fallback first if relevant, then the specific preview URLs).'; } @@ -41,11 +41,23 @@ export function buildServerInstructions(options: BuildServerInstructionsOptions) const changeDetection = options.changeDetectionEnabled ?? false; const graphSupported = options.moduleGraphSupported ?? false; const reviewEnabled = options.reviewEnabled ?? false; - const previewStoriesStep = changeDetection - ? 'After changing any component or story, call **get-changed-stories** to discover new/modified/related stories, then call **preview-stories** to retrieve preview URLs.' - : graphSupported - ? 'After changing any component or story, call **get-stories-by-component** with the absolute paths of the files you touched to find the stories that render them, then call **preview-stories** to retrieve preview URLs.' - : 'After changing any component or story, call **preview-stories** to retrieve preview URLs.'; + // When display-review is available it is the terminal step for visual + // work, so the after-change step feeds the review instead of ending in + // preview URLs — a competing "call preview-stories after every change" + // instruction reads as an alternative ending and agents take it + // (observed on the Codex MCP path: change done, preview links shared, + // review never published). + const previewStoriesStep = reviewEnabled + ? changeDetection + ? 'After changing any component or story, call **get-changed-stories** to discover the new, modified, and related stories affected by your change.' + : graphSupported + ? 'After changing any component or story, call **get-stories-by-component** with the absolute paths of the files you touched to find the stories that render them.' + : 'After changing any component or story, resolve the affected story IDs (see "Mapping any input to story IDs" below).' + : changeDetection + ? 'After changing any component or story, call **get-changed-stories** to discover new/modified/related stories, then call **preview-stories** to retrieve preview URLs.' + : graphSupported + ? 'After changing any component or story, call **get-stories-by-component** with the absolute paths of the files you touched to find the stories that render them, then call **preview-stories** to retrieve preview URLs.' + : 'After changing any component or story, call **preview-stories** to retrieve preview URLs.'; // Final response shows one set of links, never both when display-review // is available. Shared with the story-instructions output via // getFinalLinksGuidance so the two can't drift apart. @@ -57,7 +69,7 @@ export function buildServerInstructions(options: BuildServerInstructionsOptions) .replace( '{{DISPLAY_REVIEW_STEP}}', reviewEnabled - ? "\n- After a UI change, call **display-review** to publish a curated review — but only when the change is expected to be visually observable. Pure refactors with no rendering impact (type-only edits, internal renames, dead-code removal, comment/import reorg) don't need a review; skip the call, or publish a single small collection and note in the description that no visible change is expected. When you're unsure whether a refactor has visual side-effects, publish the review and say so. Every story you created in this change must appear in the review, including interaction/play-function stories; showing the stories you modified is encouraged too — curate by grouping, never by omission. Also call **display-review** whenever the user wants to see or browse stories/components rather than change them (e.g. \"show me all badge components\", \"what button variants do we have\") — resolve the matching story IDs and render them as collections, passing `changedFiles: []` since no code changed. The Storybook serving these tools is already running — a successful tool call proves it. Never start another Storybook to view the review: no `storybook dev`, no run/launch task, no editing a launch config, no new port. Reuse the running instance at the `reviewUrl`'s origin; if its port looks busy, that **is** the Storybook to reuse, not a conflict to route around. If the session has any browser-preview or navigate tool, open the returned `reviewUrl` in your preview browser yourself — don't just print the link, actually navigate to it so the review opens in your preview window. Separately, always show the `reviewUrl` to the user in your final response as well, even after you've opened it yourself — they need the link too. Call this tool again whenever the user iterates on the changes." + ? "\n- After a UI change, call **display-review** to publish a curated review — but only when the change is expected to be visually observable. Publishing that review is how you finish visual work; the change is not done without it. Pure refactors with no rendering impact (type-only edits, internal renames, dead-code removal, comment/import reorg) don't need a review; skip the call, or publish a single small collection and note in the description that no visible change is expected. When you're unsure whether a refactor has visual side-effects, publish the review and say so. Every story you created in this change must appear in the review, including interaction/play-function stories; showing the stories you modified is encouraged too — curate by grouping, never by omission. Also call **display-review** whenever the user wants to see or browse stories/components rather than change them (e.g. \"show me all badge components\", \"what button variants do we have\") — resolve the matching story IDs and render them as collections, passing `changedFiles: []` since no code changed. The Storybook serving these tools is already running — a successful tool call proves it. Never start another Storybook to view the review: no `storybook dev`, no run/launch task, no editing a launch config, no new port. Reuse the running instance at the `reviewUrl`'s origin; if its port looks busy, that **is** the Storybook to reuse, not a conflict to route around. If the session has any browser-preview or navigate tool, open the returned `reviewUrl` in your preview browser yourself — don't just print the link, actually navigate to it so the review opens in your preview window. Separately, always show the `reviewUrl` to the user in your final response as well, even after you've opened it yourself — they need the link too. Call this tool again whenever the user iterates on the changes.\n- Use **preview-stories** only while iterating on a specific story or when the user asks for a direct link to one — never as the ending of visual work; the review is the ending." : '', ) .trim(), diff --git a/packages/addon-mcp/src/tools/get-changed-stories.test.ts b/packages/addon-mcp/src/tools/get-changed-stories.test.ts index 27da3e6e..1146ab79 100644 --- a/packages/addon-mcp/src/tools/get-changed-stories.test.ts +++ b/packages/addon-mcp/src/tools/get-changed-stories.test.ts @@ -232,6 +232,106 @@ describe('getChangedStoriesTool', () => { `); }); + // Registers the tool on a fresh server with the review feature enabled, so + // the "publish the review now" next-step hint paths can be exercised. + async function createReviewEnabledServer() { + const adapter = new ValibotJsonSchemaAdapter(); + const reviewServer = new McpServer( + { + name: 'test-server-review', + version: '1.0.0', + description: 'Test server for get-changed-stories with review enabled', + }, + { adapter, capabilities: { tools: { listChanged: true } } }, + ).withContext(); + + await reviewServer.receive( + { + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: '2025-06-18', + capabilities: {}, + clientInfo: { name: 'test', version: '1.0.0' }, + }, + }, + { sessionId: 'test-session' }, + ); + + await addGetChangedStoriesTool(reviewServer, undefined, { reviewEnabled: true }); + return reviewServer; + } + + async function callToolOn(targetServer: McpServer) { + return targetServer.receive( + { + jsonrpc: '2.0' as const, + id: 1, + method: 'tools/call', + params: { name: GET_CHANGED_STORIES_TOOL_NAME, arguments: {} }, + }, + { sessionId: 'test-session', custom: testContext }, + ); + } + + it('appends the display-review next-step hint when review is enabled and stories were detected', async () => { + mockGetStatusStore.mockReturnValue({ + getAll: () => ({ + 'button--primary': { + 'storybook/change-detection': { + value: 'status-value:new', + storyId: 'button--primary', + }, + }, + }), + }); + + const text = getResultText(await callToolOn(await createReviewEnabledServer())); + + expect(text).toContain('Detected 1 changed story'); + expect(text).toContain('publish the review now — call **display-review**'); + }); + + it('omits the display-review hint when review is enabled but no stories resolve', async () => { + // Status store entries that don't exist in the index resolve to zero + // stories — exactly the case where the agent should fall back to + // get-stories-by-component instead of being pointed at an empty list. + mockGetStatusStore.mockReturnValue({ + getAll: () => ({ + 'not-in-index--at-all': { + 'storybook/change-detection': { + value: 'status-value:new', + storyId: 'not-in-index--at-all', + }, + }, + }), + }); + + const text = getResultText(await callToolOn(await createReviewEnabledServer())); + + expect(text).toContain('Detected 0 changed stories'); + expect(text).not.toContain('publish the review now'); + }); + + it('omits the display-review hint when review is disabled', async () => { + mockGetStatusStore.mockReturnValue({ + getAll: () => ({ + 'button--primary': { + 'storybook/change-detection': { + value: 'status-value:new', + storyId: 'button--primary', + }, + }, + }), + }); + + const text = getResultText(await callTool()); + + expect(text).toContain('Detected 1 changed story'); + expect(text).not.toContain('publish the review now'); + }); + it('supports getAll() status-store API', async () => { mockGetStatusStore.mockReturnValue({ getAll: () => ({ diff --git a/packages/addon-mcp/src/tools/get-changed-stories.ts b/packages/addon-mcp/src/tools/get-changed-stories.ts index ce0d5e62..62f500e2 100644 --- a/packages/addon-mcp/src/tools/get-changed-stories.ts +++ b/packages/addon-mcp/src/tools/get-changed-stories.ts @@ -69,6 +69,7 @@ export async function addGetChangedStoriesTool( server: McpServer, enabled: Parameters['tool']>[0]['enabled'] = () => server.ctx.custom?.toolsets?.dev ?? true, + { reviewEnabled = false }: { reviewEnabled?: boolean } = {}, ) { server.tool( { @@ -181,6 +182,16 @@ export async function addGetChangedStoriesTool( let text = `${banner}Detected ${stories.length} changed stor${stories.length === 1 ? 'y' : 'ies'} (${counts.new} new, ${counts.modified} modified, ${counts.affected} related).`; + // Front-loaded like the banner above: host-side tool-output caps + // can cut the tail of a long story list, and this next-step nudge + // is the product fix that keeps agents from ending visual work at + // preview URLs instead of the review. Only when there are story + // IDs to curate — a zero-result is the moment to fall back to + // get-stories-by-component instead. + if (reviewEnabled && stories.length > 0) { + text += `\n\nNext: if the change is visually observable, publish the review now — call **display-review** curating these story IDs. That review link is how you finish; do not substitute individual preview URLs for it.`; + } + const serializeStory = ({ storyId, title, name, importPath }: ChangedStory) => `- \`${storyId}\`: ${title} / ${name} (\`${importPath}\`)`; diff --git a/packages/addon-mcp/src/tools/get-storybook-story-instructions.test.ts b/packages/addon-mcp/src/tools/get-storybook-story-instructions.test.ts index 02ee94e2..aaf4eae6 100644 --- a/packages/addon-mcp/src/tools/get-storybook-story-instructions.test.ts +++ b/packages/addon-mcp/src/tools/get-storybook-story-instructions.test.ts @@ -261,6 +261,16 @@ describe('getUIBuildingInstructionsTool', () => { expect(instructions).toContain('Never also list the individual story or preview URLs'); // The old contradictory instruction must be gone. expect(instructions).not.toContain('present links in this order'); + + // The story-linking workflow must route discovery into the review, not + // the preview list, and forbid hand-constructed story IDs — matching + // the server instructions that `storybook ai --help` also embeds. + // While this line contradicted them, agents were observed publishing + // reviews with IDs derived from file names and no discovery call. + expect(instructions).toContain('Story IDs must come from that call'); + expect(instructions).toContain('never construct them from file names'); + expect(instructions).toContain('Feed the discovered IDs into **display-review**'); + expect(instructions).not.toContain('first, then use `preview-stories`'); }); it('tells the agent to include preview URLs when review is disabled', async () => { diff --git a/packages/addon-mcp/src/tools/get-storybook-story-instructions.ts b/packages/addon-mcp/src/tools/get-storybook-story-instructions.ts index 480e57c6..826a2187 100644 --- a/packages/addon-mcp/src/tools/get-storybook-story-instructions.ts +++ b/packages/addon-mcp/src/tools/get-storybook-story-instructions.ts @@ -144,8 +144,18 @@ export async function buildStorybookStoryInstructions( const reviewEnabled = reviewStatus.available; const framework = typeof frameworkPreset === 'string' ? frameworkPreset : frameworkPreset?.name; const renderer = frameworkToRendererMap[framework!]; + // Mirrors the review-aware rewrite in build-server-instructions.ts: + // discovery feeds the review, not the preview list. Plugin-path agents do + // see those server instructions (`storybook ai --help` embeds them as its + // "# Storybook workflow instructions" section), but this tool is billed as + // the source of truth for story work and this line still routed discovery + // into previews — a contradiction agents resolved by constructing story + // IDs from file names and publishing reviews with zero discovery calls. + // The two channels must state the same workflow. const storyLinkingWorkflow = changeDetectionEnabled - ? `After changing UI, call \`${GET_CHANGED_STORIES_TOOL_NAME}\` first, then use \`${PREVIEW_STORIES_TOOL_NAME}\` with selected \`storyId\` values from those results.` + ? reviewEnabled + ? `After changing any component or story, call \`${GET_CHANGED_STORIES_TOOL_NAME}\` to discover the new, modified, and related stories affected by your change. Story IDs must come from that call (or a fallback discovery tool such as get-stories-by-component for shared-infrastructure changes) — never construct them from file names, export names, or memory. Feed the discovered IDs into **display-review** when the change is visually observable; use \`${PREVIEW_STORIES_TOOL_NAME}\` only while iterating on a specific story.` + : `After changing UI, call \`${GET_CHANGED_STORIES_TOOL_NAME}\` first, then use \`${PREVIEW_STORIES_TOOL_NAME}\` with selected \`storyId\` values from those results.` : `After changing UI, call \`${PREVIEW_STORIES_TOOL_NAME}\` and share the most relevant links for the changes.`; const changedStoryFallbackLinkGuidance = changeDetectionEnabled ? `When sharing preview/story links (not when ending with a review section): if you did not pass every changed story into \`${PREVIEW_STORIES_TOOL_NAME}\`, include this Storybook fallback link so the user can view the complete changed list: \`/?statuses=affected;modified;new\`.` diff --git a/packages/addon-mcp/src/tools/preview-stories.test.ts b/packages/addon-mcp/src/tools/preview-stories.test.ts index c304e05f..a68087e5 100644 --- a/packages/addon-mcp/src/tools/preview-stories.test.ts +++ b/packages/addon-mcp/src/tools/preview-stories.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { McpServer } from 'tmcp'; import { ValibotJsonSchemaAdapter } from '@tmcp/adapter-valibot'; -import { addPreviewStoriesTool } from './preview-stories.ts'; +import { addPreviewStoriesTool, getPreviewStoriesToolDescription } from './preview-stories.ts'; import type { AddonContext } from '../types.ts'; import smallStoryIndexFixture from '../../fixtures/small-story-index.fixture.json' with { type: 'json' }; import monorepoStoryIndexFixture from '../../fixtures/monorepo-story-index.fixture.json' with { type: 'json' }; @@ -787,6 +787,107 @@ describe('previewStoriesTool', () => { }); }); + describe('review-enabled sessions', () => { + // Registers the tool on a fresh server with the review feature enabled, + // so the display-review recovery nudge paths can be exercised. + async function createReviewEnabledServer() { + const adapter = new ValibotJsonSchemaAdapter(); + const reviewServer = new McpServer( + { + name: 'test-server-review', + version: '1.0.0', + description: 'Test server for preview-stories with review enabled', + }, + { adapter, capabilities: { tools: { listChanged: true } } }, + ).withContext(); + + await reviewServer.receive( + { + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: '2025-06-18', + capabilities: {}, + clientInfo: { name: 'test', version: '1.0.0' }, + }, + }, + { sessionId: 'test-session' }, + ); + + await addPreviewStoriesTool(reviewServer, undefined, { reviewEnabled: true }); + return reviewServer; + } + + async function callToolOn( + targetServer: McpServer, + stories: Array>, + ) { + return targetServer.receive( + { + jsonrpc: '2.0' as const, + id: 1, + method: 'tools/call', + params: { name: PREVIEW_STORIES_TOOL_NAME, arguments: { stories } }, + }, + { sessionId: 'test-session', custom: testContext }, + ); + } + + it('appends the display-review recovery nudge when review is enabled and a URL resolved', async () => { + const response = await callToolOn(await createReviewEnabledServer(), [ + { storyId: 'button--primary' }, + ]); + + const texts = response.result?.content.map((block: { text: string }) => block.text); + expect(texts?.[0]).toBe('http://localhost:6006/?path=/story/button--primary'); + expect(texts?.at(-1)).toContain('publish the review with **display-review**'); + expect(texts?.at(-1)).toContain('available in this session'); + }); + + it('omits the nudge when review is enabled but no story resolved to a URL', async () => { + const response = await callToolOn(await createReviewEnabledServer(), [ + { storyId: 'does-not--exist' }, + ]); + + const texts = response.result?.content.map((block: { text: string }) => block.text); + expect(texts?.join('\n')).not.toContain('display-review'); + }); + + it('omits the nudge and all display-review mentions when review is disabled', async () => { + // The default `server` from beforeEach registers the tool without + // reviewEnabled — display-review is not registered in such sessions, + // so neither the result nor the description may point at it. + const response = await server.receive( + { + jsonrpc: '2.0' as const, + id: 1, + method: 'tools/call', + params: { + name: PREVIEW_STORIES_TOOL_NAME, + arguments: { stories: [{ storyId: 'button--primary' }] }, + }, + }, + { sessionId: 'test-session', custom: testContext }, + ); + + const texts = response.result?.content.map((block: { text: string }) => block.text); + expect(texts?.join('\n')).not.toContain('display-review'); + expect(getPreviewStoriesToolDescription()).not.toContain('display-review'); + }); + + it('frames the tool as mid-loop only in the review-enabled description', () => { + const description = getPreviewStoriesToolDescription({ reviewEnabled: true }); + expect(description).toContain('while iterating on a specific story'); + expect(description).toContain('publish a curated review with display-review'); + expect(description).toContain('changedFiles: []'); + // No "include the URLs in your final response" default and no hedged + // availability clause — both sanctioned preview links as an ending. + expect(description).not.toContain('final user-facing response'); + expect(description).not.toMatch(/and the display-review tool is available/); + }); + }); + describe('Monorepo path resolution', () => { it('should match stories when index.json importPath has no leading ./', async () => { // Simulate monorepo setup where Storybook runs from apps/storybook diff --git a/packages/addon-mcp/src/tools/preview-stories.ts b/packages/addon-mcp/src/tools/preview-stories.ts index 70d68d79..49af1c86 100644 --- a/packages/addon-mcp/src/tools/preview-stories.ts +++ b/packages/addon-mcp/src/tools/preview-stories.ts @@ -13,9 +13,25 @@ import fs from 'node:fs/promises'; import { PREVIEW_STORIES_TOOL_NAME } from './tool-names.ts'; export const PREVIEW_STORIES_RESOURCE_URI = `ui://${PREVIEW_STORIES_TOOL_NAME}/preview.html`; -export const PREVIEW_STORIES_TOOL_DESCRIPTION = `Use this tool to get one or more Storybook preview URLs. -Include each returned preview URL in your final user-facing response so users can open them directly — unless you're also publishing a curated review via display-review, in which case link the review page instead of listing individual URLs. -When the user asked to see or browse existing stories or components (e.g. "show me all the Button variants") and the display-review tool is available, publish a curated review with display-review (passing changedFiles: []) instead of answering with raw preview links; use this tool for verifying your own changes or sharing a specific story on request.`; + +// With review enabled this is strictly a mid-loop tool: no "include the URLs +// in your final response" default (that sanctioned preview links as the +// ending of visual work) and no hedging about display-review's availability +// (a hedged "when available" clause let an agent that wrongly believed the +// review tool was missing treat raw links as a sanctioned fallback). When +// review is disabled the tool is not registered, so the description must not +// mention it at all. +export function getPreviewStoriesToolDescription({ + reviewEnabled = false, +}: { reviewEnabled?: boolean } = {}): string { + if (!reviewEnabled) { + return `Use this tool to get one or more Storybook preview URLs. +Include each returned preview URL in your final user-facing response so users can open them directly.`; + } + + return `Use this tool to get Storybook preview URLs while iterating on a specific story, or when the user asks for a direct link to one. +Do not end visual work or browse requests with these links — publish a curated review with display-review instead (passing changedFiles: [] when no code changed) and link that.`; +} export const PreviewStoriesInput = v.object({ stories: v.pipe( @@ -53,11 +69,13 @@ export const PreviewStoriesOutput = v.object({ export type PreviewStoriesInput = v.InferOutput; export type PreviewStoriesOutput = v.InferOutput; -export function getPreviewStoriesToolMetadata() { +export function getPreviewStoriesToolMetadata({ + reviewEnabled = false, +}: { reviewEnabled?: boolean } = {}) { return { name: PREVIEW_STORIES_TOOL_NAME, title: 'Get story preview URLs', - description: PREVIEW_STORIES_TOOL_DESCRIPTION, + description: getPreviewStoriesToolDescription({ reviewEnabled }), schema: PreviewStoriesInput, outputSchema: PreviewStoriesOutput, _meta: { ui: { resourceUri: PREVIEW_STORIES_RESOURCE_URI } }, @@ -68,6 +86,7 @@ export async function addPreviewStoriesTool( server: McpServer, enabled: Parameters['tool']>[0]['enabled'] = () => server.ctx.custom?.toolsets?.dev ?? true, + { reviewEnabled = false }: { reviewEnabled?: boolean } = {}, ) { const previewStoryAppScript = await fs.readFile( url.fileURLToPath( @@ -113,7 +132,7 @@ export async function addPreviewStoriesTool( server.tool( { - ...getPreviewStoriesToolMetadata(), + ...getPreviewStoriesToolMetadata({ reviewEnabled }), enabled, }, async (input) => { @@ -185,11 +204,27 @@ export async function addPreviewStoriesTool( }); } - return { - content: textResult.map((text) => ({ + const content: Array<{ type: 'text'; text: string }> = textResult.map((text) => ({ + type: 'text', + text, + })); + + // Recovery nudge for the review exit ramp: agents that skip + // display-review (observed: an agent wrongly claimed the tool was + // not exposed) end visual work on exactly this call, so the result + // itself must contradict that belief while there is still a step + // left to recover in. Only when at least one URL resolved — an + // all-error result has nothing to curate into a review. + const resolvedAnyStory = structuredResult.some((story) => 'previewUrl' in story); + if (reviewEnabled && resolvedAnyStory) { + content.push({ type: 'text', - text, - })), + text: `These preview links are for iterating or sharing a specific story — they are not how visual work or a browse request ends. The display-review tool is available in this session: if you are finishing visually observable work or showing a set of stories, publish the review with **display-review** and link that instead.`, + }); + } + + return { + content, structuredContent: { stories: structuredResult, }, diff --git a/packages/addon-mcp/src/tools/tool-registry.ts b/packages/addon-mcp/src/tools/tool-registry.ts index 8173cb6f..046accab 100644 --- a/packages/addon-mcp/src/tools/tool-registry.ts +++ b/packages/addon-mcp/src/tools/tool-registry.ts @@ -98,8 +98,10 @@ const addonToolDefinitions: AddonToolDefinition[] = [ { name: PREVIEW_STORIES_TOOL_NAME, toolset: 'dev', - getMetadata: () => getPreviewStoriesToolMetadata(), - register: (server, _context, enabled) => addPreviewStoriesTool(server, enabled), + getMetadata: ({ availability }) => + getPreviewStoriesToolMetadata({ reviewEnabled: availability.reviewEnabled }), + register: (server, { availability }, enabled) => + addPreviewStoriesTool(server, enabled, { reviewEnabled: availability.reviewEnabled }), }, { name: GET_UI_BUILDING_INSTRUCTIONS_TOOL_NAME, @@ -128,7 +130,8 @@ const addonToolDefinitions: AddonToolDefinition[] = [ toolset: 'dev', available: ({ availability }) => availability.changeDetectionEnabled, getMetadata: () => getChangedStoriesToolMetadata(), - register: (server, _context, enabled) => addGetChangedStoriesTool(server, enabled), + register: (server, { availability }, enabled) => + addGetChangedStoriesTool(server, enabled, { reviewEnabled: availability.reviewEnabled }), }, { name: GET_STORIES_BY_COMPONENT_TOOL_NAME, diff --git a/packages/claude-plugin/skills/stories/SKILL.md b/packages/claude-plugin/skills/stories/SKILL.md index cc780e9c..3e9cddb9 100644 --- a/packages/claude-plugin/skills/stories/SKILL.md +++ b/packages/claude-plugin/skills/stories/SKILL.md @@ -1,6 +1,6 @@ --- name: stories -description: Invoke FIRST, before any frontend component change — create, edit, or delete, no exceptions. Also for adding or updating stories (*.stories.* files), covering components with stories, starting or previewing Storybook to verify UI, and read-only asks to show, browse, or list components, stories, or UI states, or look up docs, props, or usage. +description: Invoke FIRST, before creating, editing, or deleting components, stories, styles, CSS, themes, colors, or design tokens — anything that changes how the UI looks, no exceptions. Also for starting or previewing Storybook to verify UI, requests to show, browse, or list components, stories, or UI states, and docs, props, or usage lookups. --- Prerequisites: diff --git a/packages/codex-plugin/plugins/storybook/skills/stories/SKILL.md b/packages/codex-plugin/plugins/storybook/skills/stories/SKILL.md index 27527965..664f9f71 100644 --- a/packages/codex-plugin/plugins/storybook/skills/stories/SKILL.md +++ b/packages/codex-plugin/plugins/storybook/skills/stories/SKILL.md @@ -1,6 +1,6 @@ --- name: stories -description: Invoke FIRST, before any frontend component change — create, edit, or delete, no exceptions. Also for adding or updating stories (*.stories.* files), covering components with stories, starting or previewing Storybook to verify UI, and read-only asks to show, browse, or list components, stories, or UI states, or look up docs, props, or usage. +description: Invoke FIRST, before creating, editing, or deleting components, stories, styles, CSS, themes, colors, or design tokens — anything that changes how the UI looks, no exceptions. Also for starting or previewing Storybook to verify UI, requests to show, browse, or list components, stories, or UI states, and docs, props, or usage lookups. --- Prerequisites: