This commit is contained in:
2026-11-08 20:08:53 +08:00
parent 7526a5fe4d
commit 9b924747c5
2692 changed files with 394867 additions and 0 deletions

View File

@@ -0,0 +1,17 @@
from . import ai_web_page
from . import ai_website_service
from . import ai_website_service_brand_kit
from . import ai_website_service_refinement
from . import ai_website_service_snippets
from . import ai_web_scraper_batch
from . import ai_tool
from . import ai_tool_webform
from . import ai_composer
from . import ai_session
from . import ir_attachment
from . import ir_ui_view
from . import mail_message
from . import discuss_channel
from . import website_page
from . import res_config_settings
from . import website

View File

@@ -0,0 +1,42 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class AIComposer(models.Model):
_inherit = 'ai.composer'
interface_key = fields.Selection(
selection_add=[
("website_seo_ai", "Optimize the SEO of their website pages"),
('website_builder_ai', 'Edit a website page'),
],
ondelete={
"website_seo_ai": "cascade",
"website_builder_ai": "cascade",
},
)
@api.depends("interface_key")
def _compute_hide_model_selection(self):
super()._compute_hide_model_selection()
for rule in self:
rule.hide_model_selection = rule.hide_model_selection or rule.interface_key in (
"website_seo_ai", "website_builder_ai")
@api.depends("interface_key")
def _compute_hide_prompt_button_page(self):
super()._compute_hide_prompt_button_page()
for rule in self:
rule.hide_prompt_button_page = rule.hide_prompt_button_page or rule.interface_key in ("website_seo_ai", "website_builder_ai")
def _get_initial_context(self, res_model=None, res_id=None, text_selection=None,
text_of_editable=None, reference_image_path=None):
parts = super()._get_initial_context(
res_model=res_model, res_id=res_id, text_selection=text_selection,
text_of_editable=text_of_editable, reference_image_path=reference_image_path,
)
if self.interface_key != 'website_builder_ai':
return parts
parts.append({'type': 'text', 'text': self.env['ai.website.service']._create_snippets_list()})
return parts

View File

@@ -0,0 +1,145 @@
from typing import override
from odoo import _, fields, models
from .ai_website_service import MAX_GENERATED_IMAGES
WEBSITE_BUILDER_TIMEOUT = 180
class AiSession(models.Model):
_inherit = 'ai.session'
# Page identity captured when scraping suspends the conversation. The editor
# supplies fresh context when it resumes; this snapshot guards against navigation.
website_builder_context = fields.Json(string="Website Builder Context")
@override
def _get_model_round_options(self):
completion_options = super()._get_model_round_options()
if self._is_website_builder_session():
completion_options['timeout'] = WEBSITE_BUILDER_TIMEOUT
return completion_options
@override
def _submit_agent_request(self, message=None):
if message is not None and self._is_website_builder_session():
website_page = self.env.context['current_view_info']['website_page']
if selected_elements := website_page.get('selected_elements'):
selected_elements_data = [
{key: element[key] for key in ('id', 'tag', 'text')}
for element in selected_elements
]
message = [*message, {
'type': 'text',
'text': f"<website_element_attachments>\n{selected_elements_data}\n</website_element_attachments>",
}]
return super()._submit_agent_request(message)
@override
def _resume_pending_interaction(self, response, ai_session_config=None, *, automatic=False):
if self._is_website_builder_session() and response['kind'] == 'async':
if not self._accept_scraper_resume(response['call_id']):
return
return super()._resume_pending_interaction(
response, ai_session_config=ai_session_config, automatic=automatic,
)
@override
def _get_session_advance_unavailable_message(self):
self.ensure_one()
if not self._is_website_builder_session():
return False
current_view_info = self.env.context.get('current_view_info')
if not current_view_info or 'website_page' not in current_view_info:
return _("Please open the website builder to use this AI on the website.")
if not current_view_info['website_page']['is_page_ai_editable']:
return _("The current page is a special page that cannot be edited by the AI.")
return False
def _get_context_input(self, rag_context):
"""State whether the AI may add JavaScript, the site's current brand kit,
and the generated-image ceiling, with every single message."""
context = super()._get_context_input(rag_context)
if self._is_website_builder_session():
state = "ON" if self.env['ai.website.service']._ai_scripts_allowed(self.state or {}) else "OFF"
brand_kit = self.env['ai.website.service']._get_current_brand_kit()
return context.replace(
"</odoo_current_context>",
f"\n## AI JavaScript\n{state}\n## Brand kit\n{brand_kit}\n"
f"## Generated images\nAt most {MAX_GENERATED_IMAGES} `data-ai-image-prompt` "
"placeholders total, across every action in one `apply_html_to_page` call.\n"
"</odoo_current_context>",
)
return context
def _run_agentic_loop(self, *args, **kwargs):
if self._is_website_builder_session():
kwargs['timeout'] = WEBSITE_BUILDER_TIMEOUT
yield from super()._run_agentic_loop(*args, **kwargs)
def _set_pending_tool_call(self, pending_tool_call):
# Session bookkeeping runs with the session's privileges; the tool itself
# runs as the editor, who need not have write access to ai.session.
if pending_tool_call.get('await_external_result'):
self._save_context_for_async_resume()
super()._set_pending_tool_call(pending_tool_call)
def _save_context_for_async_resume(self):
"""Remember the target page, without retaining its editable HTML."""
self.ensure_one()
if not self._is_website_builder_session():
return
page = (self.env.context.get('current_view_info') or {}).get('website_page') or {}
self.website_builder_context = {
'current_view_info': {'website_page': {
key: page.get(key) for key in ('main_object', 'location', 'website_id')
}},
}
def _get_scraper_resume_data(self):
"""Expose a ready call's identity, without sending its scraped content."""
self.ensure_one()
pending = self.pending_tool_call or {}
call_id = str(pending.get('call_id'))
if (
not self.channel_id
or not self._is_website_builder_session()
or not pending.get('await_external_result')
or call_id not in (self.state or {}).get('website_scraper_results', {})
):
return False
snapshot = (self.website_builder_context or {}).get('current_view_info') or {}
page = snapshot.get('website_page') or {}
return {
'channel_id': self.channel_id.id,
'session_id': self.id,
'resume_token': self.resume_token,
'tool_call_id': call_id,
'target_page': {key: page.get(key) for key in ('main_object', 'location', 'website_id')},
}
def _accept_scraper_resume(self, call_id):
"""Ignore obsolete notifications and let only one editor resume a ready result."""
self.ensure_one()
if not call_id or not self.try_lock_for_update():
return False
self.invalidate_recordset(['pending_tool_call', 'state', 'website_builder_context'])
pending = self.pending_tool_call or {}
if (
not pending.get('await_external_result')
or str(pending.get('call_id')) != str(call_id)
or str(call_id) not in (self.state or {}).get('website_scraper_results', {})
):
return False
snapshot = (self.website_builder_context or {}).get('current_view_info') or {}
target = snapshot.get('website_page') or {}
current = (self.env.context.get('current_view_info') or {}).get('website_page') or {}
return bool(
target.get('main_object')
and target['main_object'] == current.get('main_object')
and target.get('website_id') == current.get('website_id')
)
def _is_website_builder_session(self):
return len(self) == 1 and self.ai_composer_id.interface_key == 'website_builder_ai'

