Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.44% covered (success)
90.44%
265 / 293
65.38% covered (warning)
65.38%
17 / 26
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_AI_Page
90.59% covered (success)
90.59%
260 / 287
65.38% covered (warning)
65.38%
17 / 26
107.16
0.00% covered (danger)
0.00%
0 / 1
 should_render_wp_build
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_ai_admin_request
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 maybe_load_wp_build
50.00% covered (danger)
50.00%
1 / 2
0.00% covered (danger)
0.00%
0 / 1
2.50
 add_admin_shell_member
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
12
 load_as_admin_shell_guest
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 should_add_menu
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
5
 add_actions
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
4
 get_page_hook
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
 add_page_actions
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 admin_styles
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 load_agents_manager
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 get_agents_manager_agent_id
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 add_scheduled_tasks_provider
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 add_scheduled_tasks_data
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
1
 is_scheduled_tasks_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 page_admin_scripts
100.00% covered (success)
100.00%
122 / 122
100.00% covered (success)
100.00%
1 / 1
21
 get_tracks_user_data
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 is_current_user_automattician
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
5.07
 get_search_settings_url
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
7
 search_page_will_register
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
9.00
 has_my_jetpack
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 get_ai_plan_info
93.75% covered (success)
93.75%
15 / 16
0.00% covered (danger)
0.00%
0 / 1
9.02
 is_jetpack_purchase
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 get_wpcom_plan_purchase
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
5.05
 render
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 page_render
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
2.06
1<?php
2/**
3 * Jetpack AI admin page.
4 *
5 * Registers the "AI" submenu item under Jetpack and mounts the React-based
6 * MCP settings interface.
7 *
8 * @package automattic/jetpack
9 */
10
11use Automattic\Jetpack\Activity_Log\Jetpack_Activity_Log;
12use Automattic\Jetpack\Activity_Log\REST_Controller as Activity_Log_REST_Controller;
13use Automattic\Jetpack\Admin_UI\Admin_Menu;
14use Automattic\Jetpack\Agents_Manager\Agents_Manager;
15use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
16use Automattic\Jetpack\Connection\Manager as Connection_Manager;
17use Automattic\Jetpack\Current_Plan;
18use Automattic\Jetpack\Feature_Flags\Feature_Flags;
19use Automattic\Jetpack\Modules;
20use Automattic\Jetpack\Redirect;
21use Automattic\Jetpack\Status;
22use Automattic\Jetpack\Status\Host;
23use Automattic\Jetpack\Terms_Of_Service;
24use Automattic\Jetpack\Tracking;
25
26if ( ! defined( 'ABSPATH' ) ) {
27    exit( 0 );
28}
29
30require_once dirname( __DIR__ ) . '/class-jetpack-ai-feature-flags.php';
31require_once dirname( __DIR__ ) . '/class-jetpack-ai-settings.php';
32require_once __DIR__ . '/class-jetpack-wp-build-page.php';
33
34/**
35 * Builds the Jetpack AI admin page and its sidebar menu entry.
36 */
37class Jetpack_AI_Page {
38
39    /**
40     * The wp-build route's page id, which must not be the `jetpack-ai` menu slug.
41     *
42     * @var string
43     */
44    const WP_BUILD_PAGE_ID = 'jetpack-ai-hub';
45
46    /**
47     * Activity Log actor ID that WordPress.com matches against every MCP agent event.
48     *
49     * @var string
50     */
51    const ALL_AI_AGENTS_ACTOR_ID = 'mcp:*';
52
53    /**
54     * Whether this request renders through wp-build.
55     *
56     * Checks the render function too: if the build output is missing, the request would
57     * otherwise get no bundle at all now that the legacy entry is gone.
58     *
59     * @since 16.3
60     *
61     * @return bool
62     */
63    public static function should_render_wp_build() {
64        return function_exists( 'jetpack_plugin_jetpack_ai_hub_wp_admin_render_page' );
65    }
66
67    /**
68     * Whether the current request targets the AI Hub admin page.
69     *
70     * @since 16.3
71     *
72     * @return bool
73     */
74    private static function is_ai_admin_request() {
75        if ( ! is_admin() ) {
76            return false;
77        }
78
79        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading the page slug only.
80        return isset( $_GET['page'] ) && 'jetpack-ai' === sanitize_text_field( wp_unslash( $_GET['page'] ) );
81    }
82
83    /**
84     * Load wp-build for the AI Hub page.
85     *
86     * @since 16.3
87     *
88     * @return void
89     */
90    public static function maybe_load_wp_build() {
91        if ( self::is_ai_admin_request() ) {
92            Jetpack_WP_Build_Page::load( self::WP_BUILD_PAGE_ID );
93        }
94    }
95
96    /**
97     * Register Jetpack AI with the admin shell, which switches between Jetpack dashboards without a page load.
98     *
99     * @since 16.5
100     *
101     * @param array $members Shell members keyed by admin page slug.
102     * @return array
103     */
104    public function add_admin_shell_member( $members ) {
105        // On Simple, mu-wpcom registers the page and hooks this, as Jetpack_Admin never runs there.
106        if ( ! file_exists( JETPACK__PLUGIN_DIR . 'build/build.php' ) || ! $this->should_add_menu() ) {
107            return $members;
108        }
109
110        $members['jetpack-ai'] = array(
111            'build_prefix' => 'jetpack_plugin',
112            'build_page'   => self::WP_BUILD_PAGE_ID,
113            'init_modules' => array( '@jetpack-plugin/init' ),
114            // "Jetpack AI" is a product name and should not be translated.
115            'title'        => 'Jetpack AI',
116            'header'       => array(
117                'title'    => 'Jetpack AI',
118                'subtitle' => __( 'Create, connect, and automate with Jetpack AI.', 'jetpack' ),
119            ),
120            'capability'   => 'manage_options',
121            'handles'      => array( 'jetpack-ai-admin', 'jetpack-script-data', 'jp-tracks-functions', 'wp-jp-i18n-loader' ),
122            'load'         => array( $this, 'load_as_admin_shell_guest' ),
123        );
124        return $members;
125    }
126
127    /**
128     * Ready the AI Hub routes and page data while another dashboard's page is open, without the screen ID alias.
129     *
130     * @since 16.5
131     *
132     * @return void
133     */
134    public function load_as_admin_shell_guest() {
135        if ( Jetpack_WP_Build_Page::load( self::WP_BUILD_PAGE_ID, false ) ) {
136            add_action( 'admin_enqueue_scripts', array( $this, 'page_admin_scripts' ) );
137        }
138    }
139
140    /**
141     * Whether add_actions() registers the page, and so whether the admin shell may serve it.
142     *
143     * @return bool
144     */
145    private function should_add_menu() {
146        $is_offline_mode = ( new Status() )->is_offline_mode();
147
148        if ( ! current_user_can( 'manage_options' ) && ( $is_offline_mode || ! Jetpack::is_connection_ready() ) ) {
149            return false;
150        }
151
152        return Jetpack::is_connection_ready() || $is_offline_mode;
153    }
154
155    /**
156     * Register the page and its page-specific hooks.
157     *
158     * The AI Hub owns its full React layout, so it does not need the legacy
159     * Jetpack_Admin_Page lifecycle. Keeping this controller independent also
160     * lets WordPress.com Simple load the same page without replacing its
161     * request-wide Jetpack_Admin_Page compatibility stub.
162     */
163    public function add_actions() {
164        if ( ! $this->should_add_menu() ) {
165            return;
166        }
167
168        $hook = $this->get_page_hook();
169        if ( ! $hook ) {
170            return;
171        }
172
173        add_action( 'admin_print_scripts-' . $hook, array( $this, 'page_admin_scripts' ) );
174
175        // Preserve the standalone Jetpack page's existing base stylesheet. Simple
176        // never loaded it for the Hub because it conflicts with wpcom admin pages.
177        if ( ! ( new Host() )->is_wpcom_simple() ) {
178            add_action( 'admin_print_styles-' . $hook, array( $this, 'admin_styles' ) );
179        }
180
181        $this->add_page_actions( $hook );
182    }
183
184    /**
185     * Register the "AI" submenu under the Jetpack top-level menu.
186     *
187     * @return string|false Hook returned by Admin_Menu::add_menu().
188     */
189    public function get_page_hook() {
190        return Admin_Menu::add_menu(
191            // "Jetpack AI" is a product name and should not be translated.
192            'Jetpack AI',
193            'Jetpack AI',
194            'manage_options',
195            'jetpack-ai',
196            array( $this, 'render' ),
197            null,
198            array(
199                'product' => 'jetpack-ai',
200                'key'     => 'jetpack-ai',
201            )
202        );
203    }
204
205    /**
206     * Attach page-specific actions.
207     *
208     * @param string $hook The page hook returned by get_page_hook().
209     */
210    public function add_page_actions( $hook ) {
211        add_action( 'load-' . $hook, array( $this, 'load_agents_manager' ) );
212    }
213
214    /**
215     * Enqueue the stylesheet historically supplied by Jetpack_Admin_Page.
216     */
217    public function admin_styles() {
218        $min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
219
220        wp_enqueue_style( 'jetpack-admin', plugins_url( "css/jetpack-admin{$min}.css", JETPACK__PLUGIN_FILE ), array( 'genericons', 'jetpack-connection' ), JETPACK__VERSION . '-20121016' );
221        wp_style_add_data( 'jetpack-admin', 'rtl', 'replace' );
222        wp_style_add_data( 'jetpack-admin', 'suffix', $min );
223    }
224
225    /**
226     * Request the existing Agents Manager shell for this page.
227     */
228    public function load_agents_manager() {
229        if ( ! self::is_scheduled_tasks_enabled() ) {
230            return;
231        }
232
233        Agents_Manager::init();
234
235        add_filter( 'agents_manager_should_load', '__return_true' );
236        add_filter( 'agents_manager_agent_id', array( $this, 'get_agents_manager_agent_id' ) );
237        add_filter( 'agents_manager_agent_providers', array( $this, 'add_scheduled_tasks_provider' ) );
238        add_filter( 'jetpack_ai_sidebar_agents_manager_data', array( $this, 'add_scheduled_tasks_data' ) );
239    }
240
241    /**
242     * Use the generic WP Orchestrator agent in AI Hub.
243     *
244     * @return string Agent ID.
245     */
246    public function get_agents_manager_agent_id() {
247        return 'wp-orchestrator';
248    }
249
250    /**
251     * Add the AI Hub provider that supplies scheduled task starter prompts.
252     *
253     * @param array $providers Existing provider module URLs.
254     * @return array Updated provider module URLs.
255     */
256    public function add_scheduled_tasks_provider( $providers ) {
257        $providers[] = add_query_arg(
258            'ver',
259            JETPACK__VERSION,
260            plugins_url( '_inc/jetpack-ai-scheduled-tasks-provider.js', JETPACK__PLUGIN_FILE )
261        );
262
263        return $providers;
264    }
265
266    /**
267     * Customize Agents Manager's empty view for the Scheduled tasks page.
268     *
269     * @param array $data Existing Agents Manager data.
270     * @return array Updated Agents Manager data.
271     */
272    public function add_scheduled_tasks_data( $data ) {
273        $current_user = wp_get_current_user();
274
275        $data['emptyViewHeading'] = sprintf(
276            /* translators: %s: Current user's display name. */
277            __( 'Howdy %s! Let’s schedule a task.', 'jetpack' ),
278            $current_user->display_name
279        );
280        $data['emptyViewHelp']                     = __( 'Got a different request? Ask away.', 'jetpack' );
281        $data['scheduledTaskEmptyViewSuggestions'] = array(
282            array(
283                'id'         => 'create-daily-reminder',
284                'label'      => __( 'Create a daily reminder', 'jetpack' ),
285                'prompt'     => __( 'Create a daily reminder', 'jetpack' ),
286                'autoSubmit' => true,
287            ),
288            array(
289                'id'         => 'draft-weekly-post',
290                'label'      => __( 'Draft a weekly post', 'jetpack' ),
291                'prompt'     => __( 'Draft a weekly post', 'jetpack' ),
292                'autoSubmit' => true,
293            ),
294            array(
295                'id'         => 'schedule-monthly-report',
296                'label'      => __( 'Schedule a monthly report', 'jetpack' ),
297                'prompt'     => __( 'Schedule a monthly report', 'jetpack' ),
298                'autoSubmit' => true,
299            ),
300        );
301
302        return $data;
303    }
304
305    /**
306     * Whether the Scheduled tasks tab and its Agents Manager sidebar are enabled.
307     *
308     * @since 16.2
309     *
310     * @return bool
311     */
312    private static function is_scheduled_tasks_enabled() {
313        return Feature_Flags::is_enabled( Jetpack_AI_Feature_Flags::SCHEDULED_TASKS );
314    }
315
316    /**
317     * Enqueue scripts and styles for the AI admin page.
318     */
319    public function page_admin_scripts() {
320        // wp-build owns the route bundle and its dependencies; this handle only carries the
321        // inline settings below, so the plugin version is version enough to bust its cache.
322        $script_version = JETPACK__VERSION;
323
324        $blog_id     = Connection_Manager::get_site_id( true );
325        $status      = new Status();
326        $site_suffix = $status->get_site_suffix();
327        // Use the plain hostname for the Atomic activity log URL â€” get_site_suffix() can
328        // include '::' for subdirectory installs, which would break the URL. This matches
329        // the approach used by jetpack-mu-wpcom for the sidebar Activity Log link.
330        $site_host         = wp_parse_url( home_url(), PHP_URL_HOST );
331        $activity_log_site = ( is_string( $site_host ) && '' !== $site_host ) ? $site_host : $site_suffix;
332
333        // Link to the Jetpack SEO page when it registers, which takes both checks below
334        // (see the SEO package's Initializer::init()); otherwise to the Traffic card.
335        $seo_settings_url          = admin_url( 'admin.php?page=jetpack-settings#/traffic' );
336        $is_internal_test          = jetpack_is_internal_testing_environment();
337        $show_scheduled_tasks_view = self::is_scheduled_tasks_enabled();
338        if (
339            // is_available() is the newer of the two; an older SEO package loaded first can lack it.
340            method_exists( '\Automattic\Jetpack\SEO\Initializer', 'is_available' )
341            && \Automattic\Jetpack\SEO\Initializer::is_available()
342            && \Automattic\Jetpack\SEO\Initializer::is_seo_surface_visible()
343        ) {
344            $seo_settings_url = admin_url( 'admin.php?page=jetpack-seo' );
345        }
346
347        // The route bundle is registered by wp-build; this handle exists only to carry the
348        // inline settings below, which the app reads from `window.jetpackAiSettings`.
349        wp_register_script( 'jetpack-ai-admin', false, array(), $script_version, true );
350        wp_enqueue_script( 'jetpack-ai-admin' );
351
352        // The Tracks sender (w.js); without it, queued events never leave the
353        // browser. Consent-gated like the other surfaces that load it.
354        $can_send_tracks = ( new Tracking( 'jetpack', new Connection_Manager() ) )->should_enable_tracking( new Terms_Of_Service(), $status );
355        if ( $can_send_tracks ) {
356            Tracking::register_tracks_functions_scripts( true );
357        }
358
359        // Unconditional, as on the other Jetpack admin pages: the connection store
360        // reads it, and only Scheduled tasks used to need it here.
361        Connection_Initial_State::render_script( 'jetpack-ai-admin' );
362
363        $host            = new Host();
364        $has_my_jetpack  = self::has_my_jetpack();
365        $is_offline_mode = $status->is_offline_mode();
366
367        /**
368         * Filters the host-specific AI Hub configuration.
369         *
370         * @since 16.2
371         *
372         * @param array $config AI Hub host configuration.
373         */
374        $config = apply_filters(
375            'jetpack_ai_admin_config',
376            array(
377                // The Overview and Features views launch on self-hosted sites first.
378                // Keep this filterable so hosts can close them independently.
379                'showGatedViews'    => ! $host->is_wpcom_platform() || ( $host->is_woa_site() && $is_internal_test ),
380                'showA12sBadge'     => $host->is_woa_site() && $is_internal_test,
381                // The same verdicts the feature-settings endpoint reports. That call
382                // exists for the AI Features toggles; the notice must not wait on it.
383                'isUserConnected'   => Jetpack_AI_Settings::user_is_connected(),
384                'isConnected'       => Jetpack_AI_Settings::site_is_connected(),
385                'hostAllowsAi'      => Jetpack_AI_Settings::host_allows_ai(),
386                'masterEnabled'     => Jetpack_AI_Settings::is_master_enabled(),
387                // The route, not a flag: each one documents a different hook.
388                'masterForcedOff'   => Jetpack_AI_Settings::get_master_forced_off_route(),
389                'isOfflineMode'     => $is_offline_mode,
390                'canConnectSite'    => current_user_can( 'jetpack_connect' ),
391                // These three answer one question; a filter changing one alone leaves
392                // a label pointing at a page that is not there.
393                'hasMyJetpack'      => $has_my_jetpack,
394                'userConnectionUrl' => $has_my_jetpack
395                    ? 'admin.php?page=my-jetpack#/connection'
396                    : 'admin.php?page=jetpack-settings#/connect-user',
397                'manageUrl'         => $has_my_jetpack
398                    ? 'admin.php?page=my-jetpack#/features'
399                    : 'admin.php?page=jetpack_modules',
400                'mcpSettingsApi'    => array(
401                    'path'   => '/wpcom/v2/jetpack-ai/mcp-settings',
402                    'format' => 'jetpack',
403                ),
404                // Self-hosted sites get the Hub's `-self-hosted` ChatGPT and Claude connect links.
405                'isSelfHosted'      => ! $host->is_wpcom_platform(),
406                // WordPress.com MCP runs a site's own abilities on every Jetpack site,
407                // Atomic included, as Calypso's MCP page shows them.
408                'showSiteAbilities' => ! $host->is_wpcom_simple(),
409            )
410        );
411
412        // WordPress.com sites use Calypso's log; self-hosted sites use the wp-admin page, which only
413        // exists while the `activity-log` module is on. An empty URL hides the row.
414        $activity_log_filtered = false;
415        if ( $host->is_wpcom_platform() ) {
416            $activity_log_url = 'https://wordpress.com/activity-log/' . $activity_log_site;
417            // Answered by the host, without a remote call.
418            $activity_log_filtered = Current_Plan::supports( 'full-activity-log' );
419        } elseif ( ( new Modules() )->is_active( 'activity-log' ) ) {
420            $activity_log_url = admin_url( 'admin.php?page=' . Jetpack_Activity_Log::PAGE_SLUG );
421            // Filters need paid access. That check can call WordPress.com, so skip it
422            // when the row can't show: offline, or without a linked user.
423            $activity_log_filtered = ! $is_offline_mode
424                && ! empty( $config['isUserConnected'] )
425                && Activity_Log_REST_Controller::has_activity_logs_access();
426        } else {
427            $activity_log_url = '';
428        }
429        if ( $activity_log_filtered ) {
430            // add_query_arg() does not encode values.
431            $activity_log_url = add_query_arg( 'actor', rawurlencode( self::ALL_AI_AGENTS_ACTOR_ID ), $activity_log_url );
432        }
433
434        $show_gated_views = ! empty( $config['showGatedViews'] );
435
436        $plan_info = $show_gated_views ? self::get_ai_plan_info() : array( 'name' => '' );
437
438        $settings = array(
439            'blogId'              => $blog_id ? (int) $blog_id : 0,
440            'activityLogUrl'      => $activity_log_url,
441            'activityLogFiltered' => $activity_log_filtered,
442            'seoSettingsUrl'      => $seo_settings_url,
443            'searchSettingsUrl'   => self::get_search_settings_url(),
444            'siteAdminUrl'        => admin_url(),
445            'userConnectionUrl'   => esc_url_raw( $config['userConnectionUrl'] ?? '' ),
446            'manageUrl'           => esc_url_raw( $config['manageUrl'] ?? '' ),
447            'hasMyJetpack'        => ! empty( $config['hasMyJetpack'] ),
448            'isConnected'         => ! empty( $config['isConnected'] ),
449            'hostAllowsAi'        => ! empty( $config['hostAllowsAi'] ),
450            'masterEnabled'       => ! empty( $config['masterEnabled'] ),
451            'masterForcedOff'     => in_array(
452                $config['masterForcedOff'] ?? '',
453                array(
454                    Jetpack_AI_Settings::FORCED_OFF_ROUTE_FILTER,
455                    Jetpack_AI_Settings::FORCED_OFF_ROUTE_FILTER_VIP,
456                    Jetpack_AI_Settings::FORCED_OFF_ROUTE_MODULES,
457                ),
458                true
459            ) ? $config['masterForcedOff'] : '',
460            'isOfflineMode'       => ! empty( $config['isOfflineMode'] ),
461            'canConnectSite'      => ! empty( $config['canConnectSite'] ),
462            'apiRoot'             => esc_url_raw( rest_url() ),
463            'apiNonce'            => wp_create_nonce( 'wp_rest' ),
464            'pluginUrl'           => plugins_url( '', JETPACK__PLUGIN_FILE ),
465            // Images ship from the plugin directory, so the plugin version is what busts their cache.
466            'assetsVersion'       => JETPACK__VERSION,
467            // The redirect entry bakes in the jetpack_ai_yearly product and
468            // a post-checkout return to this page, so both can be
469            // retargeted without shipping a code change.
470            'upgradeUrl'          => Redirect::get_url( 'jetpack-ai-hub-upgrade' ),
471            // The purchase granting AI â€” the usage card only uses it to pick
472            // the right loading-skeleton shape before the usage fetch lands.
473            // Only looked up when a gated view can render the card.
474            'planName'            => $plan_info['name'],
475            'showFeaturesView'    => $show_gated_views,
476            'showA12sBadge'       => ! empty( $config['showA12sBadge'] ),
477            // The tab and its Agents Manager sidebar ship disabled by default.
478            'featureFlags'        => array(
479                Jetpack_AI_Feature_Flags::SCHEDULED_TASKS => $show_scheduled_tasks_view,
480            ),
481            // The usage endpoint proxies as the current user, which needs
482            // their own WordPress.com account linked â€” not just the site.
483            'isUserConnected'     => ! empty( $config['isUserConnected'] ),
484            // Tracks audience properties for the jetpack_mcp_* events, per the
485            // Tracks standards for AI product events (AIINT-586). The client
486            // sends them as the strings 'true'/'false' (AIINT-576).
487            'isA11n'              => self::is_current_user_automattician(),
488            'isTest'              => $is_internal_test,
489            // Identity for Tracks; the lookup can call WordPress.com on a
490            // cache miss, so it shares the sender's guard.
491            'tracksUserData'      => $can_send_tracks ? self::get_tracks_user_data() : null,
492            'mcpSettingsApi'      => $config['mcpSettingsApi'] ?? array(),
493            'isSelfHosted'        => true === ( $config['isSelfHosted'] ?? false ),
494            'showSiteAbilities'   => true === ( $config['showSiteAbilities'] ?? false ),
495        );
496
497        wp_add_inline_script(
498            'jetpack-ai-admin',
499            'var jetpackAiSettings = ' . wp_json_encode(
500                $settings,
501                JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP
502            ) . ';',
503            'before'
504        );
505
506        /*
507         * `@automattic/jetpack-analytics` reads `window.jpTracksContext.blog_id` at
508         * event-fire time and attaches it to every Tracks event fired from this page.
509         * Without it, JS-fired events from self-hosted sites carry no blog_id â€” the
510         * Tracks pixel cannot resolve the site â€” so the events cannot be joined to
511         * plan or site data. Mirrors Connection\Initial_State::render().
512         */
513        wp_add_inline_script(
514            'jetpack-ai-admin',
515            sprintf(
516                'window.jpTracksContext = window.jpTracksContext || {}; window.jpTracksContext.blog_id = %s;',
517                absint( $blog_id )
518            ),
519            'before'
520        );
521    }
522
523    /**
524     * Connected-user identity for Tracks; null when no WordPress.com account is
525     * linked. Two keys only, so email and locale stay out of the page HTML.
526     *
527     * @return array{userid:int, username:string}|null
528     */
529    private static function get_tracks_user_data() {
530        $identity = \Jetpack_Tracks_Client::get_connected_user_tracks_identity();
531        if ( ! is_array( $identity ) || ! isset( $identity['userid'] ) || ! isset( $identity['username'] ) ) {
532            return null;
533        }
534
535        return array(
536            'userid'   => (int) $identity['userid'],
537            'username' => (string) $identity['username'],
538        );
539    }
540
541    /**
542     * Whether the current user is an Automattician.
543     *
544     * Identity check for the Tracks `is_a11n` audience property â€” it answers
545     * "who is this", not "may they use the tool", so it deliberately does not
546     * consult the MCP allowlist: allowlisted external testers are not a11ns.
547     *
548     * On wpcom Simple/Atomic the platform's is_automattician() is authoritative.
549     * Self-hosted Jetpack has no platform check; there the Tracks identity of a
550     * connected user is their WordPress.com account, so the connected account's
551     * email domain is the identity signal.
552     *
553     * @return bool
554     */
555    private static function is_current_user_automattician() {
556        if ( function_exists( 'is_automattician' ) ) {
557            return (bool) is_automattician( get_current_user_id() );
558        }
559
560        $user_data = ( new Connection_Manager() )->get_connected_user_data();
561        $email     = is_array( $user_data ) && ! empty( $user_data['email'] )
562            ? strtolower( (string) $user_data['email'] )
563            : '';
564
565        return '' !== $email && '@automattic.com' === substr( $email, -15 );
566    }
567
568    /**
569     * The Search dashboard page the AI Answers row links to, or '' once a host
570     * has removed it. Removal is remove_submenu_page() on `admin_menu`, which only
571     * unsets the registry entry â€” menu_page_url() still answers for the page and
572     * wp-admin then denies it â€” so the registry is read after that hook has run.
573     *
574     * @return string
575     */
576    private static function get_search_settings_url() {
577        global $submenu;
578
579        $url = admin_url( 'admin.php?page=jetpack-search#/ai-answers' );
580
581        // The admin shell's guest endpoint runs on admin-ajax, which never builds the menu.
582        if ( wp_doing_ajax() ) {
583            return self::search_page_will_register() ? $url : '';
584        }
585
586        // Search registers under the Jetpack menu, or menu-less (parent '') when
587        // `jetpack_search_should_add_search_submenu` says no; both are reachable.
588        foreach ( array( 'jetpack', '' ) as $parent ) {
589            foreach ( (array) ( $submenu[ $parent ] ?? array() ) as $item ) {
590                if ( isset( $item[2] ) && 'jetpack-search' === $item[2] ) {
591                    return $url;
592                }
593            }
594        }
595
596        return '';
597    }
598
599    /**
600     * Whether the Search dashboard has hooked its page registration, for requests that never build the menu.
601     *
602     * A host that removes the page on `admin_menu` isn't seen here.
603     *
604     * @since 16.5
605     *
606     * @return bool
607     */
608    private static function search_page_will_register() {
609        global $wp_filter;
610        if ( ! class_exists( '\Automattic\Jetpack\Search\Dashboard' ) || ! isset( $wp_filter['admin_menu'] ) ) {
611            return false;
612        }
613        foreach ( $wp_filter['admin_menu']->callbacks as $callbacks ) {
614            foreach ( $callbacks as $callback ) {
615                $function = $callback['function'];
616                if ( is_array( $function ) && $function[0] instanceof \Automattic\Jetpack\Search\Dashboard && 'add_wp_admin_submenu' === $function[1] ) {
617                    return true;
618                }
619            }
620        }
621        return false;
622    }
623
624    /**
625     * Whether My Jetpack is loaded on this host.
626     *
627     * Hosts drop it with the `jetpack_my_jetpack_should_initialize` filter, and
628     * VIP removes it from outside this codebase, where that filter cannot answer.
629     *
630     * @return bool
631     */
632    private static function has_my_jetpack() {
633        if ( ( new Host() )->is_vip_site() ) {
634            return false;
635        }
636
637        return class_exists( 'Automattic\\Jetpack\\My_Jetpack\\Initializer' )
638            && method_exists( 'Automattic\\Jetpack\\My_Jetpack\\Initializer', 'should_initialize' )
639            && \Automattic\Jetpack\My_Jetpack\Initializer::should_initialize();
640    }
641
642    /**
643     * Name of the purchase granting this site AI ("Jetpack Complete"), from
644     * My Jetpack's purchase data â€” its Plans section's source.
645     *
646     * @return array{name: string} An empty string when nothing paid grants AI
647     *                             or the data is unavailable.
648     */
649    private static function get_ai_plan_info() {
650        $empty = array( 'name' => '' );
651
652        if ( ! class_exists( '\Automattic\Jetpack\My_Jetpack\Products\Jetpack_Ai' ) ) {
653            return $empty;
654        }
655
656        // The purchase lookup can make remote requests; cache the outcome
657        // (empty included) so the admin page pays that cost at most hourly.
658        $cached = get_transient( 'jetpack_ai_overview_plan_info' );
659        if ( is_array( $cached ) ) {
660            return array_merge( $empty, $cached );
661        }
662
663        // A failed lookup is not "no purchase": skip the hour-long cache so the
664        // next page load can try again instead of pinning a blank name.
665        if ( is_wp_error( \Automattic\Jetpack\My_Jetpack\Wpcom_Products::get_site_current_purchases() ) ) {
666            return $empty;
667        }
668
669        $purchase = \Automattic\Jetpack\My_Jetpack\Products\Jetpack_Ai::get_paid_plan_purchase_for_product();
670
671        // A WordPress.com site names its own plan, never a Jetpack one.
672        if ( self::is_jetpack_purchase( $purchase ) && ( new Host() )->is_woa_site() ) {
673            $purchase = self::get_wpcom_plan_purchase();
674        }
675
676        $info = $empty;
677        if ( $purchase && ! empty( $purchase->product_name ) && 'expired' !== ( $purchase->expiry_status ?? '' ) ) {
678            // The design shows the bare plan name ("Complete", "Business"), so
679            // trim the store names' brand prefixes; they are untranslated.
680            $info['name'] = (string) preg_replace( '/^(Jetpack|WordPress\.com) /', '', (string) $purchase->product_name );
681        }
682
683        set_transient( 'jetpack_ai_overview_plan_info', $info, HOUR_IN_SECONDS );
684
685        return $info;
686    }
687
688    /**
689     * Whether a purchase was bought from the Jetpack store.
690     *
691     * @param object|null $purchase Purchase from My Jetpack.
692     * @return bool
693     */
694    private static function is_jetpack_purchase( $purchase ) {
695        return (bool) $purchase && 0 === strpos( (string) ( $purchase->product_slug ?? '' ), 'jetpack_' );
696    }
697
698    /**
699     * The purchase behind the site's current WordPress.com plan.
700     *
701     * The plan record carries only a slug and a display name lives on purchases,
702     * so the slug is matched back to the purchase that created it.
703     *
704     * @return object|null Null when the plan or its purchase cannot be found.
705     */
706    private static function get_wpcom_plan_purchase() {
707        $current_plan = \Automattic\Jetpack\My_Jetpack\Wpcom_Products::get_site_current_plan();
708        $plan_slug    = is_array( $current_plan ) && ! empty( $current_plan['product_slug'] )
709            ? (string) $current_plan['product_slug']
710            : '';
711
712        // An empty slug simply matches nothing below, so it needs no guard.
713        foreach ( (array) \Automattic\Jetpack\My_Jetpack\Wpcom_Products::get_site_current_purchases() as $purchase ) {
714            if ( $plan_slug === ( $purchase->product_slug ?? '' ) ) {
715                return $purchase;
716            }
717        }
718
719        return null;
720    }
721
722    /**
723     * Override the base render() to skip wrap_ui entirely.
724     *
725     * Wrap_ui renders the Jetpack masthead header and static footer, which
726     * duplicate the header/footer that AdminPage (React) already provides.
727     * Calling page_render() directly lets AdminPage own the full layout.
728     */
729    public function render() {
730        $this->page_render();
731    }
732
733    /**
734     * Render the page, or say why it could not be rendered.
735     *
736     * The generated wp-build page owns the markup the app mounts into.
737     */
738    public function page_render() {
739        if ( self::should_render_wp_build() ) {
740            jetpack_plugin_jetpack_ai_hub_wp_admin_render_page(); // @phan-suppress-current-line PhanUndeclaredFunction -- should_render_wp_build() checks function_exists(); defined in the generated build/pages/, which Phan excludes.
741            return;
742        }
743
744        // The build output is missing; say so rather than leaving a silent blank page.
745        printf(
746            '<div class="wrap"><h1>%s</h1><div class="notice notice-error"><p>%s</p></div></div>',
747            esc_html__( 'Jetpack AI', 'jetpack' ),
748            esc_html__( 'Jetpack AI could not be loaded because its assets are missing. Reinstalling or updating the plugin usually fixes this. If it keeps happening, contact your site administrator or host.', 'jetpack' )
749        );
750    }
751}
752
753/*
754 * wp-build must load before add_actions() runs on any host, so hook it here: Jetpack_Admin and
755 * mu-wpcom's WordPress.com Simple integration both require this file before `admin_menu`, and
756 * add_action() dedupes.
757 */
758add_action( 'admin_menu', array( 'Jetpack_AI_Page', 'maybe_load_wp_build' ), 1 );