初始提交

This commit is contained in:
2026-11-04 19:58:07 +08:00
commit 53b7d22429
829 changed files with 469986 additions and 0 deletions

28
ai/tests/__init__.py Normal file
View File

@@ -0,0 +1,28 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import common
from . import test_ai_access
from . import test_ai_agent
from . import test_ai_agent_compute_date
from . import test_ai_agent_source
from . import test_ai_embedding
from . import test_ai_message_parts
from . import test_ai_methods
from . import test_ai_open_menu_graph_tour
from . import test_ai_session
from . import test_ai_url_scraper_controller
from . import test_ai_web_page
from . import test_ai_web_scraper_batch
from . import test_mail_call_artifact_ai
from . import test_data
from . import test_discuss_channel
from . import test_instance_validation
from . import test_ir_actions_server
from . import test_ir_attachment
from . import test_llm_tool_calling
from . import test_schema_validation
from . import test_tool_update_records
from . import test_ai_prompt_button
from . import test_ai_image_tools
from . import test_ai_composer
from . import test_tool_create_records
from . import test_markdown_formatting

290
ai/tests/common.py Normal file
View File

@@ -0,0 +1,290 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import copy
from collections import deque
from contextlib import contextmanager
from unittest.mock import Mock, patch
from odoo.fields import Command
from odoo.tests import HttpCase, TransactionCase, tagged
from odoo.tools import hmac
from odoo.addons.ai.models.ai_agent import AIAgent
from odoo.addons.ai.models.ai_embedding import AIEmbedding
from odoo.addons.ai.models.ai_session import AiSession
from odoo.addons.ai.models.ir_actions_server import IrActionsServer
from odoo.addons.ai.utils.ai_utils import UserInputResponse
class TestAICommon(TransactionCase):
"""Common helpers for testing Enterprise against normalized IAP responses."""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.user_internal = cls.env['res.users'].create({
'name': 'User internal',
'login': 'user_internal',
'email': 'user_internal@user.com',
'group_ids': [Command.set(cls.env.ref('base.group_user').ids)],
})
cls.call_id = 0
cls.agent = cls.env['ai.agent'].create({
'name': 'Test Agent',
'system_prompt': "Do this",
})
cls.agent_with_sources = cls.env['ai.agent'].create({
'name': 'Test Agent with sources',
'system_prompt': "Do this",
})
test_attachment = cls.env['ir.attachment'].create({
'name': 'test_doc.txt',
'raw': b'Odoo is an open-source ERP system with many modules.',
'res_model': 'ai.agent',
'res_id': cls.agent_with_sources.id,
})
cls.test_source = cls.env['ai.agent.source'].create({
'name': 'Test Source',
'type': 'binary',
'agent_id': cls.agent_with_sources.id,
'attachment_id': test_attachment.id,
'status': 'indexed',
'is_active': True,
})
cls.test_embedding = cls.env['ai.embedding'].create(
{
'res_model': 'ir.attachment',
'res_id': test_attachment.id,
'content': test_attachment.index_content,
'embedding_model': 'embedding_model',
'embedding_vector': [0.1] * 1536,
'sequence': 1,
})
cls.tools = cls.env['ir.actions.server'].create([{
'model_id': cls.env["ir.model"]._get_id('ai.agent'),
'state': 'code',
'name': f'tool_{i + 1}_',
'ai_tool_name': f'tool_{i + 1}_',
'use_in_ai': True,
'code': f"ai['result'] = 'tc_{i + 1}'"
} for i in range(3)])
cls.skill_loading_tool = cls.env.ref("ai.ir_actions_server_load_skills")
cls.skill = cls.env['ai.skill'].create({
'name': 'Test Skill',
'instructions': 'Use this when needed',
'tool_ids': cls.tools.ids,
})
cls.agent_with_tools = cls.env['ai.agent'].create({
'name': 'Test Agent with tools',
'skill_ids': cls.skill,
})
def mock_completion_request(self, responses):
return patch.object(AiSession, '_get_completions', side_effect=({
'status': 'success',
'result': {
'role': 'assistant',
'content': parts,
'provider_metadata': {},
},
} for parts in responses))
def mock_embedding_request(self):
return patch.object(AIEmbedding, '_get_embeddings', side_effect=lambda self, input, *args, **kwargs: {
'status': 'success',
'embeddings': [[0.1] * 1536 for _ in range(len(input))],
}, autospec=True)
def mock_default_tools(self, tools: IrActionsServer):
return patch.object(
AIAgent, "_get_default_tools", autospec=True,
side_effect=lambda agent: agent.env["ir.actions.server"].browse(tools.ids),
)
def mock_tool_response(self, tool, args=None):
tool.ensure_one()
self.call_id += 1
return [{
'type': 'tool_call',
'name': tool.sudo().ai_tool_name,
'args': args or {},
'call_id': self.call_id,
}]
def mock_text_response(self, text):
return [{'type': 'text', 'text': text}]
def _create_ai_session(self, agent: AIAgent):
return self.env['ai.session'].sudo().create({
'agent_id': agent.id,
'channel_id': agent._create_ai_chat_channel().id,
})
def _get_ai_session_default_controls(self):
return {
"enable_web_search": True,
"enable_resources_only": False,
"enable_think_longer": False,
"auto_confirm": False,
"show_agent_steps": False,
}
def _get_tool_result(self, session, call_id):
return next(
part
for event in session.event_ids
for part in event.metadata.get('content', [])
if part.get('type') == 'tool_result'
and part['tool_call_id'] == call_id
)
def _assert_tool_result_texts(self, event, expected):
self.assertEqual(
[
(
part['tool_call_id'],
part['result'][0].get('text'),
part['success'],
)
for part in event.metadata.get('content', [])
if part.get('type') == 'tool_result'
],
expected,
)
def _prepare_default_tools(self, agent: AIAgent, session: AiSession = None):
tools = session._get_session_default_tools() if session else agent._get_default_tools()
tools_by_name = {tool.sudo().ai_tool_name: tool for tool in tools}
return self.env["ai.session"]._prepare_tools(tools_by_name)
@tagged("post_install", "-at_install")
class TestAICallbackCommon(HttpCase, TestAICommon):
"""Exercise session endpoints with a fake IAP transport."""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(user=cls.env.ref("base.user_admin"))
def _create_ai_session(self, agent: AIAgent):
agent = agent.with_env(self.env)
return self.env["ai.session"].sudo().create({
"agent_id": agent.id,
# These tests supply conversation replies, not channel-title replies.
"channel_id": agent._create_ai_chat_channel("Test conversation").id,
})
@contextmanager
def mock_callback_completions(self, responses, *, channel_name="Test conversation"):
self._iap_requests = deque()
self._iap_replies = iter(responses)
self._iap_channel_name = channel_name
conversation_transport = Mock()
def accept_request(connection, route, params, **kwargs):
self.assertEqual(route, "1/get_completions")
self._iap_requests.append(copy.deepcopy(params))
if params["usage"] != "channel_name":
conversation_transport(connection, route, params, **kwargs)
return {}
with patch(
"odoo.addons.ai.models.ai_session.call_odoo_ai_transport",
side_effect=accept_request,
):
yield conversation_transport
self.assertFalse(self._iap_requests)
def _deliver_iap_callbacks(self):
while self._iap_requests:
submitted = self._iap_requests.popleft()
if submitted["usage"] == "channel_name":
content = self.mock_text_response(self._iap_channel_name)
else:
content = next(self._iap_replies)
llm_result = {"result": {
"role": "assistant",
"content": content,
"provider_metadata": {},
}}
response = self.url_open(
"/ai/completion_result_ready",
json={
"request_uuid": submitted["request_uuid"],
"llm_result": llm_result,
"llm_error": False,
"signature": hmac(None, "odoo_ai-webhook", (
submitted["request_uuid"], llm_result, False,
), secret=submitted["webhook_secret"]),
},
)
self.assertEqual(response.status_code, 200, response.text)
self.assertIsNone(response.json())
self.env.invalidate_all()
def _call_ai_endpoint(self, route, params):
user = self.env.user
self.authenticate(user.login, user.login, session_extra={
"context": {"allowed_company_ids": self.env.companies.ids},
})
acknowledgement = self.make_jsonrpc_request(route, params)
self._deliver_iap_callbacks()
return acknowledgement
def _post_user_message_on_session(self, session: AiSession, body: str, ai_session_config=None):
mail_msg = session.channel_id.message_post(body=body, message_type="comment")
config = self._get_ai_session_default_controls() | {"ai_prompt_button_ref": None} | (ai_session_config or {})
return self._call_ai_endpoint("/ai/start_session_advance", {
"channel_id": session.channel_id.id,
"mail_message_id": mail_msg.id,
"ai_session_config": config,
})
def _resume_pending_tool_on_session(self, session: AiSession, response, ai_session_config=None):
return self._call_ai_endpoint("/ai/resume_pending_interaction", {
"channel_id": session.channel_id.id,
"session_id": session.id,
"resume_token": session.resume_token,
"response": response,
"ai_session_config": ai_session_config,
})
def _confirm_pending_tool(self, session: AiSession, auto_confirm: bool = False):
return self._resume_pending_tool_on_session(session, {
"kind": "confirmation",
"value": UserInputResponse.AUTO_CONFIRM if auto_confirm else UserInputResponse.CONFIRM_ONCE,
}, ai_session_config=self._get_ai_session_default_controls())
@contextmanager
def mock_iap_results(env, return_values, *, channel_name="test_channel"):
"""Send signed mocked IAP replies to the admin tour over the bus."""
responses = iter(return_values)
def submit(connection, route, params, **kwargs):
assert route == "1/get_completions"
if params["usage"] == "channel_name":
content = [{"type": "text", "text": channel_name}]
else:
content = next(responses)
llm_result = {"result": {
"role": "assistant",
"content": content,
"provider_metadata": {},
}}
env.ref("base.user_admin")._bus_send("ai.test/callbacks_ready", {
"request_uuid": params["request_uuid"],
"llm_result": llm_result,
"llm_error": False,
"signature": hmac(None, "odoo_ai-webhook", (
params["request_uuid"], llm_result, False,
), secret=params["webhook_secret"]),
})
# Submission is already in postcommit; dispatch this test notification explicitly.
env.cr.precommit.run()
env.cr.postcommit.run()
return {}
with patch("odoo.addons.ai.models.ai_session.call_odoo_ai_transport", side_effect=submit):
yield

BIN
ai/tests/fixtures/audio_3s_opus.webm vendored Normal file

Binary file not shown.

216
ai/tests/test_ai_access.py Normal file
View File