1134
ai_website/models/ai_tool.py Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,540 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import contextlib
import json
import re
import secrets
from lxml import etree, html as lxml_html
from odoo import api, models
from odoo.addons.ai_website.models.ai_website_service import _WHOLE_ZONE_SELECTORS
# The public form runtime re-injects a fresh signature on every render
# (website/tools.py add_form_signature), so any signature in generated or
# fetched markup is dead weight, and a hardcoded hash trips the safety
# reviewer. Strip them everywhere.
_FORM_SIGNATURE_RE = re.compile(r'<input\b[^>]*website_form_signature[^>]*>\s*', re.IGNORECASE)
_SUCCESS_MODES = ('redirect', 'message', 'nothing')
# The field types the editor can render, one website.form_field_* template
# each (website_form_editor.xml). Any other data-type crashes the sidebar's
# field rendering.
_FIELD_TYPES = frozenset((
'char', 'text', 'email', 'tel', 'url', 'integer', 'float', 'monetary',
'date', 'datetime', 'binary', 'boolean', 'selection', 'many2one',
'one2many', 'many2many', 'html',
))
_EMAIL_TO_INPUT_RE = re.compile(r'<input\b[^>]*\bname="email_to"[^>]*>', re.IGNORECASE)
# The accept values the editor's file-type options produce. The submit
# validator matches them against the files' MIME types, so anything else
# (e.g. an extension list) rejects every upload.
_FILE_ACCEPT_VALUES = frozenset((
'image/*', 'application/pdf', 'application/*', 'video/*', 'audio/*',
))
def _blank_email_to_values(html):
"""Clear the `value` attribute of any `email_to` inputs in the HTML.
This prevents the AI from silently copying the default company address
from snippets without the user's explicit approval."""
return _EMAIL_TO_INPUT_RE.sub(
lambda match: re.sub(r'\bvalue="[^"]*"', 'value=""', match.group(0)),
html,
)
def _with_class(cls):
"""Generate an XPath condition to safely match a class name within a
space-separated class attribute."""
return f'contains(concat(" ", normalize-space(@class), " "), " {cls} ")'
def _field_name(field_el):
"""The name a field wrapper submits under. A multi-option field carries it
on its group wrapper, every other field on its input."""
return next(iter(field_el.xpath(
f'.//*[{_with_class("s_website_form_multiple")}]/@data-name'
f' | .//*[{_with_class("s_website_form_input")}]/@name')), None)
class AIToolWebform(models.AbstractModel):
"""Webform support for the website builder agent.
The agent builds forms by writing HTML adapted from the canonical form
snippets; this layer makes those forms functional by construction:
- a normalizer gates every HTML apply: purely mechanical details
(signatures, ids, submit anchor, custom-vs-bound markers) are repaired
in place, while anything that would break the submission or the editor
and needs the model's (or the user's) intent raises, so the error goes
back through the tool result and the model corrects its own output;
- the "Set Form Action" tool wires a form through the form editor's own
client-side code paths, and the "Get Webform Info" tool describes the
available form actions and their bindable fields.
"""
_inherit = 'ai.tool'
@api.model
def _ai_tool_apply_html_to_page(self, tool_context, actions):
"""Normalize the webforms in the actions before the base apply
pipeline runs."""
# Some providers send structured arguments JSON-encoded; parse before
# normalizing.
if isinstance(actions, str):
with contextlib.suppress(json.JSONDecodeError):
actions = json.loads(actions)
if isinstance(actions, list):
# Before super(): the safety reviewer must never see a signature.
self._normalize_webform_actions(actions)
return super()._ai_tool_apply_html_to_page(tool_context, actions)
@api.model
def _ai_tool_get_snippets(self, snippet_keys):
"""Strip live signatures and blank out email recipients from fetched
snippets to prevent the model from faithfully copying them."""
result = super()._ai_tool_get_snippets(snippet_keys)
if isinstance(result, str):
result = _FORM_SIGNATURE_RE.sub('', result)
result = _blank_email_to_values(result)
return result
@api.model
def _normalize_webform_actions(self, actions):
"""Validate and normalize the webforms of every action's content,
in place."""
for index, action in enumerate(actions):
if not isinstance(action, dict):
continue
content = action.get('content') or ''
if 's_website_form' not in content and '<form' not in content:
continue
content = _FORM_SIGNATURE_RE.sub('', content)
try:
root = lxml_html.fragment_fromstring(content, create_parent='div')
except (etree.ParserError, ValueError):
# Unparseable content is the sanitizer's problem, not ours.
action['content'] = content
continue
# The palette only ever nests the form section inside a wrapper
# snippet section, so a page-level one is always wrong; only a
# targeted replace may hold one as fragment root, to swap the
# existing nested form section in place.
selector = (action.get('selector') or '').strip().lower()
if (action.get('mode') in ('before', 'after') or not selector
or selector in _WHOLE_ZONE_SELECTORS.get(action.get('zone'), ())):
if any('s_website_form' in child.classes for child in root):
raise ValueError(
f"Action #{index}: a section carrying s_website_form cannot sit "
"directly at page level; it is always nested inside a wrapper "
"section, as in the droppable form snippets (s_title_form, "
"s_form_aside, s_website_form_cover). Fetch one and keep its "
"structure."
)
self._normalize_webforms(index, root)
action['content'] = (root.text or '') + ''.join(
lxml_html.tostring(child, encoding='unicode') for child in root)
@api.model
def _normalize_webforms(self, index, root):
"""Normalize every webform of the fragment, after the fragment-wide
checks: no form field outside a <form>, and a non-empty end message
for every form whose success mode shows one."""
if root.xpath(f'//*[({_with_class("s_website_form_field")} or {_with_class("s_website_form_input")}) and not(ancestor::form)]'):
raise ValueError(
f"Action #{index}: the HTML contains form fields outside of a <form> "
"element; they can never be submitted. Fetch a form snippet with "
"\"Get Snippets\" and keep the fields inside its <form>."
)
fields_by_model = {}
actions_by_key = self._get_webform_actions()
for form in root.xpath('//form'):
is_webform = form.get('data-model_name') or form.xpath(f'.//*[{_with_class("s_website_form_input")}]')
if not is_webform:
continue # e.g. a search bar
self._normalize_webform(index, form, actions_by_key, fields_by_model)
if form.get('data-success-mode') == 'message':
# The runtime looks the message up with
# `form.parentNode.querySelector`, so anywhere else is invisible.
message = form.getparent().xpath(f'.//*[{_with_class("s_website_form_end_message")}]')
if not message or (len(message[0]) == 0 and not (message[0].text or '').strip()):
raise ValueError(
f"Action #{index}: the form uses data-success-mode=\"message\" but "
"the div.s_website_form_end_message to show after submission is "
"missing or empty. Include it, with real themed content, as a "
"SIBLING right after the form in the SAME action (widen the "
"selector if it already exists on the page outside the replaced "
"element)."
)
@api.model
def _normalize_webform(self, index, form, actions_by_key, fields_by_model):
"""Normalize one webform: check its action wiring, structure and
fields, repairing what is purely mechanical and raising whenever the
model must rewrite its HTML."""
model = form.get('data-model_name')
if not model:
raise ValueError(
f"Action #{index}: the form has fields but no data-model_name, so "
"submissions go nowhere. Wire the form to an action with the "
"\"Set Form Action\" tool."
)
if model not in {a['model'] for a in actions_by_key.values()}:
raise ValueError(
f"Action #{index}: the form targets the model '{model}' which is not "
"enabled for website forms. Use the \"Get Webform Info\" tool to list "
"the available form actions and their models."
)
if model not in fields_by_model:
fields_by_model[model] = self.env['ir.model'].get_authorized_fields(model, {})
authorized_fields = fields_by_model[model]
rows = form.xpath(f'.//*[{_with_class("s_website_form_rows")}]')
submit = form.xpath(f'.//*[{_with_class("s_website_form_submit")}]')
if not rows or not submit:
raise ValueError(
f"Action #{index}: the form structure is incomplete (missing the "
"s_website_form_rows container or the s_website_form_submit block). "
"Fetch a form snippet with \"Get Snippets\" and keep its structure."
)
if not submit[0].xpath(f'.//*[{_with_class("s_website_form_send")}]'):
raise ValueError(
f"Action #{index}: the form has no submit button "
"(a.s_website_form_send inside the s_website_form_submit block)."
)
# The runtime renders the submission status after this span; without it
# every submit crashes in the visitor's browser.
if not submit[0].xpath('.//span[@id="s_website_form_result"]'):
span = etree.SubElement(submit[0], 'span')
span.set('id', 's_website_form_result')
send = submit[0].xpath(f'.//*[{_with_class("s_website_form_send")}]')[0]
send.addprevious(span)
if form.xpath('.//input[not(normalize-space(@name))] | .//select[not(normalize-space(@name))] | .//textarea[not(normalize-space(@name))]'):
raise ValueError(
f"Action #{index}: the form contains an input without a name; its "
"value would be lost on submission. Name every input."
)
invalid_types = {
field_type
for field_type in form.xpath(f'.//*[{_with_class("s_website_form_field")}]/@data-type')
if field_type not in _FIELD_TYPES
}
if invalid_types:
raise ValueError(
f"Action #{index}: invalid field data-type(s) "
f"{', '.join(sorted(invalid_types))} - the editor breaks on them. "
"data-type is the ORM field type, never the HTML input type "
f"(a numeric field is integer or float). Valid values: "
f"{', '.join(sorted(_FIELD_TYPES))}."
)
# One field without its structural label breaks the editing sidebar
# for the whole form.
if form.xpath(f'.//*[{_with_class("s_website_form_field")}'
f' and not({_with_class("s_website_form_dnone")})'
f' and not(.//label[{_with_class("s_website_form_label")}])]'):
raise ValueError(
f"Action #{index}: a field is missing its <label "
"class=\"s_website_form_label\">; every field wrapper must contain "
"one, single checkboxes included (their caption goes IN that label; "
"the form-check div holds only the input). Without it the field "
"cannot be edited."
)
# A native temporal input bypasses the date wrapper the runtime
# serializes from.
if form.xpath('.//input[@type="date" or @type="datetime-local" or @type="time"]'):
raise ValueError(
f"Action #{index}: never use native date inputs (type=\"date\", "
"\"datetime-local\" or \"time\"), their raw value makes every "
"submission crash. A date/datetime field is a text input with class "
"\"datetimepicker-input s_website_form_input\" inside a "
"div.s_website_form_date (or _datetime) with classes "
"\"input-group date\"."
)
for field in form.xpath(f'.//*[{_with_class("s_website_form_field")}]'
'[@data-type="date" or @data-type="datetime"]'):
if not field.xpath(f'.//*[{_with_class("s_website_form_date")} or {_with_class("s_website_form_datetime")}]'):
raise ValueError(
f"Action #{index}: a date/datetime field is missing its picker "
"wrapper: put the text input (class \"datetimepicker-input "
"s_website_form_input\") inside a div.s_website_form_date (or "
"_datetime) with classes \"input-group date\", or its value "
"crashes the submission."
)
self._normalize_file_inputs(index, form)
self._reconcile_field_names(index, form, authorized_fields)
self._check_bound_choice_values(index, form, authorized_fields)
self._check_required_fields(index, form, model)
if model == 'mail.mail':
self._ensure_email_to(form)
self._normalize_field_ids(form)
self._normalize_success_attrs(form)
@api.model
def _normalize_file_inputs(self, index, form):
"""Bounce accept values the submit validator cannot match, and stamp
default file count/size limits when missing or zero."""
for input_el in form.xpath(f'.//input[@type="file"][{_with_class("s_website_form_input")}]'):
accept = (input_el.get('accept') or '').strip()
if accept:
invalid = [value for value in map(str.strip, accept.split(','))
if value not in _FILE_ACCEPT_VALUES]
if invalid:
raise ValueError(
f"Action #{index}: the file field's accept value(s) "
f"{', '.join(invalid)} reject every upload. accept takes only: "
f"{', '.join(sorted(_FILE_ACCEPT_VALUES))} (comma-separated), "
"or omit it to allow any file."
)
for attr, default in (('data-max-files-number', '1'), ('data-max-file-size', '64')):
value = input_el.get(attr) or ''
if not value.isdigit() or int(value) == 0:
input_el.set(attr, default)
if int(input_el.get('data-max-files-number')) > 1:
input_el.set('multiple', '')
@api.model
def _reconcile_field_names(self, index, form, authorized_fields):
"""Make each field's custom-field marker match its input name, and
validate hidden presets.
A field bound to a model field must not carry the marker (the editor
renames a custom field's input after its label, dropping the binding);
an unknown name must carry it (unmarked, the name is sent to the
whitelist RPC at save, which rejects it). A hidden relational preset
must hold a numeric record id."""
for field in form.xpath(f'.//*[{_with_class("s_website_form_field")}]'):
if 's_website_form_dnone' in field.classes:
continue
name = _field_name(field)
if not name:
continue
classes = (field.get('class') or '').split()
is_bound = name in authorized_fields and not authorized_fields[name].get('_property')
if is_bound and 's_website_form_custom' in classes:
classes.remove('s_website_form_custom')
field.set('class', ' '.join(classes))
elif not is_bound and 's_website_form_custom' not in classes:
classes.append('s_website_form_custom')
field.set('class', ' '.join(classes))
for hidden in form.xpath(f'.//*[{_with_class("s_website_form_dnone")}]//input[@type="hidden"]'):
name = hidden.get('name')
field = authorized_fields.get(name)
if field and not field.get('_property') and field.get('type') in ('many2one', 'integer'):
value = hidden.get('value') or ''
if not value.isdigit():
raise ValueError(
f"Action #{index}: the hidden field '{name}' must hold the "
"numeric id of the targeted record (look it up with the "
f"retrieval tools), not '{value}'."
)
@api.model
def _check_bound_choice_values(self, index, form, authorized_fields):
"""A choice input bound to a model field posts its option `value`
verbatim, so anything but the field's selection key (or the record
id) makes the insert raise and the visitor's submit die silently."""
for field_el in form.xpath(f'.//*[{_with_class("s_website_form_field")}'
f' and not({_with_class("s_website_form_dnone")})]'):
name = _field_name(field_el)
field = name and authorized_fields.get(name)
if not field or field.get('_property'):
continue
# The empty entry is the editor's own "allow empty" option.
values = [value for value in field_el.xpath(
'.//input[@type="radio"]/@value | .//input[@type="checkbox"]/@value'
' | .//select//option/@value') if value]
if field.get('type') == 'selection':
keys = {str(key) for key, _label in (field.get('selection') or [])}
if any(value not in keys for value in values):
pairs = ', '.join(f"'{key}' = {label}" for key, label in (field.get('selection') or []))
raise ValueError(
f"Action #{index}: the options of the field '{name}' must have "
f"one of the model's selection keys as `value` ({pairs}), the "
"visible option text is free, the `value` is not. Other values "
"make every submission fail."
)
elif field.get('type') in ('many2one', 'one2many', 'many2many'):
if any(not value.isdigit() for value in values):
raise ValueError(
f"Action #{index}: the options of the relational field '{name}' "
"must have the targeted record's numeric id as `value` (look the "
"ids up with the retrieval tools), the visible option text is "
"free. Other values make every submission fail."
)
@api.model
def _check_required_fields(self, index, form, model):
"""Bounce when a required field of the target model has no input.
Only form-writable fields are demanded: a required field that is
blacklisted for website forms is the server's to fill (e.g. through a
`website_form_input_filter` hook), never the form's."""
names = set(form.xpath('.//input/@name | .//select/@name | .//textarea/@name'))
writable_fields = self.env['ir.model']._get(model)._get_form_writable_fields({})
missing = [
name for name, field in writable_fields.items()
if field.get('required') and not field.get('_property') and name not in names
]
if missing:
raise ValueError(
f"Action #{index}: the form targets '{model}' but is missing the "
f"mandatory field(s) {', '.join(missing)} - submissions would fail. "
"Add them as visible fields (or hidden preset fields with a value)."
)
@api.model
def _ensure_email_to(self, form):
"""Add the hidden email_to field back when the model dropped it. Without
it the form renders with no website_form_signature and the server
refuses every submission."""
if form.xpath('.//input[@name="email_to"]'):
return
rows = form.xpath(f'.//*[{_with_class("s_website_form_rows")}]')[0]
rows.insert(0, lxml_html.fragment_fromstring(
'<div data-name="Field" class="s_website_form_field s_website_form_dnone">'
'<input type="hidden" class="form-control s_website_form_input" name="email_to" value=""/>'
'</div>'))
@api.model
def _normalize_field_ids(self, form):
"""Regenerate every field input id (and its label's `for`). The model
copies snippet markup verbatim, so without this two forms on a page
share ids and labels focus the wrong input."""
for field in form.xpath(f'.//*[{_with_class("s_website_form_field")}]'):
inputs = field.xpath(f'.//*[{_with_class("s_website_form_input")}]')
if not inputs:
continue
base_id = 'o' + secrets.token_hex(6) # like the editor's generateHTMLId()
multiple = len(inputs) > 1
old_to_new = {}
for i, input_el in enumerate(inputs):
new_id = f'{base_id}{i}' if multiple else base_id
if input_el.get('id'):
old_to_new[input_el.get('id')] = new_id
input_el.set('id', new_id)
# An unset fill-with sometimes ends up serialized as the
# literal string "undefined"; drop it.
if input_el.get('data-fill-with') == 'undefined':
del input_el.attrib['data-fill-with']
for label in field.xpath('.//label[@for]'):
if label.get('for') in old_to_new:
label.set('for', old_to_new[label.get('for')])
@api.model
def _normalize_success_attrs(self, form):
"""Fall back to a valid success mode, and give redirect forms (the
default mode) a target page so submitting never dead-ends."""
mode = form.get('data-success-mode')
if mode not in _SUCCESS_MODES:
mode = 'redirect'
form.set('data-success-mode', mode)
if mode == 'redirect' and not (form.get('data-success-page') or '').strip():
form.set('data-success-page', '/contactus-thank-you')
# ------------------------------------------------------------------
# Webform tools
# ------------------------------------------------------------------
@api.model
def _get_webform_actions(self):
"""Map action key -> form-enabled model info, as the builder's Action
selector sees it."""
return {
(model['website_form_key'] or model['model']): model
for model in self.env['ir.model'].get_compatible_form_models()
}
@api.model
def _ai_tool_set_webform_action(self, action_key, form_selector, fields):
"""Validate the action key and delegate the wiring to the
`website_set_form_action` client tool, which runs the form editor's
own action-switch code on the page."""
if isinstance(fields, str):
with contextlib.suppress(json.JSONDecodeError):
fields = json.loads(fields)
actions = self._get_webform_actions()
if action_key not in actions:
return f"Unknown form action '{action_key}'. Available actions: {', '.join(actions)}."
return {"client_tool": {"name": "website_set_form_action", "params": {
"selector": form_selector,
"action_key": action_key,
"fields": fields if isinstance(fields, list) else [],
}}}
@api.model
def _ai_tool_get_webform_info(self, action_key):
"""Without an action key, list the available form actions; with one,
describe it: its model and the fields available for binding."""
actions = self._get_webform_actions()
if not actions:
return "No webform action is available on this database."
if not action_key:
result = (
"The webform actions available on this database (the action decides what "
"a submission creates):\n\n"
"| Action key | Name | Target model (data-model_name) |\n| --- | --- | --- |\n"
)
for key, action in actions.items():
result += f"| {key} | {action['website_form_label'] or action['name']} | {action['model']} |\n"
result += (
'\nCall this tool again with an action_key to list the model fields a '
'form input `name` can bind to.'
)
return result
action = actions.get(action_key)
if not action:
return f"Unknown form action '{action_key}'. Available actions: {', '.join(actions)}."
fields_data = self.env['ir.model'].get_authorized_fields(action['model'], {})
result = (
f"The form action '{action_key}' ({action['website_form_label'] or action['name']}) "
f"creates a '{action['model']}' record on submission "
f"(the form's data-model_name must be \"{action['model']}\").\n"
'Model fields a form input `name` can bind to (the visitor\'s input is '
'written to the field):\n\n'
"| Field | Label | Type | Required |\n| --- | --- | --- | --- |\n"
)
for name, field in sorted(fields_data.items()):
if field.get('_property'):
continue
field_type = field.get('type', '')
if field.get('selection'):
values = ", ".join(f"'{key}' = {label}" for key, label in field['selection'])
field_type += f" (option values: {values})"
required = 'yes' if field.get('required') else ''
result += f"| {name} | {field.get('string') or name} | {field_type} | {required} |\n"
result += (
"\nRequired fields MUST be present in the form (visible, or hidden with a "
"value) or submissions fail.\n"
"A relational field (many2one/many2many) can target a specific record "
"invisibly: put it in a hidden s_website_form_dnone field with the record's "
"numeric id as value (e.g. <input type=\"hidden\" name=\"project_id\" "
"value=\"42\"/>); find the id with the retrieval tools.\n"
"A visible input bound to a selection field must use the quoted keys above "
"as its option `value`s, VERBATIM (the visible option text is free); one "
"bound to a relational field uses the records' numeric ids.\n"
"Never invent a field name: an input whose name is not listed above is a "
"free-text answer stored as plain text, not data. Use such custom fields "
"for any question no listed field covers."
)
if action['model'] == 'mail.mail':
website = self.env['ai.website.service']._current_website()
company_email = (website.company_id.email or self.env.company.email or '').strip()
result += (
"\nThe hidden email_to input's value is the address that receives the "
"submissions; it must ALWAYS be chosen by the user. "
+ (f"The company address is {company_email} - offer it as the "
"recommended choice when asking."
if company_email else
"The company has no address configured - ask the user which "
"address to use.")
)
return result

View File

@@ -0,0 +1,21 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class AIWebPage(models.Model):
_inherit = 'ai.web.page'
def _get_internal_domains(self):
"""
OVERRIDE
Extend the internal domains with every website's domain.
Handles protocols, paths, and punycode fallback.
:return: list of internal domains
:rtype: list of str
"""
websites = self.env['website'].search([])
internal_domains = set(super()._get_internal_domains())
for site in websites:
if domain := self._get_url_domain(site.domain_punycode or site.domain):
internal_domains.add(domain)
return list(internal_domains)

View File

@@ -0,0 +1,13 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class AIWebScraperBatch(models.Model):
_inherit = 'ai.web.scraper.batch'
# Set when the batch is started by the `scrape_website_pages` AI tool, so that
# `ai.tool._web_scraper_result_ready` knows which conversation and which suspended
# tool call the result belongs to.
ai_session_id = fields.Many2one('ai.session', string="AI Session", ondelete='set null')
tool_call_id = fields.Char(string="Tool Call ID")

