初始提交

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

View File

@@ -0,0 +1,304 @@
import { createAIChat, defineAIModels } from "@ai/../tests/ai_test_helpers";
import {
click,
contains,
insertText,
openDiscuss,
start,
startServer,
} from "@mail/../tests/mail_test_helpers";
import { Store } from "@mail/../tests/mock_server/store";
import { makeKwArgs, onRpc, serverState } from "@web/../tests/web_test_helpers";
import { describe, expect, test } from "@odoo/hoot";
import { press, queryAll, queryOne } from "@odoo/hoot-dom";
const THREAD_SELECTOR = ".o-mail-DiscussContent .o-mail-Thread";
const AGENT_HEADER_SELECTOR = ".o-agent-header";
const STEPS_BUTTON_SELECTOR = "button:text('Steps taken')";
const STEP_MSG_SELECTOR = ".o-mail-Message .o-ai-agent-step";
const TOOL_SUMMARY_SELECTOR = ".o-ai-agent-step .o-ai-tool-summary";
const RESPONSE_SELECTOR = ".o-mail-Message.o-ai-agent-response";
const PREVIEW_SELECTOR = ".o-mail-NotificationMessage";
const TOOL_STATUS_SELECTOR = ".o-ai-tool-status";
describe.current.tags("desktop");
defineAIModels();
async function openAgentStepsThread() {
const pyEnv = await startServer();
const agentPartnerId = pyEnv["res.partner"].create({ name: "Agent Partner" });
const agentId = pyEnv["ai.agent"].create({
name: "Agent Partner",
partner_id: agentPartnerId,
});
const { channelId, sessionId } = createAIChat(pyEnv, agentId);
const childPartnerId = pyEnv["res.partner"].create({ name: "Child Agent" });
const childAgentId = pyEnv["ai.agent"].create({ name: "Child Agent", partner_id: childPartnerId });
pyEnv["ai.session"].create({
agent_id: childAgentId,
parent_session_id: sessionId,
channel_id: channelId,
});
const noteSubtypeId = pyEnv["mail.message.subtype"].search([
["subtype_xmlid", "=", "mail.mt_note"],
])[0];
const commentSubtypeId = pyEnv["mail.message.subtype"].search([
["subtype_xmlid", "=", "mail.mt_comment"],
])[0];
pyEnv["mail.message"].create([
{
author_id: serverState.partnerId,
body: "Find matching leads",
message_type: "comment",
model: "discuss.channel",
res_id: channelId,
subtype_id: commentSubtypeId,
},
{
author_id: childPartnerId,
body: '<div class="o-ai-agent-step">Looking for matching leads</div>',
message_type: "comment",
model: "discuss.channel",
res_id: channelId,
subtype_id: noteSubtypeId,
},
{
author_id: childPartnerId,
body: '<div class="o-ai-agent-step"><div class="o-ai-tool-summary">Searched your leads</div></div>',
message_type: "notification",
model: "discuss.channel",
res_id: channelId,
subtype_id: noteSubtypeId,
},
{
author_id: childPartnerId,
body: "Here are the matching leads",
message_type: "comment",
model: "discuss.channel",
res_id: channelId,
subtype_id: commentSubtypeId,
},
{
author_id: childPartnerId,
body: "Leads Preview",
message_type: "notification",
model: "discuss.channel",
res_id: channelId,
subtype_id: commentSubtypeId,
},
{
author_id: serverState.partnerId,
body: "Prepare a follow-up",
message_type: "comment",
model: "discuss.channel",
res_id: channelId,
subtype_id: commentSubtypeId,
},
{
author_id: agentPartnerId,
body: '<div class="o-ai-agent-step">Preparing the follow-up</div>',
message_type: "comment",
model: "discuss.channel",
res_id: channelId,
subtype_id: noteSubtypeId,
},
{
author_id: agentPartnerId,
body: '<div class="o-ai-agent-step"><div class="o-ai-tool-summary">Created a follow-up</div></div>',
message_type: "notification",
model: "discuss.channel",
res_id: channelId,
subtype_id: noteSubtypeId,
},
{
author_id: agentPartnerId,
body: "The follow-up is ready",
message_type: "comment",
model: "discuss.channel",
res_id: channelId,
subtype_id: commentSubtypeId,
},
]);
await start();
await openDiscuss(channelId);
}
test("agent step groups are folded by default", async () => {
await openAgentStepsThread();
// only the 2 final responses and the preview is shown
await contains(PREVIEW_SELECTOR, { count: 1 });
await contains(RESPONSE_SELECTOR, { count: 2 });
await contains(STEP_MSG_SELECTOR, { count: 0 });
await contains(TOOL_SUMMARY_SELECTOR, { count: 0 });
await contains(TOOL_STATUS_SELECTOR, { count: 0 });
// 2 final responses -> 2 times the agent header and the next steps button
await contains(AGENT_HEADER_SELECTOR, { count: 2 });
await contains(AGENT_HEADER_SELECTOR + ":eq(0)", { text: "Child Agent" });
await contains(AGENT_HEADER_SELECTOR + ":eq(1)", { text: "Agent Partner" });
await contains(STEPS_BUTTON_SELECTOR, { count: 2 });
const responses = queryAll(RESPONSE_SELECTOR);
for (const response of responses) {
expect(response.previousElementSibling).toHaveClass("o-agent-header");
}
await contains(`${STEPS_BUTTON_SELECTOR} i[data-icon='chevron_right']`, { count: 2 });
});
test("Steps taken toggles its own group without affecting another group", async () => {
await openAgentStepsThread();
// open the first group of messages, containing one step msg and one tool summary
await click(`${STEPS_BUTTON_SELECTOR}:eq(0)`);
await contains(STEP_MSG_SELECTOR, { count: 1 });
await contains(TOOL_SUMMARY_SELECTOR, { count: 1 });
expect(queryOne(STEP_MSG_SELECTOR)).toHaveText("Looking for matching leads");
expect(queryOne(TOOL_SUMMARY_SELECTOR)).toHaveText("Searched your leads");
// both final responses and the preview should be shown
await contains(RESPONSE_SELECTOR, { count: 2 });
await contains(PREVIEW_SELECTOR, { count: 1 });
// only the first step groups button changed
await contains(`${STEPS_BUTTON_SELECTOR}:eq(0) i[data-icon='expand_more']`);
await contains(`${STEPS_BUTTON_SELECTOR}:eq(1) i[data-icon='chevron_right']`);
// header is shown above the step message
expect(
queryOne(STEP_MSG_SELECTOR).closest(".o-mail-Message").previousElementSibling,
).toHaveClass("o-agent-header");
// clicking again should hide them
await click(`${STEPS_BUTTON_SELECTOR}:eq(0)`);
await contains(STEP_MSG_SELECTOR, { count: 0 });
await contains(TOOL_SUMMARY_SELECTOR, { count: 0 });
// final responses and preview should still be shown
await contains(RESPONSE_SELECTOR, { count: 2 });
await contains(PREVIEW_SELECTOR, { count: 1 });
// agent headers as well
await contains(AGENT_HEADER_SELECTOR, { count: 2 });
await contains(STEPS_BUTTON_SELECTOR, { count: 2 });
// open the second group of messages, containing one step msg and one tool summary
await click(`${STEPS_BUTTON_SELECTOR}:eq(1)`);
await contains(STEP_MSG_SELECTOR, { count: 1 });
await contains(TOOL_SUMMARY_SELECTOR, { count: 1 });
expect(queryOne(STEP_MSG_SELECTOR)).toHaveText("Preparing the follow-up");
expect(queryOne(TOOL_SUMMARY_SELECTOR)).toHaveText("Created a follow-up");
// both final responses and the preview should be shown
await contains(RESPONSE_SELECTOR, { count: 2 });
await contains(PREVIEW_SELECTOR, { count: 1 });
// agent headers as well
await contains(AGENT_HEADER_SELECTOR, { count: 2 });
await contains(STEPS_BUTTON_SELECTOR, { count: 2 });
});
test("incoming agent step are hidden until clicking on the tool status", async () => {
const pyEnv = await startServer();
const agentPartnerId = pyEnv["res.partner"].create({ name: "Agent Partner" });
const agentId = pyEnv["ai.agent"].create({
name: "Agent Partner",
partner_id: agentPartnerId,
});
const { channelId, sessionId } = createAIChat(pyEnv, agentId);
pyEnv["mail.message"].create({
author_id: serverState.partnerId,
body: "Previous user message",
message_type: "comment",
model: "discuss.channel",
res_id: channelId,
});
onRpc("/ai/start_session_advance", () => {
const channel = pyEnv["discuss.channel"].browse(channelId)[0];
pyEnv["discuss.channel"].message_post(
channelId,
makeKwArgs({
author_id: agentPartnerId,
body: '<div class="o-ai-agent-step">Searching the latest matching leads</div>',
message_type: "comment",
subtype_xmlid: "mail.mt_note",
}),
);
pyEnv["bus.bus"]._sendone(
channel,
"mail.record/insert",
new Store()
.add(pyEnv["ai.session"].browse(sessionId), {
toolStatus: "Searching matching leads",
loop_state: "waiting_model",
})
.as_dict(),
);
expect.step("agent_step");
return { loop_state: "waiting_model" };
});
await start();
await openDiscuss(channelId);
// a thread ending with a user message has no agent group or tool status
await contains(`${THREAD_SELECTOR} .o-mail-Message:has(:text('Previous user message'))`);
await contains(STEP_MSG_SELECTOR, { count: 0 });
await contains(AGENT_HEADER_SELECTOR, { count: 0 });
await contains(STEPS_BUTTON_SELECTOR, { count: 0 });
await contains(TOOL_STATUS_SELECTOR, { count: 0 });
await insertText(".o-mail-Composer-input", "Find matching leads");
await press("Enter");
await expect.waitForSteps(["agent_step"]);
// with Show Steps disabled, only the folded toolStatus should be shown
await contains(STEP_MSG_SELECTOR, { count: 0 });
await contains(AGENT_HEADER_SELECTOR, { count: 0 });
await contains(STEPS_BUTTON_SELECTOR, { count: 0 });
await contains(RESPONSE_SELECTOR, { count: 0 });
await contains(PREVIEW_SELECTOR, { count: 0 });
await contains(TOOL_STATUS_SELECTOR, { count: 1 });
await contains(`${TOOL_STATUS_SELECTOR}:is(button)`);
expect(queryOne(`${TOOL_STATUS_SELECTOR}:is(button)`)).toHaveText("Searching matching leads");
// clicking on the tool status reveals the agent header and the step message
await click(TOOL_STATUS_SELECTOR);
await contains(STEP_MSG_SELECTOR);
expect(queryOne(STEP_MSG_SELECTOR)).toHaveText("Searching the latest matching leads");
await contains(AGENT_HEADER_SELECTOR);
await contains(STEPS_BUTTON_SELECTOR);
// steps button is unfolded, no other message is shown
await contains(`${STEPS_BUTTON_SELECTOR} i[data-icon='expand_more']`);
await contains(RESPONSE_SELECTOR, { count: 0 });
await contains(PREVIEW_SELECTOR, { count: 0 });
await contains(TOOL_STATUS_SELECTOR);
// tool status is not a button anymore, just a text showing the current action
await contains(`${TOOL_STATUS_SELECTOR}:is(button)`, { count: 0 });
expect(queryOne(TOOL_STATUS_SELECTOR)).toHaveText("Searching matching leads");
// clicking on next steps folds the current group again
await click(STEPS_BUTTON_SELECTOR);
await contains(STEP_MSG_SELECTOR, { count: 0 });
await contains(AGENT_HEADER_SELECTOR, { count: 0 });
await contains(STEPS_BUTTON_SELECTOR, { count: 0 });
await contains(RESPONSE_SELECTOR, { count: 0 });
await contains(PREVIEW_SELECTOR, { count: 0 });
await contains(TOOL_STATUS_SELECTOR, { count: 1 });
await contains(`${TOOL_STATUS_SELECTOR}:is(button)`);
pyEnv["bus.bus"]._sendone(
pyEnv["discuss.channel"].browse(channelId)[0],
"mail.record/insert",
new Store()
.add(pyEnv["ai.session"].browse(sessionId), { loop_state: "ready", toolStatus: false })
.as_dict(),
);
await contains(TOOL_STATUS_SELECTOR, { count: 0 });
});
test("toggle-agent-steps action is shown", async () => {
const pyEnv = await startServer();
const agentPartnerId = pyEnv["res.partner"].create({ name: "Agent Partner" });
const agentId = pyEnv["ai.agent"].create({
name: "Agent Partner",
partner_id: agentPartnerId,
});
const { channelId } = createAIChat(pyEnv, agentId);
await start();
await openDiscuss(channelId);
await click(".o-mail-Composer button[title='More Actions']");
await contains(".o-dropdown-item[name='toggle-agent-steps']", { text: "Show Steps" });
});

View File

