From ac97a1e1832cc8f58be6157a16126aa6049d6e27 Mon Sep 17 00:00:00 2001 From: orakili Date: Fri, 29 Nov 2024 09:49:04 +0000 Subject: [PATCH 1/5] feat: add basic reliefweb_ai module and alter the chat form to ask anonymous users to log in or register to use the functionality. Refs: RW-1134 --- config/core.extension.yml | 1 + config/reliefweb_ai.settings.yml | 8 +++ html/modules/custom/reliefweb_ai/README.md | 8 +++ .../config/install/reliefweb_ai.settings.yml | 7 ++ .../config/schema/reliefweb_ai.schema.yml | 18 ++++++ .../custom/reliefweb_ai/reliefweb_ai.info.yml | 7 ++ .../custom/reliefweb_ai/reliefweb_ai.module | 64 +++++++++++++++++++ 7 files changed, 113 insertions(+) create mode 100644 config/reliefweb_ai.settings.yml create mode 100644 html/modules/custom/reliefweb_ai/README.md create mode 100644 html/modules/custom/reliefweb_ai/config/install/reliefweb_ai.settings.yml create mode 100644 html/modules/custom/reliefweb_ai/config/schema/reliefweb_ai.schema.yml create mode 100644 html/modules/custom/reliefweb_ai/reliefweb_ai.info.yml create mode 100644 html/modules/custom/reliefweb_ai/reliefweb_ai.module diff --git a/config/core.extension.yml b/config/core.extension.yml index d7db6a7ba..fbc25c75b 100644 --- a/config/core.extension.yml +++ b/config/core.extension.yml @@ -70,6 +70,7 @@ module: path: 0 path_alias: 0 redirect: 0 + reliefweb_ai: 0 reliefweb_analytics: 0 reliefweb_api: 0 reliefweb_bookmarks: 0 diff --git a/config/reliefweb_ai.settings.yml b/config/reliefweb_ai.settings.yml new file mode 100644 index 000000000..433d1265f --- /dev/null +++ b/config/reliefweb_ai.settings.yml @@ -0,0 +1,8 @@ +_core: + default_config_hash: nHU5kwKkXn_06ta7EBLeQ5LzFi6l-SPQww_lfzgLNrs +ocha_ai_chat: + allow_for_anonymous: false + login_instructions_replace: false + login_instructions: | +

The use of Ask ReliefWeb requires an account on ReliefWeb.

+

Please login or create a new account.

diff --git a/html/modules/custom/reliefweb_ai/README.md b/html/modules/custom/reliefweb_ai/README.md new file mode 100644 index 000000000..bc84b3483 --- /dev/null +++ b/html/modules/custom/reliefweb_ai/README.md @@ -0,0 +1,8 @@ +ReliefWeb AI +============ + +AI usage for ReliefWeb. + +## AI chat + +Currently this module simply alters the chat form to display the chat popup to anonymous users but asking them to log in or register an account to use the chat. This behavior can be controller via the configuration of this module. diff --git a/html/modules/custom/reliefweb_ai/config/install/reliefweb_ai.settings.yml b/html/modules/custom/reliefweb_ai/config/install/reliefweb_ai.settings.yml new file mode 100644 index 000000000..82ce61ec4 --- /dev/null +++ b/html/modules/custom/reliefweb_ai/config/install/reliefweb_ai.settings.yml @@ -0,0 +1,7 @@ +ocha_ai_chat: + allow_for_anonymous: false + login_instructions_replace: false + login_instructions: | +

The use of Ask ReliefWeb requires an account on ReliefWeb.

+

Please login or create a new account.