@@ -0,0 +1,216 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.exceptions import AccessError
from odoo.tests import new_test_user, HttpCase, JsonRpcException, tagged, users
from odoo.tools import mute_logger
@tagged('post_install', '-at_install')
class TestAiFieldsAccess(HttpCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.internal_user = new_test_user(cls.env, 'internal')
cls.portal_user = new_test_user(cls.env, 'portal_user', 'base.group_portal')
def test_ai_access_agent_system(self):
# system: every right
agent = self.env['ai.agent'].create({'name': 'test agent'})
agent.write({'subtitle': 'bloups'})
self.assertEqual(self.env['ai.agent'].search([('name', '=', 'test agent')]), agent)
agent.unlink()
self.assertFalse(agent.exists())
@users('internal')
def test_ai_access_agent_internal(self):
# internal: readonly
with self.assertRaises(AccessError):
self.env['ai.agent'].create({'name': 'test agent'})
agent_sudo = self.env['ai.agent'].sudo().create({'name': 'test agent'})
agent = self.env['ai.agent'].search([('name', '=', 'test agent')])
self.assertEqual(agent, agent_sudo)
self.assertEqual('test agent', agent.name)
with self.assertRaises(AccessError):
agent.write({'subtitle': 'bloups'})
with self.assertRaises(AccessError):
agent.unlink()
def test_ai_access_embedding_system(self):
# system: every right
attachment = self.env['ir.attachment'].create({
'name': 'test attachment',
'raw': b'test',
'res_model': 'ai.embedding',
'res_id': 0,
})
embedding = self.env['ai.embedding'].create({
'res_id': attachment.id,
'res_model': 'ir.attachment',
'content': 'test content',
'embedding_model': 'embedding_model',
})
embedding.write({'content': 'updated content'})
self.assertEqual(
self.env['ai.embedding'].search([('id', '=', embedding.id)]),
embedding
)
embedding.unlink()
self.assertFalse(embedding.exists())
@users('internal')
def test_ai_access_embedding_internal(self):
# internal: readonly
attachment = self.env['ir.attachment'].create({
'name': 'test attachment',
'raw': b'test',
'res_model': 'ai.embedding',
'res_id': 0,
})
with self.assertRaises(AccessError):
self.env['ai.embedding'].create({
'res_id': attachment.id,
'res_model': 'ir.attachment',
'content': 'test content',
'embedding_model': 'embedding_model',
})
embedding_sudo = self.env['ai.embedding'].sudo().create({
'res_id': attachment.id,
'res_model': 'ir.attachment',
'content': 'test content',
'embedding_model': 'embedding_model',
})
with self.assertRaises(AccessError):
embedding = self.env['ai.embedding'].search([('id', '=', embedding_sudo.id)])
self.assertEqual(embedding, embedding_sudo)
self.assertEqual('test content', embedding.content)
with self.assertRaises(AccessError):
embedding_sudo.sudo(False).write({'content': 'updated content'})
with self.assertRaises(AccessError):
embedding_sudo.sudo(False).unlink()
def test_ai_access_skill_system(self):
# system: every right
skill = self.env['ai.skill'].create({
'name': 'test skill',
'description': 'skill description',
})
skill.write({'description': 'updated skill description'})
self.assertEqual(
self.env['ai.skill'].search([('id', '=', skill.id)]),
skill
)
skill.unlink()
self.assertFalse(skill.exists())
@users('internal')
def test_ai_access_skill_internal(self):
# internal: readonly
with self.assertRaises(AccessError):
self.env['ai.skill'].create({
'name': 'test skill',
'description': 'skill description',
})
skill_sudo = self.env['ai.skill'].sudo().create({
'name': 'test skill',
'description': 'skill description',
})
skill = self.env['ai.skill'].search([('id', '=', skill_sudo.id)])
self.assertEqual(skill, skill_sudo)
self.assertEqual('test skill', skill.name)
with self.assertRaises(AccessError):
skill.write({'description': 'updated skill description'})
with self.assertRaises(AccessError):
skill.unlink()
def test_create_ai_chat_with_restriced_record(self):
"""User should not be able to create a chat linked to a not accessible record
"""
user = self.internal_user
partner = self.env['res.partner'].create({'name': "Partner"})
# remove res.partner read access from the user
self.env['ir.access'].search([
('model_id.model', '=', 'res.partner'),
('group_id', 'in', user.all_group_ids.ids)
]).active = False
self.env['ir.access'].create({
'name': 'all except partner',
'model_id': self.env['ir.model']._get('res.partner').id,
'group_id': self.env.ref('base.group_user').id,
'operation': 'r',
'domain': str([('id', '!=', partner.id)]),
})
with self.assertRaises(AccessError):
self.env['ai.agent'].with_user(user).action_launch_ai_chat('mail_composer', 'res.partner', partner.id)
def test_chat_with_restriced_record(self):
"""Make sure that when access to a record is lost, new messages can't be sent anymore
"""
user = self.internal_user
partner = self.env['res.partner'].create({'name': "Partner"})
session_data = self.env['ai.agent'].action_launch_ai_chat(
'chatter_ai_button',
'res.partner',
partner.id,
'test',
None,
None,
None,
)
# remove res.partner read access from the user
access_records = self.env['ir.access'].search([
('model_id.model', '=', 'res.partner'),
('group_id', 'in', user.all_group_ids.ids),
])
access_records.active = False
session = self.env['ai.session'].search([('channel_id', '=', session_data['ai_channel_id'])])
with self.assertRaises(AccessError):
session.with_user(user).sudo()._submit_agent_request([
{'type': 'text', 'text': "Hello"},
])
@mute_logger('odoo.http')
def test_direct_response_portal(self):
"""Check that get_direct_response cannot be used by portal users
"""
self.authenticate('portal_user', 'portal_user')
with self.assertRaises(JsonRpcException, msg='odoo.exceptions.AccessError'):
self.make_jsonrpc_request(
"/ai/get_direct_response",
{
"interface_key": "systray_ai_button",
"prompt": "<p>Test prompt</p>",
}
)
def test_get_tool_params_requires_channel_access(self):
"""Internal users can read tool parameters only from channels they can access."""
agent = self.env['ai.agent'].create({'name': 'Test Agent'})
channel = agent._create_ai_chat_channel().with_user(self.internal_user)
session = self.env['ai.session'].create({
'agent_id': agent.id,
'channel_id': channel.id,
})
event = self.env['ai.session.event'].create({
'ai_session_id': session.id,
'metadata': {'role': 'assistant', 'content': [{
'type': 'tool_call',
'name': 'test_tool',
'call_id': 'call_1',
'args': {"value": "test"},
}]},
}).with_user(self.internal_user)
self.assertFalse(session.with_user(self.internal_user).has_access('read'))
self.assertFalse(event.has_access('read'))
self.assertFalse(channel.has_access('read'))
with self.assertRaises(AccessError):
event.get_tool_params('call_1')
self.env['discuss.channel.member'].create({
'channel_id': channel.id,
'partner_id': self.internal_user.partner_id.id,
})
self.assertTrue(channel.has_access('read'))
self.assertEqual(event.get_tool_params('call_1'), {'value': 'test'})

124
ai/tests/test_ai_agent.py Normal file
View File

@@ -0,0 +1,124 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from unittest.mock import patch
from odoo.tests import new_test_user, tagged, users
from odoo.addons.ai.tests.common import TestAICommon
from odoo.addons.ai.utils.ai_utils import AI_MODELS_BLOCKLIST
from odoo.addons.base.tests.test_ir_cron import CronMixinCase
@tagged("post_install", "-at_install")
class TestAIAgent(TestAICommon, CronMixinCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.internal_user = new_test_user(cls.env, 'internal')
cls.regular_user = new_test_user(cls.env, 'regular', groups='base.group_user,base.group_user_regular')
def test_get_llm_response_with_sources(self):
"""Responses include source links when the LLM returns attachment ids."""
agent = self.env["ai.agent"].create({
"name": "Odoo Agent",
})
attachment = self.env["ir.attachment"].create({
"name": "Doc 1",
"raw": b"content text",
"mimetype": "text/plain",
})
source = self.env["ai.agent.source"].create({
"name": "Doc 1",
"agent_id": agent.id,
"attachment_id": attachment.id,
"type": "binary",
"status": "indexed",
"is_active": True,
})
message = f"Here is your answer [SOURCE:{source.id}]"
cited_llm_response = agent._get_llm_response_with_sources(message)
self.assertNotIn("[SOURCE", cited_llm_response)
self.assertIn("href=\"/web/content/%s\"" % (attachment.id), cited_llm_response)
self.assertIn("[1]", cited_llm_response)
def test_parse_domain_raises_for_ir_prefix(self):
with self.assertRaisesRegex(ValueError, "ir.config_parameter cannot be used by AI Agents"):
self.env['ai.tool']._parse_domain("ir.config_parameter", "[('id', '=', '1')]")
def test_parse_domain_raises_for_blocklisted_model(self):
for model in AI_MODELS_BLOCKLIST:
if self.env['ir.module.module']._get('ai_agentic').state == 'installed' and model == "base.automation":
# skip case since 'base.automation' is accessible to agents if the ai_agentic is installed
# (Used to create/update automations, access rights checks are performed in the tools)
continue
with self.subTest(model=model):
with self.assertRaisesRegex(ValueError, f"{model} cannot be used by AI Agents"):
self.env['ai.tool']._parse_domain(model, "[('id', '=', '1')]")
@users("internal")
def test_ai_tool_get_menus_as_non_admin(self):
"""_ai_tool_get_menus should work for non-admin users and exclude inaccessible menus."""
settings_menu = self.env.ref("base.menu_administration")
menus_csv = self.env["ai.tool"]._ai_tool_get_menus()['response']
self.assertNotIn(
settings_menu.name,
menus_csv,
"Menus the user cannot access should not appear in the available menus.",
)
@users("regular")
def test_get_menu_details_as_regular_user(self):
"""_ai_tool_get_menu_details should work for non-admin users, returning details for
accessible menus and an error for inaccessible ones.
"""
settings_menu = self.env.ref("base.menu_administration")
channels_menu = self.env.ref("mail.menu_channel")
result = self.env["ai.tool"]._ai_tool_get_menu_details(
[settings_menu.id, channels_menu.id], True,
)['response']
menus_by_id = {m["menu_id"]: m for m in result["menus"]}
self.assertIn("error", menus_by_id[settings_menu.id],
"Inaccessible menu should return an error.")
self.assertNotIn("error", menus_by_id[channels_menu.id],
"Accessible act_window menu should return details without an error.")
def test_build_rag_context_with_res_field_attachment(self):
"""Ensure RAG context works by bypassing the implicit 'res_field' filter with 'skip_res_field_check', preventing KeyError."""
admin_user = self.env.ref('base.user_admin')
agent = self.env["ai.agent"].with_user(admin_user).create({
"name": "RAG Agent",
})
attachment = self.env["ir.attachment"].create({
"name": "Invoice PDF",
"raw": b"pdf content",
"res_model": "sale.order",
"res_id": 1,
"res_field": "invoice_pdf",
"mimetype": "text/plain",
})
self.env["ai.agent.source"].create({
"agent_id": agent.id,
"attachment_id": attachment.id,
"name": "Invoice source",
"status": "indexed",
"is_active": True,
})
embedding = self.env["ai.embedding"].create({
"res_model": "ir.attachment",
"res_id": attachment.id,
"content": "Dummy chunk",
})
with patch('odoo.addons.ai.models.ai_embedding.AIEmbedding._get_similar_chunks') as mock_get_similar_chunks, \
self.mock_embedding_request():
mock_get_similar_chunks.return_value = self.env["ai.embedding"].browse(embedding.id)
rag_context = agent.with_user(admin_user)._build_rag_context("Prompt")
self.assertTrue(rag_context, "RAG context should contain a message for user")
self.assertIn("Invoice source", rag_context)
self.assertIn("Dummy chunk", rag_context)

View File

@@ -0,0 +1,555 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, timedelta, UTC
from zoneinfo import ZoneInfo
from odoo.tests import TransactionCase, tagged
@tagged("post_install", "-at_install")
class TestAIAgentComputeDate(TransactionCase):
"""Test suite for AI agent compute_date tool."""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.agent = cls.env["ai.agent"].create({
"name": "Test AI Agent",
})
# Create a test model with date and datetime fields (using mail.activity as it has both)
cls.test_model = "mail.activity"
cls.date_field = "date_done" # date field
cls.datetime_field = "create_date" # datetime field
def test_validate_inputs(self):
"""Test input validation."""
# Test invalid model_name
with self.assertRaises(ValueError):
self.env['ai.tool']._ai_tool_compute_date("", "create_date")
with self.assertRaises(ValueError):
self.env['ai.tool']._ai_tool_compute_date("invalid.model", "create_date")
# Test invalid field_name
with self.assertRaises(ValueError):
self.env['ai.tool']._ai_tool_compute_date(self.test_model, "")
with self.assertRaises(ValueError):
self.env['ai.tool']._ai_tool_compute_date(self.test_model, "nonexistent_field")
# Test non-date field
with self.assertRaises(ValueError):
self.env['ai.tool']._ai_tool_compute_date(self.test_model, "name")
def test_navigate_day(self):
"""Test navigation by day."""
# Yesterday
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "navigate", "period": "day", "offset": -1}]
)['response']
expected = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
self.assertEqual(result, expected)
# Tomorrow
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "navigate", "period": "day", "offset": 1}]
)['response']
expected = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d')
self.assertEqual(result, expected)
# 3 days ago
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "navigate", "period": "day", "offset": -3}]
)['response']
expected = (datetime.now() - timedelta(days=3)).strftime('%Y-%m-%d')
self.assertEqual(result, expected)
def test_navigate_day_with_boundary(self):
"""Test navigation by day with boundaries."""
# Yesterday at start (midnight)
with self.mock_datetime_and_now(datetime(2025, 10, 14)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.datetime_field,
operations=[{"type": "navigate", "period": "day", "offset": -1, "boundary": "start"}]
)['response']
# Result should be in UTC
# October 13, 2025 00:00:00 in user timezone
expected_dt = datetime(2025, 10, 13, 0, 0, 0, tzinfo=ZoneInfo(self.env.user.tz or 'UTC'))
expected_utc = expected_dt.astimezone(UTC)
self.assertEqual(result, expected_utc.strftime('%Y-%m-%d %H:%M:%S'))
def test_navigate_week(self):
"""Test navigation by week."""
# Start of this week
# Use Wednesday, October 15, 2025
with self.mock_datetime_and_now(datetime(2025, 10, 15)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "navigate", "period": "week", "offset": 0, "boundary": "start"}]
)['response']
# Start of week is Monday (ISO 8601), so October 13, 2025
self.assertEqual(result, "2025-10-13")
# End of last week
with self.mock_datetime_and_now(datetime(2025, 10, 15)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "navigate", "period": "week", "offset": -1, "boundary": "end"}]
)['response']
# End of last week is Sunday October 12, 2025
self.assertEqual(result, "2025-10-12")
def test_navigate_month(self):
"""Test navigation by month."""
# Start of this month
with self.mock_datetime_and_now(datetime(2025, 10, 15)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "navigate", "period": "month", "offset": 0, "boundary": "start"}]
)['response']
self.assertEqual(result, "2025-10-01")
# End of last month
with self.mock_datetime_and_now(datetime(2025, 10, 15)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "navigate", "period": "month", "offset": -1, "boundary": "end"}]
)['response']
self.assertEqual(result, "2025-09-30")
# Month navigation with day clamping (Jan 31 -> Feb 28/29)
with self.mock_datetime_and_now(datetime(2025, 1, 31)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "navigate", "period": "month", "offset": 1}]
)['response']
# February 2025 has 28 days, so day should be clamped to 28
self.assertEqual(result, "2025-02-28")
def test_navigate_quarter(self):
"""Test navigation by quarter."""
# Start of this quarter (Q4 2025)
with self.mock_datetime_and_now(datetime(2025, 10, 15)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "navigate", "period": "quarter", "offset": 0, "boundary": "start"}]
)['response']
self.assertEqual(result, "2025-10-01")
# End of last quarter (Q3 2025)
with self.mock_datetime_and_now(datetime(2025, 10, 15)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "navigate", "period": "quarter", "offset": -1, "boundary": "end"}]
)['response']
self.assertEqual(result, "2025-09-30")
def test_navigate_year(self):
"""Test navigation by year."""
# Start of this year
with self.mock_datetime_and_now(datetime(2025, 10, 15)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "navigate", "period": "year", "offset": 0, "boundary": "start"}]
)['response']
self.assertEqual(result, "2025-01-01")
# End of last year
with self.mock_datetime_and_now(datetime(2025, 10, 15)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "navigate", "period": "year", "offset": -1, "boundary": "end"}]
)['response']
self.assertEqual(result, "2024-12-31")
def test_find_previous_weekday(self):
"""Test finding previous occurrence of weekday."""
# Last Monday (starting from Wednesday October 15, 2025)
with self.mock_datetime_and_now(datetime(2025, 10, 15)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "find_previous", "weekday": 0}] # Monday
)['response']
# Previous Monday is October 13, 2025
self.assertEqual(result, "2025-10-13")
# Last Friday
with self.mock_datetime_and_now(datetime(2025, 10, 15)):
# Wednesday
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "find_previous", "weekday": 4}] # Friday
)['response']
# Previous Friday is October 10, 2025
self.assertEqual(result, "2025-10-10")
def test_find_next_weekday(self):
"""Test finding next occurrence of weekday."""
# Next Monday (starting from Wednesday October 15, 2025)
with self.mock_datetime_and_now(datetime(2025, 10, 15)):
# Wednesday
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "find_next", "weekday": 0}] # Monday
)['response']
# Next Monday is October 20, 2025
self.assertEqual(result, "2025-10-20")
# Next Friday
with self.mock_datetime_and_now(datetime(2025, 10, 15)):
# Wednesday
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "find_next", "weekday": 4}] # Friday
)['response']
# Next Friday is October 17, 2025
self.assertEqual(result, "2025-10-17")
def test_pin_time(self):
"""Test pinning to specific time."""
# 3 days ago at noon
with self.mock_datetime_and_now(datetime(2025, 10, 15)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.datetime_field,
operations=[{"type": "navigate", "period": "day", "offset": -3}],
pin={"time": "12:00"}
)['response']
# October 12, 2025 12:00:00 in user timezone
expected_dt = datetime(2025, 10, 12, 12, 0, 0, tzinfo=ZoneInfo(self.env.user.tz or 'UTC'))
expected_utc = expected_dt.astimezone(UTC)
self.assertEqual(result, expected_utc.strftime('%Y-%m-%d %H:%M:%S'))
# Tomorrow at 5 PM
with self.mock_datetime_and_now(datetime(2025, 10, 15)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.datetime_field,
operations=[{"type": "navigate", "period": "day", "offset": 1}],
pin={"time": "17:00"}
)['response']
expected_dt = datetime(2025, 10, 16, 17, 0, 0, tzinfo=ZoneInfo(self.env.user.tz or 'UTC'))
expected_utc = expected_dt.astimezone(UTC)
self.assertEqual(result, expected_utc.strftime('%Y-%m-%d %H:%M:%S'))
def test_pin_day(self):
"""Test pinning to specific day of month."""
# 15th of this month
with self.mock_datetime_and_now(datetime(2025, 10, 20)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "navigate", "period": "month", "offset": 0}],
pin={"day": 15}
)['response']
self.assertEqual(result, "2025-10-15")
def test_pin_weekday_occurrence(self):
"""Test pinning to Nth occurrence of weekday in month."""
# Second Tuesday of October 2025
with self.mock_datetime_and_now(datetime(2025, 10, 20)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "navigate", "period": "month", "offset": 0, "boundary": "start"}],
pin={"day": {"weekday": 1, "occurrence": 2}}, # Tuesday, 2nd occurrence
)['response']
# October 2025: 1st Tuesday is Oct 7, 2nd Tuesday is Oct 14
self.assertEqual(result, "2025-10-14")
# First Monday of last month
with self.mock_datetime_and_now(datetime(2025, 10, 20)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "navigate", "period": "month", "offset": -1, "boundary": "start"}],
pin={"day": {"weekday": 0, "occurrence": 1}}, # Monday, 1st occurrence
)['response']
# September 2025: 1st Monday is Sep 1
self.assertEqual(result, "2025-09-01")
# 2nd Friday of March last year
with self.mock_datetime_and_now(datetime(2025, 10, 30)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[
{"type": "navigate", "period": "year", "offset": -1, "boundary": "start"}, # Jan 1, 2024
{"type": "navigate", "period": "month", "offset": 2, "boundary": "start"}, # Mar 1, 2024
],
pin={"day": {"weekday": 4, "occurrence": 2}}, # Friday, 2nd occurrence
)['response']
# March 2024: 1st Friday is Mar 1, 2nd Friday is Mar 8
self.assertEqual(result, "2024-03-08")
def test_navigate_to_specific_month_and_day(self):
"""Test navigating to a specific month and day without using pin.month."""
# February 15th of this quarter (Q1 2025)
with self.mock_datetime_and_now(datetime(2025, 1, 20)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[
{"type": "navigate", "period": "quarter", "offset": 0, "boundary": "start"}, # Jan 1, 2025
{"type": "navigate", "period": "month", "offset": 1, "boundary": "start"}, # Feb 1, 2025
],
pin={"day": 15},
)['response']
self.assertEqual(result, "2025-02-15")
def test_combined_operations(self):
"""Test combining multiple operations."""
# Last Monday at 5 PM
with self.mock_datetime_and_now(datetime(2025, 10, 15)):
# Wednesday
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.datetime_field,
operations=[{"type": "find_previous", "weekday": 0}], # Monday
pin={"time": "17:00"}
)['response']
expected_dt = datetime(2025, 10, 13, 17, 0, 0, tzinfo=ZoneInfo(self.env.user.tz or 'UTC'))
expected_utc = expected_dt.astimezone(UTC)
self.assertEqual(result, expected_utc.strftime('%Y-%m-%d %H:%M:%S'))
def test_offset_limits(self):
"""Test offset validation."""
# Test offset too large
with self.assertRaises(ValueError):
self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "navigate", "period": "day", "offset": 101}]
)
# Test offset too small
with self.assertRaises(ValueError):
self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "navigate", "period": "day", "offset": -101}]
)
def test_offset_none(self):
"""Test that None offsets are treated as 0 (no movement)."""
with self.mock_datetime_and_now(datetime(2025, 10, 15)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "navigate", "period": "day", "offset": None}]
)['response']
self.assertEqual(result, "2025-10-15")
def test_datetime_field_returns_utc(self):
"""Test that datetime fields return UTC timestamps."""
with self.mock_datetime_and_now(datetime(2025, 10, 15)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.datetime_field,
operations=[{"type": "navigate", "period": "day", "offset": 0, "boundary": "start"}]
)['response']
# Result should be in UTC and contain time
self.assertRegex(result, r'^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$')
def test_date_field_returns_date_only(self):
"""Test that date fields return date-only format."""
with self.mock_datetime_and_now(datetime(2025, 10, 15)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "navigate", "period": "day", "offset": 0}]
)['response']
# Result should be date-only
self.assertRegex(result, r'^\d{4}-\d{2}-\d{2}$')
self.assertNotIn(':', result)
def test_pin_with_none_values(self):
"""Test that pin fields with None values are properly ignored (LLM pattern)."""
# LLMs often generate complete JSON with None for unused fields
# This should work without raising validation errors
with self.mock_datetime_and_now(datetime(2025, 10, 15)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.datetime_field,
operations=[{"type": "navigate", "period": "day", "offset": -1}],
pin={"time": "23:59:59"},
)['response']
# Should succeed and use only the time pin
expected_dt = datetime(2025, 10, 14, 23, 59, 59, tzinfo=ZoneInfo(self.env.user.tz or 'UTC'))
expected_utc = expected_dt.astimezone(UTC)
self.assertEqual(result, expected_utc.strftime('%Y-%m-%d %H:%M:%S'))
def test_pin_weekday_occurrence_with_none_fields(self):
"""Test weekday_occurrence with None values for other pin fields."""
# Second Monday of last month with None for unused pin fields
with self.mock_datetime_and_now(datetime(2025, 10, 20)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[{"type": "navigate", "period": "month", "offset": -1, "boundary": "start"}],
pin={"day": {"weekday": 0, "occurrence": 2}},
)['response']
# September 2025: 2nd Monday is Sep 8
self.assertEqual(result, "2025-09-08")
def test_operations_with_none_values(self):
"""Test that operation fields with None values are properly ignored."""
# LLMs may include None for optional operation fields
with self.mock_datetime_and_now(datetime(2025, 10, 15)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[
{"type": "navigate", "period": "month", "offset": -1, "boundary": "start", "weekday": None},
{"type": "find_next", "weekday": 0, "offset": None, "period": None, "boundary": None},
],
)['response']
# Start of last month (Sept 1 is Monday), find_next Monday goes forward 7 days = Sept 8
self.assertEqual(result, "2025-09-08")
def test_pin_with_only_time_no_other_fields(self):
"""Test pin with only time field, no other fields present."""
with self.mock_datetime_and_now(datetime(2025, 10, 15)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.datetime_field,
operations=[{"type": "navigate", "period": "day", "offset": 0}],
pin={"time": "12:30:45"},
)['response']
expected_dt = datetime(2025, 10, 15, 12, 30, 45, tzinfo=ZoneInfo(self.env.user.tz or 'UTC'))
expected_utc = expected_dt.astimezone(UTC)
self.assertEqual(result, expected_utc.strftime('%Y-%m-%d %H:%M:%S'))
def test_complex_query_with_none_values(self):
"""Test complex date computation matching production pattern from logs."""
# Simulates: "invoiced sales orders from 2nd week of last month"
# Navigate to start of last month, find next Monday, add 1 week
with self.mock_datetime_and_now(datetime(2025, 10, 14)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.date_field,
operations=[
{"type": "navigate", "period": "month", "offset": -1, "boundary": "start", "weekday": None},
{"type": "find_next", "weekday": 0, "offset": None, "period": None, "boundary": None},
{"type": "navigate", "period": "week", "offset": 1, "boundary": None, "weekday": None},
],
pin=None,
)['response']
# Sept 1 is Monday, find_next Monday = Sept 8, + 1 week = Sept 15
self.assertEqual(result, "2025-09-15")
def test_find_weekday_crosses_dst_boundary(self):
"""Test find_weekday operations that cross DST boundaries without pin."""
self.env.user.tz = 'Europe/Brussels'
# Test crossing DST end boundary (CEST UTC+2 -> CET UTC+1)
# Start: Friday Oct 24, 2025 (CEST, UTC+2) at default midnight
# Find next Monday: Oct 27, 2025 (CET, UTC+1) - crosses DST boundary on Oct 26
with self.mock_datetime_and_now(datetime(2025, 10, 24)):
# Friday
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.datetime_field,
operations=[{"type": "find_next", "weekday": 0}], # Monday
pin=None, # No pin - this is critical for the bug
)['response']
# Oct 27, 2025 00:00:00 CET (UTC+1) = Oct 26, 2025 23:00:00 UTC
self.assertEqual(result, "2025-10-26 23:00:00")
# Test crossing DST start boundary (CET UTC+1 -> CEST UTC+2)
# Start: Friday Mar 28, 2025 (CET, UTC+1) at default midnight
# Find next Monday: Mar 31, 2025 (CEST, UTC+2) - crosses DST boundary on Mar 30
with self.mock_datetime_and_now(datetime(2025, 3, 28)):
# Friday
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.datetime_field,
operations=[{"type": "find_next", "weekday": 0}], # Monday
pin=None,
)['response']
# Mar 31, 2025 00:00:00 CEST (UTC+2) = Mar 30, 2025 22:00:00 UTC
self.assertEqual(result, "2025-03-30 22:00:00")
def test_dst_timezone_handling(self):
"""Test that DST transitions are handled correctly when navigating between seasons."""
# Set user timezone to Europe/Brussels (has DST)
self.env.user.tz = 'Europe/Brussels'
# Test: Navigate from winter (CET, UTC+1) to summer (CEST, UTC+2)
# Start in October (CET, UTC+1), navigate to May (CEST, UTC+2)
with self.mock_datetime_and_now(datetime(2025, 10, 30)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.datetime_field,
operations=[
{"type": "navigate", "period": "quarter", "offset": -2, "boundary": "start"}, # Apr 1, 2025
{"type": "navigate", "period": "month", "offset": 1, "boundary": "start"}, # May 1, 2025
],
pin={"day": 16, "time": "00:00:00"},
)['response']
# May 16, 2025 00:00:00 in Brussels (UTC+2) = May 15, 2025 22:00:00 UTC
self.assertEqual(result, "2025-05-15 22:00:00")
# Test: Navigate from summer (CEST, UTC+2) to winter (CET, UTC+1)
# Start in May (CEST, UTC+2), navigate to November (CET, UTC+1)
# DST ends last Sunday of October (Oct 26, 2025), so Nov 1 is definitely CET
with self.mock_datetime_and_now(datetime(2025, 5, 16)):
result = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.datetime_field,
operations=[
{"type": "navigate", "period": "quarter", "offset": 2, "boundary": "start"}, # Oct 1, 2025
{"type": "navigate", "period": "month", "offset": 1, "boundary": "start"}, # Nov 1, 2025
],
pin={"time": "00:00:00"},
)['response']
# November 1, 2025 00:00:00 in Brussels (UTC+1) = October 31, 2025 23:00:00 UTC
self.assertEqual(result, "2025-10-31 23:00:00")
# Test: Verify 3rd Friday of May with time pins
# This is the actual case from the user's log
with self.mock_datetime_and_now(datetime(2025, 10, 30)):
# Start of day
result_start = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.datetime_field,
operations=[
{"type": "navigate", "period": "quarter", "offset": -2, "boundary": "start"}, # Apr 1, 2025
{"type": "navigate", "period": "month", "offset": 1, "boundary": "start"}, # May 1, 2025
],
pin={"day": {"weekday": 4, "occurrence": 3}, "time": "00:00:00"},
)['response']
# End of day
result_end = self.env['ai.tool']._ai_tool_compute_date(
self.test_model,
self.datetime_field,
operations=[
{"type": "navigate", "period": "quarter", "offset": -2, "boundary": "start"}, # Apr 1, 2025
{"type": "navigate", "period": "month", "offset": 1, "boundary": "start"}, # May 1, 2025
],
pin={"day": {"weekday": 4, "occurrence": 3}, "time": "23:59:59"},
)['response']
# May 2025: 3rd Friday is May 16, 2025
# May 16, 2025 00:00:00 CEST (UTC+2) = May 15, 2025 22:00:00 UTC
# May 16, 2025 23:59:59 CEST (UTC+2) = May 16, 2025 21:59:59 UTC
self.assertEqual(result_start, "2025-05-15 22:00:00")
self.assertEqual(result_end, "2025-05-16 21:59:59")

View File

@@ -0,0 +1,42 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.ai.tests.common import TestAICommon
class TestAIAgentSource(TestAICommon):
def test_unlink_source_should_unlinks_attachment(self):
"""Tests that unlinking a source unlinks its linked attachment."""
attachment_id = self.test_source.attachment_id
self.test_source.unlink()
self.assertFalse(attachment_id.exists(), "Attachment should be deleted with its source.")
def test_ai_web_page_source_unlink_if_single_source(self):
"""Tests that unlinking a source unlinks its linked web page
if it's the only source referencing that web page."""
web_page = self.env["ai.web.page"].create({
"url": "http://example.com",
"content": "<p>Some content</p>",
})
source_a = self.env["ai.agent.source"].create({
"name": "Some web source",
"agent_id": self.agent.id,
"type": "url",
"web_page_id": web_page.id,
"status": "indexed",
})
source_b = self.env["ai.agent.source"].create({
"name": "Some web source",
"agent_id": self.agent.id,
"type": "url",
"web_page_id": web_page.id,
"status": "indexed",
})
source_a.unlink()
self.assertTrue(web_page.exists(), "Web page should not be deleted if still referenced by a source.")
source_b.unlink()
self.assertFalse(web_page.exists(), "Web page should be deleted if not linked to any source.")

View File

@@ -0,0 +1,101 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from psycopg2 import IntegrityError
from odoo.tests import tagged, mute_logger
from .common import TestAICommon
@tagged("post_install", "-at_install")
class TestAIComposer(TestAICommon):
@mute_logger('odoo.sql_db')
def test_unique_composer_constraint(self):
"""Creating two composers with the same interface_key and focused_model_id should raise,
even for two different agents: the rule is unique system-wide, not per agent."""
agent_a = self.env['ai.agent'].create({'name': 'Agent A'})
agent_b = self.env['ai.agent'].create({'name': 'Agent B'})
partner_model = self.env['ir.model']._get('res.partner')
self.env['ai.composer'].create({
'name': 'First',
'interface_key': 'systray_ai_button',
'ai_agent_id': agent_a.id,
'focused_model_id': partner_model.id,
})
with self.assertRaises(IntegrityError):
self.env['ai.composer'].create({
'name': 'Second',
'interface_key': 'systray_ai_button',
'ai_agent_id': agent_b.id,
'focused_model_id': partner_model.id,
})
@mute_logger('odoo.sql_db')
def test_unique_composer_constraint_conflicts_with_system_default(self):
"""A new composer with no focused_model_id collides with the seeded system-default
rule for that interface_key, since NULL models are not distinct from one another."""
agent = self.env['ai.agent'].create({'name': 'Test Agent'})
with self.assertRaises(IntegrityError):
self.env['ai.composer'].create({
'name': 'Custom Systray Default',
'interface_key': 'systray_ai_button',
'ai_agent_id': agent.id,
})
def test_unique_composer_constraint_different_models(self):
"""Creating composers with same agent and interface_key but different models should not raise."""
agent = self.env['ai.agent'].create({'name': 'Test Agent'})
partner_model = self.env['ir.model']._get('res.partner')
mail_message_model = self.env['ir.model']._get('mail.message')
self.env['ai.composer'].create({
'name': 'Partner Composer',
'interface_key': 'systray_ai_button',
'ai_agent_id': agent.id,
'focused_model_id': partner_model.id,
})
self.env['ai.composer'].create({
'name': 'Mail Message Composer',
'interface_key': 'systray_ai_button',
'ai_agent_id': agent.id,
'focused_model_id': mail_message_model.id,
})
def test_retrieve_transcription_composer(self):
agent = self.env['ai.agent'].create({
'name': 'Test AI Agent',
})
ai_agent_model = self.env['ir.model']._get('ai.agent')
default_transcription_composer = self.env['ai.composer'].search([
('interface_key', '=', 'voice_transcription_component'),
('focused_model_id', '=', False),
], limit=1)
ai_agent_transcription_composer = self.env['ai.composer'].create({
'name': 'AI Agent Composer',
'interface_key': 'voice_transcription_component',
'ai_agent_id': agent.id,
'focused_model_id': ai_agent_model.id,
})
res = self.env['ai.composer'].retrieve_transcription_composer('ai.agent')
self.assertEqual(res['id'], ai_agent_transcription_composer.id, "Should retrieve the composer specific to ai.agent")
res = self.env['ai.composer'].retrieve_transcription_composer(False)
self.assertEqual(res['id'], default_transcription_composer.id, "Should retrieve the default composer when no model is provided")
def test_file_viewer_ai_button_composer_context(self):
attachment = self.env['ir.attachment'].create({
'name': 'test attachment',
'raw': b'test',
})
composer = self.env['ai.composer'].create({
'name': 'File Viewer Composer',
'interface_key': 'file_viewer_ai_button',
'focused_model_id': self.env['ir.model']._get_id('ir.attachment'),
})
context = composer._get_initial_context(res_model='ir.attachment', res_id=attachment.id)
self.assertTrue(
any("test attachment" in part['text'] for part in context),
"The attachment name should be present in the context parts"
)