@@ -0,0 +1,241 @@
import { defineMailModels } from "@mail/../tests/mail_test_helpers";
import { AiPrompt } from "@ai/ai_prompt/ai_prompt";
import { setSelection } from "@html_editor/../tests/_helpers/selection";
import { insertText } from "@html_editor/../tests/_helpers/user_actions";
import {
defineModels,
fields,
models,
mountWithCleanup,
onRpc,
patchWithCleanup,
} from "@web/../tests/web_test_helpers";
import { beforeEach, describe, expect, test } from "@odoo/hoot";
import { click, queryOne } from "@odoo/hoot-dom";
import { animationFrame } from "@odoo/hoot-mock";
class Dummy extends models.Model {
_name = "dummy";
name = fields.Char();
message_ids = fields.One2many({ relation: "mail.message", string: "Messages" });
async mail_allowed_qweb_expressions() {
return ["object.display_name"];
}
async ai_find_default_records(comodel, domain, field_name, property_name) {
return [];
}
_records = [
{ id: 1, name: "Bob" },
{ id: 2, name: "Patrick" },
{ id: 3, name: "Sheldon" },
];
}
defineMailModels();
defineModels([Dummy]);
describe.current.tags("desktop");
let htmlEditor;
beforeEach(() => {
patchWithCleanup(AiPrompt.prototype, {
onEditorLoad(editor) {
htmlEditor = editor;
return super.onEditorLoad(...arguments);
},
});
});
let updatePromptVal = "";
test("AI Prompt - Readonly", async () => {
await mountWithCleanup(AiPrompt, {
props: {
readonly: true,
prompt: '<p>Hello <span data-ai-field="name">World</span></p>',
updatePrompt: () => {},
},
});
expect("span.o_readonly_ai_prompt").toHaveCount(1);
expect("span.o_readonly_ai_prompt").toHaveText("Hello World");
});
test("AI Prompt - Editable", async () => {
await mountWithCleanup(AiPrompt, {
props: {
model: "dummy",
updatePrompt: (change) => (updatePromptVal = change),
prompt: '<p>Hello <span data-ai-field="name">World</span></p>',
},
});
expect("div.o_ai_prompt").toHaveCount(1);
expect("div.o_ai_prompt").toHaveText("Hello World");
setSelection({ anchorNode: queryOne(".o_ai_prompt .odoo-editor-editable p"), anchorOffset: 4 });
await insertText(htmlEditor, " bloups");
await click(document.body);
expect(updatePromptVal).toBe(
'<p>Hello <span data-ai-field="name" data-oe-protected="true">World</span> bloups</p>'
);
});
test("AI Prompt - Field selector without template editor group", async () => {
onRpc("has_group", () => false);
await mountWithCleanup(AiPrompt, {
props: {
model: "dummy",
updatePrompt: (change) => (updatePromptVal = change),
prompt: "<p>Hello</p>",
},
});
setSelection({ anchorNode: queryOne(".o_ai_prompt .odoo-editor-editable p"), anchorOffset: 1 });
await insertText(htmlEditor, " /fie");
await animationFrame();
expect(".o-we-command").toHaveCount(1);
expect(".o-we-command .o-we-command-name").toHaveText("Field Selector");
await click(".o-we-command");
await animationFrame();
// only displayname available (see mail_allowed_qweb_expressions)
expect(".o_model_field_selector_popover_item").toHaveCount(1);
expect(".o_model_field_selector_popover_item_name").toHaveText("Display name");
await click(".o_model_field_selector_popover_item_name");
await animationFrame();
await click(document.body);
expect(updatePromptVal).toBe(
'<p>Hello <span data-ai-field="display_name" data-oe-protected="true">Display name</span>&nbsp;</p>'
);
// clicking on the field should reopen the field selector
await click("div.o_ai_prompt span[data-ai-field]");
await animationFrame();
expect(".o_model_field_selector_popover").toHaveCount(1);
});
test("AI Prompt - Field selector with template editor group", async () => {
await mountWithCleanup(AiPrompt, {
props: {
model: "dummy",
updatePrompt: (change) => (updatePromptVal = change),
prompt: "<p>Hello</p>",
},
});
setSelection({ anchorNode: queryOne(".o_ai_prompt .odoo-editor-editable p"), anchorOffset: 1 });
await insertText(htmlEditor, " /fiel");
await animationFrame();
await click(".o-we-command");
await animationFrame();
await click(".o_model_field_selector_popover_item_name:contains('Created on')");
await animationFrame();
await expect(".o_model_field_selector_popover .badge").toHaveCount(1);
await expect(".o_model_field_selector_popover .badge").toHaveText("Created on");
await expect(
".o_model_field_selector_popover_item_name:contains('Created on') i[data-icon='check']"
).toHaveCount(1);
await click(".o_model_field_selector_popover_item_name:contains('Display name')");
await animationFrame();
await expect(".o_model_field_selector_popover .badge").toHaveCount(2);
await click(".btn-primary");
await animationFrame();
await click(document.body);
expect(updatePromptVal).toBe(
`<p>Hello <span data-ai-field="create_date" data-oe-protected="true">Created on</span>, <span data-ai-field="display_name" data-oe-protected="true">Display name</span>&nbsp;</p>`
);
// clicking on the record should reopen the field selector
await click("div.o_ai_prompt span[data-ai-field]");
await animationFrame();
expect(".o_model_field_selector_popover").toHaveCount(1);
});
test("AI prompt - Insert messages", async () => {
await mountWithCleanup(AiPrompt, {
props: {
model: "dummy",
updatePrompt: (change) => (updatePromptVal = change),
prompt: "<p>Messages</p>",
},
});
setSelection({ anchorNode: queryOne(".o_ai_prompt .odoo-editor-editable p"), anchorOffset: 1 });
await insertText(htmlEditor, " /fiel");
await animationFrame();
await click(".o-we-command");
await animationFrame();
await click(".o_model_field_selector_popover_item_name:contains('Messages')");
await animationFrame();
await click(".btn-primary");
await animationFrame();
await click(document.body);
expect(updatePromptVal).toBe(
'<p>Messages <span data-ai-field="message_ids" data-oe-protected="true">Messages</span>&nbsp;</p>'
);
});
test("AI Prompt - Without comodel", async () => {
await mountWithCleanup(AiPrompt, {
props: {
model: "dummy",
updatePrompt: (change) => (updatePromptVal = change),
prompt: '<p>Hello <span data-ai-field="name">World</span></p>',
},
});
setSelection({ anchorNode: queryOne(".o_ai_prompt .odoo-editor-editable p"), anchorOffset: 1 });
await insertText(htmlEditor, "/rec");
await animationFrame();
// record selector should not be shown
expect(".o-we-command").toHaveCount(0);
});
test("AI Prompt - With comodel", async () => {
await mountWithCleanup(AiPrompt, {
props: {
comodel: "dummy",
domain: "[['id', 'in', [1, 2]]]",
model: "dummy",
updatePrompt: (change) => (updatePromptVal = change),
prompt: "<p>Hello</p>",
missingRecordsWarning: "Missing Records",
},
});
expect(".o_ai_prompt + .alert").toHaveText("Missing Records");
setSelection({ anchorNode: queryOne(".o_ai_prompt .odoo-editor-editable p"), anchorOffset: 1 });
insertText(htmlEditor, " /rec");
await animationFrame();
expect(".o-we-command").toHaveCount(1);
expect(".o-we-command-name").toHaveText("Records Selector");
await click(".o-we-command");
await animationFrame();
await click(".o_records_selector_popover input");
await animationFrame();
// filtered using the domain
expect(".o-autocomplete--dropdown-item").toHaveCount(2);
await click(".o-autocomplete--dropdown-item:contains('Bob')");
await animationFrame();
await click(".o_records_selector_popover input");
await animationFrame();
expect(".o-autocomplete--dropdown-item").toHaveCount(1);
await click(".o-autocomplete--dropdown-item:contains('Patrick')");
await animationFrame();
await click(".o_records_selector_popover .btn-primary");
await animationFrame();
await click(document.body);
expect(updatePromptVal).toBe(
'<p>Hello <span data-ai-record-id="1" data-oe-protected="true">Bob</span>, <span data-ai-record-id="2" data-oe-protected="true">Patrick</span>&nbsp;</p>'
);
// clicking on the record should reopen the field selector
await click("div.o_ai_prompt span[data-ai-record-id]");
await animationFrame();
expect(".o_records_selector_popover").toHaveCount(1);
});
test("AI Prompt - Invalid records", async () => {
await mountWithCleanup(AiPrompt, {
props: {
comodel: "dummy",
model: "dummy",
updatePrompt: () => {},
prompt: '<p>Hello <span data-oe-protected data-ai-record-id="5">Larry</span></p>',
},
});
expect(".o_ai_prompt").toHaveText("Hello Invalid Record");
});

View File

@@ -0,0 +1,29 @@
import { mailModels } from "@mail/../tests/mail_test_helpers";
import { AIAgent, AIAgentSource } from "./mock_server/mock_models/ai_agent";
import { Partner } from "./mock_server/mock_models/res_partner";
import { defineModels } from "@web/../tests/web_test_helpers";
import { AIComposer } from "./mock_server/mock_models/ai_composer";
import { AIPromptButton } from "./mock_server/mock_models/ai_prompt_button";
import { AISession } from "./mock_server/mock_models/ai_session";
import { DiscussChannel } from "./mock_server/mock_models/discuss_channel";
export function defineAIModels() {
return defineModels(aiModels);
}
export function createAIChat(pyEnv, agentId) {
const channelId = pyEnv["ai.agent"].browse(agentId)._create_ai_chat_channel();
const sessionId = pyEnv["ai.session"].create({ agent_id: agentId, channel_id: channelId });
return { channelId, sessionId };
}
export const aiModels = {
...mailModels,
AIAgent,
AIComposer,
AIPromptButton,
AISession,
AIAgentSource,
DiscussChannel,
Partner,
};

View File

@@ -0,0 +1,40 @@
import { expect, test } from "@odoo/hoot";
import { animationFrame } from "@odoo/hoot-mock";
import { Component, signal, xml } from "@odoo/owl";
import { defineMailModels } from "@mail/../tests/mail_test_helpers";
import { mountWithCleanup } from "@web/../tests/web_test_helpers";
import { AudioVisualizer } from "@ai/components/audio_visualizer/audio_visualizer";
defineMailModels();
function barHeights() {
return [...document.querySelectorAll(".o-ai-audio-visualizer-bar")].map((bar) =>
parseFloat(bar.style.height)
);
}
test("audio visualizer bar heights reactively follow the frequencies prop", async () => {
const frequencies = signal(new Uint8Array(128).fill(0));
class Container extends Component {
static components = { AudioVisualizer };
static template = xml`
<div style="width: 200px;">
<AudioVisualizer frequencies="this.frequencies()" maxHeight="32"/>
</div>`;
setup() {
this.frequencies = frequencies;
}
}
await mountWithCleanup(Container);
await animationFrame();
await animationFrame();
expect(barHeights().every((h) => h === 0)).toBe(true);
frequencies.set(new Uint8Array(128).fill(255));
await animationFrame();
expect(barHeights().some((h) => h > 0)).toBe(true);
});

View File

