Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
89.80% covered (warning)
89.80%
220 / 245
73.33% covered (warning)
73.33%
22 / 30
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_AI_Sidebar
90.16% covered (success)
90.16%
220 / 244
73.33% covered (warning)
73.33%
22 / 30
136.16
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
 maybe_enqueue_abilities_script
92.31% covered (success)
92.31%
24 / 26
0.00% covered (danger)
0.00%
0 / 1
7.02
 get_asset_data_from_file
30.00% covered (danger)
30.00%
3 / 10
0.00% covered (danger)
0.00%
0 / 1
13.57
 get_asset_data_from_remote
27.27% covered (danger)
27.27%
3 / 11
0.00% covered (danger)
0.00%
0 / 1
25.85
 register_provider
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
5.03
 get_ai_sidebar_asset_data
78.57% covered (warning)
78.57%
11 / 14
0.00% covered (danger)
0.00%
0 / 1
7.48
 is_seo_suggestions_enabled
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
 is_jetpack_ai_sidebar_preview_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 is_host_enabled
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
6
 has_enabled_sidebar_features
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 should_expose_provider
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 is_agents_manager_disconnected
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 get_jetpack_ai_sidebar_preview_config
100.00% covered (success)
100.00%
28 / 28
100.00% covered (success)
100.00%
1 / 1
11
 is_toolbar_button_enabled
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 register_toolbar_button_extension
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 is_agent_notice_enabled
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
 is_wordpress_agent_enabled
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 is_wordpress_agent_eligible
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 has_wordpress_agent_plan
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 register_agent_notice_extension
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
4
 can_current_user_enable_agent
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 is_agent_action_available
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 add_agents_manager_data
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
 get_agents_manager_data_fields
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 enable_agents_manager_on_provider_surfaces
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 maybe_patch_jetpack_ai_sidebar_preview_data
95.65% covered (success)
95.65%
22 / 23
0.00% covered (danger)
0.00%
0 / 1
8
 get_agent_provider_upsert_script
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 is_block_editor
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
 is_supported_provider_surface
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
6
 has_ai_features
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2/**
3 * Jetpack AI Sidebar — Agents Manager integration and provider registration.
4 *
5 * Initializes the jetpack-agents-manager package so it loads the Agents
6 * Manager bundle and emits its `agentsManagerData` payload, registers Jetpack
7 * AI as an Agents Manager provider, and loads the Jetpack AI provider bundle
8 * that exposes Jetpack AI abilities in the block editor.
9 *
10 * @package automattic/jetpack
11 */
12
13namespace Automattic\Jetpack\Extensions\AiAssistantPlugin;
14
15use Automattic\Jetpack\Agents_Manager\Agents_Manager;
16use Automattic\Jetpack\Connection\Manager as Connection_Manager;
17use Automattic\Jetpack\Current_Plan;
18use Automattic\Jetpack\SEO\Ai_Seo;
19use Automattic\Jetpack\Status;
20use Automattic\Jetpack\Status\Host;
21
22// Required directly rather than relying on the plugin bootstrap: on
23// WordPress.com Simple the extension files load through wpcom's own loader
24// and load-jetpack.php never runs.
25require_once __DIR__ . '/../../../../_inc/lib/class-jetpack-ai-settings.php';
26
27const AM_ASSET_BASE_PATH                  = 'widgets.wp.com/agents-manager/';
28const AI_SIDEBAR_ASSET_TRANSIENT          = 'jetpack_ai_sidebar_asset';
29const AI_SIDEBAR_JS_URL                   = 'https://' . AM_ASSET_BASE_PATH . 'jetpack-ai-sidebar.min.js';
30const AI_SIDEBAR_CSS_URL                  = 'https://' . AM_ASSET_BASE_PATH . 'jetpack-ai-sidebar.css';
31const AI_SIDEBAR_RTL_CSS_URL              = 'https://' . AM_ASSET_BASE_PATH . 'jetpack-ai-sidebar.rtl.css';
32const AI_SIDEBAR_PROVIDER_URL             = 'https://' . AM_ASSET_BASE_PATH . 'jetpack-ai-sidebar.provider.mjs';
33const AI_SIDEBAR_AGENT_ID                 = 'wp-orchestrator';
34const AI_SIDEBAR_TOOLBAR_BUTTON_EXTENSION = 'ai-sidebar-toolbar-button';
35const AI_SIDEBAR_AGENT_NOTICE_EXTENSION   = 'ai-sidebar-agent-notice';
36const AI_SIDEBAR_AGENT_SUPPORT_EXTENSION  = 'ai-sidebar-agent-support';
37const AI_SIDEBAR_AGENT_ENABLE_EXTENSION   = 'ai-sidebar-agent-enable';
38
39/**
40 * Initializes the Agents Manager package and registers the Jetpack AI
41 * provider in the block editor.
42 */
43class Jetpack_AI_Sidebar {
44
45    /**
46     * Initialize hooks.
47     *
48     * @return void
49     */
50    public static function init(): void {
51        // Ahead of the sidebar gate: the notice also shows on sites merely eligible for the Agent.
52        add_action( 'jetpack_register_gutenberg_extensions', array( __CLASS__, 'register_agent_notice_extension' ), 99 );
53
54        // Gate the whole sidebar entrypoint on the preview surface, which is
55        // itself overridable via the jetpack_ai_sidebar_enabled filter.
56        if ( ! self::is_jetpack_ai_sidebar_preview_enabled() ) {
57            return;
58        }
59
60        // Initialize the Agents Manager package so it owns loading the Agents
61        // Manager bundle and emitting the `agentsManagerData` payload. The call
62        // is idempotent: on WordPress.com and Atomic, jetpack-mu-wpcom may have
63        // already initialized it, in which case this is a no-op.
64        Agents_Manager::init();
65
66        // Register as Agents Manager provider. The filter fires inside
67        // Agents_Manager::enqueue_scripts(). Priority 20 so Jetpack loads
68        // AFTER Image Studio (priority 10).
69        add_filter( 'agents_manager_agent_providers', array( __CLASS__, 'register_provider' ), 20 );
70
71        add_filter( 'jetpack_ai_sidebar_agents_manager_data', array( __CLASS__, 'add_agents_manager_data' ), 10, 1 );
72
73        // Ask the Agents Manager package to mount on Jetpack AI provider surfaces.
74        add_filter( 'agents_manager_enabled_in_block_editor', array( __CLASS__, 'enable_agents_manager_on_provider_surfaces' ) );
75
76        // Enqueue the IIFE bundle on supported editor surfaces — it registers
77        // Jetpack AI abilities via @wordpress/abilities, which Big Sky or the
78        // Agents Manager can discover regardless of which provider system is active.
79        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'maybe_enqueue_abilities_script' ), 201 );
80
81        // Patch Jetpack AI Sidebar Preview data into agentsManagerData when the
82        // Agents Manager bundle was enqueued by an external host (Big Sky on
83        // Atomic, etc.) and the jetpack_ai_sidebar_agents_manager_data filter
84        // never fired. Priority 250 runs after both jetpack-mu-wpcom and the
85        // Agents Manager package enqueue (priority 101).
86        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'maybe_patch_jetpack_ai_sidebar_preview_data' ), 250 );
87
88        // Let editor JS know when the Jetpack AI Sidebar toolbar button replaces the legacy AI toolbar.
89        add_action( 'jetpack_register_gutenberg_extensions', array( __CLASS__, 'register_toolbar_button_extension' ), 99 );
90    }
91
92    // ──────────────────────────────────────────────────
93    // Jetpack AI provider bundle
94    // ──────────────────────────────────────────────────
95
96    /**
97     * Enqueue the IIFE bundle that registers Jetpack AI abilities.
98     *
99     * This runs independently of AM/provider registration so preview abilities
100     * are available even when Big Sky standalone is the active UI.
101     *
102     * @return void
103     */
104    public static function maybe_enqueue_abilities_script(): void {
105        if ( ! self::should_expose_provider() ) {
106            return;
107        }
108
109        // CIAB (next-admin) has its own AM setup — don't enqueue alongside it.
110        if ( did_action( 'next_admin_init' ) ) {
111            return;
112        }
113
114        if ( self::is_agents_manager_disconnected() ) {
115            return;
116        }
117
118        // Guard against double-enqueue (e.g. hooked multiple times).
119        if ( wp_script_is( 'jetpack-ai-provider' ) ) {
120            return;
121        }
122
123        $asset_data = self::get_ai_sidebar_asset_data();
124        if ( ! $asset_data ) {
125            return;
126        }
127
128        $version      = $asset_data['version'] ?? false;
129        $dependencies = $asset_data['dependencies'] ?? array();
130
131        wp_enqueue_script(
132            'jetpack-ai-provider',
133            AI_SIDEBAR_JS_URL,
134            $dependencies,
135            $version,
136            true
137        );
138
139        wp_enqueue_style(
140            'jetpack-ai-provider',
141            is_rtl() ? AI_SIDEBAR_RTL_CSS_URL : AI_SIDEBAR_CSS_URL,
142            array(),
143            $version
144        );
145    }
146
147    // ──────────────────────────────────────────────────
148    // Asset manifest (Image Studio pattern)
149    // ──────────────────────────────────────────────────
150
151    /**
152     * Try to read the asset manifest from the local filesystem.
153     *
154     * On WordPress.com, widgets.wp.com assets are available at ABSPATH.
155     *
156     * @param string $relative_path The relative path to the JSON file.
157     * @return array|false The decoded asset data, or false if not available locally.
158     */
159    private static function get_asset_data_from_file( string $relative_path ) {
160        $local_path = ABSPATH . $relative_path;
161        if ( ! file_exists( $local_path ) ) {
162            return false;
163        }
164
165        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Reading a local file, not a remote URL.
166        $contents = file_get_contents( $local_path );
167        if ( false === $contents ) {
168            return false;
169        }
170
171        $data = json_decode( $contents, true );
172        if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $data ) ) {
173            return false;
174        }
175
176        return $data;
177    }
178
179    /**
180     * Fetch the asset manifest via HTTP.
181     *
182     * @param string $url The URL to fetch.
183     * @return array|false The decoded asset data, or false on failure.
184     */
185    private static function get_asset_data_from_remote( string $url ) {
186        $response = wp_safe_remote_get( $url );
187        if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
188            return false;
189        }
190
191        $content_type = wp_remote_retrieve_header( $response, 'content-type' );
192        if ( is_string( $content_type ) && false === stripos( $content_type, 'json' ) ) {
193            return false;
194        }
195
196        $body = wp_remote_retrieve_body( $response );
197        $data = json_decode( $body, true );
198        if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $data ) ) {
199            return false;
200        }
201
202        return $data;
203    }
204
205    // ──────────────────────────────────────────────────
206    // Provider registration
207    // ──────────────────────────────────────────────────
208
209    /**
210     * Register Jetpack AI as an Agents Manager provider.
211     *
212     * Appends the CDN-hosted ESM wrapper URL to the providers list so AM
213     * can dynamically import it. Asset enqueueing is handled separately by
214     * maybe_enqueue_abilities_script.
215     *
216     * @param array $providers Existing provider URLs.
217     * @return array Updated providers.
218     */
219    public static function register_provider( array $providers ): array {
220        // CIAB (next-admin) has AM natively — skip to avoid duplicate agents.
221        if ( did_action( 'next_admin_init' ) ) {
222            return $providers;
223        }
224
225        // The provider IIFE is enqueued on the same surfaces where the ESM
226        // wrapper is registered. Avoid registering the wrapper when AM may
227        // import it before window.__JetpackAIProvider exists.
228        if ( ! self::should_expose_provider() ) {
229            return $providers;
230        }
231
232        // The providers filter still runs for disconnected variants.
233        if ( self::is_agents_manager_disconnected() ) {
234            return $providers;
235        }
236
237        // Don't register if the IIFE bundle cannot be loaded. The ESM wrapper
238        // re-exports from window.__JetpackAIProvider at import time; if the
239        // IIFE never ran, toolProvider is still a truthy Proxy and AM would
240        // call getAbilities() on it and get undefined, breaking the merge.
241        if ( ! self::get_ai_sidebar_asset_data() ) {
242            return $providers;
243        }
244
245        // Register as AM provider via CDN-hosted ESM wrapper.
246        // AM dynamically imports this module to merge tools, suggestions, and components.
247        // No ?ver= needed — the wrapper re-exports from window.__JetpackAIProvider
248        // at import time, so its behavior always matches the loaded IIFE bundle.
249        $providers[] = AI_SIDEBAR_PROVIDER_URL;
250
251        return $providers;
252    }
253
254    /**
255     * Fetch and cache the CDN asset manifest for the AI sidebar bundle.
256     *
257     * @return array|false The decoded asset data, or false on failure.
258     */
259    private static function get_ai_sidebar_asset_data() {
260        $skip_cache = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG;
261
262        if ( ! $skip_cache ) {
263            $cached = get_transient( AI_SIDEBAR_ASSET_TRANSIENT );
264            if ( false !== $cached ) {
265                return $cached;
266            }
267        }
268
269        $json_path = AM_ASSET_BASE_PATH . 'jetpack-ai-sidebar.asset.json';
270
271        // Try local file first (available on WordPress.com).
272        $data = self::get_asset_data_from_file( $json_path );
273
274        // Fallback to remote fetch.
275        if ( false === $data ) {
276            $data = self::get_asset_data_from_remote( 'https://' . $json_path );
277        }
278
279        if ( false === $data ) {
280            // The manifest is unavailable from both the local file and the CDN
281            // — for example when the server cannot reach widgets.wp.com. Skip
282            // rather than enqueue a provider whose bundle the browser may also
283            // be unable to load, which would break the Agents Manager merge.
284            return false;
285        }
286
287        if ( ! $skip_cache ) {
288            set_transient( AI_SIDEBAR_ASSET_TRANSIENT, $data, HOUR_IN_SECONDS );
289        }
290
291        return $data;
292    }
293
294    // ──────────────────────────────────────────────────
295    // Helper methods
296    // ──────────────────────────────────────────────────
297
298    /**
299     * UI feature flag for the SEO suggestions (SEO title and meta description).
300     *
301     * Two halves: the site can offer AI SEO at all — the package's shared gate,
302     * the same one the AI settings row uses, so the control and the surface it
303     * governs cannot drift — and the feature's own toggle is on. Kept independent
304     * of the Optimize Title suggestion: SEO suggestions target the SEO meta
305     * fields, not the visible post title.
306     *
307     * The SEO *feature* option is consulted, not the automatic-generation one:
308     * a switched-off feature must not offer suggestions, even user-initiated
309     * ones, while automatic generation governs only automatic runs.
310     *
311     * Guarded with class_exists: the autoloader can pick an older jetpack-seo
312     * copy from another plugin, predating the shared gate. Suggestions stay off
313     * without it.
314     *
315     * @return bool
316     */
317    private static function is_seo_suggestions_enabled(): bool {
318        return class_exists( Ai_Seo::class )
319            && Current_Plan::supports( 'ai-seo-enhancer' )
320            && Ai_Seo::is_available()
321            && \Jetpack_AI_Settings::is_ai_seo_enabled();
322    }
323
324    /**
325     * UI feature flag for the public Jetpack AI Sidebar Preview surface: this
326     * host loads the sidebar, and at least one feature it surfaces is on.
327     *
328     * @return bool
329     */
330    private static function is_jetpack_ai_sidebar_preview_enabled(): bool {
331        return self::is_host_enabled() && self::has_enabled_sidebar_features();
332    }
333
334    /**
335     * Whether this host enables the sidebar, before checking individual features.
336     *
337     * @since 16.2
338     *
339     * @return bool
340     */
341    public static function is_host_enabled(): bool {
342        $host = new Host();
343
344        $enabled = false;
345        if ( $host->is_wpcom_platform() && class_exists( 'Big_Sky' ) ) {
346            $default = $host->is_wpcom_simple() ? '1' : '0';
347            // The plan check is the costly one, so it goes after the option.
348            $enabled = (bool) get_option( 'big_sky_enable', $default ) && self::has_wordpress_agent_plan();
349        }
350
351        /**
352         * Filter to enable or disable the Jetpack AI sidebar feature.
353         *
354         * Defaults to true only on WordPress.com platform sites with Big Sky
355         * present and enabled. Acts as a host-level override that can force the
356         * sidebar on (e.g. for local development) or off, and is respected by
357         * init() and every sidebar surface. The override cannot force the
358         * sidebar on while the writing-assistant and SEO enhancer features are
359         * both off — a featureless sidebar never loads.
360         *
361         * @param bool $enabled Whether the Jetpack AI sidebar is enabled.
362         */
363        $enabled = (bool) apply_filters( 'jetpack_ai_sidebar_enabled', $enabled );
364
365        // Re-asserted after the filter so a later filter cannot surface a sidebar
366        // blocked by the host or master gates — the gates are final, as with
367        // is_ai_enabled().
368        return $enabled && \Jetpack_AI_Settings::apply_master_gates( true );
369    }
370
371    /**
372     * Whether any feature the sidebar surfaces is effectively enabled; with
373     * nothing to offer it must not load. Caveat: init() runs before seo-tools
374     * registers jetpack_disable_seo_tools, so that term reads its default here.
375     *
376     * @return bool
377     */
378    private static function has_enabled_sidebar_features(): bool {
379        return \Jetpack_AI_Settings::is_feature_enabled( 'writing_assistant' )
380            || self::is_seo_suggestions_enabled();
381    }
382
383    /**
384     * Whether the Jetpack AI provider bundle should be exposed for this request.
385     *
386     * This is scoped to the supported editor surfaces: post editor, page editor,
387     * and site editor. Each surface remains subject to the preview and AI feature
388     * gates.
389     *
390     * @return bool
391     */
392    private static function should_expose_provider(): bool {
393        return self::is_jetpack_ai_sidebar_preview_enabled()
394            && self::is_supported_provider_surface()
395            && self::has_ai_features();
396    }
397
398    /**
399     * Whether the Agents Manager is loading a disconnected build, which it does
400     * when the current user has no linked WordPress.com account.
401     *
402     * @return bool
403     */
404    private static function is_agents_manager_disconnected(): bool {
405        $variant = Agents_Manager::get_active_variant();
406
407        // Null means the Agents Manager is not loading at all, which is not a disconnection.
408        return is_string( $variant ) && str_contains( $variant, 'disconnected' );
409    }
410
411    /**
412     * Preview configuration consumed by the Agents Manager and Jetpack AI provider bundles.
413     *
414     * @return array Preview mode and feature availability.
415     */
416    private static function get_jetpack_ai_sidebar_preview_config(): array {
417        // Ability permission callbacks enforce server-side access for these
418        // features. The writing suggestions additionally follow the writing
419        // assistant toggle on the AI settings page — a switched-off feature
420        // must not surface suggestions even when an external host (Big Sky,
421        // Woo) draws the sidebar — and SEO requires the site-side gates below.
422        $writing_on = \Jetpack_AI_Settings::is_feature_enabled( 'writing_assistant' );
423
424        $features = array(
425            'aiEditorialReview'       => (bool) apply_filters( 'jetpack_ai_editorial_review_enabled', true ) && $writing_on,
426            'generateFeedback'        => $writing_on,
427            'proofreadContent'        => $writing_on,
428            'blockTransformations'    => $writing_on,
429            'blockToolbarButton'      => $writing_on,
430            'optimizeTitleSuggestion' => $writing_on,
431            'seoSuggestions'          => self::is_seo_suggestions_enabled(),
432            'excerptSuggestion'       => $writing_on,
433            'chatHistory'             => false,
434            'supportGuides'           => false,
435        );
436
437        /**
438         * Filter the feature set exposed in Jetpack AI Sidebar Preview.
439         *
440         * @param array $features Associative array of preview feature flags.
441         */
442        $filtered_features = apply_filters( 'jetpack_ai_sidebar_preview_features', $features );
443        $features          = is_array( $filtered_features ) ? array_merge( $features, $filtered_features ) : $features;
444
445        // Normalize the flags released here while leaving host-added values
446        // untouched. Keep the AI settings page toggles and SEO's site-side
447        // requirements final.
448        $features['aiEditorialReview']       = (bool) $features['aiEditorialReview'] && $writing_on;
449        $features['generateFeedback']        = (bool) $features['generateFeedback'] && $writing_on;
450        $features['proofreadContent']        = (bool) $features['proofreadContent'] && $writing_on;
451        $features['blockToolbarButton']      = (bool) $features['blockToolbarButton'] && $writing_on;
452        $features['optimizeTitleSuggestion'] = (bool) $features['optimizeTitleSuggestion'] && $writing_on;
453        $features['seoSuggestions']          = (bool) $features['seoSuggestions'] && self::is_seo_suggestions_enabled();
454        $features['excerptSuggestion']       = (bool) $features['excerptSuggestion'] && $writing_on;
455        // Block transformations (Translate, Change Tone, etc.) are writing features
456        // and follow the writing assistant toggle.
457        $features['blockTransformations'] = (bool) $features['blockTransformations'] && $writing_on;
458
459        return array(
460            'enabled'                    => self::is_jetpack_ai_sidebar_preview_enabled(),
461            'features'                   => $features,
462            // Not in $features, which is public and host-filterable.
463            'agentNoticeActionAvailable' => self::is_agent_action_available(),
464        );
465    }
466
467    /**
468     * Whether the Jetpack AI Sidebar toolbar button replaces the legacy AI toolbar.
469     *
470     * The button is a writing entry point, so it follows the writing assistant
471     * toggle. Switching it off cannot bring the legacy toolbar back in its place:
472     * the editor renders that toolbar only while this feature is unavailable AND
473     * the AI Assistant block and its ai-assistant-support extension are
474     * registered, and both of those are themselves gated on the writing assistant.
475     *
476     * @return bool
477     */
478    public static function is_toolbar_button_enabled(): bool {
479        $preview_config = self::get_jetpack_ai_sidebar_preview_config();
480
481        return self::should_expose_provider()
482            && ! self::is_agents_manager_disconnected()
483            && true === ( $preview_config['features']['blockToolbarButton'] ?? false );
484    }
485
486    /**
487     * Register the Jetpack AI Sidebar toolbar button feature.
488     *
489     * @return void
490     */
491    public static function register_toolbar_button_extension(): void {
492        if ( ! self::is_toolbar_button_enabled() ) {
493            \Jetpack_Gutenberg::set_extension_unavailable(
494                AI_SIDEBAR_TOOLBAR_BUTTON_EXTENSION,
495                'jetpack_ai_sidebar_feature_disabled'
496            );
497            return;
498        }
499
500        \Jetpack_Gutenberg::set_extension_available( AI_SIDEBAR_TOOLBAR_BUTTON_EXTENSION );
501    }
502
503    /**
504     * Whether the legacy AI panel should point people at the WordPress Agent.
505     *
506     * True once there is a working agent to open, or earlier, once the site is
507     * eligible to turn one on.
508     *
509     * @return bool
510     */
511    public static function is_agent_notice_enabled(): bool {
512        if ( self::is_agent_action_available() ) {
513            return true;
514        }
515
516        return self::is_wordpress_agent_eligible()
517            && self::is_supported_provider_surface()
518            && self::has_ai_features()
519            && ! self::is_agents_manager_disconnected();
520    }
521
522    /**
523     * Whether the site has turned the WordPress Agent on, whatever Jetpack's own
524     * sidebar gate says.
525     *
526     * The Big Sky plugin's own Settings > Writing checkbox can turn it off while
527     * the plugin stays active, so the option counts as well as the class.
528     *
529     * @return bool
530     */
531    private static function is_wordpress_agent_enabled(): bool {
532        $host = new Host();
533
534        if ( ! $host->is_wpcom_platform() || ! class_exists( 'Big_Sky' ) ) {
535            return false;
536        }
537
538        $default = $host->is_wpcom_simple() ? '1' : '0';
539
540        return (bool) get_option( 'big_sky_enable', $default );
541    }
542
543    /**
544     * Whether the site is eligible to turn the WordPress Agent on, whether or not
545     * it has done so yet.
546     *
547     * Eligibility follows the plan, not the Big Sky sticker: a site downgraded to
548     * Free keeps the sticker but is no longer offered the Agent. Not gated on the
549     * Big_Sky class, which on Simple only loads once the Agent is on.
550     *
551     * @return bool
552     */
553    private static function is_wordpress_agent_eligible(): bool {
554        $host = new Host();
555
556        return $host->is_wpcom_platform() && self::has_wordpress_agent_plan();
557    }
558
559    /**
560     * Whether the site has a plan that grants the Big Sky feature.
561     *
562     * Prefers the mu-wpcom check, which also counts the Big Sky free trial that the
563     * plan check cannot see. Atomic can run an older mu-wpcom without it, so fall
564     * back to Current_Plan, which resolves through the platform plan features.
565     *
566     * @return bool
567     */
568    private static function has_wordpress_agent_plan(): bool {
569        if ( function_exists( 'wpcom_site_has_wordpress_agent_plan' ) ) {
570            // @phan-suppress-next-line PhanUndeclaredFunction -- Provided by jetpack-mu-wpcom on WordPress.com; guarded above.
571            return wpcom_site_has_wordpress_agent_plan();
572        }
573
574        return Current_Plan::supports( 'big-sky' );
575    }
576
577    /**
578     * Register the WordPress Agent notice feature.
579     *
580     * @return void
581     */
582    public static function register_agent_notice_extension(): void {
583        if ( ! self::is_agent_notice_enabled() ) {
584            // Its own reason, so the payload tells this apart from the toolbar button.
585            \Jetpack_Gutenberg::set_extension_unavailable(
586                AI_SIDEBAR_AGENT_NOTICE_EXTENSION,
587                'jetpack_ai_sidebar_agent_notice_disabled'
588            );
589            return;
590        }
591
592        \Jetpack_Gutenberg::set_extension_available( AI_SIDEBAR_AGENT_NOTICE_EXTENSION );
593
594        if ( self::can_current_user_enable_agent() ) {
595            \Jetpack_Gutenberg::set_extension_available( AI_SIDEBAR_AGENT_ENABLE_EXTENSION );
596        } else {
597            \Jetpack_Gutenberg::set_extension_unavailable(
598                AI_SIDEBAR_AGENT_ENABLE_EXTENSION,
599                'jetpack_ai_sidebar_agent_enable_not_allowed'
600            );
601        }
602
603        // Tells the notice whether to offer to enable the Agent or to open it.
604        if ( self::is_wordpress_agent_enabled() ) {
605            \Jetpack_Gutenberg::set_extension_available( AI_SIDEBAR_AGENT_SUPPORT_EXTENSION );
606            return;
607        }
608
609        \Jetpack_Gutenberg::set_extension_unavailable(
610            AI_SIDEBAR_AGENT_SUPPORT_EXTENSION,
611            'jetpack_ai_sidebar_agent_disabled'
612        );
613    }
614
615    /**
616     * Whether the current user can reach the WordPress.com page that turns the Agent on.
617     *
618     * Mirrors the dashboard's canManageSite(), which answers anything else with a 404.
619     * Membership matters because super admins pass manage_options on sites they do not belong to.
620     *
621     * @return bool
622     */
623    public static function can_current_user_enable_agent(): bool {
624        $host = new Host();
625
626        return is_user_member_of_blog()
627            && current_user_can( 'manage_options' )
628            && ! $host->is_p2_site()
629            && ! $host->is_vip_site();
630    }
631
632    /**
633     * Whether the notice's action button has a working agent to send people to.
634     *
635     * Narrower than is_agent_notice_enabled(): an eligible site shows the notice,
636     * but only an enabled one has a chat to open.
637     *
638     * @return bool
639     */
640    public static function is_agent_action_available(): bool {
641        return self::should_expose_provider() && ! self::is_agents_manager_disconnected();
642    }
643
644    /**
645     * Add Jetpack AI Sidebar-specific data to externally emitted Agents Manager payloads.
646     *
647     * @param mixed $data Data encoded into `agentsManagerData`.
648     * @return mixed Filtered data.
649     */
650    public static function add_agents_manager_data( $data ) {
651        if ( ! is_array( $data ) ) {
652            return $data;
653        }
654
655        $fields = self::get_agents_manager_data_fields( $data );
656        if ( ! $fields ) {
657            return $data;
658        }
659
660        // Set our fields in place, leaving the rest of $data (including agentProviders)
661        // untouched so the client-side gate can drop Jetpack AI Sidebar while keeping
662        // fallbacks such as the Big Sky provider. Hosts that need intentional overrides
663        // should use the sidebar and preview feature filters.
664        foreach ( $fields as $key => $value ) {
665            $data[ $key ] = $value;
666        }
667        return $data;
668    }
669
670    /**
671     * Fields Jetpack should add to `agentsManagerData` for the current screen.
672     *
673     * @param array $data Existing Agents Manager data.
674     * @return array
675     */
676    private static function get_agents_manager_data_fields( array $data = array() ): array {
677        if ( ! self::should_expose_provider() ) {
678            return array();
679        }
680
681        $fields = array();
682        if ( empty( $data['agentId'] ) ) {
683            $fields['agentId'] = AI_SIDEBAR_AGENT_ID;
684        }
685        $fields['jetpackAiSidebar'] = self::get_jetpack_ai_sidebar_preview_config();
686
687        return $fields;
688    }
689
690    /**
691     * Enable Agents Manager when the Jetpack AI provider can be exposed.
692     *
693     * @param mixed $enabled Existing Agents Manager block-editor gate value.
694     * @return bool
695     */
696    public static function enable_agents_manager_on_provider_surfaces( $enabled ): bool {
697        if ( $enabled ) {
698            return true;
699        }
700
701        return self::should_expose_provider();
702    }
703
704    /**
705     * Inject Jetpack AI Sidebar Preview data into an externally enqueued AM bundle.
706     *
707     * The design-intended hook is jetpack_ai_sidebar_agents_manager_data, applied
708     * by jetpack-agents-manager Agents_Manager::enqueue_scripts(). On Atomic the bundled
709     * mu-wpcom (via wpcomsh) lags this PR, so the filter never fires and the
710     * client gets agentsManagerData without our fields. This `before` script runs
711     * after the upstream `before` that declares the const (added earlier) but
712     * before the AM bundle reads it, so the field is set when AM initialises.
713     * Gives Atomic parity with Jurassic Ninja without depending on a wpcomsh
714     * redeploy.
715     *
716     * Skipped on WordPress.com Simple — wpcom's data extension owns the predicate
717     * there, including any WordPress.com-specific kill-switch override.
718     *
719     * @return void
720     */
721    public static function maybe_patch_jetpack_ai_sidebar_preview_data(): void {
722        if ( ( new Host() )->is_wpcom_simple() ) {
723            return;
724        }
725
726        // 'registered' rather than 'enqueued': wp_add_inline_script attaches to any
727        // registered handle and serializes correctly regardless of when the
728        // enqueue lands in the dependency graph.
729        if ( ! wp_script_is( 'agents-manager', 'registered' ) ) {
730            return;
731        }
732
733        // The fields getter carries the provider exposure gate.
734        $fields = self::get_agents_manager_data_fields();
735        if ( ! $fields ) {
736            return;
737        }
738
739        // The second path the provider URL can reach agentsManagerData by.
740        if ( self::is_agents_manager_disconnected() ) {
741            return;
742        }
743
744        // Build the assignments from the same field source as the data filter so the
745        // two emit paths cannot drift. agentId is guarded client-side because the
746        // externally emitted payload may already define the active agent.
747        $assignments = '';
748        foreach ( $fields as $key => $value ) {
749            $assignment_value = wp_json_encode( $value, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP );
750
751            if ( 'agentId' === $key ) {
752                $assignments .= ' if ( ! agentsManagerData.agentId ) { agentsManagerData.agentId = ' . $assignment_value . '; }';
753                continue;
754            }
755
756            $assignments .= ' agentsManagerData.' . $key . ' = ' . $assignment_value . ';';
757        }
758
759        if ( self::get_ai_sidebar_asset_data() ) {
760            $assignments .= self::get_agent_provider_upsert_script();
761        }
762
763        wp_add_inline_script(
764            'agents-manager',
765            'if ( typeof agentsManagerData === "object" && agentsManagerData !== null ) {' . $assignments . ' }',
766            'before'
767        );
768    }
769
770    /**
771     * Build the inline script that upserts Jetpack AI Sidebar into agentProviders.
772     *
773     * @return string Inline JavaScript.
774     */
775    private static function get_agent_provider_upsert_script(): string {
776        $provider_url = wp_json_encode( AI_SIDEBAR_PROVIDER_URL, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP );
777
778        return ' agentsManagerData.agentProviders = Array.isArray( agentsManagerData.agentProviders ) ? agentsManagerData.agentProviders : [];'
779            . ' if ( agentsManagerData.agentProviders.indexOf( ' . $provider_url . ' ) === -1 ) { agentsManagerData.agentProviders.push( ' . $provider_url . ' ); }';
780    }
781
782    /**
783     * Check if the current screen is a block editor.
784     *
785     * @return bool
786     */
787    private static function is_block_editor(): bool {
788        if ( ! function_exists( 'get_current_screen' ) ) {
789            return false;
790        }
791
792        $screen = get_current_screen();
793        return $screen && $screen->is_block_editor();
794    }
795
796    /**
797     * Check if the current screen can consume the Jetpack AI provider bundle.
798     *
799     * @return bool
800     */
801    private static function is_supported_provider_surface(): bool {
802        $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
803        if ( ! $screen instanceof \WP_Screen ) {
804            return false;
805        }
806
807        if ( 'site-editor' === $screen->base ) {
808            return true;
809        }
810
811        return self::is_block_editor()
812            && 'post' === $screen->base
813            && in_array( $screen->post_type, array( 'post', 'page' ), true );
814    }
815
816    /**
817     * Check whether AI features are available.
818     *
819     * - wpcom simple: available when Jetpack AI is enabled.
820     * - Atomic/self-hosted: requires Jetpack AI enabled, a connected owner, and non-offline mode.
821     *
822     * @return bool
823     */
824    private static function has_ai_features(): bool {
825        if ( ! \Jetpack_AI_Settings::is_ai_enabled() ) {
826            return false;
827        }
828
829        $host = new Host();
830
831        if ( $host->is_wpcom_simple() ) {
832            return true;
833        }
834
835        return ( new Connection_Manager( 'jetpack' ) )->has_connected_owner()
836            && ! ( new Status() )->is_offline_mode();
837    }
838}