diff --git a/backport-changelog/7.2/15889.md b/backport-changelog/7.2/15889.md
new file mode 100644
index 00000000000000..c6c8d957248b3b
--- /dev/null
+++ b/backport-changelog/7.2/15889.md
@@ -0,0 +1,3 @@
+https://github.com/WordPress/wordpress-develop/pull/15889
+
+* https://github.com/WordPress/gutenberg/pull/78367
diff --git a/lib/compat/plugin/connectors.php b/lib/compat/plugin/connectors.php
index 4ad20400de2471..6bd4a4411bc7bf 100644
--- a/lib/compat/plugin/connectors.php
+++ b/lib/compat/plugin/connectors.php
@@ -22,7 +22,7 @@ function _gutenberg_connectors_add_settings_menu_item(): void {
remove_submenu_page( 'options-general.php', 'connectors-wp-admin' );
remove_submenu_page( 'options-general.php', 'options-connectors.php' );
- add_submenu_page(
+ $hook_suffix = add_submenu_page(
'options-general.php',
__( 'Connectors', 'gutenberg' ),
__( 'Connectors', 'gutenberg' ),
@@ -31,6 +31,38 @@ function _gutenberg_connectors_add_settings_menu_item(): void {
'gutenberg_options_connectors_wp_admin_render_page',
1
);
+
+ if ( $hook_suffix ) {
+ add_action( "load-{$hook_suffix}", '_gutenberg_connectors_load_screen' );
+ }
+}
+
+/**
+ * Sets up the Connectors screen for plugin installation via the standard
+ * `wp.updates` AJAX flow.
+ *
+ * Plugin installation from the Connectors screen goes through the REST
+ * `/wp/v2/plugins` endpoint, which fails outright when the filesystem method
+ * is not `direct` and credentials have not yet been stored. Enqueuing the
+ * `updates` script and printing the standard "Connection Information" modal
+ * mirrors what Plugins > Add Plugin already provides, so the React layer
+ * can fall back to `wp.updates.installPlugin()` for the credentials flow.
+ *
+ * @access private
+ */
+function _gutenberg_connectors_load_screen(): void {
+ wp_enqueue_script( 'updates' );
+ add_action( 'admin_footer', '_gutenberg_connectors_print_filesystem_credentials_modal' );
+}
+
+/**
+ * Prints the filesystem credentials modal on the Connectors screen.
+ *
+ * @access private
+ */
+function _gutenberg_connectors_print_filesystem_credentials_modal(): void {
+ wp_print_request_filesystem_credentials_modal();
+ wp_print_admin_notice_templates();
}
/**
diff --git a/routes/connectors-home/ai-plugin-callout.tsx b/routes/connectors-home/ai-plugin-callout.tsx
index 8e6349e25e1a2e..eba2a1023ee155 100644
--- a/routes/connectors-home/ai-plugin-callout.tsx
+++ b/routes/connectors-home/ai-plugin-callout.tsx
@@ -12,7 +12,14 @@ import { store as noticesStore } from '@wordpress/notices';
import { addQueryArgs } from '@wordpress/url';
import { getConnectorData } from './default-connectors';
import { WpLogoDecoration } from './wp-logo-decoration';
-import type { PluginStatus } from './use-connector-plugin';
+import {
+ installPluginViaWpUpdates,
+ isFilesystemUnavailableError,
+} from './use-connector-plugin';
+import type {
+ InstallButtonClickEvent,
+ PluginStatus,
+} from './use-connector-plugin';
const AI_PLUGIN_SLUG = 'ai';
const AI_PLUGIN_PAGE_SLUG = 'ai-wp-admin';
@@ -118,15 +125,48 @@ export function AiPluginCallout() {
const { createSuccessNotice, createErrorNotice } =
useDispatch( noticesStore );
- const installPlugin = async () => {
+ const installPlugin = async ( event: InstallButtonClickEvent ) => {
+ /*
+ * `currentTarget` is only set while the event is being handled, so
+ * read it before the first `await`.
+ */
+ const trigger = event.currentTarget;
setIsBusy( true );
try {
- await saveEntityRecord(
- 'root',
- 'plugin',
- { slug: AI_PLUGIN_SLUG, status: 'active' },
- { throwOnError: true }
- );
+ try {
+ await saveEntityRecord(
+ 'root',
+ 'plugin',
+ { slug: AI_PLUGIN_SLUG, status: 'active' },
+ { throwOnError: true }
+ );
+ } catch ( error ) {
+ /*
+ * The REST plugin endpoint rejects installs up front with
+ * `fs_unavailable` when FS_METHOD is not 'direct' and
+ * credentials have not been stored. Fall back to
+ * wp.updates.installPlugin() so the standard "Connection
+ * Information" modal handles credential entry, then activate
+ * via REST.
+ */
+ if ( ! isFilesystemUnavailableError( error ) ) {
+ throw error;
+ }
+ const outcome = await installPluginViaWpUpdates(
+ AI_PLUGIN_SLUG,
+ trigger
+ );
+ if ( outcome === 'canceled' ) {
+ // User closed the credentials modal; abort silently.
+ return;
+ }
+ await saveEntityRecord(
+ 'root',
+ 'plugin',
+ { plugin: AI_PLUGIN_ID, status: 'active' },
+ { throwOnError: true }
+ );
+ }
setJustActivated( true );
createSuccessNotice(
__( 'AI plugin installed and activated successfully.' ),
diff --git a/routes/connectors-home/default-connectors.tsx b/routes/connectors-home/default-connectors.tsx
index 84ec7983fb04fa..15a29d645fd452 100644
--- a/routes/connectors-home/default-connectors.tsx
+++ b/routes/connectors-home/default-connectors.tsx
@@ -13,7 +13,11 @@ import { select } from '@wordpress/data';
import { __, sprintf } from '@wordpress/i18n';
import { Badge, Link } from '@wordpress/ui';
import { unlock } from '@wordpress/routes-lock-unlock';
-import { useConnectorPlugin, type PluginStatus } from './use-connector-plugin';
+import {
+ useConnectorPlugin,
+ type InstallButtonClickEvent,
+ type PluginStatus,
+} from './use-connector-plugin';
import {
OpenAILogo,
ClaudeLogo,
@@ -127,7 +131,7 @@ interface ConnectorActionAreaProps {
actionButtonRef: {
current: HTMLButtonElement | null;
};
- handleButtonClick: () => void;
+ handleButtonClick: ( event?: InstallButtonClickEvent ) => void;
getButtonLabel: () => string;
}
diff --git a/routes/connectors-home/test/ai-plugin-callout.jsdom.test.tsx b/routes/connectors-home/test/ai-plugin-callout.jsdom.test.tsx
index 9d325d91a92722..130f5aeecfc17f 100644
--- a/routes/connectors-home/test/ai-plugin-callout.jsdom.test.tsx
+++ b/routes/connectors-home/test/ai-plugin-callout.jsdom.test.tsx
@@ -4,6 +4,7 @@ import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import { useDispatch, useSelect } from '@wordpress/data';
import { AiPluginCallout } from '../ai-plugin-callout';
+import { installPluginViaWpUpdates } from '../use-connector-plugin';
vi.mock(
import( '@wordpress/a11y' ),
@@ -112,6 +113,11 @@ vi.mock(
} ) as unknown as typeof import( '../default-connectors' )
);
+vi.mock( import( '../use-connector-plugin' ), async ( importOriginal ) => ( {
+ ...( await importOriginal() ),
+ installPluginViaWpUpdates: vi.fn(),
+} ) );
+
vi.mock(
import( '../wp-logo-decoration' ),
() =>
@@ -181,6 +187,9 @@ describe( 'AiPluginCallout', () => {
mapSelect( () => selectorStore )
);
+ vi.mocked( installPluginViaWpUpdates ).mockReset();
+ vi.mocked( installPluginViaWpUpdates ).mockResolvedValue( 'installed' );
+
mockSaveEntityRecord.mockReset();
mockSaveEntityRecord.mockResolvedValue( undefined );
mockCreateSuccessNotice.mockReset();
@@ -221,5 +230,102 @@ describe( 'AiPluginCallout', () => {
{ throwOnError: true }
);
} );
+
+ expect( installPluginViaWpUpdates ).not.toHaveBeenCalled();
+ } );
+
+ it( 'falls back to wp.updates then activates when the REST install reports fs_unavailable', async () => {
+ const user = userEvent.setup();
+
+ storeState.plugin = undefined;
+ /*
+ * The REST install (using `slug`) is rejected up front; the
+ * subsequent activate (using `plugin`) succeeds.
+ */
+ mockSaveEntityRecord.mockImplementation(
+ (
+ _kind: string,
+ _name: string,
+ record: Record< string, unknown >
+ ) =>
+ 'slug' in record
+ ? Promise.reject( { code: 'fs_unavailable' } )
+ : Promise.resolve( undefined )
+ );
+ vi.mocked( installPluginViaWpUpdates ).mockResolvedValue( 'installed' );
+
+ render( );
+
+ await user.click(
+ screen.getByRole( 'button', { name: 'Install the AI plugin' } )
+ );
+
+ await waitFor( () => {
+ expect( installPluginViaWpUpdates ).toHaveBeenCalledWith(
+ 'ai',
+ expect.any( HTMLButtonElement )
+ );
+ } );
+
+ await waitFor( () => {
+ expect( mockSaveEntityRecord ).toHaveBeenCalledWith(
+ 'root',
+ 'plugin',
+ { plugin: 'ai/ai', status: 'active' },
+ { throwOnError: true }
+ );
+ } );
+
+ expect( mockCreateErrorNotice ).not.toHaveBeenCalled();
+ } );
+
+ it( 'aborts silently when the filesystem credentials modal is canceled', async () => {
+ const user = userEvent.setup();
+
+ storeState.plugin = undefined;
+ mockSaveEntityRecord.mockRejectedValue( { code: 'fs_unavailable' } );
+ vi.mocked( installPluginViaWpUpdates ).mockResolvedValue( 'canceled' );
+
+ render( );
+
+ await user.click(
+ screen.getByRole( 'button', { name: 'Install the AI plugin' } )
+ );
+
+ await waitFor( () => {
+ expect( installPluginViaWpUpdates ).toHaveBeenCalledWith(
+ 'ai',
+ expect.any( HTMLButtonElement )
+ );
+ } );
+
+ /*
+ * Only the initial REST install attempt ran: no activate follow-up
+ * and no error notice.
+ */
+ expect( mockSaveEntityRecord ).toHaveBeenCalledTimes( 1 );
+ expect( mockCreateErrorNotice ).not.toHaveBeenCalled();
+ } );
+
+ it( 'shows an error notice when the REST install fails for another reason', async () => {
+ const user = userEvent.setup();
+
+ storeState.plugin = undefined;
+ mockSaveEntityRecord.mockRejectedValue( {
+ code: 'rest_cannot_install',
+ } );
+
+ render( );
+
+ await user.click(
+ screen.getByRole( 'button', { name: 'Install the AI plugin' } )
+ );
+
+ await waitFor( () => {
+ expect( mockCreateErrorNotice ).toHaveBeenCalled();
+ } );
+
+ // A non-filesystem error must not trigger the wp.updates fallback.
+ expect( installPluginViaWpUpdates ).not.toHaveBeenCalled();
} );
} );
diff --git a/routes/connectors-home/use-connector-plugin.ts b/routes/connectors-home/use-connector-plugin.ts
index a6e7d35df7a12a..4f086fdc74ad77 100644
--- a/routes/connectors-home/use-connector-plugin.ts
+++ b/routes/connectors-home/use-connector-plugin.ts
@@ -24,6 +24,188 @@ interface UseConnectorPluginOptions {
initialIsConnected?: boolean;
}
+interface WpUpdatesInstallPluginResponse {
+ slug: string;
+ plugin?: string;
+}
+
+interface WpUpdatesInstallPluginErrorResponse {
+ slug: string;
+ errorCode?: string;
+ errorMessage?: string;
+}
+
+interface WpUpdates {
+ installPlugin: ( args: { slug: string } ) => void;
+ maybeRequestFilesystemCredentials?: ( event: {
+ target: Element | null;
+ } ) => void;
+}
+
+type JQueryHandler = (
+ event: unknown,
+ response:
+ WpUpdatesInstallPluginResponse | WpUpdatesInstallPluginErrorResponse
+) => void;
+
+type JQueryAjaxCompleteHandler = (
+ event: unknown,
+ xhr: { status: number; responseJSON?: unknown },
+ settings: { data?: unknown }
+) => void;
+
+interface WpUpdatesGlobal {
+ wp?: {
+ updates?: WpUpdates;
+ };
+ jQuery?: ( target: Document ) => {
+ on: (
+ events: string,
+ handler: JQueryHandler | JQueryAjaxCompleteHandler
+ ) => void;
+ off: (
+ events: string,
+ handler: JQueryHandler | JQueryAjaxCompleteHandler
+ ) => void;
+ };
+}
+
+/**
+ * Whether a rejected REST plugin install failed because the filesystem
+ * requires credentials (`FS_METHOD` is not `direct` and none are stored).
+ *
+ * @param error Rejection from the REST plugin endpoint.
+ */
+export function isFilesystemUnavailableError( error: unknown ): boolean {
+ return (
+ typeof error === 'object' &&
+ error !== null &&
+ ( error as { code?: unknown } ).code === 'fs_unavailable'
+ );
+}
+
+/**
+ * Outcome of an install routed through `wp.updates.installPlugin()`.
+ *
+ * `canceled` is a normal control-flow result (the user closed the
+ * filesystem credentials modal), not an error. Genuine install
+ * failures reject the promise instead.
+ */
+export type WpUpdatesInstallOutcome = 'installed' | 'canceled';
+
+/**
+ * Click event of the button that starts an install.
+ */
+export type InstallButtonClickEvent = { currentTarget: Element };
+
+/**
+ * Installs a plugin via `wp.updates.installPlugin()`.
+ *
+ * @param slug Plugin slug.
+ * @param trigger Element that started the install. Focus returns to it when
+ * the filesystem credentials modal closes.
+ */
+export function installPluginViaWpUpdates(
+ slug: string,
+ trigger?: Element | null
+): Promise< WpUpdatesInstallOutcome > {
+ return new Promise( ( resolve, reject ) => {
+ const w = window as unknown as WpUpdatesGlobal;
+ const jq = w.jQuery;
+ const updates = w.wp?.updates;
+ if ( ! jq || ! updates?.installPlugin ) {
+ reject( new Error( 'wp.updates.installPlugin is not available.' ) );
+ return;
+ }
+
+ /*
+ * Handlers are registered with on()/off() (not one()) and filtered
+ * by slug. With one(), a concurrent install of a *different* plugin
+ * firing first would consume the one-shot handler and leave this
+ * promise pending forever. on() + explicit cleanup() only tears
+ * down once the matching slug's event arrives.
+ */
+ const cleanup = () => {
+ jq( document ).off( 'wp-plugin-install-success', onSuccess );
+ jq( document ).off( 'wp-plugin-install-error', onError );
+ jq( document ).off( 'credential-modal-cancel', onCancel );
+ jq( document ).off( 'ajaxComplete', onAjaxComplete );
+ };
+
+ const onSuccess: JQueryHandler = ( _event, response ) => {
+ if (
+ ( response as WpUpdatesInstallPluginResponse ).slug !== slug
+ ) {
+ return;
+ }
+ cleanup();
+ resolve( 'installed' );
+ };
+ const onError: JQueryHandler = ( _event, response ) => {
+ if (
+ ( response as WpUpdatesInstallPluginErrorResponse ).slug !==
+ slug
+ ) {
+ return;
+ }
+ cleanup();
+ const errResponse = response as WpUpdatesInstallPluginErrorResponse;
+ reject(
+ new Error( errResponse.errorMessage ?? 'Install failed.' )
+ );
+ };
+ const onCancel: JQueryHandler = () => {
+ cleanup();
+ resolve( 'canceled' );
+ };
+ /*
+ * When the server returns an unexpected response (for example, an
+ * expired nonce or a PHP fatal error), none of the events above
+ * fire. Watch the install request itself so the install fails
+ * instead of staying on "Installing…".
+ */
+ const onAjaxComplete: JQueryAjaxCompleteHandler = (
+ _event,
+ xhr,
+ settings
+ ) => {
+ if ( typeof settings.data !== 'string' ) {
+ return;
+ }
+ const params = new URLSearchParams( settings.data );
+ if (
+ params.get( 'action' ) !== 'install-plugin' ||
+ params.get( 'slug' ) !== slug
+ ) {
+ return;
+ }
+ if (
+ xhr.status !== 200 ||
+ typeof xhr.responseJSON !== 'object' ||
+ xhr.responseJSON === null
+ ) {
+ cleanup();
+ reject( new Error( 'Install failed.' ) );
+ }
+ };
+
+ jq( document ).on( 'wp-plugin-install-success', onSuccess );
+ jq( document ).on( 'wp-plugin-install-error', onError );
+ jq( document ).on( 'credential-modal-cancel', onCancel );
+ jq( document ).on( 'ajaxComplete', onAjaxComplete );
+
+ /*
+ * Open the credentials modal before sending the request, as
+ * Plugins > Add Plugin does. The modal then opens without an error,
+ * and focus returns to the install button when it closes.
+ */
+ updates.maybeRequestFilesystemCredentials?.( {
+ target: trigger ?? null,
+ } );
+ updates.installPlugin( { slug } );
+ } );
+}
+
interface UseConnectorPluginReturn {
pluginStatus: PluginStatus;
canInstallPlugins: boolean | undefined;
@@ -36,7 +218,7 @@ interface UseConnectorPluginReturn {
currentUsername: string;
hasResolvedSettings: boolean;
keySource: ApiKeySource;
- handleButtonClick: () => void;
+ handleButtonClick: ( event?: InstallButtonClickEvent ) => void;
getButtonLabel: () => string;
saveApiKey: ( apiKey: string ) => Promise< void >;
removeApiKey: () => Promise< void >;
@@ -251,18 +433,59 @@ export function useConnectorPlugin( {
);
};
- const installPlugin = async () => {
+ const installPlugin = async ( event?: InstallButtonClickEvent ) => {
if ( ! pluginSlug ) {
return;
}
+ /*
+ * `currentTarget` is only set while the event is being handled, so
+ * read it before the first `await`.
+ */
+ const trigger = event?.currentTarget;
setIsBusy( true );
try {
- await saveEntityRecord(
- 'root',
- 'plugin',
- { slug: pluginSlug, status: 'active' },
- { throwOnError: true }
- );
+ try {
+ await saveEntityRecord(
+ 'root',
+ 'plugin',
+ { slug: pluginSlug, status: 'active' },
+ { throwOnError: true }
+ );
+ } catch ( error ) {
+ /*
+ * The REST plugin endpoint rejects installs up front with
+ * `fs_unavailable` when FS_METHOD is not 'direct' and
+ * credentials have not been stored. Fall back to
+ * wp.updates.installPlugin() so the standard "Connection
+ * Information" modal handles credential entry, then activate
+ * via REST.
+ */
+ if ( ! isFilesystemUnavailableError( error ) ) {
+ throw error;
+ }
+ const outcome = await installPluginViaWpUpdates(
+ pluginSlug,
+ trigger
+ );
+ if ( outcome === 'canceled' ) {
+ // User closed the credentials modal; abort silently.
+ return;
+ }
+ if ( pluginBasename ) {
+ await saveEntityRecord(
+ 'root',
+ 'plugin',
+ { plugin: pluginBasename, status: 'active' },
+ { throwOnError: true }
+ );
+ }
+ // Refresh plugin entity so derived state reflects install.
+ invalidateResolution( 'getEntityRecord', [
+ 'root',
+ 'plugin',
+ pluginBasename,
+ ] );
+ }
setPluginStatusOverride( 'active' );
// Re-fetch settings since the new plugin may register new settings.
invalidateResolution( 'getEntityRecord', [ 'root', 'site' ] );
@@ -342,12 +565,12 @@ export function useConnectorPlugin( {
}
};
- const handleButtonClick = () => {
+ const handleButtonClick = ( event?: InstallButtonClickEvent ) => {
if ( pluginStatus === 'not-installed' ) {
if ( canInstallPlugins === false ) {
return;
}
- installPlugin();
+ installPlugin( event );
} else if ( pluginStatus === 'inactive' ) {
if ( canActivatePlugins === false ) {
return;