@@ -0,0 +1,358 @@
import { expect, describe, test } from "@odoo/hoot";
import { animationFrame } from "@odoo/hoot-mock";
import { click, queryAll, queryOne } from "@odoo/hoot-dom";
import { contains, startServer, start, openFormView, mailModels } from "@mail/../tests/mail_test_helpers";
import { fields, models, defineModels, patchWithCleanup } from "@web/../tests/web_test_helpers";
import { CallDebrief } from "@mail/views/fields/call_debrief/call_debrief";
describe.current.tags("desktop", "call_debrief");
class MailCallArtifact extends models.Model {
_name = "mail.call.artifact";
transcript = fields.Text();
is_stt = fields.Boolean();
media_id = fields.Many2one({ relation: "ir.attachment" });
recording_upload_pending = fields.Boolean();
start_ms = fields.Integer();
end_ms = fields.Integer();
test_record_id = fields.Many2one({ relation: "test.call.record" });
}
class TestCallRecord extends models.Model {
_name = "test.call.record";
start_date = fields.Datetime();
end_date = fields.Datetime();
artifact_ids = fields.One2many({
relation: "mail.call.artifact",
relation_field: "test_record_id",
});
}
defineModels({ ...mailModels, MailCallArtifact, TestCallRecord });
const AUDIO_FIXTURE_URL = "/mail/static/tests/fixtures/audio_60s.webm";
const VIDEO_FIXTURE_URL = "/mail/static/tests/fixtures/video_60s.webm";
/**
* Creates a media artifact (audio or video) that maps to the 60-second fixture.
* @param {Object} pyEnv The python environment
* @param {Object} options
* @param {number} options.start Start time in seconds relative to the call
* @param {string} [options.type="audio"] "audio" or "video"
* @returns {number} The created artifact ID
*/
function _createRecording(pyEnv, { start = 0, type = "audio" } = {}) {
const duration = 60; // Always 60s to match the fixture length
const attachmentId = pyEnv["ir.attachment"].create({
name: `fixture_${start}_${type}.webm`,
mimetype: type === "video" ? "video/webm" : "audio/webm",
});
return pyEnv["mail.call.artifact"].create({
media_id: attachmentId,
is_stt: false,
start_ms: start * 1000,
end_ms: (start + duration) * 1000,
});
}
function _setupCallDebriefPatch() {
patchWithCleanup(CallDebrief.prototype, {
async _loadData(props) {
await super._loadData(props);
if (!this.state.mediaSegments) {
return;
}
// Automatically inject the correct static fixture URL based on type
for (const segment of this.state.mediaSegments) {
segment.mediaUrl = segment.type === "video" ? VIDEO_FIXTURE_URL : AUDIO_FIXTURE_URL;
}
},
});
}
async function _openDebriefView(pyEnv, testRecordId) {
await openFormView("test.call.record", testRecordId, {
arch: `
<form>
<field name="start_date" invisible="1"/>
<field name="end_date" invisible="1"/>
<field name="artifact_ids" widget="call_debrief" options="{'callStartDateField': 'start_date', 'callEndDateField': 'end_date'}"/>
</form>
`,
});
}
test("CallDebrief: transcript only interactions", async () => {
const pyEnv = await startServer();
const testRecordId = pyEnv["test.call.record"].create({
start_date: "2023-01-01 10:00:00",
end_date: "2023-01-01 10:00:10",
artifact_ids: [
pyEnv["mail.call.artifact"].create({
transcript: "1\n00:00:01,000 --> 00:00:03,000\nHello world",
is_stt: true,
start_ms: 0,
end_ms: 10000,
}),
],
});
await start();
await _openDebriefView(pyEnv, testRecordId);
expect(".o-CallDebrief-media-container").toHaveClass("o-CallDebrief-media-container--no-video");
const line = queryOne("p[data-timestamp]");
await click(line);
await animationFrame();
expect(".o-CallDebriefTimeline-timestamp").toHaveText("00:01");
});
test("CallDebrief: transcript gap detection", async () => {
const pyEnv = await startServer();
const testRecordId = pyEnv["test.call.record"].create({
start_date: "2023-01-01 10:00:00",
end_date: "2023-01-01 10:00:20",
artifact_ids: [
pyEnv["mail.call.artifact"].create({
transcript:
"1\n00:00:01,000 --> 00:00:03,000\nHello\n\n2\n00:00:08,000 --> 00:00:10,000\nWorld",
is_stt: true,
start_ms: 0,
end_ms: 20000,
}),
],
});
await start();
await _openDebriefView(pyEnv, testRecordId);
const gaps = queryAll(".o-CallDebrief-transcript-gap");
expect(gaps).toHaveCount(1, { message: "Should detect exactly one gap." });
// Gap should represent the 5s difference between 00:03 and 00:08
expect(gaps[0]).toHaveText("silence (00:05)");
const lines = queryAll("p[data-timestamp]");
expect(lines).toHaveCount(2, { message: "Should render both spoken lines." });
});
test("CallDebrief: renders video and transcript with playback", async () => {
_setupCallDebriefPatch();
const pyEnv = await startServer();
const transcriptSourceId = pyEnv["ir.attachment"].create({
name: "transcription_source.ogg",
mimetype: "audio/ogg",
});
const transcriptId = pyEnv["mail.call.artifact"].create({
transcript: "1\n00:00:01,000 --> 00:00:03,000\nHello world",
is_stt: true,
media_id: transcriptSourceId,
start_ms: 0,
end_ms: 60000,
});
const videoId = _createRecording(pyEnv, { start: 0, type: "video" });
const testRecordId = pyEnv["test.call.record"].create({
start_date: "2023-01-01 10:00:00",
end_date: "2023-01-01 10:01:00", // 60s call
artifact_ids: [transcriptId, videoId],
});
await start();
await _openDebriefView(pyEnv, testRecordId);
expect(".o-CallDebrief-media-container").not.toHaveClass(
"o-CallDebrief-media-container--no-video"
);
await contains(".o-CallDebrief-video video");
await contains("audio", { count: 0 });
await contains(".o-CallDebrief-transcript-text", { text: "Hello world" });
// Mute first to avoid noise
await click("button.o-CallDebrief-muteBtn");
// Start playback
const video = queryOne("video");
const playingPromise = new Promise((r) => video.addEventListener("playing", r, { once: true }));
await click("[data-icon='play_arrow']");
await animationFrame();
expect("[data-icon='pause']").toHaveCount(1);
// Wait for actual playback to start before pausing
await playingPromise;
// Stop playback to avoid AbortError when the test destroys the video element
await click("[data-icon='pause']");
await animationFrame();
});
test("CallDebrief: timeline-transcript-media synchronization", async () => {
_setupCallDebriefPatch();
const pyEnv = await startServer();
// Create 3 segments of 60s each = 180s total duration
const art1 = _createRecording(pyEnv, { start: 0, type: "audio" });
const art2 = _createRecording(pyEnv, { start: 60, type: "audio" });
const art3 = _createRecording(pyEnv, { start: 120, type: "audio" });
// Transcripts associated with each segment time range
const trans1 = pyEnv["mail.call.artifact"].create({
transcript: "1\n00:00:05,000 --> 00:00:08,000\nSegment 1 Text",
is_stt: true,
start_ms: 0,
end_ms: 60000,
});
const trans2 = pyEnv["mail.call.artifact"].create({
// Relative 2s -> Global 62s
transcript: "1\n00:00:02,000 --> 00:00:04,000\nSegment 2 Text",
is_stt: true,
start_ms: 60000,
end_ms: 120000,
});
const trans3 = pyEnv["mail.call.artifact"].create({
// Relative 5s -> Global 125s
transcript: "1\n00:00:05,000 --> 00:00:07,000\nSegment 3 Text",
is_stt: true,
start_ms: 120000,
end_ms: 180000,
});
const testRecordId = pyEnv["test.call.record"].create({
start_date: "2023-01-01 10:00:00",
end_date: "2023-01-01 10:03:00",
artifact_ids: [art1, trans1, art2, trans2, art3, trans3],
});
await start();
await _openDebriefView(pyEnv, testRecordId);
await animationFrame();
// Ensure Segment 1's initial audio element is loaded before we click or interact with it
const initialAudio = queryOne("audio");
if (
initialAudio &&
[HTMLMediaElement.HAVE_NOTHING, HTMLMediaElement.HAVE_METADATA].includes(
initialAudio.readyState
)
) {
await new Promise((r) => initialAudio.addEventListener("loadeddata", r, { once: true }));
}
const lines = queryAll("p[data-timestamp]");
// Select transcript line -> Adjusts playhead and audio
await click(lines[0]);
await animationFrame();
expect(".o-CallDebriefTimeline-timestamp").toHaveText("00:05");
expect(lines[0]).toHaveClass("o-CallDebrief-transcript-highlight");
const audioTime1 = queryOne("audio").currentTime;
expect(Math.abs(audioTime1 - 5) <= 1).toBe(true, {
message: `Audio currentTime should be close to 5s, but was ${audioTime1}`,
});
// Fire timeupdate to clear the skipNextTimeUpdate flag that was set by the line click
queryOne("audio").dispatchEvent(new Event("timeupdate"));
// Move playhead -> Seeks audio and scroll to nearest transcript line
// Clicking the timeline defaults to center (50%). Total duration 180s -> 90s (01:30).
await click(".o-CallDebriefTimeline");
await animationFrame();
const timestampText = queryOne(".o-CallDebriefTimeline-timestamp").innerText;
const [minutes, seconds] = timestampText.split(":").map(Number);
const totalSeconds = minutes * 60 + seconds;
expect(Math.abs(totalSeconds - 90) <= 2).toBe(true, {
message: `Playhead should move close to 90s (01:30), but was ${timestampText}`,
});
// 90s is closer to Segment 2 (62s) than Segment 3 (125s)
expect(lines[1]).toHaveClass("o-CallDebrief-transcript-highlight");
// Global 90s is 30s relative to Segment 2 (starts at 60s)
const audioTime2 = queryOne("audio").currentTime;
expect(Math.abs(audioTime2 - 30) <= 1).toBe(true, {
message: `Audio currentTime should be close to 30s, but was ${audioTime2}`,
});
// Media timestamp change (simulates playing) -> Updates playhead position and transcript highlight
const audio = queryOne("audio");
audio.currentTime = 6;
// Wait for the seek to complete so the `seeking` flag becomes false, otherwise onTimeUpdate skips the event
await new Promise((r) => audio.addEventListener("seeked", r, { once: true }));
audio.dispatchEvent(new Event("timeupdate"));
await animationFrame();
const finalTimestampText = queryOne(
".o-CallDebriefMediaControls-timeLabel .o_current_time"
).innerText;
const [finalM, finalS] = finalTimestampText.split(":").map(Number);
const finalTotalSeconds = finalM * 60 + finalS;
// Segment 2 starts at 60s, so 60 + 6 = 66s (01:06)
expect(Math.abs(finalTotalSeconds - 66) <= 1).toBe(true, {
message: `Timestamp should be close to 66s (01:06), but was ${finalTimestampText}`,
});
// Global 66s is within Segment 2, so the second transcript line (starts at 62s) should be highlighted
expect(lines[1]).toHaveClass("o-CallDebrief-transcript-highlight");
});
test("CallDebrief: skips STT artifacts from playable segments", async () => {
_setupCallDebriefPatch();
const pyEnv = await startServer();
// Create 1 standard audio recording and 1 parallel pending STT artifact (both covering 0s to 60s)
const audioId = _createRecording(pyEnv, { start: 0, type: "audio" });
const transcriptAttachmentId = pyEnv["ir.attachment"].create({
name: "stt_audio.webm",
mimetype: "audio/webm",
});
const transcriptId = pyEnv["mail.call.artifact"].create({
media_id: transcriptAttachmentId,
transcript: "1\n00:00:01,000 --> 00:00:03,000\nHello world",
is_stt: true,
start_ms: 0,
end_ms: 60000,
});
const testRecordId = pyEnv["test.call.record"].create({
start_date: "2023-01-01 10:00:00",
end_date: "2023-01-01 10:01:00", // 60s call
artifact_ids: [audioId, transcriptId],
});
await start();
await _openDebriefView(pyEnv, testRecordId);
await animationFrame();
// The STT artifact must be skipped from the timeline (only 1 media segment should be rendered)
expect(".o-CallDebriefTimeline-media-segment").toHaveCount(1, {
message: "Only the standard recording should be rendered on the timeline, not the STT artifact.",
});
// The transcript itself must still load and render correctly
expect("p[data-timestamp]").toHaveCount(1, {
message: "The transcript should still render correctly.",
});
});
test("CallDebrief: skips pending media without hiding its transcript", async () => {
const pyEnv = await startServer();
const mediaId = _createRecording(pyEnv, { type: "video" });
pyEnv["mail.call.artifact"].write([mediaId], { recording_upload_pending: true });
const transcriptId = pyEnv["mail.call.artifact"].create({
transcript: "1\n00:00:01,000 --> 00:00:03,000\nHello world",
is_stt: true,
start_ms: 0,
end_ms: 60000,
});
const testRecordId = pyEnv["test.call.record"].create({
start_date: "2023-01-01 10:00:00",
end_date: "2023-01-01 10:01:00",
artifact_ids: [mediaId, transcriptId],
});
await start();
await _openDebriefView(pyEnv, testRecordId);
await contains(".o-CallDebrief-transcript-text", { text: "Hello world" });
await contains(".o-CallDebriefTimeline-media-segment", { count: 0 });
await contains("video, audio", { count: 0 });
});

View File

@@ -0,0 +1,73 @@
import { runOneWayClientToolBatch } from "@ai/discuss/core/common/ai_client_tool_service";
import { aiSessionIdentifier } from "@ai/utils/ai_session_identifier";
import {
click,
contains,
insertText,
openFormView,
start,
startServer,
} from "@mail/../tests/mail_test_helpers";
import { test } from "@odoo/hoot";
import { Command, getService, onRpc, serverState } from "@web/../tests/web_test_helpers";
import { defineAIModels } from "./ai_test_helpers";
defineAIModels();
test.tags("desktop");
test("closing the full composer after the AI agent navigated away should not crash", async () => {
const pyEnv = await startServer();
const partnerId = pyEnv["res.partner"].create({ name: "Abigail Peterson" });
const agentPartnerId = pyEnv["res.partner"].create({ name: "Agent Partner" });
const aiAgentId = pyEnv["ai.agent"].create({
name: "Agent Partner",
partner_id: agentPartnerId,
});
const channelId = pyEnv["discuss.channel"].create({
channel_member_ids: [
Command.create({ partner_id: serverState.partnerId }),
Command.create({ partner_id: agentPartnerId }),
],
channel_type: "ai_chat",
ai_agent_id: aiAgentId,
});
pyEnv["ai.session"].create({ agent_id: aiAgentId, channel_id: channelId });
onRpc("/ai/start_session_advance", () => ({ loop_state: "waiting_model" }));
await start();
await openFormView("res.partner", partnerId);
await contains(".o-mail-Chatter");
await click("button", { text: "Send message" });
await insertText(".o-mail-Composer-input", "hey");
await click("button[title='Open Full Composer']");
await contains(".o_dialog .o_form_view");
// Simulate the AI agent navigating to another view while the full
// composer dialog is still open: this tears down the current form view,
// and with it the chatter of the partner, underneath the still-open
// dialog.
const channel = await getService("mail.store")["discuss.channel"].getOrFetch(channelId);
await channel.post("show me all my contacts in the US");
await runOneWayClientToolBatch(getService("mail.store"), {
channel_id: channelId,
aiSessionIdentifier,
commands: [
{
name: "show_view",
params: {
action: {
type: "ir.actions.act_window",
name: "Contacts",
res_model: "res.partner",
views: [[false, "list"]],
},
options: { clearBreadcrumbs: true },
},
oneway: true,
},
],
});
await contains(".o_list_view");
await contains(".o-mail-Chatter", { count: 0 });
// make sure composer dialog is closed
await contains(".o_dialog", { count: 0 });
});

View File

@@ -0,0 +1,306 @@
import { aiSessionIdentifier } from "@ai/utils/ai_session_identifier";
import { runOneWayClientToolBatch } from "@ai/discuss/core/common/ai_client_tool_service";
import {
click,
contains,
insertText,
setupChatHub,
start,
startServer,
} from "@mail/../tests/mail_test_helpers";
import { before, beforeEach, describe, expect, test } from "@odoo/hoot";
import { press } from "@odoo/hoot-dom";
import {
Command,
MockServer,
getService,
mockService,
onRpc,
serverState,
} from "@web/../tests/web_test_helpers";
import { registry } from "@web/core/registry";
import { defineAIModels } from "./ai_test_helpers";
describe.current.tags("desktop");
defineAIModels();
/**
* Registers an AI tool for the duration of the current test.
* The tool is added before the test runs and removed after.
*
* @param {string} name
* @param {(thread, params) => Promise<void>} handler
*/
function withAITool(name, handler) {
before(() => {
const aiTools = registry.category("ai.client_tools");
aiTools.add(name, handler);
return () => aiTools.remove(name);
});
}
let channelId, channel;
beforeEach(async () => {
const pyEnv = await startServer();
const partnerId = pyEnv["res.partner"].create({ name: "Agent Partner" });
const aiAgentId = pyEnv["ai.agent"].create({
name: "Agent Partner",
partner_id: partnerId,
});
channelId = pyEnv["discuss.channel"].create({
channel_member_ids: [
Command.create({ partner_id: serverState.partnerId }),
Command.create({ partner_id: partnerId }),
],
channel_type: "ai_chat",
ai_agent_id: aiAgentId,
ai_session_ids: [Command.create({ agent_id: aiAgentId })],
});
[channel] = pyEnv["discuss.channel"].search_read([["id", "=", channelId]]);
});
async function postInChatWindow(text) {
await contains(".o-mail-ChatWindow");
await click(".o-mail-ChatWindow .o-mail-Composer-input");
await insertText(".o-mail-ChatWindow .o-mail-Composer-input", text);
await press("Enter");
}
test("Oneway tool request is dispatched to handler in tool registry", async () => {
withAITool("dummy_tool", async (thread, params) => {
expect.step(`dummy_tool:${params.greeting}`);
expect(thread.id).toBe(channelId);
});
onRpc("/ai/start_session_advance", () => {
expect.step("start session advance");
return { loop_state: "waiting_model" };
});
setupChatHub({ opened: [channelId] });
await start();
await postInChatWindow("do the thing");
await expect.waitForSteps(["start session advance"]);
MockServer.env["bus.bus"]._sendone(channel, "ai.session/client_tools", {
channel_id: channelId,
aiSessionIdentifier,
commands: [
{
name: "dummy_tool",
params: { greeting: "hello" },
oneway: true,
},
],
});
await expect.waitForSteps(["dummy_tool:hello"]);
});
test("Client tool result is sent in a follow-up request", async () => {
const [sessionId] = MockServer.env["ai.session"].search([["channel_id", "=", channelId]]);
const resumeToken = "client-result-token";
withAITool("get_client_data", async (thread, params) => {
expect.step(`get_client_data:${params.key}`);
expect(thread.id).toBe(channelId);
return { clientValue: 42 };
});
onRpc("/ai/start_session_advance", async (request) => {
const { params } = await request.json();
expect("response" in params).toBe(false);
expect(params.ai_session_identifier).toBe(aiSessionIdentifier);
expect.step("start session advance");
return { loop_state: "waiting_model" };
});
onRpc("/ai/resume_pending_interaction", async (request) => {
const { params } = await request.json();
expect(params.channel_id).toBe(channelId);
expect(params.ai_session_identifier).toBe(aiSessionIdentifier);
expect(params.session_id).toBe(sessionId);
expect(params.resume_token).toBe(resumeToken);
expect("mail_message_id" in params).toBe(false);
expect(params.response).toEqual({
kind: "client_result",
value: { clientValue: 42 },
});
expect.step("client result submitted");
return { loop_state: "waiting_model" };
});
setupChatHub({ opened: [channelId] });
await start();
await postInChatWindow("get client data");
await expect.waitForSteps(["start session advance"]);
MockServer.env["bus.bus"]._sendone(channel, "mail.record/insert", {
"ai.session": [
{
id: sessionId,
loop_state: "waiting_client_result",
clientToolRequest: {
aiSessionIdentifier,
name: "get_client_data",
params: { key: "value" },
resumeToken,
},
},
],
});
await expect.waitForSteps(["get_client_data:value", "client result submitted"]);
});
test("Client tool error is sent in a follow-up request", async () => {
const [sessionId] = MockServer.env["ai.session"].search([["channel_id", "=", channelId]]);
const resumeToken = "client-error-token";
withAITool("get_client_data", async () => {
expect.step("get_client_data");
throw new Error("Client tool failed");
});
onRpc("/ai/start_session_advance", () => {
expect.step("start session advance");
return { loop_state: "waiting_model" };
});
onRpc("/ai/resume_pending_interaction", async (request) => {
const { params } = await request.json();
expect(params.channel_id).toBe(channelId);
expect(params.ai_session_identifier).toBe(aiSessionIdentifier);
expect(params.session_id).toBe(sessionId);
expect(params.resume_token).toBe(resumeToken);
expect("mail_message_id" in params).toBe(false);
expect(params.response).toEqual({
kind: "client_error",
value: "Client tool failed",
});
expect.step("client error submitted");
return { loop_state: "waiting_model" };
});
setupChatHub({ opened: [channelId] });
await start();
await postInChatWindow("get client data");
await expect.waitForSteps(["start session advance"]);
MockServer.env["bus.bus"]._sendone(channel, "mail.record/insert", {
"ai.session": [
{
id: sessionId,
loop_state: "waiting_client_result",
clientToolRequest: {
aiSessionIdentifier,
name: "get_client_data",
params: {},
resumeToken,
},
},
],
});
await expect.waitForSteps(["get_client_data", "client error submitted"]);
});
test("Reload runs once after oneway tools", async () => {
withAITool("first_tool", async () => expect.step("first"));
mockService("action", {
doAction(action) {
expect(action.tag).toBe("soft_reload");
expect.step("reload");
},
});
onRpc("/ai/start_session_advance", () => {
expect.step("start session advance");
return { loop_state: "waiting_model" };
});
setupChatHub({ opened: [channelId] });
await start();
await postInChatWindow("do the thing");
await expect.waitForSteps(["start session advance"]);
MockServer.env["bus.bus"]._sendone(channel, "ai.session/client_tools", {
channel_id: channelId,
aiSessionIdentifier,
commands: [
{ name: "reload", oneway: true },
{ name: "reload", oneway: true },
{ name: "first_tool", oneway: true },
],
});
await expect.waitForSteps(["first", "reload"]);
});
test("Reload without oneway sends its result in a follow-up request", async () => {
const [sessionId] = MockServer.env["ai.session"].search([["channel_id", "=", channelId]]);
const resumeToken = "reload-result-token";
mockService("action", {
doAction(action) {
expect(action.tag).toBe("soft_reload");
expect.step("reload");
},
});
onRpc("/ai/start_session_advance", () => {
expect.step("start session advance");
return { loop_state: "waiting_model" };
});
onRpc("/ai/resume_pending_interaction", async (request) => {
const { params } = await request.json();
expect(params.channel_id).toBe(channelId);
expect(params.ai_session_identifier).toBe(aiSessionIdentifier);
expect(params.session_id).toBe(sessionId);
expect(params.resume_token).toBe(resumeToken);
expect("mail_message_id" in params).toBe(false);
expect(params.response).toEqual({
kind: "client_result",
value: "Success",
});
expect.step("reload result submitted");
return { loop_state: "waiting_model" };
});
setupChatHub({ opened: [channelId] });
await start();
await postInChatWindow("reload");
await expect.waitForSteps(["start session advance"]);
MockServer.env["bus.bus"]._sendone(channel, "mail.record/insert", {
"ai.session": [
{
id: sessionId,
loop_state: "waiting_client_result",
clientToolRequest: {
aiSessionIdentifier,
name: "reload",
params: {},
resumeToken,
},
},
],
});
await expect.waitForSteps(["reload", "reload result submitted"]);
});
test("Client tools only execute and submit results in the requesting tab", async () => {
const [sessionId] = MockServer.env["ai.session"].search([["channel_id", "=", channelId]]);
withAITool("dummy_tool", async () => expect.step("oneway executed"));
withAITool("get_client_data", async () => {
expect.step("pending executed");
return "result";
});
onRpc("/ai/resume_pending_interaction", async (request) => {
const { params } = await request.json();
expect(params.ai_session_identifier).toBe(aiSessionIdentifier);
expect(params.response).toEqual({ kind: "client_result", value: "result" });
expect.step("result submitted");
return { loop_state: "ready" };
});
setupChatHub({ opened: [channelId] });
await start();
const store = getService("mail.store");
const session = store["ai.session"].get(sessionId);
const payload = {
channel_id: channelId,
aiSessionIdentifier: "another-tab",
commands: [{ name: "dummy_tool", params: {}, oneway: true }],
};
const request = {
aiSessionIdentifier: "another-tab",
name: "get_client_data",
params: {},
resumeToken: "same-command",
};
await runOneWayClientToolBatch(store, payload);
session.clientToolRequest = request;
await session.processPendingClientTool();
expect.verifySteps([]);
await runOneWayClientToolBatch(store, { ...payload, aiSessionIdentifier });
session.clientToolRequest = { ...request, aiSessionIdentifier };
await expect.waitForSteps(["oneway executed", "pending executed", "result submitted"]);
});

