Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
98.02% |
892 / 910 |
|
80.85% |
38 / 47 |
CRAP | |
0.00% |
0 / 1 |
| AI_Launchpad_REST | |
98.13% |
892 / 909 |
|
80.85% |
38 / 47 |
268 | |
0.00% |
0 / 1 |
| is_private_site | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| was_launched_at_creation | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
6 | |||
| __construct | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
2 | |||
| schedule_completion_pass | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
5 | |||
| run_scheduled_completion_passes | |
83.33% |
5 / 6 |
|
0.00% |
0 / 1 |
5.12 | |||
| register_routes | |
100.00% |
194 / 194 |
|
100.00% |
1 / 1 |
1 | |||
| sanitize_validation_errors | |
100.00% |
15 / 15 |
|
100.00% |
1 / 1 |
7 | |||
| can_read | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
2 | |||
| can_write | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
2 | |||
| check_eligibility | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
3 | |||
| get_ai_tool_back_url | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
1 | |||
| get_data | |
100.00% |
53 / 53 |
|
100.00% |
1 / 1 |
24 | |||
| get_current_tasks | |
95.65% |
22 / 23 |
|
0.00% |
0 / 1 |
16 | |||
| backfill_to_minimum | |
100.00% |
27 / 27 |
|
100.00% |
1 / 1 |
9 | |||
| backfill_pool | |
100.00% |
14 / 14 |
|
100.00% |
1 / 1 |
2 | |||
| maybe_mark_completed | |
94.44% |
17 / 18 |
|
0.00% |
0 / 1 |
6.01 | |||
| report_task_completions | |
95.83% |
23 / 24 |
|
0.00% |
0 / 1 |
10 | |||
| update_wizard | |
100.00% |
15 / 15 |
|
100.00% |
1 / 1 |
3 | |||
| update_tailored | |
100.00% |
51 / 51 |
|
100.00% |
1 / 1 |
11 | |||
| log_tailoring | |
22.22% |
2 / 9 |
|
0.00% |
0 / 1 |
7.23 | |||
| tailoring_log_extra | |
100.00% |
20 / 20 |
|
100.00% |
1 / 1 |
4 | |||
| get_mcp_connections | |
100.00% |
24 / 24 |
|
100.00% |
1 / 1 |
10 | |||
| fetch_remote_mcp_connections | |
100.00% |
35 / 35 |
|
100.00% |
1 / 1 |
13 | |||
| allow_full_mcp_access | |
100.00% |
20 / 20 |
|
100.00% |
1 / 1 |
7 | |||
| complete_task | |
100.00% |
22 / 22 |
|
100.00% |
1 / 1 |
4 | |||
| skip_task | |
100.00% |
18 / 18 |
|
100.00% |
1 / 1 |
3 | |||
| dismiss | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
1 | |||
| get_skipped_task_ids | |
80.00% |
4 / 5 |
|
0.00% |
0 / 1 |
2.03 | |||
| apply_skipped_tasks | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
3 | |||
| sanitize_subtitle | |
100.00% |
20 / 20 |
|
100.00% |
1 / 1 |
5 | |||
| get_available_tasks | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
1 | |||
| excluded_task_ids_for_goal | |
100.00% |
10 / 10 |
|
100.00% |
1 / 1 |
6 | |||
| available_task_ids | |
96.97% |
32 / 33 |
|
0.00% |
0 / 1 |
4 | |||
| adopt_builder_input | |
100.00% |
16 / 16 |
|
100.00% |
1 / 1 |
5 | |||
| build_all_catalog_tasks | |
100.00% |
22 / 22 |
|
100.00% |
1 / 1 |
5 | |||
| build_tasks | |
95.65% |
66 / 69 |
|
0.00% |
0 / 1 |
30 | |||
| get_cta_override | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
4 | |||
| get_themes_showcase_path | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
3 | |||
| ensure_theme_task | |
100.00% |
9 / 9 |
|
100.00% |
1 / 1 |
6 | |||
| move_task_after | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
3 | |||
| build_store_tasks | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
1 | |||
| build_install_woocommerce_task | |
100.00% |
18 / 18 |
|
100.00% |
1 / 1 |
5 | |||
| build_setup_store_task | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
5 | |||
| insert_before_launch_task | |
90.00% |
9 / 10 |
|
0.00% |
0 / 1 |
7.05 | |||
| get_in_progress_draft_url | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
4 | |||
| get_task_title | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
6 | |||
| get_output_schema | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 | |||
| 1 | <?php |
| 2 | /** |
| 3 | * AI Launchpad REST endpoints. |
| 4 | * |
| 5 | * @package automattic/jetpack-mu-wpcom |
| 6 | * @since 6.11.0 |
| 7 | */ |
| 8 | |
| 9 | use Automattic\Jetpack\Connection\Client; |
| 10 | use Automattic\Jetpack\Connection\Manager as Connection_Manager; |
| 11 | use Automattic\Jetpack\Constants; |
| 12 | |
| 13 | /** |
| 14 | * REST endpoints for the AI Launchpad wizard and AI output options. |
| 15 | */ |
| 16 | class AI_Launchpad_REST extends WP_REST_Controller { |
| 17 | |
| 18 | const OPTION_WIZARD = 'wpcom_ai_launchpad_wizard'; |
| 19 | const OPTION_AI_OUTPUT = 'wpcom_ai_launchpad_ai_output'; |
| 20 | const OPTION_DISMISSED = 'wpcom_ai_launchpad_dismissed'; |
| 21 | const OPTION_SKIPPED = 'wpcom_ai_launchpad_skipped_tasks'; |
| 22 | // Latched "every task is done" flag, autoloaded so the menu gate reads it without rebuilding the task list. |
| 23 | // Set once; cleared only by an explicit reset (re-tailor, dismiss, reset). |
| 24 | const OPTION_COMPLETED = 'wpcom_ai_launchpad_completed'; |
| 25 | |
| 26 | // The goals the wizard offers. |
| 27 | const GOALS = array( 'write', 'build', 'sell', 'newsletter', 'educate', 'portfolio' ); |
| 28 | |
| 29 | // The AI tools the "Bring your AI tool" view links to, the only connections GET /mcp-connections returns. |
| 30 | const MCP_INTEGRATIONS = array( 'chatgpt', 'claude' ); |
| 31 | |
| 32 | // Seconds an Atomic site keeps WordPress.com's MCP answer: enough for the view's first check to reuse the page's. |
| 33 | const MCP_CACHE_TTL = 3; |
| 34 | |
| 35 | /** |
| 36 | * Options whose writes can finish a task outside Site Setup: every listener records completion in the statuses |
| 37 | * option, and the launch task reads `launch-status` live. |
| 38 | */ |
| 39 | const COMPLETION_TRIGGER_OPTIONS = array( 'launchpad_checklist_tasks_statuses', 'launch-status' ); |
| 40 | |
| 41 | /** |
| 42 | * Caps on the client-reported `validation_errors` that reach the `tailored` Logstash record. The client applies |
| 43 | * the same caps; these are the ones that hold for any caller. |
| 44 | */ |
| 45 | const MAX_VALIDATION_ERRORS = 4; |
| 46 | const MAX_VALIDATION_ERROR_LENGTH = 400; |
| 47 | |
| 48 | /** |
| 49 | * Blogs with a completion pass queued for shutdown, as blog id => true. |
| 50 | * |
| 51 | * @var array<int, true> |
| 52 | */ |
| 53 | private $pending_completion_blog_ids = array(); |
| 54 | |
| 55 | // `woo_launch_site`, `link_in_bio_launched`, and `videopress_launched` stay valid launch tasks so a stray AI |
| 56 | // emission passes PUT validation rather than failing the whole list into the deterministic fallback. It is |
| 57 | // normalized to `site_launched` as it is persisted (see update_tailored) and again on read (see build_tasks, |
| 58 | // which is what covers lists persisted before the write-side remap existed). |
| 59 | const LAUNCH_TASK_IDS = array( 'site_launched', 'blog_launched', 'woo_launch_site', 'link_in_bio_launched', 'videopress_launched' ); |
| 60 | |
| 61 | /** |
| 62 | * Tasks the AI Launchpad marks complete on CTA click, because their real signal is unreachable from wp-admin. |
| 63 | * |
| 64 | * Server-side allowlist so the complete-task route can only tick these ids. Mirrored client-side in model.ts. |
| 65 | * |
| 66 | * A registry task may be listed here, but only if its `is_complete` reads `launchpad_checklist_tasks_statuses`: |
| 67 | * that is the option complete_task() writes for it, and a definition computing completion from live site state |
| 68 | * would ignore the write and render as to-do straight after being ticked. |
| 69 | */ |
| 70 | const COMPLETE_ON_CLICK_TASK_IDS = array( |
| 71 | 'complete_profile', |
| 72 | 'manage_subscribers', |
| 73 | 'manage_paid_newsletter_plan', |
| 74 | 'earn_money', |
| 75 | 'start_building_your_audience', |
| 76 | 'site_monitoring_page', |
| 77 | 'setup_ssh', |
| 78 | 'share_site', |
| 79 | 'pick_fonts_colors', |
| 80 | ); |
| 81 | |
| 82 | /** |
| 83 | * Task ids the AI Launchpad synthesizes itself (never present in the AI payload): the sell goal's store-setup |
| 84 | * lead tasks. Skips must accept them alongside the AI-selected ids. |
| 85 | * |
| 86 | * Must list every id minted by build_store_tasks() — a synthetic task missing here renders with a |
| 87 | * Skip button whose write is rejected. |
| 88 | */ |
| 89 | const SYNTHETIC_TASK_IDS = array( |
| 90 | 'install_woocommerce', |
| 91 | 'setup_woocommerce_store', |
| 92 | ); |
| 93 | |
| 94 | /** |
| 95 | * Tasks whose catalog visibility gate is a false negative in this read path, so the AI Launchpad overrides it. |
| 96 | * |
| 97 | * `add_10_email_subscribers` is gated off WordPress.com, but AI_Launchpad_Subscribers_Listener reads the count on |
| 98 | * Atomic, so the task must still render. `add_about_page` is gated on the `_wpcom_template_layout_category` |
| 99 | * page-meta key being registered, which does not happen during a REST request, so the task is wrongly hidden even |
| 100 | * though its "add a page" CTA works — force it visible so tailoring can offer this genuinely useful task. |
| 101 | */ |
| 102 | const FORCE_VISIBLE_TASK_IDS = array( |
| 103 | 'add_10_email_subscribers', |
| 104 | 'add_about_page', |
| 105 | ); |
| 106 | |
| 107 | /** |
| 108 | * Commerce tasks whose catalog visibility gate requires WooCommerce to be active. |
| 109 | * |
| 110 | * On a fresh sell site these would be dropped, collapsing the list. Instead the sell branch keeps them as a |
| 111 | * disabled preview of the store roadmap until WooCommerce is active. See build_tasks()'s $disable_hidden_woo mode. |
| 112 | */ |
| 113 | const WOO_TASK_IDS = array( |
| 114 | 'woo_customize_store', |
| 115 | 'woo_products', |
| 116 | 'set_up_payments', |
| 117 | ); |
| 118 | |
| 119 | /** |
| 120 | * CTA destinations the AI Launchpad repoints to wp-admin, keyed by task id, each mapping to an `admin_url()` path. |
| 121 | * |
| 122 | * The catalog sends these to Calypso flows that are a poor fit for wp-admin. Overridden on read so the shared |
| 123 | * catalog (used by the legacy launchpad too) is left untouched. |
| 124 | */ |
| 125 | const CTA_OVERRIDES = array( |
| 126 | 'connect_social_media' => 'admin.php?page=jetpack-social', |
| 127 | ); |
| 128 | |
| 129 | /** |
| 130 | * Jetpack Social tasks, hidden on private sites where wpcom does not load Publicize (so their CTA page would 404). |
| 131 | * `drive_traffic` needs no entry: it remaps onto `connect_social_media` before this gate runs. |
| 132 | */ |
| 133 | const SOCIAL_PAGE_TASK_IDS = array( |
| 134 | 'connect_social_media', |
| 135 | ); |
| 136 | |
| 137 | /** |
| 138 | * Tasks the model may pick only when the site's goal is one of the listed goals. |
| 139 | * |
| 140 | * These were prose rules in the tailoring prompt ("Only include woo_* if the goal is sell OR the user |
| 141 | * explicitly mentions selling"). Prose is not enforcement: the model can ignore it, and when the |
| 142 | * available-tasks lookup fails the prompt falls back to the unfiltered menu. Enforced here instead, at |
| 143 | * both ends — the menu never offers them (available_task_ids) and PUT drops them (update_tailored). |
| 144 | * |
| 145 | * The free-text escape hatch is deliberately gone. The wizard goal is an explicit user choice, and the |
| 146 | * escape hatch was the non-determinism being removed. |
| 147 | * |
| 148 | * The two directions of disagreement with a task's `goals` annotation in js/lib/prompts.ts are not |
| 149 | * equivalent, and only one is acceptable: |
| 150 | * |
| 151 | * - Annotation BROADER than this map is fine. The annotation is soft affinity for the model, this is the |
| 152 | * hard rule, and a task can be a tasteful fit for a goal it is not permitted on — the rule still blocks |
| 153 | * it. The payment tasks are the live example: annotated for `newsletter` as well as `sell`, permitted |
| 154 | * only on `sell`. |
| 155 | * - Annotation NARROWER than this map is a bug. It means a task the annotation itself calls goal-specific |
| 156 | * can be selected and persisted on any goal, which is the inappropriate-task problem this whole change |
| 157 | * exists to fix. `woo_tax`, `woo_marketing` and `woo_add_domain` were exactly that: annotated `sell`, |
| 158 | * unrestricted here, and renderable on a blog — their catalog gate |
| 159 | * (wpcom_launchpad_is_woocommerce_setup_visible) is goal-agnostic and passes on any WoA site with |
| 160 | * WooCommerce active, which is every site this feature runs on. |
| 161 | * |
| 162 | * So: every id annotated with a single goal belongs here. No exceptions — `sensei_setup` is listed even |
| 163 | * though its catalog gate (WoA plus Sensei LMS active) already hides it almost everywhere, because a rule |
| 164 | * with one documented exception is a rule the next auditor has to re-derive. AI_Launchpad_Task_Menu_Test |
| 165 | * reads the annotations and fails if a single-goal one is missing here. |
| 166 | * |
| 167 | * The ids are matched after wpcom_ai_launchpad_remap_task_id(), so a twin of a restricted task is covered |
| 168 | * by the entry for the id it renders as and must not be listed separately. |
| 169 | */ |
| 170 | const GOAL_RESTRICTED_TASK_IDS = array( |
| 171 | 'woo_products' => 'sell', |
| 172 | 'woo_customize_store' => 'sell', |
| 173 | 'woo_woocommerce_payments' => 'sell', |
| 174 | 'woo_tax' => 'sell', |
| 175 | 'woo_marketing' => 'sell', |
| 176 | 'woo_add_domain' => 'sell', |
| 177 | 'set_up_payments' => 'sell', |
| 178 | 'stripe_connected' => 'sell', |
| 179 | 'add_10_email_subscribers' => 'newsletter', |
| 180 | 'import_subscribers' => 'newsletter', |
| 181 | 'newsletter_plan_created' => 'newsletter', |
| 182 | 'sensei_setup' => 'educate', |
| 183 | ); |
| 184 | |
| 185 | /** |
| 186 | * Tasks excluded for one specific goal and allowed on every other — the inverse of GOAL_RESTRICTED_TASK_IDS. |
| 187 | * |
| 188 | * Split into its own map rather than folded in behind a `!sell` marker, so neither map needs a value whose |
| 189 | * meaning flips on a prefix and each docblock describes all of its own entries. |
| 190 | * |
| 191 | * `add_gallery_page` is excluded for sell so a store site cannot end up with both the store sequence and a |
| 192 | * gallery. get_current_tasks() used to enforce that structurally, through the if/else that injected the |
| 193 | * gallery only on the non-sell branch; now that the model picks the gallery from the menu, this entry is |
| 194 | * the only thing holding it — the menu never offers it on sell, and PUT drops it if the model picks it anyway. |
| 195 | * |
| 196 | * Both ends are write-side: build_tasks() applies no exclusion, so a payload that already holds an excluded id |
| 197 | * renders it. Reaching that needs a compound failure (the availability lookup fails, so the prompt falls back |
| 198 | * to the full menu, AND the wizard-goal option has not landed yet, so the goal comes from the model's echo). |
| 199 | * True of every entry in both maps, not just this one; read-side enforcement is the fix if it ever bites. |
| 200 | */ |
| 201 | const GOAL_EXCLUDED_TASK_IDS = array( |
| 202 | 'add_gallery_page' => 'sell', |
| 203 | ); |
| 204 | |
| 205 | /** |
| 206 | * Tasks the AI builder already did, never offered on an AI-built site: its content, its design (store design |
| 207 | * included), and its name. AI_Launchpad_Task_Menu_Test checks the JS AI-built fallback lists against it. |
| 208 | */ |
| 209 | const AI_BUILT_EXCLUDED_TASK_IDS = array( |
| 210 | 'first_post_published', |
| 211 | 'add_about_page', |
| 212 | 'update_about_page', |
| 213 | 'add_new_page', |
| 214 | 'edit_page', |
| 215 | 'add_contact_page', |
| 216 | 'add_events_page', |
| 217 | 'add_video_page', |
| 218 | 'add_gallery_page', |
| 219 | 'add_portfolio_piece', |
| 220 | 'site_theme_selected', |
| 221 | 'design_edited', |
| 222 | 'front_page_updated', |
| 223 | 'pick_fonts_colors', |
| 224 | 'woo_customize_store', |
| 225 | 'site_title', |
| 226 | 'setup_general', |
| 227 | ); |
| 228 | |
| 229 | /** |
| 230 | * First-post tasks that can sit "in progress": the AI-created draft post exists but has not been published yet. |
| 231 | * |
| 232 | * Detected through the `_wpcom_ai_launchpad_first_post` marker meta (via AI_Launchpad_First_Post_Listener), so an |
| 233 | * unrelated pre-existing draft never counts. Paired with `add_about_page`, which has its own marker meta. |
| 234 | * `first_post_published_newsletter` needs no entry: it remaps onto `first_post_published` before this runs. |
| 235 | */ |
| 236 | const IN_PROGRESS_FIRST_POST_TASK_IDS = array( |
| 237 | 'first_post_published', |
| 238 | ); |
| 239 | |
| 240 | /** |
| 241 | * Whether the site's visibility is set to private (`blog_public = -1`). |
| 242 | * |
| 243 | * Read directly to avoid a hard dependency on the Status package in this read path. |
| 244 | * |
| 245 | * @return bool |
| 246 | */ |
| 247 | private function is_private_site() { |
| 248 | return '-1' === (string) get_option( 'blog_public' ); |
| 249 | } |
| 250 | |
| 251 | /** |
| 252 | * Whether the site was public from the moment it was created. |
| 253 | * |
| 254 | * WordPress.com only writes `launch-status` for a site created private or coming soon, as `unlaunched`, and flips |
| 255 | * it to `launched` at launch. A public site without it never had anything to launch. |
| 256 | * |
| 257 | * Limited to sites created past the no-guidance cutoff, so the launch task of an older site doesn't flip to done |
| 258 | * (and report a completion) on deploy. |
| 259 | * |
| 260 | * @return bool |
| 261 | */ |
| 262 | private function was_launched_at_creation() { |
| 263 | if ( get_option( 'launch-status' ) ) { |
| 264 | return false; |
| 265 | } |
| 266 | |
| 267 | if ( $this->is_private_site() || 1 === (int) get_option( 'wpcom_public_coming_soon' ) ) { |
| 268 | return false; |
| 269 | } |
| 270 | |
| 271 | $blog_id = function_exists( 'get_wpcom_blog_id' ) ? get_wpcom_blog_id() : false; |
| 272 | |
| 273 | return $blog_id && wpcom_launchpad_is_past_no_guidance_cutoff( $blog_id ); |
| 274 | } |
| 275 | |
| 276 | /** |
| 277 | * Class constructor. |
| 278 | */ |
| 279 | public function __construct() { |
| 280 | $this->namespace = 'wpcom/v2'; |
| 281 | $this->rest_base = 'ai-launchpad'; |
| 282 | |
| 283 | add_action( 'rest_api_init', array( $this, 'register_routes' ) ); |
| 284 | |
| 285 | foreach ( self::COMPLETION_TRIGGER_OPTIONS as $option ) { |
| 286 | add_action( "add_option_{$option}", array( $this, 'schedule_completion_pass' ) ); |
| 287 | add_action( "update_option_{$option}", array( $this, 'schedule_completion_pass' ) ); |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | /** |
| 292 | * Queues a completion pass for shutdown, so finishing the last task outside Site Setup (a launch, the editor) |
| 293 | * hides the menu on the next page load. Deferred so it sees the request's final state, not a write mid-way. |
| 294 | * |
| 295 | * @return void |
| 296 | */ |
| 297 | public function schedule_completion_pass() { |
| 298 | // Some tasks judge completion by the current user, so cron or a visitor must not decide the owner's list. |
| 299 | if ( |
| 300 | ! current_user_can( 'manage_options' ) |
| 301 | || get_option( self::OPTION_COMPLETED ) |
| 302 | || ! get_option( self::OPTION_AI_OUTPUT ) |
| 303 | || true !== $this->check_eligibility() |
| 304 | ) { |
| 305 | return; |
| 306 | } |
| 307 | |
| 308 | $this->pending_completion_blog_ids[ get_current_blog_id() ] = true; |
| 309 | add_action( 'shutdown', array( $this, 'run_scheduled_completion_passes' ) ); |
| 310 | } |
| 311 | |
| 312 | /** |
| 313 | * Runs the queued completion passes, each in the blog that queued it: on WordPress.com Simple the write can |
| 314 | * happen inside a switch_to_blog() that is restored by shutdown. |
| 315 | * |
| 316 | * @return void |
| 317 | */ |
| 318 | public function run_scheduled_completion_passes() { |
| 319 | foreach ( array_keys( $this->pending_completion_blog_ids ) as $blog_id ) { |
| 320 | $switched = is_multisite() && get_current_blog_id() !== $blog_id && switch_to_blog( $blog_id ); |
| 321 | $this->maybe_mark_completed(); |
| 322 | if ( $switched ) { |
| 323 | restore_current_blog(); |
| 324 | } |
| 325 | } |
| 326 | $this->pending_completion_blog_ids = array(); |
| 327 | } |
| 328 | |
| 329 | /** |
| 330 | * Register our routes. |
| 331 | */ |
| 332 | public function register_routes() { |
| 333 | register_rest_route( |
| 334 | $this->namespace, |
| 335 | $this->rest_base, |
| 336 | array( |
| 337 | array( |
| 338 | 'methods' => WP_REST_Server::READABLE, |
| 339 | 'callback' => array( $this, 'get_data' ), |
| 340 | 'permission_callback' => array( $this, 'can_read' ), |
| 341 | 'args' => array( |
| 342 | // Testing aid: render the full task catalog so every task can be exercised from one site. |
| 343 | 'all_tasks' => array( |
| 344 | 'description' => 'Return the full task catalog instead of the tailored list (testing aid).', |
| 345 | 'type' => 'boolean', |
| 346 | 'default' => false, |
| 347 | ), |
| 348 | 'start' => array( |
| 349 | 'description' => 'The screen Site Setup opens on: `ai-tool` for "Which AI do you use?".', |
| 350 | 'type' => 'string', |
| 351 | 'enum' => array( 'ai-tool' ), |
| 352 | ), |
| 353 | ), |
| 354 | ), |
| 355 | array( |
| 356 | 'methods' => WP_REST_Server::DELETABLE, |
| 357 | 'callback' => array( $this, 'dismiss' ), |
| 358 | 'permission_callback' => array( $this, 'can_write' ), |
| 359 | ), |
| 360 | ) |
| 361 | ); |
| 362 | |
| 363 | register_rest_route( |
| 364 | $this->namespace, |
| 365 | $this->rest_base . '/wizard', |
| 366 | array( |
| 367 | array( |
| 368 | 'methods' => 'PUT', |
| 369 | 'callback' => array( $this, 'update_wizard' ), |
| 370 | 'permission_callback' => array( $this, 'can_write' ), |
| 371 | 'args' => array( |
| 372 | 'goal' => array( |
| 373 | 'description' => 'The site goal picked in the wizard.', |
| 374 | 'type' => 'string', |
| 375 | 'enum' => self::GOALS, |
| 376 | 'required' => true, |
| 377 | ), |
| 378 | 'site_name' => array( |
| 379 | 'description' => 'The site name entered in the wizard.', |
| 380 | 'type' => 'string', |
| 381 | 'required' => true, |
| 382 | 'sanitize_callback' => 'sanitize_text_field', |
| 383 | ), |
| 384 | 'description' => array( |
| 385 | 'description' => 'The free-text site description entered in the wizard.', |
| 386 | 'type' => 'string', |
| 387 | 'required' => true, |
| 388 | 'sanitize_callback' => 'sanitize_textarea_field', |
| 389 | ), |
| 390 | 'locale' => array( |
| 391 | 'description' => 'The site language the AI writes the drafts and page intros in.', |
| 392 | 'type' => 'string', |
| 393 | 'default' => 'en', |
| 394 | 'sanitize_callback' => 'sanitize_text_field', |
| 395 | ), |
| 396 | 'ui_locale' => array( |
| 397 | 'description' => 'The account language the AI writes the task subtitles in.', |
| 398 | 'type' => 'string', |
| 399 | 'default' => 'en', |
| 400 | 'sanitize_callback' => 'sanitize_text_field', |
| 401 | ), |
| 402 | ), |
| 403 | ), |
| 404 | ) |
| 405 | ); |
| 406 | |
| 407 | register_rest_route( |
| 408 | $this->namespace, |
| 409 | $this->rest_base . '/available-tasks', |
| 410 | array( |
| 411 | array( |
| 412 | 'methods' => WP_REST_Server::READABLE, |
| 413 | 'callback' => array( $this, 'get_available_tasks' ), |
| 414 | 'permission_callback' => array( $this, 'can_read' ), |
| 415 | 'args' => array( |
| 416 | 'goal' => array( |
| 417 | 'description' => 'The selected goal; sell keeps commerce tasks as available previews.', |
| 418 | 'type' => 'string', |
| 419 | 'default' => '', |
| 420 | 'sanitize_callback' => 'sanitize_key', |
| 421 | ), |
| 422 | ), |
| 423 | ), |
| 424 | ) |
| 425 | ); |
| 426 | |
| 427 | register_rest_route( |
| 428 | $this->namespace, |
| 429 | $this->rest_base . '/mcp-connections', |
| 430 | array( |
| 431 | array( |
| 432 | 'methods' => WP_REST_Server::READABLE, |
| 433 | 'callback' => array( $this, 'get_mcp_connections' ), |
| 434 | 'permission_callback' => array( $this, 'can_read' ), |
| 435 | ), |
| 436 | ) |
| 437 | ); |
| 438 | |
| 439 | register_rest_route( |
| 440 | $this->namespace, |
| 441 | $this->rest_base . '/mcp-access', |
| 442 | array( |
| 443 | array( |
| 444 | 'methods' => 'POST', |
| 445 | 'callback' => array( $this, 'allow_full_mcp_access' ), |
| 446 | 'permission_callback' => array( $this, 'can_write' ), |
| 447 | ), |
| 448 | ) |
| 449 | ); |
| 450 | |
| 451 | register_rest_route( |
| 452 | $this->namespace, |
| 453 | $this->rest_base . '/complete-task', |
| 454 | array( |
| 455 | array( |
| 456 | 'methods' => 'POST', |
| 457 | 'callback' => array( $this, 'complete_task' ), |
| 458 | 'permission_callback' => array( $this, 'can_write' ), |
| 459 | 'args' => array( |
| 460 | 'task_id' => array( |
| 461 | 'description' => 'The acknowledgment task to mark complete.', |
| 462 | 'type' => 'string', |
| 463 | 'required' => true, |
| 464 | 'sanitize_callback' => 'sanitize_key', |
| 465 | ), |
| 466 | ), |
| 467 | ), |
| 468 | ) |
| 469 | ); |
| 470 | |
| 471 | register_rest_route( |
| 472 | $this->namespace, |
| 473 | $this->rest_base . '/skip-task', |
| 474 | array( |
| 475 | array( |
| 476 | 'methods' => 'POST', |
| 477 | 'callback' => array( $this, 'skip_task' ), |
| 478 | 'permission_callback' => array( $this, 'can_write' ), |
| 479 | 'args' => array( |
| 480 | 'task_id' => array( |
| 481 | 'description' => 'The task to skip.', |
| 482 | 'type' => 'string', |
| 483 | 'required' => true, |
| 484 | 'sanitize_callback' => 'sanitize_key', |
| 485 | ), |
| 486 | ), |
| 487 | ), |
| 488 | ) |
| 489 | ); |
| 490 | |
| 491 | register_rest_route( |
| 492 | $this->namespace, |
| 493 | $this->rest_base . '/tailored', |
| 494 | array( |
| 495 | array( |
| 496 | 'methods' => 'PUT', |
| 497 | 'callback' => array( $this, 'update_tailored' ), |
| 498 | 'permission_callback' => array( $this, 'can_write' ), |
| 499 | 'args' => array( |
| 500 | 'source' => array( |
| 501 | 'description' => 'Whether the payload came from the AI or the deterministic fallback. Query parameter; the JSON body must match the agent output schema exactly.', |
| 502 | 'type' => 'string', |
| 503 | 'enum' => array( 'ai', 'fallback' ), |
| 504 | 'default' => 'ai', |
| 505 | ), |
| 506 | 'duration_ms' => array( |
| 507 | 'description' => 'Client-measured tailoring duration in milliseconds, for the tailored Logstash record.', |
| 508 | 'type' => 'integer', |
| 509 | 'minimum' => 0, |
| 510 | ), |
| 511 | 'attempts' => array( |
| 512 | 'description' => 'How many jetpack-ai-query attempts the client made, for the tailored Logstash record.', |
| 513 | 'type' => 'integer', |
| 514 | 'minimum' => 0, |
| 515 | ), |
| 516 | 'ai_session_id' => array( |
| 517 | 'description' => 'Client-minted id for this tailoring run, carried by every Tracks event fired afterwards.', |
| 518 | 'type' => 'string', |
| 519 | 'default' => '', |
| 520 | // A UUID is 36 characters; 64 leaves headroom without letting an |
| 521 | // oversized value reach the option, the inline script, and every |
| 522 | // Tracks event. sanitize_key() doesn't bound length on its own, so |
| 523 | // the validate_callback is what actually enforces maxLength here — |
| 524 | // WP only runs per-arg schema validation when one is wired in. |
| 525 | 'maxLength' => 64, |
| 526 | 'sanitize_callback' => 'sanitize_key', |
| 527 | 'validate_callback' => 'rest_validate_request_arg', |
| 528 | ), |
| 529 | 'validation_errors' => array( |
| 530 | 'description' => 'Why each failed jetpack-ai-query attempt failed, one entry per attempt (schema paths and rule names, never values), for the tailored Logstash record.', |
| 531 | 'type' => 'array', |
| 532 | 'items' => array( 'type' => 'string' ), |
| 533 | 'default' => array(), |
| 534 | // Sanitized down rather than validated: a malformed diagnostic must never cost the |
| 535 | // user their tailored list. |
| 536 | 'sanitize_callback' => array( self::class, 'sanitize_validation_errors' ), |
| 537 | ), |
| 538 | ), |
| 539 | ), |
| 540 | ) |
| 541 | ); |
| 542 | } |
| 543 | |
| 544 | /** |
| 545 | * Sanitizes the client-reported jetpack-ai-query failure reasons for the `tailored` Logstash record. |
| 546 | * |
| 547 | * The client sends only schema paths and rule names. This keeps it that way for any caller: anything that is |
| 548 | * not a string is dropped, every reason is reduced to the characters such a path and rule use (no quotes, so no |
| 549 | * quoted value survives), each is cut to MAX_VALIDATION_ERROR_LENGTH, and at most MAX_VALIDATION_ERRORS are kept. |
| 550 | * |
| 551 | * @param mixed $value The raw param value. |
| 552 | * @return string[] The sanitized reasons. |
| 553 | */ |
| 554 | public static function sanitize_validation_errors( $value ) { |
| 555 | if ( is_string( $value ) ) { |
| 556 | $value = array( $value ); |
| 557 | } |
| 558 | if ( ! is_array( $value ) ) { |
| 559 | return array(); |
| 560 | } |
| 561 | |
| 562 | $reasons = array(); |
| 563 | foreach ( $value as $reason ) { |
| 564 | if ( ! is_string( $reason ) ) { |
| 565 | continue; |
| 566 | } |
| 567 | $reason = trim( substr( (string) preg_replace( '/[^A-Za-z0-9_.$\[\]:;<>= -]/', '', $reason ), 0, self::MAX_VALIDATION_ERROR_LENGTH ) ); |
| 568 | if ( '' === $reason ) { |
| 569 | continue; |
| 570 | } |
| 571 | $reasons[] = $reason; |
| 572 | if ( count( $reasons ) >= self::MAX_VALIDATION_ERRORS ) { |
| 573 | break; |
| 574 | } |
| 575 | } |
| 576 | |
| 577 | return $reasons; |
| 578 | } |
| 579 | |
| 580 | /** |
| 581 | * Permission callback for reads. |
| 582 | * |
| 583 | * @return true|WP_Error|false |
| 584 | */ |
| 585 | public function can_read() { |
| 586 | if ( ! current_user_can( 'edit_posts' ) ) { |
| 587 | return false; |
| 588 | } |
| 589 | |
| 590 | return $this->check_eligibility(); |
| 591 | } |
| 592 | |
| 593 | /** |
| 594 | * Permission callback for writes. |
| 595 | * |
| 596 | * @return true|WP_Error|false |
| 597 | */ |
| 598 | public function can_write() { |
| 599 | if ( ! current_user_can( 'manage_options' ) ) { |
| 600 | return false; |
| 601 | } |
| 602 | |
| 603 | return $this->check_eligibility(); |
| 604 | } |
| 605 | |
| 606 | /** |
| 607 | * Returns a 404 error for ineligible sites, true otherwise. |
| 608 | * |
| 609 | * @return true|WP_Error |
| 610 | */ |
| 611 | private function check_eligibility() { |
| 612 | // Fail closed: if the gate is unavailable, treat the site as not eligible. |
| 613 | if ( ! function_exists( 'wpcom_ai_launchpad_is_eligible' ) || ! wpcom_ai_launchpad_is_eligible() ) { |
| 614 | return new WP_Error( |
| 615 | 'ai_launchpad_not_eligible', |
| 616 | __( 'This site is not eligible for the AI Launchpad.', 'jetpack-mu-wpcom' ), |
| 617 | array( 'status' => 404 ) |
| 618 | ); |
| 619 | } |
| 620 | |
| 621 | return true; |
| 622 | } |
| 623 | |
| 624 | /** |
| 625 | * Calypso's "Let's design your site" page for this site, where Back on the `start=ai-tool` view leads. |
| 626 | * |
| 627 | * @return string |
| 628 | */ |
| 629 | private function get_ai_tool_back_url() { |
| 630 | return esc_url_raw( |
| 631 | add_query_arg( |
| 632 | 'siteSlug', |
| 633 | rawurlencode( wpcom_get_site_slug() ), |
| 634 | wpcom_get_calypso_origin() . '/setup/onboarding/setup-your-site-ai' |
| 635 | ) |
| 636 | ); |
| 637 | } |
| 638 | |
| 639 | /** |
| 640 | * Composite read: wizard payload, AI output, enriched tasks, statuses, and eligibility. |
| 641 | * |
| 642 | * @param WP_REST_Request|null $request Request object (for the `all_tasks` testing param and `start`). |
| 643 | * @return array |
| 644 | */ |
| 645 | public function get_data( $request = null ) { |
| 646 | $wizard = get_option( self::OPTION_WIZARD ); |
| 647 | $ai_output = get_option( self::OPTION_AI_OUTPUT ); |
| 648 | if ( is_array( $ai_output ) ) { |
| 649 | // Internal analytics bookkeeping (see report_task_completions), not part of the client contract. |
| 650 | unset( $ai_output['tracked_completed'] ); |
| 651 | } |
| 652 | |
| 653 | // Testing aid: ?all_tasks=1 renders the whole catalog, independent of the persisted tailored output. |
| 654 | $all_tasks = $request instanceof WP_REST_Request && $request->get_param( 'all_tasks' ); |
| 655 | if ( $all_tasks ) { |
| 656 | $tasks = $this->apply_skipped_tasks( $this->build_all_catalog_tasks() ); |
| 657 | } else { |
| 658 | $tasks = $this->get_current_tasks(); |
| 659 | } |
| 660 | |
| 661 | // The membership tasks' completion is recomputed in build_tasks(), so overlay it to keep |
| 662 | // checklist_statuses consistent with tasks[].completed for them. |
| 663 | $checklist_statuses = (array) get_option( 'launchpad_checklist_tasks_statuses', array() ); |
| 664 | foreach ( $tasks as $task ) { |
| 665 | if ( AI_Launchpad_Memberships::has_override( $task['id'] ) ) { |
| 666 | $checklist_statuses[ $task['id'] ] = $task['completed']; |
| 667 | } |
| 668 | } |
| 669 | |
| 670 | $this->maybe_mark_completed(); |
| 671 | |
| 672 | // The client shows the wizard when there is no AI output and ?all_tasks=1 is off (decideInitialView() |
| 673 | // in js/lib/orchestration.ts). The banner never renders there, so skip the offer and its ExPlat |
| 674 | // assignment: a user who sees only the wizard must not count as exposed. The list reads this endpoint |
| 675 | // again once the wizard finishes, and that read carries the offer. |
| 676 | $shows_wizard = ! is_array( $ai_output ) && ! $all_tasks; |
| 677 | $starts_on_ai_tool = $request instanceof WP_REST_Request && 'ai-tool' === $request->get_param( 'start' ); |
| 678 | |
| 679 | $inferred_input = null; |
| 680 | if ( $shows_wizard && current_user_can( 'manage_options' ) ) { |
| 681 | $builder_input = wpcom_ai_launchpad_builder_input(); |
| 682 | if ( null !== $builder_input ) { |
| 683 | $inferred_input = $this->adopt_builder_input( $builder_input ); |
| 684 | $wizard = get_option( self::OPTION_WIZARD ); |
| 685 | } |
| 686 | } |
| 687 | |
| 688 | // An AI-built site skips the wizard, and `start=ai-tool` opens it on the AI tool view instead of its first step. |
| 689 | $opens_wizard = $shows_wizard && null === $inferred_input; |
| 690 | $opens_on_ai_tool = $opens_wizard && $starts_on_ai_tool; |
| 691 | $assigns_goals_variation = $opens_wizard && ! $starts_on_ai_tool; |
| 692 | |
| 693 | $detects_directly = function_exists( 'wpcom_mcp_get_user_connections' ); |
| 694 | // Atomic reaches the AI tool view only through `start=ai-tool`, so only that read pays for asking WordPress.com. |
| 695 | $detects_remotely = ! $detects_directly && $opens_on_ai_tool && null !== $this->fetch_remote_mcp_connections(); |
| 696 | |
| 697 | return array( |
| 698 | 'wizard' => is_array( $wizard ) ? $wizard : null, |
| 699 | 'ai_output' => is_array( $ai_output ) ? $ai_output : null, |
| 700 | 'tasks' => $tasks, |
| 701 | 'checklist_statuses' => $checklist_statuses, |
| 702 | 'dismissed' => (bool) get_option( self::OPTION_DISMISSED, false ), |
| 703 | // Lets the page celebrate a list finished elsewhere, which this read latches. |
| 704 | 'list_completed' => (bool) get_option( self::OPTION_COMPLETED ), |
| 705 | 'is_eligible' => true, |
| 706 | // Whether the next tailoring is for an AI-built site, so the client fallback skips the builder's tasks. |
| 707 | 'ai_built' => wpcom_ai_launchpad_is_ai_built(), |
| 708 | // What the AI Website Builder learned, so an AI-built site skips the wizard and tailors with it. |
| 709 | 'inferred_input' => $inferred_input, |
| 710 | // The language this request is translated into, which is the reader's own. Task subtitles |
| 711 | // follow it, since they are read here and never published. |
| 712 | 'user_language' => determine_locale(), |
| 713 | // Site context the client needs for the launch-task CTA, the preview thumbnail/title, and wizard prefill. |
| 714 | 'site' => array( |
| 715 | 'url' => home_url(), |
| 716 | 'title' => get_bloginfo( 'name' ), |
| 717 | 'description' => get_bloginfo( 'description' ), |
| 718 | // Block themes open the Site Editor; classic themes fall back to the Customizer. |
| 719 | 'edit_url' => wp_is_block_theme() ? admin_url( 'site-editor.php' ) : admin_url( 'customize.php' ), |
| 720 | // The site language, which the AI output and the copy written into pages follow. |
| 721 | 'language' => wpcom_ai_launchpad_site_locale(), |
| 722 | 'copy' => wpcom_ai_launchpad_site_copy(), |
| 723 | // Preselects the wizard goal, e.g. `newsletter` for a site from the newsletter signup flow. |
| 724 | 'site_intent' => get_option( 'site_intent' ), |
| 725 | ), |
| 726 | // The free DIFM offer banner under the task list, or null when it must not show. |
| 727 | 'difm_offer' => $shows_wizard ? null : AI_Launchpad_Difm_Offer::get_offer(), |
| 728 | // The goals step's experiment variation, assigned only when the wizard opens on its own first step. |
| 729 | 'goals_variation' => $assigns_goals_variation ? AI_Launchpad_Bring_Your_AI_Tool::get_variation() : null, |
| 730 | // Where Back leads from a `start=ai-tool` Site Setup; built here from an allowlisted origin. |
| 731 | 'ai_tool_back_url' => $opens_on_ai_tool ? $this->get_ai_tool_back_url() : null, |
| 732 | // Whether GET /mcp-connections can see connections: through wpcom's helper, or once WordPress.com has answered. |
| 733 | 'mcp_detection' => $detects_directly || $detects_remotely, |
| 734 | // Whether each check asks WordPress.com over the network. |
| 735 | 'mcp_remote' => $detects_remotely, |
| 736 | // Whether POST /mcp-access can allow full access in place, which needs wpcom's helper and a site admin. |
| 737 | 'mcp_allow_full' => function_exists( 'wpcom_mcp_set_user_access_level' ) && current_user_can( 'manage_options' ), |
| 738 | ); |
| 739 | } |
| 740 | |
| 741 | /** |
| 742 | * The site's tailored task list (AI-selected + the synthetic store tasks, skip overlay applied) — the tasks |
| 743 | * GET renders, minus the ?all_tasks testing view. Shared by GET and the completion check. |
| 744 | * |
| 745 | * @return array |
| 746 | */ |
| 747 | public function get_current_tasks() { |
| 748 | $ai_output = get_option( self::OPTION_AI_OUTPUT ); |
| 749 | |
| 750 | // Guard the nested payload: partial/failed writes may leave the option without payload.tasks. |
| 751 | $payload = is_array( $ai_output ) && isset( $ai_output['payload'] ) && is_array( $ai_output['payload'] ) |
| 752 | ? $ai_output['payload'] |
| 753 | : array(); |
| 754 | // Validate `inferred` as an array before reading from it, since a partial write could leave it non-array. |
| 755 | $inferred = isset( $payload['inferred'] ) && is_array( $payload['inferred'] ) ? $payload['inferred'] : array(); |
| 756 | $theme_category = isset( $inferred['theme_category'] ) && is_string( $inferred['theme_category'] ) |
| 757 | ? $inferred['theme_category'] |
| 758 | : ''; |
| 759 | |
| 760 | // The same authority update_tailored() enforces against: the user's own wizard goal, not the |
| 761 | // model's echo of it. Anything else lets PUT strip a goal's tasks while GET injects them. |
| 762 | $goal = wpcom_ai_launchpad_resolve_goal( $payload ); |
| 763 | |
| 764 | if ( ! function_exists( 'is_plugin_active' ) ) { |
| 765 | require_once ABSPATH . 'wp-admin/includes/plugin.php'; |
| 766 | } |
| 767 | $woo_active = is_plugin_active( 'woocommerce/woocommerce.php' ); |
| 768 | |
| 769 | // On a sell site without WooCommerce, keep the gated commerce tasks as a disabled preview of the store |
| 770 | // roadmap instead of dropping them (which would collapse the list to almost nothing). |
| 771 | $disable_hidden_woo = 'sell' === $goal && ! $woo_active; |
| 772 | |
| 773 | $theme_cta = $this->get_themes_showcase_path( $goal, $theme_category ); |
| 774 | |
| 775 | $ai_tasks = isset( $payload['tasks'] ) && is_array( $payload['tasks'] ) ? $payload['tasks'] : array(); |
| 776 | |
| 777 | // A store needs a theme, so a sell list offers "Choose a theme" even when the AI did not pick one — unless it |
| 778 | // was tailored for an AI-built site, whose builder already chose the design (get_ai_task_ids mirrors this). |
| 779 | if ( 'sell' === $goal && ! wpcom_ai_launchpad_is_list_ai_built() ) { |
| 780 | $ai_tasks = $this->ensure_theme_task( $ai_tasks ); |
| 781 | } |
| 782 | |
| 783 | $tasks = empty( $ai_tasks ) ? array() : $this->build_tasks( $ai_tasks, false, $theme_cta, $disable_hidden_woo ); |
| 784 | |
| 785 | // The sell goal leads with the store-setup tasks; the theme task then follows them: pick the |
| 786 | // store's look once the store exists. Other goals need no injection — the gallery task is now |
| 787 | // on the menu, so the AI picks it when the site is visual. |
| 788 | if ( 'sell' === $goal ) { |
| 789 | $tasks = array_merge( $this->build_store_tasks( $woo_active ), $tasks ); |
| 790 | $tasks = $this->move_task_after( $tasks, 'site_theme_selected', 'setup_woocommerce_store' ); |
| 791 | } |
| 792 | |
| 793 | // Restore the list toward six after the visibility gate has dropped tasks (before skips, which are the |
| 794 | // user's own removals). No-op on an empty list so the wizard still runs when there is no AI output. |
| 795 | $tasks = $this->backfill_to_minimum( $tasks, $theme_cta, $disable_hidden_woo ); |
| 796 | |
| 797 | return $this->apply_skipped_tasks( $tasks ); |
| 798 | } |
| 799 | |
| 800 | /** |
| 801 | * Tops a short rendered list back up toward the six tasks the AI is asked to return. |
| 802 | * |
| 803 | * The catalog visibility gate in build_tasks() drops any task it hides on this site (e.g. add_about_page needs a |
| 804 | * page-template meta key that is absent during a REST request) with no replacement, so a gate-heavy AI pick can |
| 805 | * collapse the list to two or three cards. This backfills from a small pool of broadly-useful tasks and keeps the |
| 806 | * launch task last. Candidates are built one at a time, stopping at the target, so the tail of the pool is only |
| 807 | * evaluated when the earlier fillers were not enough — mobile_app_installed's completion check does a remote |
| 808 | * lookup while incomplete, which the common short-by-one list never has to pay for. Backfilled cards are |
| 809 | * skippable (see skip_task); a fuller, AI-ranked overflow pool is the eventual replacement. |
| 810 | * |
| 811 | * @param array $tasks The rendered task list, already gated, launch task last. |
| 812 | * @param string $theme_cta Pre-resolved themes-showcase CTA passed through to build_tasks(). |
| 813 | * @param bool $disable_hidden_woo Whether hidden commerce tasks render as a disabled preview. |
| 814 | * @return array |
| 815 | */ |
| 816 | private function backfill_to_minimum( $tasks, $theme_cta, $disable_hidden_woo ) { |
| 817 | $target = 6; |
| 818 | if ( count( $tasks ) >= $target || empty( $tasks ) ) { |
| 819 | return $tasks; |
| 820 | } |
| 821 | |
| 822 | foreach ( $this->backfill_pool() as $id => $subtitle ) { |
| 823 | if ( count( $tasks ) >= $target ) { |
| 824 | break; |
| 825 | } |
| 826 | $present = array_column( $tasks, 'id' ); |
| 827 | if ( in_array( $id, $present, true ) ) { |
| 828 | continue; |
| 829 | } |
| 830 | |
| 831 | // build_tasks() applies the same gating and remap the AI list gets, so a pool task the site |
| 832 | // hides simply does not appear. |
| 833 | $built = $this->build_tasks( |
| 834 | array( |
| 835 | array( |
| 836 | 'id' => $id, |
| 837 | 'subtitle' => $subtitle, |
| 838 | ), |
| 839 | ), |
| 840 | false, |
| 841 | $theme_cta, |
| 842 | $disable_hidden_woo |
| 843 | ); |
| 844 | if ( empty( $built ) ) { |
| 845 | continue; |
| 846 | } |
| 847 | $task = $built[0]; |
| 848 | // A filler card that is already complete offers nothing to do; better a shorter list. The remap |
| 849 | // inside build_tasks() can also land the card on an id already present — skip that too. |
| 850 | if ( ! empty( $task['completed'] ) || in_array( $task['id'], $present, true ) ) { |
| 851 | continue; |
| 852 | } |
| 853 | $tasks = $this->insert_before_launch_task( $tasks, $task ); |
| 854 | } |
| 855 | |
| 856 | return $tasks; |
| 857 | } |
| 858 | |
| 859 | /** |
| 860 | * The ordered id => subtitle pool the short-list backfill draws from: broadly-useful tasks that render on most |
| 861 | * sites and are skippable, most-broadly-applicable first. Each has a distinct card title, and none duplicate work |
| 862 | * the wizard already did (e.g. no site-title task — the wizard captured the name). Excludes tasks whose completion |
| 863 | * depends on the AI-task list (the theme/social listeners, the complete-on-click route), since a backfilled card is |
| 864 | * not on that list. skip_task() reads the ids here to keep every backfilled card skippable, so the set lives here. |
| 865 | * A list tailored for an AI-built site swaps the design and page fillers for ones the builder did not cover. |
| 866 | * |
| 867 | * @return array<string, string> |
| 868 | */ |
| 869 | private function backfill_pool() { |
| 870 | if ( wpcom_ai_launchpad_is_list_ai_built() ) { |
| 871 | $pool = array( |
| 872 | 'add_site_icon' => __( 'Add your logo or site icon.', 'jetpack-mu-wpcom' ), |
| 873 | 'domain_upsell' => __( 'Give your site its own domain.', 'jetpack-mu-wpcom' ), |
| 874 | // domain_upsell's stand-in on a plan that includes a domain, where the upsell is hidden. |
| 875 | 'domain_claim' => __( 'Claim the free domain that comes with your plan.', 'jetpack-mu-wpcom' ), |
| 876 | ); |
| 877 | } else { |
| 878 | $pool = array( |
| 879 | 'design_edited' => __( 'Make the design your own.', 'jetpack-mu-wpcom' ), |
| 880 | 'add_new_page' => __( 'Add a page your visitors will want, like About or Contact.', 'jetpack-mu-wpcom' ), |
| 881 | ); |
| 882 | } |
| 883 | |
| 884 | // Last, so the remote lookup in mobile_app_installed's completion check only runs when nothing else fits. |
| 885 | return $pool + array( |
| 886 | 'connect_social_media' => __( 'Connect your social accounts to reach more people.', 'jetpack-mu-wpcom' ), |
| 887 | 'mobile_app_installed' => __( 'Manage your site from anywhere with the Jetpack app.', 'jetpack-mu-wpcom' ), |
| 888 | ); |
| 889 | } |
| 890 | |
| 891 | /** |
| 892 | * Runs the completion pass: reports newly-completed tasks to Tracks, then latches OPTION_COMPLETED (and records |
| 893 | * the all-tasks-completed event) the first time the list is fully done. Called on every path that can finish a |
| 894 | * task (read, skip, complete-on-click, a COMPLETION_TRIGGER_OPTIONS write); the already-set check skips the |
| 895 | * rebuild once latched. |
| 896 | * |
| 897 | * @return void |
| 898 | */ |
| 899 | private function maybe_mark_completed() { |
| 900 | if ( get_option( self::OPTION_COMPLETED ) ) { |
| 901 | return; |
| 902 | } |
| 903 | |
| 904 | // No AI output means the wizard hasn't produced a list yet: nothing to report or latch. |
| 905 | if ( ! get_option( self::OPTION_AI_OUTPUT ) ) { |
| 906 | return; |
| 907 | } |
| 908 | |
| 909 | $tasks = $this->get_current_tasks(); |
| 910 | // After the rebuild, whose own status writes queue a pass too: this one covers them all. |
| 911 | unset( $this->pending_completion_blog_ids[ get_current_blog_id() ] ); |
| 912 | // An empty list is not "complete" — the wizard still needs to run. |
| 913 | if ( empty( $tasks ) ) { |
| 914 | return; |
| 915 | } |
| 916 | |
| 917 | $this->report_task_completions( $tasks ); |
| 918 | |
| 919 | foreach ( $tasks as $task ) { |
| 920 | // A skip coerces `completed` true; a disabled preview task stays incomplete until its prerequisite is met. |
| 921 | if ( empty( $task['completed'] ) ) { |
| 922 | return; |
| 923 | } |
| 924 | } |
| 925 | |
| 926 | update_option( self::OPTION_COMPLETED, true, true ); |
| 927 | // After the per-task reports above, so any task_completed reports precede it (a list finished |
| 928 | // purely by skips or born-completed tasks latches with none). |
| 929 | wpcom_ai_launchpad_record_tracks_event( |
| 930 | 'jetpack_ai_launchpad_all_tasks_completed', |
| 931 | array(), |
| 932 | array_column( $tasks, 'id' ) |
| 933 | ); |
| 934 | } |
| 935 | |
| 936 | /** |
| 937 | * Records a `task_completed` Tracks event for every rendered task that newly reads as completed, whatever |
| 938 | * completed it (client click, PHP listener, or live recomputation à la Woo/domains/memberships) — the only |
| 939 | * uniform signal is the rendered list itself, so completions are diffed on read. |
| 940 | * |
| 941 | * The already-reported ids are embedded in the existing AI-output envelope (`tracked_completed`) rather than a |
| 942 | * new option; a re-tailor rewrites the envelope, which re-baselines the set at the same moment the skip/completed |
| 943 | * options reset. PUT /tailored seeds the key with the born-completed tasks, so a pass here only ever reports |
| 944 | * user-triggered completions; an envelope persisted before the key existed gets the same silent baseline on its |
| 945 | * first pass. Skipped tasks render as completed but already emit `task_skipped`, so they are excluded (and never |
| 946 | * reported later). |
| 947 | * |
| 948 | * @param array $tasks The current rendered tasks. |
| 949 | * @return void |
| 950 | */ |
| 951 | private function report_task_completions( $tasks ) { |
| 952 | $ai_output = get_option( self::OPTION_AI_OUTPUT ); |
| 953 | if ( ! is_array( $ai_output ) ) { |
| 954 | return; |
| 955 | } |
| 956 | |
| 957 | $skipped = $this->get_skipped_task_ids(); |
| 958 | $completed = array(); |
| 959 | foreach ( $tasks as $task ) { |
| 960 | if ( ! empty( $task['completed'] ) && ! in_array( $task['id'], $skipped, true ) ) { |
| 961 | $completed[] = $task['id']; |
| 962 | } |
| 963 | } |
| 964 | |
| 965 | // null = no key yet, i.e. the baseline pass right after tailoring. Remapped like the skip overlay: a |
| 966 | // baseline recorded under a since-remapped id must keep covering the id its card renders as now, or the |
| 967 | // same completion would be re-reported once under the new id. |
| 968 | $reported = isset( $ai_output['tracked_completed'] ) && is_array( $ai_output['tracked_completed'] ) |
| 969 | ? array_values( array_unique( array_map( 'wpcom_ai_launchpad_remap_task_id', $ai_output['tracked_completed'] ) ) ) |
| 970 | : null; |
| 971 | $newly = array_values( array_diff( $completed, $reported ?? array() ) ); |
| 972 | |
| 973 | if ( null !== $reported ) { |
| 974 | if ( empty( $newly ) ) { |
| 975 | return; |
| 976 | } |
| 977 | $rendered_ids = array_column( $tasks, 'id' ); |
| 978 | foreach ( $newly as $task_id ) { |
| 979 | wpcom_ai_launchpad_record_tracks_event( |
| 980 | 'jetpack_ai_launchpad_task_completed', |
| 981 | array( 'task_id' => $task_id ), |
| 982 | $rendered_ids |
| 983 | ); |
| 984 | } |
| 985 | } |
| 986 | |
| 987 | $ai_output['tracked_completed'] = array_merge( $reported ?? array(), $newly ); |
| 988 | update_option( self::OPTION_AI_OUTPUT, $ai_output, false ); |
| 989 | } |
| 990 | |
| 991 | /** |
| 992 | * Persists the wizard input and writes the entered Name and Brief description back to blogname / blogdescription. |
| 993 | * |
| 994 | * Empty values are skipped so the wizard never blanks an existing title or tagline. |
| 995 | * |
| 996 | * @param WP_REST_Request $request Request object. |
| 997 | * @return array |
| 998 | */ |
| 999 | public function update_wizard( $request ) { |
| 1000 | $wizard = array( |
| 1001 | 'version' => 1, |
| 1002 | 'goal' => $request['goal'], |
| 1003 | 'site_name' => $request['site_name'], |
| 1004 | 'description' => $request['description'], |
| 1005 | 'locale' => $request['locale'], |
| 1006 | 'ui_locale' => $request['ui_locale'], |
| 1007 | 'generated_at' => time(), |
| 1008 | ); |
| 1009 | |
| 1010 | update_option( self::OPTION_WIZARD, $wizard, false ); |
| 1011 | |
| 1012 | if ( '' !== trim( (string) $request['site_name'] ) ) { |
| 1013 | update_option( 'blogname', $request['site_name'] ); |
| 1014 | } |
| 1015 | if ( '' !== trim( (string) $request['description'] ) ) { |
| 1016 | // Collapse the textarea brief's newlines to keep the inline-rendered tagline single-line. |
| 1017 | update_option( 'blogdescription', sanitize_text_field( $request['description'] ) ); |
| 1018 | } |
| 1019 | |
| 1020 | return array( 'wizard' => $wizard ); |
| 1021 | } |
| 1022 | |
| 1023 | /** |
| 1024 | * Validates the AI output payload against the agent output schema, wraps it, and persists it. |
| 1025 | * |
| 1026 | * @param WP_REST_Request $request Request object. |
| 1027 | * @return array|WP_Error |
| 1028 | */ |
| 1029 | public function update_tailored( $request ) { |
| 1030 | $payload = $request->get_json_params(); |
| 1031 | |
| 1032 | $validation = rest_validate_value_from_schema( $payload, $this->get_output_schema(), 'payload' ); |
| 1033 | if ( is_wp_error( $validation ) ) { |
| 1034 | return new WP_Error( 'ai_launchpad_invalid_payload', $validation->get_error_message(), array( 'status' => 422 ) ); |
| 1035 | } |
| 1036 | |
| 1037 | $last_task = end( $payload['tasks'] ); |
| 1038 | if ( ! in_array( $last_task['id'], self::LAUNCH_TASK_IDS, true ) ) { |
| 1039 | return new WP_Error( |
| 1040 | 'ai_launchpad_missing_launch_task', |
| 1041 | __( 'The last task must be a launch task.', 'jetpack-mu-wpcom' ), |
| 1042 | array( 'status' => 422 ) |
| 1043 | ); |
| 1044 | } |
| 1045 | |
| 1046 | // The AI's raw picks, captured before the unknown-id filter below so hallucinated ids stay observable. |
| 1047 | $raw_task_ids = array_column( $payload['tasks'], 'id' ); |
| 1048 | |
| 1049 | $definitions = wpcom_launchpad_get_task_definitions(); |
| 1050 | $tasks = array(); |
| 1051 | |
| 1052 | // The exclusions key off the goal the user chose, resolved through the shared helper so this and the |
| 1053 | // read path cannot disagree about which goal the site has. |
| 1054 | $excluded = self::excluded_task_ids_for_goal( wpcom_ai_launchpad_resolve_goal( $payload ) ); |
| 1055 | |
| 1056 | foreach ( $payload['tasks'] as $task ) { |
| 1057 | // Judge — and persist — the id this task will actually render as. build_tasks() remaps broken and |
| 1058 | // twinned ids on read, so checking the raw id would let a restricted task in under its other name: |
| 1059 | // `subscribers_added` is off the menu and unrestricted, yet renders as the newsletter-restricted |
| 1060 | // `import_subscribers`. The rule has to see the card, not the spelling. |
| 1061 | $task_id = wpcom_ai_launchpad_remap_task_id( $task['id'] ); |
| 1062 | |
| 1063 | if ( ! isset( $definitions[ $task_id ] ) && ! AI_Launchpad_Task_Registry::has( $task_id ) ) { |
| 1064 | continue; |
| 1065 | } |
| 1066 | |
| 1067 | // Goal-restricted tasks are dropped even if the model picked them: the menu filter is advisory |
| 1068 | // (a failed availability lookup falls back to the full menu), this is not. |
| 1069 | if ( in_array( $task_id, $excluded, true ) ) { |
| 1070 | continue; |
| 1071 | } |
| 1072 | |
| 1073 | $subtitle = $this->sanitize_subtitle( $task['subtitle'] ); |
| 1074 | if ( is_wp_error( $subtitle ) ) { |
| 1075 | return $subtitle; |
| 1076 | } |
| 1077 | |
| 1078 | $tasks[] = array( |
| 1079 | 'id' => $task_id, |
| 1080 | 'subtitle' => $subtitle, |
| 1081 | ); |
| 1082 | } |
| 1083 | |
| 1084 | // However few tasks survive (the launch task always does), keep them: the read side backfills the list. |
| 1085 | $payload['tasks'] = $tasks; |
| 1086 | |
| 1087 | $ai_output = array( |
| 1088 | 'version' => 1, |
| 1089 | 'source' => $request['source'], |
| 1090 | 'generated_at' => time(), |
| 1091 | 'ai_built' => wpcom_ai_launchpad_is_ai_built(), |
| 1092 | 'payload' => $payload, |
| 1093 | ); |
| 1094 | |
| 1095 | // Omitted rather than stored empty, so the props builder reports "none" for a write |
| 1096 | // that carried no session id (a client from before this shipped, or a direct call). |
| 1097 | if ( '' !== $request['ai_session_id'] ) { |
| 1098 | $ai_output['ai_session_id'] = $request['ai_session_id']; |
| 1099 | } |
| 1100 | |
| 1101 | update_option( self::OPTION_AI_OUTPUT, $ai_output, false ); |
| 1102 | |
| 1103 | // A fresh list must not inherit the previous one's skips or "done" flag. |
| 1104 | delete_option( self::OPTION_SKIPPED ); |
| 1105 | delete_option( self::OPTION_COMPLETED ); |
| 1106 | |
| 1107 | // Baseline the born-completed tasks now (needs the fresh options above), so completion |
| 1108 | // reporting only ever emits for completions the user actually triggers afterwards. |
| 1109 | $rendered_tasks = $this->get_current_tasks(); |
| 1110 | $baseline = array(); |
| 1111 | foreach ( $rendered_tasks as $task ) { |
| 1112 | if ( ! empty( $task['completed'] ) ) { |
| 1113 | $baseline[] = $task['id']; |
| 1114 | } |
| 1115 | } |
| 1116 | $ai_output['tracked_completed'] = $baseline; |
| 1117 | update_option( self::OPTION_AI_OUTPUT, $ai_output, false ); |
| 1118 | |
| 1119 | // After the writes, so the observed rendered list is the fresh one. |
| 1120 | $this->log_tailoring( $ai_output, $raw_task_ids, $request['duration_ms'], $request['attempts'], array_column( $rendered_tasks, 'id' ), (array) $request['validation_errors'] ); |
| 1121 | |
| 1122 | // The analytics bookkeeping stays out of responses, mirroring get_data(). |
| 1123 | unset( $ai_output['tracked_completed'] ); |
| 1124 | |
| 1125 | return array( 'ai_output' => $ai_output ); |
| 1126 | } |
| 1127 | |
| 1128 | /** |
| 1129 | * Emits the tailoring observation event to Logstash, keyed `feature: atomic_ai_launchpad`, `message: tailored` |
| 1130 | * (the public-api logstash endpoint whitelists features by their `atomic_` prefix — a bare feature name is |
| 1131 | * rejected with a 400 on the Atomic HTTP dispatch path). Best-effort: logging must never fail the tailoring write. |
| 1132 | * |
| 1133 | * @param array $ai_output The persisted AI output envelope. |
| 1134 | * @param string[] $raw_task_ids The AI's selected ids before the unknown-id filter. |
| 1135 | * @param int|null $duration_ms Client-measured tailoring duration, or null when not sent. |
| 1136 | * @param int|null $attempts Client-reported jetpack-ai-query attempt count, or null when not sent. |
| 1137 | * @param string[]|null $rendered_ids The rendered task ids, when the caller already computed them. |
| 1138 | * @param string[] $validation_errors Why each failed jetpack-ai-query attempt failed, already sanitized. |
| 1139 | * @return void |
| 1140 | */ |
| 1141 | private function log_tailoring( $ai_output, $raw_task_ids, $duration_ms = null, $attempts = null, $rendered_ids = null, $validation_errors = array() ) { |
| 1142 | try { |
| 1143 | /** |
| 1144 | * Gates the tailoring observation event sent to Logstash. Checked before the event |
| 1145 | * is built, so disabling it also skips the extra task-list rebuild the event needs. |
| 1146 | * |
| 1147 | * @param bool $enabled Whether to send the event. Default true. |
| 1148 | */ |
| 1149 | if ( ! apply_filters( 'wpcom_ai_launchpad_tailoring_log_enabled', true ) ) { |
| 1150 | return; |
| 1151 | } |
| 1152 | |
| 1153 | \Automattic\Jetpack\Jetpack_Mu_Wpcom::log2logstash( |
| 1154 | 'atomic_ai_launchpad', |
| 1155 | 'tailored', |
| 1156 | $this->tailoring_log_extra( $ai_output, $raw_task_ids, $duration_ms, $attempts, $rendered_ids, $validation_errors ) |
| 1157 | ); |
| 1158 | } catch ( \Throwable $e ) { |
| 1159 | unset( $e ); |
| 1160 | } |
| 1161 | } |
| 1162 | |
| 1163 | /** |
| 1164 | * The tailoring observation event: how the AI's output relates to what the site will actually render. |
| 1165 | * |
| 1166 | * Carries the inferred details, the AI's raw selected ids (pre-filter, so hallucinated ids are observable), the |
| 1167 | * rendered ids, and their delta — `dropped` is what the unknown-id filter and the visibility gate removed, `added` |
| 1168 | * is what synthetics and the backfill floor put in. The delta is diffed post-remap so a selected id that renders |
| 1169 | * under its working equivalent does not read as a drop plus an addition. The raw wizard title/description are |
| 1170 | * never included, and the one inferred field that echoes the user's own words near-verbatim is stripped: |
| 1171 | * `brand_name` restates the title. |
| 1172 | * |
| 1173 | * @param array $ai_output The persisted AI output envelope. |
| 1174 | * @param string[] $raw_task_ids The AI's selected ids before the unknown-id filter. |
| 1175 | * @param int|null $duration_ms Client-measured tailoring duration, or null when not sent. |
| 1176 | * @param int|null $attempts Client-reported jetpack-ai-query attempt count, or null when not sent. |
| 1177 | * @param string[]|null $rendered_ids The rendered task ids, when the caller already computed them. |
| 1178 | * @param string[] $validation_errors Why each failed jetpack-ai-query attempt failed, already sanitized. |
| 1179 | * @return array |
| 1180 | */ |
| 1181 | private function tailoring_log_extra( $ai_output, $raw_task_ids, $duration_ms = null, $attempts = null, $rendered_ids = null, $validation_errors = array() ) { |
| 1182 | // Schema-validated on the write path, so `inferred` is always present here. |
| 1183 | $inferred = $ai_output['payload']['inferred']; |
| 1184 | unset( $inferred['brand_name'] ); |
| 1185 | |
| 1186 | $rendered = $rendered_ids ?? array_column( $this->get_current_tasks(), 'id' ); |
| 1187 | $remapped = array_unique( array_map( 'wpcom_ai_launchpad_remap_task_id', $raw_task_ids ) ); |
| 1188 | |
| 1189 | $extra = array( |
| 1190 | 'source' => $ai_output['source'], |
| 1191 | 'ai_built' => ! empty( $ai_output['ai_built'] ), |
| 1192 | 'inferred' => $inferred, |
| 1193 | 'selected' => $raw_task_ids, |
| 1194 | 'rendered' => $rendered, |
| 1195 | 'dropped' => array_values( array_diff( $remapped, $rendered ) ), |
| 1196 | 'added' => array_values( array_diff( $rendered, $remapped ) ), |
| 1197 | ); |
| 1198 | |
| 1199 | // Client-measured timing, replacing the retired ai_response_received Tracks event. |
| 1200 | if ( null !== $duration_ms ) { |
| 1201 | $extra['duration_ms'] = (int) $duration_ms; |
| 1202 | } |
| 1203 | if ( null !== $attempts ) { |
| 1204 | $extra['attempts'] = (int) $attempts; |
| 1205 | } |
| 1206 | // Only when an attempt failed, so a first-try success keeps the record's usual shape. |
| 1207 | if ( ! empty( $validation_errors ) ) { |
| 1208 | $extra['validation_errors'] = array_values( $validation_errors ); |
| 1209 | } |
| 1210 | |
| 1211 | return $extra; |
| 1212 | } |
| 1213 | |
| 1214 | /** |
| 1215 | * The current user's ChatGPT and Claude MCP connections, which the wizard polls to tell when the user has added |
| 1216 | * WordPress.com to their AI tool. |
| 1217 | * |
| 1218 | * Read from wpcom's `wpcom_mcp_get_user_connections()`, newest first, or on Atomic from WordPress.com as the user, |
| 1219 | * with an error when it can't answer. Elsewhere the list is empty, so the wizard keeps waiting. |
| 1220 | * |
| 1221 | * `access_level` is the account-wide MCP access level shared by every tool (`full`, `read_only`, or null for a |
| 1222 | * fresh account or one tuned per tool), returned only once something is connected, since reading it is costly. |
| 1223 | * |
| 1224 | * @return array{connections: string[], access_level: string|null}|WP_Error |
| 1225 | */ |
| 1226 | public function get_mcp_connections() { |
| 1227 | if ( ! function_exists( 'wpcom_mcp_get_user_connections' ) ) { |
| 1228 | $remote = $this->fetch_remote_mcp_connections(); |
| 1229 | if ( null === $remote && Constants::is_true( 'IS_ATOMIC' ) ) { |
| 1230 | // An empty list would read as read-only access to a wizard already showing a connected tool. |
| 1231 | return new WP_Error( |
| 1232 | 'mcp_connections_unavailable', |
| 1233 | __( 'Your AI tool connections can’t be checked right now.', 'jetpack-mu-wpcom' ), |
| 1234 | array( 'status' => 503 ) |
| 1235 | ); |
| 1236 | } |
| 1237 | return $remote ?? array( |
| 1238 | 'connections' => array(), |
| 1239 | 'access_level' => null, |
| 1240 | ); |
| 1241 | } |
| 1242 | |
| 1243 | $connections = array(); |
| 1244 | // @phan-suppress-next-line PhanUndeclaredFunction -- wpcom-only, not yet in the wpcom stubs. |
| 1245 | foreach ( (array) wpcom_mcp_get_user_connections( get_current_user_id() ) as $connection ) { |
| 1246 | if ( ! is_array( $connection ) || ! in_array( $connection['integration'] ?? null, self::MCP_INTEGRATIONS, true ) ) { |
| 1247 | continue; |
| 1248 | } |
| 1249 | $connections[] = $connection['integration']; |
| 1250 | } |
| 1251 | |
| 1252 | $access_level = null; |
| 1253 | if ( $connections && function_exists( 'wpcom_mcp_get_user_access_level' ) ) { |
| 1254 | // @phan-suppress-next-line PhanUndeclaredFunction -- wpcom-only, not yet in the wpcom stubs. |
| 1255 | $level = wpcom_mcp_get_user_access_level( get_current_user_id() ); |
| 1256 | $access_level = is_string( $level ) ? $level : null; |
| 1257 | } |
| 1258 | |
| 1259 | return array( |
| 1260 | 'connections' => $connections, |
| 1261 | 'access_level' => $access_level, |
| 1262 | ); |
| 1263 | } |
| 1264 | |
| 1265 | /** |
| 1266 | * The current user's ChatGPT and Claude connections from WordPress.com's `/me/mcp-connections`, asked as that user |
| 1267 | * from an Atomic site. |
| 1268 | * |
| 1269 | * @return array{connections: string[], access_level: string|null}|null Null off Atomic, without a connected user, or for a |
| 1270 | * minute after WordPress.com failed to answer. |
| 1271 | */ |
| 1272 | private function fetch_remote_mcp_connections() { |
| 1273 | $user_id = get_current_user_id(); |
| 1274 | // Without a user token the client would record the failed signing as a connection error. |
| 1275 | if ( ! Constants::is_true( 'IS_ATOMIC' ) || ! ( new Connection_Manager() )->is_user_connected( $user_id ) ) { |
| 1276 | return null; |
| 1277 | } |
| 1278 | |
| 1279 | $cache_key = 'wpcom_ai_launchpad_mcp_' . $user_id; |
| 1280 | $cached = get_transient( $cache_key ); |
| 1281 | if ( is_array( $cached ) || 'unavailable' === $cached ) { |
| 1282 | return is_array( $cached ) ? $cached : null; |
| 1283 | } |
| 1284 | |
| 1285 | $response = Client::wpcom_json_api_request_as_user( |
| 1286 | '/me/mcp-connections', |
| 1287 | '2', |
| 1288 | array( |
| 1289 | 'method' => 'GET', |
| 1290 | 'timeout' => 3, |
| 1291 | ) |
| 1292 | ); |
| 1293 | $status = is_wp_error( $response ) ? 0 : (int) wp_remote_retrieve_response_code( $response ); |
| 1294 | $data = is_wp_error( $response ) ? null : json_decode( wp_remote_retrieve_body( $response ), true ); |
| 1295 | if ( 200 !== $status || ! is_array( $data ) || ! is_array( $data['connections'] ?? null ) ) { |
| 1296 | // Remembered for a minute, so page loads and checks don't keep asking a WordPress.com that can't answer. |
| 1297 | set_transient( $cache_key, 'unavailable', MINUTE_IN_SECONDS ); |
| 1298 | return null; |
| 1299 | } |
| 1300 | |
| 1301 | $connections = array_values( |
| 1302 | array_filter( |
| 1303 | $data['connections'], |
| 1304 | static function ( $integration ) { |
| 1305 | return in_array( $integration, self::MCP_INTEGRATIONS, true ); |
| 1306 | } |
| 1307 | ) |
| 1308 | ); |
| 1309 | $level = $data['access_level'] ?? null; |
| 1310 | $result = array( |
| 1311 | 'connections' => $connections, |
| 1312 | 'access_level' => $connections && is_string( $level ) ? $level : null, |
| 1313 | ); |
| 1314 | set_transient( $cache_key, $result, self::MCP_CACHE_TTL ); |
| 1315 | |
| 1316 | return $result; |
| 1317 | } |
| 1318 | |
| 1319 | /** |
| 1320 | * Sets the current user's account-wide MCP access level to full, as choosing Full access on the MCP connect |
| 1321 | * screen does: every write tool is turned on and per-tool opt-outs are cleared. |
| 1322 | * |
| 1323 | * Acts on the current user only, through wpcom's `wpcom_mcp_set_user_access_level()`, and only on a read-only |
| 1324 | * account: the wizard offers the button for no other, and a 409 keeps a since-tuned account's per-tool settings. |
| 1325 | * Where wpcom's helpers are not defined, or on any error, the wizard links to the WordPress.com MCP settings instead. |
| 1326 | * |
| 1327 | * @return array{access_level: string}|WP_Error |
| 1328 | */ |
| 1329 | public function allow_full_mcp_access() { |
| 1330 | if ( ! function_exists( 'wpcom_mcp_set_user_access_level' ) || ! function_exists( 'wpcom_mcp_get_user_access_level' ) ) { |
| 1331 | return new WP_Error( |
| 1332 | 'mcp_access_unavailable', |
| 1333 | __( 'MCP access can’t be changed here.', 'jetpack-mu-wpcom' ), |
| 1334 | array( 'status' => 501 ) |
| 1335 | ); |
| 1336 | } |
| 1337 | |
| 1338 | $user_id = get_current_user_id(); |
| 1339 | // @phan-suppress-next-line PhanUndeclaredFunction -- wpcom-only, not yet in the wpcom stubs. |
| 1340 | if ( 'read_only' !== wpcom_mcp_get_user_access_level( $user_id ) ) { |
| 1341 | return new WP_Error( |
| 1342 | 'mcp_access_not_read_only', |
| 1343 | __( 'MCP access isn’t read only, so it can’t be changed here.', 'jetpack-mu-wpcom' ), |
| 1344 | array( 'status' => 409 ) |
| 1345 | ); |
| 1346 | } |
| 1347 | |
| 1348 | // @phan-suppress-next-line PhanUndeclaredFunction -- wpcom-only, not yet in the wpcom stubs. |
| 1349 | $result = wpcom_mcp_set_user_access_level( $user_id, 'full' ); |
| 1350 | if ( is_wp_error( $result ) ) { |
| 1351 | $data = $result->get_error_data(); |
| 1352 | if ( ! is_array( $data ) || ! isset( $data['status'] ) ) { |
| 1353 | $result->add_data( array( 'status' => 500 ) ); |
| 1354 | } |
| 1355 | return $result; |
| 1356 | } |
| 1357 | |
| 1358 | return array( 'access_level' => 'full' ); |
| 1359 | } |
| 1360 | |
| 1361 | /** |
| 1362 | * Marks an acknowledgment task complete when the user clicks its CTA, since these tasks have no wp-admin signal. |
| 1363 | * |
| 1364 | * Restricted to the COMPLETE_ON_CLICK_TASK_IDS allowlist and to tasks on the site's AI-selected list. |
| 1365 | * |
| 1366 | * @param WP_REST_Request $request Request object. |
| 1367 | * @return array|WP_Error |
| 1368 | */ |
| 1369 | public function complete_task( $request ) { |
| 1370 | $task_id = $request['task_id']; |
| 1371 | |
| 1372 | if ( ! in_array( $task_id, self::COMPLETE_ON_CLICK_TASK_IDS, true ) ) { |
| 1373 | return new WP_Error( |
| 1374 | 'ai_launchpad_task_not_completable', |
| 1375 | __( 'This task cannot be completed this way.', 'jetpack-mu-wpcom' ), |
| 1376 | array( 'status' => 400 ) |
| 1377 | ); |
| 1378 | } |
| 1379 | |
| 1380 | // Only tasks the AI put on this site's list may be completed. |
| 1381 | if ( ! in_array( $task_id, wpcom_ai_launchpad_get_ai_task_ids(), true ) ) { |
| 1382 | return new WP_Error( |
| 1383 | 'ai_launchpad_task_not_selected', |
| 1384 | __( 'This task is not on the tailored list.', 'jetpack-mu-wpcom' ), |
| 1385 | array( 'status' => 404 ) |
| 1386 | ); |
| 1387 | } |
| 1388 | |
| 1389 | // The registry's ids are not in the shared catalog, and wpcom_mark_launchpad_task_complete() drops |
| 1390 | // what the catalog does not define, so those go through the registry's own write. |
| 1391 | if ( AI_Launchpad_Task_Registry::has( $task_id ) ) { |
| 1392 | AI_Launchpad_Task_Registry::mark_complete( $task_id ); |
| 1393 | } else { |
| 1394 | wpcom_mark_launchpad_task_complete( $task_id ); |
| 1395 | } |
| 1396 | |
| 1397 | // Latch now so completing the last task hides the menu on the next page load, not just on the next read. |
| 1398 | $this->maybe_mark_completed(); |
| 1399 | |
| 1400 | return array( |
| 1401 | 'completed' => true, |
| 1402 | 'task_id' => $task_id, |
| 1403 | 'list_completed' => (bool) get_option( self::OPTION_COMPLETED ), |
| 1404 | ); |
| 1405 | } |
| 1406 | |
| 1407 | /** |
| 1408 | * Marks a task as skipped: it renders (and counts) as completed without its real completion signal ever firing. |
| 1409 | * |
| 1410 | * Restricted to tasks on the site's AI-selected list, the synthetic ids the list adds itself, and the short-list |
| 1411 | * backfill pool — so every rendered card (AI, synthetic, or filler) is skippable. Persisted separately from |
| 1412 | * `launchpad_checklist_tasks_statuses` because several catalog tasks recompute completion live (memberships, woo, |
| 1413 | * domains) and would ignore a status write; the skip set is overlaid on read instead. |
| 1414 | * |
| 1415 | * @param WP_REST_Request $request Request object. |
| 1416 | * @return array|WP_Error |
| 1417 | */ |
| 1418 | public function skip_task( $request ) { |
| 1419 | $task_id = $request['task_id']; |
| 1420 | |
| 1421 | $skippable = array_merge( wpcom_ai_launchpad_get_ai_task_ids(), self::SYNTHETIC_TASK_IDS, array_keys( $this->backfill_pool() ) ); |
| 1422 | if ( ! in_array( $task_id, $skippable, true ) ) { |
| 1423 | return new WP_Error( |
| 1424 | 'ai_launchpad_task_not_skippable', |
| 1425 | __( 'This task is not on the tailored list.', 'jetpack-mu-wpcom' ), |
| 1426 | array( 'status' => 404 ) |
| 1427 | ); |
| 1428 | } |
| 1429 | |
| 1430 | $skipped = $this->get_skipped_task_ids(); |
| 1431 | if ( ! in_array( $task_id, $skipped, true ) ) { |
| 1432 | $skipped[] = $task_id; |
| 1433 | update_option( self::OPTION_SKIPPED, $skipped, false ); |
| 1434 | } |
| 1435 | |
| 1436 | // Latch now so skipping the last task hides the menu on the next page load, not just on the next read. |
| 1437 | $this->maybe_mark_completed(); |
| 1438 | |
| 1439 | return array( |
| 1440 | 'skipped' => true, |
| 1441 | 'task_id' => $task_id, |
| 1442 | 'list_completed' => (bool) get_option( self::OPTION_COMPLETED ), |
| 1443 | ); |
| 1444 | } |
| 1445 | |
| 1446 | /** |
| 1447 | * Deletes the AI output and marks the AI Launchpad as dismissed. |
| 1448 | * |
| 1449 | * @return array |
| 1450 | */ |
| 1451 | public function dismiss() { |
| 1452 | delete_option( self::OPTION_AI_OUTPUT ); |
| 1453 | delete_option( self::OPTION_SKIPPED ); |
| 1454 | delete_option( self::OPTION_COMPLETED ); |
| 1455 | update_option( self::OPTION_DISMISSED, true, true ); |
| 1456 | |
| 1457 | return array( 'dismissed' => true ); |
| 1458 | } |
| 1459 | |
| 1460 | /** |
| 1461 | * The persisted skipped task ids, always as a clean string array, remapped onto the |
| 1462 | * ids the launchpad renders — a skip recorded under a task's raw id before that id |
| 1463 | * was remapped must keep applying to the card it renders as now. |
| 1464 | * |
| 1465 | * @return string[] |
| 1466 | */ |
| 1467 | private function get_skipped_task_ids() { |
| 1468 | $skipped = get_option( self::OPTION_SKIPPED, array() ); |
| 1469 | if ( ! is_array( $skipped ) ) { |
| 1470 | return array(); |
| 1471 | } |
| 1472 | |
| 1473 | $skipped = array_map( 'wpcom_ai_launchpad_remap_task_id', array_filter( $skipped, 'is_string' ) ); |
| 1474 | |
| 1475 | return array_values( array_unique( $skipped ) ); |
| 1476 | } |
| 1477 | |
| 1478 | /** |
| 1479 | * Overlays the persisted skips onto the enriched tasks: a skipped task carries `skipped: true` and is coerced to |
| 1480 | * completed, so progress, auto-expand, and reloads all treat it as done (a skip must never pop back open). |
| 1481 | * |
| 1482 | * @param array $tasks The enriched task list. |
| 1483 | * @return array |
| 1484 | */ |
| 1485 | private function apply_skipped_tasks( $tasks ) { |
| 1486 | $skipped = $this->get_skipped_task_ids(); |
| 1487 | |
| 1488 | foreach ( $tasks as &$task ) { |
| 1489 | $task['skipped'] = in_array( $task['id'], $skipped, true ); |
| 1490 | if ( $task['skipped'] ) { |
| 1491 | $task['completed'] = true; |
| 1492 | } |
| 1493 | } |
| 1494 | unset( $task ); |
| 1495 | |
| 1496 | return $tasks; |
| 1497 | } |
| 1498 | |
| 1499 | /** |
| 1500 | * Strips HTML from a subtitle and rejects URLs and template syntax. |
| 1501 | * |
| 1502 | * @param string $subtitle The raw subtitle. |
| 1503 | * @return string|WP_Error The sanitized subtitle, or an error. |
| 1504 | */ |
| 1505 | private function sanitize_subtitle( $subtitle ) { |
| 1506 | $subtitle = trim( wp_strip_all_tags( $subtitle, true ) ); |
| 1507 | |
| 1508 | if ( '' === $subtitle ) { |
| 1509 | return new WP_Error( |
| 1510 | 'ai_launchpad_invalid_subtitle', |
| 1511 | __( 'Task subtitles must contain text.', 'jetpack-mu-wpcom' ), |
| 1512 | array( 'status' => 422 ) |
| 1513 | ); |
| 1514 | } |
| 1515 | |
| 1516 | if ( preg_match( '#https?://#i', $subtitle ) ) { |
| 1517 | return new WP_Error( |
| 1518 | 'ai_launchpad_subtitle_contains_url', |
| 1519 | __( 'Task subtitles must not contain URLs.', 'jetpack-mu-wpcom' ), |
| 1520 | array( 'status' => 422 ) |
| 1521 | ); |
| 1522 | } |
| 1523 | |
| 1524 | if ( str_contains( $subtitle, '{{' ) || str_contains( $subtitle, '[[' ) ) { |
| 1525 | return new WP_Error( |
| 1526 | 'ai_launchpad_subtitle_contains_template', |
| 1527 | __( 'Task subtitles must not contain template syntax.', 'jetpack-mu-wpcom' ), |
| 1528 | array( 'status' => 422 ) |
| 1529 | ); |
| 1530 | } |
| 1531 | |
| 1532 | return mb_substr( $subtitle, 0, 200 ); |
| 1533 | } |
| 1534 | |
| 1535 | /** |
| 1536 | * Read endpoint backing the client's availability-aware tailoring: the task ids that will render for the given |
| 1537 | * goal. Fetched before the AI call, so the prompt offers only renderable tasks. |
| 1538 | * |
| 1539 | * @param WP_REST_Request $request Request object. |
| 1540 | * @return array |
| 1541 | */ |
| 1542 | public function get_available_tasks( $request ) { |
| 1543 | $ids = $this->available_task_ids( (string) $request['goal'] ); |
| 1544 | return array( |
| 1545 | 'available_task_ids' => $ids['actionable'], |
| 1546 | 'renderable_task_ids' => $ids['renderable'], |
| 1547 | ); |
| 1548 | } |
| 1549 | |
| 1550 | /** |
| 1551 | * The task ids that must not be offered to, or accepted from, the model for a given goal. |
| 1552 | * |
| 1553 | * The two maps read in opposite directions, and an unknown or empty goal matches neither: every |
| 1554 | * GOAL_RESTRICTED_TASK_IDS entry is excluded (it never got the goal it requires), while every |
| 1555 | * GOAL_EXCLUDED_TASK_IDS entry is allowed (it never hit the goal that excludes it). |
| 1556 | * On an AI-built site it also excludes AI_BUILT_EXCLUDED_TASK_IDS, whatever the goal. |
| 1557 | * |
| 1558 | * @param string $goal The selected goal. |
| 1559 | * @return string[] |
| 1560 | */ |
| 1561 | public static function excluded_task_ids_for_goal( $goal ) { |
| 1562 | $excluded = array(); |
| 1563 | |
| 1564 | foreach ( self::GOAL_RESTRICTED_TASK_IDS as $task_id => $required_goal ) { |
| 1565 | if ( $goal !== $required_goal ) { |
| 1566 | $excluded[] = $task_id; |
| 1567 | } |
| 1568 | } |
| 1569 | |
| 1570 | foreach ( self::GOAL_EXCLUDED_TASK_IDS as $task_id => $excluded_goal ) { |
| 1571 | if ( $goal === $excluded_goal ) { |
| 1572 | $excluded[] = $task_id; |
| 1573 | } |
| 1574 | } |
| 1575 | |
| 1576 | // Tailoring follows the live spec; a saved list follows its own flag (is_list_ai_built). |
| 1577 | if ( wpcom_ai_launchpad_is_ai_built() ) { |
| 1578 | $excluded = array_merge( $excluded, self::AI_BUILT_EXCLUDED_TASK_IDS ); |
| 1579 | } |
| 1580 | |
| 1581 | return $excluded; |
| 1582 | } |
| 1583 | |
| 1584 | /** |
| 1585 | * The task ids that will actually render on this site for the given goal — the menu tailoring should choose from. |
| 1586 | * |
| 1587 | * Built by running the whole catalog through the real gate (visibility + force-visible overrides, and the sell |
| 1588 | * goal's woo-preview mode), so a task the AI could pick but the site would drop is never offered. `actionable` |
| 1589 | * additionally excludes tasks that are already complete — they leave nothing to do — except the launch tasks, |
| 1590 | * which the output contract requires last even on a site that already launched. `renderable` keeps the completed |
| 1591 | * ones: the client falls back to it when completion leaves too few actionable tasks to fill a valid list. The |
| 1592 | * client intersects these with its own TASK_MENU. Computed once per wizard submit. |
| 1593 | * |
| 1594 | * The AI Launchpad's own tasks are appended separately, since they are not catalog entries and the catalog |
| 1595 | * sweep cannot find them. They run their own gate on the way in: a registry definition may declare an |
| 1596 | * `is_visible` callable, and one that fails it is withheld from both lists here exactly as a catalog task |
| 1597 | * failing wpcom_launchpad_checklists()->is_visible() is. A definition without one is visible everywhere — |
| 1598 | * the gallery's shape, since it asks nothing of the site. |
| 1599 | * |
| 1600 | * @param string $goal The inferred/selected goal. |
| 1601 | * @return array{renderable: string[], actionable: string[]} |
| 1602 | */ |
| 1603 | private function available_task_ids( $goal ) { |
| 1604 | if ( ! function_exists( 'is_plugin_active' ) ) { |
| 1605 | require_once ABSPATH . 'wp-admin/includes/plugin.php'; |
| 1606 | } |
| 1607 | // Sell keeps the commerce tasks as a disabled preview until WooCommerce is active, so they count as available. |
| 1608 | $disable_hidden_woo = 'sell' === $goal && ! is_plugin_active( 'woocommerce/woocommerce.php' ); |
| 1609 | |
| 1610 | $tasks = $this->build_all_catalog_tasks( false, $disable_hidden_woo ); |
| 1611 | |
| 1612 | $actionable = array_filter( |
| 1613 | $tasks, |
| 1614 | static function ( $task ) { |
| 1615 | return ! $task['completed'] || in_array( $task['id'], self::LAUNCH_TASK_IDS, true ); |
| 1616 | } |
| 1617 | ); |
| 1618 | |
| 1619 | $excluded = self::excluded_task_ids_for_goal( $goal ); |
| 1620 | |
| 1621 | // The registry's tasks are not in the catalog, so the sweep above cannot see them. Offer every registry |
| 1622 | // task that this site can render and that is not already complete; a completed one still renders, so it |
| 1623 | // stays on the renderable list the client relaxes to. |
| 1624 | $registry_renderable = array_values( |
| 1625 | array_filter( |
| 1626 | AI_Launchpad_Task_Registry::task_ids(), |
| 1627 | static function ( $task_id ) { |
| 1628 | return AI_Launchpad_Task_Registry::is_visible( $task_id ); |
| 1629 | } |
| 1630 | ) |
| 1631 | ); |
| 1632 | $registry_actionable = array_values( |
| 1633 | array_filter( |
| 1634 | $registry_renderable, |
| 1635 | static function ( $task_id ) { |
| 1636 | return ! AI_Launchpad_Task_Registry::is_complete( $task_id ); |
| 1637 | } |
| 1638 | ) |
| 1639 | ); |
| 1640 | |
| 1641 | // array_unique guards a future registry id that shadows a catalog one: the endpoint would otherwise |
| 1642 | // advertise it twice. |
| 1643 | $renderable = array_unique( array_merge( array_column( $tasks, 'id' ), $registry_renderable ) ); |
| 1644 | $actionable = array_unique( array_merge( array_column( $actionable, 'id' ), $registry_actionable ) ); |
| 1645 | |
| 1646 | return array( |
| 1647 | 'renderable' => array_values( array_diff( $renderable, $excluded ) ), |
| 1648 | 'actionable' => array_values( array_diff( $actionable, $excluded ) ), |
| 1649 | ); |
| 1650 | } |
| 1651 | |
| 1652 | /** |
| 1653 | * Records the builder's input as the wizard answers, or reuses an existing answer's goal. |
| 1654 | * |
| 1655 | * The builder's name and description are always used; blogname and blogdescription are never touched. |
| 1656 | * |
| 1657 | * @param array $builder_input The builder's input. |
| 1658 | * @return array The input to tailor with. |
| 1659 | */ |
| 1660 | private function adopt_builder_input( $builder_input ) { |
| 1661 | $wizard = get_option( self::OPTION_WIZARD ); |
| 1662 | if ( false === $wizard ) { |
| 1663 | $wizard = array( |
| 1664 | 'version' => 1, |
| 1665 | 'goal' => $builder_input['goal'], |
| 1666 | 'site_name' => $builder_input['site_name'], |
| 1667 | 'description' => $builder_input['description'], |
| 1668 | 'locale' => wpcom_ai_launchpad_site_locale(), |
| 1669 | 'ui_locale' => determine_locale(), |
| 1670 | 'generated_at' => time(), |
| 1671 | 'source' => 'ai_builder', |
| 1672 | ); |
| 1673 | add_option( self::OPTION_WIZARD, $wizard, '', false ); |
| 1674 | } |
| 1675 | |
| 1676 | // update_tailored() enforces the wizard's goal, so the prompt must use it too. |
| 1677 | if ( is_array( $wizard ) && isset( $wizard['goal'] ) && in_array( $wizard['goal'], self::GOALS, true ) ) { |
| 1678 | $builder_input['goal'] = $wizard['goal']; |
| 1679 | } |
| 1680 | |
| 1681 | return $builder_input; |
| 1682 | } |
| 1683 | |
| 1684 | /** |
| 1685 | * Builds the enriched task list for every catalog task (backs `?all_tasks=1` when the gate is bypassed, and |
| 1686 | * available_task_ids() when it is not). |
| 1687 | * |
| 1688 | * Each task is enriched in isolation so one that can't be built is skipped rather than breaking the whole view. |
| 1689 | * |
| 1690 | * @param bool $bypass_visibility Whether to skip the catalog visibility gate (the testing view does). |
| 1691 | * @param bool $disable_hidden_woo Whether hidden commerce tasks render as a disabled preview instead of dropping. |
| 1692 | * @return array |
| 1693 | */ |
| 1694 | private function build_all_catalog_tasks( $bypass_visibility = true, $disable_hidden_woo = false ) { |
| 1695 | $built = array(); |
| 1696 | $seen_ids = array(); |
| 1697 | foreach ( array_keys( wpcom_launchpad_get_task_definitions() ) as $task_id ) { |
| 1698 | try { |
| 1699 | $one = $this->build_tasks( |
| 1700 | array( |
| 1701 | array( |
| 1702 | 'id' => $task_id, |
| 1703 | 'subtitle' => $task_id, |
| 1704 | ), |
| 1705 | ), |
| 1706 | $bypass_visibility, |
| 1707 | null, |
| 1708 | $disable_hidden_woo |
| 1709 | ); |
| 1710 | } catch ( \Throwable $e ) { |
| 1711 | continue; |
| 1712 | } |
| 1713 | // build_tasks runs per id here, so its own dedup can't see this collision: the catalog holds both |
| 1714 | // `woo_launch_site` and `site_launched`, and the former is remapped onto the latter. Keep the first. |
| 1715 | $card = $one[0] ?? null; |
| 1716 | if ( null === $card || isset( $seen_ids[ $card['id'] ] ) ) { |
| 1717 | continue; |
| 1718 | } |
| 1719 | $seen_ids[ $card['id'] ] = true; |
| 1720 | $built[] = $card; |
| 1721 | } |
| 1722 | return $built; |
| 1723 | } |
| 1724 | |
| 1725 | /** |
| 1726 | * Enriches the persisted tasks with title, completion state, and CTA path from the catalog. |
| 1727 | * |
| 1728 | * @param array $tasks The persisted `payload.tasks` array. |
| 1729 | * @param bool $bypass_visibility Skip the catalog visibility gate (for the all-tasks testing view). |
| 1730 | * @param string|null $theme_cta The resolved themes-showcase path for the theme-picker tasks, or |
| 1731 | * null to keep their default CTAs. |
| 1732 | * @param bool $disable_hidden_woo Keep WOO_TASK_IDS that fail the visibility gate as disabled preview |
| 1733 | * cards instead of dropping them (sell goal while WooCommerce is inactive). |
| 1734 | * @return array |
| 1735 | */ |
| 1736 | private function build_tasks( $tasks, $bypass_visibility = false, $theme_cta = null, $disable_hidden_woo = false ) { |
| 1737 | $definitions = wpcom_launchpad_get_task_definitions(); |
| 1738 | $built = array(); |
| 1739 | $seen_ids = array(); |
| 1740 | |
| 1741 | // Some catalog visibility callbacks call is_plugin_active(), which is not loaded during a REST request. |
| 1742 | if ( ! function_exists( 'is_plugin_active' ) ) { |
| 1743 | require_once ABSPATH . 'wp-admin/includes/plugin.php'; |
| 1744 | } |
| 1745 | |
| 1746 | $is_private_site = $this->is_private_site(); |
| 1747 | $launched_at_creation = $this->was_launched_at_creation(); |
| 1748 | |
| 1749 | foreach ( $tasks as $task ) { |
| 1750 | if ( ! is_array( $task ) || ! isset( $task['id'] ) || ! isset( $task['subtitle'] ) ) { |
| 1751 | continue; |
| 1752 | } |
| 1753 | |
| 1754 | // Broken/meaningless-in-context ids render as their working equivalent (see the helper for the why). |
| 1755 | $task['id'] = wpcom_ai_launchpad_remap_task_id( $task['id'] ); |
| 1756 | |
| 1757 | // One card per id — the client keys cards by id. The remap above can collide with the target id already |
| 1758 | // being present (notably the ?all_tasks=1 view, which enumerates every catalog id), so collapse any |
| 1759 | // repeat to the first occurrence. |
| 1760 | if ( isset( $seen_ids[ $task['id'] ] ) ) { |
| 1761 | continue; |
| 1762 | } |
| 1763 | |
| 1764 | // Tasks the AI Launchpad owns are built from its own registry: the shared catalog does not |
| 1765 | // define them, and routing them through wpcom_launchpad_checklists() would mean relying on |
| 1766 | // the catalog accepting entries it never registered. |
| 1767 | if ( AI_Launchpad_Task_Registry::has( $task['id'] ) ) { |
| 1768 | // The registry's own visibility gate, filtered on read for the same reason as the catalog's |
| 1769 | // below: a persisted list outlives the site state it was tailored for, so a task whose |
| 1770 | // precondition has since gone must stop rendering rather than offer a CTA that leads nowhere. |
| 1771 | if ( ! $bypass_visibility && ! AI_Launchpad_Task_Registry::is_visible( $task['id'] ) ) { |
| 1772 | continue; |
| 1773 | } |
| 1774 | |
| 1775 | $card = AI_Launchpad_Task_Registry::build( $task['id'], (string) $task['subtitle'] ); |
| 1776 | if ( null !== $card ) { |
| 1777 | $seen_ids[ $task['id'] ] = true; |
| 1778 | $built[] = $card; |
| 1779 | } |
| 1780 | continue; |
| 1781 | } |
| 1782 | |
| 1783 | if ( ! isset( $definitions[ $task['id'] ] ) ) { |
| 1784 | continue; |
| 1785 | } |
| 1786 | |
| 1787 | // The Jetpack Social tasks point at an admin page wpcom doesn't load on a private site, so hide them there. |
| 1788 | if ( $is_private_site && in_array( $task['id'], self::SOCIAL_PAGE_TASK_IDS, true ) ) { |
| 1789 | continue; |
| 1790 | } |
| 1791 | |
| 1792 | $definition = $definitions[ $task['id'] ]; |
| 1793 | $definition['id'] = $task['id']; |
| 1794 | $disabled = false; |
| 1795 | |
| 1796 | // Honor the catalog's own visibility gate: a task the catalog would hide here must not render, since its |
| 1797 | // CTA would 404 and it could never complete. Filtered on read so the deterministic fallback stays usable. |
| 1798 | if ( |
| 1799 | ! $bypass_visibility |
| 1800 | && ! in_array( $task['id'], self::FORCE_VISIBLE_TASK_IDS, true ) |
| 1801 | && ! wpcom_launchpad_checklists()->is_visible( $definition ) |
| 1802 | ) { |
| 1803 | // On a sell site without WooCommerce, keep the commerce tasks as a disabled preview of the store |
| 1804 | // roadmap rather than dropping them and collapsing the list. Everything else stays hidden. |
| 1805 | if ( $disable_hidden_woo && in_array( $task['id'], self::WOO_TASK_IDS, true ) ) { |
| 1806 | $disabled = true; |
| 1807 | } else { |
| 1808 | continue; |
| 1809 | } |
| 1810 | } |
| 1811 | |
| 1812 | if ( $disabled ) { |
| 1813 | // A disabled preview always renders as the locked card: never resolve its completion (the woo |
| 1814 | // completion callback marks the task complete as a side effect, which must not fire on a read) and |
| 1815 | // never resolve a CTA path (it has no reachable action). |
| 1816 | $completed = false; |
| 1817 | $calypso_path = null; |
| 1818 | } else { |
| 1819 | // The membership tasks' catalog callbacks are always false on Atomic; recompute from local signals. |
| 1820 | $completed = AI_Launchpad_Memberships::has_override( $task['id'] ) |
| 1821 | ? AI_Launchpad_Memberships::is_task_complete( $task['id'] ) |
| 1822 | : wpcom_launchpad_checklists()->is_task_complete( $definition ); |
| 1823 | |
| 1824 | // The catalog's launch tasks wait for `launch-status` to become `launched`, which never happens on a |
| 1825 | // site that was launched from the start. |
| 1826 | if ( $launched_at_creation && in_array( $task['id'], self::LAUNCH_TASK_IDS, true ) ) { |
| 1827 | $completed = true; |
| 1828 | } |
| 1829 | |
| 1830 | // The theme-picker task points at the showcase pre-filtered for the site (Store category on sell, |
| 1831 | // the AI's inferred category elsewhere) instead of plain themes.php. The legacy design_selected/ |
| 1832 | // design_completed ids consolidate onto site_theme_selected via wpcom_ai_launchpad_remap_task_id(). |
| 1833 | $theme_showcase_path = 'site_theme_selected' === $task['id'] ? $theme_cta : null; |
| 1834 | $cta_override = $this->get_cta_override( $task['id'] ); |
| 1835 | if ( null !== $theme_showcase_path ) { |
| 1836 | $calypso_path = $theme_showcase_path; |
| 1837 | } elseif ( null !== $cta_override ) { |
| 1838 | $calypso_path = $cta_override; |
| 1839 | } else { |
| 1840 | $calypso_path = wpcom_launchpad_checklists()->load_calypso_path( $definition ); |
| 1841 | } |
| 1842 | |
| 1843 | // Simple sites have no reachable wp-admin plugins screen; route any plugin-screen CTA to Calypso. |
| 1844 | $calypso_path = wpcom_ai_launchpad_to_simple_plugins_path( $calypso_path ); |
| 1845 | } |
| 1846 | |
| 1847 | $title = isset( $definition['get_title'] ) ? $definition['get_title']() : ''; |
| 1848 | $in_progress = false; |
| 1849 | |
| 1850 | // A saved-but-unpublished draft (found by marker meta) puts a site-editor task "in progress": reopen that |
| 1851 | // draft instead of creating a new one, and surface the drafts icon + a "Continue…" prompt in the card. |
| 1852 | if ( ! $completed && ! $disabled ) { |
| 1853 | $draft_url = $this->get_in_progress_draft_url( $task['id'] ); |
| 1854 | if ( null !== $draft_url ) { |
| 1855 | $in_progress = true; |
| 1856 | $calypso_path = $draft_url; |
| 1857 | } |
| 1858 | } |
| 1859 | |
| 1860 | // Title follows our precise in-progress signal so it, the icon, and the CTA agree. |
| 1861 | $title = $this->get_task_title( $task['id'], $in_progress, $title ); |
| 1862 | |
| 1863 | $seen_ids[ $task['id'] ] = true; |
| 1864 | $built[] = array( |
| 1865 | 'id' => $task['id'], |
| 1866 | 'subtitle' => $task['subtitle'], |
| 1867 | 'title' => $title, |
| 1868 | 'completed' => $completed, |
| 1869 | 'in_progress' => $in_progress, |
| 1870 | 'disabled' => $disabled, |
| 1871 | 'calypso_path' => $calypso_path, |
| 1872 | ); |
| 1873 | } |
| 1874 | |
| 1875 | return $built; |
| 1876 | } |
| 1877 | |
| 1878 | /** |
| 1879 | * The wp-admin CTA destination the AI Launchpad substitutes for a task's catalog path, or null to keep the catalog's. |
| 1880 | * |
| 1881 | * Static repoints live in CTA_OVERRIDES; `add_subscribe_block` is resolved here because its destination depends on |
| 1882 | * the active theme: the Site Editor is where a block theme adds the Subscribe block to a template (the action its |
| 1883 | * completion listener watches), and the block-based widget editor is the closest equivalent on a classic theme |
| 1884 | * (normally unreachable — the task's catalog visibility is FSE-only — but the theme can change after tailoring). |
| 1885 | * |
| 1886 | * @param string $task_id The catalog task id. |
| 1887 | * @return string|null |
| 1888 | */ |
| 1889 | private function get_cta_override( $task_id ) { |
| 1890 | if ( 'add_subscribe_block' === $task_id ) { |
| 1891 | return admin_url( wp_is_block_theme() ? 'site-editor.php' : 'widgets.php' ); |
| 1892 | } |
| 1893 | |
| 1894 | if ( isset( self::CTA_OVERRIDES[ $task_id ] ) ) { |
| 1895 | return admin_url( self::CTA_OVERRIDES[ $task_id ] ); |
| 1896 | } |
| 1897 | |
| 1898 | return null; |
| 1899 | } |
| 1900 | |
| 1901 | /** |
| 1902 | * The theme-showcase subject-category slugs (the `subject` taxonomy from /rest/v1.2/theme-filters). |
| 1903 | * Every category carries free themes, unlike free-text search, which surfaces mostly paid results. |
| 1904 | */ |
| 1905 | const THEME_CATEGORIES = array( |
| 1906 | 'blog', |
| 1907 | 'portfolio', |
| 1908 | 'business', |
| 1909 | 'store', |
| 1910 | 'art-design', |
| 1911 | 'about', |
| 1912 | 'real-estate', |
| 1913 | 'health-wellness', |
| 1914 | 'authors-writers', |
| 1915 | 'newsletter', |
| 1916 | 'education', |
| 1917 | 'magazine', |
| 1918 | 'music', |
| 1919 | 'restaurant', |
| 1920 | 'travel-lifestyle', |
| 1921 | 'fashion-beauty', |
| 1922 | 'community-non-profit', |
| 1923 | 'podcast', |
| 1924 | 'entertainment', |
| 1925 | ); |
| 1926 | |
| 1927 | /** |
| 1928 | * The wordpress.com themes-showcase path the theme-picker tasks should point at. |
| 1929 | * |
| 1930 | * Sell sites always land on the showcase's Store category so shop-ready templates lead; other goals get the |
| 1931 | * showcase pre-filtered by the AI's inferred category, re-checked against the allowlist since the envelope is |
| 1932 | * stored data. Without a valid category the plain showcase is returned (never null: the catalog CTA can resolve |
| 1933 | * to wp-admin's themes.php, which skips the showcase). The client's `toNavigableUrl` resolves the relative path |
| 1934 | * against wordpress.com. |
| 1935 | * |
| 1936 | * @param string $goal The inferred goal. |
| 1937 | * @param string $category The AI's inferred theme_category slug. |
| 1938 | * @return string |
| 1939 | */ |
| 1940 | private function get_themes_showcase_path( $goal, $category ) { |
| 1941 | if ( 'sell' === $goal ) { |
| 1942 | $category = 'store'; |
| 1943 | } |
| 1944 | |
| 1945 | if ( ! in_array( $category, self::THEME_CATEGORIES, true ) ) { |
| 1946 | return '/themes/' . rawurlencode( wpcom_get_site_slug() ); |
| 1947 | } |
| 1948 | |
| 1949 | return '/themes/filter/' . $category . '/' . rawurlencode( wpcom_get_site_slug() ); |
| 1950 | } |
| 1951 | |
| 1952 | /** |
| 1953 | * Ensures the persisted task list contains the theme-picker task, appending `site_theme_selected` when no |
| 1954 | * task already resolves to it. A design task that remaps onto it (via wpcom_ai_launchpad_remap_task_id) |
| 1955 | * counts as present, so a theme card is never duplicated. |
| 1956 | * |
| 1957 | * @param array $tasks The persisted `payload.tasks` array. |
| 1958 | * @return array |
| 1959 | */ |
| 1960 | private function ensure_theme_task( $tasks ) { |
| 1961 | foreach ( $tasks as $task ) { |
| 1962 | if ( is_array( $task ) && isset( $task['id'] ) && is_string( $task['id'] ) |
| 1963 | && 'site_theme_selected' === wpcom_ai_launchpad_remap_task_id( $task['id'] ) ) { |
| 1964 | return $tasks; |
| 1965 | } |
| 1966 | } |
| 1967 | |
| 1968 | $tasks[] = array( |
| 1969 | 'id' => 'site_theme_selected', |
| 1970 | 'subtitle' => __( 'Choose a theme that fits your store.', 'jetpack-mu-wpcom' ), |
| 1971 | ); |
| 1972 | |
| 1973 | return $tasks; |
| 1974 | } |
| 1975 | |
| 1976 | /** |
| 1977 | * Moves the task with the given id to immediately after another task. The list is returned unchanged |
| 1978 | * unless both ids are present. |
| 1979 | * |
| 1980 | * @param array $tasks The built task list. |
| 1981 | * @param string $move_id The id of the task to move. |
| 1982 | * @param string $after_id The id of the task to place it after. |
| 1983 | * @return array |
| 1984 | */ |
| 1985 | private function move_task_after( $tasks, $move_id, $after_id ) { |
| 1986 | $ids = array_column( $tasks, 'id' ); |
| 1987 | $from = array_search( $move_id, $ids, true ); |
| 1988 | if ( false === $from || false === array_search( $after_id, $ids, true ) ) { |
| 1989 | return $tasks; |
| 1990 | } |
| 1991 | |
| 1992 | $moved = array_splice( $tasks, $from, 1 ); |
| 1993 | // Recompute the anchor: extracting an earlier element shifts it left by one. |
| 1994 | $to = array_search( $after_id, array_column( $tasks, 'id' ), true ); |
| 1995 | array_splice( $tasks, $to + 1, 0, $moved ); |
| 1996 | |
| 1997 | return $tasks; |
| 1998 | } |
| 1999 | |
| 2000 | /** |
| 2001 | * Builds the synthetic store-setup lead tasks for the sell goal: an "install WooCommerce" task and a "set up |
| 2002 | * your store" task. Their ids are listed in SYNTHETIC_TASK_IDS so the tasks stay skippable. |
| 2003 | * |
| 2004 | * Both are read live (installed/active/profiler options), so no marker or listener is needed. While WooCommerce |
| 2005 | * is inactive the setup task shows as a disabled preview, matching the disabled commerce tasks below it. Callers |
| 2006 | * gate this on the sell goal. |
| 2007 | * |
| 2008 | * @param bool $active Whether WooCommerce is active. |
| 2009 | * @return array The lead tasks in display order. |
| 2010 | */ |
| 2011 | private function build_store_tasks( $active ) { |
| 2012 | return array( |
| 2013 | $this->build_install_woocommerce_task( $active ), |
| 2014 | $this->build_setup_store_task( $active ), |
| 2015 | ); |
| 2016 | } |
| 2017 | |
| 2018 | /** |
| 2019 | * The "Install the WooCommerce plugin" lead task: to-do until the plugin exists, in-progress while it is |
| 2020 | * installed-but-inactive, and complete once active. |
| 2021 | * |
| 2022 | * @param bool $active Whether WooCommerce is active. |
| 2023 | * @return array |
| 2024 | */ |
| 2025 | private function build_install_woocommerce_task( $active ) { |
| 2026 | $in_progress = ! $active && array_key_exists( 'woocommerce/woocommerce.php', get_plugins() ); |
| 2027 | |
| 2028 | $calypso_path = null; |
| 2029 | if ( ! $active ) { |
| 2030 | // Installed-but-inactive activates from the plugins list; not-installed installs from the plugin search. |
| 2031 | // On Simple both wp-admin screens are unreachable, so route through the Calypso WooCommerce plugin page. |
| 2032 | $wp_admin_path = $in_progress |
| 2033 | ? admin_url( 'plugins.php?plugin_status=inactive' ) |
| 2034 | : admin_url( 'plugin-install.php?s=woocommerce&tab=search&type=term' ); |
| 2035 | $calypso_path = wpcom_ai_launchpad_to_simple_plugins_path( $wp_admin_path, 'woocommerce' ); |
| 2036 | } |
| 2037 | |
| 2038 | return array( |
| 2039 | 'id' => 'install_woocommerce', |
| 2040 | 'subtitle' => $in_progress |
| 2041 | ? __( 'Activate the WooCommerce plugin to continue.', 'jetpack-mu-wpcom' ) |
| 2042 | : __( 'Add the WooCommerce plugin to start selling.', 'jetpack-mu-wpcom' ), |
| 2043 | 'title' => __( 'Install the WooCommerce plugin', 'jetpack-mu-wpcom' ), |
| 2044 | 'completed' => $active, |
| 2045 | 'in_progress' => $in_progress, |
| 2046 | 'disabled' => false, |
| 2047 | 'calypso_path' => $calypso_path, |
| 2048 | ); |
| 2049 | } |
| 2050 | |
| 2051 | /** |
| 2052 | * The "Set up your store" lead task: to-do until the WooCommerce setup wizard (core profiler) is completed or |
| 2053 | * skipped, then complete. Shown as a disabled preview until WooCommerce is active, since the wizard needs it. |
| 2054 | * |
| 2055 | * @param bool $active Whether WooCommerce is active. |
| 2056 | * @return array |
| 2057 | */ |
| 2058 | private function build_setup_store_task( $active ) { |
| 2059 | $profile = (array) get_option( 'woocommerce_onboarding_profile', array() ); |
| 2060 | $completed = $active && ( ! empty( $profile['completed'] ) || ! empty( $profile['skipped'] ) ); |
| 2061 | |
| 2062 | return array( |
| 2063 | 'id' => 'setup_woocommerce_store', |
| 2064 | 'subtitle' => __( 'Complete or skip the WooCommerce setup wizard.', 'jetpack-mu-wpcom' ), |
| 2065 | 'title' => __( 'Set up your store', 'jetpack-mu-wpcom' ), |
| 2066 | 'completed' => $completed, |
| 2067 | 'in_progress' => false, |
| 2068 | 'disabled' => ! $active, |
| 2069 | 'calypso_path' => $completed || ! $active ? null : admin_url( 'admin.php?page=wc-admin&path=%2Fsetup-wizard' ), |
| 2070 | ); |
| 2071 | } |
| 2072 | |
| 2073 | /** |
| 2074 | * Inserts a task immediately before the trailing launch task (or appends it), idempotently by id. |
| 2075 | * |
| 2076 | * @param array $tasks The enriched task list. |
| 2077 | * @param array $task The task entry to insert. |
| 2078 | * @return array |
| 2079 | */ |
| 2080 | private function insert_before_launch_task( $tasks, $task ) { |
| 2081 | foreach ( $tasks as $existing ) { |
| 2082 | if ( isset( $existing['id'] ) && $existing['id'] === $task['id'] ) { |
| 2083 | return $tasks; |
| 2084 | } |
| 2085 | } |
| 2086 | |
| 2087 | $insert_at = count( $tasks ); |
| 2088 | foreach ( $tasks as $index => $existing ) { |
| 2089 | if ( isset( $existing['id'] ) && in_array( $existing['id'], self::LAUNCH_TASK_IDS, true ) ) { |
| 2090 | $insert_at = $index; |
| 2091 | break; |
| 2092 | } |
| 2093 | } |
| 2094 | |
| 2095 | array_splice( $tasks, $insert_at, 0, array( $task ) ); |
| 2096 | return $tasks; |
| 2097 | } |
| 2098 | |
| 2099 | /** |
| 2100 | * Resolves the editor URL of a site-editor task's in-progress draft, or null when there is none. |
| 2101 | * |
| 2102 | * The About page is found by its marker meta; the first-post tasks by the latest draft post. Returned as an |
| 2103 | * `admin_url()` so the client reopens the existing draft rather than creating a duplicate. |
| 2104 | * |
| 2105 | * @param string $task_id The catalog task id. |
| 2106 | * @return string|null |
| 2107 | */ |
| 2108 | private function get_in_progress_draft_url( $task_id ) { |
| 2109 | $draft_id = null; |
| 2110 | |
| 2111 | if ( 'add_about_page' === $task_id ) { |
| 2112 | $draft_id = AI_Launchpad_About_Page_Listener::get_draft_id(); |
| 2113 | } elseif ( in_array( $task_id, self::IN_PROGRESS_FIRST_POST_TASK_IDS, true ) ) { |
| 2114 | $draft_id = AI_Launchpad_First_Post_Listener::get_draft_id(); |
| 2115 | } |
| 2116 | |
| 2117 | if ( null === $draft_id ) { |
| 2118 | return null; |
| 2119 | } |
| 2120 | |
| 2121 | return admin_url( 'post.php?post=' . $draft_id . '&action=edit' ); |
| 2122 | } |
| 2123 | |
| 2124 | /** |
| 2125 | * The card title for a site-editor task, chosen by our precise (marker-based) in-progress signal so the title, |
| 2126 | * icon, and CTA stay in agreement. |
| 2127 | * |
| 2128 | * This overrides `first_post_published`'s catalog title in both states: the catalog swaps it to "Continue…" |
| 2129 | * whenever ANY draft exists (a looser signal than our marker), so an unrelated draft would otherwise show a |
| 2130 | * "Continue…" title beside the not-started icon. Tasks not listed keep their catalog title. |
| 2131 | * |
| 2132 | * @param string $task_id The catalog task id. |
| 2133 | * @param bool $in_progress Whether our marker detected an in-progress draft. |
| 2134 | * @param string $default The catalog-provided title, kept when we don't override. |
| 2135 | * @return string |
| 2136 | */ |
| 2137 | private function get_task_title( $task_id, $in_progress, $default ) { |
| 2138 | switch ( $task_id ) { |
| 2139 | case 'add_about_page': |
| 2140 | return $in_progress ? __( 'Continue working on the About page', 'jetpack-mu-wpcom' ) : $default; |
| 2141 | case 'first_post_published': |
| 2142 | return $in_progress |
| 2143 | ? __( 'Continue to write your first post', 'jetpack-mu-wpcom' ) |
| 2144 | : __( 'Write your first post', 'jetpack-mu-wpcom' ); |
| 2145 | default: |
| 2146 | return $default; |
| 2147 | } |
| 2148 | } |
| 2149 | |
| 2150 | /** |
| 2151 | * Loads the agent output schema used to validate `PUT /tailored` bodies. |
| 2152 | * |
| 2153 | * @return array |
| 2154 | */ |
| 2155 | private function get_output_schema() { |
| 2156 | static $schema = null; |
| 2157 | |
| 2158 | if ( null === $schema ) { |
| 2159 | $schema = json_decode( file_get_contents( __DIR__ . '/contracts/agent-output-schema.json' ), true ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Local package file. |
| 2160 | } |
| 2161 | |
| 2162 | return $schema; |
| 2163 | } |
| 2164 | } |
| 2165 | |
| 2166 | // @phan-suppress-next-line PhanNoopNew -- instantiated for the constructor's add_action side effect. |
| 2167 | new AI_Launchpad_REST(); |