diff --git a/docs/DEVELOPER_GUIDE.md b/docs/DEVELOPER_GUIDE.md index 0ec7deb82..36f68e4d2 100644 --- a/docs/DEVELOPER_GUIDE.md +++ b/docs/DEVELOPER_GUIDE.md @@ -76,10 +76,37 @@ class My_Experiment extends Abstract_Feature { public function register(): void { // Register your hooks here add_action( 'init', array( $this, 'initialize' ) ); - add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); + add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) ); add_filter( 'the_content', array( $this, 'filter_content' ) ); } + /** + * Registers the experiment's UI hooks. + * + * Only runs for users allowed to use the experiment. + * + * @since x.x.x + */ + public function register_ui(): void { + add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); + } + + /** + * Registers the experiment's abilities. + * + * @since x.x.x + */ + public function register_abilities(): void { + $this->register_feature_ability( + 'my-plugin/my-ability', + array( + 'label' => __( 'My Ability', 'ai' ), + 'description' => __( 'Description of what my ability does.', 'ai' ), + 'ability_class' => My_Ability::class, // Your Abstract_Ability subclass. + ) + ); + } + /** * Initializes the experiment. * @@ -134,6 +161,14 @@ The optional `usage` key in `load_metadata()` tells site owners, in short phrase Keep the "At a Glance" section of the experiment's doc in `docs/experiments` in sync with these values. +#### Access Control + +`register()` is the only required method. `register_ui()` runs only for users allowed to use the feature, or for everyone when the feature does not opt in to access control. Put asset enqueues, columns, row or bulk actions, and admin menu items there. Abilities, meta, frontend output, cron, and REST routes stay in `register()`. + +Register your feature's abilities with `register_feature_ability()` so its access control settings apply wherever the ability runs. Abilities registered directly with `wp_register_ability()` are not tied to any feature. + +The optional `access_control` metadata key opts the feature in to access control settings. It is opt-in and defaults to `false`. Set `'access_control' => true` only once the feature registers its abilities with `register_feature_ability()` and its UI hooks in `register_ui()`. See [Access Controls](admin/access-controls.md). + If you want a complete end-to-end reference instead of a starter snippet, see the [Custom Experiment Reference](experiments/custom-experiment-reference.md). It points to the in-repo `Example_Experiment` implementation and shows a minimal third-party plugin example using the same extension points. ### Step 3: Register the Experiment @@ -196,6 +231,8 @@ class My_Experiment extends Abstract_Feature { } ``` +`register_ui()` runs separately from `register()`, so if your experiment also implements `register_ui()`, repeat the requirement check there. + ## Plugin API The plugin provides a set of hooks and filters to allow third-party developers to extend its functionality. diff --git a/docs/admin/access-controls.md b/docs/admin/access-controls.md new file mode 100644 index 000000000..69e03a4a2 --- /dev/null +++ b/docs/admin/access-controls.md @@ -0,0 +1,109 @@ +# Access Controls + +## Summary + +Access Controls let administrators limit each supported AI feature to chosen roles and specific users. A restriction applies wherever the feature's abilities run, not just in the plugin's own screens. Nothing changes for anyone until an administrator turns access control on for a feature **and saves**. + +## Overview + +### For End Users + +On the AI settings page (**Settings → AI**), open the **Developer Tools** menu (the wrench icon) and select **Access controls**. Each enabled feature that supports access control then shows: + +- **Enable access control**: turns the restriction on or off for that feature. +- **Roles**: one checkbox per role that has the `edit_posts` capability. **Administrator** and **Editor** are checked by default. +- **Users**: search for and add individual users. Listed users can always use the feature, whatever their role. +- **Save**: appears once you change something. Nothing is stored until you click it. + +When the **Access controls** view is turned off, a feature that is actually restricted shows "Access restricted to selected roles and users." so the restriction stays visible. Turning the view off never clears saved settings. + +### What changes, and when + +- **Access control off** (the default): access is identical to before. Anyone who passes the feature's normal permission checks can use it. +- **Turned on but not saved**: nothing is written, so access is still identical to before. +- **Turned on and saved**: only the checked roles and the listed users can use the feature. If you save without touching the defaults, Administrator and Editor are saved. That can be stricter than before. For example, Authors and Contributors lose access. +- **No roles checked and no users listed**: nobody can use the feature, including administrators. + +On multisite, super admins can always use every feature. + +Access control only ever adds a restriction. Each ability's own permission checks still apply, so adding a user here does not let them edit posts they otherwise could not. + +### Where the restriction applies + +The restriction applies to the feature's abilities on every path they run: + +- the plugin's own buttons and screens in wp-admin and the editor (users without access do not get the feature's UI); +- the Abilities REST API (`/wp-abilities/v1/abilities/{name}/run`); +- MCP over HTTP; +- `runAbility()` in JavaScript, and server-side calls to `wp_get_ability()->execute()`; +- abilities one feature calls from another. For example, alt text generated during Image Generation is checked against the Alt Text Generation feature's settings; +- Text to Speech's own REST routes (`/ai/v1/text-to-speech/{id}`), which are not abilities but check the same capability. + +A user without access gets a `wpai_feature_access_denied` error (HTTP 401 when logged out, 403 when logged in). + +**Automatic runs are not affected.** Work the feature does on its own, without a user asking, carries on whatever the access settings say. For example, Comment Moderation still analyses new comments, and Text to Speech jobs that are already queued still finish. + +**WP-CLI without `--user` is not restricted.** Commands run through WP-CLI without `--user` bypass access control. With an explicit `--user`, the restriction applies to that user, so `wp mcp-adapter serve --user=bob` respects Bob's access. This includes MCP over STDIO, which runs through WP-CLI. + +### Which features support it + +Only features whose `access_control` metadata is `true` show these controls. Access control is opt-in. Every built-in feature outside the **Admin** category opts in, and so do Comment Moderation and Suggest Reply. Other admin features already require `manage_options`. Third-party features must set `'access_control' => true` to opt in. + +### Settings export and import + +Access control settings are **not** included in [settings export and import](settings-import-export.md). Role slugs and user IDs differ between sites, so configure access controls on each site directly. + +## Stored options + +Each supported feature stores three options, registered in their own option group (`ai_experiments_access`) and exposed through the core `/wp/v2/settings` endpoint: + +| Option | Type | Default | +|---|---|---| +| `wpai_feature__access_control_enabled` | boolean | `false` | +| `wpai_feature__roles` | list of role slugs | unset, meaning no role restriction | +| `wpai_feature__users` | list of user IDs | `[]` | + +An unset roles option is different from an empty list. Unset means "no restriction yet". A saved empty list means "no role has access". + +## For Developers + +### The `wpai_use_feature` capability + +Access is decided by the `wpai_use_feature` meta capability, with the feature ID as its argument: + +```php +if ( current_user_can( 'wpai_use_feature', 'title-generation' ) ) { + // The current user may use Title Generation. +} +``` + +The plugin maps it to `exist` (allowed) or `do_not_allow` (denied) in a `map_meta_cap` filter at priority 10. The recommended way to extend the check is your own `map_meta_cap` filter at a later priority that adds a requirement to the plugin's result. The following example also requires `publish_posts` for Title Generation. The admin's role and user settings stay in force, so a user must pass both: + +```php +add_filter( + 'map_meta_cap', + static function ( array $caps, string $cap, int $user_id, array $args ): array { + if ( 'wpai_use_feature' === $cap && 'title-generation' === ( $args[0] ?? '' ) ) { + // Also require publish_posts, on top of the access control settings. + $caps[] = 'publish_posts'; + } + return $caps; + }, + 20, + 4 +); +``` + +Run your filter after priority 10 so it sees the plugin's result. Append to `$caps` rather than replacing it: returning a new array discards the plugin's decision. + +The `user_has_cap` filter also works, but it only sees the primitive `exist` or `do_not_allow` result, not the roles and users behind it. Core never grants `do_not_allow`, so `user_has_cap` is mainly useful for denying access. + +### Linking abilities to features + +Features register their abilities with `Abstract_Feature::register_feature_ability()`. It adds the feature ID to the ability's `wpai_feature` meta key and then calls `wp_register_ability()`. The plugin checks `wpai_use_feature` for that feature whenever an ability with this meta key runs. + +Abilities registered directly with `wp_register_ability()` are not tied to any feature, so only their own `permission_callback` applies. `register_feature_ability()` adds the meta key only for features that opt in with `'access_control' => true`. + +On WordPress 7.0.x, the check applies only to abilities whose class extends `Abstract_Ability`, because the core `wp_ability_permission_result` filter arrives in WordPress 7.1. + +Feature UI that should be hidden from users without access belongs in `register_ui()`. See the [Developer Guide](../DEVELOPER_GUIDE.md). diff --git a/docs/experiments/custom-experiment-reference.md b/docs/experiments/custom-experiment-reference.md index 92d0c8fd9..66925ee30 100644 --- a/docs/experiments/custom-experiment-reference.md +++ b/docs/experiments/custom-experiment-reference.md @@ -9,7 +9,7 @@ The example is intentionally small and uses the same APIs and patterns as the pl - Creating a feature class by extending `Abstract_Feature` - Registering the experiment with the AI plugin - Adding metadata such as the label, description, and category -- Hooking into WordPress actions and filters in `register()` +- Hooking into WordPress actions and filters in `register()`, and user-facing hooks in `register_ui()` - Disabling the experiment with the standard feature filters ## Reference Class @@ -52,6 +52,10 @@ class My_Experiment extends Abstract_Feature { } public function register(): void { + // Abilities, meta, frontend output, cron, and REST routes go here. + } + + public function register_ui(): void { add_action( 'admin_notices', array( $this, 'render_notice' ) ); } @@ -78,7 +82,10 @@ add_action( - `Abstract_Feature` provides the shared experiment lifecycle used throughout the plugin. - `load_metadata()` keeps labels and descriptions in one place, matching built-in experiments. -- `register()` is where the experiment attaches behavior through WordPress hooks. +- `register()` is the required method where the experiment attaches behavior through WordPress hooks. +- `register_ui()` runs only for users allowed to use the feature, or for everyone when the feature does not opt in to access control. Put asset enqueues, columns, row or bulk actions, and admin menu items there. Abilities, meta, frontend output, cron, and REST routes stay in `register()`. +- Register your feature's abilities with `register_feature_ability()` so its access control settings apply wherever the ability runs. Abilities registered directly with `wp_register_ability()` are not tied to any feature. +- The optional `access_control` metadata key opts the feature in to [access control settings](../admin/access-controls.md). It is opt-in and defaults to `false`, so this example does not opt in. Set `'access_control' => true` only once the feature registers its abilities with `register_feature_ability()` and its UI hooks in `register_ui()`. - `wpai_register_features` is the safest entry point for third-party plugins because it registers your feature after the plugin sets up its registry. ## Alternative Registration Method diff --git a/includes/Abstracts/Abstract_Ability.php b/includes/Abstracts/Abstract_Ability.php index d1331205a..0ce238cec 100644 --- a/includes/Abstracts/Abstract_Ability.php +++ b/includes/Abstracts/Abstract_Ability.php @@ -106,6 +106,31 @@ abstract protected function execute_callback( $input ); */ abstract protected function permission_callback( $input ); + /** + * {@inheritDoc} + * + * Back-fills the core `wp_ability_permission_result` filter on WordPress + * versions that predate it (< 7.1), so authorization layers hooked to it + * apply on every supported version. Remove once the minimum is 7.1. + * + * @since x.x.x + * + * @param mixed $input Optional. The input data for permission checking. + * @return bool|\WP_Error Whether the ability has the necessary permission. + */ + public function check_permissions( $input = null ) { + $result = parent::check_permissions( $input ); + + if ( version_compare( get_bloginfo( 'version' ), '7.1-alpha', '>=' ) ) { + return $result; + } + + /** This filter is documented in wp-includes/abilities-api/class-wp-ability.php */ + $filtered = apply_filters( 'wp_ability_permission_result', $result, $this->get_name(), $input, $this ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Back-fills the core hook on WordPress < 7.1. + + return is_bool( $filtered ) || is_wp_error( $filtered ) ? $filtered : false; + } + /** * Returns the meta of the ability. * diff --git a/includes/Abstracts/Abstract_Feature.php b/includes/Abstracts/Abstract_Feature.php index 92fc9149e..4bb1bac59 100644 --- a/includes/Abstracts/Abstract_Feature.php +++ b/includes/Abstracts/Abstract_Feature.php @@ -10,6 +10,8 @@ namespace WordPress\AI\Abstracts; use InvalidArgumentException; +use WP_Ability; +use WordPress\AI\Access_Control\Feature_Access; use WordPress\AI\Contracts\Feature; use WordPress\AI\Features\Feature_Category; @@ -91,6 +93,14 @@ abstract class Abstract_Feature implements Feature { */ private array $usage; + /** + * Whether per-feature access control applies to this feature. + * + * @since x.x.x + * @var bool + */ + private bool $access_control; + /** * Constructor. * @@ -132,6 +142,8 @@ final public function __construct() { $this->image = $metadata['image'] ?? ''; $this->capability = $metadata['capability'] ?? 'text_generation'; $this->usage = self::normalize_usage( $metadata['usage'] ?? array() ); + + $this->access_control = (bool) ( $metadata['access_control'] ?? false ); } /** @@ -165,7 +177,7 @@ private static function normalize_usage( $usage ): array { * Loads feature metadata. * * Must return an array with keys: label, description. - * Optionally includes: category, stability, image, capability, usage. + * Optionally includes: category, stability, image, capability, usage, access_control. * * The `usage` key summarizes, in short user-facing phrases, when the * feature runs, what it sends to the AI provider, and how many requests @@ -175,8 +187,14 @@ private static function normalize_usage( $usage ): array { * Features that make no AI requests can set `details` instead of * `requests` to describe what they store or change. * + * The `access_control` key opts the feature in to per-feature role/user + * access control. It is opt-in and defaults to false. A feature should + * opt in only once it registers its abilities with + * register_feature_ability() and its UI hooks in register_ui(). + * * @since 0.6.0 * @since 1.5.0 Added the `usage` key. + * @since x.x.x Added the `access_control` key. * * @return array{ * label: string, @@ -185,6 +203,7 @@ private static function normalize_usage( $usage ): array { * stability?: 'deprecated'|'experimental'|'stable', * image?: string, * capability?: string, + * access_control?: bool, * usage?: array{ * trigger?: 'automatic'|'on_demand'|'none', * runs?: string, @@ -399,6 +418,47 @@ final public static function get_field_option_name( string $option_name ): strin return 'wpai_feature_' . static::get_id() . '_field_' . $option_name; } + /** + * Checks whether per-feature access control applies to this feature. + * + * @since x.x.x + * + * @return bool True if admins can restrict this feature to roles and users. + */ + public function supports_access_control(): bool { + return $this->access_control; + } + + /** + * Registers user-facing hooks: asset enqueues, list table columns, row and + * bulk actions, admin menu items. + * + * @since x.x.x + */ + public function register_ui(): void { + // No-op by default. + } + + /** + * Registers an ability owned by this feature. + * + * @since x.x.x + * + * @param lowercase-string&non-falsy-string $name The ability name, with namespace. + * @param array $args The ability registration args. + * @return \WP_Ability|null The registered ability, or null on failure. + */ + protected function register_feature_ability( string $name, array $args ): ?WP_Ability { + if ( $this->supports_access_control() ) { + $meta = isset( $args['meta'] ) && is_array( $args['meta'] ) ? $args['meta'] : array(); + + $meta[ Feature_Access::ABILITY_META_KEY ] = static::get_id(); + $args['meta'] = $meta; + } + + return wp_register_ability( $name, $args ); + } + /** * {@inheritDoc} * diff --git a/includes/Access_Control/Feature_Access.php b/includes/Access_Control/Feature_Access.php new file mode 100644 index 000000000..cffd11529 --- /dev/null +++ b/includes/Access_Control/Feature_Access.php @@ -0,0 +1,189 @@ + $caps Primitive capabilities required. + * @param string $cap Capability being checked. + * @param int $user_id User ID. + * @param array $args Extra arguments; `$args[0]` is the feature ID. + * @return list Primitive capabilities required. + */ + public function map_meta_cap( $caps, $cap, $user_id, $args ): array { + if ( self::CAPABILITY !== $cap ) { + return (array) $caps; + } + + $feature_id = isset( $args[0] ) && is_string( $args[0] ) ? $args[0] : ''; + if ( '' === $feature_id ) { + return array( 'do_not_allow' ); + } + + return self::user_can_use_feature( (int) $user_id, $feature_id ) ? array( 'exist' ) : array( 'do_not_allow' ); + } + + /** + * Checks whether a user may use a feature under its access control settings. + * + * @since x.x.x + * + * @param int $user_id The user ID (0 for logged out). + * @param string $feature_id The feature ID. + * @return bool True if the user may use the feature. + */ + public static function user_can_use_feature( int $user_id, string $feature_id ): bool { + if ( defined( 'WP_CLI' ) && WP_CLI && class_exists( '\WP_CLI' ) && empty( \WP_CLI::get_config( 'user' ) ) ) { + return true; + } + + if ( ! (bool) get_option( self::enabled_option( $feature_id ), false ) ) { + return true; + } + + // Unset roles mean "no role restriction". + // The explicit null default bypasses the registered setting default. + $roles = get_option( self::roles_option( $feature_id ), null ); + if ( null === $roles ) { + return true; + } + + if ( $user_id > 0 && is_multisite() && is_super_admin( $user_id ) ) { + return true; + } + + $users = get_option( self::users_option( $feature_id ), array() ); + if ( $user_id > 0 && is_array( $users ) && in_array( $user_id, array_map( 'intval', $users ), true ) ) { + return true; + } + + $user = $user_id > 0 ? get_userdata( $user_id ) : false; + if ( ! $user ) { + return false; + } + + return is_array( $roles ) && array() !== array_intersect( (array) $user->roles, $roles ); + } + + /** + * Denies tagged abilities to users without access to the owning feature. + * + * @since x.x.x + * + * @param bool|\WP_Error $result Permission result so far. + * @param string $ability_name The ability name. + * @param mixed $input The ability input. + * @param mixed $ability The ability instance. + * @return bool|\WP_Error The permission result. + */ + public function filter_ability_permission( $result, $ability_name, $input, $ability ) { + if ( true !== $result || ! $ability instanceof WP_Ability ) { + return $result; + } + + $feature_id = $ability->get_meta_item( self::ABILITY_META_KEY ); + if ( ! is_string( $feature_id ) || '' === $feature_id ) { + return $result; + } + + if ( current_user_can( self::CAPABILITY, $feature_id ) ) { // phpcs:ignore WordPress.WP.Capabilities.Undetermined -- Plugin meta capability, mapped in map_meta_cap(). + return $result; + } + + return new WP_Error( + 'wpai_feature_access_denied', + __( 'You do not have permission to use this feature.', 'ai' ), + array( 'status' => rest_authorization_required_code() ) + ); + } +} diff --git a/includes/Experiments/Alt_Text_Generation/Alt_Text_Generation.php b/includes/Experiments/Alt_Text_Generation/Alt_Text_Generation.php index c7315974b..6f804e4d8 100644 --- a/includes/Experiments/Alt_Text_Generation/Alt_Text_Generation.php +++ b/includes/Experiments/Alt_Text_Generation/Alt_Text_Generation.php @@ -68,11 +68,12 @@ public static function get_id(): string { */ protected function load_metadata(): array { return array( - 'label' => __( 'Alt Text Generation', 'ai' ), - 'description' => __( 'Generates accessible alternative (alt) text for images using AI vision models, following common web accessibility guidance. Requires an AI connector that includes support for vision-based image analysis models.', 'ai' ), - 'category' => Experiment_Category::EDITOR, - 'capability' => 'vision', - 'usage' => array( + 'label' => __( 'Alt Text Generation', 'ai' ), + 'description' => __( 'Generates accessible alternative (alt) text for images using AI vision models, following common web accessibility guidance. Requires an AI connector that includes support for vision-based image analysis models.', 'ai' ), + 'category' => Experiment_Category::EDITOR, + 'access_control' => true, + 'capability' => 'vision', + 'usage' => array( 'trigger' => 'on_demand', 'runs' => __( 'When you click Generate Alt Text or run the bulk action, and automatically when you import an image made with Image Generation', 'ai' ), 'sends' => __( 'The image, plus post content when used in the editor', 'ai' ), @@ -86,6 +87,20 @@ protected function load_metadata(): array { */ public function register(): void { add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) ); + + if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) { + return; + } + + \WP_CLI::add_command( 'ai alt-text', Alt_Text_Command::class ); + } + + /** + * {@inheritDoc} + * + * @since x.x.x + */ + public function register_ui(): void { add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_editor_assets' ) ); add_action( 'wp_enqueue_media', array( $this, 'enqueue_media_frame_assets' ) ); add_action( 'admin_enqueue_scripts', array( $this, 'maybe_enqueue_media_library_assets' ) ); @@ -94,12 +109,6 @@ public function register(): void { add_filter( 'bulk_actions-upload', array( $this, 'register_bulk_action' ) ); add_filter( 'handle_bulk_actions-upload', array( $this, 'handle_bulk_action' ), 10, 3 ); add_filter( 'removable_query_args', array( $this, 'register_removable_query_args' ) ); - - if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) { - return; - } - - \WP_CLI::add_command( 'ai alt-text', Alt_Text_Command::class ); } /** @@ -108,7 +117,7 @@ public function register(): void { * @since 0.3.0 */ public function register_abilities(): void { - wp_register_ability( + $this->register_feature_ability( 'ai/' . self::get_id(), array( 'label' => $this->get_label(), diff --git a/includes/Experiments/Block_Container_Label_Generation/Block_Container_Label_Generation.php b/includes/Experiments/Block_Container_Label_Generation/Block_Container_Label_Generation.php index 0d1fcfbed..f8fab1418 100644 --- a/includes/Experiments/Block_Container_Label_Generation/Block_Container_Label_Generation.php +++ b/includes/Experiments/Block_Container_Label_Generation/Block_Container_Label_Generation.php @@ -44,10 +44,11 @@ public static function get_id(): string { */ protected function load_metadata(): array { return array( - 'label' => __( 'Block Container Label Generation', 'ai' ), - 'description' => __( 'Generate concise labels for content blocks. Requires an AI connector that includes support for text generation models.', 'ai' ), - 'category' => Experiment_Category::EDITOR, - 'usage' => array( + 'label' => __( 'Block Container Label Generation', 'ai' ), + 'description' => __( 'Generate concise labels for content blocks. Requires an AI connector that includes support for text generation models.', 'ai' ), + 'category' => Experiment_Category::EDITOR, + 'access_control' => true, + 'usage' => array( 'trigger' => 'on_demand', 'runs' => __( 'When you click Generate Block Labels in List View or Generate label in the Rename modal', 'ai' ), 'sends' => __( 'The text of each container block and its inner blocks, the post title, and a short outline of the other container blocks and their labels', 'ai' ), @@ -63,6 +64,14 @@ protected function load_metadata(): array { */ public function register(): void { add_action( 'wp_abilities_api_init', array( $this, 'register_ability' ) ); + } + + /** + * {@inheritDoc} + * + * @since x.x.x + */ + public function register_ui(): void { add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); } @@ -72,7 +81,7 @@ public function register(): void { * @since 1.5.0 */ public function register_ability(): void { - wp_register_ability( + $this->register_feature_ability( sprintf( 'ai/%s', $this->get_id() ), array( 'label' => $this->get_label(), diff --git a/includes/Experiments/Comment_Moderation/Comment_Moderation.php b/includes/Experiments/Comment_Moderation/Comment_Moderation.php index 79029694d..439167787 100644 --- a/includes/Experiments/Comment_Moderation/Comment_Moderation.php +++ b/includes/Experiments/Comment_Moderation/Comment_Moderation.php @@ -301,10 +301,11 @@ public static function get_id(): string { */ protected function load_metadata(): array { return array( - 'label' => __( 'Comment Moderation', 'ai' ), - 'description' => __( 'Automatically moderate comments based on toxicity detection and sentiment analysis and give each comment a value score. Requires an AI connector that includes support for text generation models.', 'ai' ), - 'category' => Experiment_Category::ADMIN, - 'usage' => array( + 'label' => __( 'Comment Moderation', 'ai' ), + 'description' => __( 'Automatically moderate comments based on toxicity detection and sentiment analysis and give each comment a value score. Requires an AI connector that includes support for text generation models.', 'ai' ), + 'category' => Experiment_Category::ADMIN, + 'access_control' => true, + 'usage' => array( 'trigger' => 'automatic', 'runs' => __( 'Automatically, on each new comment, including guest comments by default. You can also run it from the "Analyze Sentiment, Toxicity, and Value" row action or bulk action in Comments', 'ai' ), 'sends' => __( 'Comment text, author name, and a post excerpt', 'ai' ), @@ -324,7 +325,14 @@ public function register(): void { // Moderate new comments. add_action( 'wp_insert_comment', array( $this, 'moderate_comment' ) ); + } + /** + * {@inheritDoc} + * + * @since x.x.x + */ + public function register_ui(): void { // Add columns to comments list table. add_filter( 'manage_edit-comments_columns', array( $this, 'add_columns' ) ); add_action( 'manage_comments_custom_column', array( $this, 'render_column' ), 10, 2 ); @@ -364,7 +372,7 @@ public function register(): void { * @since 0.9.0 */ public function register_abilities(): void { - wp_register_ability( + $this->register_feature_ability( 'ai/comment-analysis', array( 'label' => __( 'Comment Analysis', 'ai' ), diff --git a/includes/Experiments/Content_Classification/Content_Classification.php b/includes/Experiments/Content_Classification/Content_Classification.php index c95db13b6..7a1bd4837 100644 --- a/includes/Experiments/Content_Classification/Content_Classification.php +++ b/includes/Experiments/Content_Classification/Content_Classification.php @@ -88,10 +88,11 @@ public static function get_id(): string { */ protected function load_metadata(): array { return array( - 'label' => __( 'Content Classification', 'ai' ), - 'description' => __( 'AI-powered suggestions for post tags and categories based on content analysis. Requires an AI connector that includes support for text generation models.', 'ai' ), - 'category' => Experiment_Category::EDITOR, - 'usage' => array( + 'label' => __( 'Content Classification', 'ai' ), + 'description' => __( 'AI-powered suggestions for post tags and categories based on content analysis. Requires an AI connector that includes support for text generation models.', 'ai' ), + 'category' => Experiment_Category::EDITOR, + 'access_control' => true, + 'usage' => array( 'trigger' => 'on_demand', 'runs' => __( 'When you click Suggest Tags or Suggest Categories', 'ai' ), 'sends' => __( 'Post content, title, slug, author name, excerpt, content type, the terms already assigned, and up to 100 existing terms to choose from', 'ai' ), @@ -105,6 +106,14 @@ protected function load_metadata(): array { */ public function register(): void { add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) ); + } + + /** + * {@inheritDoc} + * + * @since x.x.x + */ + public function register_ui(): void { add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); } @@ -114,7 +123,7 @@ public function register(): void { * @since 0.7.0 */ public function register_abilities(): void { - wp_register_ability( + $this->register_feature_ability( 'ai/' . $this->get_id(), array( 'label' => $this->get_label(), diff --git a/includes/Experiments/Content_Gap_Suggestions/Content_Gap_Suggestions.php b/includes/Experiments/Content_Gap_Suggestions/Content_Gap_Suggestions.php index 55f9d7307..12166257a 100644 --- a/includes/Experiments/Content_Gap_Suggestions/Content_Gap_Suggestions.php +++ b/includes/Experiments/Content_Gap_Suggestions/Content_Gap_Suggestions.php @@ -61,6 +61,14 @@ protected function load_metadata(): array { */ public function register(): void { add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) ); + } + + /** + * {@inheritDoc} + * + * @since x.x.x + */ + public function register_ui(): void { add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); } @@ -70,7 +78,7 @@ public function register(): void { * @since x.x.x */ public function register_abilities(): void { - wp_register_ability( + $this->register_feature_ability( 'ai/' . $this->get_id(), array( 'label' => $this->get_label(), diff --git a/includes/Experiments/Content_Resizing/Content_Resizing.php b/includes/Experiments/Content_Resizing/Content_Resizing.php index 432365b2d..bed416ed8 100644 --- a/includes/Experiments/Content_Resizing/Content_Resizing.php +++ b/includes/Experiments/Content_Resizing/Content_Resizing.php @@ -40,10 +40,11 @@ public static function get_id(): string { */ protected function load_metadata(): array { return array( - 'label' => __( 'Content Resizing', 'ai' ), - 'description' => __( 'Shorten, expand, or rephrase selected block content. Requires an AI connector that includes support for text generation models.', 'ai' ), - 'category' => Experiment_Category::EDITOR, - 'usage' => array( + 'label' => __( 'Content Resizing', 'ai' ), + 'description' => __( 'Shorten, expand, or rephrase selected block content. Requires an AI connector that includes support for text generation models.', 'ai' ), + 'category' => Experiment_Category::EDITOR, + 'access_control' => true, + 'usage' => array( 'trigger' => 'on_demand', 'runs' => __( 'When you choose Shorten, Expand, or Rephrase', 'ai' ), 'sends' => __( 'The selected paragraph', 'ai' ), @@ -57,6 +58,14 @@ protected function load_metadata(): array { */ public function register(): void { add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) ); + } + + /** + * {@inheritDoc} + * + * @since x.x.x + */ + public function register_ui(): void { add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); } @@ -66,7 +75,7 @@ public function register(): void { * @since 0.9.0 */ public function register_abilities(): void { - wp_register_ability( + $this->register_feature_ability( 'ai/' . $this->get_id(), array( 'label' => $this->get_label(), diff --git a/includes/Experiments/Content_Translation/Content_Translation.php b/includes/Experiments/Content_Translation/Content_Translation.php index 7ea0f51fc..b3bb5689a 100644 --- a/includes/Experiments/Content_Translation/Content_Translation.php +++ b/includes/Experiments/Content_Translation/Content_Translation.php @@ -43,10 +43,11 @@ public static function get_id(): string { */ protected function load_metadata(): array { return array( - 'label' => __( 'Content Translation', 'ai' ), - 'description' => __( 'Translate the text of your blocks into a different language. Requires an AI connector that includes support for text generation models.', 'ai' ), - 'category' => Experiment_Category::EDITOR, - 'usage' => array( + 'label' => __( 'Content Translation', 'ai' ), + 'description' => __( 'Translate the text of your blocks into a different language. Requires an AI connector that includes support for text generation models.', 'ai' ), + 'category' => Experiment_Category::EDITOR, + 'access_control' => true, + 'usage' => array( 'trigger' => 'on_demand', 'runs' => __( 'When you click Translate', 'ai' ), 'sends' => __( 'Each paragraph and heading block, and optionally the title', 'ai' ), @@ -62,17 +63,25 @@ protected function load_metadata(): array { */ public function register(): void { add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) ); - add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); add_action( 'enqueue_block_assets', array( $this, 'enqueue_block_assets' ) ); } + /** + * {@inheritDoc} + * + * @since x.x.x + */ + public function register_ui(): void { + add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); + } + /** * Registers required abilities. * * @since 1.3.0 */ public function register_abilities(): void { - wp_register_ability( + $this->register_feature_ability( sprintf( 'ai/%s', $this->get_id() ), array( 'label' => $this->get_label(), diff --git a/includes/Experiments/Editorial_Notes/Editorial_Notes.php b/includes/Experiments/Editorial_Notes/Editorial_Notes.php index 9f2f78dcb..6baa3d7b0 100644 --- a/includes/Experiments/Editorial_Notes/Editorial_Notes.php +++ b/includes/Experiments/Editorial_Notes/Editorial_Notes.php @@ -43,10 +43,11 @@ public static function get_id(): string { */ protected function load_metadata(): array { return array( - 'label' => __( 'Editorial Notes', 'ai' ), - 'description' => __( 'Adds editorial suggestions to posts block-by-block, covering Accessibility, Readability, Grammar, and SEO. Requires an AI connector that includes support for text generation models.', 'ai' ), - 'category' => Experiment_Category::EDITOR, - 'usage' => array( + 'label' => __( 'Editorial Notes', 'ai' ), + 'description' => __( 'Adds editorial suggestions to posts block-by-block, covering Accessibility, Readability, Grammar, and SEO. Requires an AI connector that includes support for text generation models.', 'ai' ), + 'category' => Experiment_Category::EDITOR, + 'access_control' => true, + 'usage' => array( 'trigger' => 'on_demand', 'runs' => __( 'When you click Generate Editorial Notes', 'ai' ), 'sends' => __( 'Each block\'s text with surrounding content', 'ai' ), @@ -60,7 +61,6 @@ protected function load_metadata(): array { */ public function register(): void { add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) ); - add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_assets' ) ); add_filter( 'rest_pre_insert_comment', array( $this, 'maybe_set_ai_author' ), 10, 2 ); register_meta( @@ -83,13 +83,22 @@ public function register(): void { ); } + /** + * {@inheritDoc} + * + * @since x.x.x + */ + public function register_ui(): void { + add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_assets' ) ); + } + /** * Registers any needed abilities. * * @since 0.4.0 */ public function register_abilities(): void { - wp_register_ability( + $this->register_feature_ability( 'ai/' . $this->get_id(), array( 'label' => $this->get_label(), diff --git a/includes/Experiments/Editorial_Updates/Editorial_Updates.php b/includes/Experiments/Editorial_Updates/Editorial_Updates.php index f3acd6e9f..fb4904cc3 100644 --- a/includes/Experiments/Editorial_Updates/Editorial_Updates.php +++ b/includes/Experiments/Editorial_Updates/Editorial_Updates.php @@ -43,10 +43,11 @@ public static function get_id(): string { */ protected function load_metadata(): array { return array( - 'label' => __( 'Editorial Updates', 'ai' ), - 'description' => __( 'Applies pending editorial Notes to your content and saves the post, without a preview. Use revisions to review or undo the changes. Requires an AI connector that includes support for text generation models.', 'ai' ), - 'category' => Experiment_Category::EDITOR, - 'usage' => array( + 'label' => __( 'Editorial Updates', 'ai' ), + 'description' => __( 'Applies pending editorial Notes to your content and saves the post, without a preview. Use revisions to review or undo the changes. Requires an AI connector that includes support for text generation models.', 'ai' ), + 'category' => Experiment_Category::EDITOR, + 'access_control' => true, + 'usage' => array( 'trigger' => 'on_demand', 'runs' => __( 'When you click Apply Editorial Updates, which also saves the post', 'ai' ), 'sends' => __( 'Each block with pending Notes, with surrounding content', 'ai' ), @@ -62,6 +63,14 @@ protected function load_metadata(): array { */ public function register(): void { add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) ); + } + + /** + * {@inheritDoc} + * + * @since x.x.x + */ + public function register_ui(): void { add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_assets' ) ); } @@ -71,7 +80,7 @@ public function register(): void { * @since 0.8.0 */ public function register_abilities(): void { - wp_register_ability( + $this->register_feature_ability( 'ai/' . $this->get_id(), array( 'label' => $this->get_label(), diff --git a/includes/Experiments/Excerpt_Generation/Excerpt_Generation.php b/includes/Experiments/Excerpt_Generation/Excerpt_Generation.php index b549cee5d..adbed7c59 100644 --- a/includes/Experiments/Excerpt_Generation/Excerpt_Generation.php +++ b/includes/Experiments/Excerpt_Generation/Excerpt_Generation.php @@ -46,10 +46,11 @@ public static function get_id(): string { */ protected function load_metadata(): array { return array( - 'label' => __( 'Excerpt Generation', 'ai' ), - 'description' => __( 'Generates excerpt suggestions from content. Requires an AI connector that includes support for text generation models.', 'ai' ), - 'category' => Experiment_Category::EDITOR, - 'usage' => array( + 'label' => __( 'Excerpt Generation', 'ai' ), + 'description' => __( 'Generates excerpt suggestions from content. Requires an AI connector that includes support for text generation models.', 'ai' ), + 'category' => Experiment_Category::EDITOR, + 'access_control' => true, + 'usage' => array( 'trigger' => 'on_demand', 'runs' => __( 'When you click Generate excerpt', 'ai' ), 'sends' => __( 'Post content, title, slug, author name, excerpt, content type, and assigned categories and tags', 'ai' ), @@ -63,6 +64,14 @@ protected function load_metadata(): array { */ public function register(): void { add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) ); + } + + /** + * {@inheritDoc} + * + * @since x.x.x + */ + public function register_ui(): void { add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); add_action( 'wp_entity_fields_api_init', array( $this, 'update_excerpt_field' ) ); } @@ -73,7 +82,7 @@ public function register(): void { * @since 0.2.0 */ public function register_abilities(): void { - wp_register_ability( + $this->register_feature_ability( 'ai/' . $this->get_id(), array( 'label' => $this->get_label(), diff --git a/includes/Experiments/Meta_Description/Meta_Description.php b/includes/Experiments/Meta_Description/Meta_Description.php index b8bf03946..7cf6ec955 100644 --- a/includes/Experiments/Meta_Description/Meta_Description.php +++ b/includes/Experiments/Meta_Description/Meta_Description.php @@ -43,10 +43,11 @@ public static function get_id(): string { */ protected function load_metadata(): array { return array( - 'label' => __( 'Meta Description Generation', 'ai' ), - 'description' => __( 'Generates meta description suggestions and integrates those with various SEO plugins. Requires an AI connector that includes support for text generation models.', 'ai' ), - 'category' => Experiment_Category::EDITOR, - 'usage' => array( + 'label' => __( 'Meta Description Generation', 'ai' ), + 'description' => __( 'Generates meta description suggestions and integrates those with various SEO plugins. Requires an AI connector that includes support for text generation models.', 'ai' ), + 'category' => Experiment_Category::EDITOR, + 'access_control' => true, + 'usage' => array( 'trigger' => 'on_demand', 'runs' => __( 'When you click Generate Meta Description', 'ai' ), 'sends' => __( 'Post content, title, slug, author name, excerpt, content type, and assigned categories and tags', 'ai' ), @@ -62,19 +63,27 @@ protected function load_metadata(): array { */ public function register(): void { add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) ); - add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); $this->maybe_output_meta_description(); $this->register_post_meta(); } + /** + * {@inheritDoc} + * + * @since x.x.x + */ + public function register_ui(): void { + add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); + } + /** * Registers the meta description ability. * * @since 0.7.0 */ public function register_abilities(): void { - wp_register_ability( + $this->register_feature_ability( 'ai/' . $this->get_id(), array( 'label' => $this->get_label(), diff --git a/includes/Experiments/Revision_Change_Summary/Revision_Change_Summary.php b/includes/Experiments/Revision_Change_Summary/Revision_Change_Summary.php index 27f040f2c..3ff962184 100644 --- a/includes/Experiments/Revision_Change_Summary/Revision_Change_Summary.php +++ b/includes/Experiments/Revision_Change_Summary/Revision_Change_Summary.php @@ -41,10 +41,11 @@ public static function get_id(): string { */ protected function load_metadata(): array { return array( - 'label' => __( 'Revision Change Summary', 'ai' ), - 'description' => __( 'Summarizes what changed between two revisions of a post in plain language. Requires an AI connector that includes support for text generation models.', 'ai' ), - 'category' => Experiment_Category::EDITOR, - 'usage' => array( + 'label' => __( 'Revision Change Summary', 'ai' ), + 'description' => __( 'Summarizes what changed between two revisions of a post in plain language. Requires an AI connector that includes support for text generation models.', 'ai' ), + 'category' => Experiment_Category::EDITOR, + 'access_control' => true, + 'usage' => array( 'trigger' => 'on_demand', 'runs' => __( 'When you click Summarize changes on a revisions screen', 'ai' ), 'sends' => __( 'The changed lines of the title and content between the two revisions', 'ai' ), @@ -58,6 +59,14 @@ protected function load_metadata(): array { */ public function register(): void { add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) ); + } + + /** + * {@inheritDoc} + * + * @since x.x.x + */ + public function register_ui(): void { add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_assets' ) ); add_action( 'admin_enqueue_scripts', array( $this, 'maybe_enqueue_classic_assets' ) ); } @@ -68,7 +77,7 @@ public function register(): void { * @since 1.5.0 */ public function register_abilities(): void { - wp_register_ability( + $this->register_feature_ability( 'ai/' . $this->get_id(), array( 'label' => $this->get_label(), diff --git a/includes/Experiments/Slug_Generation/Slug_Generation.php b/includes/Experiments/Slug_Generation/Slug_Generation.php index 91abafe72..e6060f5cf 100644 --- a/includes/Experiments/Slug_Generation/Slug_Generation.php +++ b/includes/Experiments/Slug_Generation/Slug_Generation.php @@ -43,10 +43,11 @@ public static function get_id(): string { */ protected function load_metadata(): array { return array( - 'label' => __( 'Slug Generation', 'ai' ), - 'description' => __( 'Suggests SEO-friendly permalink slugs from post title or content. Requires an AI connector that includes support for text generation models.', 'ai' ), - 'category' => Experiment_Category::EDITOR, - 'usage' => array( + 'label' => __( 'Slug Generation', 'ai' ), + 'description' => __( 'Suggests SEO-friendly permalink slugs from post title or content. Requires an AI connector that includes support for text generation models.', 'ai' ), + 'category' => Experiment_Category::EDITOR, + 'access_control' => true, + 'usage' => array( 'trigger' => 'on_demand', 'runs' => __( 'When you click Generate Slug or Generate Suggestions', 'ai' ), 'sends' => __( 'Post content, title, current slug, author name, excerpt, content type, and assigned categories and tags', 'ai' ), @@ -62,6 +63,14 @@ protected function load_metadata(): array { */ public function register(): void { add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) ); + } + + /** + * {@inheritDoc} + * + * @since x.x.x + */ + public function register_ui(): void { add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); } @@ -72,7 +81,7 @@ public function register(): void { */ public function register_abilities(): void { // Register the AI ability to generate slugs using the Abilities API. - wp_register_ability( + $this->register_feature_ability( 'ai/' . $this->get_id(), array( 'label' => $this->get_label(), diff --git a/includes/Experiments/Suggest_Reply/Suggest_Reply.php b/includes/Experiments/Suggest_Reply/Suggest_Reply.php index fec843acb..42fb63ed7 100644 --- a/includes/Experiments/Suggest_Reply/Suggest_Reply.php +++ b/includes/Experiments/Suggest_Reply/Suggest_Reply.php @@ -42,10 +42,11 @@ public static function get_id(): string { */ protected function load_metadata(): array { return array( - 'label' => __( 'Suggest Reply', 'ai' ), - 'description' => __( 'Adds a "Suggest Reply" action to the Comments screen and Activity widget, enabling moderators to quickly generate comment reply suggestions.', 'ai' ), - 'category' => Experiment_Category::ADMIN, - 'usage' => array( + 'label' => __( 'Suggest Reply', 'ai' ), + 'description' => __( 'Adds a "Suggest Reply" action to the Comments screen and Activity widget, enabling moderators to quickly generate comment reply suggestions.', 'ai' ), + 'category' => Experiment_Category::ADMIN, + 'access_control' => true, + 'usage' => array( 'trigger' => 'on_demand', 'runs' => __( 'When you click Suggest reply', 'ai' ), 'sends' => __( 'Comment text, author name, post title, and excerpt', 'ai' ), @@ -61,6 +62,14 @@ protected function load_metadata(): array { */ public function register(): void { add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) ); + } + + /** + * {@inheritDoc} + * + * @since x.x.x + */ + public function register_ui(): void { add_filter( 'comment_row_actions', array( $this, 'add_row_action' ), 10, 2 ); add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); } @@ -71,7 +80,7 @@ public function register(): void { * @since 1.2.0 */ public function register_abilities(): void { - wp_register_ability( + $this->register_feature_ability( 'ai/suggest-reply', array( 'label' => __( 'Reply Suggestion', 'ai' ), diff --git a/includes/Experiments/Summarization/Summarization.php b/includes/Experiments/Summarization/Summarization.php index c5502399e..98c606801 100644 --- a/includes/Experiments/Summarization/Summarization.php +++ b/includes/Experiments/Summarization/Summarization.php @@ -60,10 +60,11 @@ public static function get_id(): string { */ protected function load_metadata(): array { return array( - 'label' => __( 'Content Summarization', 'ai' ), - 'description' => __( 'Summarizes long-form content into digestible overviews. Requires an AI connector that includes support for text generation models.', 'ai' ), - 'category' => Experiment_Category::EDITOR, - 'usage' => array( + 'label' => __( 'Content Summarization', 'ai' ), + 'description' => __( 'Summarizes long-form content into digestible overviews. Requires an AI connector that includes support for text generation models.', 'ai' ), + 'category' => Experiment_Category::EDITOR, + 'access_control' => true, + 'usage' => array( 'trigger' => 'on_demand', 'runs' => __( 'When you click Generate Summary or run the bulk action', 'ai' ), 'sends' => __( 'Post content, title, slug, author name, excerpt, content type, and assigned categories and tags', 'ai' ), @@ -78,8 +79,16 @@ protected function load_metadata(): array { public function register(): void { $this->register_post_meta(); add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) ); - add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_assets' ), 5 ); add_action( 'enqueue_block_assets', array( $this, 'enqueue_block_assets' ) ); + } + + /** + * {@inheritDoc} + * + * @since x.x.x + */ + public function register_ui(): void { + add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_assets' ), 5 ); add_action( 'load-edit.php', array( $this, 'register_bulk_action_hooks_for_screen' ) ); add_action( 'admin_enqueue_scripts', array( $this, 'maybe_enqueue_bulk_assets' ) ); @@ -150,7 +159,7 @@ public function register_post_meta(): void { * @since 0.2.0 */ public function register_abilities(): void { - wp_register_ability( + $this->register_feature_ability( 'ai/' . $this->get_id(), array( 'label' => $this->get_label(), diff --git a/includes/Experiments/Text_To_Speech/REST_Controller.php b/includes/Experiments/Text_To_Speech/REST_Controller.php index c83d7daab..95fb8602c 100644 --- a/includes/Experiments/Text_To_Speech/REST_Controller.php +++ b/includes/Experiments/Text_To_Speech/REST_Controller.php @@ -12,6 +12,7 @@ use WP_Error; use WP_REST_Request; use WP_REST_Server; +use WordPress\AI\Access_Control\Feature_Access; use function WordPress\AI\has_text_to_speech_support; @@ -117,6 +118,11 @@ public function can_generate( WP_REST_Request $request ) { ); } + $access_error = $this->feature_access_error(); + if ( $access_error ) { + return $access_error; + } + return true; } @@ -143,6 +149,11 @@ public function can_view_status( WP_REST_Request $request ) { ); } + $access_error = $this->feature_access_error(); + if ( $access_error ) { + return $access_error; + } + return true; } @@ -171,6 +182,11 @@ public function can_delete( WP_REST_Request $request ) { ); } + $access_error = $this->feature_access_error(); + if ( $access_error ) { + return $access_error; + } + $audio_id = absint( get_post_meta( $post_id, Job_Manager::META_AUDIO_ID, true ) ); if ( $audio_id && get_post( $audio_id ) && ! current_user_can( 'delete_post', $audio_id ) ) { @@ -217,6 +233,25 @@ protected function check_post( WP_REST_Request $request ) { return true; } + /** + * Returns an error when the current user may not use Text to Speech. + * + * @since x.x.x + * + * @return \WP_Error|null Error when access is denied, null otherwise. + */ + private function feature_access_error(): ?WP_Error { + if ( current_user_can( Feature_Access::CAPABILITY, Text_To_Speech::get_id() ) ) { // phpcs:ignore WordPress.WP.Capabilities.Undetermined -- Plugin meta capability, mapped in Feature_Access::map_meta_cap(). + return null; + } + + return new WP_Error( + 'wpai_feature_access_denied', + esc_html__( 'You do not have permission to use this feature.', 'ai' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + /** * Starts (or restarts) a background audio generation job. * diff --git a/includes/Experiments/Text_To_Speech/Text_To_Speech.php b/includes/Experiments/Text_To_Speech/Text_To_Speech.php index 9c1511586..acdde89b6 100644 --- a/includes/Experiments/Text_To_Speech/Text_To_Speech.php +++ b/includes/Experiments/Text_To_Speech/Text_To_Speech.php @@ -40,11 +40,12 @@ public static function get_id(): string { */ protected function load_metadata(): array { return array( - 'label' => __( 'Text to Speech', 'ai' ), - 'description' => __( 'Generates an audio version of post content so visitors can listen instead of read. Requires an AI connector that includes support for text to speech models.', 'ai' ), - 'category' => Experiment_Category::EDITOR, - 'capability' => 'text_to_speech_conversion', - 'usage' => array( + 'label' => __( 'Text to Speech', 'ai' ), + 'description' => __( 'Generates an audio version of post content so visitors can listen instead of read. Requires an AI connector that includes support for text to speech models.', 'ai' ), + 'category' => Experiment_Category::EDITOR, + 'access_control' => true, + 'capability' => 'text_to_speech_conversion', + 'usage' => array( 'trigger' => 'on_demand', 'runs' => __( 'When you click Generate Audio or Regenerate Audio in the editor, then in the background until the audio is done', 'ai' ), 'sends' => __( 'The post title and saved post content as plain text, plus the chosen voice', 'ai' ), @@ -62,13 +63,21 @@ public function register(): void { add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) ); add_action( 'rest_api_init', array( $this, 'register_rest_routes' ) ); - add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_assets' ), 5 ); add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_frontend_assets' ) ); add_action( Job_Manager::CRON_HOOK, array( $this, 'process_chunk' ) ); add_filter( 'the_content', array( $this, 'render_audio_player' ) ); add_action( 'wp_after_insert_post', array( $this, 'sync_audio_visibility' ) ); } + /** + * {@inheritDoc} + * + * @since x.x.x + */ + public function register_ui(): void { + add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_assets' ), 5 ); + } + /** * Registers the post meta used to track generated audio. * @@ -133,7 +142,7 @@ public function register_post_meta(): void { * @since 1.5.0 */ public function register_abilities(): void { - wp_register_ability( + $this->register_feature_ability( 'ai/speech-generation', array( 'label' => __( 'Speech Generation', 'ai' ), diff --git a/includes/Experiments/Title_Generation/Title_Generation.php b/includes/Experiments/Title_Generation/Title_Generation.php index 58c9e64bb..969aff521 100644 --- a/includes/Experiments/Title_Generation/Title_Generation.php +++ b/includes/Experiments/Title_Generation/Title_Generation.php @@ -39,10 +39,11 @@ public static function get_id(): string { */ protected function load_metadata(): array { return array( - 'label' => __( 'Title Generation', 'ai' ), - 'description' => __( 'Generates title suggestions from content. Requires an AI connector that includes support for text generation models.', 'ai' ), - 'category' => Experiment_Category::EDITOR, - 'usage' => array( + 'label' => __( 'Title Generation', 'ai' ), + 'description' => __( 'Generates title suggestions from content. Requires an AI connector that includes support for text generation models.', 'ai' ), + 'category' => Experiment_Category::EDITOR, + 'access_control' => true, + 'usage' => array( 'trigger' => 'on_demand', 'runs' => __( 'When you click Generate', 'ai' ), 'sends' => __( 'Post content, current title, slug, author name, excerpt, content type, and assigned categories and tags', 'ai' ), @@ -58,6 +59,14 @@ protected function load_metadata(): array { */ public function register(): void { add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) ); + } + + /** + * {@inheritDoc} + * + * @since x.x.x + */ + public function register_ui(): void { add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); } @@ -67,7 +76,7 @@ public function register(): void { * @since 0.1.0 */ public function register_abilities(): void { - wp_register_ability( + $this->register_feature_ability( 'ai/' . $this->get_id(), array( 'label' => $this->get_label(), diff --git a/includes/Experiments/Type_Ahead/Type_Ahead.php b/includes/Experiments/Type_Ahead/Type_Ahead.php index e677cc619..85d8efec5 100644 --- a/includes/Experiments/Type_Ahead/Type_Ahead.php +++ b/includes/Experiments/Type_Ahead/Type_Ahead.php @@ -56,10 +56,11 @@ public static function get_id(): string { */ protected function load_metadata(): array { return array( - 'label' => __( 'Type-ahead Text', 'ai' ), - 'description' => __( 'Ghost text suggestions while writing paragraphs in the block editor. Requires an AI connector that includes support for text generation models.', 'ai' ), - 'category' => Experiment_Category::EDITOR, - 'usage' => array( + 'label' => __( 'Type-ahead Text', 'ai' ), + 'description' => __( 'Ghost text suggestions while writing paragraphs in the block editor. Requires an AI connector that includes support for text generation models.', 'ai' ), + 'category' => Experiment_Category::EDITOR, + 'access_control' => true, + 'usage' => array( 'trigger' => 'automatic', 'runs' => __( 'Automatically, when you pause typing at the end of a paragraph. You can also press Ctrl + Option + G on macOS, or Shift + Alt + G on Windows and Linux, to ask for a suggestion anywhere in a paragraph', 'ai' ), 'sends' => __( 'The current paragraph and the blocks around it', 'ai' ), @@ -75,6 +76,14 @@ protected function load_metadata(): array { */ public function register(): void { add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) ); + } + + /** + * {@inheritDoc} + * + * @since x.x.x + */ + public function register_ui(): void { add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_assets' ) ); add_action( 'enqueue_block_assets', array( $this, 'enqueue_block_assets' ) ); } @@ -85,7 +94,7 @@ public function register(): void { * @since 1.1.0 */ public function register_abilities(): void { - wp_register_ability( + $this->register_feature_ability( 'ai/' . $this->get_id(), array( 'label' => $this->get_label(), diff --git a/includes/Experiments/WebMCP/WebMCP.php b/includes/Experiments/WebMCP/WebMCP.php index 64b1ccacb..75d7a8b30 100644 --- a/includes/Experiments/WebMCP/WebMCP.php +++ b/includes/Experiments/WebMCP/WebMCP.php @@ -67,11 +67,12 @@ public static function get_id(): string { */ protected function load_metadata(): array { return array( - 'label' => __( 'WebMCP', 'ai' ), - 'description' => __( 'Lets an agent browser work in the block editor through WebMCP: set the title, insert and edit blocks, save and publish, with every change visible on the page as it happens.', 'ai' ), - 'category' => Experiment_Category::EDITOR, - 'capability' => 'none', - 'usage' => array( + 'label' => __( 'WebMCP', 'ai' ), + 'description' => __( 'Lets an agent browser work in the block editor through WebMCP: set the title, insert and edit blocks, save and publish, with every change visible on the page as it happens.', 'ai' ), + 'category' => Experiment_Category::EDITOR, + 'access_control' => true, + 'capability' => 'none', + 'usage' => array( 'trigger' => 'none', 'runs' => __( 'When an agent browser calls one of its tools in the block editor', 'ai' ), 'sends' => __( 'Nothing to your AI provider. Depending on the tool called, the post title, status, and a short text preview of each block go to the AI model the agent browser uses', 'ai' ), @@ -84,6 +85,15 @@ protected function load_metadata(): array { * {@inheritDoc} */ public function register(): void { + // Abilities are exposed client-side; see register_ui(). + } + + /** + * {@inheritDoc} + * + * @since x.x.x + */ + public function register_ui(): void { add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); } diff --git a/includes/Features/Image_Generation/Image_Generation.php b/includes/Features/Image_Generation/Image_Generation.php index 0db257013..ea5c88660 100644 --- a/includes/Features/Image_Generation/Image_Generation.php +++ b/includes/Features/Image_Generation/Image_Generation.php @@ -41,12 +41,13 @@ public static function get_id(): string { */ protected function load_metadata(): array { return array( - 'label' => __( 'Image Generation and Editing', 'ai' ), - 'description' => __( 'Generate and edit images using AI. Requires an AI connector that includes support for image generation models.', 'ai' ), - 'stability' => 'stable', - 'image' => WPAI_PLUGIN_URL . 'assets/images/showcase-image-generation.webp', - 'capability' => 'image_generation', - 'usage' => array( + 'label' => __( 'Image Generation and Editing', 'ai' ), + 'description' => __( 'Generate and edit images using AI. Requires an AI connector that includes support for image generation models.', 'ai' ), + 'stability' => 'stable', + 'image' => WPAI_PLUGIN_URL . 'assets/images/showcase-image-generation.webp', + 'capability' => 'image_generation', + 'access_control' => true, + 'usage' => array( 'trigger' => 'on_demand', 'runs' => __( 'When you click Generate Image or Generate featured image', 'ai' ), 'sends' => __( 'Your prompt; featured images also send post content, title, and post type; editing an image also sends the existing image', 'ai' ), @@ -61,6 +62,14 @@ protected function load_metadata(): array { public function register(): void { $this->register_post_meta(); add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) ); + } + + /** + * {@inheritDoc} + * + * @since x.x.x + */ + public function register_ui(): void { add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_inline_assets' ) ); add_action( 'admin_menu', array( $this, 'register_admin_menu' ) ); @@ -155,7 +164,7 @@ public function register_post_meta(): void { * @since 0.2.0 */ public function register_abilities(): void { - wp_register_ability( + $this->register_feature_ability( 'ai/' . $this->get_id(), array( 'label' => $this->get_label(), @@ -165,7 +174,7 @@ public function register_abilities(): void { ), ); - wp_register_ability( + $this->register_feature_ability( 'ai/image-import', array( 'label' => __( 'Base64 Image Import', 'ai' ), @@ -175,7 +184,7 @@ public function register_abilities(): void { ), ); - wp_register_ability( + $this->register_feature_ability( 'ai/image-prompt-generation', array( 'label' => __( 'Image Prompt Generation', 'ai' ), diff --git a/includes/Features/Loader.php b/includes/Features/Loader.php index 5cdddbf9e..f04364637 100644 --- a/includes/Features/Loader.php +++ b/includes/Features/Loader.php @@ -10,6 +10,8 @@ namespace WordPress\AI\Features; use Throwable; +use WordPress\AI\Abstracts\Abstract_Feature; +use WordPress\AI\Access_Control\Feature_Access; use WordPress\AI\Contracts\Feature; // Exit if accessed directly. @@ -167,7 +169,9 @@ private function get_default_features(): array { * Initializes all enabled features. * * Loops through all registered features and calls their register() method - * if they are enabled. + * if they are enabled. For enabled features that extend Abstract_Feature, + * register_ui() then runs for users with access to the feature, or for + * everyone when the feature opts out of access control. * * @since 0.6.0 */ @@ -198,6 +202,12 @@ private function initialize_features(): void { foreach ( $features as $feature ) { $options[] = sprintf( 'wpai_feature_%s_enabled', $feature::get_id() ); + if ( $feature instanceof Abstract_Feature && $feature->supports_access_control() ) { + $options[] = Feature_Access::enabled_option( $feature::get_id() ); + $options[] = Feature_Access::roles_option( $feature::get_id() ); + $options[] = Feature_Access::users_option( $feature::get_id() ); + } + if ( ! method_exists( $feature, 'get_preloaded_options' ) ) { continue; } @@ -216,6 +226,21 @@ private function initialize_features(): void { // Register the feature. $feature->register(); + + if ( ! $feature instanceof Abstract_Feature ) { + continue; + } + + // Register its user-facing hooks for everyone when the feature opts out of access control, otherwise only for users allowed to use it. + if ( + $feature->supports_access_control() + // phpcs:ignore WordPress.WP.Capabilities.Undetermined -- Plugin meta capability, mapped in Feature_Access::map_meta_cap(). + && ! current_user_can( Feature_Access::CAPABILITY, $feature::get_id() ) + ) { + continue; + } + + $feature->register_ui(); } /** diff --git a/includes/Main.php b/includes/Main.php index 58bc78618..0d40736c5 100644 --- a/includes/Main.php +++ b/includes/Main.php @@ -12,6 +12,7 @@ namespace WordPress\AI; use WordPress\AI\Abilities\Meta_Description\SEO_Integration; +use WordPress\AI\Access_Control\Feature_Access; use WordPress\AI\Admin\Activation; use WordPress\AI\Admin\Dashboard\Dashboard_Widgets; use WordPress\AI\Admin\Deactivation; @@ -99,6 +100,9 @@ public function load(): void { // List featured Connector plugins on the Connectors screen. ( new Featured_Connectors() )->init(); + // Restrict features, and the abilities they register, to chosen roles and users. + ( new Feature_Access() )->init(); + // Add plugin action links to plugins screen. add_filter( 'plugin_action_links_' . plugin_basename( WPAI_PLUGIN_FILE ), array( $this, 'plugin_action_links' ) ); diff --git a/includes/Settings/Settings_Page.php b/includes/Settings/Settings_Page.php index b9500bac9..8619189cc 100644 --- a/includes/Settings/Settings_Page.php +++ b/includes/Settings/Settings_Page.php @@ -39,6 +39,15 @@ class Settings_Page { */ private const PAGE_SLUG = 'ai-wp-admin'; + /** + * Roles pre-checked when access control is turned on for a feature. + * + * @since x.x.x + * + * @var list + */ + public const DEFAULT_ACCESS_ROLES = array( 'administrator', 'editor' ); // phpcs:ignore SlevomatCodingStandard.Classes.DisallowMultiConstantDefinition -- This is used as an array const. + /** * Initializes the settings page hooks. * @@ -75,6 +84,8 @@ static function ( array $data ) use ( $registry ): array { $data['connectorsUrl'] = admin_url( 'options-connectors.php' ); $data['featureGroups'] = $feature_metadata['groups'] ?? array(); $data['features'] = $feature_metadata['features'] ?? array(); + $data['roles'] = self::get_access_control_roles(); + $data['defaultAccessRoles'] = array_values( array_intersect( self::DEFAULT_ACCESS_ROLES, array_keys( wp_roles()->roles ) ) ); return $data; } ); @@ -209,7 +220,8 @@ private static function get_feature_docs_url( Feature $feature ): string { * isValid?: array{min?: int, max?: int} * }>, * usage: array{trigger: 'automatic'|'on_demand'|'none', runs: string, sends: string, requests: string, details: string}|array{}, - * docsUrl: string + * docsUrl: string, + * supportsAccessControl: bool * }> * } */ @@ -236,17 +248,18 @@ private static function get_settings_feature_metadata( Registry $registry ): arr $categories_in_use[ $category ] = true; $features[] = array( - 'id' => $feature_id, - 'settingName' => "wpai_feature_{$feature_id}_enabled", - 'label' => $feature->get_label(), - 'description' => wp_strip_all_tags( $feature->get_description() ), - 'category' => $category, - 'settingsFields' => $feature->get_settings_fields_metadata(), - 'stability' => $feature->get_stability(), - 'image' => esc_url( $feature->get_image() ), - 'capability' => $feature->get_capability(), - 'usage' => $feature instanceof Abstract_Feature ? $feature->get_usage() : array(), - 'docsUrl' => self::get_feature_docs_url( $feature ), + 'id' => $feature_id, + 'settingName' => "wpai_feature_{$feature_id}_enabled", + 'label' => $feature->get_label(), + 'description' => wp_strip_all_tags( $feature->get_description() ), + 'category' => $category, + 'settingsFields' => $feature->get_settings_fields_metadata(), + 'stability' => $feature->get_stability(), + 'image' => esc_url( $feature->get_image() ), + 'capability' => $feature->get_capability(), + 'usage' => $feature instanceof Abstract_Feature ? $feature->get_usage() : array(), + 'docsUrl' => self::get_feature_docs_url( $feature ), + 'supportsAccessControl' => $feature instanceof Abstract_Feature && $feature->supports_access_control(), ); } @@ -318,7 +331,8 @@ static function ( array $group ): array { * isValid?: array{min?: int, max?: int} * }>, * usage: array{trigger: 'automatic'|'on_demand'|'none', runs: string, sends: string, requests: string, details: string}|array{}, - * docsUrl: string + * docsUrl: string, + * supportsAccessControl: bool * }> * } $metadata Settings UI metadata. * @param \WordPress\AI\Features\Registry $registry Feature registry instance. @@ -327,4 +341,28 @@ static function ( array $group ): array { return is_array( $filtered_metadata ) ? $filtered_metadata : $metadata; } + + /** + * Returns the roles offered in access control settings. + * + * @since x.x.x + * + * @return list Role IDs and translated names. + */ + private static function get_access_control_roles(): array { + $roles = array(); + + foreach ( wp_roles()->roles as $role_id => $role ) { + if ( empty( $role['capabilities']['edit_posts'] ) ) { + continue; + } + + $roles[] = array( + 'id' => (string) $role_id, + 'name' => translate_user_role( $role['name'] ), + ); + } + + return $roles; + } } diff --git a/includes/Settings/Settings_Registration.php b/includes/Settings/Settings_Registration.php index 4ca654775..5f3ba043d 100644 --- a/includes/Settings/Settings_Registration.php +++ b/includes/Settings/Settings_Registration.php @@ -11,6 +11,8 @@ namespace WordPress\AI\Settings; +use WordPress\AI\Abstracts\Abstract_Feature; +use WordPress\AI\Access_Control\Feature_Access; use WordPress\AI\Features\Registry; use WordPress\AI\REST\Models_Controller; use WordPress\AI\REST\Settings_IO_Controller; @@ -40,6 +42,15 @@ class Settings_Registration { */ public const OPTION_GROUP = 'ai_experiments'; + /** + * The option group for per-feature access control settings. + * + * @since x.x.x + * + * @var string + */ + public const ACCESS_CONTROL_OPTION_GROUP = 'ai_experiments_access'; + /** * The option name for the former global experiments toggle. * @@ -189,6 +200,10 @@ public function register_settings(): void { ) ); + if ( $feature instanceof Abstract_Feature && $feature->supports_access_control() ) { + $this->register_access_control_settings( $feature_id ); + } + // Allow experiments to register their own custom settings. if ( ! method_exists( $feature, 'register_settings' ) ) { continue; @@ -197,4 +212,92 @@ public function register_settings(): void { $feature->register_settings(); } } + + /** + * Registers the access control settings for one feature. + * + * @since x.x.x + * + * @param string $feature_id The feature ID. + */ + private function register_access_control_settings( string $feature_id ): void { + register_setting( + self::ACCESS_CONTROL_OPTION_GROUP, + Feature_Access::enabled_option( $feature_id ), + array( + 'type' => 'boolean', + 'default' => false, + 'sanitize_callback' => 'rest_sanitize_boolean', + 'show_in_rest' => true, + ) + ); + + register_setting( + self::ACCESS_CONTROL_OPTION_GROUP, + Feature_Access::roles_option( $feature_id ), + array( + 'type' => 'array', + 'default' => null, + 'sanitize_callback' => static function ( $roles ): ?array { + if ( null === $roles ) { + return null; + } + + if ( ! is_array( $roles ) ) { + return array(); + } + + $valid_roles = array_keys( wp_roles()->roles ); + + return array_values( + array_unique( + array_filter( + $roles, + static function ( $role ) use ( $valid_roles ): bool { + return is_string( $role ) && in_array( $role, $valid_roles, true ); + } + ) + ) + ); + }, + 'show_in_rest' => array( + 'schema' => array( + 'type' => 'array', + 'items' => array( 'type' => 'string' ), + ), + ), + ) + ); + + register_setting( + self::ACCESS_CONTROL_OPTION_GROUP, + Feature_Access::users_option( $feature_id ), + array( + 'type' => 'array', + 'default' => array(), + 'sanitize_callback' => static function ( $users ): array { + if ( ! is_array( $users ) ) { + return array(); + } + + return array_values( + array_unique( + array_filter( + array_map( 'absint', $users ), + static function ( int $user_id ): bool { + return $user_id > 0 && false !== get_userdata( $user_id ); + } + ) + ) + ); + }, + 'show_in_rest' => array( + 'schema' => array( + 'type' => 'array', + 'items' => array( 'type' => 'integer' ), + ), + ), + ) + ); + } } diff --git a/routes/ai-home/components/AccessControlSettings.tsx b/routes/ai-home/components/AccessControlSettings.tsx new file mode 100644 index 000000000..1a0e52a20 --- /dev/null +++ b/routes/ai-home/components/AccessControlSettings.tsx @@ -0,0 +1,350 @@ +/** + * WordPress dependencies + */ +import { + Button, + CheckboxControl, + Flex, + FlexItem, + FormTokenField, + Spinner, + ToggleControl, +} from '@wordpress/components'; +import { useCallback, useEffect, useMemo, useState } from '@wordpress/element'; +import { __ } from '@wordpress/i18n'; + +/** + * Internal dependencies + */ +import { useAccessControlSettings } from '../hooks/use-access-control-settings'; +import { useRolesUsersContext } from '../hooks/use-roles-users'; +import type { User } from '../hooks/use-roles-users'; + +interface UserTokenItem { + id?: number; + value: string; +} + +interface AccessControlSettingsProps { + featureId: string; +} + +const formatUserToken = ( id: number, name?: string ): string => { + return name ? `${ name } (#${ id })` : id.toString(); +}; + +export function AccessControlSettings( { + featureId, +}: AccessControlSettingsProps ): React.JSX.Element { + const { roles, defaultRoles, suggestions, isSearching, search } = + useRolesUsersContext(); + + const { + settings, + savedEnabled, + savedRoles, + stage, + save, + isDirty, + isSaving, + } = useAccessControlSettings( featureId ); + + const rolesNotYetSaved = savedEnabled && savedRoles === null; + + const [ localEnabled, setLocalEnabled ] = useState< boolean | null >( + null + ); + const [ localRoles, setLocalRoles ] = useState< string[] | null >( null ); + const [ selectedUserMap, setSelectedUserMap ] = useState< + Map< number, string > + >( new Map() ); + const [ localUsers, setLocalUsers ] = useState< number[] | null >( null ); + + const effectiveEnabled = localEnabled ?? settings.enabled; + // Unset roles (never saved) show the pre-checked defaults. + const effectiveRoles = useMemo( + () => localRoles ?? settings.roles ?? defaultRoles, + [ localRoles, settings.roles, defaultRoles ] + ); + const effectiveUsers = localUsers ?? settings.users; + + const handleToggleEnabled = useCallback( + ( enabled: boolean ) => { + setLocalEnabled( enabled ); + if ( enabled ) { + stage( + settings.roles === null + ? { enabled, roles: effectiveRoles } + : { enabled } + ); + } else if ( savedRoles === null ) { + stage( { enabled, roles: null } ); + } else { + stage( { enabled } ); + } + }, + [ stage, settings.roles, savedRoles, effectiveRoles ] + ); + + const suggestionTokenToId = useMemo( () => { + const map = new Map< string, number >(); + suggestions.forEach( ( u: User ) => { + map.set( formatUserToken( u.id, u.name ), u.id ); + map.set( u.name, u.id ); + } ); + return map; + }, [ suggestions ] ); + + const selectedUsersTokens = useMemo( () => { + return effectiveUsers.map( ( id ) => ( { + id, + value: formatUserToken( id, selectedUserMap.get( id ) ), + } ) ); + }, [ effectiveUsers, selectedUserMap ] ); + + // Seed selectedUserMap with users returned from search suggestions. + useEffect( () => { + setSelectedUserMap( ( prev ) => { + const next = new Map( prev ); + suggestions.forEach( ( u: User ) => next.set( u.id, u.name ) ); + return next; + } ); + }, [ suggestions ] ); + + // Exclude already-selected users from the suggestions dropdown. + const userSuggestionNames = useMemo( + () => + suggestions + .filter( ( u: User ) => ! effectiveUsers.includes( u.id ) ) + .map( ( u: User ) => formatUserToken( u.id, u.name ) ), + [ suggestions, effectiveUsers ] + ); + + const handleRoleToggle = useCallback( + ( roleId: string, checked: boolean ) => { + const newRoles = checked + ? [ ...effectiveRoles, roleId ] + : effectiveRoles.filter( ( r ) => r !== roleId ); + setLocalRoles( newRoles ); + stage( { roles: newRoles } ); + }, + [ stage, effectiveRoles ] + ); + + const handleUsersChange = useCallback( + ( tokens: ( string | UserTokenItem )[] ) => { + const newUsers: number[] = []; + const newMap = new Map< number, string >( selectedUserMap ); + + tokens.forEach( ( token ) => { + let id: number | undefined; + let label = ''; + + if ( typeof token === 'object' && token !== null ) { + label = token.value; + if ( + 'id' in token && + typeof ( token as { id?: unknown } ).id === 'number' + ) { + id = ( token as { id: number } ).id; + } + } else if ( typeof token === 'string' ) { + label = token; + } + + // If id is not already known from the token object, extract from label. + if ( id === undefined ) { + // 1. Check formatted token e.g. "Jane Doe (#12)" or "(ID: 12)" + const idMatch = label.match( /(?:#|ID:\s*)(\d+)\)?$/i ); + if ( idMatch ) { + id = Number( idMatch[ 1 ] ); + } + } + + if ( id === undefined ) { + // 2. Check if the token is a numeric user ID string e.g. "12" + const numericId = Number( label ); + if ( Number.isInteger( numericId ) && numericId > 0 ) { + id = numericId; + } + } + + if ( id === undefined ) { + // 3. Fallback: match from suggestionTokenToId + id = suggestionTokenToId.get( label ); + } + + if ( id !== undefined ) { + if ( ! newUsers.includes( id ) ) { + newUsers.push( id ); + } + + // Extract clean display name if available and save in newMap + const cleanName = label + .replace( /\s*\((?:#|ID:\s*)\d+\)$/i, '' ) + .trim(); + if ( cleanName && cleanName !== id.toString() ) { + newMap.set( id, cleanName ); + } + } + } ); + + setLocalUsers( newUsers ); + setSelectedUserMap( newMap ); + stage( { users: newUsers } ); + search( '' ); + }, + [ stage, suggestionTokenToId, selectedUserMap, search ] + ); + + const handleInputChange = useCallback( + ( input: string ) => { + search( input ); + }, + [ search ] + ); + + const handleSave = useCallback( async () => { + await save( + effectiveEnabled && settings.roles === null + ? { roles: effectiveRoles } + : undefined + ); + setLocalEnabled( null ); + setLocalRoles( null ); + setLocalUsers( null ); + }, [ save, effectiveEnabled, settings.roles, effectiveRoles ] ); + + return ( +
+ + + + + { effectiveEnabled && ( + <> + +
+ + { __( 'Roles', 'ai' ) } + +
+ { roles.map( ( role ) => ( + + handleRoleToggle( + role.id, + checked + ) + } + /> + ) ) } +
+ { rolesNotYetSaved && ( +

+ { __( + 'Role selections have not been saved yet, so access is not restricted.', + 'ai' + ) } +

+ ) } +
+
+ + +
+ +
+ { isSearching && ( +
+ +
+ ) } +
+
+ + ) } + { ( isDirty || rolesNotYetSaved ) && ( + + + + ) } +
+
+ ); +} + +/** + * Shows that a feature is restricted while the access controls view is hidden. + * + * @param {Object} props Component props. + * @param {string} props.featureId The feature ID. + * @return {React.JSX.Element|null} The notice, or null when unrestricted. + */ +export function AccessRestrictedNotice( { + featureId, +}: { + featureId: string; +} ): React.JSX.Element | null { + const { savedEnabled, savedRoles } = useAccessControlSettings( featureId ); + + if ( ! savedEnabled || savedRoles === null ) { + return null; + } + + return ( +

+ { __( 'Access restricted to selected roles and users.', 'ai' ) } +

+ ); +} diff --git a/routes/ai-home/components/FeatureToggle.tsx b/routes/ai-home/components/FeatureToggle.tsx index 0d0a5aad8..f9dc52dc4 100644 --- a/routes/ai-home/components/FeatureToggle.tsx +++ b/routes/ai-home/components/FeatureToggle.tsx @@ -14,6 +14,11 @@ import { Stack } from '@wordpress/ui'; * Internal dependencies */ import { useDeveloperModeContext } from '../hooks/use-developer-mode'; +import { useAccessControlModeContext } from '../hooks/use-access-control-mode'; +import { + AccessControlSettings, + AccessRestrictedNotice, +} from './AccessControlSettings'; import { DeveloperSettings } from './DeveloperSettings'; import { ConnectorApprovalNotice } from './ConnectorApprovalNotice'; import { FeatureToggleControl } from './FeatureToggleText'; @@ -26,6 +31,7 @@ type FeatureToggleProps = DataFormControlProps< AISettings > & { capability?: string; usage?: FeatureUsage | null; docsUrl?: string; + supportsAccessControl?: boolean; }; interface ConnectorApprovalState { @@ -40,14 +46,15 @@ const AI_PLUGIN = 'ai/ai.php'; /** * FeatureToggle component. * - * @param {FeatureToggleProps} props The component props. - * @param {FeatureToggleProps['field']} props.field The field to display. - * @param {AISettings} props.data The data to display. - * @param {FeatureToggleProps['onChange']} props.onChange The function to call when the value changes. - * @param {string} props.featureId The feature ID. - * @param {string} props.capability The AI capability type for model filtering. - * @param {FeatureUsage} props.usage When the feature runs, what it sends, and how many requests it makes. - * @param {string} props.docsUrl URL of the feature's documentation. + * @param {FeatureToggleProps} props The component props. + * @param {FeatureToggleProps['field']} props.field The field to display. + * @param {AISettings} props.data The data to display. + * @param {FeatureToggleProps['onChange']} props.onChange The function to call when the value changes. + * @param {string} props.featureId The feature ID. + * @param {string} props.capability The AI capability type for model filtering. + * @param {FeatureUsage} props.usage When the feature runs, what it sends, and how many requests it makes. + * @param {string} props.docsUrl URL of the feature's documentation. + * @param {boolean} props.supportsAccessControl Whether access control applies. * @return {React.JSX.Element} The component. */ export function FeatureToggle( { @@ -58,9 +65,11 @@ export function FeatureToggle( { capability = 'text_generation', usage, docsUrl, + supportsAccessControl = false, }: FeatureToggleProps ): React.JSX.Element { const checked = !! field.getValue( { item: data } ); const isDeveloperMode = useDeveloperModeContext(); + const isAccessControlMode = useAccessControlModeContext(); const { createErrorNotice } = useDispatch( noticesStore ); const [ approvalState, setApprovalState ] = @@ -134,6 +143,13 @@ export function FeatureToggle( { } } } /> + { checked && + supportsAccessControl && + ( isAccessControlMode ? ( + + ) : ( + + ) ) } { checked && isDeveloperMode && ( ( false ); + +export function useAccessControlModeContext(): boolean { + return useContext( AccessControlModeContext ); +} + +interface UseAccessControlModeReturn { + isAccessControlMode: boolean; + toggleAccessControlMode: () => void; +} + +/** + * useAccessControlMode hook. + * + * @return {UseAccessControlModeReturn} The access control mode return object. + */ +export function useAccessControlMode(): UseAccessControlModeReturn { + const [ isAccessControlMode, setIsAccessControlMode ] = useState< boolean >( + () => { + try { + return localStorage.getItem( STORAGE_KEY ) === 'true'; + } catch { + return false; + } + } + ); + + useEffect( () => { + try { + if ( isAccessControlMode ) { + localStorage.setItem( STORAGE_KEY, 'true' ); + } else { + localStorage.removeItem( STORAGE_KEY ); + } + } catch {} + }, [ isAccessControlMode ] ); + + const toggleAccessControlMode = useCallback( () => { + setIsAccessControlMode( ( prev ) => ! prev ); + }, [] ); + + return { isAccessControlMode, toggleAccessControlMode }; +} diff --git a/routes/ai-home/hooks/use-access-control-settings.ts b/routes/ai-home/hooks/use-access-control-settings.ts new file mode 100644 index 000000000..e842db7fb --- /dev/null +++ b/routes/ai-home/hooks/use-access-control-settings.ts @@ -0,0 +1,180 @@ +/** + * WordPress dependencies + */ +import { store as coreStore } from '@wordpress/core-data'; +import { useDispatch, useSelect } from '@wordpress/data'; +import { useCallback, useMemo } from '@wordpress/element'; +import { __ } from '@wordpress/i18n'; +import { store as noticesStore } from '@wordpress/notices'; + +interface AccessControlSettings { + enabled: boolean; + roles: string[] | null; + users: number[]; +} + +interface UseAccessControlSettingsReturn { + settings: AccessControlSettings; + savedEnabled: boolean; + savedRoles: string[] | null; + stage: ( next: Partial< AccessControlSettings > ) => void; + save: ( pending?: Partial< AccessControlSettings > ) => Promise< void >; + isDirty: boolean; + isSaving: boolean; +} + +/** + * Reads and writes the access control settings for a specific feature. + * + * @param {string} featureId The feature ID. + * @return {UseAccessControlSettingsReturn} The settings and update functions. + */ +export function useAccessControlSettings( + featureId: string +): UseAccessControlSettingsReturn { + const enabledKey = `wpai_feature_${ featureId }_access_control_enabled`; + const rolesKey = `wpai_feature_${ featureId }_roles`; + const usersKey = `wpai_feature_${ featureId }_users`; + + const { record, editedRecord, nonTransientEdits, isSaving } = useSelect( + ( select ) => { + const store: any = select( coreStore ); + return { + record: store.getEntityRecord( 'root', 'site' ) as + | Record< string, unknown > + | undefined, + editedRecord: store.getEditedEntityRecord( 'root', 'site' ) as + | Record< string, unknown > + | undefined, + nonTransientEdits: ( store.getEntityRecordNonTransientEdits( + 'root', + 'site' + ) ?? {} ) as Record< string, unknown >, + isSaving: store.isSavingEntityRecord( + 'root', + 'site' + ) as boolean, + }; + }, + [] + ); + + const { editEntityRecord } = useDispatch( coreStore ); + const { __experimentalSaveSpecifiedEntityEdits: saveSpecifiedEdits } = + useDispatch( coreStore ) as any; + const { createErrorNotice, createSuccessNotice } = + useDispatch( noticesStore ); + + const rawEnabled = editedRecord?.[ enabledKey ]; + const rawRoles = editedRecord?.[ rolesKey ]; + const rawUsers = editedRecord?.[ usersKey ]; + const savedEnabled = record?.[ enabledKey ] === true; + const rawSavedRoles = record?.[ rolesKey ]; + const savedRoles = Array.isArray( rawSavedRoles ) + ? rawSavedRoles.map( String ) + : null; + + const settings: AccessControlSettings = { + enabled: typeof rawEnabled === 'boolean' ? rawEnabled : false, + roles: Array.isArray( rawRoles ) ? rawRoles.map( String ) : null, + users: Array.isArray( rawUsers ) ? rawUsers.map( Number ) : [], + }; + + const isDirty = useMemo( + () => + enabledKey in nonTransientEdits || + rolesKey in nonTransientEdits || + usersKey in nonTransientEdits, + [ enabledKey, rolesKey, usersKey, nonTransientEdits ] + ); + + const stage = useCallback( + ( next: Partial< AccessControlSettings > ) => { + const edits: Record< string, unknown > = {}; + if ( next.enabled !== undefined ) { + // A saved `false` is stored as '' and comes back from REST as + // null, so staging `false` over anything but a persisted `true` + // stages the persisted value, which reverts the edit. + const persistedEnabled = record?.[ enabledKey ]; + edits[ enabledKey ] = + ! next.enabled && persistedEnabled !== true + ? persistedEnabled + : next.enabled; + } + if ( next.roles !== undefined ) { + edits[ rolesKey ] = next.roles; + } + if ( next.users !== undefined ) { + edits[ usersKey ] = next.users; + } + // @ts-expect-error -- core-data types don't expose editEntityRecord for 'root'/'site' args. + editEntityRecord( 'root', 'site', undefined, edits ); + }, + [ enabledKey, rolesKey, usersKey, record, editEntityRecord ] + ); + + // `pending` is staged right before saving, so its keys are saved too. + const save = useCallback( + async ( pending?: Partial< AccessControlSettings > ) => { + if ( pending ) { + stage( pending ); + } + const pendingKeys = pending + ? [ + pending.enabled !== undefined ? enabledKey : '', + pending.roles !== undefined ? rolesKey : '', + pending.users !== undefined ? usersKey : '', + ] + : []; + const editedKeys = [ enabledKey, rolesKey, usersKey ].filter( + ( key ) => + key in nonTransientEdits || pendingKeys.includes( key ) + ); + if ( editedKeys.length === 0 ) { + return; + } + try { + await saveSpecifiedEdits( + 'root', + 'site', + undefined, + editedKeys, + { + throwOnError: true, + } + ); + createSuccessNotice( + __( 'Access control settings saved.', 'ai' ), + { + type: 'snackbar', + } + ); + } catch { + createErrorNotice( + __( 'Failed to save access control settings.', 'ai' ), + { type: 'snackbar' } + ); + } + }, + [ + enabledKey, + rolesKey, + usersKey, + nonTransientEdits, + stage, + saveSpecifiedEdits, + createSuccessNotice, + createErrorNotice, + ] + ); + + return { + settings, + savedEnabled, + savedRoles, + stage, + save, + isDirty, + isSaving, + }; +} diff --git a/routes/ai-home/hooks/use-roles-users.ts b/routes/ai-home/hooks/use-roles-users.ts new file mode 100644 index 000000000..03dd7f957 --- /dev/null +++ b/routes/ai-home/hooks/use-roles-users.ts @@ -0,0 +1,221 @@ +/** + * WordPress dependencies + */ +import apiFetch from '@wordpress/api-fetch'; +import { store as coreStore } from '@wordpress/core-data'; +import { useSelect } from '@wordpress/data'; +import { + createContext, + createElement, + useCallback, + useContext, + useEffect, + useMemo, + useRef, + useState, +} from '@wordpress/element'; +import { addQueryArgs } from '@wordpress/url'; + +/** + * Internal dependencies + */ +import { useAccessControlModeContext } from './use-access-control-mode'; + +export interface Role { + id: string; + name: string; +} + +export interface User { + id: number; + name: string; +} + +export interface RolesUsersContextValue { + roles: Role[]; + defaultRoles: string[]; + suggestions: User[]; + isSearching: boolean; + search: ( query: string ) => void; +} + +const DEFAULT_CONTEXT_VALUE: RolesUsersContextValue = { + roles: [], + defaultRoles: [], + suggestions: [], + isSearching: false, + search: () => {}, +}; + +const RolesUsersContext = createContext< RolesUsersContextValue >( + DEFAULT_CONTEXT_VALUE +); + +const DEBOUNCE_MS = 300; +const SEARCH_PER_PAGE = 10; +const USERS_OPTION_PATTERN = /^wpai_feature_.+_users$/; + +function fetchUsers( query: Record< string, string | number > ) { + return apiFetch< Array< { id: number; name: string } > >( { + path: addQueryArgs( '/wp/v2/users', { + context: 'view', + _fields: 'id,name', + ...query, + } ), + } ).then( ( users ) => + users.map( ( user ) => ( { id: user.id, name: user.name } ) ) + ); +} + +/** + * Shares the role list and a debounced user search with access control fields. + * + * Roles come from page data. Users come from core's /wp/v2/users endpoint: + * saved user IDs are resolved once for their display names, and the search + * results are merged after them. + * + * @param {Object} props Component props. + * @param {Role[]} props.roles Roles offered as checkboxes. + * @param {string[]} props.defaultRoles Roles pre-checked while roles are unsaved. + * @param {React.ReactNode} props.children Child elements. + * @return {React.JSX.Element} The provider. + */ +export function RolesUsersProvider( { + roles, + defaultRoles, + children, +}: { + roles: Role[]; + defaultRoles: string[]; + children: React.ReactNode; +} ): React.JSX.Element { + const isEnabled = useAccessControlModeContext(); + + // A string key keeps the selector's return value referentially stable. + const savedIdsKey = useSelect( ( select ) => { + const record = ( select( coreStore ) as any ).getEntityRecord( + 'root', + 'site' + ) as Record< string, unknown > | undefined; + const ids = new Set< number >(); + Object.entries( record ?? {} ).forEach( ( [ key, value ] ) => { + if ( USERS_OPTION_PATTERN.test( key ) && Array.isArray( value ) ) { + value.forEach( ( id ) => { + const num = Number( id ); + if ( Number.isInteger( num ) && num > 0 ) { + ids.add( num ); + } + } ); + } + } ); + return Array.from( ids ) + .sort( ( a, b ) => a - b ) + .join( ',' ); + }, [] ); + + const [ savedUsers, setSavedUsers ] = useState< User[] >( [] ); + const [ searchResults, setSearchResults ] = useState< User[] >( [] ); + const [ isSearching, setIsSearching ] = useState( false ); + const debounceTimer = useRef< ReturnType< typeof setTimeout > | null >( + null + ); + const latestRequest = useRef( 0 ); + + useEffect( () => { + if ( ! isEnabled || ! savedIdsKey ) { + return; + } + let isCurrent = true; + fetchUsers( { include: savedIdsKey, per_page: 100 } ) + .then( ( users ) => { + if ( isCurrent ) { + setSavedUsers( users ); + } + } ) + .catch( () => {} ); + return () => { + isCurrent = false; + }; + }, [ isEnabled, savedIdsKey ] ); + + const runSearch = useCallback( ( query: string ) => { + const requestId = ++latestRequest.current; + setIsSearching( true ); + const params: Record< string, string | number > = { + per_page: SEARCH_PER_PAGE, + ...( query ? { search: query } : {} ), + }; + fetchUsers( params ) + .then( ( users ) => { + if ( requestId === latestRequest.current ) { + setSearchResults( users ); + } + } ) + .catch( () => {} ) + .finally( () => { + if ( requestId === latestRequest.current ) { + setIsSearching( false ); + } + } ); + }, [] ); + + useEffect( () => { + if ( ! isEnabled ) { + return; + } + runSearch( '' ); + return () => { + if ( debounceTimer.current ) { + clearTimeout( debounceTimer.current ); + } + }; + }, [ isEnabled, runSearch ] ); + + const search = useCallback( + ( query: string ) => { + if ( ! isEnabled ) { + return; + } + if ( debounceTimer.current ) { + clearTimeout( debounceTimer.current ); + } + debounceTimer.current = setTimeout( + () => runSearch( query ), + DEBOUNCE_MS + ); + }, + [ isEnabled, runSearch ] + ); + + const value = useMemo( () => { + const seen = new Set< number >(); + const suggestions = [ ...savedUsers, ...searchResults ].filter( + ( user ) => { + if ( seen.has( user.id ) ) { + return false; + } + seen.add( user.id ); + return true; + } + ); + return { roles, defaultRoles, suggestions, isSearching, search }; + }, [ + roles, + defaultRoles, + savedUsers, + searchResults, + isSearching, + search, + ] ); + + return createElement( RolesUsersContext.Provider, { value }, children ); +} + +/** + * Returns the shared roles and user search state. + * + * @return {RolesUsersContextValue} Roles, user suggestions and search trigger. + */ +export function useRolesUsersContext(): RolesUsersContextValue { + return useContext( RolesUsersContext ); +} diff --git a/routes/ai-home/package.json b/routes/ai-home/package.json index 36868ee15..1d8bcd99c 100644 --- a/routes/ai-home/package.json +++ b/routes/ai-home/package.json @@ -20,6 +20,7 @@ "@wordpress/i18n": "*", "@wordpress/notices": "*", "@wordpress/primitives": "*", - "@wordpress/ui": "*" + "@wordpress/ui": "*", + "@wordpress/url": "*" } } diff --git a/routes/ai-home/stage.tsx b/routes/ai-home/stage.tsx index 341b81605..e248eeb3e 100644 --- a/routes/ai-home/stage.tsx +++ b/routes/ai-home/stage.tsx @@ -32,6 +32,10 @@ import { store as noticesStore } from '@wordpress/notices'; */ import AIIcon from './ai-icon'; import { DeveloperSettings } from './components/DeveloperSettings'; +import { + AccessControlSettings, + AccessRestrictedNotice, +} from './components/AccessControlSettings'; import { FeatureToggle } from './components/FeatureToggle'; import { FeatureToggleControl, @@ -49,6 +53,13 @@ import { useDeveloperMode, useDeveloperModeContext, } from './hooks/use-developer-mode'; +import { + AccessControlModeContext, + useAccessControlMode, + useAccessControlModeContext, +} from './hooks/use-access-control-mode'; +import { RolesUsersProvider } from './hooks/use-roles-users'; +import type { Role } from './hooks/use-roles-users'; import { useSettingsImportExport } from './hooks/use-settings-import-export'; import './style.scss'; @@ -81,6 +92,7 @@ interface FeatureData { capability: string; usage: FeatureUsage | null; docsUrl: string; + supportsAccessControl: boolean; } interface PageData { @@ -89,9 +101,13 @@ interface PageData { connectorsUrl: string; featureGroups: FeatureGroupData[]; features: FeatureData[]; + roles: Role[]; + defaultAccessRoles: string[]; } -const FEATURE_SETTING_PATTERN = /^wpai_feature_(.+)_enabled$/; +// Feature toggles only; access control toggles also end in `_enabled`. +const FEATURE_SETTING_PATTERN = + /^wpai_feature_(?!.*_access_control_enabled$)(.+)_enabled$/; function isRecord( value: unknown ): value is Record< string, unknown > { return typeof value === 'object' && value !== null; @@ -163,9 +179,19 @@ function parseFeature( value: unknown ): FeatureData | null { capability: toStringValue( feature.capability ) || 'text_generation', usage: parseFeatureUsage( feature.usage ), docsUrl: toStringValue( feature.docsUrl ), + supportsAccessControl: feature.supportsAccessControl === true, }; } +function parseRole( value: unknown ): Role | null { + if ( ! isRecord( value ) ) { + return null; + } + const role = value as Partial< Role >; + const id = toStringValue( role.id ); + return id ? { id, name: toStringValue( role.name ) || id } : null; +} + function getFeatureIdFromSettingName( settingName: string ): string { const match = FEATURE_SETTING_PATTERN.exec( settingName ); return match?.[ 1 ] ?? settingName; @@ -210,6 +236,8 @@ function getPageData(): PageData { connectorsUrl: '', featureGroups: [], features: [], + roles: [], + defaultAccessRoles: [], }; try { @@ -242,6 +270,14 @@ function getPageData(): PageData { connectorsUrl: toStringValue( pageData.connectorsUrl ), featureGroups, features, + roles: Array.isArray( pageData.roles ) + ? pageData.roles.map( parseRole ).filter( isDefined ) + : [], + defaultAccessRoles: Array.isArray( pageData.defaultAccessRoles ) + ? pageData.defaultAccessRoles.filter( + ( id ): id is string => typeof id === 'string' + ) + : [], }; } catch { return fallback; @@ -566,6 +602,7 @@ function FeatureToggleWithSettings( { const feature = FEATURES_BY_SETTING.get( field.id ); const checked = !! field.getValue( { item: data } ); const isDeveloperMode = useDeveloperModeContext(); + const isAccessControlMode = useAccessControlModeContext(); const { isAdvancedSettingsEnabled } = useAdvancedSettingsContext(); return ( @@ -583,6 +620,13 @@ function FeatureToggleWithSettings( { { checked && isAdvancedSettingsEnabled && feature && ( ) } + { checked && + feature?.supportsAccessControl && + ( isAccessControlMode ? ( + + ) : ( + + ) ) } { checked && isDeveloperMode && feature && ( @@ -628,6 +673,13 @@ function VisualCardToggle( { } help={ field.description } /> + { checked && + feature?.supportsAccessControl && + ( isAccessControlMode ? ( + + ) : ( + + ) ) } { checked && isDeveloperMode && feature && ( ( () => { // Return the stable module-level reference when page data is available so @@ -708,6 +762,7 @@ function AISettingsPage() { capability: 'text_generation', usage: null, docsUrl: '', + supportsAccessControl: false, } ); return acc; }, [] ); @@ -834,6 +889,8 @@ function AISettingsPage() { const featureCapability = feature.capability; const featureUsage = feature.usage; const featureDocsUrl = feature.docsUrl; + const featureSupportsAccessControl = + feature.supportsAccessControl; baseField.Edit = ( props ) => ( ); } @@ -947,197 +1005,239 @@ function AISettingsPage() { return ( - } - title={ __( 'AI', 'ai' ) } - subTitle={ - - { __( - 'Turn on stable Features and early-stage Experiments. Experiments may change or be removed in any release, and some run automatically once enabled, so try them on a staging site first.', - 'ai' - ) } - - } - actions={ - <> - - { __( 'Learn', 'ai' ) } - - - { __( 'Docs', 'ai' ) } - - - { __( 'Contribute', 'ai' ) } - - - { () => ( - <> - - { - toggleDeveloperMode(); - } } - > - { __( - 'Model selection', - 'ai' - ) } - - - { __( - 'Advanced settings', - 'ai' - ) } - - - - { - void handleExport(); - } } - > - { __( - 'Export settings', - 'ai' - ) } - - { - fileInputRef.current?.click(); - } } - > - { __( - 'Import settings', - 'ai' - ) } - - - - ) } - - { /* Hidden file input for import */ } - - { pendingImport && ( - { - void handleImportConfirm(); - } } - onCancel={ handleImportCancel } - isImporting={ isImporting } - /> - ) } - - } + - - { ! PAGE_DATA.hasValidCredentials && ( - - - { ! PAGE_DATA.hasCredentials - ? __( - 'The AI plugin requires a valid AI Connector to function properly. Verify you have one or more AI Connectors configured.', - 'ai' - ) - : __( - "Your configured AI Connectors don't support text generation, which most AI features require.", - 'ai' - ) } - - { PAGE_DATA.connectorsUrl && ( - - - { __( 'Manage Connectors', 'ai' ) } - - - ) } - - ) } - { isLoading ? ( + } + title={ __( 'AI', 'ai' ) } + subTitle={ + + { __( + 'Turn on stable Features and early-stage Experiments. Experiments may change or be removed in any release, and some run automatically once enabled, so try them on a staging site first.', + 'ai' + ) } + + } + actions={ + <> + + { __( 'Learn', 'ai' ) } + + + { __( 'Docs', 'ai' ) } + + + { __( 'Contribute', 'ai' ) } + + + { () => ( + <> + + { + toggleDeveloperMode(); + } } + > + { __( + 'Model selection', + 'ai' + ) } + + + { __( + 'Advanced settings', + 'ai' + ) } + + + { __( + 'Access controls', + 'ai' + ) } + + + + { + void handleExport(); + } } + > + { __( + 'Export settings', + 'ai' + ) } + + { + fileInputRef.current?.click(); + } } + > + { __( + 'Import settings', + 'ai' + ) } + + + + ) } + + { /* Hidden file input for import */ } + + { pendingImport && ( + { + void handleImportConfirm(); + } } + onCancel={ handleImportCancel } + isImporting={ isImporting } + /> + ) } + + } + > - + { ! PAGE_DATA.hasValidCredentials && ( + + + { ! PAGE_DATA.hasCredentials + ? __( + 'The AI plugin requires a valid AI Connector to function properly. Verify you have one or more AI Connectors configured.', + 'ai' + ) + : __( + "Your configured AI Connectors don't support text generation, which most AI features require.", + 'ai' + ) } + + { PAGE_DATA.connectorsUrl && ( + + + { __( + 'Manage Connectors', + 'ai' + ) } + + + ) } + + ) } + { isLoading ? ( + + + + ) : ( + + data={ data } + fields={ fields } + form={ form } + onChange={ handleChange } + /> + ) } - ) : ( - - data={ data } - fields={ fields } - form={ form } - onChange={ handleChange } - /> - ) } - - + + + ); diff --git a/routes/ai-home/style.scss b/routes/ai-home/style.scss index 507b5b9e0..89b9f7f5e 100644 --- a/routes/ai-home/style.scss +++ b/routes/ai-home/style.scss @@ -134,6 +134,51 @@ body:has(.ai-settings-page) .components-popover { } } +.ai-access-control-mode-fields { + margin-top: var(--wpds-dimension-gap-md, 12px); + + &__fieldset { + border: none; + margin: 0; + padding: 0; + } + + &__legend { + font-size: 11px; + font-weight: 500; + text-transform: uppercase; + letter-spacing: 0.5px; + margin-bottom: 8px; + } + + &__roles-grid { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 12px; + } + + &__user-search-wrapper { + position: relative; + } + + &__user-search-input { + flex: 1; + } + + &__user-search-spinner { + margin-top: 4px; + position: absolute; + inset-inline-end: 0; + top: 20px; + } +} + +.ai-access-restricted-notice { + margin: 8px 0 0; + font-size: 12px; + color: var(--wpds-color-fg-content-neutral-weak, #757575); +} + /** * Snackbar notifications are rendered full-width by the route shell and, by * default, centered over the (centered) settings content, where they obscure diff --git a/tests/Integration/Includes/Access_Control/Feature_Ability_RegistrationTest.php b/tests/Integration/Includes/Access_Control/Feature_Ability_RegistrationTest.php new file mode 100644 index 000000000..5fd4451f9 --- /dev/null +++ b/tests/Integration/Includes/Access_Control/Feature_Ability_RegistrationTest.php @@ -0,0 +1,60 @@ +getExtension() ) { + continue; + } + // Tokens, not regex, so docblocks that mention the function don't count. + $tokens = token_get_all( (string) file_get_contents( $file->getPathname() ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents, WordPressVIPMinimum.Performance.FetchingRemoteData.FileGetContentsUnknown -- Reading local source in a test. + foreach ( $tokens as $token ) { + if ( ! is_array( $token ) ) { + continue; + } + + $is_call = T_STRING === $token[0] && 'wp_register_ability' === $token[1]; + // PHP 8 tokenizes `\wp_register_ability` as one fully qualified name. + if ( ! $is_call && defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $token[0] ) { // phpcs:ignore PHPCompatibility.Constants.NewConstants.t_name_fully_qualifiedFound -- Guarded by defined() for PHP 7.4. + $is_call = 'wp_register_ability' === ltrim( $token[1], '\\' ); + } + + if ( $is_call ) { + $offenders[] = str_replace( $root . '/', '', $file->getPathname() ); + break; + } + } + } + } + + $this->assertSame( array(), $offenders, 'Register feature abilities with $this->register_feature_ability() so access control applies.' ); + } +} diff --git a/tests/Integration/Includes/Access_Control/Feature_AccessTest.php b/tests/Integration/Includes/Access_Control/Feature_AccessTest.php new file mode 100644 index 000000000..1c06f1379 --- /dev/null +++ b/tests/Integration/Includes/Access_Control/Feature_AccessTest.php @@ -0,0 +1,298 @@ + + */ + public static array $permissions = array(); + + /** + * {@inheritDoc} + * + * @since x.x.x + */ + protected function input_schema(): array { + return array( + 'type' => 'object', + 'properties' => array( 'value' => array( 'type' => 'string' ) ), + 'required' => array( 'value' ), + ); + } + + /** + * {@inheritDoc} + * + * @since x.x.x + */ + protected function output_schema(): array { + return array( + 'type' => 'object', + 'properties' => array( 'echo' => array( 'type' => 'string' ) ), + ); + } + + /** + * {@inheritDoc} + * + * @since x.x.x + */ + protected function execute_callback( $input ) { + return array( 'echo' => $input['value'] ); + } + + /** + * {@inheritDoc} + * + * @since x.x.x + */ + protected function permission_callback( $input ) { + return self::$permissions[ $this->get_name() ] ?? true; + } + + /** + * {@inheritDoc} + * + * @since x.x.x + */ + protected function meta(): array { + return array(); + } +} + +/** + * Feature_Access test case. + * + * @since x.x.x + */ +class Feature_AccessTest extends WP_UnitTestCase { + + private const FEATURE = 'access-test-feature'; + + private static int $admin_id; + private static int $author_id; + private static int $other_author_id; + + /** + * Creates users once for the class. + * + * @param WP_UnitTest_Factory $factory The factory. + */ + public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ): void { + self::$admin_id = $factory->user->create( array( 'role' => 'administrator' ) ); + self::$author_id = $factory->user->create( array( 'role' => 'author' ) ); + self::$other_author_id = $factory->user->create( array( 'role' => 'author' ) ); + } + + /** + * Registers fixture abilities and resets the REST server. + */ + public function setUp(): void { + parent::setUp(); + + global $wp_rest_server; + $wp_rest_server = new WP_REST_Server(); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Resetting the REST server for the test. + do_action( 'rest_api_init', $wp_rest_server ); + + global $wp_current_filter; + $wp_current_filter[] = 'wp_abilities_api_init'; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Faking the action context to register within it. + try { + $this->register_tagged_fixture( 'ai/access-gated', true ); + $this->register_tagged_fixture( 'ai/access-gated-denied', false ); + $this->register_ungated_fixture( 'ai/access-ungated' ); + } finally { + array_pop( $wp_current_filter ); + } + } + + /** + * Cleans up abilities, options and the REST server. + */ + public function tearDown(): void { + foreach ( array( 'ai/access-gated', 'ai/access-ungated', 'ai/access-gated-denied' ) as $name ) { + if ( wp_has_ability( $name ) ) { + wp_unregister_ability( $name ); + } + } + + delete_option( Feature_Access::enabled_option( self::FEATURE ) ); + delete_option( Feature_Access::roles_option( self::FEATURE ) ); + delete_option( Feature_Access::users_option( self::FEATURE ) ); + + Access_Fixture_Ability::$permissions = array(); + + global $wp_rest_server; + $wp_rest_server = null; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Resetting the REST server after the test. + + wp_set_current_user( 0 ); + parent::tearDown(); + } + + /** + * Backwards compatibility: enabling access control without saving a role list changes nothing. + */ + public function test_enabled_without_saved_roles_keeps_todays_access(): void { + update_option( Feature_Access::enabled_option( self::FEATURE ), true ); + + $this->assertTrue( user_can( self::$author_id, Feature_Access::CAPABILITY, self::FEATURE ) ); + $this->assertTrue( user_can( 0, Feature_Access::CAPABILITY, self::FEATURE ), 'Logged-out visitors keep UI hooks as today.' ); + + wp_set_current_user( self::$author_id ); + $this->assertTrue( wp_get_ability( 'ai/access-gated' )->check_permissions( array( 'value' => 'x' ) ) ); + } + + /** + * Backwards compatibility: with access control off, a saved restrictive list is ignored. + */ + public function test_saved_lists_ignored_while_access_control_disabled(): void { + update_option( Feature_Access::roles_option( self::FEATURE ), array() ); + + $this->assertTrue( user_can( self::$author_id, Feature_Access::CAPABILITY, self::FEATURE ) ); + $this->assertTrue( user_can( 0, Feature_Access::CAPABILITY, self::FEATURE ) ); + } + + public function test_listed_user_has_access_without_a_listed_role(): void { + $this->restrict( array( 'administrator' ), array( self::$author_id ) ); + + $this->assertTrue( user_can( self::$author_id, Feature_Access::CAPABILITY, self::FEATURE ) ); + $this->assertFalse( user_can( self::$other_author_id, Feature_Access::CAPABILITY, self::FEATURE ) ); + } + + public function test_empty_roles_and_users_deny_everyone(): void { + $this->restrict( array(), array() ); + + $this->assertFalse( user_can( self::$admin_id, Feature_Access::CAPABILITY, self::FEATURE ) ); + $this->assertFalse( user_can( 0, Feature_Access::CAPABILITY, self::FEATURE ) ); + } + + public function test_restricted_user_cannot_run_tagged_ability_directly(): void { + $this->restrict( array( 'administrator' ), array() ); + + wp_set_current_user( self::$author_id ); + $denied = wp_get_ability( 'ai/access-gated' )->check_permissions( array( 'value' => 'x' ) ); + $this->assertWPError( $denied ); + $this->assertSame( 'wpai_feature_access_denied', $denied->get_error_code() ); + + // Core reports a WP_Error permission result from execute() as incorrect usage. + $this->setExpectedIncorrectUsage( 'WP_Ability::execute' ); + $this->assertWPError( wp_get_ability( 'ai/access-gated' )->execute( array( 'value' => 'x' ) ) ); + + wp_set_current_user( self::$admin_id ); + $this->assertTrue( wp_get_ability( 'ai/access-gated' )->check_permissions( array( 'value' => 'x' ) ) ); + } + + public function test_rest_run_endpoint_denies_restricted_user(): void { + $this->restrict( array( 'administrator' ), array() ); + wp_set_current_user( self::$author_id ); + + $request = new WP_REST_Request( 'POST', '/wp-abilities/v1/abilities/ai/access-gated/run' ); + $request->set_header( 'Content-Type', 'application/json' ); + $request->set_body( wp_json_encode( array( 'input' => array( 'value' => 'x' ) ) ) ); + $response = rest_do_request( $request ); + + $this->assertSame( 403, $response->get_status() ); + $this->assertSame( 'wpai_feature_access_denied', $response->get_data()['code'] ); + } + + public function test_untagged_ability_is_not_gated(): void { + $this->restrict( array( 'administrator' ), array() ); + wp_set_current_user( self::$author_id ); + + $this->assertTrue( wp_get_ability( 'ai/access-ungated' )->check_permissions( array( 'value' => 'x' ) ) ); + } + + public function test_access_never_grants_what_permission_callback_denies(): void { + $this->restrict( array( 'administrator' ), array() ); + wp_set_current_user( self::$admin_id ); + + $this->assertFalse( wp_get_ability( 'ai/access-gated-denied' )->check_permissions( array( 'value' => 'x' ) ) ); + } + + /** + * Enables access control for the fixture feature with the given lists. + * + * @param list $roles Allowed roles. + * @param list $users Allowed user IDs. + */ + private function restrict( array $roles, array $users ): void { + update_option( Feature_Access::enabled_option( self::FEATURE ), true ); + update_option( Feature_Access::roles_option( self::FEATURE ), $roles ); + update_option( Feature_Access::users_option( self::FEATURE ), $users ); + } + + /** + * Registers one fixture ability tagged with the fixture feature. + * + * Uses an Abstract_Ability subclass so the permission filter polyfill + * applies on WordPress 7.0.x. + * + * @param string $name Ability name. + * @param bool $permission Result of the ability's own permission callback. + */ + private function register_tagged_fixture( string $name, bool $permission ): void { + Access_Fixture_Ability::$permissions[ $name ] = $permission; + + wp_register_ability( + $name, + array( + 'label' => $name, + 'description' => 'Access control fixture.', + 'category' => WPAI_DEFAULT_ABILITY_CATEGORY, + 'ability_class' => Access_Fixture_Ability::class, + 'meta' => array( + 'show_in_rest' => true, + Feature_Access::ABILITY_META_KEY => self::FEATURE, + ), + ) + ); + } + + /** + * Registers one untagged fixture ability. + * + * @param string $name Ability name. + */ + private function register_ungated_fixture( string $name ): void { + wp_register_ability( + $name, + array( + 'label' => $name, + 'description' => 'Access control fixture.', + 'category' => WPAI_DEFAULT_ABILITY_CATEGORY, + 'input_schema' => array( + 'type' => 'object', + 'properties' => array( 'value' => array( 'type' => 'string' ) ), + 'required' => array( 'value' ), + ), + 'execute_callback' => static fn( array $input ): array => array( 'echo' => $input['value'] ), + 'permission_callback' => static fn(): bool => true, + 'meta' => array( 'show_in_rest' => true ), + ) + ); + } +} diff --git a/tests/Integration/Includes/Experiment_LoaderTest.php b/tests/Integration/Includes/Experiment_LoaderTest.php index fb3d3d8b9..771403a42 100644 --- a/tests/Integration/Includes/Experiment_LoaderTest.php +++ b/tests/Integration/Includes/Experiment_LoaderTest.php @@ -9,6 +9,7 @@ use WP_UnitTestCase; use WordPress\AI\Abstracts\Abstract_Feature; +use WordPress\AI\Access_Control\Feature_Access; use WordPress\AI\Experiments\Experiment_Category; use WordPress\AI\Features\Loader; use WordPress\AI\Features\Registry; @@ -26,6 +27,13 @@ class Mock_Experiment extends Abstract_Feature { */ public $register_called = false; + /** + * Tracks if register_ui was called. + * + * @var bool + */ + public $register_ui_called = false; + /** * {@inheritDoc} */ @@ -38,8 +46,9 @@ public static function get_id(): string { */ protected function load_metadata(): array { return array( - 'label' => 'Mock Experiment', - 'description' => 'A mock experiment for testing', + 'label' => 'Mock Experiment', + 'description' => 'A mock experiment for testing', + 'access_control' => true, ); } @@ -50,6 +59,13 @@ public function register(): void { $this->register_called = true; } + /** + * {@inheritDoc} + */ + public function register_ui(): void { + $this->register_ui_called = true; + } + /** * {@inheritDoc} */ @@ -58,6 +74,30 @@ public function get_preloaded_options(): array { } } +/** + * Test experiment that does not opt in to access control. + * + * @since x.x.x + */ +class Mock_Opted_Out_Experiment extends Mock_Experiment { + /** + * {@inheritDoc} + */ + public static function get_id(): string { + return 'mock-opted-out-experiment'; + } + + /** + * {@inheritDoc} + */ + protected function load_metadata(): array { + return array( + 'label' => 'Mock Opted Out Experiment', + 'description' => 'A mock experiment that does not opt in to access control', + ); + } +} + /** * Experiment that throws during instantiation. * @@ -506,6 +546,72 @@ private function queries_naming( string $needle, callable $callback, bool $using return $queries; } + /** + * Users without access get the feature's infrastructure but not its UI. + * + * @since x.x.x + */ + public function test_register_ui_skipped_for_user_without_access(): void { + update_option( 'wpai_feature_mock-experiment_enabled', true ); + update_option( Feature_Access::enabled_option( 'mock-experiment' ), true ); + update_option( Feature_Access::roles_option( 'mock-experiment' ), array( 'administrator' ) ); + wp_set_current_user( self::factory()->user->create( array( 'role' => 'author' ) ) ); + + $experiment = new Mock_Experiment(); + $this->registry->register_feature( $experiment ); + $this->invoke_initialize_features(); + + $this->assertTrue( $experiment->register_called, 'register() must still run for everyone.' ); + $this->assertFalse( $experiment->register_ui_called, 'register_ui() must not run without access.' ); + + delete_option( 'wpai_feature_mock-experiment_enabled' ); + delete_option( Feature_Access::enabled_option( 'mock-experiment' ) ); + delete_option( Feature_Access::roles_option( 'mock-experiment' ) ); + wp_set_current_user( 0 ); + } + + /** + * Users with access get the feature's UI. + * + * @since x.x.x + */ + public function test_register_ui_runs_for_user_with_access(): void { + update_option( 'wpai_feature_mock-experiment_enabled', true ); + wp_set_current_user( self::factory()->user->create( array( 'role' => 'author' ) ) ); + + $experiment = new Mock_Experiment(); + $this->registry->register_feature( $experiment ); + $this->invoke_initialize_features(); + + $this->assertTrue( $experiment->register_ui_called ); + + delete_option( 'wpai_feature_mock-experiment_enabled' ); + wp_set_current_user( 0 ); + } + + /** + * Leftover restricting options never gate a feature that has not opted in. + * + * @since x.x.x + */ + public function test_register_ui_runs_for_feature_not_opted_in_despite_saved_restriction(): void { + update_option( 'wpai_feature_mock-opted-out-experiment_enabled', true ); + update_option( Feature_Access::enabled_option( 'mock-opted-out-experiment' ), true ); + update_option( Feature_Access::roles_option( 'mock-opted-out-experiment' ), array( 'administrator' ) ); + wp_set_current_user( self::factory()->user->create( array( 'role' => 'author' ) ) ); + + $experiment = new Mock_Opted_Out_Experiment(); + $this->registry->register_feature( $experiment ); + $this->invoke_initialize_features(); + + $this->assertTrue( $experiment->register_ui_called, 'register_ui() must run for everyone when the feature has not opted in.' ); + + delete_option( 'wpai_feature_mock-opted-out-experiment_enabled' ); + delete_option( Feature_Access::enabled_option( 'mock-opted-out-experiment' ) ); + delete_option( Feature_Access::roles_option( 'mock-opted-out-experiment' ) ); + wp_set_current_user( 0 ); + } + /** * Calls the private Loader::initialize_features method via reflection. */ diff --git a/tests/Integration/Includes/Experiments/Comment_Moderation/Comment_ModerationTest.php b/tests/Integration/Includes/Experiments/Comment_Moderation/Comment_ModerationTest.php index c5650263b..bf153c4eb 100644 --- a/tests/Integration/Includes/Experiments/Comment_Moderation/Comment_ModerationTest.php +++ b/tests/Integration/Includes/Experiments/Comment_Moderation/Comment_ModerationTest.php @@ -128,6 +128,7 @@ public function test_experiment_registration() { public function test_register_adds_expected_hooks() { $experiment = new Comment_Moderation(); $experiment->register(); + $experiment->register_ui(); $this->assertIsInt( has_action( 'wp_abilities_api_init', array( $experiment, 'register_abilities' ) ) ); $this->assertIsInt( has_action( 'wp_insert_comment', array( $experiment, 'moderate_comment' ) ) ); diff --git a/tests/Integration/Includes/Experiments/Content_Resizing/Content_ResizingTest.php b/tests/Integration/Includes/Experiments/Content_Resizing/Content_ResizingTest.php index 7e8d64762..a1749d408 100644 --- a/tests/Integration/Includes/Experiments/Content_Resizing/Content_ResizingTest.php +++ b/tests/Integration/Includes/Experiments/Content_Resizing/Content_ResizingTest.php @@ -107,6 +107,7 @@ public function test_experiment_metadata() { public function test_register_hooks_actions() { $experiment = new Content_Resizing(); $experiment->register(); + $experiment->register_ui(); $this->assertNotFalse( has_action( 'wp_abilities_api_init', array( $experiment, 'register_abilities' ) ), diff --git a/tests/Integration/Includes/Experiments/Content_Translation/Content_TranslationTest.php b/tests/Integration/Includes/Experiments/Content_Translation/Content_TranslationTest.php index 3fb4736a0..52f3ecb2c 100644 --- a/tests/Integration/Includes/Experiments/Content_Translation/Content_TranslationTest.php +++ b/tests/Integration/Includes/Experiments/Content_Translation/Content_TranslationTest.php @@ -123,6 +123,7 @@ public function test_experiment_metadata(): void { public function test_register_hooks_actions(): void { $experiment = new Content_Translation(); $experiment->register(); + $experiment->register_ui(); $this->assertNotFalse( has_action( diff --git a/tests/Integration/Includes/Experiments/Meta_Description/Meta_DescriptionTest.php b/tests/Integration/Includes/Experiments/Meta_Description/Meta_DescriptionTest.php index 97b78f06c..eefabc028 100644 --- a/tests/Integration/Includes/Experiments/Meta_Description/Meta_DescriptionTest.php +++ b/tests/Integration/Includes/Experiments/Meta_Description/Meta_DescriptionTest.php @@ -95,6 +95,7 @@ public function test_experiment_can_be_disabled_via_filter(): void { public function test_register_hooks_actions(): void { $experiment = new Meta_Description(); $experiment->register(); + $experiment->register_ui(); $this->assertNotFalse( has_action( 'wp_abilities_api_init', array( $experiment, 'register_abilities' ) ), diff --git a/tests/Integration/Includes/Experiments/Slug_Generation/Slug_GenerationTest.php b/tests/Integration/Includes/Experiments/Slug_Generation/Slug_GenerationTest.php index 72d68f5c9..90ea7bab1 100644 --- a/tests/Integration/Includes/Experiments/Slug_Generation/Slug_GenerationTest.php +++ b/tests/Integration/Includes/Experiments/Slug_Generation/Slug_GenerationTest.php @@ -75,6 +75,7 @@ public function test_experiment_registration() { public function test_register_adds_hooks() { $experiment = new Slug_Generation(); $experiment->register(); + $experiment->register_ui(); $this->assertIsInt( has_action( 'wp_abilities_api_init', array( $experiment, 'register_abilities' ) ), 'Should register abilities hook' ); $this->assertIsInt( has_action( 'admin_enqueue_scripts', array( $experiment, 'enqueue_assets' ) ), 'Should register assets hook' ); } diff --git a/tests/Integration/Includes/Experiments/Suggest_Reply/Suggest_ReplyTest.php b/tests/Integration/Includes/Experiments/Suggest_Reply/Suggest_ReplyTest.php index 3ec3ae51d..2fa945104 100644 --- a/tests/Integration/Includes/Experiments/Suggest_Reply/Suggest_ReplyTest.php +++ b/tests/Integration/Includes/Experiments/Suggest_Reply/Suggest_ReplyTest.php @@ -92,6 +92,7 @@ public function test_experiment_registration() { public function test_register_adds_expected_hooks() { $experiment = new Suggest_Reply(); $experiment->register(); + $experiment->register_ui(); $this->assertIsInt( has_action( 'wp_abilities_api_init', array( $experiment, 'register_abilities' ) ) ); $this->assertIsInt( has_filter( 'comment_row_actions', array( $experiment, 'add_row_action' ) ) ); diff --git a/tests/Integration/Includes/Experiments/Summarization/SummarizationTest.php b/tests/Integration/Includes/Experiments/Summarization/SummarizationTest.php index 94e332148..516176d48 100644 --- a/tests/Integration/Includes/Experiments/Summarization/SummarizationTest.php +++ b/tests/Integration/Includes/Experiments/Summarization/SummarizationTest.php @@ -91,6 +91,7 @@ public function test_register_uses_block_editor_assets_hook() { try { $experiment->register(); + $experiment->register_ui(); $this->assertSame( 5, @@ -639,6 +640,7 @@ public function test_register_wires_bulk_action_hooks_via_load_edit(): void { try { $experiment->register(); + $experiment->register_ui(); $this->assertNotFalse( has_action( 'load-edit.php', array( $experiment, 'register_bulk_action_hooks_for_screen' ) ) diff --git a/tests/Integration/Includes/Experiments/Text_To_Speech/REST_ControllerTest.php b/tests/Integration/Includes/Experiments/Text_To_Speech/REST_ControllerTest.php index d5d41015a..1de5658b2 100644 --- a/tests/Integration/Includes/Experiments/Text_To_Speech/REST_ControllerTest.php +++ b/tests/Integration/Includes/Experiments/Text_To_Speech/REST_ControllerTest.php @@ -10,6 +10,7 @@ use WP_REST_Request; use WP_REST_Server; use WP_UnitTestCase; +use WordPress\AI\Access_Control\Feature_Access; use WordPress\AI\Experiments\Text_To_Speech\Job_Manager; use WordPress\AI\Experiments\Text_To_Speech\REST_Controller; @@ -221,4 +222,24 @@ public function test_missing_post_returns_404(): void { $this->assertSame( 404, $response->get_status() ); } + + /** + * The TTS routes are not abilities, so they must apply feature access control themselves. + * + * @since x.x.x + */ + public function test_post_denied_for_user_without_feature_access(): void { + update_option( Feature_Access::enabled_option( 'text-to-speech' ), true ); + update_option( Feature_Access::roles_option( 'text-to-speech' ), array( 'administrator' ) ); + wp_set_current_user( self::factory()->user->create( array( 'role' => 'editor' ) ) ); + $post_id = self::factory()->post->create( array( 'post_content' => 'Some content to read.' ) ); + + $response = rest_do_request( new WP_REST_Request( 'POST', '/ai/v1/text-to-speech/' . $post_id ) ); + + $this->assertSame( 403, $response->get_status() ); + $this->assertSame( 'wpai_feature_access_denied', $response->get_data()['code'] ); + + delete_option( Feature_Access::enabled_option( 'text-to-speech' ) ); + delete_option( Feature_Access::roles_option( 'text-to-speech' ) ); + } } diff --git a/tests/Integration/Includes/Experiments/Title_Generation/Title_GenerationTest.php b/tests/Integration/Includes/Experiments/Title_Generation/Title_GenerationTest.php index 527dc7dac..0e9474853 100644 --- a/tests/Integration/Includes/Experiments/Title_Generation/Title_GenerationTest.php +++ b/tests/Integration/Includes/Experiments/Title_Generation/Title_GenerationTest.php @@ -79,6 +79,7 @@ public function test_experiment_registration() { public function test_register_adds_hooks() { $experiment = new Title_Generation(); $experiment->register(); + $experiment->register_ui(); $this->assertIsInt( has_action( 'wp_abilities_api_init', array( $experiment, 'register_abilities' ) ), 'Should register abilities hook' ); $this->assertIsInt( has_action( 'admin_enqueue_scripts', array( $experiment, 'enqueue_assets' ) ), 'Should register assets hook' ); } diff --git a/tests/Integration/Includes/Experiments/Type_Ahead/Type_AheadTest.php b/tests/Integration/Includes/Experiments/Type_Ahead/Type_AheadTest.php index f3ad74894..be9fc63bd 100644 --- a/tests/Integration/Includes/Experiments/Type_Ahead/Type_AheadTest.php +++ b/tests/Integration/Includes/Experiments/Type_Ahead/Type_AheadTest.php @@ -98,6 +98,7 @@ public function test_experiment_can_be_disabled_via_filter() { public function test_register_hooks_actions() { $experiment = new Type_Ahead(); $experiment->register(); + $experiment->register_ui(); $this->assertNotFalse( has_action( 'wp_abilities_api_init', array( $experiment, 'register_abilities' ) ), diff --git a/tests/Integration/Includes/Features/Image_Generation/Image_GenerationTest.php b/tests/Integration/Includes/Features/Image_Generation/Image_GenerationTest.php index 8820d191c..88869d37c 100644 --- a/tests/Integration/Includes/Features/Image_Generation/Image_GenerationTest.php +++ b/tests/Integration/Includes/Features/Image_Generation/Image_GenerationTest.php @@ -122,6 +122,7 @@ public function test_feature_registers_abilities() { public function test_register_hooks_enqueue_block_editor_assets(): void { $feature = new Image_Generation(); $feature->register(); + $feature->register_ui(); $this->assertNotFalse( has_action( 'enqueue_block_editor_assets', array( $feature, 'enqueue_inline_assets' ) ), @@ -153,6 +154,7 @@ public function test_feature_registers_post_meta() { public function test_register_hooks_admin_menu() { $feature = new Image_Generation(); $feature->register(); + $feature->register_ui(); $this->assertNotFalse( has_action( 'admin_menu', array( $feature, 'register_admin_menu' ) ), 'admin_menu hook should be registered' ); $this->assertNotFalse( has_action( 'admin_footer-upload.php', array( $feature, 'inject_generate_image_button' ) ), 'admin_footer-upload.php hook should be registered' ); diff --git a/tests/Integration/Includes/REST/Settings_IO_ControllerTest.php b/tests/Integration/Includes/REST/Settings_IO_ControllerTest.php index a1e84ca9c..2899f2104 100644 --- a/tests/Integration/Includes/REST/Settings_IO_ControllerTest.php +++ b/tests/Integration/Includes/REST/Settings_IO_ControllerTest.php @@ -10,6 +10,7 @@ use WP_REST_Request; use WP_UnitTestCase; use WordPress\AI\Abstracts\Abstract_Feature; +use WordPress\AI\Access_Control\Feature_Access; use WordPress\AI\Features\Registry; use WordPress\AI\REST\Settings_IO_Controller; use WordPress\AI\Settings\Settings_Registration; @@ -30,8 +31,9 @@ public static function get_id(): string { */ protected function load_metadata(): array { return array( - 'label' => 'IO Test Feature', - 'description' => 'A feature for IO controller testing.', + 'label' => 'IO Test Feature', + 'description' => 'A feature for IO controller testing.', + 'access_control' => true, ); } @@ -79,6 +81,9 @@ public function tearDown(): void { delete_option( 'wpai_feature_io-test-feature_field_developer' ); unregister_setting( Settings_Registration::OPTION_GROUP, 'wpai_feature_io-test-feature_enabled' ); unregister_setting( Settings_Registration::OPTION_GROUP, 'wpai_feature_io-test-feature_field_developer' ); + unregister_setting( Settings_Registration::ACCESS_CONTROL_OPTION_GROUP, Feature_Access::enabled_option( 'io-test-feature' ) ); + unregister_setting( Settings_Registration::ACCESS_CONTROL_OPTION_GROUP, Feature_Access::roles_option( 'io-test-feature' ) ); + unregister_setting( Settings_Registration::ACCESS_CONTROL_OPTION_GROUP, Feature_Access::users_option( 'io-test-feature' ) ); parent::tearDown(); } @@ -758,5 +763,55 @@ public function test_import_of_exported_default_setting_restores_default_state() $this->assertSame( 0, $data['rejected'] ); $this->assertFalse( (bool) get_option( 'wpai_feature_io-test-feature_enabled' ) ); } + + /** + * Access control policies are site-specific and must never travel in exports. + * + * @since x.x.x + */ + public function test_export_excludes_access_control_settings(): void { + update_option( Feature_Access::enabled_option( 'io-test-feature' ), true ); + update_option( Feature_Access::roles_option( 'io-test-feature' ), array( 'editor' ) ); + update_option( Feature_Access::users_option( 'io-test-feature' ), array( 1 ) ); + + $this->controller->init(); + // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound + do_action( 'rest_api_init' ); + wp_set_current_user( $this->factory->user->create( array( 'role' => 'administrator' ) ) ); + + $data = rest_get_server()->dispatch( new WP_REST_Request( 'GET', '/ai/v1/settings/export' ) )->get_data(); + + $this->assertArrayHasKey( 'wpai_feature_io-test-feature_enabled', $data['settings'] ); + $this->assertArrayNotHasKey( Feature_Access::enabled_option( 'io-test-feature' ), $data['settings'] ); + $this->assertArrayNotHasKey( Feature_Access::roles_option( 'io-test-feature' ), $data['settings'] ); + $this->assertArrayNotHasKey( Feature_Access::users_option( 'io-test-feature' ), $data['settings'] ); + } + + /** + * Unset roles mean "no role restriction", so the settings endpoint must + * report them as null and must be able to return them to unset. + * + * @since x.x.x + */ + public function test_roles_setting_round_trips_null_as_unset(): void { + // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound + do_action( 'rest_api_init' ); + wp_set_current_user( $this->factory->user->create( array( 'role' => 'administrator' ) ) ); + $roles_key = Feature_Access::roles_option( 'io-test-feature' ); + + $data = rest_get_server()->dispatch( new WP_REST_Request( 'GET', '/wp/v2/settings' ) )->get_data(); + $this->assertArrayHasKey( $roles_key, $data ); + $this->assertNull( $data[ $roles_key ] ); + + $set = new WP_REST_Request( 'POST', '/wp/v2/settings' ); + $set->set_param( $roles_key, array( 'editor' ) ); + rest_get_server()->dispatch( $set ); + $this->assertSame( array( 'editor' ), get_option( $roles_key ) ); + + $reset = new WP_REST_Request( 'POST', '/wp/v2/settings' ); + $reset->set_param( $roles_key, null ); + rest_get_server()->dispatch( $reset ); + $this->assertSame( 'unset', get_option( $roles_key, 'unset' ) ); + } } diff --git a/tests/e2e/specs/admin/settings.spec.js b/tests/e2e/specs/admin/settings.spec.js index c9c8807b0..5cd35675f 100644 --- a/tests/e2e/specs/admin/settings.spec.js +++ b/tests/e2e/specs/admin/settings.spec.js @@ -22,6 +22,9 @@ const { disableAdvancedSettings, enableModelSelection, disableModelSelection, + enableAccessControls, + disableAccessControls, + resetFeatureAccessSettings, } = require( '../../utils/helpers' ); const EXPERIMENT_GROUPS = { @@ -680,4 +683,104 @@ test.describe( 'Plugin settings', () => { // Restore state. await disableModelSelection( page ); } ); + + test( 'Access controls: saved roles persist and stay visible when the view is off', async ( { + admin, + page, + requestUtils, + } ) => { + try { + await enableExperiment( admin, page, 'Title Generation' ); + await visitSettingsPage( admin ); + await enableAccessControls( page ); + + const section = page + .locator( '.dataforms-layouts-regular__field', { + has: page.getByText( 'Title Generation', { exact: true } ), + } ) + .first(); + const form = section.locator( '.ai-access-control-mode-fields' ); + + const toggle = form.getByRole( 'checkbox', { + name: 'Enable access control', + } ); + + // Turning the toggle on and off again on a fresh feature leaves nothing to save. + await toggle.check(); + await toggle.uncheck(); + await expect( + form.getByRole( 'button', { name: 'Save' } ) + ).toBeHidden(); + + await toggle.check(); + + // Before saving, nothing is persisted: roles are still unset (today's access). + const settingsBeforeSave = await requestUtils.rest( { + path: '/wp/v2/settings', + } ); + expect( + settingsBeforeSave[ 'wpai_feature_title-generation_roles' ] + ).toBeNull(); + + // Administrator and Editor are pre-checked, and saving them untouched persists them. + await expect( + form.getByRole( 'checkbox', { name: 'Administrator' } ) + ).toBeChecked(); + await expect( + form.getByRole( 'checkbox', { name: 'Editor' } ) + ).toBeChecked(); + await expect( + form.getByRole( 'checkbox', { name: 'Author' } ) + ).not.toBeChecked(); + await form.getByRole( 'button', { name: 'Save' } ).click(); + await expect( + page + .getByTestId( 'snackbar' ) + .filter( { hasText: 'Access control settings saved.' } ) + ).toBeVisible(); + const settingsAfterSave = await requestUtils.rest( { + path: '/wp/v2/settings', + } ); + expect( + [ + ...settingsAfterSave[ + 'wpai_feature_title-generation_roles' + ], + ].sort() + ).toEqual( [ 'administrator', 'editor' ] ); + + await form.getByRole( 'checkbox', { name: 'Editor' } ).uncheck(); + await form.getByRole( 'checkbox', { name: 'Author' } ).check(); + await form.getByRole( 'button', { name: 'Save' } ).click(); + await expect( + page + .getByTestId( 'snackbar' ) + .filter( { hasText: 'Access control settings saved.' } ) + ).toBeVisible(); + + await page.reload(); + await expect( + form.getByRole( 'checkbox', { name: 'Enable access control' } ) + ).toBeChecked(); + await expect( + form.getByRole( 'checkbox', { name: 'Author' } ) + ).toBeChecked(); + await expect( + form.getByRole( 'checkbox', { name: 'Editor' } ) + ).not.toBeChecked(); + + await disableAccessControls( page ); + await expect( + section.getByText( + 'Access restricted to selected roles and users.' + ) + ).toBeVisible(); + } finally { + await resetFeatureAccessSettings( + requestUtils, + 'title-generation' + ); + await disableExperiment( admin, page, 'Title Generation' ); + } + } ); } ); diff --git a/tests/e2e/utils/helpers.ts b/tests/e2e/utils/helpers.ts index cd22f586b..9398f5a9a 100644 --- a/tests/e2e/utils/helpers.ts +++ b/tests/e2e/utils/helpers.ts @@ -471,6 +471,27 @@ export const clearCredentials = async ( requestUtils: RequestUtils ) => { } ); }; +/** + * Resets a feature's access control settings to their defaults. + * + * @param requestUtils The requestUtils fixture from the test context. + * @param featureId The feature ID, e.g. 'title-generation'. + */ +export const resetFeatureAccessSettings = async ( + requestUtils: RequestUtils, + featureId: string +) => { + await requestUtils.rest( { + path: '/wp/v2/settings', + method: 'POST', + data: { + [ `wpai_feature_${ featureId }_access_control_enabled` ]: false, + [ `wpai_feature_${ featureId }_roles` ]: null, + [ `wpai_feature_${ featureId }_users` ]: [], + }, + } ); +}; + /** * Enables the Model Selection feature via the Developer Tools menu. * @@ -614,6 +635,67 @@ export const disableAdvancedSettings = async ( page: Page ) => { await page.keyboard.press( 'Escape' ); }; +/** + * Enables the Access Controls feature via the Developer Tools menu. + * + * Opens the Developer Tools menu, checks whether Access Controls is already + * enabled, and clicks it only when it is not. Closes the menu afterwards. + * + * @param page The page object. + */ +export const enableAccessControls = async ( page: Page ) => { + await page.getByRole( 'button', { name: 'Developer Tools' } ).click(); + + await expect( page.getByText( 'DEVELOPER TOOLS' ) ).toBeVisible(); + + const accessControls = page.getByRole( 'menuitemcheckbox', { + name: /Access controls/, + } ); + + await expect( accessControls ).toBeVisible(); + + if ( ( await accessControls.getAttribute( 'aria-checked' ) ) !== 'true' ) { + await accessControls.click(); + + // Verify the menu remains open after toggling the option. + await expect( + page.getByRole( 'menuitemcheckbox', { name: /Access controls/ } ) + ).toBeVisible(); + } + + // Close the menu. + await page.keyboard.press( 'Escape' ); +}; + +/** + * Disables the Access Controls feature via the Developer Tools menu. + * + * Opens the Developer Tools menu and clicks the Access Controls item to + * toggle it off, then closes the menu. + * + * @param page The page object. + */ +export const disableAccessControls = async ( page: Page ) => { + await page.getByRole( 'button', { name: 'Developer Tools' } ).click(); + + const accessControls = page.getByRole( 'menuitemcheckbox', { + name: /Access controls/, + } ); + + // Only click if it is currently enabled. + if ( ( await accessControls.getAttribute( 'aria-checked' ) ) === 'true' ) { + await accessControls.click(); + + // Verify the menu remains open after toggling the option. + await expect( + page.getByRole( 'menuitemcheckbox', { name: /Access controls/ } ) + ).toBeVisible(); + } + + // Close the menu. + await page.keyboard.press( 'Escape' ); +}; + /** * Opens the Document Overview (List View) in the block editor. *