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