View File

@@ -0,0 +1,626 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import contextlib
import logging
import re
import psycopg2
from lxml import etree as lxml_etree
from lxml import html as lxml_html
from markupsafe import Markup
from odoo import api, models
from odoo.exceptions import ConcurrencyError
from odoo.tools.image import image_process
from odoo.addons.base.models.assetsbundle import AssetsBundle, StylesheetAsset
from odoo.addons.html_editor.controllers.main import attachment_create
from odoo.addons.web.icons import search_icons
_logger = logging.getLogger(__name__)
# A DB error leaves the transaction unusable, so a failure path must not fail open on one.
_UNRECOVERABLE = (psycopg2.Error, ConcurrencyError)
_USER_CUSTOM_RULES_URL = '/website/static/src/scss/user_custom_rules.scss'
_USER_CUSTOM_RULES_BUNDLE = 'web.assets_frontend'
_MAX_ACTIONS = 50
_MAX_ACTION_CONTENT_LENGTH = 500_000
_MAX_CSS_CONTENT_LENGTH = 100_000
# Also stated in the per-message context, see `_get_context_input` on `ai.session`.
MAX_GENERATED_IMAGES = 10
_WHOLE_ZONE_SELECTORS = {
'main': frozenset({'main', 'body', 'html', 'div#wrap', '#wrap'}),
'footer': frozenset({'footer', '#footer', 'footer#bottom', 'footer#bottom > #footer'}),
}
_ANIMATION_RUNTIME_CLASSES = frozenset({
'o_visible', 'o_animated', 'o_animating', 'o_animate_preview', 'o_animate_in_dropdown',
})
_ANIMATION_RUNTIME_STYLE_PROPS = ('visibility', 'animation-play-state', 'animation-name')
_PALETTE_TEXT_CLASSES = frozenset({'text-light', 'text-dark'})
_ICON_SHAPE_CLASSES = frozenset({'rounded', 'rounded-circle', 'rounded-0', 'rounded-leaf', 'img-thumbnail', 'shadow'})
_PADDING_UTILITY_RE = re.compile(
r'^p[tbsexy]?(-(sm|md|lg|xl|xxl))?-\d+$' # bootstrap: p-3, pt-3, px-lg-3
r'|^p[tbxy]?\d+$' # odoo: p16, pt48, pb16
)
# JavaScript patterns that allow data exfiltration or cross-frame attacks.
# The AI safety reviewer runs first, but this regex catches the most critical
# patterns deterministically.
_DANGEROUS_JS_RE = re.compile(
r'eval\s*\('
r'|new\s+Function\s*\('
r'|document\.cookie'
r'|navigator\.sendBeacon'
r'|(?<!\w)WebSocket\s*\(|(?<!\w)EventSource\s*\('
r'|window\.top|window\.parent|window\.opener'
r'|\.contentDocument|\.contentWindow'
r'|(?<!\w)postMessage\s*\('
r'|(?<!\w)import\s*\(|(?<!\w)require\s*\('
r'|set(?:Timeout|Interval)\s*\(\s*[\'\"]'
r'|document\.write(?:ln)?\s*\('
r'|createElement\s*\(\s*[\'\"`]\s*(?:script|iframe|object|embed)'
r'|\.\s*srcdoc\b'
r'|setHTMLUnsafe\s*\('
r'|javascript\s*:',
re.IGNORECASE,
)
_SCRIPT_TAG_RE = re.compile(r'<\s*script[\s>]', re.IGNORECASE)
# CSS patterns that can be used for script injection or data exfiltration.
_DANGEROUS_CSS_RE = re.compile(
r'javascript\s*:' # javascript: URLs inside url()
r'|@import\s+(?:url\()?["\']?https?://', # External stylesheet imports
re.IGNORECASE,
)
class AIWebsiteService(models.AbstractModel):
_name = 'ai.website.service'
_description = "AI Website Service"
@api.model
def _current_website(self):
"""The website being edited. `self.env.website` is only populated from a
`website_id` context key, so the id the builder sends comes first."""
website_id = (
self.env.context.get('current_view_info', {})
.get('website_page', {})
.get('website_id')
)
if website_id:
return self.env['website'].browse(website_id)
return self.env.website or self.env.ref('base.default_website')
@api.model
def _parse_html_fragment(self, html):
"""Parse an HTML fragment under a synthetic <div> wrapper; raises
ParserError/ValueError on bad input."""
return lxml_html.fragment_fromstring(html, create_parent='div')
@api.model
def _serialize_html_fragment(self, element):
"""Inner HTML of a parsed element (its own tag dropped); inverse of
``_parse_html_fragment``."""
return (element.text or '') + ''.join(
lxml_html.tostring(child, encoding='unicode') for child in element)
@api.model
def _create_public_image_url(self, attachment):
"""
Create a permanent attachment for the given attachment and return its
public URL.
Note: ensure the attachment is supposed to be public before calling
this method.
"""
attachment.ensure_one()
image = image_process(attachment.raw.content, verify_resolution=True)
attachment_data = {
'name': attachment.name,
'data': image,
}
new_attachment = attachment_create(self.env['ir.attachment'], **attachment_data)
return new_attachment.image_src
@api.model
def _ai_scripts_allowed(self, session_state):
"""Whether the AI may add JavaScript, website-wide or just in this chat."""
return bool(
self._current_website().ai_allow_scripts
or session_state.get('website_ai_allow_scripts')
)
@api.model
def _strip_animation_runtime_state(self, content):
"""Strip the Animation interaction's runtime classes + inline
visibility/animation props from AI HTML; saved, they freeze or hide
animated elements on the public site."""
if not content or ('o_animat' not in content and 'o_visible' not in content):
return content
try:
fragment = self._parse_html_fragment(content)
except (lxml_etree.ParserError, ValueError):
return content
for el in fragment.iter():
classes = el.get('class') or ''
if not classes:
continue
if _ANIMATION_RUNTIME_CLASSES & set(classes.split()):
el.set('class', ' '.join(c for c in classes.split() if c not in _ANIMATION_RUNTIME_CLASSES))
style = el.get('style')
if style and 'o_animate' in classes:
kept = [d.strip() for d in style.split(';')
if d.strip() and d.split(':', 1)[0].strip().lower() not in _ANIMATION_RUNTIME_STYLE_PROPS]
if kept:
el.set('style', '; '.join(kept) + ';')
else:
el.attrib.pop('style')
return self._serialize_html_fragment(fragment)
@api.model
def _strip_palette_text_utilities(self, content):
"""Drop `text-light`/`text-dark`: they are palette slots 3 and 5, not shades, so on a dark palette the text vanishes into its background.
Often happens as LLM is told to generate bootstrap, so conflict on that class happen"""
if not content or not any(cls in content for cls in _PALETTE_TEXT_CLASSES):
return content
try:
fragment = self._parse_html_fragment(content)
except (lxml_etree.ParserError, ValueError):
return content
for el in fragment.iter():
classes = (el.get('class') or '').split()
if not _PALETTE_TEXT_CLASSES.intersection(classes):
continue
kept = [c for c in classes if c not in _PALETTE_TEXT_CLASSES]
if kept:
el.set('class', ' '.join(kept))
else:
el.attrib.pop('class')
return self._serialize_html_fragment(fragment)
@api.model
def _find_icon_by_keywords(self, keywords):
"""Return the name of the first icon whose name or tags match one of the
given keywords, trying keywords in order."""
for keyword in keywords:
if not keyword.strip():
continue
if match := next(search_icons(keyword), None):
return match[0]
return None
@api.model
def _generate_placeholder_icons(self, content):
"""
Fill in every `data-ai-icon-keywords` placeholder the AI left behind.
This is done by letting the AI choose 3 keywords and looking for matches
for an icon. Once found, we replace in text the correct icon.
"""
if not content or 'data-ai-icon-keywords' not in content:
return content
try:
fragment = self._parse_html_fragment(content)
except (lxml_etree.ParserError, ValueError):
return content
placeholders = fragment.xpath('.//*[@data-ai-icon-keywords]')
if not placeholders:
return content
for element in placeholders:
keywords = element.attrib.pop('data-ai-icon-keywords').split(',')
if icon_name := self._find_icon_by_keywords(keywords):
element.set('data-icon', icon_name)
return self._serialize_html_fragment(fragment)
@api.model
def _fix_icon_shape_padding(self, content):
"""
The AI keeps adding extra padding on the icons so this class removes
them if found.
"""
if not content or 'oi' not in content:
return content
try:
fragment = self._parse_html_fragment(content)
except (lxml_etree.ParserError, ValueError):
return content
changed = False
for el in fragment.iter():
classes = (el.get('class') or '').split()
if 'oi' not in classes or not _ICON_SHAPE_CLASSES.intersection(classes):
continue
kept = [c for c in classes if not _PADDING_UTILITY_RE.match(c)]
if len(kept) != len(classes):
el.set('class', ' '.join(kept))
changed = True
return self._serialize_html_fragment(fragment) if changed else content
@api.model
def _validate_html_actions(self, actions, session_state):
"""Sanity-check the HTML actions produced by the AI, raising on anything
unsafe or out of bounds. The markup is sanitized in the builder, which
knows to set the AI scripts aside first."""
if len(actions) > _MAX_ACTIONS:
raise ValueError(f"Too many actions {len(actions)}. Maximum allowed per call is {_MAX_ACTIONS}.")
for i, action in enumerate(actions):
content = action.get('content', '')
content_length = len(content)
if content_length > _MAX_ACTION_CONTENT_LENGTH:
raise ValueError(f"Action #{i}: content is too long ({content_length} characters). Maximum allowed is {_MAX_ACTION_CONTENT_LENGTH} characters.")
# The JavaScript gates run on the raw content, before any rewriting.
if _SCRIPT_TAG_RE.search(content) and not self._ai_scripts_allowed(session_state):
raise ValueError(
f"Action #{i}: adding JavaScript is turned off. Ask the user whether "
"to allow it this time, always, or not at all, and do not "
"try to deliver this behaviour some other way."
)
if _DANGEROUS_JS_RE.search(content):
raise ValueError(f"Action #{i}: content contains a forbidden pattern.")
@api.model
def _find_image_placeholders(self, content):
try:
fragment = self._parse_html_fragment(content)
except (lxml_etree.ParserError, ValueError):
return None, []
return fragment, fragment.xpath('.//*[@data-ai-image-prompt]')
@api.model
def _validate_image_placeholders(self, actions):
"""
To avoid dropping images later in _generate_placeholder_images which could
create ugly content, we instead try to catch the mistakes now and make the agent
retry.
"""
image_count = 0
blank_prompt_action_indexes = []
for i, action in enumerate(actions):
content = action.get('content')
if not content:
continue
_fragment, placeholders = self._find_image_placeholders(content)
image_count += len(placeholders)
if not all((p.get('data-ai-image-prompt') or '').strip() for p in placeholders):
blank_prompt_action_indexes.append(str(i))
# Accumulate the errors and raise them in one go.
errors = []
if image_count > MAX_GENERATED_IMAGES:
errors.append(
f"{image_count} images requested across all actions, but at most {MAX_GENERATED_IMAGES} "
"can be generated per call. Reduce the number of `data-ai-image-prompt` placeholders, "
"or split the actions across multiple calls, and try again.",
)
if blank_prompt_action_indexes:
actions_label = "Action" if len(blank_prompt_action_indexes) == 1 else "Actions"
errors.append(
f"{actions_label} {', '.join(blank_prompt_action_indexes)}: has a "
"`data-ai-image-prompt` placeholder with a blank prompt. Fill in a prompt for every "
"image placeholder, or remove the placeholder, and try again.",
)
if errors:
raise ValueError(" ".join(errors))
@api.model
def _sanitize_html_actions(self, actions):
"""Normalise HTML actions produced by the AI in place: clear the selector
on a whole-zone replace and rewrite content the model shouldn't hand-author
(animation runtime state, palette text utilities, icon padding/keywords)."""
for action in actions:
selector = (action.get('selector') or '').strip()
whole_zone_selectors = _WHOLE_ZONE_SELECTORS.get(action.get('zone'), frozenset())
if action.get('mode') == 'replace' and selector.lower() in whole_zone_selectors:
action['selector'] = ''
content = action.get('content', '')
content = self._strip_animation_runtime_state(content)
content = self._strip_palette_text_utilities(content)
content = self._fix_icon_shape_padding(content)
action['content'] = self._generate_placeholder_icons(content)
@api.model
def _get_website_assets(self):
return self.env['website.assets'].with_context(website_id=self._current_website().id)
@api.model
def _read_custom_css(self):
"""Read the current content of user_custom_rules.scss."""
assets = self._get_website_assets()
content = assets._get_content_from_url(
assets._make_custom_asset_url(
_USER_CUSTOM_RULES_URL, _USER_CUSTOM_RULES_BUNDLE), {'customized': True}
).decode()
if content and content.strip():
return content.strip()
return "The user_custom_rules.scss file is empty (no custom CSS rules yet)."
@api.model
def _validate_css_content(self, css_content):
"""
Guard against known CSS injection patterns and enforce a size limit.
"""
content_length = len(css_content)
if content_length > _MAX_CSS_CONTENT_LENGTH:
raise ValueError(f"CSS content is too large ({content_length} characters). Maximum allowed is {_MAX_CSS_CONTENT_LENGTH} characters.")
if _DANGEROUS_CSS_RE.search(css_content):
raise ValueError("CSS content contains potentially dangerous patterns (e.g javascript:, external @import).")
@api.model
def _compile_custom_css(self, css_content):
"""Compile AI provided SCSS against the frontend bundle without saving it."""
if not css_content or not css_content.strip():
return
fake_bundle = 'ai_website.custom_css_validation'
# Inline content skips StylesheetAsset._fetch_content, which rewrites
# relative url()s with the asset's /_custom/... path. That can break
# valid SCSS (e.g. `url($var)`), so we test it here.
custom_url = self._get_website_assets()._make_custom_asset_url(_USER_CUSTOM_RULES_URL, _USER_CUSTOM_RULES_BUNDLE)
web_dir = custom_url.rsplit('/', 1)[0]
css_content = StylesheetAsset.rx_url.sub(fr"url(\1{web_dir}/", css_content)
bundle = AssetsBundle(
fake_bundle,
[{
'url': 'custom_ai_css.scss',
'filename': '',
'content': css_content,
'last_modified': None,
'definition_bundle': fake_bundle
}],
{},
env=self.env,
css=True,
js=False,
assets_params={},
)
bundle.preprocess_css()
if bundle.css_errors:
raise ValueError("\n".join(bundle.css_errors))
@api.model
def _save_custom_css(self, css_content):
"""Validate, compile, persist user_custom_rules.scss and reload the
bundles. Shared by the write-css tool and the refinement CSS pass so
neither can skip a validation step."""
scoped = self.with_context(website_id=self._current_website().id)
scoped._validate_css_content(css_content)
scoped._compile_custom_css(css_content)
scoped.env['website.assets'].save_asset(
_USER_CUSTOM_RULES_URL, _USER_CUSTOM_RULES_BUNDLE,
css_content, 'scss',
)
self.env.user._bus_send("ai_website/reload_css_bundles", {})
@api.model
def _find_unscoped_css_selectors(self, css_content):
"""Find selectors that would leak across the whole site.
user_custom_rules.scss is loaded on every page, so a top-level rule like
``section {}`` restyles every section everywhere, not just the page the
AI built. Return the bare element selectors (``section``, ``h2``, …) that
aren't anchored to a class, id, ``&`` or ``:root``; at-rules, variables
and placeholders (``@``/``$``/``%``) are left alone. This is a best-effort
text scan meant to drive a warning, not a strict CSS parser."""
content = re.sub(r'//[^\n]*', '', re.sub(r'/\*.*?\*/', '', css_content, flags=re.S))
unscoped, depth, buf = [], 0, []
for char in content:
if char == '{':
if depth == 0:
selector = ''.join(buf).strip().rsplit(';', 1)[-1].strip()
if selector and not selector.startswith(('@', '$', '%')):
unscoped += [p.strip() for p in selector.split(',')
if p.strip() and not re.search(r'[.#&]|:root', p)]
buf = []
depth += 1
elif char == '}':
depth = max(depth - 1, 0)
if depth == 0:
buf = []
elif depth == 0:
buf.append(char)
return unscoped
@api.model
def _format_website_menu_tree(self, website):
"""Render the website menu hierarchy as an indented text list."""
def format_menu(menu, level):
flags = ''
if menu.new_window:
flags += ', opens in a new window'
if menu.is_mega_menu:
flags += ', mega menu (its content cannot be edited with the available tools)'
line = (
f'{" " * level}- ID: {menu.id}, Name: "{menu.name}", '
f'URL: "{menu.url}", Sequence: {menu.sequence}{flags}\n'
)
return line + ''.join(format_menu(child, level + 1) for child in menu.child_id)
top_menus = website.menu_id.child_id
if not top_menus:
return "The website menu is currently empty.\n"
return ''.join(format_menu(menu, 0) for menu in top_menus)
@api.model
def _format_website_menu_tree_html(self, website, created_ids, updated_ids, deleted_records):
"""
Render the (dry-run) website menu hierarchy as an HTML tree, highlighting
additions, changes and removals for the user confirmation preview.
"""
style_by_status = {
'created': 'color:#1f7a1f;',
'updated': 'color:#8a6d00;',
'deleted': 'color:#b02a2a; text-decoration: line-through;',
}
label_by_status = {
'created': self.env._(" (added)"),
'updated': self.env._(" (changed)"),
'deleted': self.env._(" (removed)"),
}
def render_node(name, new_window, is_mega_menu, status):
flags = ''
if new_window:
flags += self.env._(", opens in a new window")
if is_mega_menu:
flags += self.env._(", mega menu")
return Markup('<span style="%s">%s%s%s</span>') % (
style_by_status.get(status, ''), name, flags, label_by_status.get(status, ''),
)
deleted_by_parent_id = {}
for record in deleted_records:
deleted_by_parent_id.setdefault(record['parent_id'], []).append(record)
def render_deleted_subitems(parent_id):
# Menus are at most two levels deep, so a deleted item's own deleted
# sub-items (from the cascade) never have children of their own.
records = sorted(deleted_by_parent_id.get(parent_id, []), key=lambda r: (r['sequence'], r['id']))
if not records:
return Markup()
items = Markup().join(
Markup('<li>%s</li>') % render_node(record['name'], record['new_window'], record['is_mega_menu'], 'deleted')
for record in records
)
return Markup('<ul>%s</ul>') % items
def render_children(parent_menu, parent_id):
combined = [
(menu.sequence, menu.id, False, menu)
for menu in parent_menu.child_id
] + [
(record['sequence'], record['id'], True, record)
for record in deleted_by_parent_id.get(parent_id, [])
]
# Maintain the order -> compare ids for menu items that share
# the same sequence value (i.e. deleted menu and it's replacement)
combined.sort(key=lambda entry: (entry[0], entry[1]))
items = Markup()
for _sequence, menu_id, is_deleted, data in combined:
if is_deleted:
items += Markup('<li>%s%s</li>') % (
render_node(data['name'], data['new_window'], data['is_mega_menu'], 'deleted'),
render_deleted_subitems(menu_id),
)
continue
status = 'created' if menu_id in created_ids else 'updated' if menu_id in updated_ids else None
items += Markup('<li>%s%s</li>') % (
render_node(data.name, data.new_window, data.is_mega_menu, status),
render_children(data, menu_id),
)
return Markup('<ul>%s</ul>') % items if items else Markup()
tree_html = render_children(website.menu_id, website.menu_id.id)
if not tree_html:
return Markup('<p>%s</p>') % self.env._("The website menu would be empty.")
return tree_html
@api.model
def _prefetch_menus_for_operations(self, website, operations):
"""Batch-fetch every menu referenced by menu_id/parent_menu_id across the operations,
instead of searching once per lookup."""
referenced_ids = set()
for operation in operations:
for mid in (operation.get('menu_id'), operation.get('parent_menu_id')):
if not mid:
continue
with contextlib.suppress(TypeError, ValueError):
referenced_ids.add(int(mid))
if not referenced_ids:
return {}
return {
menu.id: menu
for menu in self.env['website.menu'].search([
('id', 'in', list(referenced_ids)),
('website_id', '=', website.id),
])
}
@staticmethod
def _drop_unfilled_placeholder(image):
"""Remove an <img> placeholder that got no image: kept, it renders as a broken one.
A background element is left as-is instead: removing it would break the section's layout."""
if image.tag == 'img' and not image.get('src') and (parent := image.getparent()) is not None:
parent.remove(image)
@staticmethod
def _set_background_image(element, url):
# Preserve the element's styles but replace the background image.
declarations = [
declaration for declaration in (element.get('style') or '').split(';')
if declaration.strip() and declaration.split(':', 1)[0].strip() != 'background-image'
]
declarations.append(f" background-image: url('{url}')")
element.set('style', ';'.join(declarations).strip() + ';')
@api.model
def _generate_image_url(self, prompt, aspect_ratio):
"""The public URL of one generated image, or None; a failure costs its own placeholder only."""
try:
_result, attachments = self.env['ai.tool']._generate_image_attachments(
prompt, [], prompt[:40], aspect_ratio)
if attachments:
return self._create_public_image_url(attachments[0])
except _UNRECOVERABLE:
raise
except Exception:
_logger.exception("could not generate image for %r; dropping it", prompt[:80])
return None
@api.model
def _generate_placeholder_images(self, page_html, batch_size=None):
"""Fill in every `data-ai-image-prompt` placeholder the builder left behind:
an `<img>` gets its `src` set, any other element (e.g. an `oe_img_bg` span or
div used as a parallax/cover background) gets its `background-image` style set."""
fragment, placeholders = self._find_image_placeholders(page_html)
if not placeholders:
return page_html
if len(placeholders) > MAX_GENERATED_IMAGES:
_logger.info("page asked for %d images, generating the first %d",
len(placeholders), MAX_GENERATED_IMAGES)
for skipped in placeholders[MAX_GENERATED_IMAGES:]:
skipped.attrib.pop('data-ai-image-prompt', None)
self._drop_unfilled_placeholder(skipped)
placeholders = placeholders[:MAX_GENERATED_IMAGES]
if batch_size is not None:
placeholders = placeholders[:batch_size]
jobs, targets = [], []
for image in placeholders:
prompt = (image.get('data-ai-image-prompt') or '').strip()
# A full-bleed background is cropped to a wide band.
full_bleed = {'s_parallax_bg', 'oe_img_bg'} & set((image.get('class') or '').split())
aspect_ratio = image.get('data-ai-image-aspect') or ('16:9' if full_bleed else '3:2')
image.attrib.pop('data-ai-image-prompt')
image.attrib.pop('data-ai-image-aspect', None)
if prompt:
jobs.append((prompt, aspect_ratio))
targets.append(image)
else:
self._drop_unfilled_placeholder(image)
agent = self.env.ref('ai_website.ai_agent_website_builder', raise_if_not_found=False)
if not agent:
_logger.warning("builder agent not found; dropping the placeholders")
for image in targets:
self._drop_unfilled_placeholder(image)
return self._serialize_html_fragment(fragment)
for image, (prompt, aspect_ratio) in zip(targets, jobs):
if url := self._generate_image_url(prompt, aspect_ratio):
if image.tag == 'img':
image.set('src', url)
else:
self._set_background_image(image, url)
else:
self._drop_unfilled_placeholder(image)
return self._serialize_html_fragment(fragment)

