Skip to content
31 changes: 21 additions & 10 deletions docs/experiments/editorial-notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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: <AI thread ID>` → 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

Expand Down Expand Up @@ -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
Expand All @@ -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
7 changes: 7 additions & 0 deletions docs/experiments/editorial-updates.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
186 changes: 9 additions & 177 deletions src/experiments/editorial-notes/hooks/useEditorialNotes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand All @@ -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.
*
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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 >();
Expand Down Expand Up @@ -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 },
} );
}
}
32 changes: 32 additions & 0 deletions src/experiments/editorial-notes/types/index.ts
Original file line number Diff line number Diff line change
@@ -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;
}
Loading
Loading