View File

@@ -0,0 +1,249 @@
import {
click,
contains,
insertText,
setupChatHub,
start,
startServer,
} from "@mail/../tests/mail_test_helpers";
import { describe, expect, test } from "@odoo/hoot";
import { press } from "@odoo/hoot-dom";
import { onRpc } from "@web/../tests/web_test_helpers";
import { createAIChat, defineAIModels } from "../ai_test_helpers";
describe.current.tags("desktop");
defineAIModels();
const COMPOSER_SELECTOR = ".o-mail-Composer";
const INPUT_REQUEST_SELECTOR = ".o_ai_user_input_request";
const EXTERNAL_WAIT_SELECTOR = ".o_ai_external_pending_tool";
async function startAIChat(sessionValues, messageBodies = ["What should I do?"]) {
const pyEnv = await startServer();
const agentPartnerId = pyEnv["res.partner"].create({ name: "AI Agent" });
const agentId = pyEnv["ai.agent"].create({
name: "AI Agent",
partner_id: agentPartnerId,
});
const { channelId, sessionId } = createAIChat(pyEnv, agentId);
const userInputRequest = sessionValues.user_input_request;
if (userInputRequest) {
sessionValues = {
loop_state: userInputRequest.type === "confirmation" ? "waiting_confirmation" : "waiting_answer",
...sessionValues,
user_input_request: {
resumeToken: "durable-user-input-token",
...userInputRequest,
},
};
}
pyEnv["ai.session"].write([sessionId], sessionValues);
for (const body of messageBodies) {
pyEnv["mail.message"].create({
author_id: agentPartnerId,
body,
message_type: "comment",
model: "discuss.channel",
res_id: channelId,
});
}
setupChatHub({ opened: [channelId] });
await start();
await contains(".o-mail-ChatWindow");
return { channelId, sessionId, pyEnv };
}
test("request is rendered once separately from AI messages", async () => {
await startAIChat(
{
user_input_request: {
choices: [
{ label: "One", value: "one" },
{ label: "Two", value: "two" },
],
multiSelect: false,
type: "question",
},
},
["Older AI message", "Newest AI message"],
);
await contains(".o-mail-Message", { count: 2 });
await contains(INPUT_REQUEST_SELECTOR, { count: 1 });
await contains(`.o-mail-Message ${INPUT_REQUEST_SELECTOR}`, { count: 0 });
await contains(".o-mail-Message:has(:text('Newest AI message')) .o-mail-Message-actions", {
count: 0,
});
await contains(".o-mail-Message:has(:text('Older AI message')) .o-mail-Message-actions");
});
test("pending external tool freezes the composer while showing a progress indicator", async () => {
await startAIChat(
{
external_pending_tool: true,
loop_state: "waiting_external_result",
resume_token: "durable-external-tool-token",
},
["Older AI message", "The external task has started."],
);
await contains(EXTERNAL_WAIT_SELECTOR, { count: 1 });
await contains(
`.o-mail-Message:has(:text('The external task has started.')) ${EXTERNAL_WAIT_SELECTOR} .oi-spin`
);
await contains(INPUT_REQUEST_SELECTOR, { count: 0 });
await contains(COMPOSER_SELECTOR, { count: 0 });
// Cancel is the only way out of a wait whose external result never arrives.
await contains(`${EXTERNAL_WAIT_SELECTOR} .o_ai_cancel_external`);
});
test("cancelling a pending external tool aborts it and frees the composer", async () => {
onRpc("/ai/resume_pending_interaction", async (request) => {
const { params } = await request.json();
expect(params.channel_id).toBe(channelId);
expect(params.session_id).toBe(sessionId);
expect(params.resume_token).toBe("durable-external-tool-token");
expect(params.response).toEqual({ kind: "skip" });
expect.step("pending tools aborted");
return { loop_state: "ready", interactionConsumed: true };
});
const { channelId, sessionId } = await startAIChat(
{
external_pending_tool: true,
loop_state: "waiting_external_result",
resume_token: "durable-external-tool-token",
},
["The external task has started."],
);
await click(`${EXTERNAL_WAIT_SELECTOR} .o_ai_cancel_external`);
await expect.waitForSteps(["pending tools aborted"]);
await contains(EXTERNAL_WAIT_SELECTOR, { count: 0 });
// the composer is usable again, so the chat is not frozen on a dead wait
await contains(COMPOSER_SELECTOR);
});
test("single choice submits the question answer and hides the choices", async () => {
onRpc("/ai/resume_pending_interaction", async (request) => {
const { params } = await request.json();
expect(params.response).toEqual({
kind: "question",
value: ["draft"],
});
expect(params.resume_token).toBe("durable-user-input-token");
expect.step("answer submitted");
return { loop_state: "waiting_model" };
});
await startAIChat({
user_input_request: {
choices: [
{ label: "Create a draft", value: "draft" },
{ label: "Send it now", value: "send" },
],
multiSelect: false,
allowFreeText: true,
type: "question",
},
});
await contains(`${INPUT_REQUEST_SELECTOR} button:contains('Create a draft')`);
await contains(`${INPUT_REQUEST_SELECTOR} button:contains('Send it now')`);
await contains(`${INPUT_REQUEST_SELECTOR} input[placeholder='Something else']`);
await contains(".o-mail-Message-actions", { count: 0 });
// the composer is hidden while a question is pending
await contains(COMPOSER_SELECTOR, { count: 0 });
await click(`${INPUT_REQUEST_SELECTOR} button:contains('Create a draft')`);
await expect.waitForSteps(["answer submitted"]);
await contains(INPUT_REQUEST_SELECTOR, { count: 0 });
await contains(COMPOSER_SELECTOR);
await contains(".o-mail-Message-actions");
});
test("free text submits the question answer with the typed value", async () => {
onRpc("/ai/resume_pending_interaction", async (request) => {
const { params } = await request.json();
expect(params.response).toEqual({
kind: "question",
value: ["Neither, cancel it"],
});
expect.step("answer submitted");
return { loop_state: "waiting_model" };
});
await startAIChat({
user_input_request: {
choices: [
{ label: "Create a draft", value: "draft" },
{ label: "Send it now", value: "send" },
],
multiSelect: false,
allowFreeText: true,
type: "question",
},
});
await insertText(
`${INPUT_REQUEST_SELECTOR} input[placeholder='Something else']`,
"Neither, cancel it",
);
await press("Enter");
await expect.waitForSteps(["answer submitted"]);
await contains(INPUT_REQUEST_SELECTOR, { count: 0 });
});
test("multi-select submits selected values in choice order", async () => {
onRpc("/ai/resume_pending_interaction", async (request) => {
const { params } = await request.json();
expect(params.response).toEqual({
kind: "question",
value: ["first", "third"],
});
expect.step("multi-select submitted");
return { loop_state: "waiting_model" };
});
await startAIChat({
user_input_request: {
choices: [
{ label: "First", value: "first" },
{ label: "Second", value: "second" },
{ label: "Third", value: "third" },
],
multiSelect: true,
type: "question",
},
});
await contains(`${INPUT_REQUEST_SELECTOR} button:contains('Confirm'):disabled`);
await click(`${INPUT_REQUEST_SELECTOR} button:contains('Third')`);
await click(`${INPUT_REQUEST_SELECTOR} button:contains('First')`);
await click(`${INPUT_REQUEST_SELECTOR} button:contains('Confirm'):enabled`);
await expect.waitForSteps(["multi-select submitted"]);
await contains(INPUT_REQUEST_SELECTOR, { count: 0 });
});
test("skip resumes the durable request without an answer", async () => {
onRpc("/ai/resume_pending_interaction", async (request) => {
const { params } = await request.json();
expect(params.response).toEqual({ kind: "skip" });
expect(params.resume_token).toBe("durable-user-input-token");
expect.step("question skipped");
return { loop_state: "ready" };
});
await startAIChat({
user_input_request: {
choices: [
{ label: "Create a draft", value: "draft" },
{ label: "Send it now", value: "send" },
],
multiSelect: false,
type: "question",
},
});
await contains(`${INPUT_REQUEST_SELECTOR} button:contains('Skip')`);
await click(`${INPUT_REQUEST_SELECTOR} button:contains('Skip')`);
await expect.waitForSteps(["question skipped"]);
await contains(INPUT_REQUEST_SELECTOR, { count: 0 });
});

View File

@@ -0,0 +1,131 @@
import {
click,
contains,
MENU_ACTIVE_IDS,
openDiscuss,
openMessagingMenu,
start,
startServer,
} from "@mail/../tests/mail_test_helpers";
import { test } from "@odoo/hoot";
import { Command, serverState } from "@web/../tests/web_test_helpers";
import { defineAIModels } from "../ai_test_helpers";
defineAIModels();
test("Can open a new AI chat from the messaging menu AI tab", async () => {
await start();
await openMessagingMenu(MENU_ACTIVE_IDS.AI_CHAT);
await click("button:has([data-icon='add']):text('Chat')");
await contains(".o-mail-ChatWindow-displayName:text('Test AI Agent')");
});
test("AI tab has an unread filter", async () => {
const pyEnv = await startServer();
const [alphaPartnerId, betaPartnerId] = pyEnv["res.partner"].create([
{ name: "Alpha AI" },
{ name: "Beta AI" },
]);
const [alphaAgentId, betaAgentId] = pyEnv["ai.agent"].create([
{ name: "Alpha AI", partner_id: alphaPartnerId },
{ name: "Beta AI", partner_id: betaPartnerId },
]);
const [alphaChannelId, betaChannelId] = pyEnv["discuss.channel"].create([
{
ai_agent_id: alphaAgentId,
channel_member_ids: [
Command.create({ partner_id: serverState.partnerId }),
Command.create({ partner_id: alphaPartnerId }),
],
channel_type: "ai_chat",
name: "Alpha AI",
},
{
ai_agent_id: betaAgentId,
channel_member_ids: [
Command.create({ partner_id: serverState.partnerId }),
Command.create({ partner_id: betaPartnerId }),
],
channel_type: "ai_chat",
name: "Beta AI",
},
]);
const [, betaMessageId] = pyEnv["mail.message"].create([
{
author_id: alphaPartnerId,
body: "hello",
model: "discuss.channel",
res_id: alphaChannelId,
},
{ author_id: betaPartnerId, body: "hi", model: "discuss.channel", res_id: betaChannelId },
]);
const [betaMemberId] = pyEnv["discuss.channel.member"].search([
["channel_id", "=", betaChannelId],
["partner_id", "=", serverState.partnerId],
]);
// Beta AI is marked read: its separator is past its last message.
pyEnv["discuss.channel.member"].write([betaMemberId], {
new_message_separator: betaMessageId + 1,
});
await start();
await openMessagingMenu(MENU_ACTIVE_IDS.AI_CHAT);
await contains(".o-mail-NotificationItem", { count: 2 });
await contains(".o-mail-NotificationItem:has(:text('Alpha AI'))");
await contains(".o-mail-NotificationItem:has(:text('Beta AI'))");
await click("button:text('Unread')");
await contains("button.o-active:text('Unread')");
await contains(".o-mail-NotificationItem", { count: 1 });
await contains(".o-mail-NotificationItem:has(:text('Alpha AI'))");
});
test("AI tab agent plugin filter works alongside chip filters", async () => {
const pyEnv = await startServer();
const [alphaPartnerId, betaPartnerId] = pyEnv["res.partner"].create([
{ name: "Alpha AI" },
{ name: "Beta AI" },
]);
const [alphaAgentId, betaAgentId] = pyEnv["ai.agent"].create([
{ name: "Alpha AI", partner_id: alphaPartnerId },
{ name: "Beta AI", partner_id: betaPartnerId },
]);
const alphaChannelIds = pyEnv["discuss.channel"].create(
Array.from({ length: 22 }, (_, i) => ({
ai_agent_id: alphaAgentId,
channel_member_ids: [
Command.create({ partner_id: serverState.partnerId }),
Command.create({ partner_id: alphaPartnerId }),
],
channel_type: "ai_chat",
name: `Alpha chat ${i}`,
}))
);
pyEnv["discuss.channel"].create({
ai_agent_id: betaAgentId,
channel_member_ids: [
Command.create({ partner_id: serverState.partnerId }),
Command.create({ partner_id: betaPartnerId }),
],
channel_type: "ai_chat",
name: "Beta chat",
});
pyEnv["mail.message"].create({
author_id: alphaPartnerId,
body: "hello",
model: "discuss.channel",
res_id: alphaChannelIds[0],
});
await start();
await openDiscuss(MENU_ACTIVE_IDS.AI_CHAT);
await contains(".o-mail-NotificationItem", { count: 20 });
await click("button[aria-label='Filters']");
await click(".dropdown-item:text('Beta AI')");
await contains(".o-mail-NotificationItem");
await contains(".o-mail-NotificationItem:has(:text('Beta chat'))");
await click("button[aria-label='Filters']");
await click(".dropdown-item:text('Alpha AI')");
await contains(".o-mail-NotificationItem:contains('Alpha chat')", { count: 22 });
await click("button:text('Unread')");
await contains("button.o-active:text('Unread')");
await contains(".o-mail-NotificationItem", { count: 1 });
await contains(".o-mail-NotificationItem:has(:text('Alpha chat 0'))");
});