View File

@@ -0,0 +1,191 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import re
from markupsafe import Markup
from odoo import _, api, models
_USER_WEBSITE_VALUES_URL = '/website/static/src/scss/options/user_values.scss'
_USER_COLOR_PALETTE_URL = '/website/static/src/scss/options/colors/user_color_palette.scss'
_HEX_COLOR_RE = re.compile(r'^#[0-9A-Fa-f]{6}$')
_CC_PRESET_SLOTS = frozenset({'bg', 'text', 'headings', 'link', 'btn-primary', 'btn-secondary'})
_BRAND_FONTS = frozenset({
'Inter', 'Poppins', 'Montserrat', 'Work Sans', 'DM Sans', 'Manrope',
'Space Grotesk', 'Sora', 'Archivo', 'Outfit', 'Plus Jakarta Sans',
'Roboto', 'Open Sans', 'Lato', 'Nunito Sans', 'Karla',
'Playfair Display', 'Lora', 'Cormorant Garamond', 'DM Serif Display',
'Libre Baskerville', 'Fraunces', 'Bitter', 'Spectral',
'Syne', 'Bricolage Grotesque', 'Unbounded',
})
_CORNER_PRESETS = {
'sharp': {'btn-border-radius': '0', 'btn-border-radius-sm': '0',
'btn-border-radius-lg': '0', 'input-border-radius': '0'},
'subtle': {'btn-border-radius': '0.25rem', 'btn-border-radius-sm': '0.2rem',
'btn-border-radius-lg': '0.3rem', 'input-border-radius': '0.25rem'},
'rounded': {'btn-border-radius': '0.75rem', 'btn-border-radius-sm': '0.6rem',
'btn-border-radius-lg': '1rem', 'input-border-radius': '0.6rem'},
'pill': {'btn-border-radius': '2rem', 'btn-border-radius-sm': '2rem',
'btn-border-radius-lg': '2rem', 'input-border-radius': '2rem'},
}
def _shadow_tier(infix, offset_y, blur, alpha):
base = 'box-shadow' + (f'-{infix}' if infix else '')
return {
f'{base}-color': f'rgba(0, 0, 0, {alpha})',
f'{base}-offset-x': '0',
f'{base}-offset-y': offset_y,
f'{base}-blur-radius': blur,
f'{base}-spread-radius': '0',
}
def _shadow_preset(normal, small, large):
return {**_shadow_tier('', *normal), **_shadow_tier('sm', *small), **_shadow_tier('lg', *large)}
_SHADOW_PRESETS = {
'none': _shadow_preset(('0', '0', '0'), ('0', '0', '0'), ('0', '0', '0')),
'flat': _shadow_preset(('0.125rem', '0.25rem', '0.08'), ('0.0625rem', '0.125rem', '0.06'),
('0.25rem', '0.5rem', '0.1')),
'soft': _shadow_preset(('0.5rem', '1.5rem', '0.1'), ('0.125rem', '0.375rem', '0.08'),
('1rem', '2.5rem', '0.14')),
'dramatic': _shadow_preset(('1rem', '2rem', '0.18'), ('0.25rem', '0.5rem', '0.12'),
('1.75rem', '3.5rem', '0.28')),
}
class AIWebsiteService(models.AbstractModel):
_inherit = 'ai.website.service'
@api.model
def _write_scss_customization(self, url, values):
self.env['website.assets'].with_context(
website_id=self._current_website().id,
).make_scss_customization(url, values)
@api.model
def _read_scss_customization(self, assets, url):
"""Read back the key/value pairs `make_scss_customization` wrote into `url`,
falling back to the uncustomized file — same fallback the writer itself
uses — so a site that was never customized reads as empty, not an error."""
custom_url = assets._make_custom_asset_url(url, 'web.assets_frontend')
content = assets._get_content_from_url(custom_url) or assets._get_content_from_url(url)
return dict(re.findall(r"'([\w-]+)':\s*([^,\n]+),", content.decode('utf-8')))
@api.model
def _get_current_brand_kit(self):
"""Describe the site's current palette and fonts — the theme's defaults
if "Apply Brand Kit" was never called — so the agent can match new pages
to what's actually live instead of guessing or reapplying it from scratch."""
assets = self.env['website.assets'].with_context(website_id=self._current_website().id)
colors = self._read_scss_customization(assets, _USER_COLOR_PALETTE_URL)
values = self._read_scss_customization(assets, _USER_WEBSITE_VALUES_URL)
palette = [colors[f'o-color-{i}'] for i in range(1, 6) if f'o-color-{i}' in colors]
heading_font = values.get('headings-font', '').strip("'\"")
body_font = values.get('font', '').strip("'\"")
palette_text = ', '.join(palette) if palette else "theme default (not customized)"
fonts_text = (
f"headings: {heading_font or 'default'}, body: {body_font or 'default'}"
if heading_font or body_font else "theme default (not customized)"
)
return f"Current palette: {palette_text}. Current fonts: {fonts_text}."
@api.model
def _build_palette_values(self, o_color_1, o_color_2, o_color_3, o_color_4, o_color_5, cc_presets=None):
"""Validate and assemble the user_color_palette.scss values, or return
``(None, error_message)`` on bad input."""
main_colors = {f'o-color-{i}': c for i, c in enumerate(
(o_color_1, o_color_2, o_color_3, o_color_4, o_color_5), start=1)}
for key, value in main_colors.items():
if not _HEX_COLOR_RE.match(value or ''):
return None, f"Invalid hex color for {key}: {value!r}. Use a 6-digit hex like '#A1B2C3'."
values = dict(main_colors)
for preset in cc_presets or []:
index = preset.get('index')
if index not in (1, 2, 3, 4, 5):
return None, f"Invalid cc_presets entry — 'index' must be an integer 1..5 (got {index!r})."
for slot, color in preset.items():
if slot == 'index' or color is None:
continue
if slot not in _CC_PRESET_SLOTS:
return None, f"Invalid cc_presets slot {slot!r} on index {index}. Allowed: {sorted(_CC_PRESET_SLOTS)}."
if not _HEX_COLOR_RE.match(color):
return None, f"Invalid hex color for o-cc{index}-{slot}: {color!r}. Use a 6-digit hex like '#A1B2C3'."
values[f'o-cc{index}-{slot}'] = color
return values, None
@api.model
def _build_typography_values(self, typography):
"""Validate fonts against _BRAND_FONTS and assemble the user_values.scss
font keys. heading_font + body_font are required together; button_font is
optional. Empty typography yields ``({}, None)``."""
if not typography:
return {}, None
heading = (typography.get('heading_font') or '').strip()
body = (typography.get('body_font') or '').strip()
button = (typography.get('button_font') or '').strip()
if not heading or not body:
return None, "typography requires both 'heading_font' and 'body_font'."
for font in (heading, body, button):
if font and font not in _BRAND_FONTS:
return None, f"Unknown font {font!r}. Choose from the brand font catalog: {', '.join(sorted(_BRAND_FONTS))}."
values = {'font': f"'{body}'", 'headings-font': f"'{heading}'"}
if button:
values['buttons-font'] = f"'{button}'"
google = list(dict.fromkeys(f for f in (heading, body, button) if f))
values['google-fonts'] = "('" + "', '".join(google) + "')"
return values, None
@api.model
def _build_design_values(self, design):
"""Map the corner/shadow keywords to their theme variables. Empty design
yields ``({}, None)``."""
if not design:
return {}, None
values = {}
corners = (design.get('corners') or '').strip().lower()
if corners:
if corners not in _CORNER_PRESETS:
return None, f"Unknown corners preset {corners!r}. Allowed: {', '.join(sorted(_CORNER_PRESETS))}."
values.update(_CORNER_PRESETS[corners])
shadow = (design.get('shadow') or '').strip().lower()
if shadow:
if shadow not in _SHADOW_PRESETS:
return None, f"Unknown shadow preset {shadow!r}. Allowed: {', '.join(sorted(_SHADOW_PRESETS))}."
values.update(_SHADOW_PRESETS[shadow])
return values, None
@api.model
def _brand_kit_confirmation_message(self, palette_values, typography, design):
"""The site-wide warning the user must accept before the brand kit is written."""
items = []
if palette_values:
swatches = Markup('').join(
# `background-color`, not `background`: the mail sanitizer drops the shorthand.
Markup('<span style="display:inline-block;width:14px;height:14px;margin-right:3px;'
'vertical-align:middle;border:1px solid rgba(0,0,0,.2);border-radius:3px;'
'background-color:%s"></span>') % palette_values[f'o-color-{i}']
for i in range(1, 6)
)
items.append(Markup('%s %s') % (_("A new colour palette:"), swatches))
if typography and typography.get('heading_font'):
items.append(_(
"New fonts: %(heading)s for the titles, %(body)s for the text.",
heading=typography['heading_font'], body=typography['body_font'],
))
if style := ", ".join(part for part in (
(design or {}).get('corners'), (design or {}).get('shadow')) if part):
items.append(_("A new corner and shadow style: %s.", style))
return Markup('<p>%s</p><ul>%s</ul><p><b>%s</b></p>') % (
_("Before I start, I'd like to set the overall look of the site:"),
Markup('').join(Markup('<li>%s</li>') % item for item in items),
_("This applies to every page of your website, not only this one. Shall I go ahead?"),
)