+ diff --git a/html/modules/custom/reliefweb_ai/config/schema/reliefweb_ai.schema.yml b/html/modules/custom/reliefweb_ai/config/schema/reliefweb_ai.schema.yml new file mode 100644 index 000000000..faa998135 --- /dev/null +++ b/html/modules/custom/reliefweb_ai/config/schema/reliefweb_ai.schema.yml @@ -0,0 +1,18 @@ +reliefweb_ai.settings: + type: config_object + label: 'ReliefWeb AI settings.' + mapping: + ocha_ai_chat: + type: mapping + label: 'Settings for the OCHA AI chat.' + mapping: + allow_for_anonymous: + type: boolean + label: 'Allow anonymous user to access the chat.' + login_instructions_replace: + type: boolean + label: 'If TRUE, replace the chat instructions or otherwise append the login instructions.' + login_instructions: + type: text + label: 'Login or register instructions for anonymous users.' + diff --git a/html/modules/custom/reliefweb_ai/reliefweb_ai.info.yml b/html/modules/custom/reliefweb_ai/reliefweb_ai.info.yml new file mode 100644 index 000000000..6badfc6b5 --- /dev/null +++ b/html/modules/custom/reliefweb_ai/reliefweb_ai.info.yml @@ -0,0 +1,7 @@ +type: module +name: ReliefWeb AI +description: 'AI usage for ReliefWeb' +package: reliefweb +core_version_requirement: ^10 +dependencies: + - drupal:ocha_ai diff --git a/html/modules/custom/reliefweb_ai/reliefweb_ai.module b/html/modules/custom/reliefweb_ai/reliefweb_ai.module new file mode 100644 index 000000000..fb384b84b --- /dev/null +++ b/html/modules/custom/reliefweb_ai/reliefweb_ai.module @@ -0,0 +1,64 @@ +isAnonymous() || $config->get('ocha_ai_chat.allow_for_anonymous') === TRUE) { + return; + } + + $login_instructions = $config->get('ocha_ai_chat.login_instructions') ?? ''; + + // Check whether we are requested to replace the instructions or append the + // login instructions. + $replace = $config->get('ocha_ai_chat.login_instructions_replace') === TRUE || !isset($form['chat']['content']); + + if ($replace) { + $instructions = $login_instructions; + } + else { + // We cannot just append the instructions to the current ones because of + // the text format may include sanitation that removes the target + // attributes. We indeed need to preserve those attributes in the login + // instructions so the login and register links open in parent window + // and not in the chat iframe. + // So first we format the current instructions and then append the login + // ones. + $text = $form['chat']['content']['#text'] ?? ''; + $format = $form['chat']['content']['#format'] ?? 'markdown_editor'; + $instructions = (string) check_markup($text, $format); + $instructions .= $login_instructions; + } + + // Replace the instructions with a simple markup render element. + $form['chat']['content'] = [ + '#type' => 'markup', + '#markup' => $instructions, + '#prefix' => '
', + '#suffix' => '
', + ]; + + // Disable or hide the reset of the form. + foreach (Element::children($form['chat']) as $key) { + if ($key !== 'content') { + $form['chat'][$key]['#access'] = FALSE; + } + } + foreach (Element::children($form) as $key) { + if ($key !== 'chat') { + $form[$key]['#disabled'] = TRUE; + } + } +} From 0032ab0a7541643416e9aa35686b201f3b46a116 Mon Sep 17 00:00:00 2001 From: orakili Date: Fri, 29 Nov 2024 09:49:58 +0000 Subject: [PATCH 2/5] chore: allow anonymous users to access the chat popup Refs: RW-1134 --- config/user.role.anonymous.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/config/user.role.anonymous.yml b/config/user.role.anonymous.yml index fce92c9f5..6ec936568 100644 --- a/config/user.role.anonymous.yml +++ b/config/user.role.anonymous.yml @@ -4,6 +4,7 @@ status: true dependencies: module: - media + - ocha_ai_chat - system _core: default_config_hash: j5zLMOdJBqC0bMvSdth5UebkprJB8g_2FXHqhfpJzow @@ -13,4 +14,5 @@ weight: 0 is_admin: false permissions: - 'access content' + - 'access ocha ai chat' - 'view media' From d9f39a14230503c2263bd7e7fed073ad9101fdc8 Mon Sep 17 00:00:00 2001 From: orakili Date: Tue, 3 Dec 2024 07:21:45 +0000 Subject: [PATCH 3/5] feat: add some caching to chat form, consolidate messages shown when form is disabled and add destination to the login to redirect to document page. Refs: RW-1134 --- config/reliefweb_ai.settings.yml | 6 +- .../config/install/reliefweb_ai.settings.yml | 4 +- .../config/schema/reliefweb_ai.schema.yml | 4 +- .../custom/reliefweb_ai/reliefweb_ai.module | 164 ++++++++++++++---- .../reliefweb_ai/reliefweb_ai.services.yml | 6 + .../OchaAiChatCacheSubscriber.php | 56 ++++++ .../src/OchaAiChatPopupBlockHandler.php | 37 ++++ .../reliefweb_entities.module | 91 ---------- 8 files changed, 233 insertions(+), 135 deletions(-) create mode 100644 html/modules/custom/reliefweb_ai/reliefweb_ai.services.yml create mode 100644 html/modules/custom/reliefweb_ai/src/EventSubscriber/OchaAiChatCacheSubscriber.php create mode 100644 html/modules/custom/reliefweb_ai/src/OchaAiChatPopupBlockHandler.php diff --git a/config/reliefweb_ai.settings.yml b/config/reliefweb_ai.settings.yml index 433d1265f..6d460a57f 100644 --- a/config/reliefweb_ai.settings.yml +++ b/config/reliefweb_ai.settings.yml @@ -1,8 +1,8 @@ _core: - default_config_hash: nHU5kwKkXn_06ta7EBLeQ5LzFi6l-SPQww_lfzgLNrs + default_config_hash: fU8Wp0OCsudl5x0QSV_mUWWt2KbQuzhVwEB-o9A8peg ocha_ai_chat: allow_for_anonymous: false - login_instructions_replace: false + instructions_replace: false login_instructions: |