View File

@@ -0,0 +1,152 @@
import { insertText, setupChatHub, start, startServer } from "@mail/../tests/mail_test_helpers";
import { waitFor, waitForNone, describe, expect, test } from "@odoo/hoot";
import { press } from "@odoo/hoot-dom";
import { Command, contains, getService, onRpc, serverState } from "@web/../tests/web_test_helpers";
import { defineAIModels } from "../ai_test_helpers";
describe.current.tags("desktop");
defineAIModels();
test("posting in ai chat starts callback-driven response generation", async () => {
const pyEnv = await startServer();
const partnerId = pyEnv["res.partner"].create({ name: "Agent Partner" });
const aiAgentId = pyEnv["ai.agent"].create({
name: "Agent Partner",
partner_id: partnerId,
sources_ids: [Command.create({ name: "instructions.txt" })],
});
const channelId = pyEnv["discuss.channel"].create({
channel_member_ids: [
Command.create({ partner_id: serverState.partnerId }),
Command.create({ partner_id: partnerId }),
],
channel_type: "ai_chat",
ai_agent_id: aiAgentId,
});
pyEnv["ai.session"].create({
agent_id: aiAgentId,
channel_id: channelId,
loop_state: "ready",
});
onRpc("/ai/start_session_advance", () => {
expect.step("start session advance");
return {
loop_state: "waiting_model",
};
});
setupChatHub({ opened: [channelId] });
await start();
await waitFor(".o-mail-ChatWindow");
await contains("button[title='More Actions']").click();
// Test session options buttons
await contains("button[name='toggle-web-search']").click();
await waitFor("button[name='toggle-web-search'] input[type='checkbox']:checked");
await contains("button[name='toggle-restrict-to-resources']").click();
await waitFor("button[name='toggle-web-search'] input[type='checkbox']:not(:checked)");
await waitFor("button[name='toggle-restrict-to-resources'] input[type='checkbox']:checked");
await contains("button[name='toggle-think-longer']").click();
await waitFor("button[name='toggle-think-longer'] input[type='checkbox']:checked");
await contains("button[name='toggle-action-auto-approve']").click();
await waitFor("button[name='toggle-action-auto-approve'] input[type='checkbox']:checked");
await contains(".o-mail-ChatWindow .o-mail-Composer-input").click();
await insertText(".o-mail-ChatWindow .o-mail-Composer-input", "AI is bad at writing code");
await press("Enter");
await expect.waitForSteps(["start session advance"]);
});
test("loop state controls sending while the agent or its subagent is busy", async () => {
const pyEnv = await startServer();
const partnerId = pyEnv["res.partner"].create({ name: "Agent Partner" });
const aiAgentId = pyEnv["ai.agent"].create({
name: "Agent Partner",
partner_id: partnerId,
});
const channelId = pyEnv["discuss.channel"].create({
channel_member_ids: [
Command.create({ partner_id: serverState.partnerId }),
Command.create({ partner_id: partnerId }),
],
channel_type: "ai_chat",
ai_agent_id: aiAgentId,
});
const sessionId = pyEnv["ai.session"].create({
agent_id: aiAgentId,
channel_id: channelId,
loop_state: "ready",
});
onRpc("/ai/start_session_advance", () => {
expect.step("start session advance");
return {
loop_state: "waiting_model",
};
});
setupChatHub({ opened: [channelId] });
await start();
await waitFor(".o-mail-ChatWindow");
await contains(".o-mail-ChatWindow .o-mail-Composer-input").click();
await insertText(".o-mail-ChatWindow .o-mail-Composer-input", "First message");
await press("Enter");
await expect.waitForSteps(["start session advance"]);
await insertText(".o-mail-ChatWindow .o-mail-Composer-input", "Second message");
await waitFor(".o-mail-Composer button[name='send-message']:disabled");
await waitFor(".o-ai-tool-status:contains(Thinking)");
await waitForNone(".o-mail-ChatWindow-typing");
const store = getService("mail.store");
for (const loop_state of ["waiting_child", "waiting_client_result"]) {
store["ai.session"].insert({ id: sessionId, loop_state });
await waitFor(".o-mail-Composer button[name='send-message']:disabled");
await waitFor(".o-ai-tool-status:contains(Thinking)");
}
for (const loop_state of ["waiting_confirmation", "waiting_answer", "ready"]) {
store["ai.session"].insert({ id: sessionId, loop_state });
await waitFor(".o-mail-Composer button[name='send-message']:enabled");
await waitForNone(".o-ai-tool-status");
}
const child = store["ai.session"].insert({
id: sessionId + 1,
channel_id: channelId,
parent_session_id: sessionId,
});
for (const loop_state of ["waiting_confirmation", "waiting_answer"]) {
child.loop_state = loop_state;
await waitFor(".o-mail-Composer button[name='send-message']:disabled");
}
child.loop_state = "ready";
await waitFor(".o-mail-Composer button[name='send-message']:enabled");
onRpc("/ai/resume_pending_interaction", async (request) => {
const { params } = await request.json();
expect(params.session_id).toBe(child.id);
expect(params.resume_token).toBe("child-confirmation");
expect(params.response).toEqual({ kind: "confirmation", value: "confirm_once" });
expect.step("child confirmed");
return { loop_state: "ready", interactionConsumed: true };
});
child.loop_state = "waiting_confirmation";
child.userInputRequest = {
type: "confirmation",
body: "Create the contact?",
choices: [{ label: "Yes, do it", value: "confirm_once" }],
resumeToken: "child-confirmation",
};
const prompt = ".o_ai_user_input_request";
await waitFor(prompt);
expect(prompt + " .fw-bold").toHaveText("Agent Partner");
await contains(prompt + " button:contains('Yes, do it')").click();
await expect.waitForSteps(["child confirmed"]);
await waitForNone(prompt);
// Livechat retains the native typing indicator while callbacks are pending.
store["discuss.channel"].get(channelId).channel_type = "livechat";
child.loop_state = "waiting_model";
await waitFor(".o-mail-ChatWindow-typing");
child.loop_state = "ready";
await waitForNone(".o-mail-ChatWindow-typing");
});

View File

@@ -0,0 +1,85 @@
import {
contains,
mailModels,
openListView,
start,
startServer,
} from "@mail/../tests/mail_test_helpers";
import { describe, test } from "@odoo/hoot";
import { defineModels, fields } from "@web/../tests/web_test_helpers";
import "@ai/views/fields/discuss_call_history_indicators/discuss_call_history_indicators_field_patch";
describe.current.tags("desktop", "discuss_call_history");
class DiscussCallHistory extends mailModels.DiscussCallHistory {
has_transcript = fields.Boolean();
}
defineModels({ ...mailModels, DiscussCallHistory });
test("recording indicators include the transcript", async () => {
const pyEnv = await startServer();
pyEnv["discuss.call.history"].create({
has_audio: true,
has_recording: true,
has_transcript: true,
});
pyEnv["discuss.call.history"].create({
has_audio: true,
has_recording: true,
});
await start();
await openListView("discuss.call.history", {
arch: `
<list>
<field name="has_recording" widget="discuss_call_history_indicators"/>
</list>
`,
});
await contains("[data-icon='volume_up']", { count: 2 });
await contains("[data-icon='subtitles']");
await contains("[data-icon='volume_up']:not(.ms-1)", { count: 2 });
await contains("[data-icon='subtitles'].ms-1");
});
test("transcript-only recordings show only the transcript indicator", async () => {
const pyEnv = await startServer();
pyEnv["discuss.call.history"].create({
has_recording: true,
has_transcript: true,
});
await start();
await openListView("discuss.call.history", {
arch: `
<list>
<field name="has_recording" widget="discuss_call_history_indicators"/>
</list>
`,
});
await contains("[data-icon='subtitles']");
await contains("[data-icon='movie']", { count: 0 });
await contains("[data-icon='volume_up']", { count: 0 });
});
test("recording indicators respect the field value", async () => {
const pyEnv = await startServer();
pyEnv["discuss.call.history"].create({
has_audio: true,
has_recording: false,
has_video: true,
});
await start();
await openListView("discuss.call.history", {
arch: `
<list>
<field name="has_recording" widget="discuss_call_history_indicators"/>
</list>
`,
});
await contains(".o_list_view");
await contains("[data-icon='movie']", { count: 0 });
await contains("[data-icon='volume_up']", { count: 0 });
await contains("[data-icon='subtitles']", { count: 0 });
});

View File