View File

@@ -0,0 +1,130 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from unittest.mock import patch
from odoo.tests import tagged
from odoo.addons.ai.tests.common import TestAICommon
@tagged("post_install", "-at_install")
class TestAIEmbedding(TestAICommon):
def test_embedding_generation_from_new_source(self):
"""Test that adding a source to an agent triggers its embedding"""
content_to_embed = b"content to embed"
attachment = self.env["ir.attachment"].create({
"name": "shared.txt",
"raw": content_to_embed,
})
with (
self.registry_test_mode(),
self.mock_embedding_request(),
patch("odoo.addons.ai.models.ai_embedding.AIEmbedding._get_default_embedding_model", return_value="default_embedding_model"),
):
agent = self.env["ai.agent"].create({
"name": "Agent",
})
valid_source = self.env["ai.agent.source"].create({
"name": f"Source {agent.name}",
"agent_id": agent.id,
"type": "binary",
"attachment_id": attachment.id,
})
self.env.ref('ai.ir_cron_generate_embedding').method_direct_trigger()
self.assertEqual(valid_source.status, "indexed")
created_embedding = self.env["ai.embedding"].search([("res_model", "=", "ir.attachment"), ("res_id", "=", attachment.id)])
self.assertTrue(created_embedding, "An embedding should have been created for the source")
self.assertEqual(created_embedding.embedding_model, "default_embedding_model")
expected_content = (
f"{content_to_embed.decode('utf-8')}"
)
self.assertEqual(created_embedding.content, expected_content)
self.assertEqual(created_embedding.embedding_vector, [0.1] * 1536)
def test_recompute_only_reprocesses_sources_on_deprecated_provider(self):
"""A source on a still-valid provider must not be affected by another
provider's deprecated embedding, even if they share the same checksum."""
agent_with_deprecated_embedding = self.env["ai.agent"].create({
"name": "Deprecated agent",
"embedding_model": "deprecated_embedding",
})
agent_with_valid_embedding = self.env["ai.agent"].create({
"name": "Valid agent",
"embedding_model": "valid_embedding",
})
attachment = self.env["ir.attachment"].create({
"name": "shared.txt",
"raw": b"some content",
})
attachment_2 = self.env["ir.attachment"].create({
"name": "shared.txt",
"raw": b"some content",
})
with patch("odoo.addons.ai.models.ai_agent_source.AIAgentSource._trigger_embedding_generation"):
deprecated_source = self.env["ai.agent.source"].create({
"name": f"Source {agent_with_deprecated_embedding.name}",
"agent_id": agent_with_deprecated_embedding.id,
"type": "binary",
"attachment_id": attachment.id,
"status": "indexed",
"is_active": True,
})
valid_source = self.env["ai.agent.source"].create({
"name": f"Source {agent_with_valid_embedding.name}",
"agent_id": agent_with_valid_embedding.id,
"type": "binary",
"attachment_id": attachment_2.id,
"status": "indexed",
"is_active": True,
})
deprecated_embedding = self.env["ai.embedding"].create({
"res_model": "ir.attachment",
"res_id": attachment.id,
"content": "chunk content",
"embedding_model": "deprecated_embedding",
"embedding_vector": [0.1] * 1536,
})
valid_embedding = self.env["ai.embedding"].create({
"res_model": "ir.attachment",
"res_id": attachment_2.id,
"content": "chunk content",
"embedding_model": "valid_embedding",
"embedding_vector": [0.1] * 1536,
})
with (
patch(
"odoo.addons.ai.models.ai_embedding.AIEmbedding._get_supported_embedding_models",
return_value=["valid_embedding"],
),
patch(
"odoo.addons.base.models.ir_cron.IrCron._trigger",
autospec=True,
) as mock_trigger,
patch(
"odoo.addons.base.models.ir_cron.IrCron._commit_progress",
),
):
self.env["ai.embedding"]._cron_update_deprecated_embedding_models()
self.assertFalse(deprecated_embedding.embedding_vector, "Deprecated embedding must be removed")
self.assertTrue(valid_embedding.embedding_vector, "Still-valid embedding must be kept")
self.assertEqual(deprecated_source.status, "processing")
self.assertTrue(deprecated_source.is_active, "Active status shouldn't have changed.")
self.assertEqual(agent_with_deprecated_embedding.embedding_model, self.env["ai.embedding"]._get_default_embedding_model(), "Agent model should be reset to default")
self.assertEqual(
valid_source.status, "indexed",
"Source on a still-valid provider must not be reprocessed",
)
self.assertTrue(valid_source.is_active)
mock_trigger.assert_called_once()
triggered_cron = mock_trigger.call_args.args[0]
self.assertEqual(triggered_cron, self.env.ref("ai.ir_cron_generate_embedding"))

View File

@@ -0,0 +1,220 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
from unittest.mock import patch, MagicMock, mock_open
from odoo.tools import file_open
from odoo.tests import TransactionCase
from odoo.exceptions import AccessError
from odoo.addons.ai.utils.ai_image_tools import (
closest_aspect_ratio,
_calculate_aspect_ratio,
field_to_image_path,
_retrieve_record_args_from_path,
_retrieve_image_parts_from_file,
_retrieve_image_src_and_mimetype_from_record,
retrieve_image_data_from_record,
retrieve_image_parts_from_path,
)
from odoo.addons.base.tests.files import PNG_RAW
class TestImageTools(TransactionCase):
def test_calculate_aspect_ratio(self):
self.assertEqual(_calculate_aspect_ratio(1024, 1024), "1:1")
self.assertEqual(_calculate_aspect_ratio(800, 600), "4:3")
self.assertEqual(_calculate_aspect_ratio(1920, 1080), "16:9")
self.assertEqual(_calculate_aspect_ratio(None, 100), "1:1")
self.assertEqual(_calculate_aspect_ratio(100, 0), "1:1")
self.assertEqual(_calculate_aspect_ratio(19, 17), "19:17")
self.assertEqual(_calculate_aspect_ratio(500, 300), "5:3")
def test_closest_aspect_ratio(self):
self.assertEqual(closest_aspect_ratio(width=1024, height=1024), "1:1")
self.assertEqual(closest_aspect_ratio(width=1920, height=1080), "16:9")
self.assertEqual(closest_aspect_ratio(width=800, height=600), "4:3")
# Arbitrary dimensions 719x512
# 719/512 = 1.404...
# 4:3 is 1.333... (diff 0.071)
# 3:2 is 1.5 (diff 0.096)
# So it should be 4:3.
self.assertEqual(closest_aspect_ratio(width=719, height=512), "4:3")
def test_field_to_image_path(self):
record = self.env['ai.agent'].browse(1)
path = field_to_image_path(record, 'image_1024')
self.assertEqual(path, "/web/image/ai.agent/1/image_1024")
def test_retrieve_record_args_from_path(self):
cases = [
# '/web/image/<string:xmlid>'
("/web/image/ai.abc123", {'xmlid': 'ai.abc123'}),
# '/web/image/<string:xmlid>/<string:filename>'
("/web/image/ai.abc123/image_128", {'xmlid': 'ai.abc123'}),
# '/web/image/<string:xmlid>/<int:width>x<int:height>'
("/web/image/ai.abc123/1024x1024", {'xmlid': 'ai.abc123'}),
# '/web/image/<string:xmlid>/<int:width>x<int:height>/<string:filename>'
("/web/image/ai.abc123/1024x1024/image_128", {'xmlid': 'ai.abc123'}),
# '/web/image/<string:model>/<int:id>/<string:field>'
("/web/image/res.partner/123/image_128", {'model': 'res.partner', 'id': 123, 'field': 'image_128'}),
# '/web/image/<string:model>/<int:id>/<string:field>/<string:filename>'
("/web/image/res.partner/123/image_128/image_128", {'model': 'res.partner', 'id': 123, 'field': 'image_128'}),
# '/web/image/<string:model>/<int:id>/<string:field>/<int:width>x<int:height>'
("/web/image/res.partner/123/image_128/1024x1024", {'model': 'res.partner', 'id': 123, 'field': 'image_128'}),
# '/web/image/<string:model>/<int:id>/<string:field>/<int:width>x<int:height>/<string:filename>'
("/web/image/res.partner/123/image_128/1024x1024/image_128", {'model': 'res.partner', 'id': 123, 'field': 'image_128'}),
# '/web/image/<int:id>'
("/web/image/123", {'model': 'ir.attachment', 'id': 123, 'field': 'raw'}),
# '/web/image/<int:id>/<string:filename>'
("/web/image/123/image_128", {'model': 'ir.attachment', 'id': 123, 'field': 'raw'}),
# '/web/image/<int:id>/<int:width>x<int:height>'
("/web/image/123/100x100", {'model': 'ir.attachment', 'id': 123, 'field': 'raw'}),
# '/web/image/<int:id>/<int:width>x<int:height>/<string:filename>'
("/web/image/123/100x100/image_128", {'model': 'ir.attachment', 'id': 123, 'field': 'raw'}),
# '/web/image/<int:id>-<string:unique>'
("/web/image/123-abc", {'model': 'ir.attachment', 'id': 123, 'field': 'raw'}),
# '/web/image/<int:id>-<string:unique>/<string:filename>'
("/web/image/123-abc/image_128", {'model': 'ir.attachment', 'id': 123, 'field': 'raw'}),
# '/web/image/<int:id>-<string:unique>/<int:width>x<int:height>'
("/web/image/123-abc/100x100", {'model': 'ir.attachment', 'id': 123, 'field': 'raw'}),
# '/web/image/<int:id>-<string:unique>/<int:width>x<int:height>/<string:filename>'
("/web/image/123-abc/100x100/image_128", {'model': 'ir.attachment', 'id': 123, 'field': 'raw'}),
]
for path, expected in cases:
args = _retrieve_record_args_from_path(path)
for key, val in expected.items():
self.assertEqual(args.get(key), val, f"Failed for {path} at key {key}. Got {args}")
def test_retrieve_image_parts_from_file(self):
# Mocking file_open and mimetypes to isolate filesystem dependencies
with patch('odoo.addons.ai.utils.ai_image_tools.file_open', mock_open(read_data=PNG_RAW)), \
patch('mimetypes.guess_type', return_value=('image/png', None)):
parts = _retrieve_image_parts_from_file("/ai/static/src/img/test.png")
self.assertEqual(len(parts), 1)
self.assertEqual(parts[0]['type'], 'inline_data')
self.assertEqual(parts[0]['mimetype'], 'image/png')
self.assertEqual(parts[0]['data'], base64.b64encode(PNG_RAW).decode())
self.assertEqual(parts[0]['metadata']['image_path'], "/ai/static/src/img/test.png")
def test_retrieve_image_data_from_attachment(self):
attachment = self.env['ir.attachment'].create({
'name': 'test.png',
'raw': PNG_RAW,
'mimetype': 'image/png',
'store_fname': False,
})
data = retrieve_image_data_from_record(attachment, 'raw')
self.assertEqual(data['content'], PNG_RAW)
self.assertEqual(data['mimetype'], 'image/png')
def test_retrieve_image_data_from_attachment_external_url(self):
"""Test retrieval of data from an attachment withURL. The retrieved data is actually an image."""
attachment = self.env['ir.attachment'].create({
'name': 'test.png',
'type': 'url',
'url': 'https://example.com/image.png',
'mimetype': 'image/png',
})
mock_response = MagicMock()
mock_response.content = b"external content"
with patch('requests.request', return_value=mock_response), patch('odoo.addons.ai.utils.ai_image_tools.ImageProcess'):
data = retrieve_image_data_from_record(attachment, 'raw')
self.assertEqual(data['content'], b"external content")
def test_attachment_external_url_not_image(self):
"""Test retrieval of data from an attachment withURL. The retrieved data is not an image."""
attachment = self.env['ir.attachment'].create({
'name': 'test.png',
'type': 'url',
'url': 'https://example.com/image.png',
'mimetype': 'image/png',
})
mock_response = MagicMock()
mock_response.content = b"external content"
with patch('requests.request', return_value=mock_response):
data = retrieve_image_data_from_record(attachment, 'raw')
self.assertEqual(data['content'], b"")
self.assertEqual(data['mimetype'], "application/x-empty")
def test_no_crash_on_non_existent_image_field(self):
"""Retrieving an image from a field that doesn't exist on the model shouldn't crash."""
record = self.env['res.partner.category'].create({'name': 'Test Category'})
self.assertNotIn('image_1024', record._fields)
image_src = _retrieve_image_src_and_mimetype_from_record(record, 'image_1024')
self.assertEqual(image_src, {'data': b'', 'mimetype': 'application/x-empty'})
data = retrieve_image_data_from_record(record, 'image_1024')
self.assertEqual(data['content'], b'')
self.assertEqual(data['mimetype'], 'application/x-empty')
def test_retrieve_image_parts_from_path(self):
# Case 1: image_path represents a file from an odoo module (an addon)
image_path = "/ai/static/description/icon.png"
with file_open(image_path[1:], 'rb') as f:
content = f.read()
parts = retrieve_image_parts_from_path(self.env, image_path)
self.assertEqual(len(parts), 1)
self.assertEqual(parts[0]['type'], 'inline_data')
self.assertEqual(parts[0]['mimetype'], 'image/png')
self.assertEqual(parts[0]['metadata']['image_path'], image_path)
self.assertEqual(parts[0]['data'], base64.b64encode(content).decode())
# Case 2: Database record URL
attachment = self.env['ir.attachment'].create({
'name': 'test.png',
'raw': PNG_RAW,
'mimetype': 'image/png',
})
image_path = f"/web/image/ir.attachment/{attachment.id}/raw"
parts = retrieve_image_parts_from_path(self.env, image_path)
self.assertEqual(len(parts), 1)
self.assertEqual(parts[0]['type'], 'inline_data')
self.assertEqual(parts[0]['mimetype'], 'image/png')
self.assertEqual(parts[0]['metadata']['image_path'], image_path)
self.assertEqual(parts[0]['data'], base64.b64encode(PNG_RAW).decode())
def test_retrieve_image_parts_from_path_access(self):
attachment = self.env['ir.attachment'].create({
'name': 'secret.png',
'raw': PNG_RAW,
'mimetype': 'image/png',
})
image_path = f"/web/image/ir.attachment/{attachment.id}/raw"
restricted_user = self.env['res.users'].create({
'name': 'Restricted User',
'login': 'restricted_user',
})
with self.with_user(restricted_user.login):
with self.assertRaises(AccessError):
retrieve_image_parts_from_path(self.env, image_path)
parts = retrieve_image_parts_from_path(self.env, image_path)
self.assertEqual(len(parts), 1)
self.assertEqual(parts[0]['data'], base64.b64encode(PNG_RAW).decode())
self.assertEqual(parts[0]['mimetype'], 'image/png')
self.assertEqual(parts[0]['metadata']['image_path'], image_path)

View File

@@ -0,0 +1,40 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import TransactionCase, tagged
from odoo.addons.ai.utils.ai_utils import get_text_from_parts
@tagged("post_install", "-at_install")
class TestAIMessageParts(TransactionCase):
def test_get_text_multiple_strings(self):
parts = [
{'type': 'text', 'text': 'This is the first line'},
{'type': 'text', 'text': 'This is the second line'},
{'type': 'text', 'text': 'This is the third line'},
{'type': 'inline_data', 'mimetype': 'image/png', 'data': 'abc123'},
{'type': 'inline_data', 'mimetype': 'application/pdf', 'data': 'xyz456'},
]
self.assertEqual(get_text_from_parts(parts), 'This is the first line\nThis is the second line\nThis is the third line')
def test_get_text_empty(self):
parts = [
{'type': 'inline_data', 'mimetype': 'image/png', 'data': 'abc123'},
{'type': 'inline_data', 'mimetype': 'application/pdf', 'data': 'xyz456'},
]
self.assertEqual(get_text_from_parts(parts), '')
def test_get_text_single_string(self):
parts = [
{'type': 'text', 'text': 'This is the first line'},
]
self.assertEqual(get_text_from_parts(parts), 'This is the first line')
def test_get_text_single_non_string(self):
parts = [
{'type': 'text', 'text': ['This is the first line', 'This is the second line']},
]
self.assertEqual(get_text_from_parts(parts), ['This is the first line', 'This is the second line'])
parts = [
{'type': 'text', 'text': {'a': 1, 'b': 2}},
]
self.assertEqual(get_text_from_parts(parts), {'a': 1, 'b': 2})

View File

@@ -0,0 +1,43 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from freezegun import freeze_time
from odoo.addons.ai.tests.common import TestAICommon
from odoo.tests import HttpCase, tagged
from odoo.tests.common import users
@tagged("post_install", "-at_install")
class TestAIMethods(HttpCase, TestAICommon):
@freeze_time('2025-01-20 12:34:56')
@users('user_internal')
def test_get_direct_response(self):
"""Test the direct-response endpoint and its completion request."""
agent = self.agent.with_env(self.env).sudo()
self.env['ai.composer'].sudo().search(
[('focused_model_id', '=', False), ('interface_key', '=', 'systray_ai_button')]
).ai_agent_id = agent.id
self.authenticate(self.user_internal.login, self.user_internal.login)
mocked_response = self.mock_text_response("direct response")
with self.mock_completion_request([mocked_response]) as mock_request:
res = self.make_jsonrpc_request(
"/ai/get_direct_response",
{
"interface_key": "systray_ai_button",
"prompt": "<p>Test prompt</p>",
}
)
messages = [{
'role': 'user',
'content': [{'type': 'text', 'text': '<p>Test prompt</p>'}],
}]
mock_request.assert_called_once_with(
messages,
agent._get_instructions(),
self._prepare_default_tools(agent),
schema=None,
usage='agent:custom',
)
self.assertEqual(res, 'direct response')

View File

@@ -0,0 +1,73 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.ai.tests.common import mock_iap_results, TestAICommon
from odoo.tests import HttpCase, tagged
@tagged("post_install", "-at_install")
class TestAIOpenMenuGraphTour(HttpCase, TestAICommon):
@classmethod
def setUpClass(cls):
super().setUpClass()
# Minimal graph arch on res.partner to match what the mocked LLM
# will ask for (`create_date` at `month` interval).
cls.test_graph_view = cls.env['ir.ui.view'].create({
'name': 'res.partner.ai.test.graph',
'model': 'res.partner',
'type': 'graph',
'arch': """
<graph>
<field name="create_date" type="row" interval="month"/>
</graph>
""",
})
# _ai_tool_open_menu_graph requires "graph" in action.views.
cls.test_action = cls.env['ir.actions.act_window'].create({
'name': 'AI Test Contacts',
'res_model': 'res.partner',
'view_mode': 'graph',
})
# Parent under the Discuss app's Configuration menu.
cls.test_menu = cls.env['ir.ui.menu'].create({
'name': 'AI Test Contacts',
'parent_id': cls.env.ref('mail.menu_configuration').id,
'action': f'ir.actions.act_window,{cls.test_action.id}',
'sequence': 99,
})
# Retarget systray_ai_button to our test agent.
cls.env['ai.composer'].sudo().search([
('focused_model_id', '=', False),
('interface_key', '=', 'systray_ai_button'),
]).ai_agent_id = cls.agent.id
cls.open_menu_graph_tool = cls.env.ref('ai.ir_actions_server_open_menu_graph')
def test_open_menu_graph_applies_date_groupby(self):
tool_args = {
'menu_id': self.test_menu.id,
'model_name': 'res.partner',
'selected_filters': [],
'selected_groupbys': [
{'field_name': 'create_date', 'intervals': ['month']},
],
'measure': '__count',
'mode': 'bar',
'order': 'ASC',
'search': [],
}
iap_results = [
self.mock_tool_response(self.open_menu_graph_tool, args=tool_args),
self.mock_text_response("Here is your graph"),
]
# open_menu_graph is skill-gated in production; expose it as a default tool here.
with self.mock_default_tools(self.open_menu_graph_tool), \
mock_iap_results(self.env, iap_results):
self.start_tour(
"/odoo",
"ai_open_menu_graph_tour",
login="admin",
)

View File

@@ -0,0 +1,115 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
from markupsafe import Markup
from odoo.addons.ai.tests.common import TestAICommon
from odoo.tests import tagged, users
@tagged("post_install", "-at_install")
class TestAIPromptButton(TestAICommon):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.composer_id = cls.env['ai.composer'].create({
'name': 'test composer',
'interface_key': 'chatter_ai_button',
'focused_model_id': cls.env.ref('ai.model_ai_agent').id,
})
cls.rendering_record = cls.env['ai.agent'].create({
'name': 'Test record',
})
@users('user_internal')
def test_button_without_prompt(self):
"""
When the prompt field of the prompt button is empty, the name field is used as the prompt.
"""
button = self.env['ai.prompt.button'].sudo().create({
'name': 'Button without prompt',
'composer_id': self.composer_id.id,
})
message_parts = button.sudo(False)._render_prompt(self.rendering_record.id)
self.assertEqual(message_parts, [{'type': 'text', 'text': 'Button without prompt'}])
self.composer_id.focused_model_id = self.env.ref('ai.model_ai_agent').id
button = self.env['ai.prompt.button'].sudo().create({
'name': 'Button with empty prompt',
'composer_id': self.composer_id.id,
'prompt': Markup('<p></p>')
})
message_parts = button.sudo(False)._render_prompt(self.rendering_record.id)
self.assertEqual(message_parts, [{'type': 'text', 'text': 'Button with empty prompt'}])
@users('user_internal')
def test_render_basic_prompt(self):
"""
The prompt field of the button has a value, but it is simple text and doesn't contain any field references.
"""
self.composer_id.focused_model_id = self.env.ref("ai.model_ai_agent").id
button = self.env['ai.prompt.button'].sudo().create({
'name': 'Basic Prompt',
'prompt': '<p>This is a basic prompt</p>',
'composer_id': self.composer_id.id,
})
message_parts = button.sudo(False)._render_prompt(self.rendering_record.id)
self.assertEqual(len(message_parts), 1)
self.assertEqual(message_parts[0]['type'], 'text')
self.assertIn('This is a basic prompt', message_parts[0]['text'])
self.assertIn('# field values\n{}', message_parts[0]['text'])
@users('user_internal')
def test_render_prompt_with_fields(self):
"""
The prompt field of the button contains field references.
"""
self.composer_id.focused_model_id = self.env.ref('ai.model_ai_agent').id
# Use the specific span format required by parse_ai_prompt_values
button = self.env['ai.prompt.button'].sudo().create({
'name': 'Field Prompt',
'prompt': """
<div>
<p>Agent name: <span data-ai-field="name">Name</span></p>
<p>Agent image: <span data-ai-field="image_128">Image</span></p>
<p>Partner name: <span data-ai-field="partner_id.name">Partner Name</span></p>
</div>
""",
'composer_id': self.composer_id.id,
})
message_parts = button.sudo(False)._render_prompt(self.rendering_record.id)
self.assertEqual(len(message_parts), 2)
text_part = message_parts[0]
rendered_prompt_content = text_part['text']
self.assertIn('Agent name: {{name}}', rendered_prompt_content)
self.assertIn('Agent image: {{image_128}}', rendered_prompt_content)
self.assertIn('Partner name: {{partner_id.name}}', rendered_prompt_content)
agent_image_checksum = self.env['ir.attachment']._compute_checksum(self.rendering_record.image_128)
agent_partner_id = self.rendering_record.partner_id.id
field_values = {
'ai.agent': [{
'id': self.rendering_record.id,
'name': 'Test record',
'image_128': f'<file_{agent_image_checksum}/>',
'partner_id': {
'model': 'res.partner',
'ids': [agent_partner_id]
}
}],
'res.partner': [{
'id': agent_partner_id,
'name': 'Test record'
}]
}
prompt_field_values = rendered_prompt_content.split('# field values\n')[1]
self.assertEqual(field_values, json.loads(prompt_field_values))
inline_data_part = message_parts[1]
self.assertEqual(inline_data_part['type'], 'inline_data')
self.assertEqual(inline_data_part['mimetype'], 'image/png')
self.assertEqual(inline_data_part['data'], self.rendering_record.image_128.to_base64())
self.assertEqual(inline_data_part['metadata']['image_path'], f'/web/image/ai.agent/{self.rendering_record.id}/image_128')

