diff --git a/docs/experiments/editorial-notes.md b/docs/experiments/editorial-notes.md index 7b953c0b9..085766323 100644 --- a/docs/experiments/editorial-notes.md +++ b/docs/experiments/editorial-notes.md @@ -28,9 +28,10 @@ When enabled, a "Generate Editorial Notes" button appears in the post status inf - Block-level Notes with suggestions scoped to each block's content and type - Four review categories: Accessibility, Readability, Grammar, SEO -- Accumulating history: subsequent review runs append replies to existing Note threads rather than creating duplicate threads +- Accumulating history: subsequent review runs reply to the block's existing AI Note thread rather than creating duplicate threads +- Works alongside human Notes: the AI keeps its own thread on each block, and Notes added through the Notes panel stay attached to the block - Prior suggestions are sent back to the AI as context so it avoids repeating itself -- Blocks whose Note thread has been resolved (marked as approved) are skipped on re-run +- Blocks whose AI Note thread has been resolved (marked as approved) are skipped on re-run - Works with common block types: paragraphs, headings, images, lists, tables, quotes, and more ### For Developers @@ -126,10 +127,11 @@ In both cases, users without the required capability receive an `insufficient_ca Notes are `WP_Comment` objects with `comment_type = 'note'` and `status = 'hold'`. Block association is maintained via block metadata: -- **New thread**: `POST /wp/v2/comments` with `parent: 0` → response `id` stored in `block.attributes.metadata.noteId` via `updateBlockAttributes` -- **Reply**: `POST /wp/v2/comments` with `parent: existingNoteId` → block metadata unchanged (association already set) +- **`noteId` format**: `metadata.noteId` is expected to be either a number (`12`) or an array of numbers (`[12, 34]`). +- **New thread**: `POST /wp/v2/comments` with `parent: 0` → response `id` is added to `block.attributes.metadata.noteId` via `updateBlockAttributes`. Existing IDs are kept, and the block's current format is preserved: arrays are appended to, and a number is only set when the block has no Note yet. +- **Reply**: `POST /wp/v2/comments` with `parent: ` → block metadata unchanged. The AI thread is the block's root Note with `meta.wpai_note = true`. When `noteId` is a number, the AI replies to that thread. - **AI author**: All Notes created by this experiment include `meta: { wpai_note: true }`. The `rest_pre_insert_comment` filter intercepts this and sets the author to "WordPress AI" with no email, URL, or user ID, so Notes are not attributed to the authenticated user's account. -- **Resolved Notes**: Notes with `status = 'approve'` (resolved) cause their associated block to be skipped entirely on the next review run. +- **Resolved Notes**: A resolved (`status = 'approve'`) AI thread causes its block to be skipped entirely on the next review run. Resolved human threads do not, except when `noteId` is a number, in which case the block is skipped once that thread is no longer pending. ## Using the Ability via REST API @@ -264,12 +266,20 @@ async function reviewBlock( blockType, blockContent, existingNotes = [] ) { - Run the review again - Verify the resolved block is skipped entirely -5. **Note deletion cleanup:** +5. **Multiple Note threads:** + - Add a Note to a paragraph block through the Notes panel + - Run the review + - Verify the AI's suggestions appear as a separate thread and the human Note is still attached + - In the Code Editor, verify the block's `metadata.noteId` contains both IDs (e.g. `[123, 124]`) + - Run the review again and verify the AI replies in its own thread + - Resolve the human Note, run again, and verify the block is still reviewed + +6. **Note deletion cleanup:** - Delete a Note from the Notes panel - Save the post - Verify the deleted block no longer has a `noteId` in its block metadata (inspect via the Code Editor) -6. **Edge cases:** +7. **Edge cases:** - Post with only very short blocks → button completes instantly with "No new suggestions found." - All blocks already have Notes → second run skips repeats - Disable experiment → button disappears from sidebar @@ -291,14 +301,15 @@ async function reviewBlock( blockType, blockContent, existingNotes = [] ) { ### Note Storage - Notes are stored as WordPress comments with `comment_type = 'note'` and `comment_author = 'WordPress AI'` -- Block association is stored in `block.attributes.metadata.noteId` +- Block association is stored in `block.attributes.metadata.noteId`, as either a number or an array of numbers - Block metadata is saved as part of the post content when the editor saves - Note threads accumulate across review runs by design -- Deleting or trashing a root Note automatically clears `metadata.noteId` from its associated block +- Deleting or trashing a root Note automatically removes its ID from the associated block's `metadata.noteId` ### Limitations - Image block review is limited to alt text presence; it does not analyze the image itself - Block metadata (`noteId`) is only persisted after the post is saved - The 25-block cap means very long posts will have only the first 25 reviewable blocks analyzed per run -- Resolved blocks (approved Notes) are skipped in full; they will not receive new suggestions until the Note is un-resolved or deleted +- Blocks with a resolved AI thread are skipped in full; they will not receive new suggestions until the thread is un-resolved or deleted +- When `noteId` is a number, the AI replies to that existing thread even if a human started it diff --git a/docs/experiments/editorial-updates.md b/docs/experiments/editorial-updates.md index 18d44e16f..b1768588a 100644 --- a/docs/experiments/editorial-updates.md +++ b/docs/experiments/editorial-updates.md @@ -39,6 +39,13 @@ When enabled, an "Editorial Updates" button appears in the post status info pane Can safely run against any block. Output targets formatting of standard block markup (e.g. inner wrappers). +### Note Association + +Blocks are linked to Notes through `block.attributes.metadata.noteId`, which is expected to be either a number (`12`) or an array of numbers (`[12, 34]`). + +- Every pending (`status = 'hold'`) thread linked to the block is refined, whether a human or the AI started it +- After a successful refinement, the refined threads and their replies are resolved (`status = 'approve'`). Blocks whose content is unchanged keep their threads open. + ### Input Schema ```php diff --git a/src/experiments/editorial-notes/hooks/useEditorialNotes.ts b/src/experiments/editorial-notes/hooks/useEditorialNotes.ts index 2184db71a..704098436 100644 --- a/src/experiments/editorial-notes/hooks/useEditorialNotes.ts +++ b/src/experiments/editorial-notes/hooks/useEditorialNotes.ts @@ -19,60 +19,21 @@ import { store as noticesStore } from '@wordpress/notices'; */ import { flattenBlocks, - getBlockText, getPostContentBlockContext, - replaceBlockWithPlaceholder, } from '../../../utils/blocks'; -import type { ExistingNote } from '../../../utils/notes'; import { REVIEWABLE_BLOCK_TYPES, fetchAllNotesByStatus, - buildContextWindow, } from '../../../utils/notes'; import { ensureProvider } from '../../../utils/provider-status'; -import { runAbility } from '../../../utils/run-ability'; import { hasMinimumContent } from '../../../utils/character-count'; - -const BLOCK_PLACEHOLDER = '[[BLOCK_GOES_HERE]]'; +import { reviewSingleBlock } from '../utils'; const BATCH_SIZE = 4; const NOTICE_ID = 'ai_editorial_notes_error'; const NOTES_SIDEBAR_ID = 'edit-post/collab-sidebar'; const MINIMUM_CONTENT_COUNT_DEFAULT = 75; -interface BlockAttributes { - content?: string; - value?: string; - alt?: string; - caption?: string; - metadata?: { - noteId?: number; - [ key: string ]: unknown; - }; - [ key: string ]: unknown; -} - -interface Block { - clientId: string; - name: string; - attributes: BlockAttributes; - innerBlocks: Block[]; -} - -interface Suggestion { - review_type: string; - text: string; -} - -interface ReviewResult { - suggestions: Suggestion[]; -} - -interface NoteRecord { - id: number; - [ key: string ]: unknown; -} - /** * Hook for determining whether Editorial Notes should be available. * @@ -98,91 +59,6 @@ function useEditorialNotesAvailability(): { }; } -/** - * Reviews a single block and creates/updates a Note if suggestions are found. - * - * @param block The block to review. - * @param postId The current post ID. - * @param content The full post content (HTML). - * @param resolvedNoteIds Set of Note IDs that have been resolved (approved). - * @param noteContentById Map of Note ID → rendered Note content (pending only). - * @param pendingNotes All pending Notes for the post (for reply lookup). - * @return The number of suggestions created, or 0 if the block was skipped. - */ -async function reviewSingleBlock( - block: Block, - postId: number, - content: string, - resolvedNoteIds: Set< number >, - noteContentById: Map< number, string >, - pendingNotes: ExistingNote[] -): Promise< number > { - // Look up any existing Note thread on this block. - const existingNoteId = block.attributes.metadata?.noteId ?? null; - - // Skip blocks whose Note thread has been resolved. - if ( existingNoteId && resolvedNoteIds.has( existingNoteId ) ) { - return 0; - } - - const blockText = getBlockText( block ); - - if ( blockText.length === 0 ) { - return 0; - } - - // Collect pending Note texts for this block's thread as context. - const existingNoteTexts: string[] = []; - if ( existingNoteId ) { - const rootText = noteContentById.get( existingNoteId ); - if ( rootText ) { - existingNoteTexts.push( rootText ); - } - - // Also collect replies (Notes with parent === existingNoteId). - for ( const note of pendingNotes ) { - if ( note.parent === existingNoteId ) { - const replyText = noteContentById.get( note.id ); - if ( replyText ) { - existingNoteTexts.push( replyText ); - } - } - } - } - - // Replace the block with the placeholder. - const contentWithPlaceholder = - block.clientId !== undefined - ? replaceBlockWithPlaceholder( - content, - block.clientId, - BLOCK_PLACEHOLDER - ) - : content; - - // Prepare a bounded context around the placeholder. - const context = buildContextWindow( - contentWithPlaceholder, - BLOCK_PLACEHOLDER - ); - - // Call the review Ability. - const result = await runAbility< ReviewResult >( 'ai/editorial-notes', { - block_type: block.name, - block_content: blockText, - context, - post_id: postId, - existing_notes: existingNoteTexts, - } ); - - if ( result?.suggestions && result.suggestions.length > 0 ) { - await createNote( block, postId, result.suggestions, existingNoteId ); - return result.suggestions.length; - } - - return 0; -} - /** * Hook for Editorial Notes functionality. * @@ -262,8 +138,12 @@ export function useEditorialNotes(): { fetchAllNotesByStatus( postId, 'hold' ), fetchAllNotesByStatus( postId, 'approve' ), ] ); + + // Only resolved AI threads mark a block as already reviewed. const resolvedNoteIds = new Set( - approvedNotes.map( ( n ) => n.id ) + approvedNotes + .filter( ( note ) => note.meta?.wpai_note === true ) + .map( ( n ) => n.id ) ); // Build a lookup: noteId → Note content text (pending Notes only). @@ -427,7 +307,9 @@ export function useEditorialBlock(): { fetchAllNotesByStatus( postId, 'approve' ), ] ); const resolvedNoteIds = new Set( - approvedNotes.map( ( n ) => n.id ) + approvedNotes + .filter( ( note ) => note.meta?.wpai_note === true ) + .map( ( n ) => n.id ) ); const noteContentById = new Map< number, string >(); @@ -492,53 +374,3 @@ export function useEditorialBlock(): { reviewBlock, }; } - -/** - * Creates a Note (or appends a reply) for a reviewed block. - * - * When no existing Note thread is present, creates a new Note and updates - * the block's metadata with the resulting Note ID. When a thread already - * exists, appends a reply to preserve the conversation history. - * - * @param block The block that received suggestions. - * @param postId The current post ID. - * @param suggestions The suggestions to include in the Note. - * @param existingNoteId The ID of an existing Note thread, or null for a new thread. - */ -async function createNote( - block: Block, - postId: number, - suggestions: Suggestion[], - existingNoteId: number | null -): Promise< void > { - const noteContent = suggestions - .map( ( s ) => `[${ s.review_type.toUpperCase() }] ${ s.text }` ) - .join( '\n\n' ); - - const note = ( await dispatch( coreStore ).saveEntityRecord( - 'root', - 'comment', - { - post: postId, - content: noteContent, - type: 'note', - status: 'hold', - parent: existingNoteId ?? 0, - meta: { wpai_note: true }, - }, - // Reject on a failed save so the caller reports the error. - { throwOnError: true } - ) ) as NoteRecord | undefined; - - // Only update block metadata when creating a new thread (not a reply). - if ( ! existingNoteId && note?.id ) { - const existingMeta = - ( select( blockEditorStore ) as any ).getBlockAttributes( - block.clientId - )?.metadata ?? {}; - - dispatch( blockEditorStore ).updateBlockAttributes( block.clientId, { - metadata: { ...existingMeta, noteId: note.id }, - } ); - } -} diff --git a/src/experiments/editorial-notes/types/index.ts b/src/experiments/editorial-notes/types/index.ts new file mode 100644 index 000000000..1e503733e --- /dev/null +++ b/src/experiments/editorial-notes/types/index.ts @@ -0,0 +1,32 @@ +export interface BlockAttributes { + content?: string; + value?: string; + alt?: string; + caption?: string; + metadata?: { + noteId?: number | number[]; + [ key: string ]: unknown; + }; + [ key: string ]: unknown; +} + +export interface Block { + clientId: string; + name: string; + attributes: BlockAttributes; + innerBlocks: Block[]; +} + +export interface Suggestion { + review_type: string; + text: string; +} + +export interface ReviewResult { + suggestions: Suggestion[]; +} + +export interface NoteRecord { + id: number; + [ key: string ]: unknown; +} diff --git a/src/experiments/editorial-notes/utils/index.ts b/src/experiments/editorial-notes/utils/index.ts new file mode 100644 index 000000000..69ef20c5a --- /dev/null +++ b/src/experiments/editorial-notes/utils/index.ts @@ -0,0 +1,186 @@ +/** + * WordPress dependencies + */ +import { dispatch, select } from '@wordpress/data'; +import { store as blockEditorStore } from '@wordpress/block-editor'; +import { store as coreStore } from '@wordpress/core-data'; + +/** + * Internal dependencies + */ +import type { ExistingNote } from '../../../utils/notes'; +import type { Block, Suggestion, ReviewResult, NoteRecord } from '../types'; +import { runAbility } from '../../../utils/run-ability'; +import { + addNoteId, + buildContextWindow, + collectThreadTexts, + getNoteIds, + hasNoteIdList, +} from '../../../utils/notes'; +import { + getBlockText, + replaceBlockWithPlaceholder, +} from '../../../utils/blocks'; + +const BLOCK_PLACEHOLDER = '[[BLOCK_GOES_HERE]]'; + +/** + * Reviews a single block and creates/updates a Note if suggestions are found. + * + * @param block The block to review. + * @param postId The current post ID. + * @param content The full post content (HTML). + * @param resolvedNoteIds Set of AI Note IDs that have been resolved (approved). + * @param noteContentById Map of Note ID → rendered Note content (pending only). + * @param pendingNotes All pending Notes for the post (for reply lookup). + * @return The number of suggestions created, or 0 if the block was skipped. + */ +export async function reviewSingleBlock( + block: Block, + postId: number, + content: string, + resolvedNoteIds: Set< number >, + noteContentById: Map< number, string >, + pendingNotes: ExistingNote[] +): Promise< number > { + const noteIds = getNoteIds( block.attributes.metadata ); + const isSingleThread = ! hasNoteIdList( block.attributes.metadata ); + + // Skip blocks whose AI thread has been resolved. + if ( noteIds.some( ( id ) => resolvedNoteIds.has( id ) ) ) { + return 0; + } + + // A single-ID block allows one thread, so skip it once that thread is no longer pending. + if ( + isSingleThread && + noteIds.length && + ! pendingNotes.some( ( note ) => note.id === noteIds[ 0 ] ) + ) { + return 0; + } + + const blockText = getBlockText( block ); + + if ( blockText.length === 0 ) { + return 0; + } + + // Collect pending Note texts for this block's thread as context. + const existingNoteTexts = collectThreadTexts( + noteIds, + noteContentById, + pendingNotes + ); + + // Replace the block with the placeholder. + const contentWithPlaceholder = + block.clientId !== undefined + ? replaceBlockWithPlaceholder( + content, + block.clientId, + BLOCK_PLACEHOLDER + ) + : content; + + // Prepare a bounded context around the placeholder. + const context = buildContextWindow( + contentWithPlaceholder, + BLOCK_PLACEHOLDER + ); + + // Call the review Ability. + const result = await runAbility< ReviewResult >( 'ai/editorial-notes', { + block_type: block.name, + block_content: blockText, + context, + post_id: postId, + existing_notes: existingNoteTexts, + } ); + + if ( result?.suggestions && result.suggestions.length > 0 ) { + await createNote( + block, + postId, + result.suggestions, + isSingleThread + ? noteIds[ 0 ] ?? null + : findAiThreadId( noteIds, pendingNotes ) + ); + return result.suggestions.length; + } + + return 0; +} + +/** + * Creates a Note (or appends a reply) for a reviewed block. + * + * When no existing Note thread is present, creates a new Note and updates + * the block's metadata with the resulting Note ID. When a thread already + * exists, appends a reply to preserve the conversation history. + * + * @param block The block that received suggestions. + * @param postId The current post ID. + * @param suggestions The suggestions to include in the Note. + * @param existingNoteId The ID of an existing Note thread, or null for a new thread. + */ +async function createNote( + block: Block, + postId: number, + suggestions: Suggestion[], + existingNoteId: number | null +): Promise< void > { + const noteContent = suggestions + .map( ( s ) => `[${ s.review_type.toUpperCase() }] ${ s.text }` ) + .join( '\n\n' ); + + const note = ( await dispatch( coreStore ).saveEntityRecord( + 'root', + 'comment', + { + post: postId, + content: noteContent, + type: 'note', + status: 'hold', + parent: existingNoteId ?? 0, + meta: { wpai_note: true }, + }, + // Reject on a failed save so the caller reports the error. + { throwOnError: true } + ) ) as NoteRecord | undefined; + + // Only update block metadata when creating a new thread (not a reply). + if ( ! existingNoteId && note?.id ) { + const existingMeta = + ( select( blockEditorStore ) as any ).getBlockAttributes( + block.clientId + )?.metadata ?? {}; + + dispatch( blockEditorStore ).updateBlockAttributes( block.clientId, { + metadata: addNoteId( existingMeta, note.id ), + } ); + } +} + +/** + * Finds the pending AI-created root Note among a block's Note threads. + * + * @param noteIds The root Note IDs attached to the block. + * @param pendingNotes All pending Notes for the post. + * @return The AI thread's root Note ID, or null if none exists. + */ +function findAiThreadId( + noteIds: number[], + pendingNotes: ExistingNote[] +): number | null { + return ( + pendingNotes.find( + ( note ) => + noteIds.includes( note.id ) && + note.parent === 0 && + note.meta?.wpai_note + )?.id ?? null + ); +} diff --git a/src/experiments/editorial-updates/hooks/useEditorialUpdates.ts b/src/experiments/editorial-updates/hooks/useEditorialUpdates.ts index f5e3ae03d..19a810975 100644 --- a/src/experiments/editorial-updates/hooks/useEditorialUpdates.ts +++ b/src/experiments/editorial-updates/hooks/useEditorialUpdates.ts @@ -27,185 +27,26 @@ import { REVIEWABLE_BLOCK_TYPES, fetchAllNotesByStatus, buildContextWindow, + collectThreadTexts, + getNoteIds, } from '../../../utils/notes'; import { ensureProvider } from '../../../utils/provider-status'; import { runAbility } from '../../../utils/run-ability'; +import type { Block } from '../types'; +import { getRevisionReviewAction, resolveNote } from '../utils'; const BLOCK_PLACEHOLDER = '[[BLOCK_GOES_HERE]]'; const NOTICE_ID = 'wpai_editorial_updates_error'; -interface BlockAttributes { - content?: string; - value?: string; - alt?: string; - caption?: string; - metadata?: { - noteId?: number; - [ key: string ]: unknown; - }; - [ key: string ]: unknown; -} - -interface Block { - clientId: string; - name: string; - attributes: BlockAttributes; - innerBlocks: Block[]; -} - -/** - * Updates a Note status to approved. - * - * @param noteId Note ID. - */ -async function resolveNote( noteId: number ): Promise< void > { - return apiFetch< void >( { - path: `/wp/v2/comments/${ noteId }`, - method: 'PUT', - data: { status: 'approve' }, - } ); -} - -/** - * Navigates to the classic revisions screen. - * - * @param adminUrl Site admin URL, or undefined if unavailable. - * @param lastRevisionId The revision ID to open. - */ -function navigateToClassicRevisions( - adminUrl: string | undefined, - lastRevisionId: number -): void { - if ( adminUrl ) { - window.location.href = `${ adminUrl }revision.php?revision=${ lastRevisionId }`; - } -} - -/** - * Opens WordPress's in-editor visual revisions UI by clicking the - * "Revisions" button Core already renders in the Document Settings - * sidebar (`PrivatePostLastRevision` in @wordpress/editor). - * - * There is no public JS API for this in WP 7.0 — the underlying store - * action (`setCurrentRevisionId`) is registered as a private action and - * is gated behind @wordpress/private-apis, which only allows a hardcoded - * list of core module names to opt in. Calling it directly from a plugin - * throws, since the action is never attached to the public dispatch - * object. Simulating a real click on Core's own rendered button is the - * supported workaround. - * - * Elements are located by stable, locale-independent attributes rather - * than translated accessible names: the sidebar toggle uses - * `aria-controls="edit-post:document"`, which comes from the - * complementary area identifier `edit-post/document` registered by - * the WordPress editor package for the Document Settings sidebar, and - * is the same regardless of site language. - * - * Falls back to the classic revisions screen if the button can't be - * found within a short polling window (e.g. markup changes upstream, or - * the post genuinely has fewer than two revisions so Core doesn't render - * the button at all). - * - * @param root0 Options. - * @param root0.adminUrl Site admin URL, used for the classic - * revisions fallback. - * @param root0.lastRevisionId The revision ID to open. - */ -function openVisualRevisions( { - adminUrl, - lastRevisionId, -}: { - adminUrl: string | undefined; - lastRevisionId: number; -} ): void { - const MAX_ATTEMPTS = 20; - const INTERVAL_MS = 100; - - // The revisions button only exists in the DOM once the Document - // Settings sidebar is mounted, so open it first if it's collapsed. - const settingsToggle = document.querySelector< HTMLButtonElement >( - 'button[aria-controls="edit-post:document"]' - ); - if ( settingsToggle?.getAttribute( 'aria-expanded' ) === 'false' ) { - settingsToggle.click(); - } - - let attempts = 0; - const tryClick = () => { - const revisionsButton = document.querySelector< HTMLButtonElement >( - '.editor-private-post-last-revision__button, .editor-post-last-revision__title' - ); - if ( revisionsButton ) { - revisionsButton.click(); - return; - } - attempts++; - if ( attempts >= MAX_ATTEMPTS ) { - navigateToClassicRevisions( adminUrl, lastRevisionId ); - return; - } - setTimeout( tryClick, INTERVAL_MS ); - }; - tryClick(); -} - -/** - * Builds the snackbar action for reviewing changes in the revisions UI. - * - * Uses the in-editor visual revisions path (WP 7.0+ default) via - * openVisualRevisions(). Falls back to the classic revisions screen when - * visual revisions are disabled, e.g. when classic metaboxes are active - * on the post. - * - * @param root0 Options. - * @param root0.lastRevisionId The revision ID to open. - * @param root0.adminUrl Site admin URL, used for the - * classic revisions fallback. - * @param root0.disableVisualRevisions Whether Core has disabled visual - * revisions for this post. - * @return Snackbar notice actions, or an empty array when neither path - * is available. - */ -function getRevisionReviewAction( { - lastRevisionId, - adminUrl, - disableVisualRevisions, -}: { - lastRevisionId: number; - adminUrl: string | undefined; - disableVisualRevisions: boolean; -} ): Array< { label: string; url?: string; onClick?: () => void } > { - if ( ! disableVisualRevisions ) { - return [ - { - label: __( 'Review in Revisions', 'ai' ), - onClick: () => - openVisualRevisions( { adminUrl, lastRevisionId } ), - }, - ]; - } - - if ( adminUrl ) { - return [ - { - label: __( 'Review in Revisions', 'ai' ), - url: `${ adminUrl }revision.php?revision=${ lastRevisionId }`, - }, - ]; - } - - return []; -} - /** * Hook for refining blocks based on existing notes with AI. * * @return {Object} Object with refining state and functions. - * @property {boolean} isRefining Whether a refine operation is in progress. - * @property {number} progress The number of blocks processed so far. - * @property {number} total The total number of blocks to process. - * @property {boolean} hasPendingNotes Whether there are pending notes to process. - * @property {Function} runRefinement Function to trigger the refinement process. + * @property {boolean} isRefining Whether a refine operation is in progress. + * @property {number} progress The number of blocks processed so far. + * @property {number} total The total number of blocks to process. + * @property {boolean} hasPendingNotes Whether there are pending notes to process. + * @property {()=>Promise} runRefinement Function to trigger the refinement process. */ export function useEditorialUpdates(): { isRefining: boolean; @@ -242,8 +83,9 @@ export function useEditorialUpdates(): { .filter( ( block ) => REVIEWABLE_BLOCK_TYPES.includes( block.name ) ) - .map( ( block ) => block.attributes.metadata?.noteId ) - .filter( ( id ) => typeof id === 'number' ) + .flatMap( ( block ) => + getNoteIds( block.attributes.metadata ) + ) ) ); @@ -307,17 +149,18 @@ export function useEditorialUpdates(): { noteContentById.set( note.id, note.content?.rendered ?? '' ); } + // Pending note threads attached to the block, human or AI. + const getRefinableNoteIds = ( block: Block ) => + getNoteIds( block.attributes.metadata ).filter( ( id ) => + noteContentById.has( id ) + ); + // Find which blocks have matching notes const refineableBlocks = flatBlocks.filter( ( block ) => { if ( ! REVIEWABLE_BLOCK_TYPES.includes( block.name ) ) { return false; } - const existingNoteId = - block.attributes.metadata?.noteId ?? null; - if ( - ! existingNoteId || - ! noteContentById.has( existingNoteId ) - ) { + if ( getRefinableNoteIds( block ).length === 0 ) { return false; } const blockText = getBlockText( block ); @@ -355,28 +198,16 @@ export function useEditorialUpdates(): { await Promise.all( batch.map( async ( block ) => { - const existingNoteId = block.attributes.metadata - ?.noteId as number; + const pendingNoteIds = getRefinableNoteIds( block ); const blockText = getBlockText( block ); // Collect notes logic - const existingNoteTexts: string[] = []; - const rootText = noteContentById.get( existingNoteId ); - if ( rootText ) { - existingNoteTexts.push( rootText ); - } - - for ( const note of pendingNotes ) { - if ( note.parent === existingNoteId ) { - const replyText = noteContentById.get( - note.id - ); - if ( replyText ) { - existingNoteTexts.push( replyText ); - } - } - } + const existingNoteTexts = collectThreadTexts( + pendingNoteIds, + noteContentById, + pendingNotes + ); // Replace the block with the placeholder. const contentWithPlaceholder = @@ -430,9 +261,11 @@ export function useEditorialUpdates(): { refinedBlocksCount++; // Add notes for resolution - notesToResolve.push( existingNoteId ); + notesToResolve.push( ...pendingNoteIds ); for ( const note of pendingNotes ) { - if ( note.parent === existingNoteId ) { + if ( + pendingNoteIds.includes( note.parent ) + ) { notesToResolve.push( note.id ); } } diff --git a/src/experiments/editorial-updates/types/index.ts b/src/experiments/editorial-updates/types/index.ts new file mode 100644 index 000000000..349d5c4b9 --- /dev/null +++ b/src/experiments/editorial-updates/types/index.ts @@ -0,0 +1,18 @@ +export interface BlockAttributes { + content?: string; + value?: string; + alt?: string; + caption?: string; + metadata?: { + noteId?: number | number[]; + [ key: string ]: unknown; + }; + [ key: string ]: unknown; +} + +export interface Block { + clientId: string; + name: string; + attributes: BlockAttributes; + innerBlocks: Block[]; +} diff --git a/src/experiments/editorial-updates/utils/index.ts b/src/experiments/editorial-updates/utils/index.ts new file mode 100644 index 000000000..f426cffe3 --- /dev/null +++ b/src/experiments/editorial-updates/utils/index.ts @@ -0,0 +1,149 @@ +/** + * WordPress dependencies + */ +import apiFetch from '@wordpress/api-fetch'; +import { __ } from '@wordpress/i18n'; + +/** + * Updates a Note status to approved. + * + * @param noteId Note ID. + */ +export async function resolveNote( noteId: number ): Promise< void > { + return apiFetch< void >( { + path: `/wp/v2/comments/${ noteId }`, + method: 'PUT', + data: { status: 'approve' }, + } ); +} + +/** + * Navigates to the classic revisions screen. + * + * @param adminUrl Site admin URL, or undefined if unavailable. + * @param lastRevisionId The revision ID to open. + */ +function navigateToClassicRevisions( + adminUrl: string | undefined, + lastRevisionId: number +): void { + if ( adminUrl ) { + window.location.href = `${ adminUrl }revision.php?revision=${ lastRevisionId }`; + } +} + +/** + * Opens WordPress's in-editor visual revisions UI by clicking the + * "Revisions" button Core already renders in the Document Settings + * sidebar (`PrivatePostLastRevision` in `@wordpress/editor`). + * + * There is no public JS API for this in WP 7.0 — the underlying store + * action (`setCurrentRevisionId`) is registered as a private action and + * is gated behind `@wordpress/private-apis`, which only allows a hardcoded + * list of core module names to opt in. Calling it directly from a plugin + * throws, since the action is never attached to the public dispatch + * object. Simulating a real click on Core's own rendered button is the + * supported workaround. + * + * Elements are located by stable, locale-independent attributes rather + * than translated accessible names: the sidebar toggle uses + * `aria-controls="edit-post:document"`, which comes from the + * complementary area identifier `edit-post/document` registered by + * the WordPress editor package for the Document Settings sidebar, and + * is the same regardless of site language. + * + * Falls back to the classic revisions screen if the button can't be + * found within a short polling window (e.g. markup changes upstream, or + * the post genuinely has fewer than two revisions so Core doesn't render + * the button at all). + * + * @param root0 Options. + * @param root0.adminUrl Site admin URL, used for the classic + * revisions fallback. + * @param root0.lastRevisionId The revision ID to open. + */ +function openVisualRevisions( { + adminUrl, + lastRevisionId, +}: { + adminUrl: string | undefined; + lastRevisionId: number; +} ): void { + const MAX_ATTEMPTS = 20; + const INTERVAL_MS = 100; + + // The revisions button only exists in the DOM once the Document + // Settings sidebar is mounted, so open it first if it's collapsed. + const settingsToggle = document.querySelector< HTMLButtonElement >( + 'button[aria-controls="edit-post:document"]' + ); + if ( settingsToggle?.getAttribute( 'aria-expanded' ) === 'false' ) { + settingsToggle.click(); + } + + let attempts = 0; + const tryClick = () => { + const revisionsButton = document.querySelector< HTMLButtonElement >( + '.editor-private-post-last-revision__button, .editor-post-last-revision__title' + ); + if ( revisionsButton ) { + revisionsButton.click(); + return; + } + attempts++; + if ( attempts >= MAX_ATTEMPTS ) { + navigateToClassicRevisions( adminUrl, lastRevisionId ); + return; + } + setTimeout( tryClick, INTERVAL_MS ); + }; + tryClick(); +} + +/** + * Builds the snackbar action for reviewing changes in the revisions UI. + * + * Uses the in-editor visual revisions path (WP 7.0+ default) via + * openVisualRevisions(). Falls back to the classic revisions screen when + * visual revisions are disabled, e.g. when classic metaboxes are active + * on the post. + * + * @param root0 Options. + * @param root0.lastRevisionId The revision ID to open. + * @param root0.adminUrl Site admin URL, used for the + * classic revisions fallback. + * @param root0.disableVisualRevisions Whether Core has disabled visual + * revisions for this post. + * @return Snackbar notice actions, or an empty array when neither path + * is available. + */ +export function getRevisionReviewAction( { + lastRevisionId, + adminUrl, + disableVisualRevisions, +}: { + lastRevisionId: number; + adminUrl: string | undefined; + disableVisualRevisions: boolean; +} ): Array< { label: string; url?: string; onClick?: () => void } > { + if ( ! disableVisualRevisions ) { + return [ + { + label: __( 'Review in Revisions', 'ai' ), + onClick: () => + openVisualRevisions( { adminUrl, lastRevisionId } ), + }, + ]; + } + + if ( adminUrl ) { + return [ + { + label: __( 'Review in Revisions', 'ai' ), + url: `${ adminUrl }revision.php?revision=${ lastRevisionId }`, + }, + ]; + } + + return []; +} diff --git a/src/utils/notes.ts b/src/utils/notes.ts index db251db91..4ce0a706e 100644 --- a/src/utils/notes.ts +++ b/src/utils/notes.ts @@ -32,6 +32,10 @@ export interface ExistingNote { id: number; parent: number; content: { rendered: string }; + meta?: { + wpai_note?: boolean; + [ key: string ]: unknown; + }; [ key: string ]: unknown; } @@ -128,3 +132,91 @@ export function buildContextWindow( return `${ prefix }${ content.slice( start, end ) }${ suffix }`; } + +/** + * Normalizes block `metadata.noteId` to an array of unique positive Note IDs. + * + * @param metadata The block's metadata attribute. + * @param metadata.noteId The raw note ID or array of note IDs from the block's metadata. + * @return An array of Note IDs (may be empty). + */ +export function getNoteIds( metadata?: { noteId?: unknown } ): number[] { + const raw = metadata?.noteId; + const ids = ( Array.isArray( raw ) ? raw : [ raw ] ) + .map( Number ) + .filter( ( id ) => Number.isFinite( id ) && id > 0 ); + return [ ...new Set( ids ) ]; +} + +/** + * Checks whether block `metadata.noteId` is an array of Note IDs rather than a single ID. + * + * Older WordPress versions only support a single numeric `noteId`. Use this to keep that + * format when adding IDs (see `addNoteId()`) and to treat single-ID blocks as one thread. + * + * @param metadata The block's metadata attribute. + * @param metadata.noteId The raw note ID or array of note IDs from the block's metadata. + * @return True when `noteId` is an array. + */ +export function hasNoteIdList( metadata?: { noteId?: unknown } ): boolean { + return Array.isArray( metadata?.noteId ); +} + +/** + * Returns block metadata with a Note ID added, keeping the single-ID format + * unless the block already uses an array. + * + * @param metadata The block's metadata attribute. + * @param noteId The Note ID to add. + * @return The updated metadata object. + */ +export function addNoteId( + metadata: Record< string, unknown > = {}, + noteId: number +): Record< string, unknown > { + const ids = getNoteIds( metadata ); + + if ( ids.includes( noteId ) ) { + return metadata; + } + + return { + ...metadata, + noteId: hasNoteIdList( metadata ) ? [ ...ids, noteId ] : noteId, + }; +} + +/** + * Collects the root and reply texts of the given pending Note threads. + * + * @param noteIds The root Note IDs attached to the block. + * @param noteContentById Map of Note ID → rendered Note content (pending only). + * @param pendingNotes All pending Notes for the post. + * @return An array of Note texts, each root followed by its replies. + */ +export function collectThreadTexts( + noteIds: number[], + noteContentById: Map< number, string >, + pendingNotes: ExistingNote[] +): string[] { + const texts: string[] = []; + + for ( const id of noteIds ) { + const rootText = noteContentById.get( id ); + if ( rootText ) { + texts.push( rootText ); + } + + // Also collect replies (Notes with parent === id). + for ( const note of pendingNotes ) { + if ( note.parent === id ) { + const replyText = noteContentById.get( note.id ); + if ( replyText ) { + texts.push( replyText ); + } + } + } + } + + return texts; +}