The use of Ask ReliefWeb requires an account on ReliefWeb.

-

Please login or create a new account.

+

Please login or create a new account.

diff --git a/html/modules/custom/reliefweb_ai/config/install/reliefweb_ai.settings.yml b/html/modules/custom/reliefweb_ai/config/install/reliefweb_ai.settings.yml index 82ce61ec4..acee1fe5c 100644 --- a/html/modules/custom/reliefweb_ai/config/install/reliefweb_ai.settings.yml +++ b/html/modules/custom/reliefweb_ai/config/install/reliefweb_ai.settings.yml @@ -1,7 +1,7 @@ ocha_ai_chat: allow_for_anonymous: false - login_instructions_replace: false + instructions_replace: false login_instructions: |

The use of Ask ReliefWeb requires an account on ReliefWeb.

-

Please login or create a new account.

+

Please login or create a new account.

diff --git a/html/modules/custom/reliefweb_ai/config/schema/reliefweb_ai.schema.yml b/html/modules/custom/reliefweb_ai/config/schema/reliefweb_ai.schema.yml index faa998135..6bacc5ebc 100644 --- a/html/modules/custom/reliefweb_ai/config/schema/reliefweb_ai.schema.yml +++ b/html/modules/custom/reliefweb_ai/config/schema/reliefweb_ai.schema.yml @@ -9,9 +9,9 @@ reliefweb_ai.settings: allow_for_anonymous: type: boolean label: 'Allow anonymous user to access the chat.' - login_instructions_replace: + instructions_replace: type: boolean - label: 'If TRUE, replace the chat instructions or otherwise append the login instructions.' + label: 'If TRUE, replace the chat instructions when the chat is disabled (error, anonymous access etc.), otherwise append the extra instructions.' login_instructions: type: text label: 'Login or register instructions for anonymous users.' diff --git a/html/modules/custom/reliefweb_ai/reliefweb_ai.module b/html/modules/custom/reliefweb_ai/reliefweb_ai.module index fb384b84b..98710395a 100644 --- a/html/modules/custom/reliefweb_ai/reliefweb_ai.module +++ b/html/modules/custom/reliefweb_ai/reliefweb_ai.module @@ -5,60 +5,150 @@ * ReliefWeb AI module file. */ +use Drupal\Component\Utility\UrlHelper; +use Drupal\Core\Block\BlockPluginInterface; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Render\Element; +use Drupal\reliefweb_ai\OchaAiChatPopupBlockHandler; /** - * Implements hook_form_FORM_ID_alter(). + * Implements hook_form_FORM_ID_alter() for `ocha_ai_chat_chat_form`. */ function reliefweb_ai_form_ocha_ai_chat_chat_form_alter(array &$form, FormStateInterface $form_state, string $form_id) { $config = \Drupal::config('reliefweb_ai.settings'); $current_user = \Drupal::currentUser(); + $url = \Drupal::request()?->query?->get('url'); - if (!$current_user->isAnonymous() || $config->get('ocha_ai_chat.allow_for_anonymous') === TRUE) { - return; + // Add some caching context and tags. + $form['#cache']['contexts'] = array_merge($form['#cache']['contexts'] ?? [], [ + 'user.roles', 'url.query_args', + ]); + $form['#cache']['tags'] = array_merge($form['#cache']['tags'] ?? [], [ + 'config:reliefweb_ai.settings', + ]); + + // Add a more unique ID ot the chat submit button. + if (isset($form['actions']['submit'])) { + $form['actions']['submit']['#attributes']['id'] = 'ocha-ai-chat-ask'; } - $login_instructions = $config->get('ocha_ai_chat.login_instructions') ?? ''; + // Message to display if the form is disabled for any reason. + $disabled = ''; - // Check whether we are requested to replace the instructions or append the - // login instructions. - $replace = $config->get('ocha_ai_chat.login_instructions_replace') === TRUE || !isset($form['chat']['content']); + // Check if the user is anonymous and not allowed to access the chat. + if ($current_user->isAnonymous() && !$config->get('ocha_ai_chat.allow_for_anonymous')) { + $disabled = $config->get('ocha_ai_chat.login_instructions') ?? ''; - if ($replace) { - $instructions = $login_instructions; - } - else { - // We cannot just append the instructions to the current ones because of - // the text format may include sanitation that removes the target - // attributes. We indeed need to preserve those attributes in the login - // instructions so the login and register links open in parent window - // and not in the chat iframe. - // So first we format the current instructions and then append the login - // ones. - $text = $form['chat']['content']['#text'] ?? ''; - $format = $form['chat']['content']['#format'] ?? 'markdown_editor'; - $instructions = (string) check_markup($text, $format); - $instructions .= $login_instructions; + // Redirect to the current page if possible. + if (!empty($url)) { + $disabled = strtr($disabled, [ + '@destination' => UrlHelper::encodePath(parse_url($url, \PHP_URL_PATH)), + ]); + } } - // Replace the instructions with a simple markup render element. - $form['chat']['content'] = [ - '#type' => 'markup', - '#markup' => $instructions, - '#prefix' => '
', - '#suffix' => '
', - ]; - - // Disable or hide the reset of the form. - foreach (Element::children($form['chat']) as $key) { - if ($key !== 'content') { - $form['chat'][$key]['#access'] = FALSE; + if (empty($disabled)) { + // Check if we have a URL to allow the chat. + if (empty($url)) { + $instructions = t('

Something went wrong.

'); + } + // Otherwise check if the language or type of the document. + else { + $router = \Drupal::service('router.no_access_checks'); + $parameters = $router->match($url); + $node = $parameters['node'] ?? NULL; + + // Disable the form if it's not a report. + if (!isset($node) || $node->bundle() !== 'report') { + $disabled = t('

Something went wrong.

'); + } + else { + // No need to show the source when chatting with a single report. + if (isset($form['source'])) { + $form['source']['#access'] = FALSE; + } + + // Only English documents are supported due to LLM limitations. + $is_english_report = FALSE; + foreach ($node->field_language as $item) { + if ($item->target_id == 267) { + $is_english_report = TRUE; + break; + } + } + if (!$is_english_report) { + $disabled = t('

Sorry, only English reports are supported.

'); + } + + // Non supported content formats. + foreach ($node->field_content_format as $item) { + if ($item->target_id == 12) { + $disabled = t('

Sorry, maps are not supported.

'); + break; + } + elseif ($item->target_id == 12570) { + $disabled = t('

Sorry, infographics are not supported.

'); + break; + } + elseif ($item->target_id == 38974) { + $disabled = t('

Sorry, interactive reports are not supported.

'); + break; + } + } + } } } - foreach (Element::children($form) as $key) { - if ($key !== 'chat') { - $form[$key]['#disabled'] = TRUE; + + if (!empty($disabled)) { + // Check whether we are requested to replace the instructions or append the + // disabled instructions. + $replace = $config->get('ocha_ai_chat.instructions_replace') === TRUE || !isset($form['chat']['content']); + + if (!$replace) { + // We cannot just append the instructions to the current ones because of + // the text format may include sanitation that removes the target + // attributes. We indeed need to preserve those attributes in the login + // instructions so the login and register links open in parent window + // and not in the chat iframe. + // So first we format the current instructions and then append the extra + // instructions. + $text = $form['chat']['content']['#text'] ?? ''; + $format = $form['chat']['content']['#format'] ?? 'markdown_editor'; + $instructions = (string) check_markup($text, $format); + $disabled = $instructions . $disabled; } + + // Replace the instructions with a simple markup render element. + $form['chat']['content'] = [ + '#type' => 'markup', + '#markup' => $disabled, + '#prefix' => '
', + '#suffix' => '
', + ]; + + // Disable or hide the reset of the form. + foreach (Element::children($form['chat']) as $key) { + if ($key !== 'content') { + $form['chat'][$key]['#access'] = FALSE; + } + } + foreach (Element::children($form) as $key) { + if ($key !== 'chat') { + $form[$key]['#disabled'] = TRUE; + } + } + + $form['#cache']['max-age'] = 3600; + } +} + +/** + * Implements hook_block_view_alter(). + */ +function reliefweb_ai_block_view_alter(array &$build, BlockPluginInterface $block): void { + // Alter the chat popup block, notably to adjust the caching. + if ($block->getPluginId() === 'ocha_ai_chat_chat_popup') { + $build['#pre_render'][] = [OchaAiChatPopupBlockHandler::class, 'alterBuild']; + return; } } diff --git a/html/modules/custom/reliefweb_ai/reliefweb_ai.services.yml b/html/modules/custom/reliefweb_ai/reliefweb_ai.services.yml new file mode 100644 index 000000000..5696072ed --- /dev/null +++ b/html/modules/custom/reliefweb_ai/reliefweb_ai.services.yml @@ -0,0 +1,6 @@ +services: + reliefweb_ai.ocha_ai_chat_cache_subscriber: + class: Drupal\reliefweb_ai\EventSubscriber\OchaAiChatCacheSubscriber + arguments: ['@current_user'] + tags: + - { name: event_subscriber } diff --git a/html/modules/custom/reliefweb_ai/src/EventSubscriber/OchaAiChatCacheSubscriber.php b/html/modules/custom/reliefweb_ai/src/EventSubscriber/OchaAiChatCacheSubscriber.php new file mode 100644 index 000000000..0c1480537 --- /dev/null +++ b/html/modules/custom/reliefweb_ai/src/EventSubscriber/OchaAiChatCacheSubscriber.php @@ -0,0 +1,56 @@ + ['onResponse', -1000], + ]; + } + + /** + * {@inheritdoc} + */ + public function onResponse(ResponseEvent $event): void { + $request = $event->getRequest(); + $route = $request->attributes->get('_route'); + + if ($route === 'ocha_ai_chat.chat_form' || $route === 'ocha_ai_chat.chat_form.popup') { + $response = $event->getResponse(); + $cache_metadata = $response->getCacheableMetadata(); + + $cache_metadata->addCacheContexts(['user.roles:anonymous']); + if ($this->currentUser->isAnonymous()) { + // Cache for 1 hour. + $cache_metadata->setCacheMaxAge(3600); + // Ensure varnish for example can cache the page. + $response->headers->set('Cache-Control', 'public, max-age=3600'); + } + } + } + +} diff --git a/html/modules/custom/reliefweb_ai/src/OchaAiChatPopupBlockHandler.php b/html/modules/custom/reliefweb_ai/src/OchaAiChatPopupBlockHandler.php new file mode 100644 index 000000000..04ed68071 --- /dev/null +++ b/html/modules/custom/reliefweb_ai/src/OchaAiChatPopupBlockHandler.php @@ -0,0 +1,37 @@ +query?->get('url'); - if (isset($url)) { - $router = \Drupal::service('router.no_access_checks'); - $parameters = $router->match($url); - $node = $parameters['node'] ?? NULL; - - if (isset($node) && $node instanceof Report) { - // No need to show the source when chatting with a single report. - if (isset($form['source'])) { - $form['source']['#access'] = FALSE; - } - - // Only English documents are supported due to LLM limitations. - $is_english_report = FALSE; - foreach ($node->field_language as $item) { - if ($item->target_id == 267) { - $is_english_report = TRUE; - break; - } - } - if (!$is_english_report) { - $reason = t('Sorry, only English reports are supported.'); - } - - // Non supported content formats. - foreach ($node->field_content_format as $item) { - if ($item->target_id == 12) { - $reason = t('Sorry, maps are not supported.'); - break; - } - elseif ($item->target_id == 12570) { - $reason = t('Sorry, infographics are not supported.'); - break; - } - elseif ($item->target_id == 38974) { - $reason = t('Sorry, interactive reports are not supported.'); - break; - } - } - - if (!empty($reason)) { - foreach (Element::children($form) as $key) { - $form[$key]['#access'] = FALSE; - } - $form['unsupported'] = [ - '#type' => 'inline_template', - '#template' => '

{{ reason }}

', - '#context' => [ - 'reason' => $reason, - ], - ]; - } - } - } -} - -/** - * Implements hook_block_access(). - */ -function reliefweb_entities_block_access(Block $block, $operation, AccountInterface $account) { - // Disable the AI chat on map, infographic and interactive content since they - // don't have much content that can be used by the AI. - if ($operation === 'view' && $block->getPluginId() === 'ocha_ai_chat_chat_popup') { - $router = \Drupal::service('router.no_access_checks'); - try { - $parameters = $router->matchRequest(\Drupal::request()); - } - catch (\Exception $exception) { - return AccessResult::forbidden(); - } - - $node = $parameters['node'] ?? NULL; - - if (isset($node) && $node instanceof Report) { - if (in_array($node->field_content_format->target_id, [12, 12570, 38974])) { - return AccessResult::forbidden(); - } - } - } - // No opinion. - return AccessResult::neutral(); -} From 62297c778f07389d6337df909e2129e7595b34e5 Mon Sep 17 00:00:00 2001 From: orakili Date: Wed, 4 Dec 2024 00:30:58 +0000 Subject: [PATCH 4/5] fix: more properly handle response caching and ensure compatibility with ajax response Refs: RW-1134 --- .../reliefweb_ai/reliefweb_ai.services.yml | 2 +- .../OchaAiChatCacheSubscriber.php | 33 ++++++++++++++----- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/html/modules/custom/reliefweb_ai/reliefweb_ai.services.yml b/html/modules/custom/reliefweb_ai/reliefweb_ai.services.yml index 5696072ed..2d25372c2 100644 --- a/html/modules/custom/reliefweb_ai/reliefweb_ai.services.yml +++ b/html/modules/custom/reliefweb_ai/reliefweb_ai.services.yml @@ -1,6 +1,6 @@ services: reliefweb_ai.ocha_ai_chat_cache_subscriber: class: Drupal\reliefweb_ai\EventSubscriber\OchaAiChatCacheSubscriber - arguments: ['@current_user'] + arguments: ['@config.factory', '@current_user'] tags: - { name: event_subscriber } diff --git a/html/modules/custom/reliefweb_ai/src/EventSubscriber/OchaAiChatCacheSubscriber.php b/html/modules/custom/reliefweb_ai/src/EventSubscriber/OchaAiChatCacheSubscriber.php index 0c1480537..f33ae48c5 100644 --- a/html/modules/custom/reliefweb_ai/src/EventSubscriber/OchaAiChatCacheSubscriber.php +++ b/html/modules/custom/reliefweb_ai/src/EventSubscriber/OchaAiChatCacheSubscriber.php @@ -2,6 +2,8 @@ namespace Drupal\reliefweb_ai\EventSubscriber; +use Drupal\Core\Cache\CacheableResponseInterface; +use Drupal\Core\Config\ConfigFactoryInterface; use Drupal\Core\Session\AccountProxyInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Event\ResponseEvent; @@ -15,10 +17,13 @@ class OchaAiChatCacheSubscriber implements EventSubscriberInterface { /** * Constructor. * + * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory + * The config factory. * @param \Drupal\Core\Session\AccountProxyInterface $currentUser * The current user. */ public function __construct( + protected ConfigFactoryInterface $configFactory, protected AccountProxyInterface $currentUser, ) {} @@ -41,14 +46,26 @@ public function onResponse(ResponseEvent $event): void { if ($route === 'ocha_ai_chat.chat_form' || $route === 'ocha_ai_chat.chat_form.popup') { $response = $event->getResponse(); - $cache_metadata = $response->getCacheableMetadata(); - - $cache_metadata->addCacheContexts(['user.roles:anonymous']); - if ($this->currentUser->isAnonymous()) { - // Cache for 1 hour. - $cache_metadata->setCacheMaxAge(3600); - // Ensure varnish for example can cache the page. - $response->headers->set('Cache-Control', 'public, max-age=3600'); + + // Ajax response are not cacheable so only handle normal form response. + if ($response instanceof CacheableResponseInterface) { + $config = $this->configFactory->get('reliefweb_ai.settings'); + + $cache_metadata = $response->getCacheableMetadata(); + + // Vary the cache by role, url parameters and config since they control + // what is displayed to the user. + $cache_metadata->addCacheContexts(['user.roles', 'url.query_args']); + $cache_metadata->addCacheTags(['config:reliefweb_ai.settings']); + + // Cache the response for 1 hour for anonymous user when we just show + // a disabled form asking to log in or register. + if ($this->currentUser->isAnonymous() && !$config->get('ocha_ai_chat.allow_for_anonymous')) { + // Cache for 1 hour. + $cache_metadata->setCacheMaxAge(3600); + // Ensure varnish for example can cache the page. + $response->headers->set('Cache-Control', 'public, max-age=3600'); + } } } } From 495b293d416e34425cbe0d4742995906e178f4e2 Mon Sep 17 00:00:00 2001 From: orakili Date: Wed, 4 Dec 2024 00:31:43 +0000 Subject: [PATCH 5/5] fix: add unique-ish class to the chat ask button instead of ID to avoid breaking ajax Refs: RW-1134 --- html/modules/custom/reliefweb_ai/reliefweb_ai.module | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/html/modules/custom/reliefweb_ai/reliefweb_ai.module b/html/modules/custom/reliefweb_ai/reliefweb_ai.module index 98710395a..0518f7316 100644 --- a/html/modules/custom/reliefweb_ai/reliefweb_ai.module +++ b/html/modules/custom/reliefweb_ai/reliefweb_ai.module @@ -27,9 +27,9 @@ function reliefweb_ai_form_ocha_ai_chat_chat_form_alter(array &$form, FormStateI 'config:reliefweb_ai.settings', ]); - // Add a more unique ID ot the chat submit button. + // Add a more unique class to the chat submit button. if (isset($form['actions']['submit'])) { - $form['actions']['submit']['#attributes']['id'] = 'ocha-ai-chat-ask'; + $form['actions']['submit']['#attributes']['class'][] = 'ocha-ai-chat-ask'; } // Message to display if the form is disabled for any reason.