View File

@@ -0,0 +1,642 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
import logging
import re
from urllib.parse import quote
import psycopg2
from lxml import etree as lxml_etree
from lxml import html as lxml_html
from odoo import api, models
from odoo.exceptions import ConcurrencyError, UserError
from odoo.addons.ai.utils.ai_utils import get_text_from_parts
_logger = logging.getLogger(__name__)
# A DB error leaves the transaction unusable, so the passes below must not fail open on one.
_UNRECOVERABLE = (psycopg2.Error, ConcurrencyError)
# Kept under --limit-time-real (120s)
_REFINEMENT_PASS_TIMEOUT = 90
# Max kept length of a text node / asset URL when abridging the page for a pass.
_SKELETON_MAX_TEXT = 80
_SKELETON_MAX_URL = 160
# Below this RGB distance a bridged band is invisible ("blank divider"), so drop it.
_MIN_DIVIDER_BG_CONTRAST = 48
# `clearance` = min px padding to add on the anchored edge so content clears the shape's band.
_SHAPE_REGISTRY = {
'Connections/01': {'position': 'bottom', 'slots': (5,), 'clearance': 96},
'Connections/02': {'position': 'bottom', 'slots': (5,), 'clearance': 96},
'Connections/05': {'position': 'bottom', 'slots': (5,), 'clearance': 96},
'Connections/06': {'position': 'bottom', 'slots': (5,), 'clearance': 96},
'Connections/07': {'position': 'bottom', 'slots': (5,), 'clearance': 96},
'Connections/08': {'position': 'bottom', 'slots': (5,), 'clearance': 96},
'Connections/11': {'position': 'bottom', 'slots': (5,), 'clearance': 96},
'Connections/12': {'position': 'bottom', 'slots': (5,), 'clearance': 96},
'Connections/15': {'position': 'bottom', 'slots': (5,), 'clearance': 96},
'Connections/16': {'position': 'bottom', 'slots': (5,), 'clearance': 96},
'Connections/17': {'position': 'bottom', 'slots': (5,), 'clearance': 96},
'Connections/18': {'position': 'bottom', 'slots': (5,), 'clearance': 96},
'Floats/01': {'position': 'center right', 'slots': (1, 2, 3, 4, 5)},
'Floats/02': {'position': 'center', 'slots': (1, 2, 3, 5)},
'Floats/05': {'position': 'center', 'slots': (1, 2, 3, 5)},
'Floats/09': {'position': 'center right', 'slots': (1, 2, 3)},
'Floats/13': {'position': 'center', 'slots': (1, 2, 5)},
'Floats/14': {'position': 'center', 'slots': (1, 2, 3, 5)},
'Rainy/01_001': {'position': 'bottom', 'slots': (1, 5)},
'Rainy/02_001': {'position': 'top', 'slots': (1, 4, 5), 'clearance': 96},
'Rainy/08_001': {'position': 'top', 'slots': (1, 4), 'clearance': 96},
'Rainy/10': {'position': 'center', 'slots': (1, 3)},
'Zigs/01_001': {'position': 'bottom', 'slots': (2,)},
'Blobs/01_001': {'position': 'top', 'slots': (2,), 'clearance': 160},
'Blobs/03': {'position': 'top', 'slots': (2,), 'clearance': 96},
'Blobs/05_001': {'position': 'bottom', 'slots': (1,), 'clearance': 128},
'Blobs/06_001': {'position': 'top', 'slots': (1,), 'clearance': 160},
'Blobs/13': {'position': 'bottom', 'slots': (1, 5)},
'Blurry/01': {'position': 'center', 'slots': (1,)},
'Blurry/03': {'position': 'bottom', 'slots': (1, 2, 3, 4)},
'Blurry/05': {'position': 'center', 'slots': (1, 2, 4)},
'Blurry/06': {'position': 'center', 'slots': (1, 4)},
'Grids/01': {'position': 'bottom', 'slots': (5,)},
'Angular/05': {'position': 'bottom', 'slots': (5,), 'clearance': 240},
'Angular/06': {'position': 'bottom', 'slots': (1, 3, 5), 'clearance': 240},
}
_SHAPES_PASS_SCHEMA = {
"type": "object",
"properties": {
"placements": {
"type": "array",
"description": "Shape placements — usually several (connect most section transitions, accent the sparse sections)",
"items": {
"type": "object",
"properties": {
"section_index": {"type": "integer",
"description": "1-based index of the target section among the top-level sections"},
"shape": {"type": "string", "description": "Catalog key, e.g. 'Connections/02' or 'Floats/01'"},
"colors": {"type": "object", "description": "Color slot overrides; only slots this shape uses",
"properties": {slot: {"type": "string", "description": "One of o-color-1..o-color-5"}
for slot in ('c1', 'c2', 'c3', 'c4', 'c5')}},
"edge": {"type": "string", "enum": ["top", "bottom"],
"description": "Which edge the divider anchors to; the system flips/repositions automatically."},
"flip": {"type": "string", "enum": ["x", "y", "xy"],
"description": "Optional aesthetic mirroring ('x'); vertical anchoring is handled by `edge`."},
"reason": {"type": "string", "description": "One line: why this shape serves this section"},
},
"required": ["section_index", "shape", "reason"],
},
},
},
"required": ["placements"],
}
_SHAPES_CATALOG = """
### How to choose — by SECTION SIZE first, then mood
- A BIG section (a hero, a CTA, a tall quote — sparse, with room to breathe and
generous pt/pb padding) earns an ANIMATED shape: Floats, Rainy or Zigs.
- A SMALL or tight transition where two flat colour sections meet gets a thin
static Connections divider — quiet, never animated.
- COHERENCE: pick ONE animated family for the big moments and use Connections
for every small transition; that pairing IS the page's whole shape language.
Never scatter two or three different animated families across one page.
- Mood only tints WHICH options you reach for within that rule: Angular ridges
for bold/architectural, Blobs for organic/human/craft, Grids for tech/data,
Blurry glows for premium/dreamy. The SIZE rule comes first.
### Small-transition dividers — thin band where two flat sections meet
Connections (all c5, thin band; paint them in the NEXT section's background):
01 diagonal ramp - 02 single sweeping wave - 05 dome - 06 U valley -
07 soft hill - 08 double-shoulder dip - 11 round shoulder sweep -
12 concave slope - 15 two-tone overlapping waves - 16 layered triple wave -
17 small centred peak - 18 small soft dome.
### Animated accents — BIG / sparse sections only (heroes, CTAs, big quotes)
Floats: 01 corner circle + dot grids - 02 scattered mini-shapes - 05 squiggle +
dotted circle - 09 curved S-lines right - 13 sparse confetti - 14 confetti
triangles. Rainy: 01_001 (c1,c5) flying capsule cluster - 10 (c1,c3) tiny ticks
band - 02_001 (c1,c4,c5, top) capsule streaks - 08_001 (c1,c4, top) soft streaks.
Zigs/01_001 (c2) zigzag mountain band. Blobs/01_001 (c2, TALL, top) breathing blob.
### Mood backdrops & ridges — bigger sections, static, by mood
Blurry (soft glows behind sparse hero/CTA text): 01 (c1) glowing ellipse chain -
03 (c1,c2,c3,c4) two-tone curve - 05 (c1,c2,c4) corner glows - 06 (c1,c4) right glow.
Grids/01 (c5) perspective wireframe floor (tech/data). Blobs/13 (c1,c5) two-tone
S-flow statement. Angular ridges (bold, TALL bottom dividers): 05 (c5) jagged
ridge - 06 (c1,c3,c5) layered ridge. Blobs edge dividers: 05_001 (c1, bottom)
organic mound - 03 (c2, top) quarter blob - 06_001 (c1, TALL, top) hanging blob.
"""
_SHAPES_PASS_INSTRUCTIONS = f"""
You are the decorative-shapes refinement pass of the Odoo website builder. You
receive the page's `# Mood`, the resolved palette, a `# Page map` digesting each
top-level section (its background hex with the matching `o-color-N` slot,
density, padding, photo backgrounds) and the page's HTML structure. The layout,
content, colors and animations are FINAL — your job is to make the page feel
like ONE smooth, flowing design by connecting its sections with background
shapes. A page with no shapes feels abrupt and unfinished. Base every
colour/sizing decision on the page map.
Lean toward placing shapes: aim for a divider at the MAJORITY of flat-colour
section transitions, plus an atmospheric accent on each big / sparse section.
YOUR FIRST DECISION, per section, is its SIZE (see "How to choose"): a BIG /
sparse section earns an ANIMATED shape; a SMALL / tight transition gets a thin
static Connections divider. Mood only tints which family you reach for.
# Principles
- Be generous but purposeful: most section transitions deserve a divider and
most sparse hero/CTA sections deserve an accent. Skip a shape only when it
would genuinely hurt (the guards below) — never as a default.
- Decide placements as ONE coherent set: one animated family for the big
sections + Connections for the small transitions. Don't mix animated families.
- One shape per boundary: each gap hosts ONE divider (upper section's bottom OR
lower section's top, never both).
- NEVER place a shape on a section with a photographic background — the photo is
the interest; the shape becomes noise. Shapes belong on FLAT colour sections.
- Colors: a slot you don't specify defaults to the palette color of the same
number. Specify a slot only for a divider painted in the neighbour's bg.
- Divider colour is a LOOKUP, not a choice: a bottom-edge divider reads as the
NEXT section rising in — its main slot MUST be that section's background slot;
a top-edge divider uses the PREVIOUS section's. If the facing background
matches no slot, pick a different boundary.
- Use `edge` to anchor (top/bottom); the system flips/repositions. Don't use
`flip` for anchoring.
- TALL shapes paint a deep band and the system raises the section's padding to
clear them, so reserve TALL for sections with room (heroes, CTAs); on tight
transitions use the thin Connections band.
- Backdrops (Blurry, Grids, Blobs/13) go ONLY on SPARSE sections and must stay
low-contrast against that section's background.
- Animation belongs on BIG sections ONLY; on a small/dense section or a tight
transition it buries the text — use a thin Connections divider there instead.
# Output
JSON placements. Each: `section_index` (1-based), `shape` (catalog key),
`colors` (only slots that shape uses, values o-color-1..o-color-5), optional
`flip`, one-line `reason`. At most ONE placement per section.
# Shape catalog (the ONLY valid keys; color slots in parentheses)
{_SHAPES_CATALOG}
"""
_CSS_PASS_SCHEMA = {
"type": "object",
"properties": {
"scss": {"type": "string",
"description": "The COMPLETE new content of user_custom_rules.scss (existing rules preserved + additions)"},
},
"required": ["scss"],
}
_CSS_PASS_INSTRUCTIONS = """
You are the CSS-polish refinement pass of the Odoo website builder. You receive
the structure of a freshly generated page plus the current content of the
website-wide `user_custom_rules.scss` file. The page's layout, type, spacing and
palette are already set — your job is the finishing layer that utility classes
can't express: the tasteful touches that make it feel hand-crafted and alive.
Long text and image URLs are abridged in the HTML you receive; scope your rules
on the classes and structure, which are complete.
# Be creative — native CSS only
You are NOT working from a checklist. Polish THIS page like a front-end designer
on a final hand-off: reach for whatever genuinely elevates its character and
palette — hover / focus feedback, smooth transitions, pseudo-element accents and
dividers, gradient / overlay / blend-mode flourishes, soft tinted shadows, image
treatments (duotone, masks, `clip-path`), subtle decorative motion. Vary your
choices from page to page; surprise me with details that suit the design.
Reliable starting points (inspiration, not a mandate):
- Hover lift on cards / clickable blocks: a small `translateY` + a deeper,
palette-tinted shadow on hover.
- Hover zoom on an image inside a clipped container (`scale(~1.04)`).
- An underline or marker that grows under inline links or a key phrase.
- One restrained signature moment mid-page — a colour-block highlight, a tinted
image overlay, an accent behind a stat. (Gradient-clipped text is over-used and
often looks off — use it only if it truly fits, never as a default.)
- A slow ambient background drift on a mid-page CTA (never the hero — see guardrails).
A few well-placed touches beat a page stuffed with effects.
# Guardrails (don't cross these — they keep the page from breaking)
- NATIVE CSS ONLY: no JavaScript, no external `@import` or web fonts.
- Leave the FIRST section (the hero) free of added motion: NO zoom/`scale`,
ambient drift, parallax or any keyframe/looping animation on it or its
background. It already carries the page's strongest imagery and Odoo's own
entrance animations, and extra motion there fights them and looks broken.
Static polish (shadows, overlays, gradients, accents) and hover feedback on its
buttons are fine — continuous motion is not.
- Don't restyle what's already designed. Leave the existing layout, spacing,
fonts and the core colours / legibility of the text and sections as they are —
you ADD decoration (hover states, accents, overlays, shadows, flourishes); you
don't move, resize or recolour the content the user already approved.
- Animate only cheap, non-reflowing properties (`transform`, `opacity`,
`box-shadow`, `filter`, `background-position`, `color`). Never animate
`width`, `height`, `margin`, `padding` or `top`/`left` — they cause layout jank.
- Scope EVERY rule under a class that exists in the provided HTML (the page's
`ai_*` section classes, or snippet classes nested under them). This file is
global to the whole site — no bare top-level element selectors.
- Use `var(--o-color-1)`..`var(--o-color-5)` for palette colours so it re-themes.
- Keep this token block at the top of the file (add it if missing):
`:root { --ai-ease: cubic-bezier(0.22, 1, 0.36, 1); --ai-dur-fast: 0.25s; --ai-dur: 0.6s; }`
- Group this page's rules under a `/* === page: <page path> === */` marker,
replacing any previous block with the same marker, and PRESERVE every other
page's rules — return the COMPLETE new file content. Valid SCSS only.
# Output
JSON: {"scss": "<complete new file content>"}
"""
def _parse_css_color(value):
"""'#RGB', '#RRGGBB' or 'rgb(a)(r, g, b)' -> (r, g, b), else None."""
value = (value or '').strip()
if m := re.fullmatch(r'#([0-9A-Fa-f]{6})', value):
return tuple(int(m.group(1)[i:i + 2], 16) for i in (0, 2, 4))
if m := re.fullmatch(r'#([0-9A-Fa-f]{3})', value):
return tuple(int(c * 2, 16) for c in m.group(1))
if m := re.fullmatch(r'rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)[^)]*\)', value):
return tuple(int(m.group(i)) for i in (1, 2, 3))
return None
def _bump_edge_padding(section, edge, min_px):
"""Raise the section's pt/pb utility class to at least min_px (never shrink)
so content clears the shape band on `edge`."""
prefix = 'pt' if edge == 'top' else 'pb'
classes = (section.get('class') or '').split()
current = next((c for c in classes if re.fullmatch(rf'{prefix}\d+', c)), None)
if current and int(current[2:]) >= min_px:
return
if current:
classes[classes.index(current)] = f'{prefix}{min_px}'
else:
classes.append(f'{prefix}{min_px}')
section.set('class', ' '.join(classes))
class AIWebsiteService(models.AbstractModel):
_inherit = 'ai.website.service'
@api.model
def _finalize_page(self, page_html, step='images'):
"""Generate the page's images and run the refinement passes; every step fails open.
Runs in separate requests (`/ai_website/finalize_page`), called by the
`finalize_website_page` client tool: the server kills a worker at
`--limit-time-real` (120s by default), and generation alone already costs
~45s, so the build is split across the tool-pause request, one request per
image batch, one for both refinement passes, and the resumed turn.
"""
# `env.website` comes from the request host, not the site being edited.
service = self.with_context(website_id=self._current_website().id)
page_html = service._unwrap_sections_container(page_html)
if step == 'images':
page_html = service._generate_placeholder_images(page_html, batch_size=4)
_fragment, remaining_placeholders = service._find_image_placeholders(page_html)
next_step = 'images' if remaining_placeholders else 'refinements'
return {'html': page_html, 'next_step': next_step}
has_failed_pass = False
try:
live_palette = service._live_palette_css_variables()
if live_palette:
view_info = dict(service.env.context.get('current_view_info') or {})
website_page = dict(view_info.get('website_page') or {})
# The bundle wins: it is the CSS the page and the shape controller both resolve against.
website_page['css_variables'] = {**(website_page.get('css_variables') or {}), **live_palette}
view_info['website_page'] = website_page
service = service.with_context(current_view_info=view_info)
shape_actions, _shape_count = service._refinement_shapes_pass(page_html)
if shape_actions:
page_html = service._apply_section_replacements(page_html, shape_actions)
except _UNRECOVERABLE:
raise
except Exception:
has_failed_pass = True
_logger.exception("shapes refinement failed; continuing with CSS")
try:
service._refinement_css_pass(page_html)
except _UNRECOVERABLE:
raise
except Exception:
has_failed_pass = True
_logger.exception("CSS refinement failed; returning the partially refined page")
return {'html': page_html, 'next_step': None, 'error': has_failed_pass}
@api.model
def _live_palette_css_variables(self):
"""Palette ({'o-color-N' | 'o-ccN-bg': '#hex'}) read from the compiled web.assets_frontend bundle, or {}."""
website_id = self._current_website().id
if not website_id:
return {}
try:
bundle = self.env['ir.qweb'].with_context(website_id=website_id)._get_asset_bundle('web.assets_frontend')
# NOT bundle.css(): recompiling races the browser doing the same and aborts the
# transaction. Reading is enough, the builder reloads the bundle before calling us.
attachment = (bundle.get_attachments('min.css') or bundle.get_attachments('css'))[:1]
css = attachment.index_content if attachment else ''
except _UNRECOVERABLE:
raise
except Exception:
_logger.exception("could not read live palette from the frontend bundle")
return {}
if not css:
return {}
color = r'#[0-9A-Fa-f]{6,8}|rgba?\([^)]*\)'
wanted = [f'o-color-{n}' for n in range(1, 6)] + [f'o-cc{n}-bg' for n in range(1, 6)]
palette = {}
for name in wanted:
if match := re.search(r'(?i)--%s:\s*(%s)' % (re.escape(name), color), css):
palette[name] = match.group(1).strip()
return palette
@api.model
def _unwrap_sections_container(self, page_html):
"""Return the inner HTML when the page's sections are wrapped in a single
container element, so section detection sees them at top level (mirrors
the JS apply pipeline's unwrap). Unchanged otherwise."""
try:
fragment = self._parse_html_fragment(page_html)
except (lxml_etree.ParserError, ValueError):
return page_html
children = [el for el in fragment if isinstance(el.tag, str)]
if len(children) == 1:
inner = children[0]
if sum(1 for c in inner if isinstance(c.tag, str) and c.tag == 'section') > 1:
return self._serialize_html_fragment(inner)
return page_html
@api.model
def _html_structure_skeleton(self, page_html):
"""The page HTML with long text nodes and asset URLs abridged. The passes
decide from structure and headings, so body copy and image URLs are most
of the tokens and none of the signal. Unchanged if it can't be parsed."""
def abridge(text):
if not text:
return text
collapsed = re.sub(r'\s+', ' ', text)
if len(collapsed.strip()) <= _SKELETON_MAX_TEXT:
return text
return collapsed[:_SKELETON_MAX_TEXT].rstrip() + '…'
try:
fragment = self._parse_html_fragment(page_html)
except (lxml_etree.ParserError, ValueError):
return page_html
for el in fragment.iter():
if not isinstance(el.tag, str):
continue
el.text = abridge(el.text)
el.tail = abridge(el.tail)
for attribute in ('src', 'href', 'data-original-src'):
value = el.get(attribute)
if value and len(value) > _SKELETON_MAX_URL:
el.set(attribute, value[:_SKELETON_MAX_URL] + '…')
return self._serialize_html_fragment(fragment)
@api.model
def _apply_section_replacements(self, page_html, actions):
"""Apply a pass's section:nth-child(N) replace actions onto page_html and
return the merged HTML, so a later pass building on it sees the earlier
edits. Falls back to the unchanged HTML on any parse error."""
replacements = {}
for action in actions:
match = re.fullmatch(r'section:nth-child\((\d+)\)', (action.get('selector') or '').strip())
if match and action.get('mode') == 'replace' and action.get('content'):
replacements[int(match.group(1))] = action['content']
if not replacements:
return page_html
try:
fragment = self._parse_html_fragment(page_html)
children = [el for el in fragment if isinstance(el.tag, str)]
for position, content in replacements.items():
if 1 <= position <= len(children):
old = children[position - 1]
old.getparent().replace(old, lxml_html.fragment_fromstring(content))
return self._serialize_html_fragment(fragment)
except (lxml_etree.ParserError, ValueError):
_logger.warning("could not merge section replacements; later pass runs on pre-merge HTML")
return page_html
@api.model
def _parse_refinement_response(self, response):
text = get_text_from_parts(response).strip()
text = re.sub(r'^```(?:json)?\s*|\s*```$', '', text) # some models fence structured output
return json.loads(text)
@api.model
def _refinement_one_shot(self, instructions, message, schema, usage):
"""One schema-constrained refinement call, parsed, retried once (a
transient parse/decoding failure usually clears on the second attempt).
Runs at the lowest reasoning level: these are mechanical transforms of an
already-designed page, and the turn's time budget is worth more."""
last_error = None
agent = self.env.ref('ai_website.ai_agent_website_builder', raise_if_not_found=False)
for attempt in (1, 2):
try:
response = self.env['ai.session']._get_direct_response(
instructions=instructions, message=message, schema=schema,
usage=usage, timeout=_REFINEMENT_PASS_TIMEOUT,
agent_id=agent.id,
)
return self._parse_refinement_response(response)
except (UserError, ValueError) as error: # json.JSONDecodeError is a ValueError
last_error = error
_logger.warning("%s: attempt %d/2 failed (%s)", usage, attempt, error)
raise last_error
@api.model
def _refinement_css_pass(self, page_html):
"""Write the page's CSS polish (hover states, colour accents) into
user_custom_rules.scss via a focused one-shot call."""
page_path = self.env.context.get('current_view_info', {}).get('website_page', {}).get('location') or '/'
message = [{'type': 'text', 'text': (
f"# Page path\n{page_path}\n\n"
f"# Current user_custom_rules.scss\n{self._read_custom_css()}\n\n"
f"# Page structure\n{self._html_structure_skeleton(page_html)}"
)}]
scss = (self._refinement_one_shot(
instructions=_CSS_PASS_INSTRUCTIONS, message=message,
schema=_CSS_PASS_SCHEMA, usage="website_builder_css_polish",
).get('scss') or '').strip()
if not scss:
return False
self._save_custom_css(scss)
return True
@staticmethod
def _strip_section_shape(section):
"""Remove any background shape (o_we_shape div + data-oe-shape-data) from
a section. Returns True if something was removed."""
removed = False
for existing in section.findall("./div[@class]"):
if 'o_we_shape' in (existing.get('class') or '').split():
section.remove(existing)
removed = True
if section.get('data-oe-shape-data') is not None:
del section.attrib['data-oe-shape-data']
removed = True
return removed
@api.model
def _refinement_shapes_pass(self, page_html):
"""Decide and inject decorative background shapes. The LLM returns
placements; the markup is built HERE deterministically and dispatched as
section-level replace actions. The pass OWNS section shapes: it strips
any pre-existing one and re-decides, so every touched section ships a
replace action."""
css_variables = self.env.context.get('current_view_info', {}).get('website_page', {}).get('css_variables') or {}
palette_lines = "\n".join(f"- {name}: {value}" for name, value in sorted(css_variables.items())) \
or "(palette values not available; infer from the o_ccN classes)"
fragment = self._parse_html_fragment(page_html)
children = [el for el in fragment if isinstance(el.tag, str)]
section_positions = [(pos, el) for pos, el in enumerate(children, start=1) if el.tag == 'section']
sections = [el for _, el in section_positions]
prestripped_positions = {pos for pos, section in section_positions if self._strip_section_shape(section)}
page_html = self._serialize_html_fragment(fragment)
def has_photo_background(section):
classes = (section.get('class') or '').split()
if 'parallax' in classes or 'oe_img_bg' in classes or 'background-image' in (section.get('style') or ''):
return True
return any('s_parallax_bg_wrap' in (child.get('class') or '') for child in section)
section_map_lines = []
section_bg_colors = []
section_is_sparse = []
for i, section in enumerate(sections, start=1):
classes = (section.get('class') or '').split()
name = next((c for c in classes if c.startswith('ai_')), classes[0] if classes else 'section')
paddings = '/'.join(c for c in classes if re.fullmatch(r'p[tb]\d+', c)) or 'none'
if has_photo_background(section):
section_bg_colors.append(None)
section_is_sparse.append(False)
section_map_lines.append(f"{i}. {name} — PHOTO background: no shape on it, no divider facing its edges")
continue
cc = next((c[4:] for c in classes if re.fullmatch(r'o_cc[1-5]', c)), None)
bg_value = css_variables.get(f'o-cc{cc}-bg') if cc else None
section_bg_colors.append(bg_value if _parse_css_color(bg_value) else None)
bg_desc = f"bg o_cc{cc} {bg_value or '?'}" if cc else "bg unset"
text_length = len(re.sub(r'\s+', ' ', section.text_content()).strip())
image_count = len(section.findall('.//img')) + len(
[el for el in section.iter() if 'background-image' in (el.get('style') or '')])
density = 'SPARSE' if text_length < 200 and not image_count else 'dense'
section_is_sparse.append(density == 'SPARSE')
section_map_lines.append(
f"{i}. {name} — {bg_desc} — {density} content ({text_length} text chars, {image_count} image(s)) — padding {paddings}")
section_map = "\n".join(section_map_lines)
message = [{'type': 'text', 'text': (
"# Mood\nInfer the page's mood from the palette and copy; pick the shape family that fits.\n\n"
f"# Active palette (resolved CSS variables)\n{palette_lines}\n\n"
f"# Page map (top-level sections, in order)\n{section_map}\n\n"
f"# Page structure\n{self._html_structure_skeleton(page_html)}"
)}]
placements = self._refinement_one_shot(
instructions=_SHAPES_PASS_INSTRUCTIONS, message=message,
schema=_SHAPES_PASS_SCHEMA, usage="website_builder_shapes",
).get('placements') or []
if not placements and not prestripped_positions:
return [], 0
placed_positions = set()
claimed_boundaries = set()
for placement in placements:
key = placement.get('shape') or ''
shape_info = _SHAPE_REGISTRY.get(key)
index = placement.get('section_index')
if shape_info is None or not isinstance(index, int) or not (1 <= index <= len(section_positions)):
continue
position, section = section_positions[index - 1]
if position in placed_positions or has_photo_background(section):
continue
# A centred shape is a backdrop: on a dense section it lands under the text.
if 'center' in shape_info['position'] and not section_is_sparse[index - 1]:
_logger.info("shapes pass: %s is a backdrop and section %d is dense, skipping it", key, index)
continue
slots = shape_info['slots']
colors = {
slot: value
for slot, value in (placement.get('colors') or {}).items()
if re.fullmatch(r'c[1-5]', slot or '') and int(slot[1]) in slots
and re.fullmatch(r'o-color-[1-5]', value or '')
}
for slot_number in slots:
colors.setdefault(f'c{slot_number}', f'o-color-{slot_number}')
flip = 'x' if placement.get('flip') in ('x', 'xy') else None
edge = placement.get('edge') if placement.get('edge') in ('top', 'bottom') else None
natural_position = shape_info['position']
background_position = None
if edge == 'top' and 'top' not in natural_position:
flip = 'xy' if flip == 'x' else 'y'
background_position = '50% 0%'
elif edge == 'bottom' and 'top' in natural_position:
flip = 'xy' if flip == 'x' else 'y'
background_position = '50% 100%'
anchored_edge = edge or ('top' if 'top' in natural_position else 'bottom')
if 'clearance' in shape_info:
neighbor_list_index = (index - 2) if anchored_edge == 'top' else index
neighbor = sections[neighbor_list_index] if 0 <= neighbor_list_index < len(sections) else None
if neighbor is not None and has_photo_background(neighbor):
continue
boundary = (index - 1) if anchored_edge == 'top' else index # gap below section N
if boundary in claimed_boundaries:
continue
facing_color = section_bg_colors[neighbor_list_index] if neighbor is not None else None
if not facing_color:
continue
current_rgb = _parse_css_color(section_bg_colors[index - 1])
facing_rgb = _parse_css_color(facing_color)
if current_rgb and facing_rgb:
contrast = sum((a - b) ** 2 for a, b in zip(current_rgb, facing_rgb)) ** 0.5
if contrast < _MIN_DIVIDER_BG_CONTRAST:
continue
claimed_boundaries.add(boundary)
# Paint EVERY slot the facing colour (else layered dividers leak
# their default accents).
for s in slots:
colors[f'c{s}'] = facing_color
# A slot left as `o-color-N` is fine: the shape controller resolves the token itself.
colors = {slot: (css_variables.get(value) or value if re.fullmatch(r'o-color-[1-5]', value) else value)
for slot, value in colors.items()}
if clearance := shape_info.get('clearance'):
_bump_edge_padding(section, anchored_edge, min(256, -(-clearance // 8) * 8))
placed_positions.add(position)
params = dict(sorted(colors.items()))
if flip:
params['flip'] = flip
query = '&'.join(f"{name}={quote(str(value), safe='')}" for name, value in params.items())
url = f"/html_editor/shape/html_builder/{key}.svg" + (f"?{query}" if query else "")
style = f"background-image: url('{url}');"
if background_position:
style += f" background-position: {background_position};"
shape_div = lxml_html.fragment_fromstring(
f'<div class="o_we_shape o_html_builder_{key.replace("/", "_")} o_shape_show_mobile" style="{style}"></div>')
section.insert(0, shape_div)
shape_data = {'shape': f'html_builder/{key}', 'showOnMobile': True}
if colors:
shape_data['colors'] = colors
if flip:
shape_data['flip'] = list(flip)
section.set('data-oe-shape-data', json.dumps(shape_data).replace('"', "'"))
position_to_section = dict(section_positions)
actions = []
for position in sorted(prestripped_positions | placed_positions):
section = position_to_section[position]
section.tail = None
actions.append({
'zone': 'main', 'mode': 'replace',
'selector': f'section:nth-child({position})',
'content': lxml_html.tostring(section, encoding='unicode'),
})
return actions, len(placed_positions)

View File

@@ -0,0 +1,141 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import random
from typing import NamedTuple
from lxml import html as lxml_html
from odoo import api, models
class SnippetHint(NamedTuple):
group: str
label: str
intent: str
_SNIPPET_GROUPS = {
'hero': "Hero / Opening",
'content': "Content layout",
'cta': "Call to action",
'social_proof': "Social proof",
'media': "Media / Imagery",
'data': "Data / Statistics",
'form': "Form / Contact",
'other': "Catalog / Pricing",
}
_SNIPPET_HINTS = {
# group, label, intent hint
's_banner': SnippetHint('hero', "Banner", "prominent hero with a large headline and a call-to-action button"),
's_cover': SnippetHint('hero', "Cover", "full-screen background image with centered text and a primary CTA"),
's_picture': SnippetHint('hero', "Title - Image", "centered title and subtitle above a large full-width image"),
's_motto': SnippetHint('hero', "Motto", "large prominent quote or motto"),
's_title': SnippetHint('hero', "Title", "centered prominent heading to separate parts of a page"),
's_text_block': SnippetHint('content', "Text", "single-column text area for paragraphs / long-form content"),
's_text_image': SnippetHint('content', "Text - Image", "side-by-side: text left, image right"),
's_image_text': SnippetHint('content', "Image - Text", "side-by-side: image left, text right"),
's_image_text_overlap': SnippetHint('content', "Image - Text Overlap", "overlapping grid of a large image and a text box"),
's_image_frame': SnippetHint('content', "Image Frame", "single large image in a styled frame"),
's_three_columns': SnippetHint('content', "Columns", "three-column grid of cards with top images and text"),
's_features': SnippetHint('content', "Features", "multi-column feature grid with icons and short text"),
's_key_images': SnippetHint('content', "Key Images", "numbered steps paired with images and short text"),
's_color_blocks_2': SnippetHint('content', "Color Blocks", "side-by-side colored boxes with text and CTA buttons"),
's_striped': SnippetHint('content', "Striped section", "alternating striped-background rows of text"),
's_card_offset': SnippetHint('content', "Card Offset", "overlapping large image with an offset text card"),
's_cards_grid': SnippetHint('content', "Cards Grid", "multi-column grid of horizontal cards with images and text"),
's_masonry_block': SnippetHint('content', "Masonry", "asymmetric masonry grid combining images and text"),
's_media_list': SnippetHint('content', "Media List", "vertical list of items with side-by-side image and text"),
's_tabs': SnippetHint('content', "Tabs", "horizontal tabbed navigation between content areas"),
's_faq_collapse': SnippetHint('content', "FAQ", "collapsible accordion of questions and answers"),
's_faq_horizontal': SnippetHint('content', "Topics List", "horizontal list of topics or steps with text"),
's_faq_list': SnippetHint('content', "FAQ List", "multi-column grid of questions and answers (no collapse)"),
's_call_to_action': SnippetHint('cta', "Call to Action", "horizontal banner with a strong headline and a CTA button"),
's_cta_card': SnippetHint('cta', "Card Call to Action", "prominent text paired with a card holding a CTA button"),
's_company_team': SnippetHint('social_proof', "Team", "team members with circular photos and names"),
's_quotes_carousel': SnippetHint('social_proof', "Quotes", "sliding carousel of testimonials or quotes"),
's_reviews_wall': SnippetHint('social_proof', "Reviews Wall", "multi-column grid of customer review cards"),
's_references': SnippetHint('social_proof', "References", "horizontal row of partner / client logos"),
's_carousel': SnippetHint('media', "Carousel", "sliding image carousel with text and CTA per slide"),
's_carousel_cards': SnippetHint('media', "Carousel Cards", "sliding carousel of multiple cards per slide"),
's_images_wall': SnippetHint('media', "Images Wall", "masonry grid of images of varying sizes"),
's_parallax': SnippetHint('media', "Parallax", "full-width parallax background image with overlay content"),
's_big_number': SnippetHint('data', "Big number", "single massive number / statistic centered on screen"),
's_numbers': SnippetHint('data', "Numbers", "row of large prominent numbers with short labels"),
's_process_steps': SnippetHint('data', "Process Steps", "horizontal sequence of steps connected by lines"),
's_timeline': SnippetHint('data', "Timeline", "vertical timeline of milestones or events with dates"),
's_timeline_images': SnippetHint('data', "Timeline Images", "vertical timeline pairing milestones with images"),
's_comparisons': SnippetHint('data', "Comparisons", "side-by-side pricing plan cards comparing features and cost"),
's_opening_hours': SnippetHint('data', "Opening Hours", "business opening hours over a parallax background"),
's_title_form': SnippetHint('form', "Title - Form", "centered title and text above a simple form"),
's_form_aside': SnippetHint('form', "Form Aside", "side-by-side contact info and an input form"),
's_website_form_cover': SnippetHint('form', "Form Cover", "split layout with a large background image and a form"),
's_contact_info': SnippetHint('form', "Contact Info", "grid of contact details (address, phone, etc.)"),
's_attributes_horizontal': SnippetHint('other', "Horizontal Attributes", "row of small icons/images with short labels"),
's_pricelist_boxed': SnippetHint('other', "Pricelist Boxed", "centered boxed pricing menu over a parallax background"),
's_pricelist_cafe': SnippetHint('other', "Pricelist Cafe", "multi-column cafe/restaurant menu with items and prices"),
's_product_catalog': SnippetHint('other', "Pricelist", "detailed product/menu list with a background image"),
's_product_list': SnippetHint('other', "Product List", "multi-column grid of product cards with images and links"),
's_ecomm_categories_showcase': SnippetHint('other', "Categories Grid", "grid of e-commerce categories with background images"),
}
class AIWebsiteService(models.AbstractModel):
_inherit = 'ai.website.service'
@api.ormcache()
def _render_snippets(self):
website_id = self.env.website.id or self.env.context.get('host_id') or self.env.ref('base.default_website').id
snippets_html = self.env["ir.ui.view"].with_context({
"website_id": website_id,
"inherit_branding": False,
}).render_public_asset("website.snippets", values={})
return lxml_html.fromstring(f'<div>{snippets_html}</div>')
@api.model
def _create_snippets_list(self):
"""The curated snippet menu (see _SNIPPET_HINTS), grouped by purpose.
Order within a group is randomised each run so picks rotate (a fixed
order made every hero an s_banner)."""
snippets_tree = self._render_snippets()
tags_by_key = {}
snippets = snippets_tree.xpath('.//snippets[@id="snippet_structure" or @id="snippet_content"]/*')
for snippet in snippets:
key = snippet.get('data-oe-snippet-key')
if key in _SNIPPET_HINTS:
tags_by_key[key] = snippet.get('data-oe-keywords') or ""
keys_by_group = {}
for key in tags_by_key:
keys_by_group.setdefault(_SNIPPET_HINTS[key].group, []).append(key)
out = (
"# Available snippets\n"
"The building blocks you can use, grouped by purpose. Each has a unique "
"key (use it to reference the snippet), a label and an intent hint.\n\n"
)
for group, group_label in _SNIPPET_GROUPS.items():
keys = keys_by_group.get(group)
if not keys:
continue
random.shuffle(keys)
out += f'## {group_label}\n| Key | Label | Hint | Tags |\n| --- | --- | --- | --- |\n'
for key in keys:
hint = _SNIPPET_HINTS[key]
out += f'| {key} | {hint.label} | {hint.intent} | {tags_by_key[key]} |\n'
out += "\n"
return out
@api.model
def _get_snippet_html(self, snippet_key):
"""Return `(hint, html)` for one catalog snippet: `hint` is the
`SnippetHint` from `_SNIPPET_HINTS`, or `None` if the key isn't curated;
`html` is the snippet's structure, or `None` if no snippet matches the
key at all."""
snippets_tree = self._render_snippets()
section = snippets_tree.xpath(
'.//snippets[@id="snippet_structure" or @id="snippet_content"]'
'//div[@data-oe-snippet-key=$key]/*[1]',
key=snippet_key,
)
html = lxml_html.tostring(section[0], encoding='unicode') if section else None
return _SNIPPET_HINTS.get(snippet_key), html

View File

@@ -0,0 +1,25 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from markupsafe import Markup
from odoo import models
from .mail_message import ELEMENT_LABEL_CLASS
class DiscussChannel(models.Model):
_inherit = 'discuss.channel'
def message_post(self, **kwargs):
labels = self.env.context.get('ai_website_element_labels')
session = self.sudo().ai_session_ids[:1]
if labels and session._is_website_builder_session():
labels_markup = Markup('').join(
Markup('<span class="%s d-none">%s</span>') % (ELEMENT_LABEL_CLASS, label)
for label in labels
)
kwargs['body'] = Markup('%s%s') % (
kwargs.get('body', ''),
labels_markup,
)
return super().message_post(**kwargs)

View File

@@ -0,0 +1,224 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import ipaddress
import logging
import re
from time import monotonic
from urllib.parse import unquote, urlsplit
import requests
from urllib3.connectionpool import HTTPConnectionPool, HTTPSConnectionPool
from odoo import api, models
from odoo.exceptions import UserError
from odoo.tools.image import image_process
from odoo.tools.mimetypes import guess_mimetype
from odoo.addons.html_editor.controllers.main import attachment_create
from odoo.addons.html_editor.models.ir_attachment import SUPPORTED_IMAGE_MIMETYPES
_logger = logging.getLogger(__name__)
ALLOWED_IMAGE_SCHEMES = ('http', 'https')
_IMAGE_DOWNLOAD_TIMEOUT = 8
_IMAGE_DOWNLOAD_BATCH_DEADLINE = 25
_MAX_IMAGE_BYTES = 20 * 1024 * 1024
_MAX_IMAGE_REDIRECTS = 3
_MAX_IMAGES_PER_BATCH = 30
class _PublicConnectionPoolMixin:
def _validate_conn(self, conn):
"""Check the connected peer before sending any HTTP request, including on reuse.
Checking a separate DNS lookup would both repeat resolution and leave a gap
where the address could change before urllib3 establishes its connection.
"""
super()._validate_conn(conn)
# HTTPS validation already connects; HTTP normally connects when sending.
if conn.sock is None:
conn.connect()
# urllib3's PyOpenSSL wrapper exposes the underlying socket as `socket`.
try:
sock = conn.sock.socket
except AttributeError:
sock = conn.sock
ip = ipaddress.ip_address(sock.getpeername()[0])
if isinstance(ip, ipaddress.IPv6Address):
ip = ip.ipv4_mapped or ip
if not ip.is_global or ip.is_multicast or ip.is_reserved:
raise ValueError("only publicly reachable hosts are allowed.")
class _PublicHTTPConnectionPool(_PublicConnectionPoolMixin, HTTPConnectionPool):
pass
class _PublicHTTPSConnectionPool(_PublicConnectionPoolMixin, HTTPSConnectionPool):
pass
def _read_image_response(response):
content_length = response.headers.get('content-length')
if content_length and content_length.isdigit() and int(content_length) > _MAX_IMAGE_BYTES:
raise ValueError(f"image is larger than {_MAX_IMAGE_BYTES // (1024 * 1024)}MB.")
content = bytearray()
for chunk in response.iter_content(chunk_size=64 * 1024):
content += chunk
if len(content) > _MAX_IMAGE_BYTES:
raise ValueError(f"image is larger than {_MAX_IMAGE_BYTES // (1024 * 1024)}MB.")
return bytes(content)
class _ImageHTTPAdapter(requests.adapters.HTTPAdapter):
def init_poolmanager(self, *args, **kwargs):
super().init_poolmanager(*args, **kwargs)
self.poolmanager.pool_classes_by_scheme = {
'http': _PublicHTTPConnectionPool,
'https': _PublicHTTPSConnectionPool,
}
def build_response(self, req, resp):
response = super().build_response(req, resp)
if response.is_redirect:
# Requests consumes the body to prepare Response.next, even with
# stream=True. Bound that read and release the connection for reuse.
with response:
response._content = _read_image_response(response)
return response
class IrAttachment(models.Model):
_inherit = 'ir.attachment'
@api.model
def _download_external_image(self, url, session):
"""Download an external image and return its validated ``(bytes, mimetype)``.
The batch's session uses a public-address-only adapter for every redirect.
The body is read in chunks and capped so a URL cannot stream an unbounded
response into memory.
:raises ValueError: with a message meant for the caller, if the image can't be used.
"""
parsed_url = urlsplit(url)
if parsed_url.scheme not in ALLOWED_IMAGE_SCHEMES or not parsed_url.hostname:
raise ValueError("only HTTP(S) image URLs are supported.")
try:
request = session.prepare_request(requests.Request('GET', url))
except requests.RequestException as err:
raise ValueError("image could not be reached.") from err
for _redirect in range(_MAX_IMAGE_REDIRECTS + 1):
try:
response = session.send(
request,
timeout=_IMAGE_DOWNLOAD_TIMEOUT,
stream=True,
allow_redirects=False,
)
with response:
if response.next is not None:
request = response.next
continue
if response.status_code != 200:
raise ValueError(f"the server answered with HTTP {response.status_code}.")
content = _read_image_response(response)
except requests.RequestException as err:
raise ValueError("image could not be reached.") from err
if not content:
raise ValueError("the URL returned an empty response.")
try:
image_data = image_process(content, verify_resolution=True)
except (UserError, OSError, ValueError) as err:
raise ValueError("URL does not point to a supported image.") from err
mimetype = guess_mimetype(image_data)
if mimetype not in SUPPORTED_IMAGE_MIMETYPES:
raise ValueError("URL does not point to a supported image.")
return image_data, mimetype
raise ValueError("too many redirects.")
@api.model
def _get_image_name_from_url(self, url, mimetype):
"""Build an attachment name from the URL's last path segment.
The extension is forced to match ``mimetype``: `_compute_mimetype` trusts the name
over the content, so a wrong extension would leave the attachment with a mimetype
that does not describe its bytes (and no usable ``image_src``).
"""
extension = SUPPORTED_IMAGE_MIMETYPES[mimetype]
basename = unquote(urlsplit(url).path).rpartition('/')[2].strip()
# Keep it a plain file name: no separators, no leading dots, bounded length.
basename = re.sub(r'[^\w.\- ]', '', basename).lstrip('.').strip()
basename = basename.rpartition('.')[0][:100].strip() or basename[:100].strip()
return f"{basename or 'External image'}{extension}"
@api.model
def _create_attachment_from_external_image_url(self, url, session):
"""Download one external image URL and return the local attachment holding it.
:raises ValueError: with a message meant for the caller, if the image can't be used.
"""
image_data, mimetype = self._download_external_image(url, session)
# No `url=` here on purpose: passing one makes `image_src` point back at the
# external URL, which would defeat the download.
try:
attachment = attachment_create(
self.env['ir.attachment'],
name=self._get_image_name_from_url(url, mimetype),
data=image_data,
)
except UserError as err:
# Size limit, access rights, ... AccessError is a UserError.
raise ValueError(str(err)) from err
if not attachment.image_src:
_logger.warning(
"Attachment %s created from %s has no image_src (mimetype %s)",
attachment.id, url, attachment.mimetype,
)
raise ValueError("the image could not be stored.")
return attachment
@api.model
def _localize_external_image_urls(self, urls):
"""Copy external images into Odoo and map each source URL to a local one.
A URL that cannot be localized is reported rather than raised: the caller keeps a
working - if hotlinked - page instead of a failed save.
:param urls: external image URLs to download.
:return: ``{'sources': {url: local_url}, 'errors': {url: message}}``
"""
sources = {}
errors = {}
deduplicated_urls = list(dict.fromkeys(
url.strip()
for url in (urls or [])
if isinstance(url, str) and url.strip()
))[:_MAX_IMAGES_PER_BATCH]
# Downloads run one after the other, so they share a deadline. Past it the
# remaining URLs are reported as failures without being attempted: a save that
# keeps a few hotlinks beats a save that hangs on a slow host.
deadline = monotonic() + _IMAGE_DOWNLOAD_BATCH_DEADLINE
with requests.Session() as session:
# A proxy would hide the target peer's address. Also avoid sending netrc
# credentials when fetching URLs supplied by third-party pages.
session.trust_env = False
for scheme in ALLOWED_IMAGE_SCHEMES:
session.mount(f'{scheme}://', _ImageHTTPAdapter())
for url in deduplicated_urls:
if monotonic() > deadline:
errors[url] = "the images took too long to download."
continue
try:
sources[url] = self._create_attachment_from_external_image_url(url, session).image_src
except ValueError as err:
# Everything that makes a URL unusable is rejected before any attachment
# is created, so a rejected URL leaves nothing behind to clean up.
errors[url] = str(err)
if errors:
_logger.info("Could not localize %s external image(s): %s", len(errors), errors)
return {'sources': sources, 'errors': errors}

View File

@@ -0,0 +1,10 @@
from odoo import models
from typing import override
class IrUiView(models.Model):
_inherit = 'ir.ui.view'
@override
def _get_allowed_root_attrs(self):
return super()._get_allowed_root_attrs() + ['data-contains-ai-content']

View File

@@ -0,0 +1,36 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from lxml import html
from odoo import models
from odoo.addons.mail.tools.discuss import Store
from odoo.tools.mail import html_remove_xpath
ELEMENT_LABEL_CLASS = 'o-ai-website-element-label'
class MailMessage(models.Model):
_inherit = 'mail.message'
def _store_extra_fields(self, res: Store.FieldList, *, format_reply):
super()._store_extra_fields(res, format_reply=format_reply)
res.attr(
'ai_website_element_labels',
lambda message: message._ai_website_get_element_labels(),
predicate=lambda message: ELEMENT_LABEL_CLASS in (message.body or ''),
)
def _ai_website_get_element_labels(self):
self.ensure_one()
tree = html.fragment_fromstring(self.body or '', create_parent='div')
return [element.text_content() for element in tree.find_class(ELEMENT_LABEL_CLASS)]
def _convert_to_parts(self):
parts = super()._convert_to_parts()
if ELEMENT_LABEL_CLASS in (self.body or ''):
parts[0]['text'] = html_remove_xpath(
parts[0]['text'],
f"//*[hasclass('{ELEMENT_LABEL_CLASS}')]",
)
return parts

View File

@@ -0,0 +1,12 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
ai_allow_scripts = fields.Boolean(
related='website_id.ai_allow_scripts',
readonly=False,
)

View File

@@ -0,0 +1,96 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from lxml import etree
from odoo import api, fields, models
class Website(models.CachedModel):
_inherit = 'website'
ai_allow_scripts = fields.Boolean(
string="AI JavaScript",
help="Always let the AI website builder add JavaScript to the pages of this website.\n"
"When off, it asks before adding any scripts.",
default=False)
@api.model
def get_site_profile(self):
website = self.env.website or self.env.website.browse(self.env.context.get('host_id')) or self.env.ref('base.default_website')
company = website.company_id
def _menu_to_dict(menu):
return {
'name': menu.name,
'url': menu.url,
'children': [_menu_to_dict(child) for child in menu.child_id.sorted('sequence')],
}
pages = self.env['website.page'].search_fetch([
('website_id', 'in', [website.id, False]),
], ['name', 'url', 'is_published'])
return {
'website_name': website.name,
'domain': website.domain,
'homepage_url': website.homepage_url,
'default_language': {
'code': website.default_lang_id.code,
'name': website.default_lang_id.name,
},
'languages': [
{'code': lang.code, 'name': lang.name}
for lang in website.language_ids
],
'company': {
'name': company.name,
'tagline': company.report_header,
'street': company.street,
'city': company.city,
'zip': company.zip,
'state': company.state_id.name,
'country': company.country_id.name,
'email': company.email,
'phone': company.phone,
'website': company.website,
},
'menu_tree': [
_menu_to_dict(m)
for m in website.menu_id.child_id.sorted('sequence')
],
'pages': [
{'name': page.name, 'url': page.url, 'is_published': page.is_published}
for page in pages
],
}
@api.model
def get_page_html(self, url, website_id):
"""Return the innerHTML of div#wrap for a website page.
:param url: page URL.
:param website_id: the website id.
:return: HTML string of the div#wrap content, or None if not found.
"""
page = self.env['website.page'].search_fetch([
('url', '=', url),
('website_id', '=', website_id),
], ['view_id'], limit=1)
if not page:
# Website pages may be shared by all websites (website_id=False).
page = self.env['website.page'].search_fetch([
('url', '=', url),
('website_id', '=', False),
], ['view_id'], limit=1)
if not page:
return None
website = self.env['website'].browse(website_id)
arch_tree = page.view_id.sudo().with_context(
inherit_branding=False, website_id=website_id, lang=website.default_lang_id.code,
)._get_combined_arch()
wrap_els = arch_tree.xpath('.//div[@id="wrap"]')
if not wrap_els:
return None
return etree.tostring(wrap_els[0], encoding='unicode', method='html')

View File

@@ -0,0 +1,158 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
import logging
import re
from lxml import html
from odoo import api, models
from odoo.exceptions import UserError
from requests.exceptions import RequestException
from odoo.addons.ai.utils.ai_utils import get_text_from_parts
logger = logging.getLogger(__name__)
class WebsitePage(models.Model):
_name = 'website.page'
_inherit = ['website.page']
@api.model
def _extract_snippets_from_template(self, sectionsArch, template_id):
"""
Get the snippets for a given template.
:param sectionsArch: The HTML string of the template
:type sectionsArch: str
:param template_id: The ID of the template to use to get the English version
:type template_id: str
:return: Dictionary mapping snippet IDs to their sections and translated sections
:rtype: dict
"""
View = self.env['ir.ui.view']
snippets_dict = {}
doc = html.fromstring('<div id="wrap">' + sectionsArch + '</div>')
# the template_html_en is already wrapped in a div with id="wrap"
sectionsArch_en = View.with_context(inherit_branding=False, lang='en_US')._render_template(template_id)
doc_en = html.fromstring(sectionsArch_en)
# Get the main sections of the template (each is a snippet)
snippet_sections = doc.xpath('//div[@id="wrap"]/section')
snippet_sections_en = doc_en.xpath('//div[@id="wrap"]/section')
# Create a mapping of snippet IDs to English elements for lookup
en_snippets_map = {}
for idx, el_en in enumerate(snippet_sections_en):
snippet_key = el_en.attrib['data-snippet']
# Because the templates are generated from specific
# t-snippet-calls such as:
# "website.new_page_template_about_us_0_s_text_block",
# the generated data-snippet looks like:
# "new_page_template_about_us_0_s_text_block"
# while it should be "s_text_block" only.
if '_s_' in snippet_key:
el_en.attrib['data-snippet'] = f's_{snippet_key.split("_s_")[-1]}'
snippet_key = el_en.attrib['data-snippet']
if snippet_key:
en_snippets_map[f'{snippet_key}_{idx}'] = html.tostring(el_en, encoding='unicode', method='html')
# Process each snippet element
for idx, el in enumerate(snippet_sections):
snippet_id = el.get('data-snippet')
if snippet_id:
# Get the section content (current language)
section_content = html.tostring(el, encoding='unicode', method='html')
# Get the translated section content (English)
translated_section_content = en_snippets_map.get(f'{snippet_id}_{idx}', section_content)
snippets_dict[f'{snippet_id}_{idx}'] = {
'section': section_content,
'translated_section': translated_section_content
}
return snippets_dict
@api.model
def _get_default_cta_configuration(self):
return {
'cta_btn_text': 'Contact Us',
'cta_btn_href': '/contactus'
}
def _generate_response(self, content_context, placeholders):
"""
Generate a response from the AI agent
:param content_context: The context information for the agent
:type content_context: str
:param placeholders: List of placeholder texts to be replaced by AI
:type placeholders: list
:return: Response from the AI agent containing generated content
:rtype: dict
"""
agent = self.env.ref('ai_website.website_page_generator_agent')
batch = {str(i + 1): placeholder for i, placeholder in enumerate(placeholders)}
prompt = json.dumps(batch, ensure_ascii=False)
message_parts = [{'type': 'text', 'text': prompt}]
try:
response = agent._generate_single_response(message_parts, extra_instructions=content_context)
response_text = response and get_text_from_parts(response)
if response_text:
response_dict = json.loads(response_text)
result = {}
for i, placeholder in enumerate(placeholders):
key = str(i + 1)
result[placeholder] = response_dict.get(key, "").strip() or placeholder
return result
else:
return {}
except (UserError, RequestException) as e:
return {"error": str(e)}
@api.model
def _generate_ai_website_page_html(self, template_id, sectionsArch, content_context):
"""
Generate the AI-generated HTML content string of the page's template
:param template_id: The ID of the template to use
:type template_id: str
:param content_context: The context information for the agent
:type content_context: str
:return: The HTML string of the generated page
:rtype: str
"""
website = self.env.website or self.env.website.browse(self.env.context.get('host_id')) or self.env.ref('base.default_website')
text_generation_target_lang = website.default_lang_id.code
text_must_be_translated_for_openai = not text_generation_target_lang.startswith('en_')
IrQweb = self.env['ir.qweb'].with_context(
website_id=website.id,
lang=website.default_lang_id.code
)
html_text_processor = self.env['website.html.text.processor']._with_processing_context(
IrQweb=IrQweb,
text_generation_target_lang=text_generation_target_lang,
text_must_be_translated_for_openai=text_must_be_translated_for_openai,
cta_data=self._get_default_cta_configuration(),
)
snippets = self._extract_snippets_from_template(sectionsArch, template_id)
html_text_processor, generated_content, _dummy = html_text_processor._get_rendered_snippets_content(snippets)
placeholders = list(generated_content.keys())
content_context += f" Lang: {text_generation_target_lang}"
response = self._generate_response(content_context, placeholders)
if response.get("error"):
raise UserError(response.get("error"))
name_replace_parser = re.compile(r"XXXX", re.MULTILINE)
for key in generated_content:
if response.get(key):
generated_content[key] = (name_replace_parser.sub(website.name, response[key], 0))
result = []
for key, snippet in snippets.items():
# The key is like: "s_text_block_0" where the last part _0 is the
# section index. We want to get the snippet key without the index
snippet_key = key.rsplit('_', 1)[0]
el = html_text_processor._update_snippet_content(generated_content, snippet_key, snippet_html=snippet['section'])
if el is not None:
el.attrib['data-snippet'] = snippet_key
result.append(html.tostring(el, encoding='unicode', method='html'))
ai_html_string = '\n'.join(result)
return ai_html_string