diff --git a/CHANGELOG.md b/CHANGELOG.md
index 032cec07a..0cc8d81c5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,8 @@
All notable changes to this project will be documented in this file, per [the Keep a Changelog standard](http://keepachangelog.com/), and will adhere to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased] - TBD
+### Changed
+- Move Excerpt Generation into its own document sidebar panel instead of injecting buttons into the core excerpt field ([#1139](https://github.com/WordPress/ai/pull/1139)).
## [1.4.0] - 2026-10-05
### Added
diff --git a/docs/experiments/excerpt-generation.md b/docs/experiments/excerpt-generation.md
index 23be8fb1d..fe567827e 100644
--- a/docs/experiments/excerpt-generation.md
+++ b/docs/experiments/excerpt-generation.md
@@ -2,21 +2,30 @@
## Summary
-The Excerpt Generation experiment adds AI-powered excerpt generation to the WordPress post editor. It provides a "Generate excerpt" button in the excerpt panel that uses AI to create concise, engaging summaries of post content. The experiment registers a WordPress Ability (`ai/excerpt-generation`) that can be used both through the admin UI and directly via REST API requests.
+The Excerpt Generation experiment adds AI-powered excerpt generation to the WordPress post editor. It provides an "Excerpt generation" sidebar panel with a modal workflow for generating, editing, and applying excerpts. The experiment registers a WordPress Ability (`ai/excerpt-generation`) that can be used both through the admin UI and directly via REST API requests.
## Overview
### For End Users
-When enabled, the Excerpt Generation experiment adds a "Generate excerpt" button to the excerpt panel in the WordPress post editor. Users can click this button to automatically generate an excerpt suggestion based on the current post content. The generated excerpt is approximately 55 words, optimized for clarity, engagement, and SEO, and suitable for archive views, RSS feeds, and search results.
+When enabled, the Excerpt Generation experiment adds an "Excerpt generation" panel to the document sidebar of the WordPress post editor. Users can click its "Generate excerpt" button to open a modal that generates an excerpt from the post content, review or edit the suggestion, and apply it to the post. The generated excerpt is approximately 55 words, optimized for clarity, engagement, and SEO, and suitable for archive views, RSS feeds, and search results.
**Key Features:**
-- One-click excerpt generation from post content
-- Automatically populates the excerpt field in the editor
+- Generates an excerpt suggestion of roughly 55 words from the post content
+- Editable textarea allows fine-tuning the suggestion before applying
+- Copy to clipboard functionality for use outside the excerpt field
- Works with any post type that supports excerpts
-- Generates excerpts optimized for SEO and readability
-- Can regenerate excerpts if you want a different suggestion
+- Can regenerate if you want a different suggestion
+
+**Workflow:**
+
+1. Open or create a post in the editor
+2. Find the "Excerpt generation" panel in the sidebar
+3. Click "Generate excerpt" to open the modal
+4. Review the AI-generated suggestion in the textarea and edit as needed
+5. Click "Apply" to set it as the post's excerpt
+6. Save/update the post as usual
### For Developers
@@ -42,12 +51,12 @@ The ability can be called directly via REST API, making it useful for automation
- `enabled`: Whether the experiment is enabled
2. **React Side:**
- - The React entry point (`index.tsx`) registers a WordPress plugin that hooks into the excerpt panel using `__experimentalPluginPostExcerpt`
- - `ExcerptGeneration` component renders a button that calls `useExcerptGeneration()` hook
+ - The React entry point (`index.tsx`) registers a `PluginDocumentSettingPanel` named `ai-excerpt-generation`, hidden when the core Excerpt panel is disabled
+ - `ExcerptGenerationPanel` renders the generate button; clicking it opens `ExcerptGenerationModal`, which shows the suggestion in an editable textarea with Apply, Regenerate, Copy and Cancel actions
- `useExcerptGeneration` hook:
- Gets current post ID and content from the editor store
- - Calls the ability via `apiFetch` when the button is clicked
- - Updates the editor store and DOM textarea with the generated excerpt
+ - Calls the ability when the modal opens or Regenerate is clicked
+ - Updates the editor store with the excerpt when it is applied
- Handles loading states and error notifications
3. **Ability Execution:**
@@ -303,14 +312,14 @@ When a post ID is provided, the ability uses `get_post_context()` to gather post
You can extend the React components to add custom UI elements:
1. **Modify the button component:**
- - Edit `src/experiments/excerpt-generation/components/ExcerptGeneration.tsx`
+ - Edit `src/experiments/excerpt-generation/components/ExcerptGenerationPanel.tsx` or `ExcerptGenerationModal.tsx`
2. **Add custom hooks:**
- Create new hooks in `src/experiments/excerpt-generation/components/`
- Import and use them in the main component
-3. **Customize the excerpt panel:**
- - The experiment uses `__experimentalPluginPostExcerpt` to inject into the excerpt panel
+3. **Customize the sidebar panel:**
+ - The experiment uses `PluginDocumentSettingPanel` to render the panel
- You can modify `src/experiments/excerpt-generation/index.tsx` to add additional UI
## Testing
@@ -324,10 +333,12 @@ You can extend the React components to add custom UI elements:
2. **Test in the editor:**
- Create or edit a post with content
- - Scroll to the excerpt panel (or enable it in Screen Options)
- - Click the "Generate excerpt" button
- - Verify the excerpt is generated and populated in the field
+ - Open the "Excerpt generation" panel in the document sidebar
+ - Click "Generate excerpt" to open the modal
+ - Verify the suggestion populates the textarea, edit it if needed, and click "Apply"
+ - Verify the post's excerpt field is updated
- Click "Regenerate excerpt" to test regeneration
+ - Test "Copy to clipboard" and verify the text is copied
3. **Test with different post types:**
- The experiment only loads for post types that support excerpts
diff --git a/includes/Experiments/Excerpt_Generation/Excerpt_Generation.php b/includes/Experiments/Excerpt_Generation/Excerpt_Generation.php
index a5af2f77e..3a7bb26b7 100644
--- a/includes/Experiments/Excerpt_Generation/Excerpt_Generation.php
+++ b/includes/Experiments/Excerpt_Generation/Excerpt_Generation.php
@@ -94,6 +94,7 @@ public function enqueue_assets( string $hook_suffix ): void {
}
Asset_Loader::enqueue_script( 'excerpt_generation', 'experiments/excerpt-generation', array( 'include_core_abilities' => true ) );
+ Asset_Loader::enqueue_style( 'excerpt_generation', 'experiments/excerpt-generation' );
Asset_Loader::localize_script(
'excerpt_generation',
'ExcerptGenerationData',
diff --git a/src/experiments/excerpt-generation/components/ExcerptGeneration.tsx b/src/experiments/excerpt-generation/components/ExcerptGeneration.tsx
deleted file mode 100644
index 05315bf5e..000000000
--- a/src/experiments/excerpt-generation/components/ExcerptGeneration.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-/**
- * Excerpt generator component for the excerpt panel.
- */
-
-/**
- * WordPress dependencies
- */
-import { Button, Notice } from '@wordpress/components';
-import { update } from '@wordpress/icons';
-import { __ } from '@wordpress/i18n';
-import { Stack } from '@wordpress/ui';
-
-/**
- * Internal dependencies
- */
-import { useExcerptGeneration } from './useExcerptGeneration';
-
-const { aiExcerptGenerationData } = window as any;
-
-/**
- * ExcerptGeneration component.
- *
- * Provides a button to generate an excerpt.
- *
- * @return {React.JSX.Element | null} The excerpt generation component.
- */
-export default function ExcerptGeneration(): React.JSX.Element | null {
- const {
- isGenerating,
- hasExcerpt,
- isContentTooShort,
- tooShortLabel,
- handleGenerate,
- } = useExcerptGeneration();
-
- // Don't render if disabled.
- if ( ! aiExcerptGenerationData?.enabled ) {
- return null;
- }
-
- let buttonLabel: string = __( 'Generate excerpt', 'ai' );
-
- if ( isGenerating ) {
- buttonLabel = __( 'Generating…', 'ai' );
- } else if ( hasExcerpt ) {
- buttonLabel = __( 'Regenerate excerpt', 'ai' );
- }
-
- return (
-
- { isContentTooShort && (
-
- { tooShortLabel }
-
- ) }
-
-
- { buttonLabel }
-
-
- );
-}
diff --git a/src/experiments/excerpt-generation/components/ExcerptGenerationModal.tsx b/src/experiments/excerpt-generation/components/ExcerptGenerationModal.tsx
new file mode 100644
index 000000000..45b0c9d50
--- /dev/null
+++ b/src/experiments/excerpt-generation/components/ExcerptGenerationModal.tsx
@@ -0,0 +1,176 @@
+/**
+ * Modal component for generating and editing an excerpt suggestion.
+ */
+
+/**
+ * WordPress dependencies
+ */
+import { useEffect } from '@wordpress/element';
+import { __ } from '@wordpress/i18n';
+import { Modal, Button, TextareaControl, Notice } from '@wordpress/components';
+
+/**
+ * Internal dependencies
+ */
+import { useCopyToClipboardFeedback } from '../../../hooks/use-copy-to-clipboard-feedback';
+
+interface ExcerptGenerationModalProps {
+ isGenerating: boolean;
+ suggestion: string | null;
+ editableText: string;
+ isContentTooShort: boolean;
+ tooShortLabel: string;
+ onEditableTextChange: ( text: string ) => void;
+ onGenerate: () => Promise< void >;
+ onApply: ( text: string ) => void;
+ onClose: () => void;
+}
+
+function CopyButton( {
+ text,
+ disabled,
+}: {
+ text: string;
+ disabled: boolean;
+} ): JSX.Element {
+ const { ref, hasCopied } = useCopyToClipboardFeedback< HTMLButtonElement >(
+ {
+ text,
+ announcement: __( 'Excerpt copied to clipboard.', 'ai' ),
+ }
+ );
+
+ const isCopyDisabled = disabled || hasCopied;
+
+ return (
+
+ { hasCopied
+ ? __( 'Copied!', 'ai' )
+ : __( 'Copy to clipboard', 'ai' ) }
+
+ );
+}
+
+/**
+ * Modal for generating and editing an excerpt.
+ *
+ * @param props Component props.
+ * @param props.isGenerating Whether generation is in progress.
+ * @param props.suggestion The generated suggestion.
+ * @param props.editableText The current editable text value.
+ * @param props.isContentTooShort Whether the content is too short to generate a suggestion.
+ * @param props.tooShortLabel Label to show when content is too short.
+ * @param props.onEditableTextChange Callback to update the editable text.
+ * @param props.onGenerate Callback to trigger generation.
+ * @param props.onApply Callback to apply the excerpt.
+ * @param props.onClose Callback to close the modal.
+ */
+export default function ExcerptGenerationModal( {
+ isGenerating,
+ suggestion,
+ editableText,
+ isContentTooShort,
+ tooShortLabel,
+ onEditableTextChange,
+ onGenerate,
+ onApply,
+ onClose,
+}: ExcerptGenerationModalProps ): React.JSX.Element {
+ // Populate the textarea when a new suggestion arrives.
+ useEffect( () => {
+ if ( suggestion ) {
+ onEditableTextChange( suggestion );
+ }
+ }, [ suggestion, onEditableTextChange ] );
+
+ let generateButtonLabel: string = suggestion
+ ? __( 'Regenerate', 'ai' )
+ : __( 'Generate', 'ai' );
+
+ if ( isGenerating ) {
+ generateButtonLabel = __( 'Generating…', 'ai' );
+ }
+
+ return (
+
+
+ { isContentTooShort && (
+
+ { tooShortLabel }
+
+ ) }
+
+
+
+
+ {
+ onApply( editableText );
+ onClose();
+ } }
+ accessibleWhenDisabled
+ disabled={
+ isGenerating ||
+ ( !! editableText &&
+ editableText.trim().length === 0 )
+ }
+ __next40pxDefaultSize
+ >
+ { __( 'Apply', 'ai' ) }
+
+
+ { generateButtonLabel }
+
+
+
+ { __( 'Cancel', 'ai' ) }
+
+
+
+
+ );
+}
diff --git a/src/experiments/excerpt-generation/components/ExcerptGenerationPanel.tsx b/src/experiments/excerpt-generation/components/ExcerptGenerationPanel.tsx
new file mode 100644
index 000000000..bf2b6a97f
--- /dev/null
+++ b/src/experiments/excerpt-generation/components/ExcerptGenerationPanel.tsx
@@ -0,0 +1,102 @@
+/**
+ * Sidebar panel component for the excerpt generation experiment.
+ */
+
+/**
+ * WordPress dependencies
+ */
+import { useState } from '@wordpress/element';
+import { __ } from '@wordpress/i18n';
+import { Button } from '@wordpress/components';
+
+/**
+ * Internal dependencies
+ */
+import { useExcerptGeneration } from './useExcerptGeneration';
+import ExcerptGenerationModal from './ExcerptGenerationModal';
+
+/**
+ * Panel with the generate button. Generation happens in a modal where the
+ * suggestion can be reviewed and edited before it is applied to the post.
+ */
+export default function ExcerptGenerationPanel(): React.JSX.Element {
+ const {
+ isGenerating,
+ suggestion,
+ currentExcerpt,
+ isContentTooShort,
+ tooShortLabel,
+ ensureProviderAvailable,
+ generateExcerpt,
+ cancelGeneration,
+ applyExcerpt,
+ clearSuggestion,
+ } = useExcerptGeneration();
+
+ const [ isModalOpen, setIsModalOpen ] = useState( false );
+ const [ editableText, setEditableText ] = useState( '' );
+
+ const hasExcerpt = currentExcerpt.trim().length > 0;
+
+ let buttonLabel: string = hasExcerpt
+ ? __( 'Regenerate excerpt', 'ai' )
+ : __( 'Generate excerpt', 'ai' );
+
+ if ( isGenerating ) {
+ buttonLabel = __( 'Generating…', 'ai' );
+ }
+
+ const handleOpenModal = async () => {
+ if ( ! ensureProviderAvailable() ) {
+ return;
+ }
+
+ setEditableText( currentExcerpt );
+ setIsModalOpen( true );
+ await generateExcerpt();
+ };
+
+ return (
+
+
+ { buttonLabel }
+
+
+ { isContentTooShort && (
+
+ { tooShortLabel }
+
+ ) }
+
+ { isModalOpen && (
+
{
+ cancelGeneration();
+ clearSuggestion();
+ setIsModalOpen( false );
+ } }
+ />
+ ) }
+
+ );
+}
diff --git a/src/experiments/excerpt-generation/components/ExcerptInlineButton.tsx b/src/experiments/excerpt-generation/components/ExcerptInlineButton.tsx
deleted file mode 100644
index 5f2c81ffe..000000000
--- a/src/experiments/excerpt-generation/components/ExcerptInlineButton.tsx
+++ /dev/null
@@ -1,60 +0,0 @@
-/**
- * Inline button component for the excerpt link area.
- */
-
-/**
- * WordPress dependencies
- */
-import { Button } from '@wordpress/components';
-import { update } from '@wordpress/icons';
-import { __ } from '@wordpress/i18n';
-
-/**
- * Internal dependencies
- */
-import { useExcerptGeneration } from './useExcerptGeneration';
-
-const { aiExcerptGenerationData } = window as any;
-
-/**
- * Inline button component for generating excerpts next to the excerpt link.
- *
- * @return {React.JSX.Element | null} The inline button component.
- */
-export default function ExcerptInlineButton(): React.JSX.Element | null {
- const {
- isGenerating,
- hasExcerpt,
- isContentTooShort,
- tooShortLabel,
- handleGenerate,
- } = useExcerptGeneration();
-
- // Don't render if disabled.
- if ( ! aiExcerptGenerationData?.enabled ) {
- return null;
- }
-
- let buttonLabel: string = __( 'Generate excerpt', 'ai' );
-
- if ( isGenerating ) {
- buttonLabel = __( 'Generating…', 'ai' );
- } else if ( hasExcerpt ) {
- buttonLabel = __( 'Regenerate excerpt', 'ai' );
- }
-
- return (
-
- );
-}
diff --git a/src/experiments/excerpt-generation/components/ExcerptInlineWrapper.tsx b/src/experiments/excerpt-generation/components/ExcerptInlineWrapper.tsx
deleted file mode 100644
index 01b1470bf..000000000
--- a/src/experiments/excerpt-generation/components/ExcerptInlineWrapper.tsx
+++ /dev/null
@@ -1,157 +0,0 @@
-/**
- * Wrapper component that injects content next to the excerpt link.
- */
-
-/**
- * WordPress dependencies
- */
-import { createRoot, useEffect } from '@wordpress/element';
-
-/**
- * Internal dependencies
- */
-import ExcerptInlineButton from './ExcerptInlineButton';
-
-/**
- * Creates a retry function that will attempt to execute a callback when a condition is met.
- *
- * @param {Function} checkFn Function that returns true when condition is met.
- * @param {Function} callback Function to execute when condition is met.
- * @param {number} maxRetries Maximum number of retry attempts.
- * @param {number} delay Delay in milliseconds between retries.
- * @return {Function} A function that starts the retry process.
- */
-function createRetry(
- checkFn: () => boolean,
- callback: () => void,
- maxRetries: number,
- delay: number = 200
-): () => void {
- let retryCount = 0;
- let timeoutId: NodeJS.Timeout | null = null;
-
- const retry = () => {
- if ( retryCount < maxRetries ) {
- retryCount++;
- timeoutId = setTimeout( () => {
- timeoutId = null;
- if ( checkFn() ) {
- callback();
- } else {
- retry();
- }
- }, delay );
- }
- };
-
- const start = () => {
- if ( ! timeoutId ) {
- retry();
- }
- };
-
- return start;
-}
-
-/**
- * ExcerptInlineWrapper component.
- *
- * Injects a generate button next to the excerpt link in the sidebar.
- *
- * @return {React.JSX.Element} The wrapper component.
- */
-export default function ExcerptInlineWrapper(): React.JSX.Element {
- useEffect( () => {
- let isAttached = false;
- let root: ReturnType< typeof createRoot > | null = null;
- let container: HTMLElement | null = null;
- let observer: MutationObserver | null = null;
-
- const findAndAttachButton = () => {
- // Don't try if already attached.
- if ( isAttached ) {
- return;
- }
-
- // Find the excerpt dropdown button.
- const excerptDropdown = document.querySelector(
- '.editor-post-excerpt__dropdown button[class*="components-button"]'
- ) as HTMLElement | null;
-
- if ( ! excerptDropdown ) {
- // Button not found yet, retry.
- const retryExcerpt = createRetry(
- () => {
- return !! document.querySelector(
- '.editor-post-excerpt__dropdown button[class*="components-button"]'
- );
- },
- findAndAttachButton,
- 20
- );
- retryExcerpt();
- return;
- }
-
- // Check if we've already attached the button.
- if (
- excerptDropdown.parentElement?.querySelector(
- '.ai-excerpt-inline-wrapper'
- )
- ) {
- isAttached = true;
- return;
- }
-
- // Create a container for our button.
- container = document.createElement( 'span' );
- container.className = 'ai-excerpt-inline-wrapper';
- container.style.cssText = 'float: inline-end;';
-
- // Insert the container right after the button.
- excerptDropdown.parentElement?.insertBefore(
- container,
- excerptDropdown.nextSibling
- );
-
- // Render the button into the container.
- root = createRoot( container );
- root.render( );
-
- isAttached = true;
-
- // Watch for DOM changes in case the excerpt section is re-rendered.
- observer = new MutationObserver( () => {
- if (
- ! document.querySelector( '.ai-excerpt-inline-wrapper' )
- ) {
- isAttached = false;
- findAndAttachButton();
- }
- } );
-
- observer.observe( document.body, {
- childList: true,
- subtree: true,
- } );
- };
-
- // Start looking for the excerpt button after a short delay.
- const timeoutId = setTimeout( findAndAttachButton, 500 );
-
- return () => {
- clearTimeout( timeoutId );
- if ( root ) {
- root.unmount();
- }
- if ( container ) {
- container.remove();
- }
- if ( observer ) {
- observer.disconnect();
- }
- };
- }, [] );
-
- return <>>;
-}
diff --git a/src/experiments/excerpt-generation/components/useExcerptGeneration.ts b/src/experiments/excerpt-generation/components/useExcerptGeneration.ts
index 2902b2e92..30124d68d 100644
--- a/src/experiments/excerpt-generation/components/useExcerptGeneration.ts
+++ b/src/experiments/excerpt-generation/components/useExcerptGeneration.ts
@@ -1,5 +1,5 @@
/**
- * Shared hook for excerpt generation logic.
+ * Hook for excerpt generation logic.
*/
/**
@@ -7,7 +7,7 @@
*/
import { dispatch, useDispatch, useSelect } from '@wordpress/data';
import { store as editorStore } from '@wordpress/editor';
-import { useSyncExternalStore } from '@wordpress/element';
+import { useState, useCallback, useRef, useEffect } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { store as noticesStore } from '@wordpress/notices';
@@ -25,25 +25,6 @@ import type {
const NOTICE_ID = 'ai_excerpt_generation_error';
const MINIMUM_CONTENT_COUNT_DEFAULT = 250;
-let globalIsGenerating = false;
-const listeners = new Set< () => void >();
-
-function subscribe( callback: () => void ): () => void {
- listeners.add( callback );
- return () => {
- listeners.delete( callback );
- };
-}
-
-function getSnapshot(): boolean {
- return globalIsGenerating;
-}
-
-function setGlobalIsGenerating( isGenerating: boolean ): void {
- globalIsGenerating = isGenerating;
- listeners.forEach( ( listener ) => listener() );
-}
-
const getSettings = (): ExcerptGenerationData => {
const settings = ( window as any ).aiExcerptGenerationData ?? {};
@@ -54,56 +35,51 @@ const getSettings = (): ExcerptGenerationData => {
};
};
-/**
- * Generates an excerpt for the given post ID and content.
- *
- * @param postId The ID of the post to generate an excerpt for.
- * @param content The content of the post to generate an excerpt for.
- * @return A promise that resolves to the generated excerpt.
- */
-async function generateExcerpt(
- postId: number,
- content: string
-): Promise< string > {
- const params: ExcerptGenerationAbilityInput = {
- content,
- context: postId.toString(),
- };
-
- return runAbility< string >( 'ai/excerpt-generation', params )
- .then( ( response ) => {
- if ( response && typeof response === 'string' ) {
- return response;
- }
- return '';
- } )
- .catch( ( error ) => {
- throw new Error( error.message );
- } );
+interface UseExcerptGenerationReturn {
+ isGenerating: boolean;
+ suggestion: string | null;
+ currentExcerpt: string;
+ isContentTooShort: boolean;
+ tooShortLabel: string;
+ ensureProviderAvailable: () => boolean;
+ generateExcerpt: () => Promise< void >;
+ cancelGeneration: () => void;
+ applyExcerpt: ( text: string ) => void;
+ clearSuggestion: () => void;
}
/**
- * Hook for excerpt generation functionality.
+ * Hook providing excerpt generation state and actions.
*
- * @return Object with generation state and handler.
+ * @return Object with generation state, suggestion, and handlers.
*/
-export function useExcerptGeneration(): {
- isGenerating: boolean;
- hasExcerpt: boolean;
- isContentTooShort: boolean;
- minContentLength: number;
- tooShortLabel: string;
- handleGenerate: () => Promise< void >;
-} {
- const { postId, content, excerpt } = useSelect( ( select ) => {
+export function useExcerptGeneration(): UseExcerptGenerationReturn {
+ const { editPost } = useDispatch( editorStore );
+ const { removeNotice, createErrorNotice } = dispatch( noticesStore );
+
+ const [ isGenerating, setIsGenerating ] = useState( false );
+ const [ suggestion, setSuggestion ] = useState< string | null >( null );
+
+ const abortControllerRef = useRef< AbortController | null >( null );
+ const requestIdRef = useRef( 0 );
+
+ const ensureProviderAvailable = useCallback(
+ () => ensureProvider( NOTICE_ID ),
+ []
+ );
+
+ const { postId, content, currentExcerpt } = useSelect( ( select ) => {
+ const editor = select( editorStore );
+
return {
- postId: select( editorStore ).getCurrentPostId(),
- content: select( editorStore ).getEditedPostContent(),
- excerpt: select( editorStore ).getEditedPostAttribute( 'excerpt' ),
+ postId: editor.getCurrentPostId() as number,
+ content: editor.getEditedPostContent(),
+ currentExcerpt:
+ ( editor.getEditedPostAttribute( 'excerpt' ) as
+ | string
+ | undefined ) ?? '',
};
- } );
- const { editPost } = useDispatch( editorStore );
- const isGenerating = useSyncExternalStore( subscribe, getSnapshot );
+ }, [] );
const { minContentLength } = getSettings();
const isContentTooShort = ! hasMinimumContent( content, minContentLength );
@@ -119,78 +95,117 @@ export function useExcerptGeneration(): {
minContentLength
);
- const handleGenerate = async () => {
- if ( globalIsGenerating ) {
+ const cancelGeneration = useCallback( () => {
+ if ( ! abortControllerRef.current ) {
return;
}
+ requestIdRef.current += 1;
+ abortControllerRef.current.abort();
+ abortControllerRef.current = null;
+ setIsGenerating( false );
+ }, [] );
+
+ const generateExcerpt = useCallback( async () => {
if ( ! ensureProvider( NOTICE_ID ) ) {
return;
}
- setGlobalIsGenerating( true );
- dispatch( noticesStore ).removeNotice( NOTICE_ID );
+ if ( abortControllerRef.current ) {
+ abortControllerRef.current.abort();
+ }
+
+ const controller = new AbortController();
+ abortControllerRef.current = controller;
+ const currentRequestId = ++requestIdRef.current;
+
+ setIsGenerating( true );
+ setSuggestion( null );
+
+ // Clear any existing notices.
+ removeNotice( NOTICE_ID );
try {
- const generatedExcerpt = await generateExcerpt(
- postId as number,
- content
+ const params: ExcerptGenerationAbilityInput = {
+ content,
+ context: postId.toString(),
+ };
+
+ const response = await runAbility< string >(
+ 'ai/excerpt-generation',
+ params,
+ { signal: controller.signal }
);
- // Update the editor store first.
- editPost( {
- excerpt: generatedExcerpt,
- } );
+ if ( currentRequestId !== requestIdRef.current ) {
+ return;
+ }
- // Find the textarea element and update it.
- const excerptInput = document.querySelector(
- '.editor-post-excerpt .editor-post-excerpt__textarea textarea'
- ) as HTMLTextAreaElement | null;
-
- if ( excerptInput ) {
- const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
- window.HTMLTextAreaElement.prototype,
- 'value'
- )?.set;
-
- if ( nativeInputValueSetter ) {
- nativeInputValueSetter.call(
- excerptInput,
- generatedExcerpt
- );
- } else {
- excerptInput.value = generatedExcerpt;
- }
-
- excerptInput.focus();
-
- const changeEvent = new Event( 'change', {
- bubbles: true,
- cancelable: true,
+ if ( typeof response === 'string' && response.trim().length > 0 ) {
+ setSuggestion( response );
+ } else {
+ createErrorNotice( __( 'No excerpt was generated.', 'ai' ), {
+ id: NOTICE_ID,
+ isDismissible: true,
} );
- excerptInput.dispatchEvent( changeEvent );
}
} catch ( error: any ) {
+ if ( currentRequestId !== requestIdRef.current ) {
+ return;
+ }
+
const message =
typeof error === 'string'
? error
: error?.message ??
__( 'Failed to generate excerpt.', 'ai' );
- dispatch( noticesStore ).createErrorNotice( message, {
+
+ createErrorNotice( message, {
id: NOTICE_ID,
isDismissible: true,
} );
} finally {
- setGlobalIsGenerating( false );
+ if ( abortControllerRef.current === controller ) {
+ abortControllerRef.current = null;
+ }
+
+ if ( currentRequestId === requestIdRef.current ) {
+ setIsGenerating( false );
+ }
}
- };
+ }, [ content, postId, removeNotice, createErrorNotice ] );
+
+ useEffect( () => {
+ return () => {
+ requestIdRef.current += 1;
+ if ( abortControllerRef.current ) {
+ abortControllerRef.current.abort();
+ abortControllerRef.current = null;
+ }
+ };
+ }, [] );
+
+ const applyExcerpt = useCallback(
+ ( text: string ) => {
+ editPost( { excerpt: text } );
+ },
+ [ editPost ]
+ );
+
+ const clearSuggestion = useCallback( () => {
+ setSuggestion( null );
+ }, [] );
return {
isGenerating,
- hasExcerpt: excerpt && excerpt.trim().length > 0,
+ suggestion,
+ currentExcerpt,
isContentTooShort,
- minContentLength,
tooShortLabel,
- handleGenerate,
+ ensureProviderAvailable,
+ generateExcerpt,
+ cancelGeneration,
+ applyExcerpt,
+ clearSuggestion,
};
}
diff --git a/src/experiments/excerpt-generation/index.scss b/src/experiments/excerpt-generation/index.scss
new file mode 100644
index 000000000..a4de827b0
--- /dev/null
+++ b/src/experiments/excerpt-generation/index.scss
@@ -0,0 +1,32 @@
+/**
+ * Styles for the Excerpt Generation experiment.
+ */
+
+// Panel.
+.ai-excerpt-generation-panel {
+ &__generate-button {
+ width: 100%;
+ justify-content: center;
+ }
+}
+
+// Modal layout.
+.ai-excerpt-generation-modal {
+ &__content {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ }
+
+ &__actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding-top: 8px;
+ border-top: 1px solid var(--wp-admin-border-color-lighter, #dcdcde);
+ }
+
+ &__cancel {
+ margin-left: auto;
+ }
+}
diff --git a/src/experiments/excerpt-generation/index.tsx b/src/experiments/excerpt-generation/index.tsx
index a37406daf..cff3d4c0d 100644
--- a/src/experiments/excerpt-generation/index.tsx
+++ b/src/experiments/excerpt-generation/index.tsx
@@ -2,55 +2,53 @@
* Excerpt generation plugin registration.
*/
-/**
- * External dependencies
- */
-import React from 'react';
-
/**
* WordPress dependencies
*/
-// @ts-expect-error - __experimentalPluginPostExcerpt is not in type definitions but exists at runtime
-import { __experimentalPluginPostExcerpt as PluginPostExcerpt } from '@wordpress/edit-post'; // eslint-disable-line @wordpress/no-unsafe-wp-apis
+import { useSelect } from '@wordpress/data';
+import {
+ PluginDocumentSettingPanel,
+ store as editorStore,
+} from '@wordpress/editor';
+import { __ } from '@wordpress/i18n';
import { registerPlugin } from '@wordpress/plugins';
/**
* Internal dependencies
*/
-import ExcerptGeneration from './components/ExcerptGeneration';
-import ExcerptInlineWrapper from './components/ExcerptInlineWrapper';
+import ExcerptGenerationPanel from './components/ExcerptGenerationPanel';
+import './index.scss';
/**
- * Plugin component that adds a generate button to the excerpt panel.
+ * Plugin component that renders the Excerpt generation panel in the editor
+ * sidebar, right below the post summary.
+ *
+ * The panel follows core's Excerpt panel preference: when that panel is
+ * turned off in Preferences the generated excerpt would not be visible
+ * anywhere in the sidebar, so this panel is hidden as well.
*/
const ExcerptGenerationPlugin = (): React.JSX.Element | null => {
- // __experimentalPluginPostExcerpt from @wordpress/edit-post is a function
- // that returns the component (or null in site editor)
- const PluginExcerptComponent = PluginPostExcerpt();
+ const isExcerptPanelEnabled = useSelect(
+ ( select ) =>
+ select( editorStore ).isEditorPanelEnabled( 'post-excerpt' ),
+ []
+ );
- // If we're in the site editor, the function returns null
- if ( ! PluginExcerptComponent ) {
+ if ( ! isExcerptPanelEnabled ) {
return null;
}
- const PluginExcerpt = PluginExcerptComponent as React.ComponentType< {
- children: React.ReactNode;
- className?: string;
- } >;
-
return (
-
-
-
+
+
+
);
};
-// Register plugin for the form area (after the textarea)
registerPlugin( 'excerpt-generation', {
render: ExcerptGenerationPlugin,
} );
-
-// Register plugin for the inline button (next to the excerpt link)
-registerPlugin( 'excerpt-generation-inline', {
- render: ExcerptInlineWrapper,
-} );
diff --git a/tests/e2e/specs/experiments/excerpt-generation.spec.js b/tests/e2e/specs/experiments/excerpt-generation.spec.js
index cf6862d69..80a368f5e 100644
--- a/tests/e2e/specs/experiments/excerpt-generation.spec.js
+++ b/tests/e2e/specs/experiments/excerpt-generation.spec.js
@@ -15,6 +15,63 @@ const {
const LONG_CONTENT =
'Artificial intelligence is rapidly changing how content is created, edited, and published across the web today. Writers increasingly rely on automated tools to draft outlines, summarize research, and suggest improvements to their work. These systems analyze large amounts of text and surface patterns that would take a human many hours to find on their own. As the technology matures, editors are learning to combine their own judgment with machine generated suggestions to produce stronger results. This paragraph exists only to provide enough characters for the excerpt generation experiment to run, because the feature now requires a reasonable amount of content before it will offer to generate a brand new excerpt for the post.';
+// The default mock response text from responses.json / completions.json.
+const MOCK_EXCERPT =
+ 'Edit or Delete Your First WordPress Post to Begin Your Blogging Adventure';
+
+// The sidebar panel registered via PluginDocumentSettingPanel.
+const PANEL_SELECTOR = '.ai-excerpt-generation-panel';
+
+// The modal opened from the panel button.
+const MODAL_SELECTOR = '.ai-excerpt-generation-modal';
+
+/**
+ * Opens the Post sidebar and expands the Excerpt generation panel.
+ *
+ * The panel is a PluginDocumentSettingPanel which renders as a collapsible
+ * panel in the document sidebar. This helper ensures the sidebar is on the
+ * Post tab and the panel is expanded before interacting.
+ *
+ * @param {Object} editor The editor fixture.
+ * @param {Object} page The page object.
+ */
+async function openExcerptGenerationPanel( editor, page ) {
+ await editor.openDocumentSettingsSidebar();
+
+ // Switch to the Post tab if the Block tab is active.
+ const postTab = page.getByRole( 'tab', { name: 'Post' } );
+ if ( ( await postTab.count() ) > 0 ) {
+ await postTab.click();
+ }
+
+ // Expand the panel if it is collapsed.
+ const panelToggle = page.getByRole( 'button', {
+ name: 'Excerpt generation',
+ exact: true,
+ } );
+
+ if ( ( await panelToggle.count() ) > 0 ) {
+ const isExpanded = await panelToggle.getAttribute( 'aria-expanded' );
+ if ( isExpanded === 'false' ) {
+ await panelToggle.click();
+ }
+ }
+}
+
+/**
+ * Reads the post's current excerpt from the editor store.
+ *
+ * @param {Object} page The page object.
+ * @return {Promise} The edited excerpt.
+ */
+function getStoredExcerpt( page ) {
+ return page.evaluate( () =>
+ window.wp.data
+ .select( 'core/editor' )
+ .getEditedPostAttribute( 'excerpt' )
+ );
+}
+
test.describe( 'Excerpt Generation Experiment', () => {
test( 'Can enable the excerpt generation experiment', async ( {
admin,
@@ -24,7 +81,7 @@ test.describe( 'Excerpt Generation Experiment', () => {
await enableExperiment( admin, page, 'Excerpt Generation' );
} );
- test( 'Can use the Excerpt Generation Experiment', async ( {
+ test( 'Generates an excerpt and applies it from the modal', async ( {
admin,
editor,
page,
@@ -41,65 +98,185 @@ test.describe( 'Excerpt Generation Experiment', () => {
// Save the post.
await editor.saveDraft();
- // Ensure the sidebar is visible.
- await editor.openDocumentSettingsSidebar();
+ // Open the Excerpt generation panel.
+ await openExcerptGenerationPanel( editor, page );
- // Ensure the generate excerpt inline button exists.
- await expect(
- page.getByRole( 'button', { name: 'Generate excerpt' } ).first()
- ).toBeVisible();
+ // Click the generate excerpt button.
+ const panel = page.locator( PANEL_SELECTOR );
+ await panel.getByRole( 'button', { name: 'Generate excerpt' } ).click();
- // Click the Add excerpt button.
- await page.getByRole( 'button', { name: /Add an excerpt/i } ).click();
+ // The modal opens and the textarea is populated with the suggestion.
+ const modal = page.locator( MODAL_SELECTOR );
+ await expect( modal ).toBeVisible();
+ await expect( modal.getByRole( 'textbox' ) ).toHaveValue(
+ MOCK_EXCERPT,
+ { timeout: 10000 }
+ );
- // Ensure the generate excerpt button shows in the modal.
+ // Apply it.
+ await modal
+ .getByRole( 'button', { name: 'Apply', exact: true } )
+ .click();
+ await expect( modal ).not.toBeVisible();
+
+ // The excerpt was written to the post and the button label updated.
+ expect( await getStoredExcerpt( page ) ).toBe( MOCK_EXCERPT );
await expect(
- page.getByRole( 'button', { name: 'Generate excerpt' } ).last()
+ panel.getByRole( 'button', { name: 'Regenerate excerpt' } )
).toBeVisible();
- // Click the generate excerpt button.
+ // Save the post.
+ await editor.saveDraft();
+ } );
+
+ test( 'Can edit the suggestion before applying it', async ( {
+ admin,
+ editor,
+ page,
+ } ) => {
+ // Enable the Excerpt Generation Experiment.
+ await enableExperiment( admin, page, 'Excerpt Generation' );
+
+ await admin.createNewPost( {
+ postType: 'post',
+ title: 'Test Excerpt Generation Edit',
+ content: LONG_CONTENT,
+ } );
+
+ await openExcerptGenerationPanel( editor, page );
await page
+ .locator( PANEL_SELECTOR )
.getByRole( 'button', { name: 'Generate excerpt' } )
- .last()
.click();
- // Ensure the excerpt is updated.
- await expect(
- page.getByRole( 'textbox', { name: 'Write an excerpt (optional)' } )
- ).toHaveValue(
- 'Edit or Delete Your First WordPress Post to Begin Your Blogging Adventure'
+ const modal = page.locator( MODAL_SELECTOR );
+ await expect( modal.getByRole( 'textbox' ) ).toHaveValue(
+ MOCK_EXCERPT,
+ { timeout: 10000 }
);
- // Ensure the excerpt button text is updated.
- await expect(
- page.getByRole( 'button', { name: 'Regenerate excerpt' } ).last()
- ).toBeVisible();
+ // Edit the suggestion and apply the edited text.
+ await modal
+ .getByRole( 'textbox' )
+ .fill( 'A custom excerpt for testing purposes.' );
+ await modal
+ .getByRole( 'button', { name: 'Apply', exact: true } )
+ .click();
- // Delete the excerpt.
- await page
- .getByRole( 'textbox', { name: 'Write an excerpt (optional)' } )
- .fill( '' );
+ expect( await getStoredExcerpt( page ) ).toBe(
+ 'A custom excerpt for testing purposes.'
+ );
+ } );
+
+ test( 'Canceling the modal leaves the excerpt untouched', async ( {
+ admin,
+ editor,
+ page,
+ } ) => {
+ // Enable the Excerpt Generation Experiment.
+ await enableExperiment( admin, page, 'Excerpt Generation' );
- // Close the modal.
+ await admin.createNewPost( {
+ postType: 'post',
+ title: 'Test Excerpt Generation Cancel',
+ content: LONG_CONTENT,
+ excerpt: 'An existing excerpt.',
+ } );
+
+ await openExcerptGenerationPanel( editor, page );
+
+ // With an excerpt in place the button offers to regenerate.
await page
- .getByRole( 'button', { name: 'Close', exact: true } )
+ .locator( PANEL_SELECTOR )
+ .getByRole( 'button', { name: 'Regenerate excerpt' } )
.click();
- // Click the generate excerpt inline button.
- await page
- .getByRole( 'button', { name: 'Generate excerpt' } )
- .first()
+ const modal = page.locator( MODAL_SELECTOR );
+ await expect( modal.getByRole( 'textbox' ) ).toHaveValue(
+ MOCK_EXCERPT,
+ { timeout: 10000 }
+ );
+
+ // Cancel instead of applying.
+ await modal
+ .getByRole( 'button', { name: 'Cancel', exact: true } )
.click();
+ await expect( modal ).not.toBeVisible();
+
+ expect( await getStoredExcerpt( page ) ).toBe( 'An existing excerpt.' );
+ } );
+
+ test( 'Canceling generation stops loading and closes the modal', async ( {
+ admin,
+ editor,
+ page,
+ } ) => {
+ // Enable the Excerpt Generation Experiment.
+ await enableExperiment( admin, page, 'Excerpt Generation' );
+
+ await admin.createNewPost( {
+ postType: 'post',
+ title: 'Test Excerpt Generation Cancel Loading',
+ content: LONG_CONTENT,
+ } );
+
+ await openExcerptGenerationPanel( editor, page );
- // Ensure the excerpt is updated.
+ // Hold the ability request until the test releases it.
+ let resolveRequest;
+ const requestPromise = new Promise( ( resolve ) => {
+ resolveRequest = resolve;
+ } );
+ const routeMatcher = ( url ) => {
+ const decoded = decodeURIComponent( url.href );
+ return (
+ decoded.includes( 'wp-abilities' ) &&
+ decoded.includes( 'excerpt-generation' )
+ );
+ };
+ await page.route( routeMatcher, async ( route ) => {
+ await requestPromise;
+ await route.continue().catch( () => {} );
+ } );
+
+ const generateButton = page.locator(
+ '.ai-excerpt-generation-panel__generate-button'
+ );
+ await generateButton.click();
+
+ // The modal opens and both buttons show the loading state.
+ const modal = page.locator( MODAL_SELECTOR );
+ await expect( modal ).toBeVisible();
+ await expect( generateButton ).toHaveText( /Generating/ );
+ await expect( generateButton ).toBeDisabled();
await expect(
- page.getByText(
- 'Edit or Delete Your First WordPress Post to Begin Your Blogging Adventure'
- )
+ modal.getByRole( 'button', { name: /Generating/ } )
).toBeVisible();
- // Save the post.
- await editor.saveDraft();
+ // Cancel from the modal.
+ await modal
+ .getByRole( 'button', { name: 'Cancel', exact: true } )
+ .click();
+ await expect( modal ).not.toBeVisible();
+
+ // The panel button stops loading immediately.
+ await expect( generateButton ).toHaveText( 'Generate excerpt' );
+ await expect( generateButton ).toBeEnabled();
+
+ // No error notice was created.
+ const errorNotice = await page.evaluate( () =>
+ window.wp.data
+ .select( 'core/notices' )
+ .getNotices()
+ .find(
+ ( notice ) => notice.id === 'ai_excerpt_generation_error'
+ )
+ );
+ expect( errorNotice ).toBeUndefined();
+
+ // Release the pending request.
+ resolveRequest();
+ await page.unroute( routeMatcher );
} );
test( 'Generate excerpt button is disabled when there is not enough content', async ( {
@@ -117,26 +294,125 @@ test.describe( 'Excerpt Generation Experiment', () => {
content: 'Too short.',
} );
- // Ensure the sidebar is visible.
- await editor.openDocumentSettingsSidebar();
+ // Open the Excerpt generation panel.
+ await openExcerptGenerationPanel( editor, page );
- const inlineButton = page
- .getByRole( 'button', {
- name: /Excerpt generation will be available when the post content has at least/i,
- } )
- .first();
- await expect( inlineButton ).toBeVisible();
- await expect( inlineButton ).toBeDisabled();
+ const panel = page.locator( PANEL_SELECTOR );
+ const panelButton = panel.getByRole( 'button', {
+ name: /Excerpt generation will be available when the post content has at least/i,
+ } );
+ await expect( panelButton ).toBeVisible();
+ await expect( panelButton ).toBeDisabled();
- // The panel button inside the excerpt dropdown is also disabled.
- await page.getByRole( 'button', { name: /Add an excerpt/i } ).click();
+ // The reason is also shown as a hint below the button.
await expect(
- page
- .getByRole( 'button', {
- name: /Excerpt generation will be available when the post content has at least/i,
- } )
- .last()
- ).toBeDisabled();
+ panel.getByText( /at least 250 characters/ )
+ ).toBeVisible();
+ } );
+
+ test( 'Shows an error notice and keeps the excerpt when generation fails', async ( {
+ admin,
+ editor,
+ page,
+ } ) => {
+ // Enable the Excerpt Generation Experiment.
+ await enableExperiment( admin, page, 'Excerpt Generation' );
+
+ await admin.createNewPost( {
+ postType: 'post',
+ title: 'Test Excerpt Generation Failure',
+ content: LONG_CONTENT,
+ excerpt: 'An existing excerpt.',
+ } );
+
+ // Make the ability request fail. Use a URL predicate instead of a regex
+ // so the match is reliable regardless of URL encoding.
+ await page.route(
+ ( url ) =>
+ url.href.includes( 'wp-abilities' ) &&
+ url.href.includes( 'excerpt-generation' ),
+ async ( route ) => {
+ await route.fulfill( {
+ status: 500,
+ contentType: 'application/json',
+ body: JSON.stringify( {
+ code: 'internal_error',
+ message: 'AI service unavailable',
+ data: { status: 500 },
+ } ),
+ } );
+ }
+ );
+
+ await openExcerptGenerationPanel( editor, page );
+ const panelButton = page
+ .locator( PANEL_SELECTOR )
+ .getByRole( 'button', { name: 'Regenerate excerpt' } );
+ await panelButton.click();
+
+ // The error surfaces as an editor notice.
+ await page.waitForFunction( () =>
+ window.wp.data
+ .select( 'core/notices' )
+ .getNotices()
+ .some(
+ ( notice ) =>
+ notice.id === 'ai_excerpt_generation_error' &&
+ notice.content === 'AI service unavailable'
+ )
+ );
+
+ // The modal still holds the existing excerpt; cancel leaves it untouched.
+ const modal = page.locator( MODAL_SELECTOR );
+ await expect( modal.getByRole( 'textbox' ) ).toHaveValue(
+ 'An existing excerpt.'
+ );
+ await modal
+ .getByRole( 'button', { name: 'Cancel', exact: true } )
+ .click();
+ expect( await getStoredExcerpt( page ) ).toBe( 'An existing excerpt.' );
+
+ // The button is usable again.
+ await expect( panelButton ).toBeEnabled();
+ } );
+
+ test( 'Panel is hidden when the core Excerpt panel is disabled in Preferences', async ( {
+ admin,
+ editor,
+ page,
+ } ) => {
+ // Enable the Excerpt Generation Experiment.
+ await enableExperiment( admin, page, 'Excerpt Generation' );
+
+ await admin.createNewPost( {
+ postType: 'post',
+ title: 'Test Excerpt Generation Panel Preference',
+ content: LONG_CONTENT,
+ } );
+
+ // The panel is there while core's Excerpt panel is enabled.
+ await openExcerptGenerationPanel( editor, page );
+ await expect( page.locator( PANEL_SELECTOR ) ).toBeVisible();
+
+ // Turn off core's Excerpt panel, as a user would from Preferences > Panels.
+ await page.evaluate( () =>
+ window.wp.data
+ .dispatch( 'core/editor' )
+ .toggleEditorPanelEnabled( 'post-excerpt' )
+ );
+
+ try {
+ await expect( page.locator( PANEL_SELECTOR ) ).toBeHidden();
+ } finally {
+ // Restore the preference so later tests see the default state.
+ await page.evaluate( () =>
+ window.wp.data
+ .dispatch( 'core/editor' )
+ .toggleEditorPanelEnabled( 'post-excerpt' )
+ );
+ }
+
+ await expect( page.locator( PANEL_SELECTOR ) ).toBeVisible();
} );
test( 'Ensure the Excerpt Generation Experiment UI is not visible when the experiment is disabled', async ( {
@@ -161,17 +437,12 @@ test.describe( 'Excerpt Generation Experiment', () => {
// Ensure the sidebar is visible.
await editor.openDocumentSettingsSidebar();
- // Ensure the generate excerpt inline button doesn't exist.
- await expect(
- page.getByRole( 'button', { name: 'Generate excerpt' } ).first()
- ).not.toBeVisible();
-
- // Click the Add excerpt button.
- await page.getByRole( 'button', { name: /Add an excerpt/i } ).click();
+ // Ensure the Excerpt generation panel doesn't exist.
+ await expect( page.locator( PANEL_SELECTOR ) ).not.toBeVisible();
- // Ensure the generate excerpt button doesn't show in the modal.
+ // Ensure no generate excerpt button exists anywhere in the editor.
await expect(
- page.getByRole( 'button', { name: 'Generate excerpt' } ).last()
+ page.getByRole( 'button', { name: 'Generate excerpt' } )
).not.toBeVisible();
} );
} );
diff --git a/tests/e2e/specs/experiments/no-provider-degradation.spec.js b/tests/e2e/specs/experiments/no-provider-degradation.spec.js
index 062459583..8f4d22562 100644
--- a/tests/e2e/specs/experiments/no-provider-degradation.spec.js
+++ b/tests/e2e/specs/experiments/no-provider-degradation.spec.js
@@ -18,7 +18,17 @@ const MANAGE_CONNECTORS_TEXT = 'Manage Connectors';
const LONG_CONTENT =
'Artificial intelligence is rapidly changing how content is created, edited, and published across the web today. Writers increasingly rely on automated tools to draft outlines, summarize research, and suggest improvements to their work. These systems analyze large amounts of text and surface patterns that would take a human many hours to find on their own. As the technology matures, editors are learning to combine their own judgment with machine generated suggestions to produce stronger results. This paragraph exists only to provide enough words for the title generation experiment to run, because the feature now requires a reasonable amount of content before it will offer to generate a brand new title for the post.';
-async function openMetaDescriptionPanel( editor, page ) {
+/**
+ * Opens the Post sidebar and expands the given document setting panel.
+ *
+ * Plugin panels start collapsed, so their contents are not rendered until
+ * the panel is toggled open.
+ *
+ * @param {Object} editor The editor fixture.
+ * @param {Object} page The page object.
+ * @param {string} panelTitle The panel title, e.g. 'Meta Description'.
+ */
+async function openDocumentSettingPanel( editor, page, panelTitle ) {
await editor.openDocumentSettingsSidebar();
const postTab = page.getByRole( 'tab', { name: 'Post' } );
@@ -27,7 +37,7 @@ async function openMetaDescriptionPanel( editor, page ) {
}
const panelToggle = page.locator( '.components-panel__body-toggle', {
- hasText: 'Meta Description',
+ hasText: panelTitle,
} );
if ( ( await panelToggle.count() ) > 0 ) {
@@ -104,13 +114,13 @@ test.describe( 'Graceful degradation when no AI provider is configured', () => {
content: LONG_CONTENT,
} );
await editor.saveDraft();
- await editor.openDocumentSettingsSidebar();
+ await openDocumentSettingPanel( editor, page, 'Excerpt generation' );
- const inlineButton = page.locator(
- '.editor-post-excerpt__dropdown .ai-excerpt-inline-wrapper .ai-excerpt-inline-button'
- );
- await expect( inlineButton ).toBeVisible( { timeout: 5000 } );
- await inlineButton.click();
+ const generateButton = page
+ .locator( '.ai-excerpt-generation-panel' )
+ .getByRole( 'button', { name: 'Generate excerpt' } );
+ await expect( generateButton ).toBeVisible( { timeout: 5000 } );
+ await generateButton.click();
await expectProviderNotice( page );
} );
@@ -178,7 +188,7 @@ test.describe( 'Graceful degradation when no AI provider is configured', () => {
} );
await editor.saveDraft();
- await openMetaDescriptionPanel( editor, page );
+ await openDocumentSettingPanel( editor, page, 'Meta Description' );
const generateButton = page.locator(
'.ai-meta-description-panel button',
@@ -298,13 +308,13 @@ test.describe( 'Graceful degradation when no AI provider is configured', () => {
content: LONG_CONTENT,
} );
await editor.saveDraft();
- await editor.openDocumentSettingsSidebar();
+ await openDocumentSettingPanel( editor, page, 'Excerpt generation' );
- const inlineButton = page.locator(
- '.editor-post-excerpt__dropdown .ai-excerpt-inline-wrapper .ai-excerpt-inline-button'
- );
- await expect( inlineButton ).toBeVisible( { timeout: 5000 } );
- await inlineButton.click();
+ const generateButton = page
+ .locator( '.ai-excerpt-generation-panel' )
+ .getByRole( 'button', { name: 'Generate excerpt' } );
+ await expect( generateButton ).toBeVisible( { timeout: 5000 } );
+ await generateButton.click();
const notice = page.locator( '.components-notice', {
hasText: NOTICE_TEXT,