Commit 597dbc8c23e for woocommerce

commit 597dbc8c23eb8c4057f41b690453219ca584b8f5
Author: AnnaMag <AnnaMag@users.noreply.github.com>
Date:   Fri Nov 20 00:41:07 2026 +0100

    Show AI shopper as the origin of UCP checkout orders (#71157)

    * Show AI shopper as the origin of UCP checkout orders.

    Orders handed off through UCP checkout recorded no attribution, so their
    origin showed as Unknown. Completing a checkout now saves source type
    ai_shopper through woocommerce_order_save_attribution_data, with the
    UCP-Agent profile host as the source and ucp as the medium.

    * Fix UCP order source when the agent header is misnamed or the host is invalid.

    A parameter that only ends in "profile", and a host with an empty label, were stored as the order source instead of the ucp fallback.

    * Remove the attribution hook after the existing-attribution test.

    The callback stayed registered for later tests in the same process.

diff --git a/plugins/woocommerce/changelog/add-ucp-checkout-attribution b/plugins/woocommerce/changelog/add-ucp-checkout-attribution
new file mode 100644
index 00000000000..2d2790d92de
--- /dev/null
+++ b/plugins/woocommerce/changelog/add-ucp-checkout-attribution
@@ -0,0 +1,4 @@
+Significance: minor
+Type: add
+
+Show "AI shopper" as the origin of orders an AI shopping assistant hands off through UCP checkout.
diff --git a/plugins/woocommerce/src/Internal/Admin/Orders/MetaBoxes/OrderAttribution.php b/plugins/woocommerce/src/Internal/Admin/Orders/MetaBoxes/OrderAttribution.php
index a9036c13b2e..d174f5429d7 100644
--- a/plugins/woocommerce/src/Internal/Admin/Orders/MetaBoxes/OrderAttribution.php
+++ b/plugins/woocommerce/src/Internal/Admin/Orders/MetaBoxes/OrderAttribution.php
@@ -80,6 +80,9 @@ class OrderAttribution {
 		$template_data = array(
 			'meta'             => $meta,
 			'has_more_details' => $has_more_details,
+			'origin_note'      => 'ai_shopper' === ( $meta['source_type'] ?? '' )
+				? __( 'This order started with an AI shopping assistant acting on the customer’s behalf.', 'woocommerce' )
+				: '',
 		);
 		wc_get_template( 'order/attribution-details.php', $template_data );
 	}
diff --git a/plugins/woocommerce/src/Internal/Traits/OrderAttributionMeta.php b/plugins/woocommerce/src/Internal/Traits/OrderAttributionMeta.php
index 810fa4c6307..a95f132d858 100644
--- a/plugins/woocommerce/src/Internal/Traits/OrderAttributionMeta.php
+++ b/plugins/woocommerce/src/Internal/Traits/OrderAttributionMeta.php
@@ -319,6 +319,13 @@ trait OrderAttributionMeta {
 					__( 'Point of Sale', 'woocommerce' )
 					: 'Point of Sale';
 				break;
+			case 'ai_shopper':
+				// The agent named in a UCP request is not verified, so it stays in the details.
+				$label  = '';
+				$source = $translated ?
+					__( 'AI shopper', 'woocommerce' )
+					: 'AI shopper';
+				break;

 			default:
 				$label  = '';
diff --git a/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/CheckoutSessionsComplete.php b/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/CheckoutSessionsComplete.php
index 72e5eacba81..5ee14960208 100644
--- a/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/CheckoutSessionsComplete.php
+++ b/plugins/woocommerce/src/StoreApi/Routes/V1/Ucp/CheckoutSessionsComplete.php
@@ -5,6 +5,7 @@ namespace Automattic\WooCommerce\StoreApi\Routes\V1\Ucp;

 use Automattic\WooCommerce\Checkout\Helpers\ReserveStockException;
 use Automattic\WooCommerce\Enums\OrderStatus;
+use Automattic\WooCommerce\Internal\Orders\OrderAttributionController;
 use Automattic\WooCommerce\StoreApi\Exceptions\RouteException;
 use Automattic\WooCommerce\StoreApi\Utilities\Ucp\CheckoutMapper;
 use Automattic\WooCommerce\StoreApi\Utilities\Ucp\Utils;
@@ -149,6 +150,8 @@ class CheckoutSessionsComplete extends AbstractCheckoutRoute {
 			return $this->ucp_error( Utils::cart_error_code( (string) $e->getErrorCode() ), wp_specialchars_decode( $e->getMessage(), ENT_QUOTES ), 'recoverable', 200, '$.line_items' );
 		}

+		$this->record_attribution( $order, $request );
+
 		// The payment page only takes an order awaiting payment, which a checkout draft is not.
 		$order->set_status( OrderStatus::PENDING );
 		$order->save();
@@ -170,6 +173,105 @@ class CheckoutSessionsComplete extends AbstractCheckoutRoute {
 		return $this->checkout_response( $checkout_id, $this->checkout_state() ?? $state, 200, $cart );
 	}

+	/**
+	 * Record the order as started by an AI shopper, so its origin is not Unknown.
+	 *
+	 * The payment page records no attribution of its own.
+	 * The source is the host of the `profile` parameter in the `UCP-Agent` header, or `ucp` when that parameter is missing or its host is not a hostname.
+	 * A parameter only counts when its name is exactly `profile` and it is outside a quoted value.
+	 * The header is not verified, so the host is a detail and not part of the origin.
+	 * Saved only with order attribution on, and never over attribution the order already has.
+	 *
+	 * @param \WC_Order        $order   The order being handed off.
+	 * @param \WP_REST_Request $request Request object.
+	 *
+	 * @phpstan-param \WP_REST_Request<array<string, mixed>> $request
+	 */
+	private function record_attribution( \WC_Order $order, \WP_REST_Request $request ): void {
+		$attribution = wc_get_container()->get( OrderAttributionController::class );
+
+		if ( $attribution->has_attribution( $order ) ) {
+			return;
+		}
+
+		// Every field is set, because the listener reads each one without checking it exists.
+		$data = array_merge(
+			array_fill_keys( $attribution->get_field_names(), '' ),
+			array(
+				'source_type' => 'ai_shopper',
+				'utm_source'  => $this->agent_profile_host( (string) $request->get_header( 'UCP-Agent' ) ),
+				'utm_medium'  => 'ucp',
+			)
+		);
+
+		// phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingHookComment -- Documented in OrderAttributionController.
+		do_action( 'woocommerce_order_save_attribution_data', $order, $data );
+	}
+
+	/**
+	 * Host of the `profile` parameter in a UCP-Agent header, or `ucp` when it is missing or not a hostname.
+	 *
+	 * Only a parameter named exactly `profile`, outside a quoted value, counts.
+	 *
+	 * @param string $header UCP-Agent header value.
+	 * @return string
+	 */
+	private function agent_profile_host( string $header ): string {
+		$profile = $this->quoted_header_parameter( $header, 'profile' );
+		$host    = strtolower( (string) wp_parse_url( $profile, PHP_URL_HOST ) );
+
+		if ( '' === $host ) {
+			return 'ucp';
+		}
+
+		$valid = filter_var( $host, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME );
+
+		return is_string( $valid ) ? $valid : 'ucp';
+	}
+
+	/**
+	 * Value of one double-quoted parameter, matched by its exact name.
+	 *
+	 * A match counts only outside quotes, at the start of the header or after whitespace or a semicolon.
+	 *
+	 * @param string $header Header value.
+	 * @param string $name   Parameter name.
+	 * @return string Empty when the parameter is absent.
+	 */
+	private function quoted_header_parameter( string $header, string $name ): string {
+		$prefix = $name . '="';
+		$offset = 0;
+		$length = strlen( $header );
+
+		while ( $offset < $length ) {
+			$start = strpos( $header, $prefix, $offset );
+			if ( false === $start ) {
+				return '';
+			}
+
+			// An even number of quotes before the name means it is outside a value.
+			$outside_quotes = 0 === ( substr_count( substr( $header, 0, $start ), '"' ) % 2 );
+			$is_parameter   = 0 === $start;
+			if ( ! $is_parameter ) {
+				$previous     = substr( $header, $start - 1, 1 );
+				$is_parameter = ' ' === $previous || "\t" === $previous || ';' === $previous;
+			}
+
+			if ( $outside_quotes && $is_parameter ) {
+				$value_start = $start + strlen( $prefix );
+				$end         = strpos( $header, '"', $value_start );
+				if ( false === $end ) {
+					return '';
+				}
+				return substr( $header, $value_start, $end - $value_start );
+			}
+
+			$offset = $start + strlen( $prefix );
+		}
+
+		return '';
+	}
+
 	/**
 	 * Return a checkout whose payment was already handed off, as it stands, with a warning that nothing was done.
 	 *
diff --git a/plugins/woocommerce/templates/order/attribution-details.php b/plugins/woocommerce/templates/order/attribution-details.php
index fcd7cf674be..1e57b3dd2a7 100644
--- a/plugins/woocommerce/templates/order/attribution-details.php
+++ b/plugins/woocommerce/templates/order/attribution-details.php
@@ -6,7 +6,7 @@
  *
  * @see     Automattic\WooCommerce\Internal\Orders\OrderAttributionController
  * @package WooCommerce\Templates
- * @version 11.2.0
+ * @version 11.4.0
  */

 declare( strict_types=1 );
@@ -16,8 +16,9 @@ defined( 'ABSPATH' ) || exit;
 /**
  * Variables used in this file.
  *
- * @var array $meta Array of meta data.
- * @var bool  $has_more_details Whether to show the more details toggle.
+ * @var array  $meta             Array of meta data.
+ * @var bool   $has_more_details Whether to show the more details toggle.
+ * @var string $origin_note      A sentence explaining the origin, or ''.
  */
 ?>

@@ -35,6 +36,10 @@ defined( 'ABSPATH' ) || exit;
 			</span>
 		<?php endif; ?>

+		<?php if ( ! empty( $origin_note ) ) : ?>
+			<p class="description order-attribution-origin-note"><?php echo esc_html( $origin_note ); ?></p>
+		<?php endif; ?>
+
 	</div>

 	<div class="woocommerce-order-attribution-details-container closed">
diff --git a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/UcpCheckout.php b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/UcpCheckout.php
index c6b0a5948ae..a752067b51b 100644
--- a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/UcpCheckout.php
+++ b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/UcpCheckout.php
@@ -109,10 +109,12 @@ class UcpCheckout extends ControllerTestCase {
 	 * @param string $method HTTP method.
 	 * @param string $path Route path under /wc/ucp/v1.
 	 * @param array  $body Request body.
+	 * @param array  $headers Extra request headers.
 	 * @return \WP_REST_Response
 	 */
-	private function request( string $method, string $path, array $body = array() ) {
+	private function request( string $method, string $path, array $body = array(), array $headers = array() ) {
 		$request = new \WP_REST_Request( $method, '/wc/ucp/v1' . $path );
+		$request->set_headers( $headers );
 		$request->set_header( 'content-type', 'application/json' );
 		// A write needs a key of its own; the key itself is the UcpIdempotency suite's concern.
 		$request->set_header( 'Idempotency-Key', wp_generate_uuid4() );
@@ -1008,4 +1010,55 @@ class UcpCheckout extends ControllerTestCase {
 		}
 		$this->assertSame( 409, $this->request( 'POST', '/checkout-sessions', array( 'cart_id' => $created['id'] ) )->get_status() );
 	}
+
+	/**
+	 * @testdox Complete records the host of the profile parameter as the order's source, or `ucp` when that host is missing or invalid, and keeps the order a Store API order.
+	 * @testWith ["profile=\"https://Chatgpt.com/.well-known/ucp\"", "chatgpt.com"]
+	 *           ["", "ucp"]
+	 *           ["profile=\"not-a-url\"", "ucp"]
+	 *           ["profile=\"https://evil<b>host/\"", "ucp"]
+	 *           ["notprofile=\"https://example.com/\"", "ucp"]
+	 *           ["profile=\"https://a..example/\"", "ucp"]
+	 *           ["other=\"x\"; profile=\"https://shop.example/.well-known/ucp\"", "shop.example"]
+	 *           ["other=\"x profile=\"; profile=\"https://shop.example/\"", "shop.example"]
+	 *
+	 * @param string $agent  The UCP-Agent header.
+	 * @param string $source The expected utm_source.
+	 */
+	public function test_complete_records_the_agent_as_the_source( string $agent, string $source ): void {
+		$created = $this->create_ready_checkout();
+		$headers = '' === $agent ? array() : array( 'UCP-Agent' => $agent );
+
+		$response = $this->request( 'POST', '/checkout-sessions/' . $created['id'] . '/complete', array(), $headers );
+		$this->assertSame( 'requires_escalation', $response->get_data()['status'] );
+
+		$order = wc_get_order( (int) WC()->session->get( 'store_api_draft_order' ) );
+		$this->assertSame( 'ai_shopper', $order->get_meta( '_wc_order_attribution_source_type' ) );
+		$this->assertSame( $source, $order->get_meta( '_wc_order_attribution_utm_source' ) );
+		$this->assertSame( 'ucp', $order->get_meta( '_wc_order_attribution_utm_medium' ) );
+		$this->assertSame( 'store-api', $order->get_created_via(), 'wc_cancel_unpaid_orders() only cancels checkout and store-api orders.' );
+	}
+
+	/**
+	 * @testdox Complete keeps attribution the order already has.
+	 */
+	public function test_complete_keeps_existing_attribution(): void {
+		$created  = $this->create_ready_checkout();
+		$callback = static function ( \WC_Order $order ) {
+			$order->update_meta_data( '_wc_order_attribution_source_type', 'referral' );
+			$order->save_meta_data();
+		};
+		add_action( 'woocommerce_store_api_checkout_update_order_meta', $callback );
+
+		try {
+			$response = $this->request( 'POST', '/checkout-sessions/' . $created['id'] . '/complete', array(), array( 'UCP-Agent' => 'profile="https://chatgpt.com/"' ) );
+			$this->assertSame( 'requires_escalation', $response->get_data()['status'] );
+
+			$order = wc_get_order( (int) WC()->session->get( 'store_api_draft_order' ) );
+			$this->assertSame( 'referral', $order->get_meta( '_wc_order_attribution_source_type' ) );
+			$this->assertSame( '', $order->get_meta( '_wc_order_attribution_utm_source' ) );
+		} finally {
+			remove_action( 'woocommerce_store_api_checkout_update_order_meta', $callback );
+		}
+	}
 }
diff --git a/plugins/woocommerce/tests/php/src/Internal/Admin/Orders/MetaBoxes/OrderAttributionTest.php b/plugins/woocommerce/tests/php/src/Internal/Admin/Orders/MetaBoxes/OrderAttributionTest.php
index db479667e4e..95af6d16955 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Admin/Orders/MetaBoxes/OrderAttributionTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Admin/Orders/MetaBoxes/OrderAttributionTest.php
@@ -7,6 +7,7 @@ namespace Automattic\WooCommerce\Tests\Internal\Admin\Orders\MetaBoxes;

 use Automattic\WooCommerce\Internal\Admin\Orders\MetaBoxes\OrderAttribution;
 use WC_Helper_Order;
+use WC_Order;
 use WP_UnitTestCase;

 require_once WC_ABSPATH . '/includes/admin/marketplace-suggestions/class-wc-marketplace-suggestions.php';
@@ -68,6 +69,41 @@ class OrderAttributionTest extends WP_UnitTestCase {
 		ob_end_clean();
 	}

+	/**
+	 * @testdox An AI shopper order shows "AI shopper" with a sentence explaining it, and keeps the agent and UCP in the details.
+	 */
+	public function test_ai_shopper_origin_is_explained(): void {
+		$order = new WC_Order();
+		$order->add_meta_data( '_wc_order_attribution_source_type', 'ai_shopper' );
+		$order->add_meta_data( '_wc_order_attribution_utm_source', 'chatgpt.com' );
+		$order->add_meta_data( '_wc_order_attribution_utm_medium', 'ucp' );
+
+		ob_start();
+		$this->sut->output( $order );
+		$html = (string) ob_get_clean();
+
+		$this->assertStringContainsString( 'AI shopper', $html );
+		$this->assertStringContainsString( 'This order started with an AI shopping assistant acting on the customer’s behalf.', $html );
+		$this->assertStringContainsString( 'chatgpt.com', $html );
+		$this->assertStringContainsString( 'ucp', $html );
+		$this->assertStringContainsString( 'woocommerce-order-attribution-details-toggle', $html );
+	}
+
+	/**
+	 * @testdox Other origins show no explanation.
+	 */
+	public function test_other_origins_have_no_note(): void {
+		$order = new WC_Order();
+		$order->add_meta_data( '_wc_order_attribution_source_type', 'referral' );
+		$order->add_meta_data( '_wc_order_attribution_utm_source', 'woocommerce.com' );
+
+		ob_start();
+		$this->sut->output( $order );
+		$html = (string) ob_get_clean();
+
+		$this->assertStringNotContainsString( 'order-attribution-origin-note', $html );
+	}
+
 	/**
 	 * Test that additional order meta passed into the output changes `show more details` value.
 	 *
diff --git a/plugins/woocommerce/tests/php/src/Internal/Orders/OrderAttributionControllerTest.php b/plugins/woocommerce/tests/php/src/Internal/Orders/OrderAttributionControllerTest.php
index d503c10beef..654b8f75670 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Orders/OrderAttributionControllerTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Orders/OrderAttributionControllerTest.php
@@ -119,6 +119,11 @@ class OrderAttributionControllerTest extends WP_UnitTestCase {
 				'source'          => '',
 				'expected_output' => 'Point of Sale',
 			),
+			array(
+				'source_type'     => 'ai_shopper',
+				'source'          => 'chatgpt.com',
+				'expected_output' => 'AI shopper',
+			),
 			array(
 				'source_type'     => '',
 				'source'          => '',