@@ -0,0 +1,435 @@
import {
click,
contains,
insertText,
openDiscuss,
openMessagingMenu,
setupChatHub,
startServer,
start,
MENU_ACTIVE_IDS,
} from "@mail/../tests/mail_test_helpers";
import { aiSessionIdentifier } from "@ai/utils/ai_session_identifier";
import { runOneWayClientToolBatch } from "@ai/discuss/core/common/ai_client_tool_service";
import { createAIChat, defineAIModels } from "./ai_test_helpers";
import { DiscussChannel } from "./mock_server/mock_models/discuss_channel";
import { expect, test } from "@odoo/hoot";
import { waitFor } from "@odoo/hoot-dom";
import {
Command,
defineActions,
defineMenus,
getService,
makeKwArgs,
onRpc,
patchWithCleanup,
serverState,
} from "@web/../tests/web_test_helpers";
const RESUME_PREVIOUS_CHAT_SELECTOR = ".o-mail-ChatWindow a:text('Resume previous chat')";
function mockSuggestedAiChannel(channelId) {
patchWithCleanup(DiscussChannel.prototype, {
_get_suggested_ai_channel() {
return this.env["discuss.channel"].browse(channelId);
},
});
}
defineAIModels();
defineActions([
{
id: 667,
tag: "action_1",
xml_id: "action_1",
name: "Partners Action 1",
res_model: "partner",
views: [[false, "kanban"]],
},
{
id: 668,
tag: "action_2",
xml_id: "action_2",
name: "Partners Action 2",
res_model: "partner",
views: [[false, "list"]],
},
]);
defineMenus([
{
id: 1,
name: "App1",
appID: 1,
actionID: 667,
},
{
id: 2,
name: "App2",
appID: 2,
actionID: 668,
},
]);
test.tags("desktop");
test("AI chats are shown in their Discuss section", async () => {
const pyEnv = await startServer();
const channelId = pyEnv["ai.agent"].action_launch_ai_chat("systray_ai_button").ai_channel_id;
await start();
await openDiscuss(channelId);
await contains(".o-mail-MessagingMenu-tab.active:has(:text('AI'))");
await contains(".o-mail-MessagingMenuItem:has(:text('Test AI Agent'))");
});
test.tags("desktop");
test("expanding an AI chat opens only the AI chats tab", async () => {
const pyEnv = await startServer();
const agentPartnerId = pyEnv["res.partner"].create({ name: "Test AI Agent" });
const agentId = pyEnv["ai.agent"].create({
name: "Test AI Agent",
partner_id: agentPartnerId,
});
const aiChannelId = pyEnv["discuss.channel"].create({
ai_agent_id: agentId,
channel_member_ids: [
Command.create({ partner_id: serverState.partnerId }),
Command.create({ partner_id: agentPartnerId }),
],
channel_type: "ai_chat",
name: "Test AI Agent",
});
pyEnv["discuss.channel"].create({ name: "General" });
setupChatHub({ opened: [aiChannelId] });
await start();
await contains(".o-mail-ChatWindow:has(:text('Test AI Agent'))");
await click(".o-mail-ChatWindow button[name='expand-discuss']");
await contains(".o-mail-MessagingMenu-tab.active:has(:text('AI'))");
});
test.tags("desktop");
test("AI chat messaging menu preview shows the latest message", async () => {
const pyEnv = await startServer();
const agentPartnerId = pyEnv["res.partner"].create({ name: "Test AI Agent" });
const agentId = pyEnv["ai.agent"].create({
name: "Test AI Agent",
partner_id: agentPartnerId,
});
const channelId = pyEnv["discuss.channel"].create({
ai_agent_id: agentId,
channel_member_ids: [
Command.create({ partner_id: serverState.partnerId }),
Command.create({ partner_id: agentPartnerId }),
],
channel_type: "ai_chat",
name: "Test AI Agent",
});
const needactionMessageId = pyEnv["mail.message"].create({
author_id: agentPartnerId,
body: "older AI answer",
message_type: "comment",
model: "discuss.channel",
needaction: true,
res_id: channelId,
});
pyEnv["mail.notification"].create({
mail_message_id: needactionMessageId,
notification_status: "sent",
notification_type: "inbox",
res_partner_id: serverState.partnerId,
});
pyEnv["mail.message"].create({
author_id: serverState.partnerId,
body: "newer user prompt",
message_type: "comment",
model: "discuss.channel",
res_id: channelId,
});
await start();
await openMessagingMenu(MENU_ACTIVE_IDS.AI_CHAT);
await contains(".o-mail-NotificationItem", { count: 1 });
expect(".o-mail-NotificationItem-text").toHaveText("You: newer user prompt");
});
test.tags("desktop");
test("AI tab in the messaging menu shows and reopens AI chats", async () => {
const pyEnv = await startServer();
const agentPartnerId = pyEnv["res.partner"].create({ name: "Test AI Agent" });
const agentId = pyEnv["ai.agent"].create({
name: "Test AI Agent",
partner_id: agentPartnerId,
});
pyEnv["discuss.channel"].create({
ai_agent_id: agentId,
channel_member_ids: [
Command.create({ partner_id: serverState.partnerId }),
Command.create({ partner_id: agentPartnerId }),
],
channel_type: "ai_chat",
name: "Test AI Agent",
});
pyEnv["discuss.channel"].create({ name: "General" });
await start();
await openMessagingMenu(MENU_ACTIVE_IDS.AI_CHAT);
await contains(".o-mail-NotificationItem", { count: 1 });
await contains(".o-mail-NotificationItem-name:text('Test AI Agent')");
await click(".o-mail-NotificationItem-name:text('Test AI Agent')");
await contains(".o-mail-ChatWindow:has(:text('Test AI Agent'))");
});
test.tags("desktop");
test("a new AI chat suggests and reopens a matching non-empty chat that is not open", async () => {
const pyEnv = await startServer();
const previousChannelId =
pyEnv["ai.agent"].action_launch_ai_chat("systray_ai_button").ai_channel_id;
const [messageId] = pyEnv["discuss.channel"].message_post(
previousChannelId,
makeKwArgs({
body: "Previous question",
message_type: "comment",
}),
);
pyEnv["discuss.channel"].write([previousChannelId], { message_ids: [messageId] });
mockSuggestedAiChannel(previousChannelId);
const restoredChannelId =
pyEnv["ai.agent"].action_launch_ai_chat("systray_ai_button").ai_channel_id;
setupChatHub({ opened: [restoredChannelId] });
await start();
await contains(RESUME_PREVIOUS_CHAT_SELECTOR);
await click(RESUME_PREVIOUS_CHAT_SELECTOR);
await contains(RESUME_PREVIOUS_CHAT_SELECTOR, { count: 0 });
await contains(".o-mail-ChatWindow", { count: 1 });
await contains(".o-mail-ChatWindow:has(:text('Previous question'))");
});
test.tags("desktop");
test("a new AI chat does not suggest a matching non-empty chat that is already open", async () => {
const pyEnv = await startServer();
const channelId = pyEnv["ai.agent"].action_launch_ai_chat("systray_ai_button").ai_channel_id;
const [messageId] = pyEnv["discuss.channel"].message_post(
channelId,
makeKwArgs({
body: "Previous question",
message_type: "comment",
}),
);
pyEnv["discuss.channel"].write([channelId], { message_ids: [messageId] });
mockSuggestedAiChannel(channelId);
setupChatHub({ opened: [channelId] });
await start();
await contains(".o-mail-ChatWindow:has(:text('Test AI Agent'))");
await getService("aiChatLauncher").launchAIChat({
interfaceKey: "systray_ai_button",
});
await contains(RESUME_PREVIOUS_CHAT_SELECTOR, { count: 0 });
});
test.tags("desktop");
test("a new AI chat suggests a matching non-empty chat that is minimized", async () => {
const pyEnv = await startServer();
const channelId = pyEnv["ai.agent"].action_launch_ai_chat("systray_ai_button").ai_channel_id;
const [messageId] = pyEnv["discuss.channel"].message_post(
channelId,
makeKwArgs({
body: "Previous question",
message_type: "comment",
}),
);
pyEnv["discuss.channel"].write([channelId], { message_ids: [messageId] });
mockSuggestedAiChannel(channelId);
setupChatHub({ folded: [channelId] });
await start();
await getService("aiChatLauncher").launchAIChat({
interfaceKey: "systray_ai_button",
});
await contains(RESUME_PREVIOUS_CHAT_SELECTOR);
});
test.tags("mobile");
test("AI tab is available in the mobile Discuss navbar", async () => {
const pyEnv = await startServer();
const agentPartnerId = pyEnv["res.partner"].create({ name: "Test AI Agent" });
const agentId = pyEnv["ai.agent"].create({
name: "Test AI Agent",
partner_id: agentPartnerId,
});
pyEnv["discuss.channel"].create({
ai_agent_id: agentId,
channel_member_ids: [
Command.create({ partner_id: serverState.partnerId }),
Command.create({ partner_id: agentPartnerId }),
],
channel_type: "ai_chat",
name: "Test AI Agent",
});
pyEnv["discuss.channel"].create({ name: "General" });
await start();
await openDiscuss();
await contains(".o-mail-MessagingMenu-tab:text('AI')");
await click(".o-mail-MessagingMenu-tab:text('AI')");
await contains(".o-mail-MessagingMenu-tab.active:text('AI')");
await contains(".o-mail-NotificationItem", { count: 1 });
await contains(".o-mail-NotificationItem-name:text('Test AI Agent')");
});
test.tags("desktop");
test("Closing an empty AI chat deletes the channel", async () => {
const pyEnv = await startServer();
const channelId = pyEnv["ai.agent"].action_launch_ai_chat("systray_ai_button").ai_channel_id;
onRpc("discuss.channel", "unlink", ({ args }) => {
expect.step("unlink");
expect(args).toEqual([channelId]);
});
setupChatHub({ opened: [channelId] });
await start();
await contains(".o-mail-ChatWindow");
await getService("mail.store")["mail.thread"].get({
model: "discuss.channel",
id: channelId,
}).isLoadedPromise;
await click(".o-mail-ChatWindow-header [title*='Close Chat Window']");
await contains(".o-mail-ChatWindow", { count: 0 });
await expect.waitForSteps(["unlink"]);
});
test.tags("desktop");
test("Closing an AI chat with messages does not delete the channel", async () => {
onRpc("discuss.channel", "unlink", () => {
expect.step("unlink");
});
const pyEnv = await startServer();
const channelId = pyEnv["ai.agent"].action_launch_ai_chat("systray_ai_button").ai_channel_id;
pyEnv["mail.message"].create({
author_id: serverState.partnerId,
body: "Hello",
message_type: "comment",
model: "discuss.channel",
res_id: channelId,
});
setupChatHub({ opened: [channelId] });
await start();
await contains(".o-mail-ChatWindow .o-mail-Message");
await click(".o-mail-ChatWindow-header [title*='Close Chat Window']");
await contains(".o-mail-ChatWindow", { count: 0 });
expect.verifySteps([]);
});
test.tags("desktop");
test("Deleting a non-empty AI chat from Discuss asks for confirmation", async () => {
const pyEnv = await startServer();
const channelId = pyEnv["ai.agent"].action_launch_ai_chat("systray_ai_button").ai_channel_id;
pyEnv["mail.message"].create({
author_id: serverState.partnerId,
body: "Hello",
message_type: "comment",
model: "discuss.channel",
res_id: channelId,
});
onRpc("discuss.channel", "unlink", ({ args }) => {
expect.step("unlink");
expect(args).toEqual([channelId]);
});
await start();
await openDiscuss(channelId);
await contains(".o-mail-DiscussContent .o-mail-Message");
await click("[title='Chat Actions']");
await click(".o-dropdown-item:text('Delete AI chat')");
await contains(".modal");
await click(".modal .btn-primary");
await expect.waitForSteps(["unlink"]);
});
test.tags("desktop");
test("Deleting an empty AI chat from Discuss does not ask for confirmation", async () => {
const pyEnv = await startServer();
const channelId = pyEnv["ai.agent"].action_launch_ai_chat("systray_ai_button").ai_channel_id;
onRpc("discuss.channel", "unlink", ({ args }) => {
expect.step("unlink");
expect(args).toEqual([channelId]);
});
await start();
await openDiscuss(channelId);
await click("[title='Chat Actions']");
await click(".o-dropdown-item:text('Delete AI chat')");
await expect.waitForSteps(["unlink"]);
});
test.tags("desktop");
test("Command i.e. /help shouldn't call the LLM", async () => {
onRpc("/ai/start_session_advance", () => {
throw new Error("Shouldn't be called");
});
const pyEnv = await startServer();
const agentPartnerId = pyEnv["ai.agent"].create({ name: "Test Agent" });
const agentId = pyEnv["ai.agent"].create({ name: "Test Agent", partner_id: agentPartnerId });
const channelId = pyEnv["discuss.channel"].create({
name: "General",
channel_type: "ai_chat",
ai_agent_id: agentId,
});
await start();
await openDiscuss(channelId);
await insertText(".o-mail-Composer-input", "/help");
await click(".o-mail-Composer button[name='send-message']:enabled");
await contains(".o-mail-Message", { count: 1 });
await contains(".o-mail-Message:eq(0):has(:text('OdooBot'))");
});
test.tags("desktop");
test("Opening a view with an agent updates the menu and formats the help message", async () => {
const pyEnv = await startServer();
const partnerId = pyEnv["res.partner"].create({ name: "Test Agent" });
const agentId = pyEnv["ai.agent"].create({ name: "Test Agent", partner_id: partnerId });
const { channelId } = createAIChat(pyEnv, agentId);
onRpc("/ai/start_session_advance", () => ({ loop_state: "waiting_model" }));
await start();
// Let the default app finish loading before opening another action.
await waitFor(".o_menu_brand");
expect(".o_menu_brand").toHaveText("App1");
await openDiscuss(channelId);
await insertText(".o-mail-Composer-input", "hello");
await click(".o-mail-Composer button[name='send-message']:enabled");
await runOneWayClientToolBatch(getService("mail.store"), {
channel_id: channelId,
aiSessionIdentifier,
commands: [
{
name: "show_view",
oneway: true,
params: {
action: {
id: 668,
type: "ir.actions.act_window",
tag: "action_2",
xml_id: "action_2",
name: "Partners Action 2",
res_model: "partner",
domain: [["id", "=", 0]],
views: [[false, "list"]],
help: `<p class="o_view_nocontent_smiling_face">No records</p>`,
},
menuId: 2,
},
},
],
});
await waitFor(".o_list_view");
await waitFor(".o_view_nocontent_smiling_face");
expect(".o_view_nocontent_smiling_face").toHaveText("No records");
await waitFor(".o_menu_brand");
expect(".o_menu_brand").toHaveText("App2");
});

View File

@@ -0,0 +1,60 @@
import {
click,
contains,
defineMailModels,
openFormView,
start,
startServer,
} from "@mail/../tests/mail_test_helpers";
import { describe, expect, test } from "@odoo/hoot";
import { registry } from "@web/core/registry";
describe.current.tags("desktop");
defineMailModels();
const serviceRegistry = registry.category("services");
let lastLaunchArgs;
serviceRegistry.add("aiChatLauncher", {
start() {
return {
launchAIChat(args) {
lastLaunchArgs = args;
},
};
},
}, { force: true });
test("File viewer AI button launches chat with attachment context", async () => {
const pyEnv = await startServer();
const partnerId = pyEnv["res.partner"].create({});
const attachmentId = pyEnv["ir.attachment"].create({
name: "Doc.txt",
mimetype: "text/plain",
raw: "VGVzdA==",
res_model: "res.partner",
res_id: partnerId,
});
lastLaunchArgs = undefined;
await start();
await openFormView("res.partner", partnerId, {
arch: `
<form>
<sheet></sheet>
<chatter open_attachments="True"/>
</form>`,
});
await click(`.o-mail-AttachmentContainer[aria-label="Doc.txt"] .o-mail-AttachmentCard-image`);
await contains(".o-FileViewer");
await contains(".o-FileViewer-headerButton [title='Ask AI']");
await click(".o-FileViewer-headerButton [title='Ask AI']");
expect(lastLaunchArgs).toEqual({
interfaceKey: "file_viewer_ai_button",
recordModel: "ir.attachment",
recordId: attachmentId,
channelTitle: "Doc.txt",
aiChatSourceId: attachmentId,
});
});

View File

@@ -0,0 +1,60 @@
import { HtmlField } from "@html_editor/fields/html_field";
import { beforeEach, expect, test } from "@odoo/hoot";
import { queryAllTexts, queryOne } from "@odoo/hoot-dom";
import {
contains,
defineModels,
fields,
models,
mountView,
patchWithCleanup,
} from "@web/../tests/web_test_helpers";
import { setSelection } from "@html_editor/../tests/_helpers/selection";
import { insertText } from "@html_editor/../tests/_helpers/user_actions";
import { _makeUser, user } from "@web/core/user";
import { defineMailModels } from "@mail/../tests/mail_test_helpers";
class Partner extends models.Model {
txt = fields.Html({ trim: true });
_records = [{ id: 1, txt: "<p></p>" }];
}
defineModels([Partner]);
defineMailModels();
let htmlEditor;
beforeEach(() => {
patchWithCleanup(HtmlField.prototype, {
onEditorLoad(editor) {
htmlEditor = editor;
return super.onEditorLoad(...arguments);
},
getConfig() {
const config = super.getConfig();
config.Plugins = config.Plugins.filter((Plugin) => Plugin.id !== "editorVersion");
return config;
},
});
});
test.tags("desktop");
test("ChatGPT command should only be available for internal users", async () => {
patchWithCleanup(user, _makeUser({ is_internal_user: false }));
await mountView({
type: "form",
resId: 1,
resModel: "partner",
arch: `
<form>
<field name="txt" widget="html" />
</form>`,
});
setSelection({ anchorNode: queryOne("[name='txt'] .odoo-editor-editable p"), anchorOffset: 0 });
await contains(".o_we_power_buttons").hover();
expect(queryAllTexts(".o_we_power_buttons .power_button:not(.d-none)")).not.toInclude("AI");
await insertText(htmlEditor, "/");
await contains(".o-we-command-name").hover();
expect(queryAllTexts(".o-we-command-name")).not.toInclude("ChatGPT");
});

View File

@@ -0,0 +1,117 @@
import { setSelection } from "@html_editor/../tests/_helpers/selection";
import { insertText } from "@html_editor/../tests/_helpers/user_actions";
import { HtmlMailField } from "@mail/views/web/fields/html_mail_field/html_mail_field";
import { beforeEach, expect, test } from "@odoo/hoot";
import { press, queryOne } from "@odoo/hoot-dom";
import { animationFrame, enableTransitions } from "@odoo/hoot-mock";
import {
defineModels,
fields,
models,
mountView,
patchWithCleanup,
} from "@web/../tests/web_test_helpers";
import { mailModels } from "@mail/../tests/mail_test_helpers";
function setSelectionInHtmlField(selector = "p", fieldName = "body") {
const anchorNode = queryOne(`[name='${fieldName}'] .odoo-editor-editable ${selector}`);
setSelection({ anchorNode, anchorOffset: 0 });
return anchorNode;
}
class CustomMessage extends models.Model {
_name = "custom.message";
body = fields.Html();
_records = [{ id: 1, body: "<p>first</p>" }];
}
defineModels({ ...mailModels, CustomMessage });
let htmlEditor;
beforeEach(() => {
patchWithCleanup(HtmlMailField.prototype, {
onEditorLoad(editor) {
htmlEditor = editor;
return super.onEditorLoad(...arguments);
},
getConfig() {
const config = super.getConfig();
config.Plugins = config.Plugins.filter((Plugin) => Plugin.id !== "editorVersion");
return config;
},
});
});
test("HtmlMail should have the AI prompt command when dynamic placeholder plugin is active", async function () {
enableTransitions();
await mountView({
type: "form",
resId: 1,
resModel: "custom.message",
arch: `
<form>
<field name="body" widget="html_mail" options="{'dynamic_placeholder': true}"/>
</form>`,
});
setSelectionInHtmlField();
await insertText(htmlEditor, "/prompt");
await press("enter");
expect(`.odoo-editor-editable .o_editor_prompt`).toHaveCount(1);
});
test("HtmlMail should be able to undo a prompt banner", async function () {
enableTransitions();
await mountView({
type: "form",
resId: 1,
resModel: "custom.message",
arch: `
<form>
<field name="body" widget="html_mail" options="{'dynamic_placeholder': true}"/>
</form>`,
});
setSelectionInHtmlField();
await insertText(htmlEditor, "/prompt");
await press("enter");
expect(`.odoo-editor-editable .o_editor_prompt`).toHaveCount(1);
await press(["CTRL", "Z"]);
expect(`.odoo-editor-editable .o_editor_prompt`).toHaveCount(0);
});
test("HtmlMail should add a prompt empty banner", async function () {
enableTransitions();
await mountView({
type: "form",
resId: 1,
resModel: "custom.message",
arch: `
<form>
<field name="body" widget="html_mail" options="{'dynamic_placeholder': true}"/>
</form>`,
});
setSelectionInHtmlField();
await insertText(htmlEditor, "abc");
await insertText(htmlEditor, "/prompt");
await press("enter");
expect(`.odoo-editor-editable .o_editor_prompt_content`).toHaveInnerHTML(`
<div class="o-paragraph o-we-hint" o-we-hint-text="Type &quot;/&quot; for commands"><br></div>`);
});
test("Only dynamic placeholder command should be available inside an AI prompt", async function () {
await mountView({
type: "form",
resId: 1,
resModel: "custom.message",
arch: `
<form>
<field name="body" widget="html_mail" options="{'dynamic_placeholder': true}"/>
</form>`,
});
setSelectionInHtmlField();
await insertText(htmlEditor, "/prompt");
await press("enter");
await insertText(htmlEditor, "/");
await animationFrame();
expect(".o-we-command").toHaveCount(1);
expect(".o-we-command .o-we-command-name").toHaveText("Field");
});