1220
ai/tests/test_ai_session.py Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,61 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.base.tests.test_ir_cron import CronMixinCase
from odoo.tests import HttpCase, tagged
@tagged("post_install", "-at_install")
class TestAIUrlScraperController(HttpCase, CronMixinCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.agent = cls.env["ai.agent"].create({
"name": "Agent URL Source Controller Tests",
})
def _create_batch(self, batch_uuid, state="submitted"):
page = self.env["ai.web.page"].create({
"url": "https://example.com/controller-test",
})
self.env["ai.agent.source"].create({
"name": "Controller Test Source",
"agent_id": self.agent.id,
"type": "url",
"web_page_id": page.id,
})
batch = self.env["ai.web.scraper.batch"].create({
"uuid": batch_uuid,
"state": state,
"url_payloads": page._get_scraper_urls_params(),
"callback_model": "ai.web.page",
})
page.batch_id = batch.id
return batch
def test_callback_triggers_cron_for_pending_batch(self):
batch = self._create_batch("batch-callback-ok")
cron_id = self.env.ref("ai.ir_cron_run_web_scraper").id
with self.capture_triggers(cron_id) as captured_triggers:
response = self.url_open(
f"/ai/url_scraper_result_ready/{batch.uuid}",
method="POST",
)
self.assertEqual(response.status_code, 200)
self.assertTrue(captured_triggers.records)
def test_callback_returns_404_for_unknown_batch(self):
response = self.url_open(
"/ai/url_scraper_result_ready/unknown-batch-uuid",
method="POST",
)
self.assertEqual(response.status_code, 404)
def test_callback_returns_404_when_batch_not_submitted(self):
batch = self._create_batch("batch-callback-todo", state="to_submit")
response = self.url_open(
f"/ai/url_scraper_result_ready/{batch.uuid}",
method="POST",
)
self.assertEqual(response.status_code, 404)

View File

@@ -0,0 +1,424 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
from datetime import timedelta
from unittest.mock import patch
from requests.exceptions import ConnectionError as RequestsConnectionError, Timeout as RequestsTimeout
from odoo import fields
from odoo.tests import tagged
from odoo.tests.common import TransactionCase
from odoo.tools import mute_logger
from odoo.addons.ai.models.ai_web_scraper_batch import AIWebScraperBatch
from odoo.addons.base.tests.test_ir_cron import CronMixinCase
_CALL_SCRAPER = "odoo.addons.ai.models.ai_web_scraper_batch.AIWebScraperBatch._call_scraper"
_MAX_SCRAPER_CALLS = "odoo.addons.ai.models.ai_web_scraper_batch.AIWebScraperBatch._CRON_MAX_SCRAPER_CALLS"
def _patch_call_scraper(**kwargs):
"""Patch ``_call_scraper`` with a mock that cannot pass for an ``@api.ondelete`` hook.
A bare ``MagicMock`` answers ``hasattr(mock, "_ondelete")`` with True, so
``BaseModel._ondelete_methods`` picks the patched method up and calls it with the recordset
on every ``unlink()`` -- inflating the call count (and memoizing the mock on the registry
class). Speccing the mock on the real function removes that phantom attribute.
"""
return patch(_CALL_SCRAPER, spec=AIWebScraperBatch._call_scraper, **kwargs)
@tagged("post_install", "-at_install")
class TestAIWebPage(TransactionCase, CronMixinCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.agent = cls.env["ai.agent"].create({
"name": "Agent URL Source Tests",
})
def setUp(self):
super().setUp()
# These tests call the cron method directly, outside of an actual cron job context,
# so _commit_progress() would otherwise try to really commit the (test) transaction.
commit_progress_patcher = patch("odoo.addons.base.models.ir_cron.IrCron._commit_progress")
commit_progress_patcher.start()
self.addCleanup(commit_progress_patcher.stop)
def _create_url_source(self, name, url, status="processing", is_active=False, content=None):
page = self.env["ai.web.page"].search([("url", "=", url)]) or self.env["ai.web.page"].create({"url": url})
source = self.env["ai.agent.source"].create({
"name": name,
"agent_id": self.agent.id,
"type": "url",
"web_page_id": page.id,
})
if content is not None:
page.write({"content": content})
source.write({
"status": status,
"is_active": is_active,
})
return source
def _create_batch(self, sources, uuid=False, state="submitted", submitted_on=None, timeout_at=None):
pages = sources.web_page_id
batch = self.env["ai.web.scraper.batch"].create({
"uuid": uuid,
"state": state,
"submitted_on": submitted_on,
"timeout_at": timeout_at,
"url_payloads": pages._get_scraper_urls_params(),
"callback_model": "ai.web.page",
})
pages.batch_id = batch.id
return batch
def test_reprocess_resets_scraper_tracking_and_triggers_scrape_cron(self):
url = "https://example.com/article"
source_a = self._create_url_source(
"Source A", url, status="indexed", is_active=True, content="<p>Old content</p>",
)
source_b = self._create_url_source(
"Source B", url, status="indexed", is_active=True, content="<p>Old content</p>",
)
old_batch = self._create_batch(source_a | source_b, uuid="old-batch")
scraper_cron = self.env.ref("ai.ir_cron_run_web_scraper").id
with self.capture_triggers(scraper_cron) as captured_triggers, \
patch("odoo.addons.ai.models.ai_web_page.AIWebPage._get_name", return_value="Updated title"):
source_a.action_reprocess_index()
source_a.invalidate_recordset()
source_b.invalidate_recordset()
self.assertEqual(source_a.status, "processing")
self.assertEqual(source_b.status, "processing")
self.assertEqual(source_a.name, "Updated title")
self.assertEqual(source_b.name, "Updated title")
# The pages have been detached from the old batch and re-enqueued in a fresh one.
self.assertNotEqual(source_a.web_page_id.batch_id, old_batch)
self.assertNotEqual(source_b.web_page_id.batch_id, old_batch)
self.assertEqual(source_a.web_page_id.batch_id.state, "to_submit")
self.assertTrue(captured_triggers.records)
def test_scraping_cron_submits_pending_url_sources(self):
external_url = "https://external.example/a"
source_a = self._create_url_source("Source A", external_url)
source_a.web_page_id._submit_to_scraper()
with _patch_call_scraper(return_value={
"status": "accepted",
"uuid": "batch-submit",
}) as call_scraper:
self.env["ai.web.scraper.batch"]._cron_run_web_scraper()
call_scraper.assert_called_once_with(
"/website_scraper/url_sources/1.0/submit_batch",
{
"urls": [
{
"url": external_url,
"check_robots_txt": True,
"fetch_image_urls": False,
"take_screenshot": False,
},
],
"db_url": self.env["ir.config_parameter"].sudo().get_base_url(),
},
)
batch = source_a.web_page_id.batch_id
self.assertEqual(batch.uuid, "batch-submit")
self.assertEqual(batch.state, "submitted")
self.assertTrue(batch.submitted_on)
def test_enqueue_adds_media_options_and_preserves_url_specific_values(self):
batch = self.env["ai.web.scraper.batch"]._enqueue(
[
{"url": "https://example.com/default"},
{
"url": "https://example.com/override",
"fetch_image_urls": False,
"take_screenshot": True,
},
],
"ai.agent.source.url",
fetch_image_urls=True,
take_screenshot=False,
)
self.assertEqual(batch.url_payloads, [
{
"url": "https://example.com/default",
"fetch_image_urls": True,
"take_screenshot": False,
},
{
"url": "https://example.com/override",
"fetch_image_urls": False,
"take_screenshot": True,
},
])
def test_enqueue_with_timeout_schedules_scraper_cron_at_deadline(self):
scraper_cron = self.env.ref("ai.ir_cron_run_web_scraper").id
with self.capture_triggers(scraper_cron) as captured_triggers:
batch = self.env["ai.web.scraper.batch"]._enqueue(
[{"url": "https://example.com/timeout"}],
"ai.web.page",
timeout_seconds=600,
)
self.assertTrue(batch.timeout_at)
self.assertIn(batch.timeout_at, captured_triggers.records.mapped("call_at"))
def test_poll_keeps_requested_media_in_batch_result(self):
url = "https://example.com/media"
batch = self.env["ai.web.scraper.batch"].create({
"uuid": "batch-media",
"state": "submitted",
"url_payloads": [{
"url": url,
"fetch_image_urls": True,
"take_screenshot": True,
}],
"callback_model": "ai.agent.source.url",
})
scraper_result = {
"status": "success",
"pages": {
url: {
"failed": False,
"payload": json.dumps({
"text": "Page content",
"images": [{"src": "https://example.com/image.png", "kind": "img"}],
"screenshot_url": "data:image/png;base64,c2NyZWVuc2hvdA==",
}),
},
},
}
with patch(_CALL_SCRAPER, return_value=scraper_result):
batch._poll()
self.assertEqual(batch.state, "done")
payload = json.loads(batch.result["pages"][url]["payload"])
self.assertEqual(payload["images"], [{"src": "https://example.com/image.png", "kind": "img"}])
self.assertEqual(payload["screenshot_url"], "data:image/png;base64,c2NyZWVuc2hvdA==")
def test_scraping_cron_processes_successes_without_restaging_failures(self):
success_url = "https://example.com/success"
failed_url = "https://example.com/failure"
success_source = self._create_url_source("Success", success_url)
failed_source = self._create_url_source("Failure", failed_url, content="<p>Old</p>")
batch = self._create_batch(success_source | failed_source, uuid="batch-mixed")
scraper_result = {
"status": "success",
"pages": {
success_url: {
"failed": False,
"payload": json.dumps({"text": "<p>Fresh content</p>"}),
},
failed_url: {
"failed": True,
"reason": "Fetch failed",
},
},
}
ai_generate_embedding_cron = self.env.ref("ai.ir_cron_generate_embedding").id
with self.capture_triggers(ai_generate_embedding_cron) as captured_triggers_embedding, \
_patch_call_scraper(return_value=scraper_result) as call_scraper:
self.env["ai.web.scraper.batch"]._cron_run_web_scraper()
success_source.invalidate_recordset()
failed_source.invalidate_recordset()
self.assertEqual(success_source.web_page_id.content, "<p>Fresh content</p>")
self.assertEqual(success_source.status, "processing")
self.assertEqual(failed_source.status, "failed")
self.assertEqual(failed_source.error_details, "Fetch failed")
self.assertTrue(captured_triggers_embedding.records)
# Regression check: a fetched batch must not be resubmitted to the scraper within the
# same cron tick (only the fetch call happens; the cron never re-scans sources).
call_scraper.assert_called_once()
# The batch is discarded once dispatched to its consumer.
self.assertFalse(batch.exists())
def test_scraping_cron_unlinks_embeddings_when_content_changes(self):
url = "https://example.com/refresh"
source = self._create_url_source(
"Refresh Needed", url, content="<p>Old content</p>",
)
embedding = self.env["ai.embedding"].create({
"res_model": "ai.web.page",
"res_id": source.web_page_id.id,
"content": "chunk content",
"embedding_model": source.agent_id.embedding_model,
})
self._create_batch(source, uuid="batch-refresh")
updated_content = "<p>Updated content</p>"
scraper_result = {
"status": "success",
"pages": {
url: {
"failed": False,
"payload": json.dumps({"text": updated_content}),
},
},
}
ai_generate_embedding_cron = self.env.ref("ai.ir_cron_generate_embedding").id
with self.capture_triggers(ai_generate_embedding_cron) as captured_triggers_embedding, \
_patch_call_scraper(return_value=scraper_result):
self.env["ai.web.scraper.batch"]._cron_run_web_scraper()
source.invalidate_recordset()
self.assertEqual(source.web_page_id.content, updated_content)
self.assertEqual(source.status, "processing")
self.assertTrue(captured_triggers_embedding.records)
self.assertFalse(self.env["ai.embedding"].browse(embedding.id).exists())
def test_scraping_cron_marks_source_failed_on_invalid_payload(self):
url = "https://example.com/invalid-payload"
source = self._create_url_source("Invalid Payload", url)
self._create_batch(source, uuid="batch-invalid-payload")
scraper_result = {
"status": "success",
"pages": {
url: {
"failed": False,
"payload": "{not valid",
},
},
}
ai_generate_embedding_cron = self.env.ref("ai.ir_cron_generate_embedding").id
with self.capture_triggers(ai_generate_embedding_cron) as captured_triggers_embedding, \
_patch_call_scraper(return_value=scraper_result):
self.env["ai.web.scraper.batch"]._cron_run_web_scraper()
source.invalidate_recordset()
self.assertEqual(source.status, "failed")
self.assertEqual(source.error_details, "Failed to process the content of this URL.")
self.assertFalse(captured_triggers_embedding.records)
def test_scraping_cron_marks_batch_failed_after_configured_timeout(self):
source = self._create_url_source("Configured Timeout", "https://example.com/configured-timeout")
batch = self._create_batch(
source,
uuid="batch-configured-timeout",
submitted_on=fields.Datetime.now(),
timeout_at=fields.Datetime.now() - timedelta(seconds=1),
)
with patch(_CALL_SCRAPER, return_value={"status": "error_still_processing"}):
self.env["ai.web.scraper.batch"]._cron_run_web_scraper()
source.invalidate_recordset()
self.assertEqual(source.status, "failed")
self.assertFalse(source.is_active)
self.assertEqual(source.error_details, "Web scraping did not finish before the timeout.")
self.assertFalse(batch.exists())
def test_scraping_cron_marks_batch_failed_after_max_fetch_wait(self):
source = self._create_url_source("Timeout", "https://example.com/timeout")
max_wait = self.env["ai.web.scraper.batch"]._MAX_FETCH_WAIT
self._create_batch(
source,
uuid="batch-timeout",
submitted_on=fields.Datetime.now() - max_wait - timedelta(hours=1),
)
with _patch_call_scraper(return_value={
"status": "error_still_processing",
}):
self.env["ai.web.scraper.batch"]._cron_run_web_scraper()
source.invalidate_recordset()
self.assertEqual(source.status, "failed")
self.assertEqual(source.error_details, "This URL took too long to process and timed out after 24 hours.")
# Terminal batch is dispatched and discarded, detaching the page.
self.assertFalse(source.web_page_id.batch_id)
def test_repeated_fetch_attempts_do_not_prematurely_fail_batch(self):
"""Regression test for attempt poisoning: a batch must not fail just because it was
polled many times by cron runs triggered from unrelated batches finishing. Only
elapsed time since submission should matter."""
source = self._create_url_source("Slow", "https://example.com/slow")
batch = self._create_batch(source, uuid="batch-slow", submitted_on=fields.Datetime.now())
with _patch_call_scraper(return_value={
"status": "error_still_processing",
}):
for _ in range(25): # more than the old count-based attempt limit (20)
self.env["ai.web.scraper.batch"]._cron_run_web_scraper()
source.invalidate_recordset()
self.assertEqual(source.status, "processing")
self.assertEqual(batch.state, "submitted")
@mute_logger("odoo.addons.ai.models.ai_web_scraper_batch")
def test_submit_batch_transient_error_is_retried_not_failed(self):
source = self._create_url_source("Retry Submit", "https://example.com/retry-submit")
source.web_page_id._submit_to_scraper()
with _patch_call_scraper(side_effect=RequestsConnectionError("connection dropped")):
self.env["ai.web.scraper.batch"]._cron_run_web_scraper()
source.invalidate_recordset()
self.assertEqual(source.status, "processing")
self.assertFalse(source.web_page_id.batch_id.uuid)
self.assertEqual(source.web_page_id.batch_id.state, "to_submit")
@mute_logger("odoo.addons.ai.models.ai_web_scraper_batch")
def test_fetch_batch_transient_error_is_retried_not_failed(self):
source = self._create_url_source("Retry Fetch", "https://example.com/retry-fetch")
batch = self._create_batch(source, uuid="batch-retry-fetch", submitted_on=fields.Datetime.now())
with _patch_call_scraper(side_effect=RequestsTimeout("timed out")):
self.env["ai.web.scraper.batch"]._cron_run_web_scraper()
source.invalidate_recordset()
self.assertEqual(source.status, "processing")
self.assertEqual(batch.state, "submitted")
def test_cron_retriggers_when_backlog_exceeds_call_cap(self):
for i in range(3):
self._create_url_source(
f"Backlog {i}", f"https://example.com/backlog-{i}",
).web_page_id._submit_to_scraper()
scraper_cron = self.env.ref("ai.ir_cron_run_web_scraper").id
with self.capture_triggers(scraper_cron) as captured_triggers, \
patch(_MAX_SCRAPER_CALLS, 2), \
_patch_call_scraper(return_value={"status": "accepted", "uuid": "batch-backlog"}):
self.env["ai.web.scraper.batch"]._cron_run_web_scraper()
self.assertTrue(captured_triggers.records)
def test_cron_retriggers_when_scraper_call_exhausts_time_budget(self):
scraper_cron = self.env.ref("ai.ir_cron_run_web_scraper").id
for state, result, expected_state in (
("submitted", {"status": "success", "pages": {}}, "done"),
("to_submit", {"status": "accepted", "uuid": "batch-submit"}, "submitted"),
):
with self.subTest(state=state):
batches = self.env["ai.web.scraper.batch"].create([
{"state": state, "callback_model": "ai.web.page"} for _ in range(2)
])
with (
self.capture_triggers(scraper_cron) as captured_triggers,
patch(_CALL_SCRAPER, return_value=result) as call_scraper,
patch("odoo.addons.base.models.ir_cron.IrCron._commit_progress", return_value=0),
):
self.env["ai.web.scraper.batch"]._cron_run_web_scraper()
call_scraper.assert_called_once()
self.assertEqual(batches[0].state, expected_state)
self.assertEqual(batches[1].state, state)
self.assertTrue(captured_triggers.records)
batches.unlink()

View File

@@ -0,0 +1,127 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import timedelta
from unittest.mock import patch
from odoo import fields
from odoo.tests import TransactionCase, tagged
from odoo.tools import mute_logger
@tagged('post_install', '-at_install')
class TestAIWebScraperBatch(TransactionCase):
@mute_logger('odoo.addons.ai.models.ai_web_scraper_batch')
def test_dispatch_rolls_back_failed_callback_and_keeps_other_commits(self):
with self.registry_test_mode(), self.registry.cursor() as cr:
env = self.env(cr=cr)
partners = env['res.partner'].create([
{'name': name} for name in ('Before', 'Failure', 'After')
])
batches = env['ai.web.scraper.batch'].create([
{'state': 'done', 'callback_model': 'ai.web.page', 'uuid': str(partner.id)}
for partner in partners
])
visited = []
def callback(pages, batch):
visited.append(batch.id)
partner = pages.env['res.partner'].browse(int(batch.uuid))
partner.name = 'Processed'
partner.flush_recordset(['name'])
if batch == batches[1]:
pages.env.cr.execute('SELECT 1 / 0', log_exceptions=False)
with patch.object(self.registry['ai.web.page'], '_web_scraper_result_ready', callback):
env['ai.web.scraper.batch']._cron_run_web_scraper()
self.assertEqual(visited, batches.ids)
self.assertEqual(batches.exists(), batches[1])
self.assertEqual(partners.mapped('name'), ['Processed', 'Failure', 'Processed'])
# A later rollback must not undo either successful callback.
cr.rollback()
self.assertEqual(batches.exists(), batches[1])
self.assertEqual(partners.mapped('name'), ['Processed', 'Failure', 'Processed'])
@mute_logger('odoo.addons.ai.models.ai_web_scraper_batch')
def test_dispatch_preserves_timeout_when_first_callback_fails(self):
with self.registry_test_mode(), self.registry.cursor() as cr:
env = self.env(cr=cr)
batch = env['ai.web.scraper.batch'].create({
'state': 'submitted',
'callback_model': 'ai.web.page',
'timeout_at': fields.Datetime.now() - timedelta(seconds=1),
})
with (
patch.object(self.registry['ai.web.scraper.batch'], '_poll'),
patch.object(self.registry['ai.web.page'], '_web_scraper_result_ready', side_effect=ValueError('Failed')),
):
env['ai.web.scraper.batch']._cron_run_web_scraper()
self.assertTrue(batch.exists())
self.assertEqual(batch.state, 'failed')
self.assertEqual(batch.error, 'Web scraping did not finish before the timeout.')
@mute_logger('odoo.addons.ai.models.ai_web_scraper_batch')
def test_dispatch_rolls_back_when_flush_fails(self):
with self.registry_test_mode(), self.registry.cursor() as cr:
env = self.env(cr=cr)
batch = env['ai.web.scraper.batch'].create({
'state': 'done', 'callback_model': 'ai.web.page',
})
partner = env['res.partner'].create({'name': 'Before'})
def fail():
raise ValueError('Flush failed')
def callback(pages, batch):
partner.name = 'Processed'
pages.env.cr.precommit.add(fail)
with patch.object(self.registry['ai.web.page'], '_web_scraper_result_ready', callback):
env['ai.web.scraper.batch']._cron_run_web_scraper()
self.assertTrue(batch.exists(), 'The deletion must roll back together with callback writes')
self.assertEqual(partner.name, 'Before')
def test_dispatch_stops_when_cron_time_is_exhausted(self):
with self.registry_test_mode(), self.registry.cursor() as cr:
env = self.env(cr=cr)
batches = env['ai.web.scraper.batch'].create([
{'state': 'done', 'callback_model': 'ai.web.page'} for _ in range(2)
])
commit_progress = self.registry['ir.cron']._commit_progress
def stop_after_batch(cron, processed=0, **kwargs):
remaining_time = commit_progress(cron, processed, **kwargs)
return 0 if processed else remaining_time
with patch.object(self.registry['ir.cron'], '_commit_progress', stop_after_batch):
env['ai.web.scraper.batch']._cron_run_web_scraper()
self.assertEqual(batches.exists(), batches[1])
cr.rollback()
self.assertEqual(batches.exists(), batches[1])
@mute_logger('odoo.addons.ai.models.ai_web_scraper_batch')
def test_dispatch_stops_after_failure_when_cron_time_is_exhausted(self):
with self.registry_test_mode(), self.registry.cursor() as cr:
env = self.env(cr=cr)
batches = env['ai.web.scraper.batch'].create([
{'state': 'done', 'callback_model': 'ai.web.page'} for _ in range(2)
])
commit_progress = self.registry['ir.cron']._commit_progress
def stop_after_failure(cron, processed=0, **kwargs):
remaining_time = commit_progress(cron, processed, **kwargs)
return 0 if callback.called else remaining_time
with (
patch.object(self.registry['ai.web.page'], '_web_scraper_result_ready', side_effect=ValueError('Failed')) as callback,
patch.object(self.registry['ir.cron'], '_commit_progress', stop_after_failure),
):
env['ai.web.scraper.batch']._cron_run_web_scraper()
callback.assert_called_once()
self.assertEqual(batches.exists(), batches)

1
ai/tests/test_data.py Normal file

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,69 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import Command
from odoo.exceptions import AccessError
from odoo.tests import tagged, HttpCase, users
from .common import TestAICommon
@tagged('-at_install', 'post_install')
class TestDiscussChannel(HttpCase, TestAICommon):
def test_create_ai_chat(self):
agent = self.env["ai.agent"].create({"name": "Odoo AI"})
channel = agent._create_ai_chat_channel()
self.assertTrue(channel)
self.assertTrue(channel.is_member, "Current user should be member of the created channel")
self.assertEqual("ai_chat", channel.channel_type, "AI channel should be of 'ai_chat' type")
self.assertEqual(channel.name, "", "Channel name should originally be empty - will be filled in later")
self.assertEqual(agent.partner_id.name, channel.display_name, "Channel's display_name should be the agent's name")
self.assertEqual(agent, channel.sudo().ai_agent_id, "ai_agent_id should be set on the newly created ai_chat channel")
@users('user_internal')
def test_delete_ai_chat_only_deletes_channel_with_proper_types(self):
# Sudo => creating an agent requires creating a 'res.partner' to be used for chat channels.
# This is only allowed for admins
agent = self.env["ai.agent"].sudo().create({"name": "Odoo AI"})
ai_chat_channel = agent._create_ai_chat_channel()
regular_channel = self.env["discuss.channel"].create({
"channel_member_ids": [
Command.create(
{
"partner_id": self.env.user.partner_id.id,
}
),
],
"channel_type": "chat",
"name": "Non AI chat"
})
with self.assertRaises(AccessError):
regular_channel.unlink()
self.assertTrue(regular_channel.exists(), "Only channels of type 'ai_chat' should be deleted on close.")
ai_chat_channel.unlink()
self.assertFalse(ai_chat_channel.exists(), "Channel of type 'ai_chat' should be deleted when closed.")
@users('user_internal')
def test_member_can_delete_own_ai_chat(self):
"""A non-admin user should be able to delete their own AI chat channel."""
agent = self.env["ai.agent"].sudo().create({"name": "Odoo AI"})
channel = agent._create_ai_chat_channel()
self.assertIn(self.env.user.partner_id, channel.channel_member_ids.partner_id)
channel.unlink()
self.assertFalse(channel.exists(), "A member should be able to delete their own AI chat.")
@users('user_internal')
def test_non_member_cannot_delete_ai_chat(self):
"""User should only be able to delete their AI chat channels."""
user_admin = self.env.ref('base.user_admin')
agent = self.env['ai.agent'].sudo().create({'name': 'test agent'})
channel = agent.with_user(user_admin)._create_ai_chat_channel('test AI chat')
self.assertIn(user_admin.partner_id, channel.channel_member_ids.partner_id)
self.assertNotIn(self.env.user.partner_id, channel.channel_member_ids.partner_id)
with self.assertRaises(AccessError):
channel.with_user(self.env.user).unlink()
self.assertTrue(channel.exists(), "A non-member should not be able to delete an AI chat.")

View File

@@ -0,0 +1,419 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import re
from odoo.exceptions import ValidationError
from odoo.tests import tagged, TransactionCase
from odoo.addons.ai.utils.tools_schema import validators
@tagged('at_install', '-post_install') # LEGACY at_install
class TestInstanceValidation(TransactionCase):
def validate_instance_with_schema(self, schema, instance, required_parameters=None, error_message=''):
if required_parameters is None:
required_parameters = list(schema.keys())
if error_message:
with self.assertRaisesRegex(ValidationError, re.escape(error_message)):
validators.validate_params_llm_values_with_schema(
instance=instance,
schema=schema,
required_parameters=required_parameters,
env=self.env,
)
else:
return validators.validate_params_llm_values_with_schema(
instance=instance,
schema=schema,
required_parameters=required_parameters,
env=self.env,
)
def test_missing_optional_parameter(self):
'''
Assert that when some parameters are not required and are missing from the LLM response, the validation will succeed.
'''
schema = {
'user_name': {
'type': 'string',
'description': 'the name of the user',
},
'phone_number': {
'type': 'string',
'description': 'the phone number of the user',
},
}
instance = {'user_name': 'Mohamed'}
required_parameters = ['user_name']
instance = self.validate_instance_with_schema(
instance=instance,
schema=schema,
required_parameters=required_parameters,
)
# non required param should have been added
self.assertEqual(instance['phone_number'], None)
def test_missing_required_parameter(self):
'''
Assert that when some parameters are required but are missing from the LLM response, the validation will fail.
'''
schema = {
'user_name': {
'type': 'string',
'description': 'the name of the user',
},
'phone_number': {
'type': 'string',
'description': 'the phone number of the user',
},
}
instance = {'phone_number': '+32123456789'}
required_parameters = ['user_name', 'phone_number']
self.validate_instance_with_schema(
instance=instance,
schema=schema,
required_parameters=required_parameters,
error_message="Could you please provide info about 'user_name' as it is required to process your request",
)
def test_wrong_type_parameter(self):
param_name = 'user_age'
param_type = 'number'
schema = {
param_name: {
'type': param_type,
'description': 'the age of the user',
}
}
instance = {param_name: 'fifteen'}
self.validate_instance_with_schema(
schema=schema,
instance=instance,
error_message=f"The type of the parameter '{param_name}' is incorrect. It should be '{param_type}'."
)
def test_numeric_minimum(self):
optional = self.validate_instance_with_schema(
{'record_id': {'type': 'integer', 'minimum': 1}},
{},
required_parameters=[],
)
self.assertIsNone(optional['record_id'])
for param_type, valid_value in (('integer', 1), ('number', 1.0)):
with self.subTest(param_type=param_type, valid=True):
schema = {
'record_id': {
'type': param_type,
'minimum': 1,
},
}
self.validate_instance_with_schema(schema, {'record_id': valid_value})
with self.subTest(param_type=param_type, valid=False):
self.validate_instance_with_schema(
schema,
{'record_id': 0},
error_message="The value of the parameter 'record_id' must be at least 1.",
)
def test_wrong_pattern_parameter(self):
'''
Assert that when a parameter doesn't follow the expected pattern, the validation will fail.
'''
param_name = 'meeting_date'
# The pattern validates that the date of the form YYYY-mm-dd
param_pattern = r'^20\d{2}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])'
schema = {
param_name: {
'type': 'string',
'description': 'the date of the meeting',
'pattern': param_pattern,
}
}
instance = {param_name: '2025-31-01'}
self.validate_instance_with_schema(
schema=schema,
instance=instance,
error_message=f"The value '{instance[param_name]}' of the parameter '{param_name}' doesn't match the expected pattern '{param_pattern}'."
)
def test_wrong_type_array_item(self):
param_name = 'numbers_to_sum'
schema = {
param_name: {
'type': 'array',
'items': {'type': 'number'},
'description': 'the numbers whose sum is computed',
}
}
instance = {param_name: [15, 20, 'hello']}
self.validate_instance_with_schema(
schema=schema,
instance=instance,
error_message="The type of the parameter 'numbers_to_sum's item' is incorrect. It should be 'number'.",
)
def test_correct_pattern_array_item(self):
'''
Assert that when an array item follows the expected pattern, the validation will succeed.
'''
param_name = 'meeting_date'
# The pattern validates that the date of the form YYYY-mm-dd
param_pattern = r'^20\d{2}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])'
schema = {
param_name: {
'type': 'array',
'items': {'type': 'string'},
'description': 'the date of the meeting',
'pattern': param_pattern,
}
}
instance = {param_name: ['2025-01-31', '2024-05-29']}
self.validate_instance_with_schema(
schema=schema,
instance=instance,
)
def test_wrong_pattern_array_item(self):
'''
Assert that when an array item doesn't follow the expected pattern, the validation will fail.
'''
param_name = 'meeting_date'
# The pattern validates that the date of the form YYYY-mm-dd
param_pattern = r'^20\d{2}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])'
schema = {
param_name: {
'type': 'array',
'items': {'type': 'string', 'pattern': param_pattern},
'description': 'the date of the meeting',
}
}
invalid_value = '2025-31-01'
instance = {param_name: ['2025-01-31', invalid_value]}
self.validate_instance_with_schema(
schema=schema,
instance=instance,
error_message=f"The value '{invalid_value}' of the parameter 'meeting_date's item' doesn't match the expected pattern '{param_pattern}'."
)
def test_missing_optional_object_property(self):
'''
Assert that when some properties of an object parameter are not required and are missing from the LLM response, the validation will succeed.
'''
param_name = 'object_param'
schema = {
param_name: {
'type': 'object',
'description': 'user contact details',
'properties': {
'email': {
'type': 'string',
'description': 'the email of the user',
},
'phone': {
'type': 'string',
'description': 'the phone number of the user',
},
},
'required': ['email'],
}
}
instance = {param_name: {'email': 'Mohamed@gmail.com'}}
self.validate_instance_with_schema(
schema=schema,
instance=instance,
)
def test_missing_required_object_property(self):
'''
Assert that when some properties of an object parameter are required but are missing from the LLM response, the validation will fail.
'''
param_name = 'object_param'
schema = {
param_name: {
'type': 'object',
'description': 'user contact details',
'properties': {
'email': {
'type': 'str',
'description': 'the email of the user',
},
'phone': {
'type': 'str',
'description': 'the phone number of the user',
},
},
'required': ['email']
}
}
instance = {param_name: {'phone': '+32123456789'}}
self.validate_instance_with_schema(
schema=schema,
instance=instance,
error_message="Could you please provide info about 'email' as it is required to process your request",
)
def test_wrong_type_object_property(self):
param_name = 'object_param'
property_name = 'email'
property_type = 'string'
schema = {
param_name: {
'type': 'object',
'description': 'user contact details',
'properties': {
property_name: {
'type': property_type,
'description': 'the email of the user',
},
},
'required': [property_name]
}
}
instance = {param_name: {'email': 123}}
self.validate_instance_with_schema(
schema=schema,
instance=instance,
error_message=f"The type of the parameter '{property_name}' is incorrect. It should be '{property_type}'.",
)
def test_wrong_format_object_property(self):
'''
Assert that when an object property doesn't follow the expected pattern, the validation will fail.
'''
param_name = 'object_param'
property_name = 'email'
property_type = 'string'
property_pattern = r'\w+@\w+\.\w+'
property_value = 'saif_genidy@odoo'
schema = {
param_name: {
'type': 'object',
'description': 'user contact details',
'properties': {
property_name: {
'type': property_type,
'description': 'the email of the user',
'pattern': property_pattern,
},
},
'required': [property_name]
}
}
instance = {param_name: {property_name: property_value}}
self.validate_instance_with_schema(
schema=schema,
instance=instance,
error_message=f"The value '{property_value}' of the parameter '{property_name}' doesn't match the expected pattern '{property_pattern}'.",
)
def test_truncate(self):
schema = {
'object_param': {
'type': 'object',
'description': 'object root',
'properties': {
'str_value': {
'type': 'string',
'description': 'str value',
'maxLength': 5,
},
'sub_obj': {
'type': 'object',
'description': 'sub object',
'properties': {
'str_value_2': {
'type': 'string',
'description': 'str value',
'maxLength': 3,
},
},
'required': ['str_value_2'],
},
},
'required': ['str_value'],
},
}
instance = {'object_param': {'str_value': '123456789', 'sub_obj': {'str_value_2': 'abcdefg'}}}
ret = self.validate_instance_with_schema(
schema=schema,
instance=instance,
)
self.assertEqual(ret, {'object_param': {'str_value': '12345...', 'sub_obj': {'str_value_2': 'abc...'}}})
def test_enum(self):
schema = {'state': {'type': 'string', 'description': 'the date of the meeting', 'enum': ['done', 'ready']}}
self.validate_instance_with_schema(schema=schema, instance={'state': 'done'})
self.validate_instance_with_schema(
schema=schema,
instance={'state': 'invalid'},
error_message="Wrong value invalid, should be in: done, ready",
)
def test_anyof_array_items(self):
param_name = 'operations'
schema = {
param_name: {
'type': 'array',
'description': 'list of operations',
'items': {
'anyOf': [
{
'type': 'object',
'properties': {
'type': {'type': 'string', 'enum': ['navigate']},
'period': {'type': 'string', 'enum': ['day', 'week', 'month']},
},
'required': ['type', 'period'],
},
{
'type': 'object',
'properties': {
'type': {'type': 'string', 'enum': ['find_next', 'find_previous']},
'weekday': {'type': 'integer'},
},
'required': ['type', 'weekday'],
},
],
},
},
}
# Test navigate operation
instance = {param_name: [{'type': 'navigate', 'period': 'day'}]}
self.validate_instance_with_schema(schema=schema, instance=instance)
# Test find_next operation
instance = {param_name: [{'type': 'find_next', 'weekday': 4}]}
self.validate_instance_with_schema(schema=schema, instance=instance)
# Test mixed operations
instance = {param_name: [
{'type': 'navigate', 'period': 'month'},
{'type': 'find_previous', 'weekday': 0},
]}
self.validate_instance_with_schema(schema=schema, instance=instance)
# Test invalid: navigate without required period
instance = {param_name: [{'type': 'navigate'}]}
self.validate_instance_with_schema(
schema=schema,
instance=instance,
error_message="The value of parameter 'operations's item' doesn't match any of the expected schemas.",
)
# Test invalid: find_next with wrong weekday type
instance = {param_name: [{'type': 'find_next', 'weekday': 'monday'}]}
self.validate_instance_with_schema(
schema=schema,
instance=instance,
error_message="The value of parameter 'operations's item' doesn't match any of the expected schemas.",
)
# Test invalid: unknown type
instance = {param_name: [{'type': 'unknown_operation', 'period': 'day'}]}
self.validate_instance_with_schema(
schema=schema,
instance=instance,
error_message="The value of parameter 'operations's item' doesn't match any of the expected schemas.",
)

View File

@@ -0,0 +1,337 @@
import json
import psycopg2
from unittest.mock import patch
from odoo import Command
from odoo.exceptions import AccessError, ValidationError
from odoo.tests import new_test_user, tagged
from odoo.tools import mute_logger
from odoo.addons.ai.tests.common import TestAICommon
from odoo.addons.ai.models.ai_session import _logger as tool_logger
@tagged('post_install', '-at_install')
class TestAiServerActions(TestAICommon):
def test_ai_server_action_access(self):
"""Test that the group check is skipped on the tool, but not on the AI action."""
user = new_test_user(
self.env, "internal_user_ai", "base.group_user,base.group_partner_manager",
)
partner = self.env["res.partner"].create({"name": "Partner"})
action = self.env["ir.actions.server"].create(
{
"model_id": self.env["ir.model"]._get_id("res.partner"),
"state": "ai",
"name": "Test",
"ai_tool_ids": [Command.create({
"model_id": self.env["ir.model"]._get_id("res.partner"),
"state": "code",
"name": "Write Name",
"ai_tool_name": "write_name",
"use_in_ai": True,
"code": "record.write({'name': value})",
"group_ids": self.env.ref("base.group_system").ids,
})],
"ai_action_prompt": "Main Prompt",
},
)
# Check that we skip the group check on the tools
with self.mock_completion_request([self.mock_text_response("done")]) as mock_request:
action.with_user(user).with_context(active_id=partner.id, active_model='res.partner').run()
self.assertEqual(mock_request.call_count, 1)
# But not on the AI action
action.group_ids = self.env.ref("base.group_system").ids
with self.mock_completion_request([self.mock_text_response("done")]) as mock_request, self.assertRaises(AccessError):
action.with_user(user).with_context(active_id=partner.id, active_model='res.partner').run()
self.assertEqual(mock_request.call_count, 0)
def test_ai_server_action_user_access(self):
user = self.user_internal
partner = self.env["res.partner"].create({"name": "Partner"})
# Remove res.partner read access from the user
access_records = self.env['ir.access'].search([
('model_id.model', '=', 'res.partner'),
('group_id', 'in', user.all_group_ids.ids)
])
for access_record in access_records:
if access_record.operation == 'r':
access_record.for_create = True # operation cannot be empty
access_record.for_read = False
search_tool = self.env.ref('ai.ir_actions_server_search').with_user(user).sudo()
# openAI format for now, change to test_model?
mocked_responses = [
self.mock_tool_response(search_tool, {"model_name": "res.partner", "domain": json.dumps([["id", "=", partner.id]]), "fields": ["name"]}),
self.mock_text_response("Unable to fetch partner details due to access rights"),
]
with self.mock_completion_request(mocked_responses) as mock_request, \
self.assertLogs(tool_logger, level='WARNING') as mock_tool_logger:
message_parts = [{'type': 'text', 'content': {'data': 'message'}}]
self.env['ai.session'].with_user(user)._get_direct_response('instructions', message_parts, tools=search_tool)
self.assertEqual(mock_request.call_count, 2)
# Single error log stating the user cannot access the records
(error_log_record,) = mock_tool_logger.records
self.assertIn(
"The model 'res.partner' doesn't exist or is inaccessible to the current user",
error_log_record.msg,
)
@mute_logger("odoo.addons.ai.models.ai_session")
def test_ai_server_action_ai_tool(self):
partner = self.env["res.partner"].create({"name": "Partner"})
tools = self.env["ir.actions.server"].create([{
"model_id": self.env["ir.model"]._get_id("res.partner"),
"state": "code",
"name": "Return Value",
"ai_tool_name": "return_value",
"use_in_ai": True,
"code": "ai['result'] = 133333337",
}, {
"model_id": self.env["ir.model"]._get_id("res.partner"),
"state": "code",
"name": "Write Name",
"ai_tool_name": "write_name",
"use_in_ai": True,
"code": "record.write({'name': value})",
# Ensure schema validation is triggered during _ai_tool_run
"ai_tool_schema": json.dumps({
"properties": {"value": {"type": "string"}},
"required": ["value"],
}),
}])
action = self.env["ir.actions.server"].create(
{
"model_id": self.env["ir.model"]._get_id("res.partner"),
"state": "ai",
"name": "Test",
"ai_tool_ids": tools.ids,
"ai_action_prompt": "Main Prompt",
},
)
mocked_responses = [
self.mock_tool_response(tools[0], {}),
self.mock_tool_response(tools[1], {'value': 'new name'}),
self.mock_text_response("Done"),
]
with self.mock_completion_request(mocked_responses) as mock_request:
action.with_context(active_model=partner._name, active_id=partner.id).run()
self.assertEqual(mock_request.call_count, 3)
self.assertEqual(partner.name, "new name")
# Simulate the LLM answering a forbidden action (not in the tools)
bad_tool = self.env["ir.actions.server"].create({
"model_id": self.env["ir.model"]._get_id("res.partner"),
"state": "code",
"name": "Bad Action",
"ai_tool_name": "bad_action",
"use_in_ai": True,
"code": "record.write({'name': 'bad'})",
})
mocked_responses = [
self.mock_tool_response(bad_tool),
self.mock_text_response("Failed"),
]
with self.mock_completion_request(mocked_responses) as mock_request:
action.with_context(active_model=partner._name, active_id=partner.id).run()
self.assertEqual(mock_request.call_count, 2)
self.assertEqual(partner.name, "new name", "Should not execute the action because it's not listed in the tools")
def _patched_can_execute_action_on_records(*__):
raise AccessError("")
with (
patch.object(
self.env.registry["ir.actions.server"],
"_can_execute_action_on_records",
_patched_can_execute_action_on_records,
),
self.assertRaises(AccessError),
):
action.with_context(active_model=partner._name, active_id=partner.id).run()
# Check that if we mark a tool as "not used with AI" we don't send it
# to the LLM even if the m2m relation still exist
tools[1].use_in_ai = False
partner.name = 'name'
mocked_responses = [
self.mock_tool_response(tools[1], {'value': 'new name'}),
self.mock_text_response("Done"),
]
with self.mock_completion_request(mocked_responses) as mock_request:
action.with_context(active_model=partner._name, active_id=partner.id).run()
self.assertEqual(mock_request.call_count, 2)
self.assertEqual(partner.name, "name", "The action is disabled and should not be executed")
@mute_logger("odoo.addons.ai.models.ai_session")
def test_ai_server_action_ai_interactive_tool(self):
"""Check that we raise an error for interactive tools."""
partner = self.env["res.partner"].create({"name": "Partner"})
ir_action_tool = self.env["ir.actions.server"].create(
{
"model_id": self.env["ir.model"]._get_id("res.partner"),
"state": "code",
"name": "Return Value",
"ai_tool_name": "return_value",
"use_in_ai": True,
# The action tries to open a window action
"code": """action = {
"type": "ir.actions.act_window",
"res_model": "res.partner",
"target": "new",
}
""",
},
)
action = self.env["ir.actions.server"].create(
{
"model_id": self.env["ir.model"]._get_id("res.partner"),
"state": "ai",
"name": "Test",
"ai_tool_ids": ir_action_tool.ids,
"ai_action_prompt": "Main Prompt",
},
)
mocked_responses = [
self.mock_tool_response(ir_action_tool),
self.mock_text_response("Done")
]
with self.mock_completion_request(mocked_responses) as mock_request:
action.with_context(active_model=partner._name, active_id=partner.id).run()
self.assertEqual(mock_request.call_count, 2)
self.assertIn(
"This action is interactive and cannot be executed by the agent.",
"".join(partner.message_ids.mapped("body")),
"Should log the error on the partner",
)
def test_ai_create_activity(self):
# check that activities can be created from an AI action
create_activity_action = self.env['ir.actions.server'].create({
'model_id': self.env['ir.model']._get_id('res.partner'),
'state': 'next_activity',
'name': 'create activity',
'ai_tool_name': 'create_activity',
'use_in_ai': True,
'activity_type_id': self.env.ref('mail.mail_activity_data_todo').id,
'activity_note': 'created by AI',
})
ai_action = self.env['ir.actions.server'].create({
'model_id': self.env['ir.model']._get_id('res.partner'),
'state': 'ai',
'name': 'call create activity',
'ai_action_prompt': 'create an activity',
'ai_tool_ids': create_activity_action.ids,
})
mocked_responses = [
self.mock_tool_response(create_activity_action),
self.mock_text_response("Done")
]
with self.mock_completion_request(mocked_responses):
ai_action._ai_action_run(self.env.user.partner_id)
self.assertIn('created by AI', self.env.user.partner_id.activity_ids[0].note)
def test_ai_send_mail(self):
partner_model_id = self.env['ir.model']._get_id('res.partner')
send_mail_action = self.env['ir.actions.server'].create({
'model_id': partner_model_id,
'state': 'mail_post',
'name': 'send mail',
'ai_tool_name': 'send_mail',
'use_in_ai': True,
'template_id': self.env['mail.template'].create({
'name': 'Test template',
'model_id': partner_model_id,
'subject': 'mail sent by AI',
}).id,
})
ai_action = self.env['ir.actions.server'].create({
'model_id': partner_model_id,
'state': 'ai',
'name': 'send mail',
'ai_action_prompt': 'send an email',
'ai_tool_ids': send_mail_action.ids,
})
mocked_responses = [
self.mock_tool_response(send_mail_action),
self.mock_text_response("Done"),
]
with self.mock_completion_request(mocked_responses):
ai_action._ai_action_run(self.env.user.partner_id)
# check that the mail has been created
self.assertTrue(any(msg.subject == 'mail sent by AI' for msg in self.env.user.partner_id.message_ids))
def test_ai_tool_name_required_with_use_in_ai(self):
self.env['ir.actions.server'].create({
'model_id': self.env['ir.model']._get_id('res.partner'),
'state': 'code',
'name': 'Test Tool',
'use_in_ai': False,
'code': "ai['result'] = True",
})
self.assertTrue(self.env['ir.actions.server'].search([('name', '=', 'Test Tool'), ('use_in_ai', '=', False)]))
with self.assertRaises(ValidationError):
self.env['ir.actions.server'].create({
'model_id': self.env['ir.model']._get_id('res.partner'),
'state': 'code',
'name': 'Test Tool',
'use_in_ai': True,
'code': "ai['result'] = True",
})
def test_ai_tool_name_invalid_format(self):
with self.assertRaises(ValidationError):
self.env['ir.actions.server'].create({
'model_id': self.env['ir.model']._get_id('res.partner'),
'state': 'code',
'name': 'Test Tool',
'ai_tool_name': 'bad name!',
'use_in_ai': True,
'code': "ai['result'] = True",
})
@mute_logger('odoo.sql_db')
def test_raise_on_duplicate_ai_tool_name(self):
self.env['ir.actions.server'].create({
'model_id': self.env['ir.model']._get_id('res.partner'),
'state': 'code',
'name': 'Test Tool',
'use_in_ai': True,
'ai_tool_name': 'my_unique_tool',
'code': "ai['result'] = True",
})
with self.assertRaises(psycopg2.errors.UniqueViolation):
self.env['ir.actions.server'].create({
'model_id': self.env['ir.model']._get_id('res.partner'),
'state': 'code',
'name': 'Test Tool 2',
'use_in_ai': True,
'ai_tool_name': 'my_unique_tool',
'code': "ai['result'] = True",
})

View File

@@ -0,0 +1,47 @@
from unittest.mock import patch
from odoo.tests.common import TransactionCase
class TestAISources(TransactionCase):
# tests the processing of rich spreadsheets indexed by `attachment_indexation`
def _create_attachment(self, name, mimetype, content):
with patch.object(self.registry['ir.attachment'], '_index', lambda self, data, _type: data.decode() or None):
return self.env['ir.attachment'].create({
'name': name,
'mimetype': mimetype,
'raw': content,
})
def test_multi_sheet_csv_with_headers(self):
# Two sheets separated by blank line, both with headers
index_content = b"Name,Age\nAlice,30\nBob,25\n\nProduct,Price\nPen,1.2\nNotebook,2.5"
attachment = self._create_attachment('people_and_products.csv', 'text/csv', index_content)
content = attachment._get_attachment_content()
self.assertIsInstance(content, str)
self.assertTrue(content)
# Validate first sheet rows are parsed with explicit headers
self.assertIn("{'Name': 'Alice', 'Age': '30'}", content)
self.assertIn("{'Name': 'Bob', 'Age': '25'}", content)
# Validate second sheet rows are parsed with explicit headers
self.assertIn("{'Product': 'Pen', 'Price': '1.2'}", content)
self.assertIn("{'Product': 'Notebook', 'Price': '2.5'}", content)
def test_ragged_rows_extra_and_missing_columns(self):
# CSV with header, rows having extra and missing columns
# Row 2 has extra fields (captured under _extra_fields), row 3 has a missing value
sheet = b'3,10\n1,2,3,4\n5\n6,7'
attachment = self._create_attachment('ragged.csv', 'text/csv', sheet)
content = attachment._get_attachment_content()
self.assertIsInstance(content, str)
self.assertTrue(content)
# Extra fields captured under _extra_fields
self.assertIn("'Column_0': '1'", content)
self.assertIn("'Column_1': '2'", content)
self.assertIn("'_extra_fields': ['3', '4']", content)
# Missing column becomes None
self.assertIn("{'Column_0': '5', 'Column_1': None}", content)
# Normal row
self.assertIn("{'Column_0': '6', 'Column_1': '7'}", content)

View File

@@ -0,0 +1,224 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
from datetime import datetime
from unittest.mock import patch
from odoo.addons.ai.models.ai_session import _logger as ai_session_logger
from odoo.addons.ai.models.ir_actions_server import IrActionsServer
from odoo.addons.ai.utils.ai_citation import apply_web_citations
from odoo.addons.ai.utils.ai_utils import get_text_from_parts
from odoo.addons.ai.tests.common import TestAICommon
from odoo.exceptions import UserError
from odoo.tests import tagged
@tagged("post_install", "-at_install")
class TestLLMToolCalling(TestAICommon):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.tools = cls.env['ir.actions.server'].create([{
'model_id': cls.env["ir.model"]._get_id('ai.agent'),
'state': 'code',
'name': f'tool_{i + 1}',
'ai_tool_name': f'tool_{i + 1}',
'use_in_ai': True,
'code': f"ai['result'] = 'tc_{i + 1}'"
} for i in range(3)])
def test_tool_call_result_serializes_datetime(self):
"""Tool results containing datetime objects are JSON-serialized properly."""
mocked_result = {'executed_at': datetime(2026, 3, 30, 8, 15, 42)}
mocked_responses = [
self.mock_tool_response(self.tools[0]),
self.mock_text_response("Done"),
]
with patch.object(IrActionsServer, '_ai_tool_run', return_value=mocked_result), \
self.mock_completion_request(mocked_responses) as mock_request:
self.env['ai.session']._get_direct_response(
instructions="do this",
message=[{'type': 'text', 'text': "test"}],
tools=self.tools,
)
history = mock_request.call_args.args[0]
tool_output = history[-1] # last item is the tool result
self.assertEqual(tool_output['content'][0]['type'], 'tool_result')
self.assertIn('2026-03-30 08:15:42', tool_output['content'][0]['result'][0]['text'])
def test_max_api_calls_reached(self):
max_calls = 2
self.env["ir.config_parameter"].sudo().set_int("ai.max_successive_calls", max_calls)
# return more tool calls than allowed
mocked_responses = [self.mock_tool_response(self.tools[0])] * (max_calls + 1)
with self.assertRaises(UserError) as e, self.mock_completion_request(mocked_responses) as mock_request:
self.env['ai.session']._get_direct_response(
instructions="Do this",
message=[{'type': 'text', 'text': "test_prompt"}],
tools=self.tools
)
self.assertEqual(
str(e.exception),
"Number of successive API calls exceeded, please try again with a more precise request."
)
self.assertEqual(mock_request.call_count, max_calls)
def test_max_tool_calls_reached(self):
max_calls = 1
self.env["ir.config_parameter"].sudo().set_int("ai.max_tool_calls_per_call", max_calls)
mocked_responses = [
# first response: more calls than allowed
[*self.mock_tool_response(self.tools[0]), *self.mock_tool_response(self.tools[1])],
# second response, text answer
self.mock_text_response("Final answer"),
]
with self.assertLogs(ai_session_logger, level='WARNING') as mock_session_logger, \
self.mock_completion_request(mocked_responses) as mock_request:
response = self.env['ai.session']._get_direct_response(
instructions="Do this",
message=[{'type': 'text', 'text': "test prompt"}],
tools=self.tools,
)
self.assertEqual(get_text_from_parts(response), "Final answer")
warning_log, = mock_session_logger.records
self.assertEqual(warning_log.message, "AI: Tool call limit reached, stopping further tool calls")
# check the messags sent
self.assertEqual(mock_request.call_args.args[0], [
{'role': 'user', 'content': [{'type': 'text', 'text': 'test prompt'}]},
{
'role': 'assistant',
'content': [
{'args': {}, 'call_id': 1, 'name': 'tool_1', 'type': 'tool_call'},
{'args': {}, 'call_id': 2, 'name': 'tool_2', 'type': 'tool_call'},
],
'provider_metadata': {},
},
{
'role': 'user',
'content': [
{
'type': 'tool_result',
'tool_call_id': 1,
'tool_name': 'tool_1',
'result': [{'type': 'text', 'text': 'tc_1'}],
'success': True,
},
# tool call should not have been executed
{
'type': 'tool_result',
'tool_call_id': 2,
'tool_name': 'tool_2',
'result': [{'type': 'text', 'text': 'Error: Not executed (tool call limit reached)'}],
'success': False,
},
]
},
])
def test_unknown_tool_call(self):
mocked_tool_response = self.mock_tool_response(self.tools[0])
unknown_tool_name = mocked_tool_response[0]['name'] + "abc"
mocked_tool_response[0]['name'] = unknown_tool_name
mocked_responses = [
# first answer: unknown tool
mocked_tool_response,
# second answer: final answer
self.mock_text_response("Final answer")
]
with self.assertLogs(ai_session_logger, level='ERROR') as mock_session_logger, \
self.mock_completion_request(mocked_responses) as mock_request:
response = self.env['ai.session']._get_direct_response(
instructions="Do this",
message=[{'type': 'text', 'text': "test prompt"}],
tools=self.tools,
)
self.assertEqual(get_text_from_parts(response), "Final answer")
error_log, = mock_session_logger.records
self.assertEqual(error_log.message, f"AI: Try to call a non-available tool {unknown_tool_name}")
# check the messages sent
self.assertEqual(mock_request.call_args.args[0], [
{'role': 'user', 'content': [{'type': 'text', 'text': 'test prompt'}]},
{
'role': 'assistant',
'content': [{'type': 'tool_call', 'name': unknown_tool_name, 'args': {}, 'call_id': 1}],
'provider_metadata': {},
},
# tool should not have been executed since not found
{
'role': 'user',
'content': [{
'type': 'tool_result',
'tool_call_id': 1,
'tool_name': unknown_tool_name,
'result': [{'type': 'text', 'text': f"Error: Unknown tool '{unknown_tool_name}'"}],
'success': False,
}],
},
])
def test_ai_web_search(self):
web_search_tool = self.env.ref('ai.ir_actions_server_ai_web_search')
mocked_responses = [
# first answer: agent requesting web_search tool
self.mock_tool_response(web_search_tool, {'query': "Search for the latest news", 'retrieval_mode': 'fact'}),
# second answer: response of the web search tool
self.mock_text_response("Web search result"),
# third answer: agent answer using the tool result
self.mock_text_response("This is what I found"),
]
with self.mock_completion_request(mocked_responses) as mock_request:
response = self.env['ai.session']._get_direct_response(
instructions="Look this on the web",
message=[{'type': 'text', 'text': "Latest News"}],
tools=web_search_tool,
)
self.assertEqual(response, [{'type': 'text', 'text': "This is what I found"}])
args = mock_request.call_args.args
kw = mock_request.call_args.kwargs
self.assertNotIn('web_grounding', kw) # should use the tool, not the native param
self.assertIn('ai_tool_web_search', json.dumps(args[2]))
# should be the tool response containing the result of the web search
self.assertEqual(args[0][-1], {
'role': 'user',
'content': [{
'type': 'tool_result',
'tool_call_id': 1,
'tool_name': web_search_tool.ai_tool_name,
'result': [{'type': 'text', 'text': "Web search result"}],
'success': True,
}],
})
def test_apply_web_citations(self):
text = "First claim.[WEB_SOURCE:aaa111] Second claim.[WEB_SOURCE:bbb222]"
sources = {
'aaa111': {'url': 'https://a.com', 'source_name': 'a.com'},
'bbb222': {'url': 'https://b.com', 'source_name': 'b.com'},
}
result = apply_web_citations(text, sources)
self.assertNotIn('[WEB_SOURCE:', result)
self.assertIn("href='https://a.com'", result)
self.assertIn("href='https://b.com'", result)
def test_apply_web_citations_unknown_id_ignored(self):
text = "Some claim.[WEB_SOURCE:0]"
result = apply_web_citations(text, {})
self.assertNotIn('[WEB_SOURCE:', result)
self.assertNotIn('<a ', result)
self.assertIn('Some claim.', result)

View File

@@ -0,0 +1,473 @@
import logging
from datetime import UTC, datetime
from unittest.mock import patch
from odoo import fields
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.exceptions import AccessError, UserError
from odoo.tests import tagged
from odoo.tests.common import (
HttpCase,
JsonRpcException,
TransactionCase,
new_test_user,
)
from odoo.tools import mute_logger
from odoo.addons.mail.tools import discuss, jwt
_logger = logging.getLogger(__name__)
@tagged("call_artifacts")
class TestMailCallArtifactAI(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
channel = cls.env['discuss.channel'].create({'name': 'Test Channel'})
cls.call = cls.env['discuss.call.history'].create({
'start_dt': '2023-01-01 10:00:00',
'channel_id': channel.id,
})
def _create_stt_artifact(self, start_ms=0, end_ms=1000, **values):
artifact_values = {
"discuss_call_history_id": self.call.id,
"start_ms": start_ms,
"end_ms": end_ms,
"is_stt": True,
"transcription_state": "pending",
}
artifact_values.update(values)
artifact = self.env["mail.call.artifact"].create(artifact_values)
self.env["ir.attachment"].create({
"name": "transcription.webm",
"raw": b"transcription",
"res_model": artifact._name,
"res_id": artifact.id,
"mimetype": "audio/webm",
})
artifact.invalidate_recordset(["media_id"])
return artifact
def _create_media_artifact(self, start_ms=0, end_ms=1000):
artifact = self.env["mail.call.artifact"].create({
"discuss_call_history_id": self.call.id,
"start_ms": start_ms,
"end_ms": end_ms,
})
self.env["ir.attachment"].create({
"name": "recording.ogg",
"raw": b"recording",
"res_model": artifact._name,
"res_id": artifact.id,
"mimetype": "audio/ogg",
})
artifact.invalidate_recordset(["media_id"])
return artifact
def _assert_transcription_email_target(self, artifact, expected_target):
with patch.object(
self.env.registry["mail.call.artifact"],
"_send_recording_available_email",
autospec=True,
) as send_email:
artifact._after_transcription_done()
self.assertFalse(artifact.media_id)
if expected_target:
send_email.assert_called_once_with(expected_target)
else:
send_email.assert_not_called()
def test_has_transcript(self):
artifact = self._create_stt_artifact()
other_call = self.env["discuss.call.history"].create({
"channel_id": self.call.channel_id.id,
"start_dt": "2023-01-01 11:00:00",
})
transcript_domain = [
("id", "in", (self.call | other_call).ids),
("has_transcript", "=", True),
]
self.assertFalse(self.call.has_transcript)
self.assertFalse(self.call.has_recording)
self.assertFalse(self.call.search(transcript_domain))
artifact.write({
"transcript": "WEBVTT\n\n00:00.000 --> 00:01.000\nHello",
"transcription_state": "done",
})
self.assertTrue(self.call.has_transcript)
self.assertFalse(self.call.has_recording)
self.assertEqual(self.call.search(transcript_domain), self.call)
def test_recording_flags_exclude_transcription_audio(self):
artifact = self._create_stt_artifact()
for is_stt in (True, False, True):
artifact.is_stt = is_stt
self.assertEqual(self.call.has_recording, not is_stt)
self.assertEqual(self.call.has_audio, not is_stt)
self.assertFalse(self.call.has_video)
def test_recording_waits_for_matching_transcription(self):
media_artifact = self._create_media_artifact()
self.assertTrue(media_artifact._is_recording_available())
stt_artifact = self._create_stt_artifact()
self.assertFalse(stt_artifact._is_recording_media())
self.assertFalse(media_artifact._is_recording_available())
stt_artifact.transcription_state = "error"
self.assertFalse(media_artifact._is_recording_available())
stt_artifact.transcription_state = "done"
self.assertTrue(media_artifact._is_recording_available())
matching_stt_artifact = self._create_stt_artifact()
self.assertFalse(media_artifact._is_recording_available())
matching_stt_artifact.transcription_state = "done"
self.assertTrue(media_artifact._is_recording_available())
other_stt_artifact = self.env["mail.call.artifact"].create({
"discuss_call_history_id": self.call.id,
"start_ms": 1000,
"end_ms": 2000,
"is_stt": True,
"transcription_state": "pending",
})
self.assertTrue(media_artifact._is_recording_available())
self.assertFalse(other_stt_artifact._is_recording_available())
def test_transcription_targets_recording_email_artifact(self):
stt_only_artifact = self._create_stt_artifact(
has_media_output=False,
transcription_state="done",
)
self._assert_transcription_email_target(stt_only_artifact, stt_only_artifact)
self.assertTrue(stt_only_artifact._is_recording_available())
media_artifact = self._create_media_artifact(2000, 3000)
stt_artifact = self._create_stt_artifact(
2000,
3000,
has_media_output=True,
transcription_state="done",
)
self._assert_transcription_email_target(stt_artifact, media_artifact)
waiting_stt_artifact = self._create_stt_artifact(
4000,
5000,
has_media_output=True,
transcription_state="done",
)
self._assert_transcription_email_target(waiting_stt_artifact, False)
def test_allow_stt_artifact_overlapping_non_stt_artifact(self):
"""Allow STT artifacts to have overlapping media windows"""
# Archival Artifact (non-stt)
self.env['mail.call.artifact'].create({
'discuss_call_history_id': self.call.id,
'start_ms': 0,
'end_ms': 5000,
})
# STT Artifact that overlaps
self.env['mail.call.artifact'].create({
'discuss_call_history_id': self.call.id,
'start_ms': 4000,
'end_ms': 9000,
'is_stt': True,
})
def test_allow_overlap_of_two_stt_artifacts(self):
"""Bypass the standard overlap check for STT artifacts, as their internal VTT timestamps can naturally offset the chunk boundaries"""
self.env['mail.call.artifact'].create({
'discuss_call_history_id': self.call.id,
'start_ms': 0,
'end_ms': 5000,
'is_stt': True,
'transcript': '\n'.join(('WEBVTT', # noqa: FLY002
'',
'00:00.000 --> 00:05.000',
'Have you seen Mark'
)),
})
self.env['mail.call.artifact'].create({
'discuss_call_history_id': self.call.id,
'start_ms': 3000,
'end_ms': 8000,
'is_stt': True,
'transcript': '\n'.join(('WEBVTT', # noqa: FLY002
'',
'00:06.000 --> 00:08.000',
'Hello Rob! Yes, he sweeps the saloon'
)),
})
@mute_logger('odoo.addons.ai.models.mail_call_artifact')
def test_missing_transcription_retries(self):
rec = self._create_stt_artifact()
self.env["ir.config_parameter"].sudo().set_int("ai.max_transcription_retries", 2)
with (
self.enter_registry_test_mode(),
patch(
"odoo.addons.ai.models.mail_call_artifact.call_odoo_ai",
side_effect=[{"text": None}, {"text": ""}],
),
patch.object(self.env.cr, "commit"),
patch.object(
self.env.registry["mail.call.artifact"],
"_send_recording_available_email",
autospec=True,
) as send_email,
):
rec.action_transcribe_gevent()
rec.invalidate_recordset()
self.assertEqual(rec.transcription_state, "pending")
self.assertEqual(rec.transcription_error_count, 1)
self.assertTrue(rec.media_id)
send_email.assert_not_called()
rec.action_transcribe_gevent()
rec.invalidate_recordset()
self.assertEqual(rec.transcription_state, "done")
self.assertEqual(rec.transcription_error_count, 0)
self.assertFalse(rec.media_id)
send_email.assert_called_once_with(rec)
@mute_logger('odoo.addons.ai.models.mail_call_artifact')
def test_transcription_retry(self):
"""Verify that API errors trigger a retry (state remains pending) until max retries is reached"""
rec = self._create_stt_artifact()
self.env["ir.config_parameter"].sudo().set_int("ai.max_transcription_retries", 2)
with (
self.enter_registry_test_mode(),
patch(
'odoo.addons.ai.utils.ai_utils.call_odoo_ai',
side_effect=UserError("Mocked API Error")
),
patch.object(self.env.cr, 'commit')
):
# 1st attempt
rec.action_transcribe_gevent()
rec.invalidate_recordset()
self.assertEqual(rec.transcription_state, 'pending', "Should stay pending after 1st failure")
self.assertEqual(rec.transcription_error_count, 1)
# 2nd attempt
rec.action_transcribe_gevent()
rec.invalidate_recordset()
self.assertEqual(rec.transcription_state, 'error', "Should be error after max retries")
self.assertEqual(rec.transcription_error_count, 2)
self.assertEqual(rec.transcription_error_msg, "Transcription request failed")
@tagged("call_artifacts")
class TestMailCallArtifactController(HttpCase):
def test_recording_permissions_enable_transcription(self):
permissions = self.env["discuss.channel.member"]._get_recording_permissions(
self.env.user,
)
self.assertEqual(
permissions,
{
"audioRecording": True,
"transcription": True,
"videoRecording": True,
},
)
def test_transcribe_recording(self):
recording_user = mail_new_test_user(self.env, login="recording_user")
deleted_user = mail_new_test_user(self.env, login="deleted_recording_user")
call_start = datetime(2023, 1, 1, 10)
channel = self.env["discuss.channel"].create({"name": "Recorded Channel"})
call = self.env["discuss.call.history"].create({
"channel_id": channel.id,
"start_dt": call_start,
})
call_start_ms = int(call_start.replace(tzinfo=UTC).timestamp() * 1000)
issued_at = int(datetime.now(UTC).timestamp())
sfu_key = discuss.get_derived_sfu_key(self.env, channel.id)
token = jwt.sign(
{"iat": issued_at, "user_id": recording_user.id},
sfu_key,
ttl=60,
algorithm=jwt.Algorithm.HS256,
)
legacy_token = jwt.sign(
{"iat": issued_at},
sfu_key,
ttl=60,
algorithm=jwt.Algorithm.HS256,
)
deleted_user_token = jwt.sign(
{"iat": issued_at, "user_id": deleted_user.id},
sfu_key,
ttl=60,
algorithm=jwt.Algorithm.HS256,
)
deleted_user.unlink()
with (
patch.object(
self.env.registry["mail.call.artifact"],
"action_transcribe_gevent",
autospec=True,
) as action_transcribe,
patch.object(
self.env.registry["discuss.call.history"],
"_broadcast_recording_availability",
autospec=True,
) as broadcast_recording,
):
response = self.url_open(
f"/mail/rtc/recording/{call.id}/transcribe",
data=b"audio",
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "audio/ogg",
},
params={
"start_ms": call_start_ms + 1_000,
"end_ms": call_start_ms + 3_000,
"has_media_output": "0",
},
)
legacy_response = self.url_open(
f"/mail/rtc/recording/{call.id}/transcribe",
data=b"legacy audio",
headers={
"Authorization": f"Bearer {legacy_token}",
"Content-Type": "audio/ogg",
},
params={
"start_ms": call_start_ms + 4_000,
"end_ms": call_start_ms + 6_000,
},
)
deleted_user_response = self.url_open(
f"/mail/rtc/recording/{call.id}/transcribe",
data=b"deleted user audio",
headers={
"Authorization": f"Bearer {deleted_user_token}",
"Content-Type": "audio/ogg",
},
params={
"start_ms": call_start_ms + 7_000,
"end_ms": call_start_ms + 9_000,
},
)
call.invalidate_recordset(["artifact_ids"])
artifact, legacy_artifact, deleted_user_artifact = call.artifact_ids.sorted("start_ms")
self.assertEqual(response.status_code, 204)
self.assertEqual(legacy_response.status_code, 204)
self.assertEqual(deleted_user_response.status_code, 204)
self.assertEqual(len(call.artifact_ids), 3)
self.assertEqual((artifact.start_ms, artifact.end_ms), (1_000, 3_000))
self.assertTrue(artifact.is_stt)
self.assertFalse(artifact.has_media_output)
self.assertEqual(artifact.recording_started_by_id, recording_user)
self.assertEqual(artifact.transcription_state, "pending")
self.assertEqual(bytes(artifact.media_id.raw), b"audio")
self.assertEqual(artifact.media_id.mimetype, "audio/ogg")
self.assertTrue(legacy_artifact.has_media_output)
self.assertFalse(legacy_artifact.recording_started_by_id)
self.assertEqual(bytes(legacy_artifact.media_id.raw), b"legacy audio")
self.assertFalse(deleted_user_artifact.recording_started_by_id)
self.assertEqual(bytes(deleted_user_artifact.media_id.raw), b"deleted user audio")
self.assertEqual(action_transcribe.call_count, 3)
self.assertEqual(broadcast_recording.call_count, 3)
call.invalidate_recordset(["has_audio", "has_recording", "has_video"])
self.assertFalse(call.has_recording)
self.assertFalse(call.has_audio)
self.assertFalse(call.has_video)
def test_transcribe_route_rejects_session_token(self):
call_start = fields.Datetime.now()
channel = self.env["discuss.channel"].create({"name": "Recorded Channel"})
call = self.env["discuss.call.history"].create({
"channel_id": channel.id,
"start_dt": call_start,
})
token = jwt.sign(
{
"iat": int(datetime.now(UTC).timestamp()),
"session_id": 1,
"user_id": self.env.user.id,
},
discuss.get_derived_sfu_key(self.env, channel.id),
ttl=60,
algorithm=jwt.Algorithm.HS256,
)
response = self.url_open(
f"/mail/rtc/recording/{call.id}/transcribe",
method="POST",
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "audio/ogg",
},
params={
"start_ms": 1_000,
"end_ms": 3_000,
"has_media_output": "false",
},
)
self.assertEqual(response.status_code, 404)
call.invalidate_recordset(["artifact_ids"])
self.assertFalse(call.artifact_ids)
@mute_logger('odoo.http')
def test_transcribe_endpoint_security(self):
no_access_user = new_test_user(
self.env,
login='no_access_user',
groups='base.group_portal'
)
private_channel = self.env['discuss.channel'].create({'name': 'Private Channel', 'channel_type': 'chat'})
private_call = self.env['discuss.call.history'].create({
'channel_id': private_channel.id,
'start_dt': fields.Datetime.now(),
})
self.authenticate(no_access_user.login, no_access_user.login)
with self.assertRaises(JsonRpcException, msg="odoo.exceptions.AccessError"):
self.make_jsonrpc_request('/ai/transcription/call', {
'call_model': 'discuss.call.history',
'call_id': private_call.id,
})
user = new_test_user(
self.env,
login='standard_user',
groups='base.group_user'
)
public_channel = self.env['discuss.channel'].create({
'name': 'Public Channel',
'channel_type': 'channel',
})
public_channel._add_members(partners=user.partner_id)
public_call = self.env['discuss.call.history'].create({
'channel_id': public_channel.id,
'start_dt': fields.Datetime.now(),
})
artifact = self.env['mail.call.artifact'].sudo().create({
'discuss_call_history_id': public_call.id,
'start_ms': 0,
'end_ms': 1000,
'is_stt': True,
'transcription_state': 'pending',
})
self.authenticate(user.login, user.login)
with self.assertRaises(AccessError):
artifact.with_user(user).write({'transcript': 'Hacker injection'})
response = self.make_jsonrpc_request('/ai/transcription/call', {
'call_model': 'discuss.call.history',
'call_id': public_call.id,
})
self.assertEqual(response, "OK")

View File

@@ -0,0 +1,30 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import unittest
from odoo.tests import TransactionCase, tagged
from odoo.addons.ai.utils.ai_utils import markdown_format, CustomMarkdown
@tagged("post_install", "-at_install")
@unittest.skipUnless(CustomMarkdown, "can't test markdown rendering without a markdown renderer")
class TestMarkdownFormatting(TransactionCase):
def test_md_bold_boundaries_detection(self):
"""Test that markdown_format correctly detects bold boundaries"""
text = "The **Lion**, the **Giraffe** and the **Zebra**"
expected = "<p>The <strong>Lion</strong>, the <strong>Giraffe</strong> and the <strong>Zebra</strong></p>"
self.assertEqual(markdown_format(text), expected)
def test_md_italic_bold_standard_behavior(self):
"""Test that standard bold and italic markdown is converted properly to HTML."""
self.assertEqual(markdown_format("This is *italic*, right?"), "<p>This is <em>italic</em>, right?</p>")
self.assertEqual(markdown_format("Wait, *is this italic?*"), "<p>Wait, <em>is this italic?</em></p>")
self.assertEqual(markdown_format("Make it **bold**, please!"), "<p>Make it <strong>bold</strong>, please!</p>")
self.assertEqual(
markdown_format("Look at this **bold with *italic* inside**, cool? And here is *italic with **bold** inside*, interesting."),
"<p>Look at this <strong>bold with <em>italic</em> inside</strong>, cool? And here is <em>italic with <strong>bold</strong> inside</em>, interesting.</p>"
)
self.assertEqual(
markdown_format("Finally, ***bold and italic*** together!"),
"<p>Finally, <strong><em>bold and italic</em></strong> together!</p>"
)

View File

@@ -0,0 +1,455 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import re
from odoo.tests import tagged, TransactionCase
from odoo.addons.ai.utils.tools_schema.param_schema_validator import validate_schema
DUMMY_ATTRIBUTES = {'type': 'string', 'description': '...'}
DUMMY_ARRAY_ATTRIBUTES = {
'type': 'array',
'items': {
'anyOf': [{'type': 'string'}, {'type': 'number'}]}}
DUMMY_OBJECT_ATTRIBUTES = {
'type': 'object',
'properties': {
'email': {
'type': 'string',
'description': 'The email of the user',
}
},
'required': []
}
@tagged('at_install', '-post_install') # LEGACY at_install
class TestParamSchemaValidation(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.wrong_array_item_type_error_message = (
"The types of the items of the 'array' param 'array_param' are not defined correctly. "
"The types of the items must be defined as ('items': {'type': 'string'}) if all items are of the same primitive type, "
"('items': {'type': 'object', 'properties': {...}, 'required': [...]}) for objects, "
"or ('items': { 'anyOf': [ {'type': 'string'}, {'type': 'number'} ] }) if items are of different types"
)
def create_param(self, param_name='param', param_attributes=None, excluded_attributes=None):
"""
The required attributes of a parameter are filled automatically with dummy values from DUMMY_ATTRIBUTES
unless they are excluded in excluded_attributes.
"""
if param_attributes is None:
param_attributes = {}
if excluded_attributes is None:
excluded_attributes = []
param_attributes = {**DUMMY_ATTRIBUTES, **param_attributes}
for excluded_attribute in excluded_attributes:
param_attributes.pop(excluded_attribute)
schema = {}
for attribute_name, attribute_value in param_attributes.items():
schema[attribute_name] = attribute_value
return {param_name: schema}
def create_array_param(self, param_name='array_param', param_attributes=None, excluded_attributes=None):
if param_attributes is None:
param_attributes = {}
if excluded_attributes is None:
excluded_attributes = []
param_attributes = {**DUMMY_ARRAY_ATTRIBUTES, **param_attributes}
schema = self.create_param(
param_name=param_name,
param_attributes=param_attributes,
excluded_attributes=excluded_attributes,
)
return schema
def create_object_param(self, param_name='object_param', param_attributes=None, excluded_attributes=None):
if param_attributes is None:
param_attributes = {}
if excluded_attributes is None:
excluded_attributes = []
param_attributes = {**DUMMY_OBJECT_ATTRIBUTES, **param_attributes}
schema = self.create_param(
param_name=param_name,
param_attributes=param_attributes,
excluded_attributes=excluded_attributes,
)
return schema
def validate_schema(self, schema, error_type=ValueError, error_message=''):
full_schema = {
'type': 'object',
'properties': schema,
'required': list(schema.keys()),
}
if error_message:
with self.assertRaisesRegex(error_type, re.escape(error_message)):
validate_schema(full_schema)
else:
validate_schema(full_schema)
def test_valid_schema(self):
schema = {
'user_id': {
'type': 'string',
'description': 'The unique identifier of the user whose profile is being updated. This is a permanent and immutable identifier.',
'pattern': '^[a-zA-Z0-9-]+$',
},
'preferences': {
'type': 'array',
'items': {'type': 'string'},
'description': 'A list of the user\'s preferred categories or interests. These could be used for content filtering or recommendations.',
},
'contact_info': {
'type': 'object',
'description': 'An object containing the user\'s contact details.',
'properties': {
'email': {
'type': 'string',
'description': 'The primary email address for the user. Must be a valid email format.',
'pattern': '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$',
},
'phone': {
'type': 'string',
'description': 'The user\'s primary phone number. Should follow a standard international format (e.g., +[country code][area code][local number]).',
'pattern': r'^\+\d{1,3}\s?\d+$',
},
},
'required': ['email'],
},
}
self.validate_schema(schema=schema)
def test_schema_with_no_params(self):
schema = {}
self.validate_schema(
schema=schema,
)
def test_unsupported_type(self):
schema = self.create_param(
param_attributes={'type': 'method'}
)
self.validate_schema(
schema=schema,
error_message="The type 'method' of parameter 'param' is wrong.",
)
def test_missing_required_attribute(self):
# Description attribute is missing
schema = self.create_param(
excluded_attributes=['type']
)
self.validate_schema(
schema=schema,
error_message="The attributes '['type']' must be defined for the parameter 'param'.",
)
def test_unsupported_attribute(self):
param_name = 'param_with_unsupported_attributes'
schema = self.create_param(
param_name=param_name,
param_attributes={'state': 'active'}
)
self.validate_schema(
schema=schema,
error_message=f"The attributes '['state']' defined for the param '{param_name}' are not supported."
)
def test_pattern_with_non_string_parameter(self):
schema = self.create_param(
param_attributes={'type': 'number', 'pattern': r'\d*'}
)
self.validate_schema(
schema=schema,
error_message=(
"The pattern attribute cannot be defined for the parameter 'param'. "
"The pattern attribute can only be defined for string parameters or arrays whose items are only of the type string."
)
)
def test_minimum_with_numeric_parameter(self):
for param_type in ('integer', 'number'):
with self.subTest(param_type=param_type):
schema = self.create_param(
param_attributes={'type': param_type, 'minimum': 1}
)
self.validate_schema(schema=schema)
def test_minimum_with_non_numeric_parameter(self):
schema = self.create_param(
param_attributes={'type': 'string', 'minimum': 1}
)
self.validate_schema(
schema=schema,
error_message=(
"The minimum attribute cannot be defined for the parameter 'param'. "
"The minimum attribute can only be defined for integer or number parameters."
),
)
def test_minimum_must_be_numeric(self):
schema = self.create_param(
param_attributes={'type': 'integer', 'minimum': True}
)
self.validate_schema(
schema=schema,
error_type=TypeError,
error_message="The minimum attribute for the parameter 'param' must be a number.",
)
def test_array_parameter_with_different_item_types(self):
schema = self.create_array_param()
self.validate_schema(schema=schema)
def test_array_parameter_without_item_types(self):
# items attribute is missing.
schema = self.create_array_param(
excluded_attributes={'items'}
)
self.validate_schema(
schema=schema,
error_message="The attributes '['items']' must be defined for a parameter of type 'array'. They are missing for the parameter 'array_param'.",
)
def test_array_parameter_incorrect_item_types_definition_1(self):
# items attribute must be a dict
schema = self.create_array_param(
param_attributes={'items': ['number', 'string']}
)
self.validate_schema(
schema=schema,
error_message=self.wrong_array_item_type_error_message
)
def test_array_parameter_incorrect_item_types_definition_2(self):
# The dict can only have one key, either type or anyOf
schema = self.create_array_param(
param_attributes={
'items': {'anyOf': [{'type': 'string'}], 'type': 'string'}
}
)
self.validate_schema(
schema=schema,
error_message=self.wrong_array_item_type_error_message
)
def test_array_parameter_incorrect_item_types_definition_3(self):
# The value of anyOf must be a list
schema = self.create_array_param(
param_attributes={
'items': {'anyOf': {'type': 'string'}}
}
)
self.validate_schema(
schema=schema,
error_message=self.wrong_array_item_type_error_message
)
def test_array_parameter_incorrect_item_types_definition_4(self):
# No keys other than type or anyOf are allowed
schema = self.create_array_param(
param_attributes={
'items': {'item': 'string'}
}
)
self.validate_schema(
schema=schema,
error_message=self.wrong_array_item_type_error_message
)
def test_array_parameter_incorrect_item_types_definition_5(self):
# The values inside the list of anyOf must be dicts
schema = self.create_array_param(
param_attributes={
'items': {'anyOf': ['string']}
}
)
self.validate_schema(
schema=schema,
error_message=self.wrong_array_item_type_error_message
)
def test_array_parameter_incorrect_item_types_definition_6(self):
# The types of array items can be one of ['string', 'number', 'boolean']
schema = self.create_array_param(
param_attributes={
'items': {'anyOf': [{'type': 'string'}, {'type': 'array'}]}
}
)
self.validate_schema(
schema=schema,
error_message="The type 'array' of the items of the 'array' parameter 'array_param' is wrong. The available types are"
)
def test_2d_array_parameter(self):
schema = self.create_array_param(
param_attributes={
'items': {
'anyOf': [{'type': 'array'}, {'type': 'string'}]
}
}
)
self.validate_schema(
schema=schema,
error_message="The type 'array' of the items of the 'array' parameter 'array_param' is wrong. The available types are",
)
def test_pattern_with_string_array_items(self):
schema = self.create_array_param(
param_attributes={
'type': 'array',
'items': {'type': 'string'},
'pattern': r'\d*'
}
)
self.validate_schema(schema=schema)
def test_pattern_with_non_string_array_items(self):
schema = self.create_array_param(
param_attributes={
'type': 'array',
'items': {'anyOf': [{'type': 'string'}, {'type': 'number'}]},
'pattern': r'\d*'
}
)
self.validate_schema(
schema=schema,
error_message=(
"The pattern attribute cannot be defined for the parameter 'array_param'. "
"The pattern attribute can only be defined for string parameters or arrays whose items are only of the type string."
)
)
def test_object_parameter_with_array_property(self):
property_definition = self.create_array_param()
schema = self.create_object_param(
param_attributes={
'properties': property_definition,
}
)
self.validate_schema(schema=schema)
def test_object_parameter_without_properties_attribute(self):
schema = self.create_object_param(
excluded_attributes=['properties']
)
self.validate_schema(
schema=schema,
error_message="The attributes '['properties']' must be defined for a parameter of type 'object'. They are missing for the parameter 'object_param'.",
)
def test_object_parameter_without_required_attribute(self):
schema = self.create_object_param(
excluded_attributes=['required']
)
self.validate_schema(
schema=schema,
error_message="The attributes '['required']' must be defined for a parameter of type 'object'. They are missing for the parameter 'object_param'.",
)
def test_object_required_attribute_incorrect_definition(self):
schema = self.create_object_param(
param_attributes={'required': False}
)
self.validate_schema(
schema=schema,
error_type=TypeError,
error_message=(
"The attribute 'required' for the object param 'object_param' must be a 'list' containing "
"the required properties of the object or empty if all of them are not required."
)
)
def test_object_parameter_with_pattern_attribute(self):
schema = self.create_object_param(
param_attributes={'pattern': '^[a-zA-Z0-9]+$'}
)
self.validate_schema(
schema=schema,
error_message=(
"The pattern attribute cannot be defined for the parameter 'object_param'."
" The pattern attribute can only be defined for string parameters or arrays whose items are only of the type string."
),
)
def test_nested_object_parameter(self):
inner_object_definition = self.create_object_param(
param_name='inner_object'
)
outer_object_definition = self.create_object_param(
param_attributes={
'properties': inner_object_definition,
}
)
self.validate_schema(
schema=outer_object_definition,
)
def test_deeply_nested_objects(self):
schema = {
'user': {
'type': 'object',
'properties': {
'name': {'type': 'string'},
'address': {
'type': 'object',
'properties': {
'street': {'type': 'string'},
'location': {
'type': 'object',
'properties': {
'city': {'type': 'string'},
'country': {'type': 'string'},
},
'required': ['city'],
},
},
'required': ['location'],
},
},
'required': ['name'],
},
}
self.validate_schema(schema=schema)
def test_array_of_objects_parameter(self):
schema = self.create_array_param(
param_attributes={
'items': {
'type': 'object',
'properties': {
'field_name': {'type': 'string'},
'selected_periods': {
'type': 'array',
'items': {'type': 'string'},
},
},
'required': ['field_name', 'selected_periods'],
},
},
)
self.validate_schema(schema=schema)
def test_array_of_objects_missing_required(self):
schema = self.create_array_param(
param_attributes={
'items': {
'type': 'object',
'properties': {'field_name': {'type': 'string'}},
},
},
)
self.validate_schema(
schema=schema,
error_message="The required properties should be specified as a list.",
)

View File

@@ -0,0 +1,490 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import re
from markupsafe import Markup
from odoo.sql_db import _logger as sql_logger
from odoo.tests import users
from odoo.tools.mail import html_sanitize, html_to_inner_content
from odoo.tools.misc import format_datetime
from odoo.addons.ai.models.ai_session import _logger as tool_logger
from odoo.addons.ai.tests.common import TestAICallbackCommon
from odoo.addons.ai.utils.ai_utils import (
make_create_preview,
make_record_create_preview,
)
class TestAIToolCreateRecords(TestAICallbackCommon):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.create_tool = cls.env.ref("ai.ir_actions_server_create_records")
cls.create_records_skill = cls.env["ai.skill"].create(
{
"name": "Create records Skill",
"instructions": "Skill instructions",
"tool_ids": cls.create_tool.ids,
},
)
cls.agent.sudo().write(
{
"skill_ids": cls.agent.skill_ids | cls.create_records_skill,
},
)
def test_create_records(self):
session = self._create_ai_session(self.agent)
mocked_responses = [
self.mock_tool_response(self.skill_loading_tool, {"skill_ids": self.create_records_skill.ids}),
self.mock_text_response("skills enabled"),
]
with self.mock_callback_completions(mocked_responses):
self._post_user_message_on_session(session, "Load skill")
mocked_responses = [
self.mock_tool_response(
self.create_tool,
{
"explanation": "Creating new AI agent named Jimmy",
"model_name": "ai.agent",
"values": [
{
"field_values": [
{
"field": "name",
"value": "Jimmy",
},
],
},
],
},
),
]
with self.mock_callback_completions(mocked_responses):
self._post_user_message_on_session(session, "Create an agent named 'Jimmy'")
self.assertEqual(
session.pending_tool_call['call_id'],
2,
"Creation tool should be pending on first call.",
)
self.assertIn(
"Name: Jimmy",
html_to_inner_content(session.pending_tool_call['user_input_request']['body']),
)
self.assertFalse(self.env["ai.agent"].search([("name", "=", "Jimmy")]), "Agent should not exist if tool hasn't been confirmed.")
# Tool confirmation
with self.mock_callback_completions([self.mock_text_response("Agent Jimmy created")]):
self._confirm_pending_tool(session)
self.assertFalse(session.pending_tool_call, "Creation tool call should be confirmed")
self.assertTrue(self.env["ai.agent"].search([("name", "=", "Jimmy")]), "Agent should exist after tool confirmation")
def test_create_preview_single_record(self):
create_values = {
"author_id": self.env.user.partner_id.id, # many2one
"message_type": "email", # selection
"is_internal": True, # bool
"email_from": "from@example.com", # char
"incoming_email_to": "incoming@example.com", # text
"body": "<p>Hi</p>", # html
"pinned_at": "2025-01-15 12:34:56", # datetime
}
message = self.env["mail.message"].create(create_values)
preview = make_record_create_preview(message, create_values)
self.assertEqual(
preview[0],
{"label": "Author", "value": self.env.user.partner_id.display_name},
)
self.assertEqual(preview[1], {"label": "Type", "value": "email"})
self.assertEqual(preview[2], {"label": "Employee Only", "value": True})
self.assertEqual(preview[3], {"label": "From", "value": "from@example.com"})
self.assertEqual(
preview[4],
{"label": "Emails To", "value": "incoming@example.com"},
)
self.assertEqual(preview[5], {"label": "Contents", "value": "Hi"})
self.assertEqual(
preview[6],
{
"label": "Pinned",
"value": format_datetime(self.env, "2025-01-15 12:34:56"),
},
)
def test_create_preview_multiple_records(self):
create_values = [
{
"field_values": [{"field": "body", "value": "<p>Hi</p>"}],
},
{
"field_values": [
{
"field": "body",
"value": "<p>Hello</p>",
},
],
},
]
preview = make_create_preview(
self.env,
"Understood, I'll create the following messages.",
"mail.message",
create_values,
)
clean_whitespace_preview = re.sub(
r"[\n\r\t]+",
"",
preview,
) # Removing all whitespaces from the preview
clean_preview = re.sub(
r" {2,}",
"",
clean_whitespace_preview,
) # Removing all multiple leftover spaces
changes = re.findall(r"<li>(.*?)</li>", clean_preview)
self.assertEqual(len(changes), 2)
self.assertEqual(
changes[0].strip(),
'<b>Message 1:</b>Hi',
)
self.assertEqual(
changes[1].strip(),
'<b>Message 2:</b>Hello',
)
def test_create_preview_x2m_commands(self):
child_message = self.env["mail.message"].create(
{"subject": "Greetings", "body": "<p>Hey!</p>"},
)
create_values = [
{
"model_name": "mail.message",
"field_values": [
{"field": "body", "value": "<p>Hi</p>"},
{"field": "child_ids", "x2m_link_ids": child_message.ids},
],
},
]
preview = make_create_preview(
self.env,
"Understood, I'll create the following messages.",
"mail.message",
create_values,
)
self.assertEqual(
html_to_inner_content(preview),
'Understood, I\'ll create the following messages. Contents: Hi Child Messages: Message 1: "Greetings" (existing)',
)
@users("user_internal")
def test_create_records_tool_access(self):
"""Users should not be able to create records they cannot access through AI agents"""
session_sudo = self._create_ai_session(self.agent)
mocked_responses = [
self.mock_tool_response(self.skill_loading_tool, {"skill_ids": self.create_records_skill.ids}),
self.mock_text_response("skills enabled"),
]
with self.mock_callback_completions(mocked_responses):
self._post_user_message_on_session(session_sudo, "Load skill")
mocked_responses = [
self.mock_tool_response(
self.create_tool,
{
"explanation": "Creating an AI Agent called Jimmy",
"model_name": "ai.agent",
"values": [
{
"field_values": [
{
"field": "name",
"value": "Jimmy",
},
],
},
],
},
),
self.mock_text_response("Not allowed"),
]
with (
self.mock_callback_completions(mocked_responses),
self.assertLogs(tool_logger, level="WARNING") as mock_tool_logger,
):
self._post_user_message_on_session(session_sudo, "Change agent name")
# error is logged, tool call should be shown as erroneous
self.assertIn(
"You are not allowed to create 'AI Agent' (ai.agent) records.",
mock_tool_logger.records[0].msg,
)
self.assertFalse(session_sudo.pending_tool_call)
tool_result = self._get_tool_result(session_sudo, 2)
self.assertFalse(tool_result['success'])
self.assertIn(
"Error: Tool call failed: You are not allowed to create 'AI Agent' (ai.agent) records",
tool_result['result'][0]['text'],
)
# message should be in session history and posted
self.assertEqual(
{
"role": "assistant",
"content": [{"type": "text", "text": "Not allowed"}],
"provider_metadata": {},
},
session_sudo.event_ids.sorted('id')[-1].metadata,
)
self.assertIn("Not allowed", session_sudo.channel_id.message_ids[0].body)
def test_create_records_accepted_posts_preview_link(self):
"""A preview message should be posted in the channel when a creation tool call is accepted"""
action = self.env["ir.actions.act_window"].create({
"res_model": "ai.agent"
})
menu = self.env["ir.ui.menu"].create({
"name": "Test Agents",
"action": f"{action._name},{action.id}",
})
session = self._create_ai_session(self.agent)
mocked_responses = [
self.mock_tool_response(self.skill_loading_tool, {"skill_ids": self.create_records_skill.ids}),
self.mock_text_response("skills enabled"),
]
with self.mock_callback_completions(mocked_responses):
self._post_user_message_on_session(session, "Load skill")
mocked_responses = [
self.mock_tool_response(
self.create_tool,
{
"explanation": "Creating new AI agent named Jimmy",
"model_name": "ai.agent",
"preview_menu_id": menu.id,
"values": [
{
"field_values": [
{
"field": "name",
"value": "Jimmy",
},
],
},
],
},
),
]
with self.mock_callback_completions(mocked_responses):
self._post_user_message_on_session(session, "Create an agent named 'Jimmy'")
self.assertEqual(
session.pending_tool_call['call_id'],
2,
"Creation tool should be pending on first call.",
)
with self.mock_callback_completions([self.mock_text_response("Agent Jimmy created")]):
self._confirm_pending_tool(session)
self.assertFalse(session.pending_tool_call, "Creation tool call should be confirmed")
created_agent = self.env["ai.agent"].search([("name", "=", "Jimmy")])
self.assertTrue(created_agent)
all_message_contents = [
msg.body for msg in session.channel_id.message_ids[::-1]
]
self.assertIn(
f'has created <a href="#" data-oe-model="ai.agent" data-oe-id="{created_agent.id}">Jimmy</a>',
all_message_contents[-1],
"Preview message should be posted in the channel after creation is accepted",
)
self.assertEqual(all_message_contents[-2], '<p>Agent Jimmy created</p>')
def test_create_records_accepted_posts_preview_link_multiple_records(self):
"""Links should be properly formatted in the preview message when multiple records are created"""
action = self.env["ir.actions.act_window"].create({
"res_model": "ai.agent"
})
menu = self.env["ir.ui.menu"].create({
"name": "Test Agents",
"action": f"{action._name},{action.id}",
})
session = self._create_ai_session(self.agent)
mocked_responses = [
self.mock_tool_response(self.skill_loading_tool, {"skill_ids": self.create_records_skill.ids}),
self.mock_text_response("skills enabled"),
]
with self.mock_callback_completions(mocked_responses):
self._post_user_message_on_session(session, "Load skill")
mocked_responses = [
self.mock_tool_response(
self.create_tool,
{
"explanation": "Creating new AI agent named Jimmy",
"model_name": "ai.agent",
"preview_menu_id": menu.id,
"values": [
{
"field_values": [
{
"field": "name",
"value": "Jimmy",
},
],
},
{
"field_values": [
{
"field": "name",
"value": "Bob",
},
],
},
],
},
),
]
with self.mock_callback_completions(mocked_responses):
self._post_user_message_on_session(session, "Create an agent named 'Jimmy'")
self.assertEqual(
session.pending_tool_call['call_id'],
2,
"Creation tool should be pending on first call.",
)
with self.mock_callback_completions([self.mock_text_response("Agent Jimmy created")]):
self._confirm_pending_tool(session)
self.assertFalse(session.pending_tool_call, "Creation tool call should be confirmed")
created_agents = self.env["ai.agent"].search(["|", ("name", "=", "Jimmy"), ("name", "=", "Bob")], order="id ASC")
self.assertEqual(2, len(created_agents))
all_message_contents = [
msg.body for msg in session.channel_id.message_ids[::-1]
]
self.assertEqual(
html_sanitize(Markup('<div class="o_mail_notification" data-oe-type="ai_preview"><span>%s</span></div>')
% self.env._(
"has created %s",
Markup(
"<a href=\"/web#action=%d&domain=[('id', 'in', %r)]\">multiple records (%s)</a>",
)
% (action.id, created_agents.ids, self.env["ai.agent"]._description),
)),
all_message_contents[-1],
"Preview message should be posted in the channel after creation is accepted",
)
self.assertEqual(all_message_contents[-2], '<p>Agent Jimmy created</p>')
def test_create_records_raises_value_error_on_sql_constraint_fail(self):
session = self._create_ai_session(self.agent)
mocked_responses = [
self.mock_tool_response(self.skill_loading_tool, {"skill_ids": self.create_records_skill.ids}),
self.mock_text_response("skills enabled"),
]
with self.mock_callback_completions(mocked_responses):
self._post_user_message_on_session(session, "Load skills")
mocked_responses = [
self.mock_tool_response(
self.create_tool,
{
"explanation": "Creating new mail activity: Call Marc Demo",
"model_name": "mail.activity",
"values": [
{
"field_values": [
{
"field": "res_id",
"value": 9999,
},
{
"field": "res_model",
"value": "res.partner",
},
{
"field": "summary",
"value": "Call Marc Demo",
},
],
},
],
},
),
]
with self.mock_callback_completions(mocked_responses):
self._post_user_message_on_session(
session,
"Create a mail activity for tomorrow: Call Marc Demo",
)
self.assertEqual(
session.pending_tool_call['call_id'],
2,
"Creation tool should be pending on first call.",
)
# Tool confirmation
with (
self.mock_callback_completions(
[self.mock_text_response("Sorry, that failed.")],
),
self.assertLogs(tool_logger, level="WARNING") as mock_tool_logger,
self.assertLogs(sql_logger, level="ERROR"),
):
self._confirm_pending_tool(session)
self.assertIn(
"mail_activity_check_res_id_is_set_if_model",
"".join(r.msg for r in mock_tool_logger.records),
)
self.assertFalse(session.pending_tool_call)
self.assertFalse(
self.env["mail.activity"].search([("summary", "=", "Call Marc Demo")]),
)
tool_result = self._get_tool_result(session, 2)
self.assertFalse(tool_result['success'])
self.assertIn(
"Tool call failed:",
tool_result['result'][0]['text'],
)
# follow-up assistant message posted
self.assertIn("Sorry, that failed.", session.channel_id.message_ids[0].body)

View File

@@ -0,0 +1,503 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import Command
from odoo.addons.ai.models.ai_session import _logger as tool_logger
from odoo.addons.ai.tests.common import TestAICallbackCommon
from odoo.addons.ai.utils.ai_utils import make_records_update_preview
from odoo.tools.mail import html_to_inner_content
from odoo.tools.misc import format_datetime
from odoo.tests import users
from odoo.sql_db import _logger as sql_logger
class TestAiToolUpdateRecords(TestAICallbackCommon):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.update_tool = cls.env.ref('ai.ir_actions_server_update_records')
cls.update_records_skill = cls.env["ai.skill"].create({
'name': 'Test Skill',
'instructions': 'Skill instructions',
'tool_ids': cls.update_tool.ids,
})
cls.agent.sudo().write({
'skill_ids': cls.agent.skill_ids | cls.update_records_skill,
})
def test_update_records_tool(self):
"""Check that the update records tool asks for confirmation with a preview of the changes,
and that it correctly updates the records when confirming the tool call.
"""
session = self._create_ai_session(self.agent)
mocked_responses = [
self.mock_tool_response(self.skill_loading_tool, {"skill_ids": self.update_records_skill.ids}),
self.mock_text_response("skills enabled"),
]
with self.mock_callback_completions(mocked_responses):
self._post_user_message_on_session(session, "Load skill")
mocked_responses = [
self.mock_tool_response(self.update_tool, {
"explanation": "Updating Test Agent to Jimmy",
"preview_menus": [],
'updates': [
{
'model_name': 'ai.agent',
'domain': f"[('id', '=', {self.agent.id})]",
'changes': [{
'field': 'name',
'value': 'Jimmy',
}]
}
],
}),
]
with self.mock_callback_completions(mocked_responses):
self._post_user_message_on_session(session, "Change agent name")
# should ask for the confirmation
self.assertEqual(session.pending_tool_call['call_id'], 2)
# pending confirmation should preview the changes
self.assertIn(
'AI Agent "Test Agent": Agent Name → Jimmy',
html_to_inner_content(session.pending_tool_call['user_input_request']['body']),
)
# but change should not be done yet
self.assertEqual(self.agent.name, 'Test Agent')
# confirm tool
with self.mock_callback_completions([self.mock_text_response("Changes done")]):
self._confirm_pending_tool(session)
self.assertFalse(session.pending_tool_call)
# change should be done
self.assertEqual(self.agent.name, 'Jimmy')
@users('user_internal')
def test_update_records_tool_access(self):
"""Users should not be able to update records they cannot access through AI agents
"""
session_sudo = self._create_ai_session(self.agent)
mocked_responses = [
self.mock_tool_response(self.skill_loading_tool, {"skill_ids": self.update_records_skill.ids}),
self.mock_text_response("skills enabled"),
]
with self.mock_callback_completions(mocked_responses):
self._post_user_message_on_session(session_sudo, "Load skill")
mocked_responses = [
self.mock_tool_response(self.update_tool, {
"explanation": "Updating AI Agent Jimmy",
"preview_menus": [],
'updates': [
{
'model_name': 'ai.agent',
'domain': f"[('id', '=', {self.agent.id})]",
'changes': [{
'field': 'name',
'value': 'Jimmy',
}]
}
],
}),
self.mock_text_response("Not allowed")
]
with self.mock_callback_completions(mocked_responses), self.assertLogs(tool_logger, level='WARNING') as mock_tool_logger:
self._post_user_message_on_session(session_sudo, "Change agent name")
# error is logged, tool call should be shown as erroneous
self.assertIn(
"You are not allowed to modify 'AI Agent' (ai.agent) records",
mock_tool_logger.records[0].msg,
)
self.assertFalse(session_sudo.pending_tool_call)
tool_result = self._get_tool_result(session_sudo, 2)
self.assertFalse(tool_result['success'])
self.assertIn(
"Error: Tool call failed: You are not allowed to modify 'AI Agent' (ai.agent) records",
tool_result['result'][0]['text'],
)
# message should be in session history and posted
self.assertEqual(
{
'role': 'assistant',
'content': [{'type': 'text', 'text': 'Not allowed'}],
'provider_metadata': {},
},
session_sudo.event_ids.sorted('id')[-1].metadata,
)
self.assertIn("Not allowed", session_sudo.channel_id.message_ids[0].body)
def test_update_preview_basic_fields(self):
"""Check the formatting of the different field types when using the update tool record.
"""
message = self.env['mail.message'].create({
'author_id': self.env.user.partner_id.id, # many2one
'message_type': 'email', # selection
'is_internal': True, # bool
'email_from': "from@example.com", # char
'incoming_email_to': "incoming@example.com", # text
'body': "<p>Hi</p>", # html
'pinned_at': '2025-01-15 12:34:56', # datetime
})
changes = make_records_update_preview(message, {
'author_id': self.ref('base.partner_root'),
'message_type': 'comment',
'is_internal': False,
'email_from': "fromage@example.com",
'incoming_email_to': "incoming2@example.com",
'body': '<p>Hello</p>',
'pinned_at': '2025-01-16 12:34:56',
})
self.assertEqual(changes[0], {
'old_val': self.env.user.partner_id.display_name,
'new_val': self.env.ref('base.user_root').display_name,
'field_name': 'Author',
})
self.assertEqual(changes[1], {
'old_val': 'Incoming Email',
'new_val': 'Comment',
'field_name': 'Type',
})
self.assertEqual(changes[2], {
'old_val': True,
'new_val': "None",
'field_name': 'Employee Only',
})
self.assertEqual(changes[3], {
'old_val': 'from@example.com',
'new_val': 'fromage@example.com',
'field_name': 'From',
})
self.assertEqual(changes[4], {
'old_val': 'incoming@example.com',
'new_val': 'incoming2@example.com',
'field_name': 'Emails To',
})
self.assertEqual(changes[5], {
'old_val': 'Hi',
'new_val': 'Hello',
'field_name': 'Contents',
})
self.assertEqual(changes[6], {
'old_val': format_datetime(self.env, '2025-01-15 12:34:56'),
'new_val': format_datetime(self.env, '2025-01-16 12:34:56'),
'field_name': 'Pinned',
})
def test_update_preview_x2m_commands(self):
message = self.env['mail.message'].create({'body': "<p>Hi</p>"})
reaction1 = self.env['mail.message.reaction'].create({'content': "🗿", 'message_id': message.id, 'partner_id': self.env.user.partner_id.id})
reaction2 = self.env['mail.message.reaction'].create({'content': "🥸", 'message_id': message.id, 'partner_id': self.env.user.partner_id.id})
preview = make_records_update_preview(message, {
'reaction_ids': [Command.link(reaction1.id), Command.link(reaction2.id)]
})
self.assertEqual(preview[0]['field_name'], 'Reactions')
self.assertEqual(
html_to_inner_content(preview[0]['new_val']),
f'Add "mail.message.reaction,{reaction1.id}"Add "mail.message.reaction,{reaction2.id}"'
)
def test_update_preview_x2m_create_command_not_allowed(self):
"""Command.create should raise a ValueError when used in an update preview."""
message = self.env['mail.message'].create({'body': "<p>Hi</p>"})
with self.assertRaisesRegex(ValueError, f"Command {Command.CREATE} cannot be used during an update."):
make_records_update_preview(message, {
'reaction_ids': [Command.create({'content': "🗿"})],
})
def test_update_records_accepted_posts_preview_link(self):
"""A preview message should be posted in the channel when an update tool call is accepted"""
partner = self.env["res.partner"].create({"name": "Test Partner"})
action = self.env["ir.actions.act_window"].create({
"res_model": "res.partner",
})
menu = self.env["ir.ui.menu"].create({
"name": "Test Partners",
"action": f"{action._name},{action.id}",
})
session = self._create_ai_session(self.agent)
mocked_responses = [
self.mock_tool_response(self.skill_loading_tool, {"skill_ids": self.update_records_skill.ids}),
self.mock_text_response("skills enabled"),
]
with self.mock_callback_completions(mocked_responses):
self._post_user_message_on_session(session, "Load skill")
mocked_responses = [
self.mock_tool_response(self.update_tool, {
"explanation": "Updating Test Partner to Jimmy",
"preview_menus": [{"model_name": "res.partner", "menu_id": menu.id}],
'updates': [
{
'model_name': 'res.partner',
'domain': f"[('id', '=', {partner.id})]",
'changes': [{
'field': 'name',
'value': 'Jimmy',
}],
},
],
}),
]
with self.mock_callback_completions(mocked_responses):
self._post_user_message_on_session(session, "Change agent name")
# should ask for the confirmation
self.assertEqual(session.pending_tool_call['call_id'], 2)
# pending confirmation should preview the changes
self.assertIn(
'Contact "Test Partner": Name → Jimmy',
html_to_inner_content(session.pending_tool_call['user_input_request']['body']),
)
# but change should not be done yet
self.assertEqual(partner.name, 'Test Partner')
# confirm tool
with self.mock_callback_completions([self.mock_text_response("Changes done")]):
self._confirm_pending_tool(session)
self.assertFalse(session.pending_tool_call)
self.assertEqual(partner.name, 'Jimmy', "Name should have been updated")
all_message_contents = [
msg.body for msg in session.channel_id.message_ids[::-1]
]
self.assertIn(
f'has updated <a href="#" data-oe-model="res.partner" data-oe-id="{partner.id}">Jimmy</a>',
all_message_contents[-1],
"Preview message should be posted in the channel after update is accepted",
)
self.assertEqual(all_message_contents[-2], '<p>Changes done</p>')
def test_update_records_accepted_posts_preview_link_multiple_records(self):
"""A preview proper preview message should be posted in the channel when a creation tool call is accepted which modifies multiple records."""
action = self.env["ir.actions.act_window"].create(
{
"res_model": "ai.agent",
},
)
menu = self.env["ir.ui.menu"].create(
{
"name": "Test Agents",
"action": f"{action._name},{action.id}",
},
)
another_agent = self.env["ai.agent"].create({
"name": "Another agent",
})
session = self._create_ai_session(self.agent)
mocked_responses = [
self.mock_tool_response(self.skill_loading_tool, {"skill_ids": self.update_records_skill.ids}),
self.mock_text_response("skills enabled"),
]
with self.mock_callback_completions(mocked_responses):
self._post_user_message_on_session(session, "Load skill")
mocked_responses = [
self.mock_tool_response(self.update_tool, {
"explanation": "Updating Test Agent to Jimmy",
"preview_menus": [{"model_name": "ai.agent", "menu_id": menu.id}],
'updates': [
{
'model_name': 'ai.agent',
'domain': f"[('id', '=', {self.agent.id})]",
'changes': [{
'field': 'name',
'value': 'Jimmy',
}],
},
{
'model_name': 'ai.agent',
'domain': f"[('id', '=', {another_agent.id})]",
'changes': [{
'field': 'name',
'value': 'Bob',
}],
},
],
}),
]
with self.mock_callback_completions(mocked_responses):
self._post_user_message_on_session(session, "Change agent name")
# should ask for the confirmation
self.assertEqual(session.pending_tool_call['call_id'], 2)
# pending confirmation should preview the changes
self.assertIn(
'AI Agent "Test Agent": Agent Name → Jimmy AI Agent "Another agent": Agent Name → Bob',
html_to_inner_content(session.pending_tool_call['user_input_request']['body']),
)
self.assertEqual(self.agent.name, "Test Agent", "Change should not be done before accepting.")
self.assertEqual(another_agent.name, 'Another agent', "Change should not be done before accepting.")
# confirm tool
with self.mock_callback_completions([self.mock_text_response("Changes done")]):
self._confirm_pending_tool(session)
self.assertFalse(session.pending_tool_call)
self.assertEqual(self.agent.name, 'Jimmy', "Name should have been updated")
self.assertEqual(another_agent.name, 'Bob', "Name should have been updated")
all_message_contents = [
msg.body for msg in session.channel_id.message_ids[::-1]
]
self.assertIn(
# agents were updated: ai_agentic replaces the generic link note
"self-updated its configuration",
all_message_contents[-1],
"Preview message should be posted in the channel after update is accepted",
)
self.assertEqual(all_message_contents[-2], '<p>Changes done</p>')
def test_update_records_raises_value_error_on_sql_constraint_fail(self):
"""Check that the update records tool asks for confirmation with a preview of the changes,
and that it correctly updates the records when confirming the tool call.
"""
partner = self.env["res.partner"].create({"name": "Marc Demo"})
activity = self.env["mail.activity"].create(
{
"activity_type_id": self.env.ref("mail.mail_activity_data_call").id,
"res_model_id": self.env["ir.model"]._get_id("res.partner"),
"res_id": partner.id,
"summary": "Call Marc Demo",
"date_deadline": "2026-07-05",
},
)
session = self._create_ai_session(self.agent)
mocked_responses = [
self.mock_tool_response(self.skill_loading_tool, {"skill_ids": self.update_records_skill.ids}),
self.mock_text_response("skills enabled"),
]
with self.mock_callback_completions(mocked_responses):
self._post_user_message_on_session(session, "Load skill")
mocked_responses = [
self.mock_tool_response(
self.update_tool,
{
"explanation": "Updating activity 'Call Marc Demo'",
"preview_menus": [],
"updates": [
{
"model_name": "mail.activity",
"domain": f"[('id', '=', {activity.id})]",
"changes": [
{
"field": "res_id",
"value": 0,
},
],
},
],
},
),
self.mock_text_response("Changes done"),
]
with self.mock_callback_completions(mocked_responses):
self._post_user_message_on_session(session, "Change agent name")
# should ask for the confirmation
self.assertEqual(session.pending_tool_call['call_id'], 2)
with (
self.mock_callback_completions(
[self.mock_text_response("Sorry, that failed.")],
),
self.assertLogs(tool_logger, level="WARNING") as mock_tool_logger,
self.assertLogs(sql_logger, level="ERROR"),
):
self._confirm_pending_tool(session)
self.assertIn(
"mail_activity_check_res_id_is_set_if_model",
"".join(r.msg for r in mock_tool_logger.records),
)
self.assertFalse(session.pending_tool_call)
self.assertEqual(
activity.res_id,
partner.id,
"The invalid update must be rolled back.",
)
tool_result = self._get_tool_result(session, 2)
self.assertFalse(tool_result['success'])
self.assertIn(
"Tool call failed:",
tool_result['result'][0]['text'],
)
self.assertIn("Sorry, that failed.", session.channel_id.message_ids[0].body)
def test_confirmed_update_records_raises_value_error_on_dummy_truthy_domain(self):
with self.assertRaises(ValueError, msg="You cannot update using a dummy truthy domain (e.g. [], True). To update all records, pass a domain that matches all records instead."):
self.env['ai.tool'].sudo()._ai_tool_update_records(
tool_context={"tool_request_confirmed": True},
explanation="Updating all partners' names to abc",
preview_menus=[],
updates=[
{
"model_name": "res.partner",
"domain": "[]",
"changes": [
{
"field": "name",
"value": "abc",
},
],
},
],
)
with self.assertRaises(ValueError, msg="You cannot update using a dummy truthy domain (e.g. [], True). To update all records, pass a domain that matches all records instead."):
self.env['ai.tool'].sudo()._ai_tool_update_records(
tool_context={"tool_request_confirmed": True},
explanation="Updating all partners' names to abc",
preview_menus=[],
updates=[
{
"model_name": "res.partner",
"domain": "True",
"changes": [
{
"field": "name",
"value": "abc",
},
],
},
],
)