From 171d7585f29e3e217e4f17035692138d8205f461 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Fri, 15 May 2026 12:34:47 -0700 Subject: [PATCH 01/17] Connectors: Show filesystem credentials modal on plugin install When `FS_METHOD` is not `direct` and FTP credentials have not been stored, the REST `/wp/v2/plugins` endpoint rejects an install attempt up front, surfacing only a generic "Failed to install plugin" snackbar on the Connectors screen. Plugins > Add Plugin handles the same case by displaying the standard "Connection Information" modal. Print that modal on the Connectors screen, expose `filesystemCredentialsRequired` via the script module data, and route through `wp.updates.installPlugin()` when credentials are required so the legacy AJAX install path supplies them. After the install succeeds, activate via REST and refresh the plugin entity. --- lib/experimental/connectors/load.php | 70 ++++++++- routes/connectors-home/default-connectors.tsx | 6 + .../connectors-home/use-connector-plugin.ts | 138 +++++++++++++++++- 3 files changed, 206 insertions(+), 8 deletions(-) diff --git a/lib/experimental/connectors/load.php b/lib/experimental/connectors/load.php index 7e60135edb41c3..4f0f2254430ef0 100644 --- a/lib/experimental/connectors/load.php +++ b/lib/experimental/connectors/load.php @@ -23,7 +23,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' ), @@ -32,6 +32,74 @@ 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 { + require_once ABSPATH . 'wp-admin/includes/file.php'; + require_once ABSPATH . 'wp-admin/includes/template.php'; + + wp_print_request_filesystem_credentials_modal(); + wp_print_admin_notice_templates(); +} + +/** + * Exposes whether the current request can install plugins directly to the + * Connectors script module. + * + * When the filesystem method is anything other than `direct` and stored + * credentials are not yet available, the REST plugin endpoint will reject + * an install attempt up front. Surfacing this state to the client lets the + * React layer pre-emptively route through `wp.updates.installPlugin()`, + * which displays the standard filesystem credentials modal. + * + * @access private + * + * @param array $data Existing script module data. + * @return array Script module data with the filesystem flag added. + */ +function _gutenberg_connectors_add_filesystem_data_to_script_module_data( array $data ): array { + require_once ABSPATH . 'wp-admin/includes/file.php'; + + $method = get_filesystem_method(); + if ( 'direct' === $method ) { + $data['filesystemCredentialsRequired'] = false; + return $data; + } + + ob_start(); + $stored = request_filesystem_credentials( self_admin_url() ); + ob_end_clean(); + + $data['filesystemCredentialsRequired'] = empty( $stored ); + return $data; } +add_filter( 'script_module_data_options-connectors-wp-admin', '_gutenberg_connectors_add_filesystem_data_to_script_module_data' ); require __DIR__ . '/default-connectors.php'; diff --git a/routes/connectors-home/default-connectors.tsx b/routes/connectors-home/default-connectors.tsx index 2f2dec2db0e9e7..00824f0bce0070 100644 --- a/routes/connectors-home/default-connectors.tsx +++ b/routes/connectors-home/default-connectors.tsx @@ -46,6 +46,7 @@ interface ConnectorData { interface ConnectorScriptModuleData { connectors?: Record< string, ConnectorData >; isFileModDisabled?: boolean; + filesystemCredentialsRequired?: boolean; } function getConnectorScriptModuleData(): ConnectorScriptModuleData { @@ -71,6 +72,10 @@ export function getIsFileModDisabled(): boolean { return !! getConnectorScriptModuleData().isFileModDisabled; } +export function getRequiresFilesystemCredentials(): boolean { + return !! getConnectorScriptModuleData().filesystemCredentialsRequired; +} + const CONNECTOR_LOGOS: Record< string, React.ComponentType > = { google: GeminiLogo, openai: OpenAILogo, @@ -170,6 +175,7 @@ function ApiKeyConnector( { isActivated: plugin?.isActivated, keySource: auth?.keySource, initialIsConnected: auth?.isConnected, + requiresFilesystemCredentials: getRequiresFilesystemCredentials(), } ); const isExternallyConfigured = keySource === 'env' || keySource === 'constant'; diff --git a/routes/connectors-home/use-connector-plugin.ts b/routes/connectors-home/use-connector-plugin.ts index 836752b6e65916..27414dc9073200 100644 --- a/routes/connectors-home/use-connector-plugin.ts +++ b/routes/connectors-home/use-connector-plugin.ts @@ -19,6 +19,100 @@ interface UseConnectorPluginOptions { isActivated?: boolean; keySource?: ApiKeySource; initialIsConnected?: boolean; + requiresFilesystemCredentials?: boolean; +} + +interface WpUpdatesInstallPluginResponse { + slug: string; + plugin?: string; +} + +interface WpUpdatesInstallPluginErrorResponse { + slug: string; + errorCode?: string; + errorMessage?: string; +} + +interface WpUpdates { + installPlugin: ( args: { slug: string } ) => void; +} + +interface WpUpdatesGlobal { + wp?: { + updates?: WpUpdates; + }; + jQuery?: ( target: Document ) => { + one: ( + event: string, + handler: ( + event: unknown, + response: + | WpUpdatesInstallPluginResponse + | WpUpdatesInstallPluginErrorResponse + ) => void + ) => unknown; + off: ( event: string, handler: unknown ) => unknown; + }; +} + +function installPluginViaWpUpdates( slug: string ): Promise< void > { + 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; + } + + const onSuccess = ( + _event: unknown, + response: + | WpUpdatesInstallPluginResponse + | WpUpdatesInstallPluginErrorResponse + ) => { + if ( + ( response as WpUpdatesInstallPluginResponse ).slug !== slug + ) { + return; + } + cleanup(); + resolve(); + }; + const onError = ( + _event: unknown, + response: + | WpUpdatesInstallPluginResponse + | WpUpdatesInstallPluginErrorResponse + ) => { + if ( + ( response as WpUpdatesInstallPluginErrorResponse ).slug !== + slug + ) { + return; + } + cleanup(); + const errResponse = response as WpUpdatesInstallPluginErrorResponse; + reject( + new Error( errResponse.errorMessage ?? 'Install failed.' ) + ); + }; + const onCancel = () => { + cleanup(); + reject( new Error( 'Filesystem credentials request canceled.' ) ); + }; + 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 ).one( 'wp-plugin-install-success', onSuccess ); + jq( document ).one( 'wp-plugin-install-error', onError ); + jq( document ).one( 'credential-modal-cancel', onCancel ); + + updates.installPlugin( { slug } ); + } ); } interface UseConnectorPluginReturn { @@ -45,6 +139,7 @@ export function useConnectorPlugin( { isActivated, keySource = 'none', initialIsConnected = false, + requiresFilesystemCredentials = false, }: UseConnectorPluginOptions ): UseConnectorPluginReturn { const [ isExpanded, setIsExpanded ] = useState( false ); const [ isBusy, setIsBusy ] = useState( false ); @@ -168,12 +263,35 @@ export function useConnectorPlugin( { } setIsBusy( true ); try { - await saveEntityRecord( - 'root', - 'plugin', - { slug: pluginSlug, status: 'active' }, - { throwOnError: true } - ); + if ( requiresFilesystemCredentials ) { + // The REST plugin endpoint rejects installs up front when + // FS_METHOD is not 'direct' and credentials have not been + // stored. Route through wp.updates.installPlugin() so the + // standard "Connection Information" modal handles credential + // entry, then activate via REST. + await installPluginViaWpUpdates( pluginSlug ); + 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, + ] ); + } else { + await saveEntityRecord( + 'root', + 'plugin', + { slug: pluginSlug, status: 'active' }, + { throwOnError: true } + ); + } setPluginStatusOverride( 'active' ); // Re-fetch settings since the new plugin may register new settings. invalidateResolution( 'getEntityRecord', [ 'root', 'site' ] ); @@ -189,7 +307,13 @@ export function useConnectorPlugin( { type: 'snackbar', } ); - } catch { + } catch ( error ) { + // A user-initiated cancel of the filesystem credentials dialog + // should silently abort the install without a snackbar. + const message = error instanceof Error ? error.message : ''; + if ( message === 'Filesystem credentials request canceled.' ) { + return; + } createErrorNotice( sprintf( /* translators: %s: Name of the connector (e.g. "OpenAI"). */ From c75cf6cb285f3e12d9db0fffb798e117d1f361ac Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Fri, 15 May 2026 13:31:01 -0700 Subject: [PATCH 02/17] Use more specific array types --- lib/experimental/connectors/load.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/experimental/connectors/load.php b/lib/experimental/connectors/load.php index 4f0f2254430ef0..46c8b4eac48080 100644 --- a/lib/experimental/connectors/load.php +++ b/lib/experimental/connectors/load.php @@ -81,8 +81,8 @@ function _gutenberg_connectors_print_filesystem_credentials_modal(): void { * * @access private * - * @param array $data Existing script module data. - * @return array Script module data with the filesystem flag added. + * @param array $data Existing script module data. + * @return array Script module data with the filesystem flag added. */ function _gutenberg_connectors_add_filesystem_data_to_script_module_data( array $data ): array { require_once ABSPATH . 'wp-admin/includes/file.php'; From 7da7cfd5ef47ca14cc27274f12f6083bea874b67 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Fri, 15 May 2026 13:35:50 -0700 Subject: [PATCH 03/17] Avoid use of empty() --- lib/experimental/connectors/load.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/experimental/connectors/load.php b/lib/experimental/connectors/load.php index 46c8b4eac48080..19f894be664191 100644 --- a/lib/experimental/connectors/load.php +++ b/lib/experimental/connectors/load.php @@ -97,7 +97,7 @@ function _gutenberg_connectors_add_filesystem_data_to_script_module_data( array $stored = request_filesystem_credentials( self_admin_url() ); ob_end_clean(); - $data['filesystemCredentialsRequired'] = empty( $stored ); + $data['filesystemCredentialsRequired'] = ! $stored; return $data; } add_filter( 'script_module_data_options-connectors-wp-admin', '_gutenberg_connectors_add_filesystem_data_to_script_module_data' ); From cfeeea4c945130816301b424d657c7b794d5ae00 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Fri, 15 May 2026 13:55:10 -0700 Subject: [PATCH 04/17] Connectors: Harden wp.updates install fallback per review - Register the install event handlers with on()/off() instead of one() and filter by slug. With one(), a concurrent install of a different plugin firing first would consume the one-shot handler and leave the promise pending. on() + explicit cleanup() only tears down once the matching slug's event arrives. - Replace the brittle "cancel via hard-coded error message string" detection. installPluginViaWpUpdates() now resolves with 'installed' | 'canceled' so cancel is a normal control-flow outcome the caller branches on, while genuine install failures still reject. Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com> Co-Authored-By: Claude Opus 4.7 (1M context) --- .../connectors-home/use-connector-plugin.ts | 88 ++++++++++--------- 1 file changed, 46 insertions(+), 42 deletions(-) diff --git a/routes/connectors-home/use-connector-plugin.ts b/routes/connectors-home/use-connector-plugin.ts index 27414dc9073200..5bfad106414071 100644 --- a/routes/connectors-home/use-connector-plugin.ts +++ b/routes/connectors-home/use-connector-plugin.ts @@ -37,25 +37,35 @@ interface WpUpdates { installPlugin: ( args: { slug: string } ) => void; } +type JQueryHandler = ( + event: unknown, + response: + | WpUpdatesInstallPluginResponse + | WpUpdatesInstallPluginErrorResponse +) => void; + interface WpUpdatesGlobal { wp?: { updates?: WpUpdates; }; jQuery?: ( target: Document ) => { - one: ( - event: string, - handler: ( - event: unknown, - response: - | WpUpdatesInstallPluginResponse - | WpUpdatesInstallPluginErrorResponse - ) => void - ) => unknown; - off: ( event: string, handler: unknown ) => unknown; + on: ( event: string, handler: JQueryHandler ) => unknown; + off: ( event: string, handler: JQueryHandler ) => unknown; }; } -function installPluginViaWpUpdates( slug: string ): Promise< void > { +/** + * 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. + */ +type WpUpdatesInstallOutcome = 'installed' | 'canceled'; + +function installPluginViaWpUpdates( + slug: string +): Promise< WpUpdatesInstallOutcome > { return new Promise( ( resolve, reject ) => { const w = window as unknown as WpUpdatesGlobal; const jq = w.jQuery; @@ -65,26 +75,27 @@ function installPluginViaWpUpdates( slug: string ): Promise< void > { return; } - const onSuccess = ( - _event: unknown, - response: - | WpUpdatesInstallPluginResponse - | WpUpdatesInstallPluginErrorResponse - ) => { + // 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 ); + }; + + const onSuccess: JQueryHandler = ( _event, response ) => { if ( ( response as WpUpdatesInstallPluginResponse ).slug !== slug ) { return; } cleanup(); - resolve(); + resolve( 'installed' ); }; - const onError = ( - _event: unknown, - response: - | WpUpdatesInstallPluginResponse - | WpUpdatesInstallPluginErrorResponse - ) => { + const onError: JQueryHandler = ( _event, response ) => { if ( ( response as WpUpdatesInstallPluginErrorResponse ).slug !== slug @@ -97,19 +108,14 @@ function installPluginViaWpUpdates( slug: string ): Promise< void > { new Error( errResponse.errorMessage ?? 'Install failed.' ) ); }; - const onCancel = () => { + const onCancel: JQueryHandler = () => { cleanup(); - reject( new Error( 'Filesystem credentials request canceled.' ) ); - }; - 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 ); + resolve( 'canceled' ); }; - jq( document ).one( 'wp-plugin-install-success', onSuccess ); - jq( document ).one( 'wp-plugin-install-error', onError ); - jq( document ).one( 'credential-modal-cancel', onCancel ); + jq( document ).on( 'wp-plugin-install-success', onSuccess ); + jq( document ).on( 'wp-plugin-install-error', onError ); + jq( document ).on( 'credential-modal-cancel', onCancel ); updates.installPlugin( { slug } ); } ); @@ -269,7 +275,11 @@ export function useConnectorPlugin( { // stored. Route through wp.updates.installPlugin() so the // standard "Connection Information" modal handles credential // entry, then activate via REST. - await installPluginViaWpUpdates( pluginSlug ); + const outcome = await installPluginViaWpUpdates( pluginSlug ); + if ( outcome === 'canceled' ) { + // User closed the credentials modal; abort silently. + return; + } if ( pluginBasename ) { await saveEntityRecord( 'root', @@ -307,13 +317,7 @@ export function useConnectorPlugin( { type: 'snackbar', } ); - } catch ( error ) { - // A user-initiated cancel of the filesystem credentials dialog - // should silently abort the install without a snackbar. - const message = error instanceof Error ? error.message : ''; - if ( message === 'Filesystem credentials request canceled.' ) { - return; - } + } catch { createErrorNotice( sprintf( /* translators: %s: Name of the connector (e.g. "OpenAI"). */ From 8d3b1c2f7c3e44eb036fa2b401a4bc166c9300ab Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Fri, 15 May 2026 20:44:25 -0700 Subject: [PATCH 05/17] Connectors: Fix AI plugin callout install when FS credentials required The "Install the AI plugin" button in AiPluginCallout had the same silent-failure bug as the connector install: it POSTed directly to the REST plugin endpoint, which rejects the install up front when FS_METHOD is not 'direct' and credentials have not been stored. Reuse the now-exported installPluginViaWpUpdates() helper so the AI plugin install routes through wp.updates.installPlugin() (surfacing the standard "Connection Information" modal) when credentials are required, then activates via REST. The non-FS path is unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) --- routes/connectors-home/ai-plugin-callout.tsx | 38 +++++++++++++++---- .../connectors-home/use-connector-plugin.ts | 4 +- 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/routes/connectors-home/ai-plugin-callout.tsx b/routes/connectors-home/ai-plugin-callout.tsx index aa63a8e02e6a37..1b9a2d70d597a2 100644 --- a/routes/connectors-home/ai-plugin-callout.tsx +++ b/routes/connectors-home/ai-plugin-callout.tsx @@ -17,8 +17,12 @@ import { addQueryArgs } from '@wordpress/url'; /** * Internal dependencies */ -import { getConnectorData } from './default-connectors'; +import { + getConnectorData, + getRequiresFilesystemCredentials, +} from './default-connectors'; import { WpLogoDecoration } from './wp-logo-decoration'; +import { installPluginViaWpUpdates } from './use-connector-plugin'; import type { PluginStatus } from './use-connector-plugin'; @@ -130,12 +134,32 @@ export function AiPluginCallout() { const installPlugin = async () => { setIsBusy( true ); try { - await saveEntityRecord( - 'root', - 'plugin', - { slug: AI_PLUGIN_SLUG, status: 'active' }, - { throwOnError: true } - ); + if ( getRequiresFilesystemCredentials() ) { + // The REST plugin endpoint rejects installs up front when + // FS_METHOD is not 'direct' and credentials have not been + // stored. Route through wp.updates.installPlugin() so the + // standard "Connection Information" modal handles credential + // entry, then activate via REST. + const outcome = + await installPluginViaWpUpdates( AI_PLUGIN_SLUG ); + if ( outcome === 'canceled' ) { + // User closed the credentials modal; abort silently. + return; + } + await saveEntityRecord( + 'root', + 'plugin', + { plugin: AI_PLUGIN_ID, status: 'active' }, + { throwOnError: true } + ); + } else { + await saveEntityRecord( + 'root', + 'plugin', + { slug: AI_PLUGIN_SLUG, status: 'active' }, + { throwOnError: true } + ); + } setJustActivated( true ); createSuccessNotice( __( 'AI plugin installed and activated successfully.' ), diff --git a/routes/connectors-home/use-connector-plugin.ts b/routes/connectors-home/use-connector-plugin.ts index 5bfad106414071..0cd16228f313a4 100644 --- a/routes/connectors-home/use-connector-plugin.ts +++ b/routes/connectors-home/use-connector-plugin.ts @@ -61,9 +61,9 @@ interface WpUpdatesGlobal { * filesystem credentials modal), not an error. Genuine install * failures reject the promise instead. */ -type WpUpdatesInstallOutcome = 'installed' | 'canceled'; +export type WpUpdatesInstallOutcome = 'installed' | 'canceled'; -function installPluginViaWpUpdates( +export function installPluginViaWpUpdates( slug: string ): Promise< WpUpdatesInstallOutcome > { return new Promise( ( resolve, reject ) => { From 675d2eb1e824a7d462172ed541133aa84d8c12a4 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Fri, 15 May 2026 21:23:00 -0700 Subject: [PATCH 06/17] Connectors: Use strict false check for filesystem credentials sentinel request_filesystem_credentials() returns true (no credentials needed), false (needed but not provided), or an array (needed and provided). Only the explicit false sentinel should set filesystemCredentialsRequired, so compare with `false === $stored` instead of `! $stored`. This avoids coercing a (theoretical) empty-array return to "required" and matches the strict-boolean expectation of PHPStan, mirroring the Performance Lab counterpart which already uses the strict comparison. Co-Authored-By: Claude Opus 4.7 (1M context) --- lib/compat/wordpress-7.0/connectors.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compat/wordpress-7.0/connectors.php b/lib/compat/wordpress-7.0/connectors.php index 5ef2409a20f008..d8d3a03b769b8e 100644 --- a/lib/compat/wordpress-7.0/connectors.php +++ b/lib/compat/wordpress-7.0/connectors.php @@ -299,7 +299,7 @@ function _gutenberg_connectors_add_filesystem_data_to_script_module_data( array $stored = request_filesystem_credentials( self_admin_url() ); ob_end_clean(); - $data['filesystemCredentialsRequired'] = ! $stored; + $data['filesystemCredentialsRequired'] = false === $stored; return $data; } add_filter( 'script_module_data_options-connectors-wp-admin', '_gutenberg_connectors_add_filesystem_data_to_script_module_data' ); From 516b74b99c1f37e88424c4ac38a73cf7ad92502a Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Sun, 17 May 2026 21:58:42 -0700 Subject: [PATCH 07/17] Connectors: Fix AiPluginCallout test mock and add FS-credentials coverage The AiPluginCallout test mocked ../default-connectors with only getConnectorData(), so once the component started importing getRequiresFilesystemCredentials() that call was undefined and the "installs the AI plugin using the plugin slug" test failed (the install threw before reaching saveEntityRecord). Add getRequiresFilesystemCredentials() to the mock (defaulting to false) and mock installPluginViaWpUpdates from ../use-connector-plugin, then add companion tests covering the filesystem-credentials path: install routed through wp.updates then activating ai/ai, and a silent abort when the credentials modal is canceled. Co-authored-by: ekamran Co-Authored-By: Claude Opus 4.7 (1M context) --- .../test/ai-plugin-callout.tsx | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/routes/connectors-home/test/ai-plugin-callout.tsx b/routes/connectors-home/test/ai-plugin-callout.tsx index fb6361b029c200..50af7dd98fbbf2 100644 --- a/routes/connectors-home/test/ai-plugin-callout.tsx +++ b/routes/connectors-home/test/ai-plugin-callout.tsx @@ -13,6 +13,8 @@ import { useDispatch, useSelect } from '@wordpress/data'; * Internal dependencies */ import { AiPluginCallout } from '../ai-plugin-callout'; +import { getRequiresFilesystemCredentials } from '../default-connectors'; +import { installPluginViaWpUpdates } from '../use-connector-plugin'; jest.mock( '@wordpress/a11y', () => ( { speak: jest.fn(), @@ -93,6 +95,11 @@ jest.mock( '../default-connectors', () => ( { }, }, } ) ), + getRequiresFilesystemCredentials: jest.fn( () => false ), +} ) ); + +jest.mock( '../use-connector-plugin', () => ( { + installPluginViaWpUpdates: jest.fn(), } ) ); jest.mock( '../wp-logo-decoration', () => ( { @@ -158,6 +165,15 @@ describe( 'AiPluginCallout', () => { mapSelect( () => selectorStore ) ); + ( getRequiresFilesystemCredentials as jest.Mock ).mockReset(); + ( getRequiresFilesystemCredentials as jest.Mock ).mockReturnValue( + false + ); + ( installPluginViaWpUpdates as jest.Mock ).mockReset(); + ( installPluginViaWpUpdates as jest.Mock ).mockResolvedValue( + 'installed' + ); + mockSaveEntityRecord.mockReset(); mockSaveEntityRecord.mockResolvedValue( undefined ); mockCreateSuccessNotice.mockReset(); @@ -198,5 +214,63 @@ describe( 'AiPluginCallout', () => { { throwOnError: true } ); } ); + + expect( installPluginViaWpUpdates ).not.toHaveBeenCalled(); + } ); + + it( 'installs via wp.updates then activates when filesystem credentials are required', async () => { + const user = userEvent.setup(); + + storeState.plugin = undefined; + ( getRequiresFilesystemCredentials as jest.Mock ).mockReturnValue( + true + ); + ( installPluginViaWpUpdates as jest.Mock ).mockResolvedValue( + 'installed' + ); + + render( ); + + await user.click( + screen.getByRole( 'button', { name: 'Install the AI plugin' } ) + ); + + await waitFor( () => { + expect( installPluginViaWpUpdates ).toHaveBeenCalledWith( 'ai' ); + } ); + + await waitFor( () => { + expect( mockSaveEntityRecord ).toHaveBeenCalledWith( + 'root', + 'plugin', + { plugin: 'ai/ai', status: 'active' }, + { throwOnError: true } + ); + } ); + } ); + + it( 'aborts silently when the filesystem credentials modal is canceled', async () => { + const user = userEvent.setup(); + + storeState.plugin = undefined; + ( getRequiresFilesystemCredentials as jest.Mock ).mockReturnValue( + true + ); + ( installPluginViaWpUpdates as jest.Mock ).mockResolvedValue( + 'canceled' + ); + + render( ); + + await user.click( + screen.getByRole( 'button', { name: 'Install the AI plugin' } ) + ); + + await waitFor( () => { + expect( installPluginViaWpUpdates ).toHaveBeenCalledWith( 'ai' ); + } ); + + expect( mockSaveEntityRecord ).not.toHaveBeenCalled(); + expect( mockCreateErrorNotice ).not.toHaveBeenCalled(); } ); } ); From 530755e855a8f31c52deafccaa33d3d4798ab3b1 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Sun, 17 May 2026 23:09:46 -0700 Subject: [PATCH 08/17] Connectors: Use @types/jquery instead of a hand-rolled jQuery shape The wp.updates fallback in use-connector-plugin.ts declared its own minimal `jQuery?: ( target: Document ) => { on, off }` shape. Depend on @types/jquery (pinned to 3.5.34, matching wordpress-develop core) and reuse the canonical JQueryStatic / JQuery.TriggeredEvent types instead of reinventing them. Co-Authored-By: Claude Opus 4.7 (1M context) --- package-lock.json | 18 ++++++++++++++++++ package.json | 1 + routes/connectors-home/use-connector-plugin.ts | 7 ++----- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/package-lock.json b/package-lock.json index 440df02b7068c5..6465b5725c2fc7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -33,6 +33,7 @@ "@inquirer/prompts": "7.2.0", "@octokit/rest": "16.26.0", "@testing-library/jest-dom": "6.9.1", + "@types/jquery": "3.5.34", "@types/node": "^20.19.39", "@types/prettier": "2.4.4", "@types/react": "^18.3.27", @@ -18264,6 +18265,16 @@ "pretty-format": "^29.0.0" } }, + "node_modules/@types/jquery": { + "version": "3.5.34", + "resolved": "https://registry.npmjs.org/@types/jquery/-/jquery-3.5.34.tgz", + "integrity": "sha512-3m3939S3erqmTLJANS/uy0B6V7BorKx7RorcGZVjZ62dF5PAGbKEDZK1CuLtKombJkFA2T1jl8LAIIs7IV6gBQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/sizzle": "*" + } + }, "node_modules/@types/jsdom": { "version": "21.1.7", "resolved": "https://registry.npmjs.org/@types/jsdom/-/jsdom-21.1.7.tgz", @@ -18589,6 +18600,13 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/sizzle": { + "version": "2.3.10", + "resolved": "https://registry.npmjs.org/@types/sizzle/-/sizzle-2.3.10.tgz", + "integrity": "sha512-TC0dmN0K8YcWEAEfiPi5gJP14eJe30TTGjkvek3iM/1NdHHsdCA/Td6GvNndMOo/iSnIsZ4HuuhrYPDAmbxzww==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/sockjs": { "version": "0.3.36", "resolved": "https://registry.npmjs.org/@types/sockjs/-/sockjs-0.3.36.tgz", diff --git a/package.json b/package.json index 173fa51b803541..1c4cb0251430ba 100644 --- a/package.json +++ b/package.json @@ -55,6 +55,7 @@ "@inquirer/prompts": "7.2.0", "@octokit/rest": "16.26.0", "@testing-library/jest-dom": "6.9.1", + "@types/jquery": "3.5.34", "@types/node": "^20.19.39", "@types/prettier": "2.4.4", "@types/react": "^18.3.27", diff --git a/routes/connectors-home/use-connector-plugin.ts b/routes/connectors-home/use-connector-plugin.ts index 0cd16228f313a4..eb6ab11f91cf03 100644 --- a/routes/connectors-home/use-connector-plugin.ts +++ b/routes/connectors-home/use-connector-plugin.ts @@ -38,7 +38,7 @@ interface WpUpdates { } type JQueryHandler = ( - event: unknown, + event: JQuery.TriggeredEvent, response: | WpUpdatesInstallPluginResponse | WpUpdatesInstallPluginErrorResponse @@ -48,10 +48,7 @@ interface WpUpdatesGlobal { wp?: { updates?: WpUpdates; }; - jQuery?: ( target: Document ) => { - on: ( event: string, handler: JQueryHandler ) => unknown; - off: ( event: string, handler: JQueryHandler ) => unknown; - }; + jQuery?: JQueryStatic; } /** From 265ba3f5bf7d0b6b49d02f938cd9b340466c89d4 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 14 Oct 2026 09:54:19 +0000 Subject: [PATCH 09/17] Connectors: Detect filesystem credentials need from REST fs_unavailable error Instead of computing `filesystemCredentialsRequired` on the server and exposing it through script module data, attempt the standard REST plugin install first and fall back to `wp.updates.installPlugin()` only when the endpoint rejects with the `fs_unavailable` error code. The REST response becomes the single source of truth, and the PHP flag is removed. The Connectors screen still enqueues the `updates` script and prints the filesystem credentials modal so the fallback can show it. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FVht4racQmKuYmELHoLXdx --- lib/compat/plugin/connectors.php | 33 -------- routes/connectors-home/ai-plugin-callout.tsx | 40 +++++----- routes/connectors-home/default-connectors.tsx | 6 -- .../test/ai-plugin-callout.jsdom.test.tsx | 76 ++++++++++++------- .../connectors-home/use-connector-plugin.ts | 49 +++++++----- 5 files changed, 101 insertions(+), 103 deletions(-) diff --git a/lib/compat/plugin/connectors.php b/lib/compat/plugin/connectors.php index 5ffd6956b94f84..bffc24cf276921 100644 --- a/lib/compat/plugin/connectors.php +++ b/lib/compat/plugin/connectors.php @@ -67,36 +67,3 @@ function _gutenberg_connectors_print_filesystem_credentials_modal(): void { wp_print_request_filesystem_credentials_modal(); wp_print_admin_notice_templates(); } - -/** - * Exposes whether the current request can install plugins directly to the - * Connectors script module. - * - * When the filesystem method is anything other than `direct` and stored - * credentials are not yet available, the REST plugin endpoint will reject - * an install attempt up front. Surfacing this state to the client lets the - * React layer pre-emptively route through `wp.updates.installPlugin()`, - * which displays the standard filesystem credentials modal. - * - * @access private - * - * @param array $data Existing script module data. - * @return array Script module data with the filesystem flag added. - */ -function _gutenberg_connectors_add_filesystem_data_to_script_module_data( array $data ): array { - require_once ABSPATH . 'wp-admin/includes/file.php'; - - $method = get_filesystem_method(); - if ( 'direct' === $method ) { - $data['filesystemCredentialsRequired'] = false; - return $data; - } - - ob_start(); - $stored = request_filesystem_credentials( self_admin_url() ); - ob_end_clean(); - - $data['filesystemCredentialsRequired'] = false === $stored; - return $data; -} -add_filter( 'script_module_data_options-connectors-wp-admin', '_gutenberg_connectors_add_filesystem_data_to_script_module_data' ); diff --git a/routes/connectors-home/ai-plugin-callout.tsx b/routes/connectors-home/ai-plugin-callout.tsx index baf96e38a68c03..2bf20a5ef5d93e 100644 --- a/routes/connectors-home/ai-plugin-callout.tsx +++ b/routes/connectors-home/ai-plugin-callout.tsx @@ -10,12 +10,12 @@ import { import { __ } from '@wordpress/i18n'; import { store as noticesStore } from '@wordpress/notices'; import { addQueryArgs } from '@wordpress/url'; -import { - getConnectorData, - getRequiresFilesystemCredentials, -} from './default-connectors'; +import { getConnectorData } from './default-connectors'; import { WpLogoDecoration } from './wp-logo-decoration'; -import { installPluginViaWpUpdates } from './use-connector-plugin'; +import { + installPluginViaWpUpdates, + isFilesystemUnavailableError, +} from './use-connector-plugin'; import type { PluginStatus } from './use-connector-plugin'; const AI_PLUGIN_SLUG = 'ai'; @@ -125,12 +125,23 @@ export function AiPluginCallout() { const installPlugin = async () => { setIsBusy( true ); try { - if ( getRequiresFilesystemCredentials() ) { - // The REST plugin endpoint rejects installs up front when - // FS_METHOD is not 'direct' and credentials have not been - // stored. Route through wp.updates.installPlugin() so the - // standard "Connection Information" modal handles credential - // entry, then activate via REST. + 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 ); if ( outcome === 'canceled' ) { @@ -143,13 +154,6 @@ export function AiPluginCallout() { { plugin: AI_PLUGIN_ID, status: 'active' }, { throwOnError: true } ); - } else { - await saveEntityRecord( - 'root', - 'plugin', - { slug: AI_PLUGIN_SLUG, status: 'active' }, - { throwOnError: true } - ); } setJustActivated( true ); createSuccessNotice( diff --git a/routes/connectors-home/default-connectors.tsx b/routes/connectors-home/default-connectors.tsx index 868d024ad29a12..abe4ed52191a28 100644 --- a/routes/connectors-home/default-connectors.tsx +++ b/routes/connectors-home/default-connectors.tsx @@ -40,7 +40,6 @@ interface ConnectorData { interface ConnectorScriptModuleData { connectors?: Record< string, ConnectorData >; isFileModDisabled?: boolean; - filesystemCredentialsRequired?: boolean; } function getConnectorScriptModuleData(): ConnectorScriptModuleData { @@ -66,10 +65,6 @@ export function getIsFileModDisabled(): boolean { return !! getConnectorScriptModuleData().isFileModDisabled; } -export function getRequiresFilesystemCredentials(): boolean { - return !! getConnectorScriptModuleData().filesystemCredentialsRequired; -} - const CONNECTOR_LOGOS: Record< string, React.ComponentType > = { google: GeminiLogo, openai: OpenAILogo, @@ -218,7 +213,6 @@ function ApiKeyConnector( { isActivated: plugin?.isActivated, keySource: auth?.keySource, initialIsConnected: auth?.isConnected, - requiresFilesystemCredentials: getRequiresFilesystemCredentials(), } ); const isExternallyConfigured = keySource === 'env' || keySource === 'constant'; 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 bd5341c02b532d..b523bdef1368f1 100644 --- a/routes/connectors-home/test/ai-plugin-callout.jsdom.test.tsx +++ b/routes/connectors-home/test/ai-plugin-callout.jsdom.test.tsx @@ -4,7 +4,6 @@ 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 { getRequiresFilesystemCredentials } from '../default-connectors'; import { installPluginViaWpUpdates } from '../use-connector-plugin'; vi.mock( @@ -111,17 +110,13 @@ vi.mock( }, }, } ) ), - getRequiresFilesystemCredentials: vi.fn( () => false ), } ) as unknown as typeof import( '../default-connectors' ) ); -vi.mock( - import( '../use-connector-plugin' ), - () => - ( { - installPluginViaWpUpdates: vi.fn(), - } ) as unknown as typeof import( '../use-connector-plugin' ) -); +vi.mock( import( '../use-connector-plugin' ), async ( importOriginal ) => ( { + ...( await importOriginal() ), + installPluginViaWpUpdates: vi.fn(), +} ) ); vi.mock( import( '../wp-logo-decoration' ), @@ -192,14 +187,8 @@ describe( 'AiPluginCallout', () => { mapSelect( () => selectorStore ) ); - vi.mocked( getRequiresFilesystemCredentials ).mockReset(); - vi.mocked( getRequiresFilesystemCredentials ).mockReturnValue( - false - ); vi.mocked( installPluginViaWpUpdates ).mockReset(); - vi.mocked( installPluginViaWpUpdates ).mockResolvedValue( - 'installed' - ); + vi.mocked( installPluginViaWpUpdates ).mockResolvedValue( 'installed' ); mockSaveEntityRecord.mockReset(); mockSaveEntityRecord.mockResolvedValue( undefined ); @@ -245,16 +234,23 @@ describe( 'AiPluginCallout', () => { expect( installPluginViaWpUpdates ).not.toHaveBeenCalled(); } ); - it( 'installs via wp.updates then activates when filesystem credentials are required', async () => { + it( 'falls back to wp.updates then activates when the REST install reports fs_unavailable', async () => { const user = userEvent.setup(); storeState.plugin = undefined; - vi.mocked( getRequiresFilesystemCredentials ).mockReturnValue( - true - ); - vi.mocked( installPluginViaWpUpdates ).mockResolvedValue( - 'installed' + // 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( ); @@ -274,18 +270,16 @@ describe( 'AiPluginCallout', () => { { throwOnError: true } ); } ); + + expect( mockCreateErrorNotice ).not.toHaveBeenCalled(); } ); it( 'aborts silently when the filesystem credentials modal is canceled', async () => { const user = userEvent.setup(); storeState.plugin = undefined; - vi.mocked( getRequiresFilesystemCredentials ).mockReturnValue( - true - ); - vi.mocked( installPluginViaWpUpdates ).mockResolvedValue( - 'canceled' - ); + mockSaveEntityRecord.mockRejectedValue( { code: 'fs_unavailable' } ); + vi.mocked( installPluginViaWpUpdates ).mockResolvedValue( 'canceled' ); render( ); @@ -297,7 +291,31 @@ describe( 'AiPluginCallout', () => { expect( installPluginViaWpUpdates ).toHaveBeenCalledWith( 'ai' ); } ); - expect( mockSaveEntityRecord ).not.toHaveBeenCalled(); + // 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 6c597398bb076c..6436eb98cd5739 100644 --- a/routes/connectors-home/use-connector-plugin.ts +++ b/routes/connectors-home/use-connector-plugin.ts @@ -22,7 +22,6 @@ interface UseConnectorPluginOptions { isActivated?: boolean; keySource?: ApiKeySource; initialIsConnected?: boolean; - requiresFilesystemCredentials?: boolean; } interface WpUpdatesInstallPluginResponse { @@ -43,8 +42,7 @@ interface WpUpdates { type JQueryHandler = ( event: unknown, response: - | WpUpdatesInstallPluginResponse - | WpUpdatesInstallPluginErrorResponse + WpUpdatesInstallPluginResponse | WpUpdatesInstallPluginErrorResponse ) => void; interface WpUpdatesGlobal { @@ -57,6 +55,20 @@ interface WpUpdatesGlobal { }; } +/** + * 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()`. * @@ -155,7 +167,6 @@ export function useConnectorPlugin( { isActivated, keySource = 'none', initialIsConnected = false, - requiresFilesystemCredentials = false, }: UseConnectorPluginOptions ): UseConnectorPluginReturn { const [ isExpanded, setIsExpanded ] = useState( false ); const [ isBusy, setIsBusy ] = useState( false ); @@ -358,12 +369,23 @@ export function useConnectorPlugin( { } setIsBusy( true ); try { - if ( requiresFilesystemCredentials ) { - // The REST plugin endpoint rejects installs up front when - // FS_METHOD is not 'direct' and credentials have not been - // stored. Route through wp.updates.installPlugin() so the - // standard "Connection Information" modal handles credential - // entry, then activate via REST. + 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 ); if ( outcome === 'canceled' ) { // User closed the credentials modal; abort silently. @@ -383,13 +405,6 @@ export function useConnectorPlugin( { 'plugin', pluginBasename, ] ); - } else { - await saveEntityRecord( - 'root', - 'plugin', - { slug: pluginSlug, status: 'active' }, - { throwOnError: true } - ); } setPluginStatusOverride( 'active' ); // Re-fetch settings since the new plugin may register new settings. From cc3794704fc71243077cde33bf620ad71219ed95 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 14 Oct 2026 10:18:16 +0000 Subject: [PATCH 10/17] Add backport changelog entry for wordpress-develop#13953 Co-Authored-By: Claude Opus 5.5 (1M context) Co-authored-by: t-hamano <54422211+t-hamano@users.noreply.github.com> Claude-Session: https://claude.ai/code/session_01FVht4racQmKuYmELHoLXdx --- backport-changelog/7.2/13953.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 backport-changelog/7.2/13953.md diff --git a/backport-changelog/7.2/13953.md b/backport-changelog/7.2/13953.md new file mode 100644 index 00000000000000..205ce3e9ec7a4c --- /dev/null +++ b/backport-changelog/7.2/13953.md @@ -0,0 +1,3 @@ +https://github.com/WordPress/wordpress-develop/pull/13953 + +* https://github.com/WordPress/gutenberg/pull/78367 From 515d920305216b1d5fc223f22a4acb2e56870013 Mon Sep 17 00:00:00 2001 From: Aki Hamano <54422211+t-hamano@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:10:44 +0900 Subject: [PATCH 11/17] Remove unnecessary require_once statements --- lib/compat/plugin/connectors.php | 3 --- 1 file changed, 3 deletions(-) diff --git a/lib/compat/plugin/connectors.php b/lib/compat/plugin/connectors.php index 36e9175cca4d7a..6bd4a4411bc7bf 100644 --- a/lib/compat/plugin/connectors.php +++ b/lib/compat/plugin/connectors.php @@ -61,9 +61,6 @@ function _gutenberg_connectors_load_screen(): void { * @access private */ function _gutenberg_connectors_print_filesystem_credentials_modal(): void { - require_once ABSPATH . 'wp-admin/includes/file.php'; - require_once ABSPATH . 'wp-admin/includes/template.php'; - wp_print_request_filesystem_credentials_modal(); wp_print_admin_notice_templates(); } From 2a80081788d2cbcd94eb4b38d30b8e19553367a6 Mon Sep 17 00:00:00 2001 From: Aki Hamano <54422211+t-hamano@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:23:27 +0900 Subject: [PATCH 12/17] =?UTF-8?q?Fix=20install=20button=20stuck=20on=20"In?= =?UTF-8?q?stalling=E2=80=A6"=20on=20invalid=20admin-ajax=20responses?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Aki Hamano <54422211+t-hamano@users.noreply.github.com> --- routes/connectors-home/use-connector-plugin.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/routes/connectors-home/use-connector-plugin.ts b/routes/connectors-home/use-connector-plugin.ts index 6436eb98cd5739..37ff886ab7f929 100644 --- a/routes/connectors-home/use-connector-plugin.ts +++ b/routes/connectors-home/use-connector-plugin.ts @@ -36,7 +36,9 @@ interface WpUpdatesInstallPluginErrorResponse { } interface WpUpdates { - installPlugin: ( args: { slug: string } ) => void; + installPlugin: ( args: { slug: string } ) => { + fail?: ( callback: ( response: unknown ) => void ) => void; + } | void; } type JQueryHandler = ( @@ -132,7 +134,13 @@ export function installPluginViaWpUpdates( jq( document ).on( 'wp-plugin-install-error', onError ); jq( document ).on( 'credential-modal-cancel', onCancel ); - updates.installPlugin( { slug } ); + const request = updates.installPlugin( { slug } ); + request?.fail?.( ( response ) => { + if ( typeof response !== 'object' || response === null ) { + cleanup(); + reject( new Error( 'Install failed.' ) ); + } + } ); } ); } From a55a646f405497218bceda9e19bfbabdfcf2a3c8 Mon Sep 17 00:00:00 2001 From: Aki Hamano <54422211+t-hamano@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:33:08 +0900 Subject: [PATCH 13/17] Open filesystem credentials modal before install and catch invalid responses Co-authored-by: Aki Hamano <54422211+t-hamano@users.noreply.github.com> --- .../connectors-home/use-connector-plugin.ts | 65 +++++++++++++++---- 1 file changed, 54 insertions(+), 11 deletions(-) diff --git a/routes/connectors-home/use-connector-plugin.ts b/routes/connectors-home/use-connector-plugin.ts index 37ff886ab7f929..a15c0ec2f126d5 100644 --- a/routes/connectors-home/use-connector-plugin.ts +++ b/routes/connectors-home/use-connector-plugin.ts @@ -36,9 +36,10 @@ interface WpUpdatesInstallPluginErrorResponse { } interface WpUpdates { - installPlugin: ( args: { slug: string } ) => { - fail?: ( callback: ( response: unknown ) => void ) => void; - } | void; + installPlugin: ( args: { slug: string } ) => void; + maybeRequestFilesystemCredentials?: ( event: { + target: Element | null; + } ) => void; } type JQueryHandler = ( @@ -47,13 +48,25 @@ type JQueryHandler = ( 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 ) => void; - off: ( events: string, handler: JQueryHandler ) => void; + on: ( + events: string, + handler: JQueryHandler | JQueryAjaxCompleteHandler + ) => void; + off: ( + events: string, + handler: JQueryHandler | JQueryAjaxCompleteHandler + ) => void; }; } @@ -101,6 +114,7 @@ export function installPluginViaWpUpdates( 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 ) => { @@ -129,18 +143,47 @@ export function installPluginViaWpUpdates( 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 ); - const request = updates.installPlugin( { slug } ); - request?.fail?.( ( response ) => { - if ( typeof response !== 'object' || response === null ) { - cleanup(); - reject( new Error( 'Install failed.' ) ); - } + // 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: document.activeElement, } ); + updates.installPlugin( { slug } ); } ); } From 49ca8c3d102d86d1e9cbd1a6ebbe0279c7f91714 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 03:52:00 +0000 Subject: [PATCH 14/17] Pass the install button to the credentials modal instead of reading the active element Co-authored-by: t-hamano <54422211+t-hamano@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011g9URwXY34pb67XjPhYPjQ --- routes/connectors-home/ai-plugin-callout.tsx | 16 ++++++--- routes/connectors-home/default-connectors.tsx | 8 +++-- .../test/ai-plugin-callout.jsdom.test.tsx | 10 ++++-- .../connectors-home/use-connector-plugin.ts | 33 +++++++++++++++---- 4 files changed, 52 insertions(+), 15 deletions(-) diff --git a/routes/connectors-home/ai-plugin-callout.tsx b/routes/connectors-home/ai-plugin-callout.tsx index 2bf20a5ef5d93e..6606df2f45aa53 100644 --- a/routes/connectors-home/ai-plugin-callout.tsx +++ b/routes/connectors-home/ai-plugin-callout.tsx @@ -16,7 +16,10 @@ import { installPluginViaWpUpdates, isFilesystemUnavailableError, } from './use-connector-plugin'; -import type { PluginStatus } 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'; @@ -122,7 +125,10 @@ 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 { try { @@ -142,8 +148,10 @@ export function AiPluginCallout() { if ( ! isFilesystemUnavailableError( error ) ) { throw error; } - const outcome = - await installPluginViaWpUpdates( AI_PLUGIN_SLUG ); + const outcome = await installPluginViaWpUpdates( + AI_PLUGIN_SLUG, + trigger + ); if ( outcome === 'canceled' ) { // User closed the credentials modal; abort silently. return; 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 b523bdef1368f1..7a663ca5a0a909 100644 --- a/routes/connectors-home/test/ai-plugin-callout.jsdom.test.tsx +++ b/routes/connectors-home/test/ai-plugin-callout.jsdom.test.tsx @@ -259,7 +259,10 @@ describe( 'AiPluginCallout', () => { ); await waitFor( () => { - expect( installPluginViaWpUpdates ).toHaveBeenCalledWith( 'ai' ); + expect( installPluginViaWpUpdates ).toHaveBeenCalledWith( + 'ai', + expect.any( HTMLButtonElement ) + ); } ); await waitFor( () => { @@ -288,7 +291,10 @@ describe( 'AiPluginCallout', () => { ); await waitFor( () => { - expect( installPluginViaWpUpdates ).toHaveBeenCalledWith( 'ai' ); + expect( installPluginViaWpUpdates ).toHaveBeenCalledWith( + 'ai', + expect.any( HTMLButtonElement ) + ); } ); // Only the initial REST install attempt ran: no activate follow-up diff --git a/routes/connectors-home/use-connector-plugin.ts b/routes/connectors-home/use-connector-plugin.ts index a15c0ec2f126d5..18e8cb8ba20fe8 100644 --- a/routes/connectors-home/use-connector-plugin.ts +++ b/routes/connectors-home/use-connector-plugin.ts @@ -93,8 +93,21 @@ export function isFilesystemUnavailableError( error: unknown ): boolean { */ 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 + slug: string, + trigger?: Element | null ): Promise< WpUpdatesInstallOutcome > { return new Promise( ( resolve, reject ) => { const w = window as unknown as WpUpdatesGlobal; @@ -181,7 +194,7 @@ export function installPluginViaWpUpdates( // Plugins > Add Plugin does. The modal then opens without an error, // and focus returns to the install button when it closes. updates.maybeRequestFilesystemCredentials?.( { - target: document.activeElement, + target: trigger ?? null, } ); updates.installPlugin( { slug } ); } ); @@ -199,7 +212,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 >; @@ -414,10 +427,13 @@ 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 { try { @@ -437,7 +453,10 @@ export function useConnectorPlugin( { if ( ! isFilesystemUnavailableError( error ) ) { throw error; } - const outcome = await installPluginViaWpUpdates( pluginSlug ); + const outcome = await installPluginViaWpUpdates( + pluginSlug, + trigger + ); if ( outcome === 'canceled' ) { // User closed the credentials modal; abort silently. return; @@ -536,12 +555,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; From 5c827e9ed2396aef32126d79c60aa5ba97ce34b9 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 04:03:08 +0000 Subject: [PATCH 15/17] Update the backport changelog to the new core PR Co-authored-by: t-hamano <54422211+t-hamano@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011g9URwXY34pb67XjPhYPjQ --- backport-changelog/7.2/{13953.md => 15889.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename backport-changelog/7.2/{13953.md => 15889.md} (100%) diff --git a/backport-changelog/7.2/13953.md b/backport-changelog/7.2/15889.md similarity index 100% rename from backport-changelog/7.2/13953.md rename to backport-changelog/7.2/15889.md From 987e3efa4119426e02bf94dd64a8058ed979a677 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 04:03:30 +0000 Subject: [PATCH 16/17] Point the backport changelog entry to the new core PR Co-authored-by: t-hamano <54422211+t-hamano@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011g9URwXY34pb67XjPhYPjQ --- backport-changelog/7.2/15889.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backport-changelog/7.2/15889.md b/backport-changelog/7.2/15889.md index 205ce3e9ec7a4c..c6c8d957248b3b 100644 --- a/backport-changelog/7.2/15889.md +++ b/backport-changelog/7.2/15889.md @@ -1,3 +1,3 @@ -https://github.com/WordPress/wordpress-develop/pull/13953 +https://github.com/WordPress/wordpress-develop/pull/15889 * https://github.com/WordPress/gutenberg/pull/78367 From 05608352e4bf17d794201153a879a118ea71f726 Mon Sep 17 00:00:00 2001 From: Peter Wilson Date: Mon, 16 Nov 2026 08:52:27 +1100 Subject: [PATCH 17/17] Follow inline docs style-guide for multiline comemnts. --- routes/connectors-home/ai-plugin-callout.tsx | 20 +++++--- .../test/ai-plugin-callout.jsdom.test.tsx | 12 +++-- .../connectors-home/use-connector-plugin.ts | 50 +++++++++++-------- 3 files changed, 50 insertions(+), 32 deletions(-) diff --git a/routes/connectors-home/ai-plugin-callout.tsx b/routes/connectors-home/ai-plugin-callout.tsx index 6606df2f45aa53..eba2a1023ee155 100644 --- a/routes/connectors-home/ai-plugin-callout.tsx +++ b/routes/connectors-home/ai-plugin-callout.tsx @@ -126,8 +126,10 @@ export function AiPluginCallout() { useDispatch( noticesStore ); const installPlugin = async ( event: InstallButtonClickEvent ) => { - // `currentTarget` is only set while the event is being handled, so - // read it before the first `await`. + /* + * `currentTarget` is only set while the event is being handled, so + * read it before the first `await`. + */ const trigger = event.currentTarget; setIsBusy( true ); try { @@ -139,12 +141,14 @@ export function AiPluginCallout() { { 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. + /* + * 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; } 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 7a663ca5a0a909..130f5aeecfc17f 100644 --- a/routes/connectors-home/test/ai-plugin-callout.jsdom.test.tsx +++ b/routes/connectors-home/test/ai-plugin-callout.jsdom.test.tsx @@ -238,8 +238,10 @@ describe( 'AiPluginCallout', () => { const user = userEvent.setup(); storeState.plugin = undefined; - // The REST install (using `slug`) is rejected up front; the - // subsequent activate (using `plugin`) succeeds. + /* + * The REST install (using `slug`) is rejected up front; the + * subsequent activate (using `plugin`) succeeds. + */ mockSaveEntityRecord.mockImplementation( ( _kind: string, @@ -297,8 +299,10 @@ describe( 'AiPluginCallout', () => { ); } ); - // Only the initial REST install attempt ran: no activate follow-up - // and no error notice. + /* + * Only the initial REST install attempt ran: no activate follow-up + * and no error notice. + */ expect( mockSaveEntityRecord ).toHaveBeenCalledTimes( 1 ); expect( mockCreateErrorNotice ).not.toHaveBeenCalled(); } ); diff --git a/routes/connectors-home/use-connector-plugin.ts b/routes/connectors-home/use-connector-plugin.ts index 18e8cb8ba20fe8..4f086fdc74ad77 100644 --- a/routes/connectors-home/use-connector-plugin.ts +++ b/routes/connectors-home/use-connector-plugin.ts @@ -118,11 +118,13 @@ export function installPluginViaWpUpdates( 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. + /* + * 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 ); @@ -156,10 +158,12 @@ export function installPluginViaWpUpdates( 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…". + /* + * 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, @@ -190,9 +194,11 @@ export function installPluginViaWpUpdates( 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. + /* + * 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, } ); @@ -431,8 +437,10 @@ export function useConnectorPlugin( { if ( ! pluginSlug ) { return; } - // `currentTarget` is only set while the event is being handled, so - // read it before the first `await`. + /* + * `currentTarget` is only set while the event is being handled, so + * read it before the first `await`. + */ const trigger = event?.currentTarget; setIsBusy( true ); try { @@ -444,12 +452,14 @@ export function useConnectorPlugin( { { 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. + /* + * 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; }