View File

@@ -0,0 +1,29 @@
import { messagingMenuHelpers } from "@mail/../tests/mock_server/controllers/discuss/messaging_menu";
import { patch } from "@web/core/utils/patch";
// Mirrors `ai/controllers/messaging_menu.py` (AIMessagingMenuController): registers the
// AI chat tab, on top of mail/discuss's tabs.
patch(messagingMenuHelpers, {
_get_menu_tab_domain(env, tab_id) {
if (!tab_id.startsWith("ai-chat")) {
return super._get_menu_tab_domain(env, tab_id);
}
const domain = [["channel_type", "=", "ai_chat"]];
if (tab_id.includes(":")) {
domain.push(["ai_agent_id", "=", Number(tab_id.split(":")[1])]);
}
return domain;
},
_get_menu_tab_filter_domain(env, tab_id, filter_id) {
if (tab_id.startsWith("ai-chat") && filter_id === "ai_chat_unread") {
return [["self_member_id.is_unread", "=", true]];
}
if (tab_id === "ai-chat" && filter_id.startsWith("ai_agent:")) {
const agentId = Number(filter_id.split(":")[1]);
return [["ai_agent_id", "=", agentId]];
}
return super._get_menu_tab_filter_domain(env, tab_id, filter_id);
},
});

View File

@@ -0,0 +1,81 @@
import { Store } from "@mail/../tests/mock_server/store";
import { Command, fields, models } from "@web/../tests/web_test_helpers";
export class AIAgent extends models.ServerModel {
_name = "ai.agent";
name = fields.Char();
allowed_agent_ids = fields.Many2many({ relation: "ai.agent" });
partner_id = fields.Many2one({
relation: "res.partner",
});
subtitle = fields.Char();
image_128 = fields.Binary();
system_prompt = fields.Text();
sources_ids = fields.One2many({
relation: "ai.agent.source",
relation_field: "ai_agent_id",
});
_store_agent_fields(res) {
res.extend(["partner_id", "subtitle", "name"]);
// Python derives xml_id from ir.model.data; test agents are created without one, so it
// resolves to false (ir.model.data is not mocked).
res.attr("xml_id", false);
res.attr("sources_ids");
}
action_launch_ai_chat(interface_key, res_model = null, res_id = null) {
const agentPartnerId = this.env["res.partner"].create({ name: "Test AI Agent" });
const agent = this.env["ai.agent"].browse(
this.env["ai.agent"].create({ name: "Test AI Agent", partner_id: agentPartnerId }),
);
const channel = this.env["discuss.channel"].browse(agent._create_ai_chat_channel());
const composer = this.env["ai.composer"].browse(
this.env["ai.composer"].create({ interface_key }),
);
this.env["ai.session"].create({
agent_id: agent[0].id,
ai_composer_id: composer[0].id,
channel_id: channel[0].id,
res_model: res_model || false,
res_id: res_id || false,
});
const store = new Store();
store.add(channel, (res) => {
res.attr("are_prompts_from_local_storage", false);
res.from_method("_store_channel_fields");
});
return {
ai_channel_id: channel[0].id,
data: store.as_dict(),
model_has_thread: null,
};
}
/** @param {import("@mail/../tests/mock_server/mock_models/res_partner").ResPartner} partner */
_create_ai_chat_channel() {
const agent = this[0];
return this.env["discuss.channel"].create({
name: agent.name,
channel_type: "ai_chat",
channel_member_ids: [
Command.create({
partner_id: this.env.user.partner_id,
}),
Command.create({
partner_id: agent.partner_id,
}),
],
ai_agent_id: agent.id,
});
}
}
export class AIAgentSource extends models.ServerModel {
_name = "ai.agent.source";
ai_agent_id = fields.Many2one({ relation: "ai.agent" });
name = fields.Char();
}

View File

@@ -0,0 +1,14 @@
import { fields, models } from "@web/../tests/web_test_helpers";
export class AIComposer extends models.ServerModel {
_name = "ai.composer";
ai_agent_id = fields.Many2one({ relation: "ai.agent" });
interface_key = fields.Selection({
selection: [["test_interface_key", "Test Interface Key"]],
});
_store_composer_fields(res) {
res.attr("interface_key");
}
}

View File

@@ -0,0 +1,5 @@
import { models } from "@web/../tests/web_test_helpers";
export class AIPromptButton extends models.ServerModel {
_name = "ai.prompt.button";
}

View File

@@ -0,0 +1,39 @@
import { fields, models } from "@web/../tests/web_test_helpers";
export class AISession extends models.ServerModel {
_name = "ai.session";
agent_id = fields.Many2one({ relation: "ai.agent" });
parent_session_id = fields.Many2one({ relation: "ai.session" });
ai_composer_id = fields.Many2one({ relation: "ai.composer" });
channel_id = fields.Many2one({ relation: "discuss.channel" });
res_id = fields.Generic();
res_model = fields.Generic();
user_input_request = fields.Generic();
external_pending_tool = fields.Generic();
loop_state = fields.Generic({ default: "ready" });
resume_token = fields.Generic();
_store_session_fields(res) {
res.one("agent_id", "_store_agent_fields");
res.one("parent_session_id", []);
res.attr("res_model");
res.attr("res_id");
res.one("ai_composer_id", "_store_composer_fields");
res.attr("config", {
enable_think_longer: false,
enable_web_search: false,
enable_resources_only: false,
auto_confirm: false,
show_agent_steps: false,
});
res.attr("config_rules", {
enable_web_search: { enable_resources_only: false },
enable_resources_only: { enable_web_search: false },
});
res.attr("userInputRequest", (session) => session.user_input_request || false);
res.attr("external_pending_tool", (session) => Boolean(session.external_pending_tool));
res.attr("loop_state");
res.attr("resume_token");
}
}

View File

@@ -0,0 +1,34 @@
import { mailModels } from "@mail/../tests/mail_test_helpers";
import { fields } from "@web/../tests/web_test_helpers";
export class DiscussChannel extends mailModels.DiscussChannel {
ai_agent_id = fields.Many2one({ relation: "ai.agent" });
ai_session_ids = fields.One2many({ relation: "ai.session", relation_field: "channel_id" });
_store_channel_fields(res) {
super._store_channel_fields(res);
this._store_ai_fields(res);
}
_store_ai_fields(res) {
const isAiAgentChannel = (c) => this._ai_agent_channel_types().includes(c.channel_type);
res.one("ai_agent_id", "_store_agent_fields", { predicate: isAiAgentChannel, sudo: true });
res.many("ai_session_ids", "_store_session_fields", {
predicate: isAiAgentChannel,
sudo: true,
});
res.one("suggestedAiChannel", [], {
predicate: (channel) =>
channel.channel_type === "ai_chat" && !channel.message_ids?.length,
value: (channel) => this.browse(channel.id)._get_suggested_ai_channel(),
});
}
_get_suggested_ai_channel() {
return this.env["discuss.channel"].browse();
}
_ai_agent_channel_types() {
return ["ai_chat"];
}
}

View File

@@ -0,0 +1,24 @@
import { fields, models } from "@web/../tests/web_test_helpers";
export class Partner extends models.Model {
name = fields.Char();
foo = fields.Char();
_records = [{ id: 1, name: "dummy record", foo: "yop" }];
_views = {
kanban: `
<kanban>
<templates>
<t t-name="card">
<field name="foo"/>
</t>
</templates>
</kanban>
`,
list: `
<list>
<field name="foo"/>
</list>
`,
};
}

View File

@@ -0,0 +1,37 @@
import { registry } from "@web/core/registry";
import { deliverAIResults, setupAIResults } from "@ai/../tests/tours/ai_tour_helpers";
/**
* This tour sends the user message and asserts the graph view opens
* with the date-groupby facet active.
*/
registry.category("web_tour.tours").add("ai_open_menu_graph_tour", {
steps: () => [
{
trigger: ".o_navbar button[title='Ask AI']",
run: "click",
},
setupAIResults(),
{
trigger: ".o-mail-ChatWindow .o-mail-Composer-input",
run: "edit graph view of contacts per month",
},
{
trigger: ".o-mail-ChatWindow .o-mail-Composer button[title^='Send']:enabled",
run: "click",
},
deliverAIResults(),
// Graph view must open via the action emitted by _ai_tool_open_menu_graph.
{
trigger: ".o_action_manager .o_graph_view",
},
// `applyAISearch` -> `createNewGroupBy('create_date', {interval:'month'})`
{
trigger: ".o_searchview .o_facet_values:contains(Created on: Month)",
},
deliverAIResults(),
{
trigger: ".o-mail-ChatWindow .o-mail-Message-body:contains(Here is your graph)",
},
],
});

View File

@@ -0,0 +1,40 @@
const callbacks = [];
/** Listen for replies captured by the mocked IAP submission. */
export function setupAIResults(trigger = ".o-mail-ChatWindow") {
return {
content: "Listen for mocked IAP results",
trigger,
async run() {
callbacks.length = 0;
const busService = odoo.__WOWL_DEBUG__.root.env.services.bus_service;
// Each tour subscribes once and closes its browser afterward, so no manual unsubscribe is needed.
busService.subscribe("ai.test/callbacks_ready", (callback) => {
callbacks.push(callback);
});
await busService.start();
},
};
}
/** Deliver this round's mocked callbacks, including its optional chat-title reply. */
export function deliverAIResults() {
return {
content: "Deliver the mocked IAP results for this round",
trigger: "body",
async run({ waitUntil }) {
await waitUntil(() => callbacks.length > 0);
const batch = callbacks.splice(0);
for (const callback of batch) {
const response = await fetch("/ai/completion_result_ready", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(callback),
});
if (!response.ok) {
throw new Error(await response.text());
}
}
},
};
}

View File

@@ -0,0 +1,111 @@
import { describe, expect, test } from "@odoo/hoot";
import { parseTimedText } from "@ai/views/fields/call_debrief/transcript_parser";
describe.current.tags("desktop", "call_debrief");
test("Parse SRT: Standard format", () => {
const srt = `1
00:00:01,000 --> 00:00:04,000
Hello world
2
00:00:05,000 --> 00:00:09,000
Second line
Multi line text`;
const result = parseTimedText(srt);
expect(result).toEqual([
{ startSec: 1, endSec: 4, text: "Hello world" },
{ startSec: 5, endSec: 9, text: "Second line\nMulti line text" },
]);
});
test("Parse VTT: Standard format with header", () => {
const vtt = `WEBVTT
00:00:01.000 --> 00:00:04.000
Hello world
00:00:05.000 --> 00:00:09.000
Second line`;
const result = parseTimedText(vtt);
expect(result).toEqual([
{ startSec: 1, endSec: 4, text: "Hello world" },
{ startSec: 5, endSec: 9, text: "Second line" },
]);
});
test("Parse VTT: MM:SS format (no hours)", () => {
const vtt = `WEBVTT
00:01.000 --> 00:04.000
Short timestamp`;
const result = parseTimedText(vtt);
expect(result).toEqual([{ startSec: 1, endSec: 4, text: "Short timestamp" }]);
});
test("Parse VTT: With Cue Settings", () => {
const vtt = `WEBVTT
00:00:01.000 --> 00:00:04.000 align:start size:50%
Hello world`;
// The parser currently ignores settings but should still extract time correctly
const result = parseTimedText(vtt);
expect(result[0].startSec).toBe(1);
expect(result[0].endSec).toBe(4);
expect(result[0].text).toBe("Hello world");
});
test("Parse VTT: With Comments/Notes", () => {
const vtt = `WEBVTT
NOTE This is a comment
00:00:01.000 --> 00:00:04.000
Hello world
NOTE
Multi-line
comment
00:00:05.000 --> 00:00:06.000
Next line`;
const result = parseTimedText(vtt);
// Ideally comments should be ignored.
// Current impl might fail on multi-line comments or treat them as garbage blocks
// checking expected behavior for valid cues
const validCues = result.filter((r) => r.text === "Hello world" || r.text === "Next line");
expect(validCues.length).toBe(2);
});
test("Parse: Timestamps without milliseconds", () => {
const srt = `1
00:00:01 --> 00:00:04
Hello world`;
const result = parseTimedText(srt);
expect(result).toEqual([{ startSec: 1, endSec: 4, text: "Hello world" }]);
});
test("Parse: Malformed timestamps (garbage)", () => {
const srt = `1
00:xx:01,000 --> 00:00:04,000
Bad Start
2
00:00:05,000 --> garbage
Bad End`;
const result = parseTimedText(srt);
expect(result.length).toBe(0);
});
test("Parse: Empty file", () => {
expect(parseTimedText("")).toEqual([]);
expect(parseTimedText(null)).toEqual([]);
expect(parseTimedText(undefined)).toEqual([]);
});

View File

