', result['client_tool']['params']['html'])
self.assertIn('do not apply the page again', result['client_tool']['params']['note'])
# A zone-scoped action bundled in the same call rides along in the client
# tool's params — applied together with the finalized page, rather than as
# a second tool call that could land before or after it.
with patch.object(self.registry['res.users'], '_bus_send') as bus_send:
result = self.env['ai.tool']._ai_tool_apply_html_to_page(tool_context, [
{'zone': 'main', 'mode': 'replace', 'content': '
Hello
'},
{'zone': 'main', 'mode': 'replace', 'selector': '#footer', 'content': ''},
])
bus_send.assert_not_called()
self.assertEqual(result['client_tool']['params']['other_actions'], [
{'zone': 'main', 'mode': 'replace', 'selector': '#footer', 'content': ''},
])
self.assertIn('applied immediately', result['client_tool']['params']['note'])
def test_ai_tool_apply_html_names_the_page_it_edits(self):
"""The builder needs it to refuse edits meant for a page the user has left."""
view_info = {
"website_page": {
"is_page_ai_editable": True,
"location": "/about-us",
"main_object": {"model": "website.page", "id": 42},
},
}
actions = [{"zone": "main", "mode": "replace", "selector": "#target", "content": "
Hi
"}]
tool_context = self._create_page_tool_context()
with patch.object(self.env.registry["res.users"], "_bus_send") as bus_send:
result = self.env["ai.tool"].with_context(
current_view_info=view_info,
)._ai_tool_apply_html_to_page(tool_context, actions)
bus_send.assert_not_called()
self.assertEqual(result['client_tool']['name'], 'website_apply_html')
self.assertEqual(result['client_tool']['params'], {
"actions": actions,
"target_page": {
"main_object": {"model": "website.page", "id": 42},
"location": "/about-us",
},
})
def test_ai_tool_set_webform_action(self):
result = self.env['ai.tool']._ai_tool_set_webform_action(
'send_mail', 'section.s_website_form',
[{'name': 'email_to', 'value': 'someone@example.com'}])
self.assertEqual(result['client_tool']['name'], 'website_set_form_action')
self.assertEqual(result['client_tool']['params'], {
'selector': 'section.s_website_form',
'action_key': 'send_mail',
'fields': [{'name': 'email_to', 'value': 'someone@example.com'}],
})
result = self.env['ai.tool']._ai_tool_set_webform_action('no_such_action', 'form', [])
self.assertIn("Unknown form action 'no_such_action'", result)
self.assertIn('send_mail', result,
"The error should list the available action keys.")
def test_ai_webform_normalizer_bounces(self):
"""Each violation that needs the model to rewrite its HTML errors
back through the tool result; the in-place repairs are covered by
`test_ai_webform_normalizer_repairs_and_passes`."""
self._patch_authorized_fields(self.WEBFORM_FIELDS)
subject = self._form_field('', label='Subject')
cases = [
# An empty name is as lost on submission as a missing one.
('nameless input', self._webform_content(
'
'
'
'),
r"without a name", {}),
# e.g. the HTML-ism "number": the editor has no such field template.
('invalid data-type', self._webform_content(
'
'
'
'),
r"data-type", {}),
# One label-less field breaks the sidebar for the whole form.
('missing structural label', self._webform_content(
'
'
'
'
''
''
'
'),
r"s_website_form_label", {}),
# A native date input posts a raw ISO value the insert cannot
# parse; only the picker wrapper's value gets serialized.
('native date input', self._webform_content(
self._form_field('', 'date')),
r"native date inputs", {}),
('date field without its picker wrapper', self._webform_content(
self._form_field('', 'date')),
r"picker", {}),
# The submit validator matches accept entries against MIME types:
# an extension list rejects every upload.
('file accept extension list', self._webform_content(
self._form_field('', 'binary')),
r"accept value\(s\) \.pdf, \.doc", {}),
# A bound choice input posts its option value verbatim: it must be
# a selection key (not the label) or a record id (not a name).
('selection option with the label as value',
self._webform_content(self._radio('Medium')), r"'0' = Low", {}),
('relational option with a name as value',
self._webform_content(self._select('partner_id', 'Bob')), r"numeric id", {}),
('hidden preset with a name as value', self._webform_content(
'
'
'
'),
r"numeric id", {}),
# 'model' is required but not form-writable: the server fills it,
# so only 'subject' may be demanded (the trailing "-" pins the
# missing list to exactly that).
('missing required writable field', self._webform_content(
self._form_field('')),
r"mandatory field\(s\) subject -", {}),
# The palette only ever nests the form section inside a wrapper
# snippet section; page-level placements always bounce.
('form section inserted at page level', self._webform_content(subject),
r"nested inside a wrapper", {'mode': 'after', 'selector': 'section:last-child'}),
('form section replacing a whole zone', self._webform_content(subject),
r"nested inside a wrapper", {'selector': ''}),
# Same zone, named rather than left empty.
('form section replacing a named whole zone', self._webform_content(subject),
r"nested inside a wrapper", {'selector': '#wrap'}),
# The end message is all the visitor sees after submitting.
('message mode without an end message',
self._webform_content(subject, 'data-success-mode="message"'),
r"s_website_form_end_message", {}),
('message mode with an empty end message',
self._webform_content(subject, 'data-success-mode="message"',
end_message=''),
r"s_website_form_end_message", {}),
('end message outside the form\'s parent',
self._webform_content(subject, 'data-success-mode="message"')
+ '
Thanks!
',
r"s_website_form_end_message", {}),
]
for label, content, pattern, action in cases:
with self.subTest(label), self.assertRaisesRegex(ValueError, pattern):
self._apply_webform(content, **action)
# Deterministic mail.mail fields for the normalizer tests. 'model' is
# required but not form-writable (blacklisted): it must never be demanded.
WEBFORM_FIELDS = {
'email_to': {'type': 'char', 'string': 'Email To'},
'email_from': {'type': 'char', 'string': 'Email From'},
'subject': {'type': 'char', 'string': 'Subject', 'required': True},
'model': {'type': 'char', 'string': 'Related Model', 'required': True},
'priority': {'type': 'selection', 'string': 'Priority',
'selection': [('0', 'Low'), ('1', 'Medium')]},
'partner_id': {'type': 'many2one', 'string': 'Customer'},
}
def _patch_authorized_fields(self, fields):
self.patch(self.env.registry['ir.model'], 'get_authorized_fields',
lambda _self, model_name, property_origins=None: dict(fields))
def _webform_content(self, fields_html, form_attrs='', email_to='a@b.c', end_message=''):
return (
'
'
f'{end_message}
'
)
def _form_field(self, inner, data_type='char', label='Field'):
return (
f'
', 'selection', 'Priority')
def _select(self, name, value):
return self._form_field(
f'',
'many2one', 'Customer')
def _apply_webform(self, content, **action):
# A targeted replace of the form section itself: the one case where a
# top-level s_website_form fragment root is legitimate.
return self.env['ai.tool']._ai_tool_apply_html_to_page(self._create_page_tool_context(), [{
'zone': 'main',
'mode': 'replace',
'selector': 'section.s_website_form',
'content': content,
**action,
}])
def test_ai_webform_normalizer_repairs_and_passes(self):
"""Purely mechanical details are repaired in place, and a form that
follows the rules is applied."""
self._patch_authorized_fields(self.WEBFORM_FIELDS)
action = {
'zone': 'main',
'mode': 'replace',
'selector': 'section.s_website_form',
'content': (
''
''
),
}
result = self.env['ai.tool']._ai_tool_apply_html_to_page(self._create_page_tool_context(), [action])
self.assertEqual(result['client_tool']['name'], 'website_apply_html')
root = lxml_html.fromstring(action['content'])
self.assertTrue(
root.xpath('//div[contains(@class, "s_website_form_submit")]/span[@id="s_website_form_result"]'),
"The missing submission status span should be injected.")
self.assertFalse(
root.xpath('//div[contains(@class, "s_website_form_custom")]/input[@name="email_from"]'),
"A field bound to a model field must lose the custom marker.")
self.assertTrue(
root.xpath('//div[contains(@class, "s_website_form_custom")]/input[@name="Nickname"]'),
"A field with an unknown name must gain the custom marker.")
ids = root.xpath('//input[not(@type="hidden")]/@id | //select/@id')
self.assertNotIn('dup', ids)
self.assertEqual(len(set(ids)), len(ids), "Copied duplicate input ids must be regenerated.")
for name in ('email_from', 'Nickname'):
field = root.xpath(f'//input[@name="{name}"]/parent::div')[0]
self.assertEqual(field.xpath('label/@for'), field.xpath('input/@id'),
"Labels must point at their field's regenerated input id.")
# Missing file count/size limits render as a broken "0 MB": stamped.
self.assertIn('data-max-files-number="1"', action['content'])
self.assertIn('data-max-file-size="64"', action['content'])
form = root.xpath('//form')[0]
self.assertEqual(form.get('data-success-mode'), 'redirect',
"An invalid success mode falls back to redirect.")
self.assertEqual(form.get('data-success-page'), '/contactus-thank-you')
# Nested inside a wrapper snippet section, page-level placements pass.
subject = self._form_field('', label='Subject')
wrapped = ('
'
f'{self._webform_content(subject)}
')
placements = {
'website_apply_html': {'mode': 'after', 'selector': 'section:last-child'},
# An empty selector on the main zone is a full-page build, which
# goes to the client for finalization rather than a plain apply.
'finalize_website_page': {'selector': ''},
}
for tool_name, placement in placements.items():
result = self._apply_webform(wrapped, **placement)
self.assertEqual(result['client_tool']['name'], tool_name)
# Message mode with a real end message next to the form passes.
result = self._apply_webform(self._webform_content(
subject, 'data-success-mode="message"',
end_message='
Thanks!
'))
self.assertEqual(result['client_tool']['name'], 'website_apply_html')
def test_ai_tool_get_webform_info(self):
result = self.env['ai.tool']._ai_tool_get_webform_info('')
self.assertIn('send_mail', result,
"The no-key form should list the available actions.")
self.assertIn('mail.mail', result)
result = self.env['ai.tool']._ai_tool_get_webform_info('no_such_action')
self.assertIn("Unknown form action 'no_such_action'", result)
self.assertIn('send_mail', result,
"The error should list the available action keys.")
self._patch_authorized_fields(self.WEBFORM_FIELDS)
result = self.env['ai.tool']._ai_tool_get_webform_info('send_mail')
self.assertIn('"mail.mail"', result)
# The model can only write valid option values if it has seen the
# selection keys, not just the labels.
self.assertIn("'0' = Low, '1' = Medium", result)
self.assertIn('chosen by the user', result,
"The send-mail action must flag the recipient as the user's choice.")
def test_ai_tool_request_ai_scripts_scopes(self):
"""The scripts can be inserted only in the allowed scope."""
ai_tool = self.env['ai.tool']
website = self.env['ai.website.service']._current_website()
script_action = [{
'zone': 'footer',
'mode': 'replace',
'content': '',
}]
tool_context = self._create_page_tool_context()
with self.assertRaisesRegex(ValueError, "scope must be"):
ai_tool._ai_tool_request_ai_scripts(tool_context, 'everywhere')
self.assertFalse(website.ai_allow_scripts)
ai_tool._ai_tool_request_ai_scripts(tool_context, 'chat')
self.assertEqual(tool_context['state'], {'website_ai_allow_scripts': True})
self.assertFalse(website.ai_allow_scripts)
# The chat that was granted the permission can write scripts; another one cannot.
self.assertEqual(
ai_tool._ai_tool_apply_html_to_page(tool_context, script_action)['client_tool']['name'],
'website_apply_html',
)
with self.assertRaisesRegex(ValueError, "adding JavaScript is turned off"):
ai_tool._ai_tool_apply_html_to_page({'state': {}}, script_action)
website_context = self._create_page_tool_context()
ai_tool._ai_tool_request_ai_scripts(website_context, 'website')
self.assertTrue(website.ai_allow_scripts)
self.assertEqual(
ai_tool._ai_tool_apply_html_to_page({'state': {}}, script_action)['client_tool']['name'],
'website_apply_html',
)
def test_ai_tool_get_website_menus(self):
website = self.env['ai.website.service']._current_website()
menu = self.env['website.menu'].create({
'name': 'Test Menu',
'url': '/test-menu',
'website_id': website.id,
'parent_id': website.menu_id.id,
})
submenu = self.env['website.menu'].create({
'name': 'Test Submenu',
'url': '/test-submenu',
'website_id': website.id,
'parent_id': menu.id,
})
result = self.env['ai.tool']._ai_tool_get_website_menus()['response']
self.assertIn(f'- ID: {menu.id}, Name: "Test Menu", URL: "#"', result,
"The menu tree should list the menu items with their IDs; a parent item's URL becomes '#'.")
self.assertIn(f' - ID: {submenu.id}, Name: "Test Submenu", URL: "/test-submenu"', result,
"Sub-menu items should be indented under their parent.")
self.assertIn("# Website pages", result,
"The result should include the list of website pages.")
self.assertIn('- URL: "/contactus", Name: "', result,
"Default pages such as /contactus should be listed.")
def test_ai_tool_edit_website_menus_confirmation(self):
tool_context = {'tool_request_confirmed': False}
result = self.env['ai.tool']._ai_tool_edit_website_menus(tool_context, [
{'type': 'create', 'name': 'Contact', 'url': 'contactus'},
])
self.assertIsNone(result, "The tool should not apply anything before the user confirms.")
self.assertEqual(tool_context['user_input_request']['type'], 'confirmation')
self.assertFalse(
self.env['website.menu'].search([('name', '=', 'Contact')]),
"No menu item should be created before the user confirms.",
)
def test_ai_tool_edit_website_menus(self):
Menu = self.env['website.menu']
website = self.env['ai.website.service']._current_website()
client_call = self.env['ai.tool']._ai_tool_edit_website_menus({'tool_request_confirmed': True}, [
{'type': 'create', 'name': 'Contact', 'url': 'contactus'},
{'type': 'create', 'name': 'About', 'temp_id': 'new_about'},
{'type': 'create', 'name': 'Team', 'url': '/team', 'parent_temp_id': 'new_about'},
{'type': 'create', 'name': 'Email us', 'url': 'info@example.com'},
])
result = client_call['client_tool']['params']
self.assertIn("Menu operations applied successfully:", result)
self.assertIn("Here is the updated menu structure:", result,
"The result should include the updated menu tree so the AI knows the new IDs.")
contact = Menu.search([('name', '=', 'Contact'), ('website_id', '=', website.id)])
self.assertEqual(contact.url, '/contactus',
"The URL should be normalized to the matched page URL.")
self.assertTrue(contact.page_id, "The menu should be linked to the page matching its URL.")
about = Menu.search([('name', '=', 'About'), ('website_id', '=', website.id)])
team = Menu.search([('name', '=', 'Team'), ('website_id', '=', website.id)])
self.assertEqual(team.parent_id, about,
"parent_temp_id should nest the item under the menu created earlier in the same call.")
self.assertEqual(about.url, '#', "A parent menu item should have '#' as URL.")
email_menu = Menu.search([('name', '=', 'Email us'), ('website_id', '=', website.id)])
self.assertEqual(email_menu.url, 'info@example.com')
self.assertEqual(email_menu._clean_url(), 'mailto:info@example.com',
"Email URLs should render as mailto links.")
# Update: rename, re-point, nest and un-nest
self.env['ai.tool']._ai_tool_edit_website_menus({'tool_request_confirmed': True}, [
{'type': 'update', 'menu_id': contact.id, 'name': 'Reach Us', 'url': 'https://example.com', 'new_window': True},
{'type': 'update', 'menu_id': email_menu.id, 'parent_menu_id': about.id},
])
self.assertEqual(contact.name, 'Reach Us')
self.assertEqual(contact.url, 'https://example.com')
self.assertTrue(contact.new_window)
self.assertFalse(contact.page_id, "Pointing to an external URL should unlink the page.")
self.assertEqual(email_menu.parent_id, about)
self.env['ai.tool']._ai_tool_edit_website_menus({'tool_request_confirmed': True}, [
{'type': 'update', 'menu_id': email_menu.id, 'parent_menu_id': 0},
])
self.assertEqual(email_menu.parent_id, website.menu_id,
"parent_menu_id 0 should move the item back to the top level.")
# Delete a parent: children go with it
self.env['ai.tool']._ai_tool_edit_website_menus({'tool_request_confirmed': True}, [
{'type': 'delete', 'menu_id': about.id},
])
self.assertFalse(about.exists())
self.assertFalse(team.exists(), "Deleting a menu item should also delete its sub-items.")
def test_ai_tool_edit_website_menus_invalid(self):
website = self.env['ai.website.service']._current_website()
with self.assertRaisesRegex(ValueError, "not found on the current website"):
self.env['ai.tool']._ai_tool_edit_website_menus({'tool_request_confirmed': True}, [
{'type': 'delete', 'menu_id': -1},
])
with self.assertRaisesRegex(ValueError, "root menu"):
self.env['ai.tool']._ai_tool_edit_website_menus({'tool_request_confirmed': True}, [
{'type': 'update', 'menu_id': website.menu_id.id, 'name': 'Hacked'},
])
with self.assertRaisesRegex(ValueError, '"name" is required'):
self.env['ai.tool']._ai_tool_edit_website_menus({'tool_request_confirmed': True}, [
{'type': 'create', 'url': '/no-name'},
])
with self.assertRaisesRegex(ValueError, "Unknown parent_temp_id"):
self.env['ai.tool']._ai_tool_edit_website_menus({'tool_request_confirmed': True}, [
{'type': 'create', 'name': 'Orphan', 'parent_temp_id': 'missing'},
])
with self.assertRaisesRegex(ValueError, "Too many operations"):
self.env['ai.tool']._ai_tool_edit_website_menus({'tool_request_confirmed': True}, [
{'type': 'create', 'name': f'Menu {i}'} for i in range(51)
])
# Model constraints (e.g. two-level nesting) are reported with
# guidance, and a failing batch is rolled back entirely.
parent_a = self.env['website.menu'].create({
'name': 'Parent A',
'website_id': website.id,
'parent_id': website.menu_id.id,
})
parent_b = self.env['website.menu'].create({
'name': 'Parent B',
'website_id': website.id,
'parent_id': website.menu_id.id,
})
child_a = self.env['website.menu'].create({
'name': 'Child of A',
'url': '/child-a',
'website_id': website.id,
'parent_id': parent_a.id,
})
with self.assertRaisesRegex(ValueError, "is itself a sub-item"):
self.env['ai.tool']._ai_tool_edit_website_menus({'tool_request_confirmed': True}, [
{'type': 'create', 'name': 'Too Deep', 'parent_menu_id': child_a.id},
])
with self.assertRaisesRegex(ValueError, "has sub-items, so it cannot be nested"):
self.env['ai.tool']._ai_tool_edit_website_menus({'tool_request_confirmed': True}, [
{'type': 'update', 'menu_id': parent_a.id, 'parent_menu_id': parent_b.id},
])
with self.assertRaisesRegex(ValueError, "None of the operations were applied"):
self.env['ai.tool']._ai_tool_edit_website_menus({'tool_request_confirmed': True}, [
{'type': 'create', 'name': 'Survivor'},
# Invalid: parent_a already has sub-items
{'type': 'update', 'menu_id': parent_a.id, 'parent_menu_id': parent_b.id},
])
self.assertEqual(parent_a.parent_id, website.menu_id,
"The invalid nesting must not be applied.")
self.assertFalse(self.env['website.menu'].search([('name', '=', 'Survivor')]),
"A failing batch must be rolled back entirely.")
other_website = self.env['website'].create({'name': 'Other Website'})
other_menu = self.env['website.menu'].create({
'name': 'Other Menu',
'url': '/other',
'website_id': other_website.id,
'parent_id': other_website.menu_id.id,
})
with self.assertRaisesRegex(ValueError, "not found on the current website"):
self.env['ai.tool']._ai_tool_edit_website_menus({'tool_request_confirmed': True}, [
{'type': 'delete', 'menu_id': other_menu.id},
])
self.assertTrue(other_menu.exists(),
"Menus of other websites must not be editable.")
def test_ai_tool_create_page_with_menu(self):
tool_context = self._create_page_tool_context()
result = self.env['ai.tool']._ai_tool_create_page(
tool_context, 'AI Tool Page With Menu', add_to_menu=True,
)
page = self.env['website.page'].search([('url', '=', '/ai-tool-page-with-menu')])
self.assertTrue(page)
self.assertTrue(page.menu_ids)
client_tool = result['client_tool']
self.assertEqual(client_tool['name'], 'ai_website_navigate_to_edit')
self.assertEqual(client_tool['params']['url'], page.url)
self.assertFalse(client_tool['params']['save'])
self.assertEqual(tool_context['state']['page_url_pending_html'], page.url)
def test_ai_tool_create_page_refuses_when_previous_page_has_no_content(self):
tool_context = self._create_page_tool_context()
tool = self.env['ai.tool']
first_page = tool._ai_tool_create_page(tool_context, 'AI Tool Page First')
first_page_url = first_page['client_tool']['params']['url']
# The client always navigates to the page it was just told to create
# before the next tool call, so its reported location is that page's.
result = tool.with_context(
current_view_info={'website_page': {'location': first_page_url}},
)._ai_tool_create_page(tool_context, 'AI Tool Page Second')
self.assertIn('Cannot create another page yet', result)
self.assertFalse(self.env['website.page'].search([
('url', '=', '/ai-tool-page-second'),
]))
def test_ai_tool_apply_html_to_page_clears_pending_state(self):
tool_context = self._create_page_tool_context()
tool = self.env['ai.tool']
tool._ai_tool_create_page(tool_context, 'AI Tool Page Third')
self.assertIn('page_url_pending_html', tool_context['state'])
tool._ai_tool_apply_html_to_page(tool_context, [{
'zone': 'main', 'mode': 'replace', 'content': '',
}])
self.assertNotIn('page_url_pending_html', tool_context['state'])
def test_ai_tool_create_page_without_menu(self):
tool_context = self._create_page_tool_context()
self.env['ai.tool']._ai_tool_create_page(
tool_context, 'AI Tool Page Without Menu', add_to_menu=False,
)
page = self.env['website.page'].search([('url', '=', '/ai-tool-page-without-menu')])
self.assertTrue(page)
self.assertFalse(page.menu_ids)
def test_ai_tool_create_page_asks_confirmation_when_unsaved_changes(self):
tool_context = self._create_page_tool_context()
result = self.env['ai.tool'].with_context(
current_view_info={'website_page': {'pending_changes': True}},
)._ai_tool_create_page(tool_context, 'AI Tool Page With Unsaved Changes')
self.assertIsNone(result)
self.assertEqual(tool_context['user_input_request']['type'], 'confirmation')
choice_values = {choice['value'] for choice in tool_context['user_input_request']['choices']}
self.assertEqual(choice_values, {UserInputResponse.CONFIRM_ONCE, UserInputResponse.AUTO_CONFIRM, UserInputResponse.DECLINE})
self.assertFalse(self.env['website.page'].search([
('url', '=', '/ai-tool-page-with-unsaved-changes'),
]))
def test_ai_tool_create_page_saves_changes_on_confirmation(self):
tool_context = self._create_page_tool_context()
tool_context['tool_request_confirmed'] = True
tool = self.env['ai.tool'].with_context(
current_view_info={'website_page': {'pending_changes': True}},
)
result = tool._ai_tool_create_page(tool_context, 'AI Tool Page Save Changes')
page = self.env['website.page'].search([('url', '=', '/ai-tool-page-save-changes')])
self.assertTrue(page)
client_tool = result['client_tool']
self.assertEqual(client_tool['name'], 'ai_website_navigate_to_edit')
self.assertEqual(client_tool['params']['url'], page.url)
self.assertTrue(client_tool['params']['save'])
def test_ai_tool_get_site_profile(self):
self.env['website'].new_page(name='Profile Test Page', add_menu=True)
result = self.env['ai.tool']._ai_tool_get_site_profile()
self.assertIn('Here is the site profile:', result)
profile = json.loads(result.split('```json\n', 1)[1].rsplit('```', 1)[0])
self.assertIn('website_name', profile)
self.assertIn('company', profile)
self.assertIn('menu_tree', profile)
self.assertIn('Profile Test Page', [page['name'] for page in profile['pages']])
def test_ai_tool_get_page_html(self):
self.env['website'].new_page(name='Page Html Test', add_menu=False)
result = self.env['ai.tool']._ai_tool_get_page_html('/page-html-test')
self.assertIn('Here is the HTML content of the /page-html-test:', result)
self.assertIn('