@@ -0,0 +1,492 @@
import { beforeEach, describe, expect, test } from "@odoo/hoot";
import { animationFrame, queryOne } from "@odoo/hoot-dom";
import { TranscriptionPlugin } from "../src/editor/embedded_components/plugins/voice_transcription_plugin";
import { aiVoiceTranscriptionEmbeddedComponent } from "../src/editor/embedded_components/core/voice_transcription";
import {
defineModels,
fields,
makeMockServer,
models,
onRpc,
patchWithCleanup,
} from "@web/../tests/web_test_helpers";
import { renderToString } from "@web/core/utils/render";
import { defineAIModels } from "./ai_test_helpers";
import { contains, click } from "@mail/../tests/mail_test_helpers";
import {
setupMultiEditor,
validateSameHistory,
} from "@html_editor/../tests/_helpers/collaboration";
import { commit, tripleClick } from "@html_editor/../tests/_helpers/user_actions";
import { cleanHints } from "@html_editor/../tests/_helpers/dispatch";
import { parseHTML } from "@html_editor/utils/html";
import { setupEditor } from "@html_editor/../tests/_helpers/editor";
import { user } from "@web/core/user";
import { EmbeddedComponentPlugin } from "@html_editor/others/embedded_component_plugin";
import RealtimeClient from "../src/core/realtime_client";
import AudioProcessor from "../src/core/audio/audio_processor";
import { AITranscriptionEvent, transcriptionBus } from "@ai/core/transcription_bus";
class Dummy extends models.Model {
_name = "dummy";
name = fields.Char();
message_ids = fields.One2many({
relation: "mail.message",
string: "Messages",
});
_records = [
{ id: 1, name: "Bob" },
{ id: 2, name: "Patrick" },
{ id: 3, name: "Sheldon" },
];
}
defineModels([Dummy]);
defineAIModels();
beforeEach(() => {
onRpc("ai.composer", "retrieve_transcription_composer", () => ({}));
onRpc("/ai/transcription/summary", () => "<p>This is a response</p>");
onRpc("/ai/transcription/session", () => {
return {
'status': 'success',
'session_token': 'some_session_token',
'iap_transaction_token': 'some_transaction_token',
}
});
onRpc("/ai/transcription/report_realtime_session_usage", ({ args }) => {
expect(args.iapTransactionToken).toBe("some_transaction_token");
expect(args.usage).toEqual({
"input_tokens": {
"text": 1,
"audio": 1,
},
"output_tokens": 1,
"duration_seconds": 1,
});
});
patchWithCleanup(RealtimeClient.prototype, {
connect(_sessionInfo) {
if (this.socket === null) {
this.socket = new WebSocket();
}
this.socket.addEventListener("message", (event) => {
const jsonData = JSON.parse(event.data);
transcriptionBus.trigger(AITranscriptionEvent.REALTIME_CLIENT_MESSAGE, jsonData);
});
},
});
patchWithCleanup(AudioProcessor.prototype, {
async start() {
this.state = "recording";
},
stop() {
this.state = "idle";
},
});
patchWithCleanup(user, {
lang: "en-US",
});
});
function getCurrentDate() {
const today = new Date();
const timeString = today.toLocaleTimeString([user.lang], {
hour: "2-digit",
minute: "2-digit",
});
return `${today.toLocaleDateString()} - ${timeString}`;
}
const testAiVoiceTranscriptionEmbeddedComponent = {
...aiVoiceTranscriptionEmbeddedComponent,
Component: class AudioTranscriber extends aiVoiceTranscriptionEmbeddedComponent.Component {},
};
const config = {
includePlugins: [EmbeddedComponentPlugin, TranscriptionPlugin],
resources: {
embedded_components: [testAiVoiceTranscriptionEmbeddedComponent],
},
getRecordInfo: () => ({
resModel: "dummy",
resId: "1",
}),
collaboration: {
peerId: 1,
},
};
function generateTranscriptionEvent() {
return new MessageEvent("message", {
data: JSON.stringify({
item_id: 1,
type: "conversation.item.input_audio_transcription.completed",
transcript: "This is a test of transcription",
usage: {
"input_token_details": {
"text_tokens": 1,
"audio_tokens": 1,
},
"output_tokens": 1,
"duration": 1,
},
}),
})
}
describe("Component behaviour", () => {
test.tags("desktop");
test("transcript component tabs have proper hints", async () => {
const transcriptBlock = renderToString("ai.VoiceTranscriptionBlueprint");
await setupEditor(`<p>[]</p>${transcriptBlock}`, {
config,
});
expect("[data-embedded='voice-transcription']").toHaveCount(1);
expect("button:contains(Notes)").toHaveClass("active");
expect("[data-embedded-editable='notesContent'] .o-we-hint").toHaveAttribute(
"o-we-hint-text",
"Add notes about your upcoming meeting"
);
await click("button:contains(Transcript)");
await animationFrame();
expect("button:contains(Transcript)").toHaveClass("active");
expect("[data-embedded-editable='transcriptContent'] .o-we-hint").toHaveAttribute(
"o-we-hint-text",
"Start recording to get a real-time transcript of the conversation"
);
await tripleClick(queryOne("[data-embedded-editable='transcriptContent'] .o-we-hint>br"));
await animationFrame();
expect("[data-embedded-editable='transcriptContent'] .o-we-hint").toHaveAttribute(
"o-we-hint-text",
'Type "/" for commands'
);
});
test.tags("desktop");
test("transcription items are properly rendered", async () => {
const transcriptBlock = renderToString("ai.VoiceTranscriptionBlueprint");
await setupEditor(`<p>[]</p>${transcriptBlock}`, {
config,
});
expect("[data-embedded='voice-transcription']").toHaveCount(1);
await click("button:contains(Start Recording)");
await animationFrame();
expect("button:contains(Transcript)").toHaveClass("active");
expect("[data-embedded-editable='transcriptContent'] p>b").toHaveText(getCurrentDate());
expect(`[data-id='current-transcript-${config.collaboration.peerId}']`).toHaveCount(1);
expect(".o-ai-transcription-listening").toHaveText("AI is listening...");
const realtimeClient = RealtimeClient.getInstance();
realtimeClient.socket.dispatchEvent(generateTranscriptionEvent());
await click("button:contains(Stop Recording)");
await animationFrame();
expect(`[data-id='current-transcript-${config.collaboration.peerId}']`).toHaveCount(0);
expect(".o-ai-transcription-listening").toHaveCount(0);
expect("[data-embedded-editable='transcriptContent'] blockquote:last-child").toHaveText(
"This is a test of transcription"
);
});
test.tags("desktop");
test("should only summarize when there is content in the transcription tab", async () => {
const transcriptBlock = renderToString("ai.VoiceTranscriptionBlueprint");
await setupEditor(`<p>[]</p>${transcriptBlock}`, {
config,
});
expect("[data-embedded='voice-transcription']").toHaveCount(1);
await contains("[data-embedded-editable='summaryContent']", {
textContent: "",
});
expect("button:contains(Summary)").toHaveCount(0);
await click("button:contains(Start Recording)");
await click("button:contains(Stop Recording)");
await contains("[data-embedded-editable='summaryContent']", {
textContent: "",
});
await click("button:contains(Start Recording)");
await animationFrame();
const realtimeClient = RealtimeClient.getInstance();
realtimeClient.socket.dispatchEvent(generateTranscriptionEvent());
await click("button:contains(Stop Recording)");
await contains("button.active:contains(Summary)");
await contains("[data-embedded-editable='summaryContent']", {
textContent: "This is a response",
});
});
test.tags("desktop");
test("share composer should have summary content", async () => {
const transcriptBlock = renderToString("ai.VoiceTranscriptionBlueprint");
const server = await makeMockServer();
server.env["mail.compose.message"]._views.form = `
<form>
<field name="body" type="html" widget="html_composer_message"/>
</form>
`;
await setupEditor(`<p>[]</p>${transcriptBlock}`, {
config,
});
expect("[data-embedded='voice-transcription']").toHaveCount(1);
await click("button:contains(Start Recording)");
await animationFrame();
const realtimeClient = RealtimeClient.getInstance();
realtimeClient.socket.dispatchEvent(generateTranscriptionEvent());
await click("button:contains(Stop Recording)");
await click("[data-embedded='voice-transcription'] button:contains(Share by email)");
await animationFrame();
expect("div[name='body'] p").toHaveText("This is a response");
});
test.tags("desktop");
test("summary has proper prompt actions", async () => {
onRpc("ai.composer", "retrieve_transcription_composer", () => ({
ai_agent_id: 1,
default_prompt: "This is a default prompt",
available_prompt_ids: [
{
name: "Summarize this prospect call",
prompt: "Summarize this prospect call",
},
{
name: "Write an email recap",
prompt: "Write an email recap",
},
],
}));
const transcriptBlock = renderToString("ai.VoiceTranscriptionBlueprint");
const server = await makeMockServer();
server.env["mail.compose.message"]._views.form = `
<form>
<field name="body" type="html" widget="html_composer_message"/>
</form>
`;
await setupEditor(`<p>[]</p>${transcriptBlock}`, {
config,
});
expect("[data-embedded='voice-transcription']").toHaveCount(1);
await click("button:contains(Start Recording)");
await animationFrame();
const realtimeClient = RealtimeClient.getInstance();
realtimeClient.socket.dispatchEvent(generateTranscriptionEvent());
await click("button:contains(Stop Recording)");
await animationFrame();
expect(
"[data-embedded='voice-transcription'] button:contains(Summarize this prospect call)"
).toHaveCount(1);
expect(
"[data-embedded='voice-transcription'] button:contains(Write an email recap)"
).toHaveCount(1);
});
test.tags("desktop");
test("can change language on desktop for multi-lingual database", async () => {
onRpc("res.lang", "get_installed", () => [["en_US"], ["fr_BE"]]);
const transcriptBlock = renderToString("ai.VoiceTranscriptionBlueprint");
await setupEditor(`<p>[]</p>${transcriptBlock}`, {
config,
});
expect("[data-embedded='voice-transcription']").toHaveCount(1);
expect("button.o-dropdown").toHaveText("en");
await click("button:contains(en)");
await animationFrame();
await click("span:contains(fr)");
await animationFrame();
expect("button.o-dropdown").toHaveText("fr");
});
test.tags("mobile");
test("test mobile transcription flow", async () => {
const transcriptBlock = renderToString("ai.VoiceTranscriptionBlueprint");
await setupEditor(`<p>[]</p>${transcriptBlock}`, {
config,
});
expect("[data-embedded='voice-transcription']").toHaveCount(1);
await click("button:contains(Notes)");
await animationFrame();
expect("span:contains(Notes)").toHaveClass("active");
await click("span:contains(Notes)");
await click("button:contains(Start)");
await click("button:contains(Transcript)");
await animationFrame();
expect("span:contains(Transcript)").toHaveClass("active");
await click("span:contains(Transcript)");
expect("[data-embedded-editable='transcriptContent'] p>b").toHaveText(getCurrentDate());
expect(`[data-id='current-transcript-${config.collaboration.peerId}']`).toHaveCount(1);
expect(".o-ai-transcription-listening").toHaveText("AI is listening...");
const realtimeClient = RealtimeClient.getInstance();
realtimeClient.socket.dispatchEvent(generateTranscriptionEvent());
await click("button:contains(Stop)");
await animationFrame();
expect(`[data-id='current-transcript-${config.collaboration.peerId}']`).toHaveCount(0);
expect(".o-ai-transcription-listening").toHaveCount(0);
expect("[data-embedded-editable='transcriptContent'] blockquote:last-child").toHaveText(
"This is a test of transcription"
);
expect("button:contains(Summary)").toHaveCount(1);
await click("button:contains(Summary)");
await animationFrame();
expect("span:contains(Summary)").toHaveClass("active");
});
test.tags("mobile");
test("can change language on mobile for multi-lingual database", async () => {
onRpc("res.lang", "get_installed", () => [["en_US"], ["fr_BE"]]);
const transcriptBlock = renderToString("ai.VoiceTranscriptionBlueprint");
await setupEditor(`<p>[]</p>${transcriptBlock}`, {
config,
});
expect("[data-embedded='voice-transcription']").toHaveCount(1);
await click("button:has(i[data-icon='more_vert'])");
await animationFrame();
expect("button:contains(Language)").toHaveText("Language\nen");
await click("button:contains(Language)");
await click("span:contains(fr)");
await click("button:has(i[data-icon='more_vert'])");
await animationFrame();
expect("button:contains(Language)").toHaveText("Language\nfr");
});
test.tags("mobile");
test("summary has proper prompt actions in dropdown menu", async () => {
onRpc("ai.composer", "retrieve_transcription_composer", () => ({
ai_agent_id: 1,
default_prompt: "This is a default prompt",
available_prompt_ids: [
{
name: "Summarize this prospect call",
prompt: "Summarize this prospect call",
},
{
name: "Write an email recap",
prompt: "Write an email recap",
},
],
}));
const transcriptBlock = renderToString("ai.VoiceTranscriptionBlueprint");
const server = await makeMockServer();
server.env["mail.compose.message"]._views.form = `
<form>
<field name="body" type="html" widget="html_composer_message"/>
</form>
`;
await setupEditor(`<p>[]</p>${transcriptBlock}`, {
config,
});
expect("[data-embedded='voice-transcription']").toHaveCount(1);
await click("button:contains(Start)");
await animationFrame();
const realtimeClient = RealtimeClient.getInstance();
realtimeClient.socket.dispatchEvent(generateTranscriptionEvent());
await click("button:contains(Stop)");
await animationFrame();
await click("button:contains(Actions)");
await animationFrame();
expect("span.o-dropdown-item:contains(Summarize this prospect call)").toHaveCount(1);
expect("span.o-dropdown-item:contains(Write an email recap)").toHaveCount(1);
});
});
describe("Collaboration on transcription component", () => {
test.tags("desktop");
test("recording and summarization are synchronized between peers", async () => {
const peerInfos = await setupMultiEditor({
peerIds: ["c1", "c2"],
contentBefore: "<p>[c1}{c1][c2}{c2]<br></p>",
...config,
});
Object.values(peerInfos).forEach((peer) => {
peer.editor.config.getRecordInfo = config.getRecordInfo;
});
const editor1 = peerInfos.c1.editor;
const editor2 = peerInfos.c2.editor;
editor1.shared.dom.insert(
parseHTML(editor1.document, renderToString("ai.VoiceTranscriptionBlueprint"))
);
commit(editor1);
peerInfos.c2.collaborationPlugin.insertRemoteHistoryCommits(
peerInfos.c1.historyPlugin.commits
);
validateSameHistory(peerInfos);
cleanHints(editor2);
expect(editor2.editable.querySelector("[data-embedded='voice-transcription']")).toHaveCount(
1
);
await animationFrame();
await click(editor1.editable.querySelector("summary>div:last-child button:last-child"));
await animationFrame();
peerInfos.c2.collaborationPlugin.insertRemoteHistoryCommits(
peerInfos.c1.historyPlugin.commits
);
expect(
editor1.editable.querySelector("summary>div:last-child button:last-child")
).toHaveText("Stop Recording");
expect(
editor2.editable.querySelector("[data-embedded-editable='transcriptContent'] p>b")
).toHaveText(getCurrentDate());
expect(editor2.editable.querySelector(`[data-id='current-transcript-c1']`)).toHaveCount(1);
const realtimeClient = RealtimeClient.getInstance();
realtimeClient.socket.dispatchEvent(generateTranscriptionEvent());
await click(editor1.editable.querySelector("summary>div:last-child button:last-child"));
await animationFrame();
peerInfos.c2.collaborationPlugin.insertRemoteHistoryCommits(
peerInfos.c1.historyPlugin.commits
);
expect(editor2.editable.querySelector(`[data-id='current-transcript-c1']`)).toBe(null);
await click(editor2.editable.querySelector("summary ul.nav button:first-child"));
await animationFrame();
expect(
editor2.editable.querySelector("[data-embedded-editable='summaryContent'] p")
).toHaveText("This is a response");
});
});