初始提交

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,167 @@
import { _t } from "@web/core/l10n/translation";
import { registry } from "@web/core/registry";
import { rpc } from "@web/core/network/rpc";
// todo: make it a function? why is this a service
export const aiChatLauncherService = {
dependencies: ["mail.store", "orm", "action"],
start(env, services) {
const actionService = services["action"];
const mailStore = services["mail.store"];
async function openFullComposer(msgType, resModel, resId, message) {
let allRecipients = [];
const thread = await mailStore["mail.thread"].getOrFetch({
model: resModel,
id: resId,
});
if (msgType === "message") {
allRecipients = [...thread.suggestedRecipients, ...thread.additionalRecipients];
// auto-create partner
const newPartners = allRecipients.filter((recipient) => !recipient.partner_id);
if (newPartners.length !== 0) {
const recipientEmails = [];
newPartners.forEach((recipient) => {
recipientEmails.push(recipient.email);
});
const partners = await rpc("/mail/partner/from_email", {
thread_model: thread.model,
thread_id: thread.id,
emails: recipientEmails,
});
for (const index in partners) {
const partnerData = partners[index];
const partner = mailStore["res.partner"].insert(partnerData);
const email = recipientEmails[index];
const recipient = allRecipients.find(
(recipient) => recipient.email === email
);
recipient.partner_id = partner.id;
}
}
}
actionService.doAction(
{
name: msgType === "message" ? _t("Send Message") : _t("Log Note"),
res_model: "mail.compose.message",
target: "new",
type: "ir.actions.act_window",
view_id: false,
view_mode: "form",
views: [[false, "form"]],
context: {
is_full_composer: true,
default_body: message.body,
default_model: resModel,
default_partner_ids: allRecipients
.filter((r) => r.recipient_type !== "cc")
.map((r) => r.partner_id),
default_partner_cc_ids: allRecipients
.filter((r) => r.recipient_type === "cc")
.map((r) => r.partner_id),
default_res_ids: [resId],
default_subtype_xmlid:
msgType === "message" ? "mail.mt_comment" : "mail.mt_note",
default_attachment_ids: message.attachment_ids.map(
(attachment) => attachment.id
),
},
},
{ onClose: () => thread?.fetchNewMessages() }
);
}
function getLastAiChat({ interfaceKey, recordModel, recordId }) {
if (!["chatter_ai_button", "systray_ai_button"].includes(interfaceKey)) {
return;
}
return mailStore.messagingMenu.aiChatTab.channels.find(
(channel) =>
channel.isLoaded &&
channel.ai_session_ids.some(
(session) =>
session.ai_composer_id?.interface_key === interfaceKey &&
(session.res_model === recordModel ||
(!session.res_model && !recordModel)) &&
(session.res_id === recordId || (!session.res_id && !recordId))
)
);
}
return {
async launchAIChat({
interfaceKey,
channelTitle,
recordModel = null,
recordId = null,
aiSpecialActions = null,
aiChatSourceId = null,
textSelection = null,
textOfEditable = null,
userMessage = null,
referenceImagePath = null,
context = null,
}) {
// make the insert button target the component that called the AI
if (aiChatSourceId) {
services["mail.store"].aiInsertButtonTarget = aiChatSourceId;
}
// when creating an AI chat and when the last chat with the same configuration is
// empty, return that chat instead (to avoid creating several empty chats when
// clicking several times on the "create AI chat" button)
const lastAiChat = getLastAiChat({ interfaceKey, recordModel, recordId });
if (lastAiChat?.isEmpty) {
if (services["mail.store"].discuss.isActive) {
lastAiChat.setAsDiscussThread();
} else {
await lastAiChat.openChatWindow({ focus: true });
}
if (userMessage) {
lastAiChat.post(userMessage);
}
return lastAiChat;
}
const { ai_channel_id, data, model_has_thread } = await services.orm.call(
"ai.agent",
"action_launch_ai_chat",
[
interfaceKey,
recordModel,
recordId,
channelTitle,
textSelection?.textContent,
textOfEditable,
referenceImagePath,
],
{ context }
);
services["mail.store"].insert(data);
const channel = await services["mail.store"]["discuss.channel"].getOrFetch(
ai_channel_id
);
// add sendMessage and logNote only if the model inherits from mail.thread
if (interfaceKey === "chatter_ai_button" && model_has_thread) {
aiSpecialActions = {
...(aiSpecialActions || {}),
sendMessage: (message) =>
openFullComposer("message", recordModel, recordId, message),
logNote: (message) =>
openFullComposer("note", recordModel, recordId, message),
};
}
channel.aiSpecialActions = aiSpecialActions;
channel.textSelection = textSelection;
channel.aiChatSource = aiChatSourceId;
channel.open({ focus: true });
channel.openChatWindow();
if (userMessage) {
channel.post(userMessage);
}
return channel;
},
};
},
};
registry.category("services").add("aiChatLauncher", aiChatLauncherService);

View File

@@ -0,0 +1,222 @@
import { _t } from "@web/core/l10n/translation";
import { Component, proxy, signal, useProps } from "@odoo/owl";
import { registry } from "@web/core/registry";
import { standardFieldProps } from "@web/views/fields/standard_field_props";
import { useAutoresize } from "@web/core/utils/autoresize";
import { useService } from "@web/core/utils/hooks";
/**
* Widget to edit the JSON schema sent to the LLM provider.
*
* See https://json-schema.org/understanding-json-schema/reference
*/
export class AiJsonSchema extends Component {
static template = "ai.AiJsonSchema";
props = useProps(standardFieldProps);
tableRef = signal.ref();
textareaRef = signal.ref();
setup() {
this.notification = useService("notification");
this.state = proxy({
technical_mode: false,
// There's no order in the arguments, so we try to not move them when editing
orderArguments: Object.keys(this.value?.properties || {}).sort(),
});
useAutoresize(this.textareaRef);
}
get types() {
return [
["boolean", "Boolean"],
["integer", "Integer"],
["number", "Number"],
["string", "String"],
["enum_integer", "Integer Enum"],
["enum_number", "Number Enum"],
["enum_string", "String Enum"],
["regex", "Regex"],
["array_boolean", "Array of Boolean"],
["array_integer", "Array of Integer"],
["array_number", "Array of Number"],
["array_string", "Array of String"],
];
}
get value() {
let value;
try {
value = JSON.parse(this.props.record.data[this.props.name] || "{}");
} catch {
value = {};
}
const defaultKeys = {
properties: {},
required: [],
type: "object",
};
return { ...defaultKeys, ...value };
}
get arguments() {
const value = this.value;
if (!value) {
return [];
}
const required = value.required || [];
const keys = Object.keys(value.properties).sort(
(a, b) => this.state.orderArguments.indexOf(a) - this.state.orderArguments.indexOf(b)
);
return keys.map((k) => [
k,
value.properties[k],
required.includes(k),
this.getEffectiveType(value.properties[k]),
]);
}
getEffectiveType(properties) {
if (
properties.enum !== undefined &&
["integer", "number", "string"].includes(properties.type)
) {
return `enum_${properties.type}`;
}
if (properties.pattern !== undefined) {
return "regex";
}
if (
properties.type === "array" &&
["boolean", "integer", "number", "string"].includes(properties.items.type)
) {
return `array_${properties.items.type}`;
}
return properties.type;
}
onNameChange(newName, oldName, target) {
const recordValue = this.value;
if (recordValue.properties[newName]) {
this.notification.add(_t("The name should be unique"), { type: "warning" });
target.value = oldName;
return;
}
recordValue.properties[newName] = recordValue.properties[oldName];
delete recordValue.properties[oldName];
recordValue.required = recordValue.required.map((n) => (n === oldName ? newName : n));
this.state.orderArguments = this.state.orderArguments.map((n) =>
n === oldName ? newName : n
);
this.props.record.update({ [this.props.name]: JSON.stringify(recordValue) });
}
onDescriptionChange(value, name) {
const recordValue = this.value;
recordValue.properties[name].description = value;
this.props.record.update({ [this.props.name]: JSON.stringify(recordValue) });
}
onTypeChange(value, name) {
const recordValue = this.value;
delete recordValue.properties[name].enum;
delete recordValue.properties[name].pattern;
delete recordValue.properties[name].items;
delete recordValue.properties[name].maxLength;
if (value.startsWith("enum_")) {
recordValue.properties[name].type = value.split("_").at(-1);
recordValue.properties[name].enum = [];
} else if (value === "regex") {
recordValue.properties[name].type = "string";
recordValue.properties[name].pattern = "";
} else if (value.startsWith("array_")) {
recordValue.properties[name].type = "array";
recordValue.properties[name].items = { type: value.split("_").at(-1) };
} else {
recordValue.properties[name].type = value;
}
if (value === "string") {
recordValue.properties[name].maxLength = 60;
}
this.props.record.update({ [this.props.name]: JSON.stringify(recordValue) });
}
onEnumChange(value, name) {
const recordValue = this.value;
const cast =
{
integer: (v) => parseInt(v) || 0,
number: (v) => parseFloat(v) || 0.0,
}[recordValue.properties[name].type] || ((v) => v);
recordValue.properties[name].enum = (value || "").split(",").map((v) => cast(v.trim()));
this.props.record.update({ [this.props.name]: JSON.stringify(recordValue) });
}
onRegexChange(value, name) {
const recordValue = this.value;
recordValue.properties[name].type = "string";
recordValue.properties[name].pattern = value;
this.props.record.update({ [this.props.name]: JSON.stringify(recordValue) });
}
onMaxLengthChange(maxLength, name) {
maxLength = parseInt(maxLength);
const recordValue = this.value;
if (!maxLength) {
delete recordValue.properties[name].maxLength;
} else {
recordValue.properties[name].maxLength = maxLength;
}
this.props.record.update({ [this.props.name]: JSON.stringify(recordValue) });
}
onRequiredChange(value, name) {
const recordValue = this.value;
if (!value) {
recordValue.required = recordValue.required.filter((n) => n !== name);
} else if (!recordValue.required.includes(name)) {
recordValue.required.push(name);
}
this.props.record.update({ [this.props.name]: JSON.stringify(recordValue) });
}
onDelete(name) {
const recordValue = this.value;
recordValue.required = recordValue.required.filter((n) => n !== name);
this.state.orderArguments = this.state.orderArguments.filter((n) => n !== name);
delete recordValue.properties[name];
this.props.record.update({
[this.props.name]: Object.keys(recordValue.properties).length
? JSON.stringify(recordValue)
: false,
});
}
onNewArgument() {
const recordValue = this.value;
if (recordValue.properties[""]) {
this.tableRef().querySelector("td:first-child input:placeholder-shown").focus();
return;
}
recordValue.properties[""] = { type: "string", maxLength: 60 };
if (!recordValue.required.includes("")) {
recordValue.required.push("");
}
this.state.orderArguments.push("");
this.props.record.update({ [this.props.name]: JSON.stringify(recordValue) });
}
onBlur(ev) {
const value = ev.target.value;
this.props.record.update({ [this.props.name]: value });
}
}
const aiJsonSchema = {
component: AiJsonSchema,
};
registry.category("fields").add("ai_json_schema", aiJsonSchema);

View File

@@ -0,0 +1,10 @@
.o_field_ai_json_schema {
.o_ai_json_schema {
input[type=number] {
max-width: 70px;
}
}
textarea {
resize: none;
}
}

View File

@@ -0,0 +1,134 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="ai.AiJsonSchema">
<t t-if="this.state.technical_mode">
<div>
<textarea
t-ref="this.textareaRef"
class="o_input"
t-on-blur="this.onBlur"
t-out="this.props.record.data[this.props.name] or ''"
/>
</div>
<button class="btn btn-link mt-1"
t-on-click="() => (this.state.technical_mode = false)">
Pretty Edit
</button>
</t>
<t t-else="this.state.technical_mode">
<table class="table o_ai_json_schema">
<thead>
<tr>
<td>
Name
<i
class="oi ml4"
data-icon="help"
role="img"
title="Those parameters will be passed as global variables of the actions."
/>
</td>
<td>Description</td>
<td>Type</td>
<td></td> <!-- Regex / enum -->
<td>Required</td>
<td>Max Length</td>
<td></td> <!-- Delete button -->
</tr>
</thead>
<tbody t-ref="this.tableRef">
<tr t-foreach="this.arguments" t-as="argument" t-key="argument[0]">
<t t-set="name" t-value="argument[0]"/>
<t t-set="values" t-value="argument[1]"/>
<t t-set="required" t-value="argument[2]"/>
<t t-set="arg_type" t-value="argument[3]"/>
<td>
<input
class="o_input"
type="text"
placeholder="eg: name"
t-att-value="name"
t-on-change="(ev) => this.onNameChange(ev.target.value, name, ev.target)"
/>
</td>
<td>
<input
class="o_input"
type="text"
placeholder="eg: New name to write"
t-att-value="values.description"
t-on-change="(ev) => this.onDescriptionChange(ev.target.value, name)"
/>
</td>
<td>
<select
class="o_input pe-3"
t-on-change="(ev) => this.onTypeChange(ev.target.value, name)"
t-on-click.stop="() => {}">
<option
t-foreach="this.types"
t-as="type"
t-key="type[0]"
class="text-black"
t-att-selected="type[0] === arg_type"
t-att-value="type[0]"
t-out="type[1]"
/>
</select>
</td>
<td>
<input
t-if="arg_type.startsWith('enum_')"
class="o_input"
type="text"
placeholder="eg: red, blue, green"
t-att-value="values.enum.join(', ')"
t-on-change="(ev) => this.onEnumChange(ev.target.value, name)"
/>
<input
t-elif="arg_type === 'regex'"
class="o_input"
type="text"
placeholder="eg: ^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$"
t-att-value="values.pattern"
t-on-change="(ev) => this.onRegexChange(ev.target.value, name)"
/>
</td>
<td>
<input
class="form-check-input"
type="checkbox"
t-att-checked="required"
t-on-change="(ev) => this.onRequiredChange(ev.target.checked, name)"
/>
</td>
<td>
<input
t-if="arg_type === 'string'"
class="o_input"
type="number"
t-att-value="values.maxLength"
t-on-change="(ev) => this.onMaxLengthChange(ev.target.value, name)"
/>
</td>
<td>
<button class="btn text-danger p-0" t-on-click="() => this.onDelete(name)">
<i class="oi" data-icon="delete"/>
</button>
</td>
</tr>
</tbody>
</table>
<button
class="btn btn-link mt-1"
t-on-click="() => this.onNewArgument()">
Add
</button>
<button
class="btn btn-link mt-1"
t-on-click="() => (this.state.technical_mode = true)">
Edit
</button>
</t>
</t>
</templates>

View File

@@ -0,0 +1,160 @@
import {
ModelFieldSelectorPopover,
modelFieldSelectorPopoverProps,
} from "@web/core/model_field_selector/model_field_selector_popover";
import { user } from "@web/core/user";
import { useService } from "@web/core/utils/hooks";
import { onWillStart, useProps, proxy, t } from "@odoo/owl";
export class AiModelFieldSelectorPopover extends ModelFieldSelectorPopover {
static template = "ai.AiModelFieldSelectorPopover";
props = useProps({
...modelFieldSelectorPopoverProps,
updateBatch: t.function(),
fieldsPath: t.array().optional(),
aiFieldPath: t.string().optional(),
readProperty: t.boolean().optional(true),
});
setup() {
this.aiFieldsState = proxy({ selected: [] });
this.orm = useService("orm");
onWillStart(async () => {
if (this.props.fieldsPath) {
await this._loadFields(this.props.fieldsPath);
}
});
this.isTemplateEditor = null;
this.allowedQwebExpressions = null;
return super.setup();
}
get fieldNames() {
// Can not use `page.path`, because properties have custom code
const currentPath = [];
let page = this.state.page.previousPage;
while (page) {
currentPath.push(page.selectedName);
page = page.previousPage;
}
const currentPathStr = currentPath.reverse().join(".");
return super.fieldNames.filter((f) => {
const path = currentPathStr ? `${currentPathStr}.${f}` : f;
if (this.props.aiFieldPath && this.props.aiFieldPath === path) {
return false;
}
return true;
});
}
async selectField(field) {
if (field.type === "properties") {
return this.followRelation(field);
}
this.state.page.selectedName = field.name;
// Check if this exact field chain already exists in selected fields
if (this.isFieldSelected(field)) {
return;
}
this.keepLast.add(Promise.resolve());
this.aiFieldsState.selected.push([...this.fieldsChain, field]);
if (!(await user.hasGroup("mail.group_mail_template_editor"))) {
// If the user is not template editor, he won't be able to select many fields
this.onInsert();
}
}
get fieldsChain() {
let page = this.state.page.previousPage;
const fieldsChain = [];
while (page) {
fieldsChain.push(page.fieldDefs[page.selectedName]);
page = page.previousPage;
}
return fieldsChain.reverse();
}
onInsert() {
this.props.updateBatch(this.aiFieldsState.selected);
this.props.close();
}
onRemoveField(path) {
this.aiFieldsState.selected = this.aiFieldsState.selected.filter((f) => f[0] !== path);
}
async beforeFilter() {
if (this.isTemplateEditor === null) {
const getAllowedQwebExpressions = this.env.services["allowed_qweb_expressions"];
this.isTemplateEditor = await user.hasGroup("mail.group_mail_template_editor");
this.allowedQwebExpressions = await getAllowedQwebExpressions(this.props.resModel);
}
}
async followRelations() {
await this.beforeFilter();
return super.followRelations(...arguments);
}
async loadPages() {
await this.beforeFilter();
return super.loadPages(...arguments);
}
filter(fieldDefs, path) {
fieldDefs = super.filter(fieldDefs, path);
const filteredKeys = Object.keys(fieldDefs).filter((key) => {
const fullPath = `object${path ? `.${path}` : ""}.${fieldDefs[key].name}`;
if (!this.isTemplateEditor && !this.allowedQwebExpressions?.includes(fullPath)) {
return false;
}
if (fieldDefs[key].type === "separator") {
// Don't show separator property
return false;
}
return fieldDefs[key].searchable;
});
return Object.fromEntries(filteredKeys.map((k) => [k, fieldDefs[k]]));
}
/**
* Load the list of field path in the popover state.
*/
async _loadFields(fieldsPath) {
const fieldsInfos = Object.fromEntries(
await Promise.all(
fieldsPath.map(async (path) => [
path,
await this.fieldService.loadPath(this.props.resModel, path, true),
])
)
);
const selected = [];
for (const path of fieldsPath) {
const { names, modelsInfo } = await fieldsInfos[path];
const fieldsInfo = [];
for (let i = 0; i < names.length; i++) {
const f = modelsInfo[i].fieldDefs[names[i]];
fieldsInfo.push(f);
}
selected.push(fieldsInfo);
}
this.aiFieldsState.selected = selected;
}
isFieldSelected(fieldDef) {
const fullFieldPath = [...this.fieldsChain, fieldDef].map((f) => f.name).join(".");
// Check if this path exists in selected fields
return this.aiFieldsState.selected.some(
(selectedChain) => selectedChain.map((f) => f.name).join(".") === fullFieldPath
);
}
}

View File

@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8" ?>
<templates xml:space="preserve">
<t t-name="ai.AiModelFieldSelectorPopover" t-inherit="web.ModelFieldSelectorPopover" t-inherit-mode="primary">
<xpath expr="//div[hasclass('o_model_field_selector_popover_body')]" position="before">
<div>
<div
class="badge bg-primary m-1 text-white rounded d-inline-flex flex-row align-items-center text-break"
t-foreach="this.aiFieldsState.selected"
t-as="field"
t-key="field.map(f => f.name).join('.')"
>
<span class="text-wrap" t-out="field.map(f => f.string).join(' > ')"/>
<a href="#" class="oi ms-1 text-white my-0 py-0" data-icon="close" t-on-click="() => this.onRemoveField(field[0])"/>
</div>
</div>
</xpath>
<xpath expr="//t[@t-out='fieldDef.string']" position="replace">
<t t-if="this.isFieldSelected(fieldDef)">
<strong t-out="fieldDef.string"/>
</t>
<t t-else="">
<t t-out="fieldDef.string"/>
</t>
<i class="oi text-success ms-2" data-icon="check" t-if="this.isFieldSelected(fieldDef)"/>
</xpath>
<xpath expr="//div[hasclass('o_model_field_selector_popover_body')]//t[@t-if='fieldDef.record_name']" position="attributes">
<attribute name="t-if">fieldDef.record_name &amp;&amp; (!fieldDef.is_property || this.state.page.previousPage?.previousPage)</attribute>
</xpath>
<xpath expr="//div[hasclass('o_model_field_selector_popover_footer')]" position="replace">
<div t-if="this.aiFieldsState.selected.length" class="d-flex flex-row m-2">
<button class="btn btn-primary me-2" t-on-click="this.onInsert">
Insert
</button>
<button class="btn btn-secondary" t-on-click="() => this.props.close()">
Discard
</button>
</div>
</xpath>
<xpath expr="//div[hasclass('o_model_field_selector_popover')]" position="attributes">
<attribute name="class" add="o_ai_model_field_selector_popover" separator=" "/>
</xpath>
</t>
</templates>

View File

@@ -0,0 +1,87 @@
import { AiModelFieldSelectorPopover } from "@ai/ai_model_field_selector/ai_model_field_selector_popover";
import { Plugin } from "@html_editor/plugin";
import { withSequence } from "@html_editor/utils/resource";
import { _t } from "@web/core/l10n/translation";
import { isHtmlContentSupported } from "@html_editor/core/selection_plugin";
export const AI_FIELD_SELECTOR = "span[data-ai-field]";
export class AIFieldSelectorPlugin extends Plugin {
static id = "AIFieldSelector";
static dependencies = ["overlay", "selection", "history", "dom"];
static shared = ["open"];
resources = {
user_commands: [
{
id: "openAIFieldSelector",
title: _t("Field Selector"),
description: _t("Insert a field"),
icon: _t("tag"),
run: () => this.open(),
isAvailable: isHtmlContentSupported,
},
],
normalize_processors: withSequence(-1, this.normalize.bind(this)),
powerbox_categories: { id: "ai_prompt_tools", name: _t("AI Prompt Tools") },
powerbox_items: { categoryId: "ai_prompt_tools", commandId: "openAIFieldSelector" },
selectors_for_feff_providers: () => AI_FIELD_SELECTOR,
};
setup() {
/** @type {import("@html_editor/core/overlay_plugin").Overlay} */
this.overlay = this.dependencies.overlay.createOverlay(AiModelFieldSelectorPopover, {
hasAutofocus: true,
className: "popover",
});
}
normalize(element) {
// make sure fields are always protected (could be added without this plugin)
for (const fieldEl of element.querySelectorAll(AI_FIELD_SELECTOR)) {
fieldEl.dataset.oeProtected = true;
}
return element;
}
open(fieldsPath) {
this.overlay.open({
props: {
close: this.close.bind(this),
resModel: this.config.fieldSelectorResModel,
aiFieldPath: this.config.aiFieldPath,
followRelation: true,
isDebugMode: this.config.debug,
showSearchInput: true,
update: (path, field) => {},
updateBatch: (fieldsInfo) => this.insert(fieldsInfo),
fieldsPath: fieldsPath,
},
});
}
close() {
this.overlay.close();
this.dependencies.selection.focusEditable();
}
/**
* Insert the given fields as <span data-ai-field="path">name</span>
*
* @param {Array} fieldsInfo: list of field to insert
*/
insert(fieldsInfo) {
if (!fieldsInfo) {
return;
}
for (const fieldInfo of fieldsInfo) {
const span = document.createElement("span");
const fieldChain = fieldInfo.map((field) => field.name).join(".");
span.dataset.aiField = fieldChain;
span.innerText = fieldInfo.map((field) => field.string).join(" > ");
this.dependencies.dom.insert(span);
this.dependencies.dom.insert(fieldInfo === fieldsInfo.at(-1) ? "\u00A0" : ", ");
}
this.dependencies.history.commit();
}
}

View File

@@ -0,0 +1,191 @@
import { AI_FIELD_SELECTOR, AIFieldSelectorPlugin } from "@ai/ai_prompt/ai_field_selector_plugin";
import {
AI_RECORD_SELECTOR,
AIRecordsSelectorPlugin,
} from "@ai/ai_prompt/ai_records_selector_plugin";
import { FeffPlugin } from "@html_editor/main/feff_plugin";
import { HintPlugin } from "@html_editor/main/hint_plugin";
import { PlaceholderPlugin } from "@html_editor/main/placeholder_plugin";
import { PowerboxPlugin } from "@html_editor/main/powerbox/powerbox_plugin";
import { SearchPowerboxPlugin } from "@html_editor/main/powerbox/search_powerbox_plugin";
import { CORE_PLUGINS } from "@html_editor/plugin_sets";
import { childNodeIndex } from "@html_editor/utils/position";
import { withSequence } from "@html_editor/utils/resource";
import { Wysiwyg } from "@html_editor/wysiwyg";
import { Dialog } from "@web/core/dialog/dialog";
import { localization } from "@web/core/l10n/localization";
import { isHtmlEmpty } from "@web/core/utils/html";
import { DebugModePlugin } from "@web/core/debug_mode_plugin";
import { Component, markup, proxy, onPatched, t, usePlugin, useProps } from "@odoo/owl";
export class AiPrompt extends Component {
static template = "ai.AiPrompt";
static components = { Wysiwyg };
props = useProps({
comodel: t.string().optional(),
domain: t.string().optional(),
model: t.string().optional(),
onChange: t.function().optional(),
placeholder: t.string().optional(),
prompt: t.string(),
readonly: t.boolean().optional(),
aiFieldPath: t.string().optional(),
missingRecordsWarning: t.string().optional(),
updatePrompt: t.function().optional(),
});
debugMode = usePlugin(DebugModePlugin);
setup() {
this.state = proxy({
key: 0,
hasRecords: this.props.prompt.includes("data-ai-record"),
});
this.lastValue = this.props.prompt;
let prev = { ...this.props };
onPatched(() => {
const { prompt, comodel, domain } = this.props;
const promptChanged = `${prompt || ""}` !== `${prev.prompt || ""}`;
const configChanged = comodel !== prev.comodel || domain !== prev.domain;
prev = { prompt, comodel, domain };
if (promptChanged) {
if (`${prompt || ""}` === `${this.lastValue || ""}`) {
return;
}
this.lastValue = prompt;
} else if (!configChanged) {
return;
}
this.state.key++;
});
}
get content() {
const elContent = this.editor.getElContent();
if (isHtmlEmpty(elContent.innerText)) {
return "";
}
return elContent.innerHTML;
}
get hasRecords() {
return Boolean(this.editor.getElContent().querySelector(AI_RECORD_SELECTOR));
}
get missingRecordsWarning() {
return this.props.comodel && !this.state.hasRecords && this.props.missingRecordsWarning;
}
get value() {
return markup(this.props.prompt || "<p><br></p>");
}
getConfig() {
return {
content: this.value,
debug: this.debugMode.isActive(),
direction: localization.direction || "ltr",
aiFieldPath: this.props.aiFieldPath,
fieldSelectorResModel: this.props.model,
getRecordInfo: () => {
const { resModel, resId } = this.props.record;
return { resModel, resId };
},
onChange: () => this.onChange(),
onEditorReady: () => (this.state.hasRecords = this.hasRecords),
placeholder: this.props.placeholder,
Plugins: [
...CORE_PLUGINS,
AIFieldSelectorPlugin,
AIRecordsSelectorPlugin,
FeffPlugin,
HintPlugin,
PlaceholderPlugin,
PowerboxPlugin,
SearchPowerboxPlugin,
],
baseContainers: ["DIV"],
recordsSelectorDomain: this.props.domain,
recordsSelectorResModel: this.props.comodel,
// small hack to continue to show the placeholder when the widget is focused but empty
resources: {
hints: [
withSequence(20, {
selector: ".odoo-editor-editable > p:only-child",
text: this.props.placeholder,
}),
],
},
};
}
onBlur() {
const content = this.content;
if (content !== this.lastValue) {
this.props.updatePrompt(this.content);
this.lastValue = content;
}
}
onChange() {
this.state.hasRecords = this.hasRecords;
this.props.onChange?.();
}
onClick(ev) {
ev.preventDefault();
ev.stopPropagation();
const target = ev.target?.closest(`${AI_FIELD_SELECTOR}, ${AI_RECORD_SELECTOR}`);
if (!target) {
return;
}
// select the target to remove it when we will insert
this.editor.shared.selection.setSelection({
anchorNode: target.parentElement,
anchorOffset: childNodeIndex(target),
focusOffset: childNodeIndex(target) + 1,
});
if (target.matches(AI_FIELD_SELECTOR)) {
this.editor.shared.AIFieldSelector.open([target.dataset.aiField]);
} else if (this.props.comodel) {
this.editor.shared.AIRecordsSelector.open([Number(target.dataset.aiRecordId)]);
}
}
onEditorLoad(editor) {
this.editor = editor;
}
}
export class AiPromptDialog extends Component {
static template = "ai.AiPromptDialog";
static components = { Dialog, AiPrompt };
props = useProps({
aiPromptProps: t.object(),
close: t.function(),
confirm: t.function(),
});
setup() {
super.setup();
this.confirmVals = { prompt: this.props.aiPromptProps.prompt };
}
get aiPromptProps() {
return {
...this.props.aiPromptProps,
updatePrompt: (prompt) => (this.confirmVals.prompt = prompt),
};
}
confirm() {
this.props.confirm(this.confirmVals.prompt);
this.props.close();
}
}

View File

@@ -0,0 +1,3 @@
span[data-ai-record-id], span[data-ai-field] {
background-color: rgba(36, 154, 255, 0.16) !important;
}

View File

@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8" ?>
<templates xml:space="preserve">
<t t-name="ai.AiPrompt">
<span t-if="this.props.readonly" class="o_readonly_ai_prompt" t-out="this.value"/>
<t t-else="">
<div class="o_ai_prompt border-bottom" t-on-click="this.onClick">
<Wysiwyg
config="this.getConfig()"
onBlur.bind="this.onBlur"
onLoad.bind="this.onEditorLoad"
t-key="this.state.key"/>
</div>
<div t-if="this.missingRecordsWarning" t-out="this.missingRecordsWarning" class="alert alert-warning mt-1 mb-0" role="alert"/>
</t>
</t>
<t t-name="ai.AiPromptDialog">
<Dialog size="this.md" bodyClass="'o_ai_prompt_dialog'" title.translate="Edit Prompt">
<AiPrompt t-props="this.aiPromptProps"/>
<t t-set-slot="footer">
<button class="btn btn-primary" t-on-click="this.confirm">
Save
</button>
<button class="btn btn-secondary" t-on-click="this.props.close">
Discard
</button>
</t>
</Dialog>
</t>
</templates>

View File

@@ -0,0 +1,75 @@
import { _t } from "@web/core/l10n/translation";
import { registry } from "@web/core/registry";
import { AiPrompt } from "./ai_prompt";
import { standardFieldProps } from "@web/views/fields/standard_field_props";
import { Component, t, useProps } from "@odoo/owl";
export class AiPromptField extends Component {
static template = "ai.AiPromptField";
props = useProps({
...standardFieldProps,
// Field containing the model name that will be updated
modelReferenceField: t.string(),
// Field containing the field name that will be updated
fieldReferenceField: t.string().optional(),
placeholder: t.string().optional(),
// If we update a relational field, field containing the model for which we will choose candidate values
recordSelectorRelationField: t.string().optional(),
recordSelectorDomain: t.string().optional(),
showMissingRecordsWarning: t.boolean().optional(),
});
static components = { AiPrompt };
get updatedFieldName() {
return this.props.record.data[this.props.fieldReferenceField];
}
get recordSelectorRelation() {
return this.props.record.data[this.props.recordSelectorRelationField];
}
get missingRecordsMessage() {
return _t("Insert records the AI can use with the '/record' command");
}
get modelName() {
return this.props.record.data[this.props.modelReferenceField];
}
get prompt() {
return this.props.record.data[this.props.name] || "";
}
onChange() {
this.props.record.model.bus.trigger("FIELD_IS_DIRTY", true);
}
updatePrompt(value) {
if (value !== this.prompt) {
this.props.record.update({ [this.props.name]: value });
}
}
}
export const aiPrompt = {
component: AiPromptField,
supportedTypes: ["html"],
additionalClasses: ["d-inline"],
extractProps: ({ attrs, options }) => {
return {
placeholder: attrs.placeholder,
modelReferenceField: options.model_reference_field,
fieldReferenceField: options.field_reference_field,
recordSelectorRelationField: options.record_selector_relation_field,
recordSelectorDomain: options.record_selector_domain,
showMissingRecordsWarning: Boolean(options.show_missing_records_warning),
};
},
};
registry.category("fields").add("ai_prompt", aiPrompt);

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8" ?>
<templates xml:space="preserve">
<t t-name="ai.AiPromptField">
<AiPrompt
comodel="this.recordSelectorRelation"
model="this.modelName"
onChange.bind="this.onChange"
updatePrompt.bind="this.updatePrompt"
missingRecordsWarning="this.props.showMissingRecordsWarning ? this.missingRecordsMessage : undefined"
placeholder="this.props.placeholder"
prompt="this.prompt"
readonly="this.props.readonly"
aiFieldPath="this.updatedFieldName"
domain="this.props.recordSelectorDomain"/>
</t>
</templates>

View File

@@ -0,0 +1,112 @@
import { RecordsSelectorPopover } from "@ai/records_selector_popover/records_selector_popover";
import { Plugin } from "@html_editor/plugin";
import { withSequence } from "@html_editor/utils/resource";
import { Domain } from "@web/core/domain";
import { ERROR_INACCESSIBLE_OR_MISSING } from "@web/core/name_service";
import { _t } from "@web/core/l10n/translation";
import { isHtmlContentSupported } from "@html_editor/core/selection_plugin";
export const AI_RECORD_SELECTOR = "span[data-ai-record-id]";
export class AIRecordsSelectorPlugin extends Plugin {
static id = "AIRecordsSelector";
static dependencies = ["overlay", "selection", "history", "dom"];
static shared = ["open", "updateDisplayNames"];
resources = {
user_commands: [
{
id: "openAIRecordsSelector",
title: _t("Records Selector"),
description: _t("Insert records"),
icon: "checklist",
run: () => this.open(),
isAvailable: (selection) =>
!!this.config.recordsSelectorResModel && isHtmlContentSupported(selection),
},
],
normalize_processors: withSequence(-1, this.normalize.bind(this)),
powerbox_items: { categoryId: "ai_prompt_tools", commandId: "openAIRecordsSelector" },
selectors_for_feff_providers: () => AI_RECORD_SELECTOR,
on_editor_started_handlers: this.updateDisplayNames.bind(this),
};
setup() {
/** @type {import("@html_editor/core/overlay_plugin").Overlay} */
this.overlay = this.dependencies.overlay.createOverlay(RecordsSelectorPopover, {
hasAutofocus: true,
className: "popover",
});
}
normalize(element) {
// make sure records are always protected (could be added without this plugin)
for (const recordEl of element.querySelectorAll(AI_RECORD_SELECTOR)) {
recordEl.dataset.oeProtected = true;
}
return element;
}
async updateDisplayNames() {
const recordEls = this.editable.querySelectorAll(AI_RECORD_SELECTOR);
if (recordEls.length === 0) {
return;
}
if (!this.config.recordsSelectorResModel) {
for (const recordEl of recordEls) {
recordEl.innerText = _t("Invalid Record");
}
return;
}
// display names might have been updated, making the prompt incoherent (because references
// to these records in the prompt were not updated). They are therefore updated so that the
// user can observe that the prompt needs to be reworked.
const recordIds = [...recordEls].map((el) => Number(el.dataset.aiRecordId));
const displayNames = await this.services.name.loadDisplayNames(
this.config.recordsSelectorResModel,
recordIds
);
for (const recordEl of recordEls) {
if (displayNames[recordEl.dataset.aiRecordId] === ERROR_INACCESSIBLE_OR_MISSING) {
recordEl.innerText = _t("Invalid Record");
} else if (recordEl.innerText !== displayNames[recordEl.dataset.aiRecordId]) {
recordEl.innerText = displayNames[recordEl.dataset.aiRecordId];
}
}
}
open(resIds = []) {
this.overlay.open({
props: {
close: this.close.bind(this),
domain: new Domain(this.config.recordsSelectorDomain || "[]").toList(),
resModel: this.config.recordsSelectorResModel,
validate: (resIds) => this.insert(resIds),
resIds: resIds,
},
});
}
close() {
this.overlay.close();
this.dependencies.selection.focusEditable();
}
async insert(resIds) {
if (!resIds?.length) {
return;
}
const displayNames = await this.services.name.loadDisplayNames(
this.config.recordsSelectorResModel,
resIds
);
for (const resId of resIds) {
const span = document.createElement("span");
span.dataset.aiRecordId = resId;
span.innerText = displayNames[resId];
this.dependencies.dom.insert(span);
this.dependencies.dom.insert(resId === resIds.at(-1) ? "\u00A0" : ", ");
}
this.dependencies.history.commit();
}
}

View File

@@ -0,0 +1,46 @@
import { aiClientToolsRegistry } from "@ai/discuss/core/common/ai_client_tool_registry";
import { AlertDialog } from "@web/core/confirmation_dialog/confirmation_dialog";
import { _t } from "@web/core/l10n/translation";
aiClientToolsRegistry.add("reload", async (thread, params) => {
await thread.store.env.services.action.doAction({
type: "ir.actions.client",
tag: "soft_reload",
});
});
aiClientToolsRegistry.add("do_action", async (thread, params) => {
await thread.store.env.services.action.doAction(params.action);
});
aiClientToolsRegistry.add("show_view", async (thread, params) => {
const { services } = thread.store.env;
const { action, options = {}, menuId = null } = params;
if (menuId) {
options.clearBreadcrumbs = true;
options.onActionReady = () => services.menu.setCurrentMenu(menuId);
}
await services.action.doAction(action, options);
});
aiClientToolsRegistry.add("adjust_view", async (thread, params) => {
const { env } = thread.store;
const switchViewType = params.switchViewType;
if (switchViewType) {
try {
await env.services.action.switchView(switchViewType);
} catch {
env.services.dialog.add(AlertDialog, {
body: _t(
"Tried to switch to %s but the app is no longer in an action window.",
switchViewType,
),
title: _t("Unable to switch view"),
confirm: () => {},
confirmLabel: _t("Close"),
});
return;
}
}
env.bus.trigger("APPLY_AI_ADJUST_SEARCH", params);
});

View File

@@ -0,0 +1,16 @@
import { Component, useProps, t } from "@odoo/owl";
import { CheckBox } from "@web/core/checkbox/checkbox";
export class AiSessionToggle extends Component {
static template = "ai.SessionToggle";
static components = { CheckBox };
props = useProps({
aiSession: t.object(),
configAttribute: t.string(),
});
setup() {
this.attr = this.props.configAttribute;
}
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="ai.SessionToggle">
<span class="ms-4"/>
<CheckBox
id="this.props.aiSession.id"
value="this.props.aiSession.config[this.attr]"
className="'o_field_boolean o_boolean_toggle form-switch m-0 pe-none ms-auto '"
/>
</t>
</templates>

View File

@@ -0,0 +1,81 @@
import { Component, computed, onMounted, onWillUnmount, useProps, signal, t } from "@odoo/owl";
export class AudioVisualizer extends Component {
static template = "ai.AudioVisualizer";
props = useProps({
frequencies: t.instanceOf(Uint8Array),
maxHeight: t.number().optional(32),
});
barsWrapperRef = signal.ref();
barCount = signal(0)
barHeights = computed(() => this.downsampleFrequencies(this.props.frequencies, this.barCount()));
setup() {
super.setup();
this.resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
// The computation here results from the following formula
// 4 * (n-1) + 3n + 8 = width
// where 4 is the size of the gap between bars in pixels (corresponds to gap-1),
// 3 the width of each bar,
// 8 the summed horizontal padding of the component (px-1 class),
// and n the number of bars.
//
// By simplifying we obtain:
// 7n + 4 = width
// and then n = (width - 4) / 7
this.barCount.set(Math.floor((entry.borderBoxSize[0].inlineSize * 0.9 - 4) / 7));
}
});
onMounted(() => {
this.resizeObserver.observe(this.barsWrapperRef());
});
onWillUnmount(() => {
this.resizeObserver.unobserve(this.barsWrapperRef());
});
}
/**
* Downsamples the frequencies array from frequencies.length to outputLength
*
* @param {Uint8Array} frequencies frequencies to downsample
* @param {number} outputLength the length to downsample the frequencies array to
* @return {Uint8Array} the downsampled array
*/
downsampleFrequencies(frequencies, outputLength) {
if (frequencies.length <= outputLength) {
return frequencies;
}
const rateRatio = frequencies.length / outputLength;
const outputFrequencies = new Float32Array(outputLength);
let binCount = 0;
let outputIndex = 0;
let currentValue = 0;
for (let i = 0; i < frequencies.length; i++) {
const currentOutputIndex = Math.floor(i / rateRatio);
if (outputIndex !== currentOutputIndex) {
const average = currentValue / binCount;
outputFrequencies[currentOutputIndex] = (average / 255) * this.props.maxHeight;
outputIndex = currentOutputIndex;
currentValue = 0;
binCount = 0;
}
binCount++;
currentValue += frequencies[i];
}
if (binCount > 0) {
const average = currentValue / binCount;
outputFrequencies[outputIndex] = (average / 255) * this.props.maxHeight;
}
return outputFrequencies;
}
}

View File

@@ -0,0 +1,9 @@
.o-ai-audio-visualizer-bar {
transition: height 75ms ease-out;
$width: 3px;
width: $width;
min-height: $width;
background-color: var(--link-color, lightgray);
border-radius: $width/2;
}

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates>
<t t-name="ai.AudioVisualizer">
<div t-ref="this.barsWrapperRef" class="d-flex flex-grow-1 gap-1 justify-content-center align-items-center px-1">
<t t-foreach="this.barHeights()" t-as="frequency" t-key="frequency_index">
<div class="o-ai-audio-visualizer-bar" t-attf-style="height: {{frequency}}px;"></div>
</t>
</div>
</t>
</templates>

View File

@@ -0,0 +1,162 @@
import { url } from "@web/core/utils/urls";
import { AITranscriptionEvent, transcriptionBus } from "@ai/core/transcription_bus";
const VADState = {
SILENCE: "silence",
SPEECH: "speech",
};
export const ProcessorState = {
IDLE: "idle",
RECORDING: "recording",
PAUSED: "paused",
STOPPED: "stopped",
};
export default class AudioProcessor {
/** @type{AudioProcessor} */
static instance = null;
/**
* @param {function(string): void} onStateChange function called when the state is updated
*/
constructor(
analyserOptions = {
fftSize: 128,
}
) {
this.analyserOptions = analyserOptions;
if (this.audioContext?.state === "running") {
this._state = "recording";
} else {
this._state = "idle";
}
this.animationFrame = null;
this.silenceTimer = null;
/** @type {AudioContext} */
this.audioContext = null;
/** @type {MediaStream} */
this.audioStream = null;
/** @type {AnalyserNode} */
this.analyserNode = null;
}
/**
* Retrieves the singleton instance of the AudioProcessor.
*
* @param {function(string): void} onStateChange function called when the state is updated
*/
static getInstance(
analyserOptions = {
fftSize: 128,
}
) {
if (AudioProcessor.instance === null) {
AudioProcessor.instance = new AudioProcessor(analyserOptions);
}
return AudioProcessor.instance;
}
get state() {
return this._state;
}
set state(newState) {
if (this._state !== newState) {
this._state = newState;
transcriptionBus.trigger(AITranscriptionEvent.AUDIO_PROCESSOR_STATE, newState);
}
}
async start() {
if (this.audioStream === null) {
this.audioStream = await navigator.mediaDevices.getUserMedia({
audio: true,
});
}
if (!this.audioContext || this.audioContext.state === "closed") {
this.audioContext = new AudioContext();
const audioContext = this.audioContext;
const sourceNode = audioContext.createMediaStreamSource(this.audioStream);
this.analyserNode = audioContext.createAnalyser();
const workletUrl = url("/ai/static/src/core/audio/pcm16_audio_worklet.js");
await audioContext.audioWorklet.addModule(workletUrl);
const pcm16AudioProcessorNode = new AudioWorkletNode(audioContext, "pcm16-processor");
if (audioContext.state === "suspended") {
await audioContext.resume();
}
sourceNode.connect(this.analyserNode);
this.analyserNode.connect(pcm16AudioProcessorNode);
pcm16AudioProcessorNode.connect(audioContext.destination);
pcm16AudioProcessorNode.port.onmessage = (event) => {
const payload = event.data;
if (payload.type === "audio") {
transcriptionBus.trigger(
AITranscriptionEvent.AUDIO_PROCESSOR_DATA,
new Uint8Array(payload.data)
);
} else if (payload.type === "vad") {
if (payload.state === VADState.SILENCE) {
if (this.state === ProcessorState.RECORDING) {
this.state = ProcessorState.PAUSED;
this.silenceTimer = setTimeout(() => {
if (this.state === ProcessorState.PAUSED) {
this.state = ProcessorState.STOPPED;
}
}, 1000);
}
} else {
if (this.state !== ProcessorState.RECORDING) {
clearTimeout(this.silenceTimer);
this.silenceTimer = null;
}
this.state = ProcessorState.RECORDING;
}
}
};
}
this.state = ProcessorState.RECORDING;
this.runFrequencyAnalysis();
}
runFrequencyAnalysis() {
const analyseFrequencies = () => {
const data = new Uint8Array(this.analyserNode.frequencyBinCount);
this.analyserNode.getByteFrequencyData(data);
transcriptionBus.trigger(AITranscriptionEvent.AUDIO_PROCESSOR_FREQUENCY, data);
this.animationFrame = requestAnimationFrame(analyseFrequencies);
};
this.animationFrame = requestAnimationFrame(analyseFrequencies);
}
stop() {
if (this.animationFrame) {
cancelAnimationFrame(this.animationFrame);
this.animationFrame = null;
}
if (this.silenceTimer) {
clearTimeout(this.silenceTimer);
this.silenceTimer = null;
}
if (this.audioContext) {
this.audioContext.close();
this.audioContext = null;
}
if (this.audioStream) {
this.audioStream.getTracks().forEach((track) => track.stop());
this.audioStream = null;
}
this.state = ProcessorState.IDLE;
}
}

View File

@@ -0,0 +1,113 @@
// This class has several responsibility:
// - Merge the channels of an stereo audio source that to a mono output,
// - Down-sample the original input to a certain sample rate (i.e. 24kHz),
// - Finally, buffer the audio to send bigger chunks at a time.
class PCM16AudioWorklet extends AudioWorkletProcessor {
constructor(options) {
super(options);
this.maxBufferSize = 2400;
this.buffer = new Int16Array(this.maxBufferSize);
this.nextInsertPointer = 0; // Next position to insert data into the buffer
this.isSpeech = false;
this.threshold = 0.01;
}
/**
* Main method of the worklet, used to process audio and send it to the result to the main thread
*
* @param {Array<Array<Float32Array>>} inputs the list of inputs. Each of them containing a list of channels.
* @returns {boolean} true to force the worklet to stay active, false otherwise.
*/
process(inputs) {
const input = inputs[0];
if (input.length > 0) {
const inputChannel = this.combine(input);
// Here we down-sample the input channel to 24kHz
// This is used by the real-time transcription feature to be compliant
// with OpenAI's APIs
// sampleRate is injected from the AudioWorkletGlobalScope from audioContext.sampleRate
// eslint-disable-next-line no-undef
const downsampledChannel = this.downsample(inputChannel, sampleRate, 24000);
for (let i = 0; i < downsampledChannel.length; i++) {
const sample = Math.max(-1, Math.min(1, downsampledChannel[i]));
// If the next insert position is bellow the max buffer size
// then we insert a new element
// Otherwise
// We commit the buffer and reset the insert pointer
if (this.nextInsertPointer < this.maxBufferSize) {
// Converting Float32 into Int16
this.buffer[this.nextInsertPointer] =
sample < 0 ? sample * 0x8000 : sample * 0x7fff;
this.nextInsertPointer++;
} else {
this.port.postMessage({ type: "audio", data: this.buffer.buffer });
this.buffer = new Int16Array(this.maxBufferSize);
this.nextInsertPointer = 0;
}
}
// Voice Activity Detection
let sum = 0;
for (let i = 0; i < inputChannel.length; i++) {
sum += inputChannel[i] ** 2;
}
const rms = Math.sqrt(sum / inputChannel.length);
const isSpeech = rms > this.threshold;
if (this.isSpeech !== isSpeech) {
this.isSpeech = isSpeech;
this.port.postMessage({ type: "vad", state: this.isSpeech ? "speech" : "silence" });
}
}
return true;
}
/**
* Downsamples the buffer from the inputRate to the outputRate.
* The downsampling will take every inputRate/outputRate samples from the input buffer and put them in the ouput.
* @param {Float32Array} buffer the input audio buffer
* @param {Number} inputRate the source rate of the buffer
* @param {Number} outputRate the sampling rate of the output
* @returns {Float32Array} a downsampled version of the input buffer
*/
downsample(buffer, inputRate, outputRate) {
if (inputRate === outputRate) {
return buffer;
}
const rateRatio = inputRate / outputRate;
const downsampledLength = Math.round(buffer.length / rateRatio);
const outputBuffer = new Float32Array(downsampledLength);
for (let i = 0; i < outputBuffer.length; i++) {
outputBuffer[i] = buffer[Math.floor(i * rateRatio)];
}
return outputBuffer;
}
/**
* Combines multi-channels input into a mono channel output.
* This method will produce a channel where each element is the average
* of the corresponding elements in the source channels.
* @param {Array<Float32Array>} channels the channels to combine
* @returns {Float32Array} the combined channel
*/
combine(channels) {
const monoChannel = new Float32Array(channels[0].length);
for (let i = 0; i < monoChannel.length; i++) {
for (let j = 0; j < channels.length; j++) {
monoChannel[i] += channels[j][i];
}
monoChannel[i] = monoChannel[i] / channels.length;
}
return monoChannel;
}
}
registerProcessor("pcm16-processor", PCM16AudioWorklet);

View File

@@ -0,0 +1,11 @@
declare module "models" {
export interface Attachment {
description: string|undefined;
image_height: number|undefined;
image_src: string|undefined;
image_width: number|undefined;
original_id: number|undefined;
public: boolean|undefined;
res_id: number|undefined;
}
}

View File

@@ -0,0 +1,25 @@
import { Attachment } from "@mail/core/common/attachment_model";
import { patch } from "@web/core/utils/patch";
patch(Attachment.prototype, {
setup() {
super.setup(...arguments);
// media fields of the editor, appended to every attachment payload by
// ir.attachment._store_attachment_fields when ai is installed
/** @type {string|undefined} */
this.description = undefined;
/** @type {number|undefined} */
this.image_height = undefined;
/** @type {string|undefined} */
this.image_src = undefined;
/** @type {number|undefined} */
this.image_width = undefined;
/** @type {number|undefined} */
this.original_id = undefined;
/** @type {boolean|undefined} */
this.public = undefined;
/** @type {number|undefined} */
this.res_id = undefined;
},
});

View File

@@ -0,0 +1,77 @@
import { Plugin } from "@html_editor/plugin";
import { MAIN_PLUGINS } from "@html_editor/plugin_sets";
import { HISTORY_COMMIT_TYPES } from "@html_editor/core/history_plugin"
import { aiChannelDataRegistry } from "@ai/utils/ai_channel_data_registry";
export class AIImagePlugin extends Plugin {
static id = "aiImage";
static dependencies = ["selection"];
resources = {
on_history_commit_undone_handlers: (lastCommitUndone) =>
this.restoreChannelImageToReplace(lastCommitUndone, HISTORY_COMMIT_TYPES.UNDO),
on_history_commit_redone_handlers: (lastCommitRedone) =>
this.restoreChannelImageToReplace(lastCommitRedone, HISTORY_COMMIT_TYPES.REDO),
on_media_replaced_handlers: ({ newMediaEl }) =>
this.updateChannelImageToReplace(newMediaEl),
on_media_added_handlers: ({ newMediaEl }) =>
this.updateChannelImageInsertionPosition(newMediaEl),
on_will_save_handlers: async () => await this.markAttachmentsUsed(),
};
restoreChannelImageToReplace(lastCommitReversed, mode) {
if (lastCommitReversed.data.currentTarget) {
let targetEl = lastCommitReversed.data.currentTarget;
const nextTarget = lastCommitReversed.data.nextTarget;
if (!nextTarget) {
return;
}
const aiChannelId = targetEl.dataset.aiChannelId || nextTarget.dataset.aiChannelId;
if (mode === HISTORY_COMMIT_TYPES.REDO && (nextTarget || nextTarget === false)) {
targetEl = nextTarget;
}
if (targetEl && aiChannelId) {
aiChannelDataRegistry.setData(aiChannelId, "imageToReplace", targetEl);
}
}
}
updateChannelImageToReplace(newMediaEl) {
if (!newMediaEl.dataset.aiChannelId) {
return;
}
aiChannelDataRegistry.setData(newMediaEl.dataset.aiChannelId, "imageToReplace", newMediaEl);
}
updateChannelImageInsertionPosition(element) {
if (!element.dataset.aiChannelId) {
return;
}
aiChannelDataRegistry.setData(
element.dataset.aiChannelId,
"imageInsertionPosition",
this.dependencies.selection.getEditableSelection()
);
}
async markAttachmentsUsed() {
// When the media dialog is used to add an attachment (image), a copy is created from that
// attachment and the copy is used on the website. The copy has a reference `data-attachment-id`
// to the original attachment. So, the original attachment should not be deleted.
const editableEl = this.editable;
const aiGeneratedImageElements = [...editableEl.querySelectorAll("[data-ai-channel-id]")];
for (const element of aiGeneratedImageElements) {
delete element.dataset.aiChannelId;
}
const attachmentIds = aiGeneratedImageElements.map((el) =>
parseInt(el.dataset.attachmentId)
);
if (attachmentIds.length) {
await this.services.orm.call("ai.attachment.vacuum", "mark_attachments_used", [], {
attachment_ids: attachmentIds,
});
}
}
}
MAIN_PLUGINS.push(AIImagePlugin);

View File

@@ -0,0 +1,12 @@
import { BannerPlugin } from "@html_editor/main/banner_plugin";
import { closestElement } from "@html_editor/utils/dom_traversal";
import { patch } from "@web/core/utils/patch";
patch(BannerPlugin.prototype, {
onBannerEmojiChange(iconElement) {
if (closestElement(iconElement, ".o_editor_prompt")) {
return;
}
return super.onBannerEmojiChange(iconElement);
},
});

View File

@@ -0,0 +1,13 @@
import { Editor } from "@html_editor/editor";
import { patch } from "@web/core/utils/patch";
import { aiChannelBus } from "@ai/utils/ai_channel_bus";
patch(Editor.prototype, {
destroy(willBeRemoved) {
super.destroy(willBeRemoved);
// get aiSpecialActions() of MediaDialog captures this (the media dialog instance) because of the lambda function
// which indirectly makes the ai channel hold a reference to the editor. This reference is not updated once the editor
// is destroyed. Thus, the UseThis action won't function properly and has to be dropped.
aiChannelBus.trigger("AI: Drop UseThis Action");
},
});

View File

@@ -0,0 +1,32 @@
import { HtmlField, htmlField, htmlFieldProps } from "@html_editor/fields/html_field";
import { AIFieldSelectorPlugin } from "@ai/ai_prompt/ai_field_selector_plugin";
import { registry } from "@web/core/registry";
import { useProps, t } from "@odoo/owl";
export class AIFieldSelectorHtmlField extends HtmlField {
props = useProps({
...htmlFieldProps,
// The name of the field that references the model whose fields will be shown to the user when using /field
aiFieldSelectorModelReferenceField: t.string(),
});
getConfig() {
const config = super.getConfig();
config["Plugins"] = [...config["Plugins"], AIFieldSelectorPlugin];
config["fieldSelectorResModel"] =
this.props.record.data[this.props.aiFieldSelectorModelReferenceField];
return config;
}
}
export const aiFieldSelectorHtmlField = {
...htmlField,
component: AIFieldSelectorHtmlField,
extractProps({ attrs, options }, dynamicInfo) {
const props = htmlField.extractProps({ attrs, options }, dynamicInfo);
const aiFieldSelectorModelReferenceField = options.aiFieldSelectorModelReferenceField;
return { ...props, aiFieldSelectorModelReferenceField };
},
};
registry.category("fields").add("ai_field_selector_html_field", aiFieldSelectorHtmlField);

View File

@@ -0,0 +1,17 @@
import { patch } from "@web/core/utils/patch";
import { ImageFieldWithMediaDialog } from "@html_editor/fields/image_field_with_media_dialog/image_field_with_media_dialog";
patch(ImageFieldWithMediaDialog.prototype, {
get mediaDialogProps() {
const props = super.mediaDialogProps;
props.record = this.props.record;
props.originalRecordModel = this.props.record.model.config.resModel;
props.originalRecordId = this.props.record.model.config.resId;
props.aiSpecialActions = this.aiSpecialActions;
return props;
},
get aiSpecialActions() {
return {};
},
});

View File

@@ -0,0 +1,17 @@
import { patch } from "@web/core/utils/patch";
import { X2ManyImageField } from "@html_editor/fields/x2many_field/x2many_image_field";
patch(X2ManyImageField.prototype, {
get mediaDialogProps() {
const props = super.mediaDialogProps;
props.record = this.props.record._parentRecord;
props.originalRecordModel = this.props.record.config.resModel;
props.originalRecordId = this.props.record.config.resId;
props.aiSpecialActions = this.aiSpecialActions;
return props;
},
get aiSpecialActions() {
return {};
},
});

View File

@@ -0,0 +1,17 @@
import { patch } from "@web/core/utils/patch";
import { X2ManyMediaViewer } from "@html_editor/fields/x2many_field/x2many_media_viewer";
patch(X2ManyMediaViewer.prototype, {
get mediaDialogProps() {
const props = super.mediaDialogProps;
props.record = this.props.record;
props.originalRecordModel = this.props.record.model.config.resModel;
props.originalRecordId = this.props.record.model.config.resId;
props.aiSpecialActions = this.aiSpecialActions;
return props;
},
get aiSpecialActions() {
return {};
},
});

View File

@@ -0,0 +1,40 @@
import { FileSelectorControlPanel } from "@html_editor/main/media/media_dialog/file_selector";
import { t, useProps } from "@odoo/owl";
import { patch } from "@web/core/utils/patch";
import { useService } from "@web/core/utils/hooks";
import { getData } from "@ai/utils/bus_data_getter";
import { aiChannelDataRegistry } from "@ai/utils/ai_channel_data_registry";
patch(FileSelectorControlPanel.prototype, {
setup() {
super.setup();
this.aiControlPanelProps = useProps({
allowAI: t.boolean().optional(),
});
this.aiChatLauncherService = useService("aiChatLauncher");
},
async openAIChat(ev) {
const mediaDialogData = (await getData("mediaDialog")) || {};
const channel = await this.aiChatLauncherService.launchAIChat({
interfaceKey: "media_dialog",
channelTitle: mediaDialogData["record"]?.data.display_name,
recordModel: mediaDialogData["originalRecordModel"],
recordId: mediaDialogData["originalRecordId"],
aiChatSourceId: mediaDialogData["originalRecordId"],
referenceImagePath: mediaDialogData["imagePath"],
aiSpecialActions: mediaDialogData["aiSpecialActions"] || {},
});
channel.targetRecord = mediaDialogData["record"];
channel.fromShopExtraImage = mediaDialogData["fromShopExtraImage"];
aiChannelDataRegistry.setData(channel.id, "imageToReplace", mediaDialogData["imageNode"]);
aiChannelDataRegistry.setData(
channel.id,
"imageInsertionPosition",
mediaDialogData["editorSelection"]
);
if (mediaDialogData["aiBeforeCloseHandler"]) {
mediaDialogData["aiBeforeCloseHandler"](channel.id);
}
mediaDialogData["mediaDialogCloseFunction"]();
},
});

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates>
<t t-name="ai_html_editor.FileSelectorControlPanel" t-inherit="html_editor.FileSelectorControlPanel" t-inherit-mode="extension">
<xpath expr="//input[@name='url']" position="before">
<t t-if="this.aiControlPanelProps.allowAI">
<button
class="border-0 bg-transparent"
t-on-click="this.openAIChat"
title="Generate Image with AI"
>
<img src="/ai/static/description/icon.png" style="height: 22px;" alt="AI"/>
</button>
</t>
</xpath>
</t>
</templates>

View File

@@ -0,0 +1,8 @@
import { patch } from "@web/core/utils/patch";
import { FileSelector } from "@html_editor/main/media/media_dialog/file_selector";
patch(FileSelector.prototype, {
get isAIAllowed() {
return false;
},
});

View File

@@ -0,0 +1,7 @@
<templates id="template" xml:space="preserve">
<t t-name="ai_html_editor.FileSelector" t-inherit="html_editor.FileSelector" t-inherit-mode="extension">
<xpath expr="//FileSelectorControlPanel" position="attributes">
<attribute name="allowAI">this.isAIAllowed</attribute>
</xpath>
</t>
</templates>

View File

@@ -0,0 +1,8 @@
import { patch } from "@web/core/utils/patch";
import { ImageSelector } from "@html_editor/main/media/media_dialog/image_selector";
patch(ImageSelector.prototype, {
get isAIAllowed() {
return true;
},
});

View File

@@ -0,0 +1,14 @@
import { patch } from "@web/core/utils/patch";
import { CustomMediaDialog } from "@html_editor/fields/x2many_field/custom_media_dialog";
import { convertAttachmentRecordToObject } from "@ai/core/html_editor/media_dialog/media_dialog_utils";
patch(CustomMediaDialog.prototype, {
async aiSaveAction({ message }) {
const imageAttachment = message.attachment_ids.filter((attachment) =>
attachment.mimetype.includes("image")
)[0];
const imageAttachmentObject = convertAttachmentRecordToObject(imageAttachment);
imageAttachmentObject.mediaType = "attachment";
await this.props.imageSave([imageAttachmentObject]);
},
});

View File

@@ -0,0 +1,97 @@
import { convertAttachmentRecordToObject } from "@ai/core/html_editor/media_dialog/media_dialog_utils";
import { aiChannelDataRegistry } from "@ai/utils/ai_channel_data_registry";
import { useDataGetter } from "@ai/utils/bus_data_getter";
import { MediaDialog } from "@html_editor/main/media/media_dialog/media_dialog";
import { renderMedia } from "@html_editor/main/media/media_dialog/media_dialog_utils";
import { t, useProps } from "@odoo/owl";
import { patch } from "@web/core/utils/patch";
import { imageUrl } from "@web/core/utils/urls";
patch(MediaDialog.prototype, {
setup() {
super.setup();
this.aiProps = useProps({
addHistoryStep: t.function().optional(),
aiSave: t.function().optional(),
aiSpecialActions: t.any().optional(),
editorSelection: t.any().optional(),
node: t.object().optional(),
originalRecordId: t.any().optional(),
originalRecordModel: t.string().optional(),
record: t.object().optional(),
});
useDataGetter("mediaDialog", () => this.getMediaDialogData());
},
getMediaDialogData() {
return {
record: this.aiProps.record,
originalRecordModel: this.aiProps.originalRecordModel,
originalRecordId: this.aiProps.originalRecordId,
imagePath: this.getImagePath(),
imageNode: this.aiProps.node,
aiSpecialActions: this.aiSpecialActions,
mediaDialogCloseFunction: () => this.close(),
editorSelection: this.aiProps.editorSelection,
aiBeforeCloseHandler: this.props.aiBeforeCloseHandler,
};
},
getImagePath() {
let fullPath;
if (this.props.imageSrc) {
fullPath = `${window.location.origin}${this.props.imageSrc}`;
}
// If an image is replaced on website but the changes aren't saved yet, then currentSrc will be the
// base64 content of the image and not an actual url. Thus, originalSrc must take precedence over currentSrc.
else if (this.props.media?.dataset.originalSrc) {
fullPath = `${window.location.origin}${this.props.media.dataset.originalSrc}`;
} else if (this.props.media?.currentSrc) {
fullPath = this.props.media.currentSrc;
} else if (this.aiProps.originalRecordModel && this.aiProps.originalRecordId) {
fullPath = imageUrl(
this.aiProps.originalRecordModel,
this.aiProps.originalRecordId,
"image_1024"
);
}
if (!fullPath) {
return "";
}
const urlObject = new URL(fullPath);
return urlObject.pathname + urlObject.search;
},
get aiSpecialActions() {
return Object.keys(this.aiProps.aiSpecialActions || {}).length
? this.aiProps.aiSpecialActions
: { useThis: (content) => this.aiSaveAction(content) };
},
async aiSaveAction({ channel, message, store }) {
const imageAttachment = message.attachment_ids.filter((attachment) =>
attachment.mimetype.includes("image")
)[0];
const imageAttachmentObject = convertAttachmentRecordToObject(imageAttachment);
imageAttachmentObject.mediaType = "attachment";
const oldMediaNode = aiChannelDataRegistry.getData(channel.id, "imageToReplace");
const element = (
await renderMedia({
orm: store.env.services.orm,
activeTab: "IMAGES",
availableTabs: this.tabs,
oldMediaNode: oldMediaNode,
selectedMedia: [imageAttachmentObject],
extraClassesToAdd: this.extraClassesToAdd(),
extraClassesToRemove: this.initialIconClasses,
})
)[0];
element.dataset.aiChannelId = channel.id;
const saveFn = this.aiProps.aiSave || this.props.save;
await saveFn(element, [imageAttachmentObject], "IMAGES", oldMediaNode);
this.aiProps.addHistoryStep?.();
},
});

View File

@@ -0,0 +1,9 @@
import { ATTACHMENT_FIELDS } from "@html_editor/main/media/media_dialog/file_selector";
export function convertAttachmentRecordToObject(attachment_record) {
const imageAttachmentObject = {};
for (const attachment_field of ATTACHMENT_FIELDS) {
imageAttachmentObject[attachment_field] = attachment_record[attachment_field];
}
return imageAttachmentObject;
}

View File

@@ -0,0 +1,20 @@
import { MediaPlugin } from "@html_editor/main/media/media_plugin";
import { patch } from "@web/core/utils/patch";
import { aiChannelDataRegistry } from "@ai/utils/ai_channel_data_registry";
patch(MediaPlugin.prototype, {
openMediaDialog(params = {}, editableEl = null) {
params.addHistoryStep = this.dependencies.history.commit;
params.editorSelection = this.dependencies.selection.getEditableSelection();
return super.openMediaDialog(params, editableEl);
},
async addMedia(element) {
if (element.dataset.aiChannelId) {
this.dependencies.selection.setSelection(
aiChannelDataRegistry.getData(element.dataset.aiChannelId, "imageInsertionPosition")
);
}
super.addMedia(element);
},
});

View File

@@ -0,0 +1,52 @@
import { _t } from "@web/core/l10n/translation";
import { Plugin } from "@html_editor/plugin";
import { DYNAMIC_FIELD_PLUGINS } from "@html_editor/backend/dynamic_field/dynamic_field_plugin";
import { isHtmlContentSupported } from "@html_editor/core/selection_plugin";
import { htmlEscape } from "@odoo/owl";
import { parseHTML } from "@html_editor/utils/html";
export class PromptPlugin extends Plugin {
static id = "prompt";
static dependencies = ["dom", "history", "selection"];
resources = {
user_commands: [
{
id: "prompt",
title: _t("Prompt"),
description: _t("Insert an AI prompt"),
icon: "flash_on",
run: this.insertPrompt.bind(this),
isAvailable: isHtmlContentSupported,
},
],
powerbox_items: [
{
commandId: "prompt",
categoryId: "ai",
},
],
};
insertPrompt() {
const emojiHtml = `<i class="o_editor_banner_icon mb-3 fst-normal" data-oe-aria-label="${htmlEscape(
_t("Prompt")
)}">⚡</i>`;
const bannerElement = parseHTML(
this.document,
`<div class="o_editor_prompt o_editor_banner user-select-none o-contenteditable-false lh-1
d-flex align-items-center alert alert-primary pb-0 pt-3 ps-3 pe-3" data-oe-role="status">
${emojiHtml}
<div class="o_editor_prompt_content o_editor_banner_content o-contenteditable-true w-100 px-3">
<div><br></div>
</div>
</div>`
).childNodes[0];
this.dependencies.dom.insert(bannerElement);
this.dependencies.selection.setCursorEnd(
bannerElement.querySelector(`.o_editor_prompt_content > div`)
);
this.dependencies.history.commit();
}
}
DYNAMIC_FIELD_PLUGINS.push(PromptPlugin);

View File

@@ -0,0 +1,19 @@
import { UserCommandPlugin } from "@html_editor/core/user_command_plugin";
import { closestElement } from "@html_editor/utils/dom_traversal";
import { patch } from "@web/core/utils/patch";
patch(UserCommandPlugin.prototype, {
getCommand(commandId) {
const command = super.getCommand(commandId);
return {
...command,
isAvailable: (selection) => {
if (closestElement(selection.anchorNode, ".o_editor_prompt")) {
// Only the "insertField" command is available inside a prompt.
return ["insertField", "historyUndo", "historyRedo"].includes(commandId);
}
return !command.isAvailable || command.isAvailable(selection);
},
};
},
});

View File

@@ -0,0 +1,66 @@
import { AITranscriptionEvent, transcriptionBus } from "@ai/core/transcription_bus";
export default class RealtimeClient {
/**
* @type {RealtimeClient}
*/
static instance = null;
constructor() {
/** @type {WebSocket} */
this.socket = null;
this.messageListener = (event) => {
const jsonData = JSON.parse(event.data);
transcriptionBus.trigger(AITranscriptionEvent.REALTIME_CLIENT_MESSAGE, jsonData);
};
}
/**
* @returns {RealtimeClient} the instance of the RealtimeClient
*/
static getInstance() {
if (RealtimeClient.instance === null) {
RealtimeClient.instance = new RealtimeClient();
}
return RealtimeClient.instance;
}
/**
* Starts the websocket connection
*
* @param {String} sessionToken
*/
connect(sessionToken) {
this.socket = new WebSocket("wss://api.openai.com/v1/realtime", [
"realtime",
`openai-insecure-api-key.${sessionToken}`,
]);
this.socket.addEventListener("message", this.messageListener);
}
/**
* Sends audio data to the provider
*
* @param {Uint8Array} buffer the data to send
*/
send(buffer) {
if (this.socket !== null && this.socket.readyState === WebSocket.OPEN) {
this.socket.send(
JSON.stringify({
type: "input_audio_buffer.append",
audio: btoa(String.fromCharCode(...buffer)),
})
);
}
}
disconnect() {
if (this.socket !== null) {
this.socket.close();
this.socket.removeEventListener("message", this.messageListener);
this.socket = null;
}
}
}

View File

@@ -0,0 +1,15 @@
import { router } from "@web/core/browser/router";
import { patch } from "@web/core/utils/patch";
import AudioProcessor from "./audio/audio_processor";
import RealtimeClient from "./realtime_client";
patch(router, {
pushState() {
super.pushState(...arguments);
const audioProcessor = AudioProcessor.getInstance();
const realtimeClient = RealtimeClient.getInstance();
audioProcessor?.stop();
realtimeClient?.disconnect();
},
});

View File

@@ -0,0 +1,10 @@
import { EventBus } from "@odoo/owl";
export const AITranscriptionEvent = {
AUDIO_PROCESSOR_DATA: "AUDIO_PROCESSOR_DATA",
AUDIO_PROCESSOR_STATE: "AUDIO_PROCESSOR_STATE",
AUDIO_PROCESSOR_FREQUENCY: "AUDIO_PROCESSOR_FREQUENCY",
REALTIME_CLIENT_MESSAGE: "REALTIME_CLIENT_MESSAGE",
};
export const transcriptionBus = new EventBus();

View File

@@ -0,0 +1,75 @@
import { Component, markRaw, t, useProps } from "@odoo/owl";
import { CommandPalette, defaultCommandItemProps } from "@web/core/commands/command_palette";
import { _t } from "@web/core/l10n/translation";
import { registry } from "@web/core/registry";
import { useService } from "@web/core/utils/hooks";
import { highlightText } from "@web/core/utils/html";
import { patch } from "@web/core/utils/patch";
const commandProviderRegistry = registry.category("command_provider");
class AskAICommand extends Component {
static template = "ai.AskAICommand";
props = useProps({
imgUrl: t.string(),
...defaultCommandItemProps,
});
}
async function askAIProvide(aiChatLauncher, options) {
return [
{
action: async () => {
await aiChatLauncher.launchAIChat({
interfaceKey: "systray_ai_button", // own key?
userMessage: options.searchValue,
});
},
category: "app",
Component: AskAICommand,
props: { imgUrl: "/ai/static/description/icon.png" },
name: _t("Ask AI"),
},
];
}
commandProviderRegistry.add("ask_ai", {
namespace: "/",
provide(options) {
const aiChatLauncher = useService("aiChatLauncher");
return askAIProvide(aiChatLauncher, options);
},
});
// TODO: Add a unit test for this. The Ask AI command should be available in the default
// namespace (CTRL+K) when no commands are found.
patch(CommandPalette.prototype, {
setup() {
super.setup();
this.aiChatLauncher = useService("aiChatLauncher");
},
async setCommands(namespace, options = {}) {
const [askAICommand] = await askAIProvide(this.aiChatLauncher, options);
const result = await super.setCommands(namespace, options);
if (
askAICommand &&
namespace === "default" &&
this.state.commands.length === 0 &&
options.searchValue
) {
this.state.commands = markRaw([
{
...askAICommand,
keyId: this.keyId++,
text: highlightText(
options.searchValue,
askAICommand.name,
"fw-bolder text-primary"
),
},
]);
this.selectCommand(this.state.commands.length ? 0 : -1);
}
return result;
},
});

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8" ?>
<templates xml:space="preserve">
<t t-name="ai.AskAICommand">
<div class="o_command_default position-relative d-flex align-items-center px-4 py-2 cursor-pointer">
<img class="rounded me-2 object-fit-cover" t-if="this.props.imgUrl" t-att-src="this.props.imgUrl" style="width: 25px; height: 25px"/>
<t t-call-slot="name"/>
<span t-if="this.props.searchValue" class="mx-1 flex-shrink-0">"<t t-out="this.props.searchValue"/>"</span>
</div>
</t>
</templates>

View File

@@ -0,0 +1,38 @@
import { GraphController } from "@web/views/graph/graph_controller";
import { patch } from "@web/core/utils/patch";
import { useBus } from "@web/core/utils/hooks";
import { GraphModel } from "@web/views/graph/graph_model";
patch(GraphController.prototype, {
setup() {
super.setup(...arguments);
useBus(this.env.bus, "APPLY_AI_ADJUST_MODEL", async ({ detail }) => {
const { measures, mode, order, stacked, cumulated } = detail;
if (this.model instanceof GraphModel) {
const defaultMetaData = this.model._buildMetaData();
const metaData = this.model._buildMetaData({
measures,
mode: mode ?? defaultMetaData.mode,
order: order ?? defaultMetaData.order,
stacked: stacked ?? defaultMetaData.stacked,
cumulated: cumulated ?? defaultMetaData.stacked,
});
const validMeasures = measures.filter((m) => m in metaData.measures);
const activeMeasures = metaData.activeMeasures || [];
const measuresToActivate = validMeasures.filter((m) => !activeMeasures.includes(m));
// It should only be at most one item, so just take the first.
// This is because graph only allows one active measure.
const measure = measuresToActivate[0] ?? metaData.measure;
if (measure) {
await this.model.updateMetaData({ measure });
}
this.model.updateMetaData({
mode: mode ?? metaData.mode,
order: order ?? metaData.order,
stacked: stacked ?? metaData.stacked,
cumulated: cumulated ?? metaData.cumulated,
});
}
});
},
});

View File

@@ -0,0 +1,35 @@
import { PivotController } from "@web/views/pivot/pivot_controller";
import { patch } from "@web/core/utils/patch";
import { useBus } from "@web/core/utils/hooks";
import { PivotModel } from "@web/views/pivot/pivot_model";
import { computeReportMeasures } from "@web/views/utils";
patch(PivotController.prototype, {
setup() {
super.setup(...arguments);
useBus(this.env.bus, "APPLY_AI_ADJUST_MODEL", async ({ detail }) => {
const { measures } = detail;
if (this.model instanceof PivotModel) {
// Wait for any ongoing model load to avoid overwriting its metadata.
await this.model.race.getCurrentProm();
const metaData = this.model._buildMetaData();
const metaDataMeasures = computeReportMeasures(
metaData.fields,
metaData.fieldAttrs,
[...(metaData.activeMeasures || [])]
);
const validMeasures = measures.filter((m) => m in metaDataMeasures);
const activeMeasures = metaData.activeMeasures || [];
const measuresToToggle = new Set([
...validMeasures.filter((m) => !activeMeasures.includes(m)), // measures to activate
...(validMeasures.length
? activeMeasures.filter((m) => !validMeasures.includes(m))
: []), // measures to deactivate
]);
for (const measure of measuresToToggle) {
await this.model.toggleMeasure(measure);
}
}
});
},
});

View File

@@ -0,0 +1,52 @@
import { SearchBar } from "@web/search/search_bar/search_bar";
import { patch } from "@web/core/utils/patch";
import { useBus } from "@web/core/utils/hooks";
function isDefined(value) {
return value !== undefined && value !== null;
}
patch(SearchBar.prototype, {
setup() {
super.setup(...arguments);
useBus(this.env.bus, "APPLY_AI_ADJUST_SEARCH", async ({ detail }) => {
const searchModel = this.env.searchModel;
for (const facetGroupId of detail.removeFacets) {
searchModel.deactivateGroup(facetGroupId);
}
const {
toggleFilters,
toggleGroupBys,
applySearches,
customDomain,
measures,
mode,
order,
stacked,
cumulated,
} = detail;
await searchModel.applyAISearch({
filters: toggleFilters,
groupBys: toggleGroupBys,
fieldSearches: applySearches,
customDomain,
});
if (
(measures && measures.length) ||
[mode, order, stacked, cumulated].some(isDefined)
) {
this.env.bus.trigger("APPLY_AI_ADJUST_MODEL", {
measures: measures ?? [],
mode,
order,
stacked,
cumulated,
});
}
const chatboxInput = document.querySelector(".o-mail-Composer-input");
if (chatboxInput) {
chatboxInput.focus();
}
});
},
});

View File

@@ -0,0 +1,119 @@
import { SearchModel } from "@web/search/search_model";
import { patch } from "@web/core/utils/patch";
import { GROUPABLE_TYPES } from "@web/search/utils/misc";
const CHAR_FIELDS = ["char", "html", "many2many", "many2one", "one2many", "text", "properties"];
patch(SearchModel.prototype, {
validateField(fieldName, field) {
const { groupable, type } = field;
return groupable && fieldName !== "id" && GROUPABLE_TYPES.includes(type);
},
async applyAISearch({ filters, groupBys, fieldSearches, customDomain }) {
// TODO JCB: support fieldProperty
// TODO JCB: name vs fieldName, which one to use?
for (const filter of filters || []) {
if (typeof filter === "string") {
// Regular filter (string)
const [searchItem] = this.getSearchItems(
(i) => i.type === "filter" && [i.name, i.fieldName].includes(filter)
);
if (searchItem && !searchItem?.isActive) {
this.toggleSearchItem(searchItem.id);
}
} else if (typeof filter === "object" && filter.field_name && filter.selected_periods) {
// Date filter (object with field_name and selected_periods)
const [searchItem] = this.getSearchItems(
(i) => i.type === "dateFilter" && i.fieldName === filter.field_name
);
if (searchItem) {
// duplicates doesn't make sense here, e.g. [year-1, fourth_quarter, year-2, fourth_quarter]
// likely means the fourth_quarter of both year-1 and year-2.
const selectedPeriods = [...new Set(filter.selected_periods)];
for (const periodId of selectedPeriods) {
this.toggleParentFilter(searchItem.id, periodId);
}
}
}
}
for (const groupBy of groupBys || []) {
if (typeof groupBy === "string") {
// Regular groupby (string)
const [searchItem] = this.getSearchItems(
(i) => i.type === "groupBy" && [i.name, i.fieldName].includes(groupBy)
);
if (searchItem && !searchItem?.isActive) {
this.toggleSearchItem(searchItem.id);
} else if (!searchItem) {
const field = this.searchViewFields[groupBy];
if (!field || !this.validateField(groupBy, field)) {
continue;
}
this.createNewGroupBy(groupBy);
}
} else if (typeof groupBy === "object" && groupBy.field_name && groupBy.intervals) {
// Date groupby (object with field_name and intervals)
const [fstInterval, ...remIntervals] = groupBy.intervals;
if (!fstInterval) {
// nothing to do here if no interval is provided
continue;
}
const getSearchItem = () => {
const [searchItem] = this.getSearchItems(
(i) => i.type === "dateGroupBy" && i.fieldName === groupBy.field_name
);
return searchItem;
};
let intervalsToToggle = groupBy.intervals;
if (!getSearchItem()) {
// Create new date groupBy search item for the date field if it doesn't exist
const field = this.searchViewFields[groupBy.field_name];
if (field && ["date", "datetime"].includes(field.type)) {
this.createNewGroupBy(groupBy.field_name, {
interval: fstInterval,
});
}
intervalsToToggle = remIntervals;
}
const searchItem = getSearchItem();
for (const interval of intervalsToToggle) {
this.toggleDateGroupBy(searchItem.id, interval);
}
}
}
for (const searchObject of fieldSearches || []) {
const fieldName = searchObject.search_field;
const value = searchObject.value;
const [searchItem] = this.getSearchItems(
(i) => i.type === "field" && i.fieldName === fieldName
);
if (searchItem) {
this.addAutoCompletionValues(searchItem.id, {
value,
label: value,
operator:
searchItem.operator ||
(CHAR_FIELDS.includes(searchItem.fieldType) ? "ilike" : "="),
});
}
}
if (customDomain && customDomain.length) {
await this.splitAndAddDomain(customDomain);
}
},
async load(config) {
const result = await super.load(config);
if (config.ai && !config.state) {
await this.applyAISearch({
filters: config.ai.selectedFilters,
groupBys: config.ai.selectedGroupBys,
fieldSearches: config.ai.search,
customDomain: config.ai.customDomain,
});
}
return result;
},
});

View File

@@ -0,0 +1,67 @@
import { useSubEnv } from "@web/owl2/utils";
import { patch } from "@web/core/utils/patch";
import { View } from "@web/views/view";
patch(View.prototype, {
setup(...args) {
super.setup(...args);
useSubEnv({
config: {
...this.env.config,
disableSearchBarAutofocus: this.props.ai
? true
: this.env.config.disableSearchBarAutofocus,
},
});
},
async loadView(props) {
await super.loadView(props);
if ("ai" in this.componentProps) {
const aiProps = this.componentProps.ai;
if (this.props.type === "pivot") {
if (aiProps.measures && aiProps.measures.length > 0) {
this.componentProps.modelParams.metaData.activeMeasures = aiProps.measures;
}
if (aiProps.colGroupBys?.length) {
this.componentProps.modelParams.metaData.colGroupBys =
aiProps.colGroupBys.flatMap((groupBy) =>
typeof groupBy === "string"
? groupBy
: groupBy.intervals.map(
(interval) => `${groupBy.field_name}:${interval}`
)
);
}
if (aiProps.sortedColumn) {
// Set up sorted column with empty groupId for total column sorting
this.componentProps.modelParams.metaData.sortedColumn = {
groupId: [[], []], // Empty groupId means sort by total column
measure: aiProps.sortedColumn.measure,
order: aiProps.sortedColumn.order,
};
}
} else if (this.props.type === "graph") {
if (aiProps.measure) {
this.componentProps.modelParams.measure = aiProps.measure;
}
if (aiProps.mode) {
this.componentProps.modelParams.mode = aiProps.mode;
}
if (aiProps.order) {
this.componentProps.modelParams.order = aiProps.order;
}
if (aiProps.stacked !== undefined) {
this.componentProps.modelParams.stacked = aiProps.stacked;
}
if (aiProps.cumulated !== undefined) {
this.componentProps.modelParams.cumulated = aiProps.cumulated;
}
if (aiProps.groupBys && aiProps.groupBys.length > 0) {
this.componentProps.modelParams.groupBy = aiProps.groupBys;
}
}
// Remove ai from componentProps to avoid passing it to the component
delete this.componentProps.ai;
}
},
});

View File

@@ -0,0 +1,32 @@
import { t } from "@odoo/owl";
import { WithSearch, withSearchProps } from "@web/search/with_search/with_search";
import { patch } from "@web/core/utils/patch";
import { useDataGetter } from "@ai/utils/bus_data_getter";
withSearchProps.ai = t.object().optional();
patch(WithSearch.prototype, {
setup() {
super.setup(...arguments);
useDataGetter("view", () => this.getCurrentViewInfo());
},
async getCurrentViewInfo() {
const config = this.env.config;
const searchModel = this.env.searchModel;
const result = {};
// if in form view, no need to return anything
if (config.viewType === "form") {
return;
}
result.action_name = config.actionName;
result.action_id = config.actionId;
result.view_id = config.viewId;
result.model = searchModel.resModel;
result.domain = searchModel.domainString;
result.available_view_types = config.viewSwitcherEntries?.map((v) => v.type) || [];
result.view_type = config.viewType;
result.order_by = searchModel.orderBy;
result.facets = searchModel.facets.map(({ icon, color, ...rest }) => rest);
return result;
},
});

View File

@@ -0,0 +1,5 @@
declare module "menu_tabs" {
export interface MenuTabs {
AI_CHAT: "ai-chat";
}
}

View File

@@ -0,0 +1,55 @@
import { useService } from "@web/core/utils/hooks";
import { Component, onPatched, signal, t, useProps } from "@odoo/owl";
export class AgentToolSummary extends Component {
static template = "ai.AgentToolSummary";
setup() {
super.setup();
this.store = useService("mail.store");
this.orm = useService("orm");
this.props = useProps({
message: t.instanceOf(this.store["mail.message"]),
onAfterToggle: t.function(),
onBeforeToggle: t.function(),
});
this.isUnfolded = signal(false);
this.toolParams = undefined;
onPatched(() => this.props.onAfterToggle());
}
get toolCallId() {
return this.props.message.bodyEl?.querySelector(".o-ai-tool-summary")?.dataset.id;
}
async loadParams() {
const eventId = this.props.message.bodyEl?.querySelector(".o-ai-agent-step")?.dataset.id;
if (!eventId) {
return;
}
const callId = this.toolCallId;
if (!callId) {
return;
}
const toolParams = await this.orm.call("ai.session.event", "get_tool_params", [
Number(eventId),
callId,
]);
this.toolParams = toolParams;
}
async onClickMessage() {
if (!this.toolParams) {
await this.loadParams();
}
this.props.onBeforeToggle();
this.isUnfolded.set(!this.isUnfolded());
}
stringify(value) {
if (typeof value === "object" || value === "") {
return JSON.stringify(value);
}
return value;
}
}

View File

@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="ai.AgentToolSummary">
<div class="ms-3" t-att-class="{'ms-4': this.env.inChatWindow}">
<t t-if="this.store.debugMode.isActive() and this.toolCallId">
<button class="btn btn-link d-flex align-items-center text-muted py-0 ps-0 pe-3 fw-normal" t-on-click="this.onClickMessage">
<t t-out="this.props.message.richBody"/><i class="oi oi-fw ms-1 flex-shrink-0" t-att-class="this.isUnfolded() ? 'mt-1' : 'o-mt-0_5'" t-attf-data-icon="{{this.isUnfolded() ? 'expand_more' : 'chevron_right'}}"/>
</button>
<div class="o-ai-AgentToolSummary-params o-ms-4_5 me-3 overflow-auto text-nowrap" t-if="this.isUnfolded() and this.toolParams">
<table class="table table-sm table-borderless w-auto mb-0">
<tbody>
<tr t-foreach="this.toolParams" t-as="param" t-key="param">
<th scope="row" class="fw-medium text-muted ps-0 pe-1 py-1"><t t-out="param"/>:</th>
<td class="py-1"><code t-out="this.stringify(param_value)"/></td>
</tr>
</tbody>
</table>
</div>
</t>
<span t-else="" class="text-muted" t-out="this.props.message.richBody"/>
</div>
</t>
</templates>

View File

@@ -0,0 +1,256 @@
import { Component, onMounted, proxy, signal, t, useListener, useProps } from "@odoo/owl";
import { getActiveHotkey } from "@web/core/hotkeys/hotkey_utils";
import { useService } from "@web/core/utils/hooks";
export class AIUserInputRequest extends Component {
static template = "ai.UserInputRequest";
setup() {
this.store = useService("mail.store");
this.notification = useService("notification");
this.props = useProps({
request: t.instanceOf(this.store["ai.user.input.request"]),
thread: t.instanceOf(this.store["mail.thread"]),
});
this.state = proxy({
activeIndex: 0,
freeTextValue: "",
isSubmitting: false,
selectedValues: new Set(),
});
this.rootRef = signal.ref();
this.choicesListRef = signal.ref();
onMounted(() => {
// Don't steal focus from another chat window, this widget, or a composer
// where the user has already started typing.
requestAnimationFrame(() => {
const ownChatWindowEl = this.rootRef()?.closest(
".o-mail-ChatWindow, .o-mail-DiscussContent",
);
const active = document.activeElement;
const focusIsOutsideChatWindow =
active && ownChatWindowEl && !ownChatWindowEl.contains(active);
const focusIsAlreadyOnThisWidget = Boolean(this.choicesListRef()?.contains(active));
const hasComposerDraft = active?.matches(".o-mail-Composer-input") && active.value;
if (!focusIsOutsideChatWindow && !focusIsAlreadyOnThisWidget && !hasComposerDraft) {
this.choicesListRef()?.querySelector("button")?.focus();
}
});
});
useListener(
() => this.rootRef(),
"click",
(ev) => {
if (this.choicesListRef()?.contains(ev.target)) {
return;
}
this.focusActiveRow();
},
);
}
get isConfirmation() {
return this.props.request?.type === "confirmation";
}
get rows() {
const choices = this.props.request?.choices ?? [];
const rows = choices.map((data) => ({ type: "option", data }));
if (this.props.request?.allowFreeText) {
rows.push({ type: "text" });
}
return rows;
}
get activeRow() {
return this.rows[this.state.activeIndex];
}
get isFreeTextSelected() {
return Boolean(this.state.freeTextValue.trim());
}
get selectedCount() {
return this.state.selectedValues.size + (this.isFreeTextSelected ? 1 : 0);
}
get areChoicesDisabled() {
return !this.props.request?.multiSelect && this.isFreeTextSelected;
}
get showSkip() {
return Boolean(this.props.request) && !this.isConfirmation;
}
get freeTextInput() {
return this.choicesListRef()?.querySelector("input[type=text]") ?? null;
}
isRowSelected(row) {
return row.type === "text"
? this.isFreeTextSelected
: this.state.selectedValues.has(row.data.value);
}
onRowSelect(row) {
const inputRequest = this.props.request;
if (!inputRequest || !row) {
return;
}
if (row.type === "text") {
this.freeTextInput?.focus();
return;
}
if (inputRequest.multiSelect) {
const { value } = row.data;
if (this.state.selectedValues.has(value)) {
this.state.selectedValues.delete(value);
} else {
this.state.selectedValues.add(value);
}
return;
}
this.submitAnswer([row.data.value], inputRequest);
}
submitFreeText() {
const inputRequest = this.props.request;
const value = this.state.freeTextValue.trim();
if (!inputRequest || !value) {
return;
}
this.submitAnswer([value], inputRequest);
}
confirmMultiSelect() {
const inputRequest = this.props.request;
if (!inputRequest) {
return;
}
const selected = inputRequest.choices.filter((o) => this.state.selectedValues.has(o.value));
const freeText = this.state.freeTextValue.trim();
if (!selected.length && !freeText) {
return;
}
const values = [...selected.map((o) => o.value), ...(freeText ? [freeText] : [])];
this.submitAnswer(values, inputRequest);
}
async skip() {
const inputRequest = this.props.request;
if (!inputRequest) {
return;
}
await this.submitPendingInteractionResponse(inputRequest, { kind: "skip" });
}
async submitPendingInteractionResponse(inputRequest, response) {
if (this.state.isSubmitting) {
return;
}
this.state.isSubmitting = true;
const session = inputRequest.ai_session_id;
const resumeToken = inputRequest.resumeToken;
try {
const acknowledgement = await this.props.thread.requestAiSessionAdvance(
"/ai/resume_pending_interaction",
{
session_id: session.id,
response,
resume_token: resumeToken,
},
);
if (acknowledgement.interactionConsumed !== false) {
if (session.userInputRequest?.resumeToken === resumeToken) {
session.userInputRequest = undefined;
}
if (!this.props.thread.channel.aiInputSession?.userInputRequest) {
this.props.thread.composer.autofocus++;
}
}
} catch (error) {
this.notification.add(error?.message || "The AI interaction could not be submitted.", {
type: "danger",
});
} finally {
this.state.isSubmitting = false;
}
}
async submitAnswer(values, inputRequest) {
const response =
inputRequest.type === "confirmation"
? { kind: "confirmation", value: values[0] }
: { kind: "question", value: values };
await this.submitPendingInteractionResponse(inputRequest, response);
}
/** Restore focus to whatever row is active (used when the surrounding prompt is clicked). */
focusActiveRow() {
const list = this.choicesListRef();
if (!list) {
return;
}
if (this.activeRow?.type === "text") {
list.querySelector("input[type=text]")?.focus();
return;
}
list.querySelectorAll("button")?.[this.state.activeIndex]?.focus();
}
activateRow(index) {
this.state.activeIndex = index;
this.focusActiveRow();
}
onChoicesKeydown(ev) {
const rows = this.rows;
if (rows.length <= 1) {
return;
}
const isTextInput = ev.target === this.freeTextInput;
const hotkey = getActiveHotkey(ev);
switch (hotkey) {
case "space":
if (isTextInput) {
return;
}
break;
case "arrowdown":
if (isTextInput && this.areChoicesDisabled) {
return;
}
this.activateRow(Math.min(this.state.activeIndex + 1, rows.length - 1));
break;
case "arrowup":
if (isTextInput && this.areChoicesDisabled) {
return;
}
this.activateRow(Math.max(this.state.activeIndex - 1, 0));
break;
case "enter":
if (isTextInput && this.isFreeTextSelected && !this.props.request?.multiSelect) {
this.submitFreeText();
} else {
this.onRowSelect(this.activeRow);
}
break;
default: {
if (isTextInput) {
return;
}
// Number shortcuts jump straight to a choice (single-select only).
const index = Number(hotkey) - 1;
const row = rows[index];
if (this.props.request.multiSelect || row?.type !== "option") {
return;
}
this.activateRow(index);
this.onRowSelect(row);
}
}
ev.preventDefault();
ev.stopPropagation();
}
}

View File

@@ -0,0 +1,69 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="ai.UserInputRequest">
<div t-if="this.props.request" t-ref="this.rootRef" class="o_ai_user_input_request mt-1 p-2" t-on-keydown="this.onChoicesKeydown" role="group" t-att-aria-labelledby="'ai-input-' + this.props.request.resumeToken">
<div t-att-id="'ai-input-' + this.props.request.resumeToken">
<div t-if="this.props.request.ai_session_id.parent_session_id" class="fw-bold mb-1" t-out="this.props.thread.channel.aiRootSession.agent_id.name"/>
<div class="text-break" t-out="this.props.request.body"/>
</div>
<t t-set="multiSelect" t-value="this.props.request.multiSelect"/>
<ul t-ref="this.choicesListRef" class="list-unstyled p-0 m-0">
<li t-foreach="this.rows" t-as="row" t-key="row_index">
<button
class="o_ai_option btn btn-sm btn-secondary rounded-2 w-100 mt-2 d-flex align-items-center gap-2 text-start"
t-att-disabled="this.state.isSubmitting or (row.type === 'option' and this.areChoicesDisabled)"
t-on-click="() => this.onRowSelect(row)"
t-on-pointerdown="() => this.activateRow(row_index)"
t-on-focus="() => this.state.activeIndex = row_index"
>
<!-- Left indicator: checkbox (multi-select) or numbered/pencil badge (single-select) -->
<input
t-if="multiSelect"
type="checkbox"
class="flex-shrink-0 mx-2 pe-none"
tabindex="-1"
t-att-checked="this.isRowSelected(row)"
/>
<span t-else="" class="badge rounded-2 bg-200 text-900 fw-normal p-1 flex-shrink-0 d-flex align-items-center justify-content-center lh-1">
<t t-if="row.type === 'option'" t-out="row_index + 1"/>
<i t-else="" class="oi oi-filled" data-icon="edit"/>
</span>
<!--Row content-->
<span t-if="row.type === 'option'" class="flex-grow-1 text-break p-1" t-out="row.data.label"/>
<t t-else="">
<input
type="text"
class="flex-grow-1 min-w-0 border-0 bg-transparent shadow-none p-1"
placeholder="Something else"
t-model.proxy="this.state.freeTextValue"
t-on-focus="() => this.state.activeIndex = this.rows.length - 1"
/>
<i
t-if="!multiSelect and this.isFreeTextSelected"
class="oi flex-shrink-0 px-1" data-icon="send"
t-on-click.stop="this.submitFreeText"
/>
</t>
</button>
</li>
</ul>
<!-- Footer: skip action, and multi-select confirmation. -->
<div t-if="this.showSkip or multiSelect" class="d-flex align-items-center justify-content-end gap-2 mt-2 w-100">
<button
t-if="this.showSkip"
class="btn btn-sm btn-link text-muted p-0"
t-on-click="this.skip"
>Skip</button>
<button
t-if="multiSelect"
class="btn btn-sm btn-secondary rounded-2"
t-att-disabled="this.state.isSubmitting or this.selectedCount === 0"
t-on-click="this.confirmMultiSelect"
>Confirm</button>
</div>
</div>
</t>
</templates>

View File

@@ -0,0 +1,114 @@
body:has(.o-mail-ChatWindow.o-isAiComposer) .o-overlay-item:has(.o-FileViewer),
body:has(.o-mail-ChatWindow.o-isAiComposer) .o-overlay-item:has(.o_dialog):not(:has(.o_error_dialog)) {
z-index: $zindex-offcanvas;
}
body:has(.o-mail-ChatWindow.o-isAiComposer) .o-overlay-item:has(.o-we-toolbar){
z-index: $zindex-offcanvas - 1;
}
.o-mail-ChatWindow.o-isAiComposer{
--mail-ChatWindow-mobileZindex: #{$zindex-offcanvas};
}
.o-mail-ChatHub-bubbles.o-hasAiChat:not(.o-mobile),
.o-mail-ChatHub .o-mail-ChatWindow.o-isAiComposer:not(.o-mobile) {
z-index: $zindex-offcanvas + 1;
}
.ai-chat-prompt-button {
margin: 4px 8px 0 0;
padding: 0 4px;
text-align: justify;
}
.o-mail-Discuss .o-mail-Message:has(div.ai-message-body) {
width: 75%;
.ai-pre-response {
width: 60%
}
}
.ai-message-body {
padding-top: 0 !important;
padding-bottom: 0 !important;
> *:last-child {
margin-bottom: 0px;
}
:is(h2, h3, h4):not(:first-child) {
margin-top: 12px !important;
}
li > p {
margin-bottom: 0px;
}
h1 {
font-size: 1.3rem;
}
h2 {
font-size: 1.2rem;
}
.ai-table-response {
display: block;
max-width: 100%;
width: fit-content;
overflow-x: auto;
td {
min-width: 120px;
max-width: 400px;
}
th {
white-space: nowrap;
}
}
.ai-pre-response {
.ai-code-response {
display: block;
min-width: max-content;
}
}
}
@media (max-width: 1500px) {
.o-mail-Message:has(div.ai-message-body) {
width: 100% !important;
}
.ai-pre-response {
width: 100% !important;
}
}
.o-ai-AgentToolSummary-params {
max-height: 15rem;
}
.o_ai_user_input_request {
margin-inline: 0.5rem;
.o_ai_option {
&:hover .badge {
background-color: $o-gray-300 !important;
}
&:focus-within {
background-color: var(--btn-hover-bg) !important;
border-color: transparent !important;
box-shadow: 0 0 0 0.1rem RGBA(#{$btn-link-focus-shadow-rgb}, .5) !important;
outline: none;
.badge {
background-color: $o-gray-300 !important;
}
}
input:focus {
outline: none;
box-shadow: none;
}
}
}

View File

@@ -0,0 +1,11 @@
import { ChatHub } from "@mail/core/common/chat_hub";
import { patch } from "@web/core/utils/patch";
patch(ChatHub.prototype, {
get bubblesAttClass() {
return {
...super.bubblesAttClass,
"o-hasAiChat": this.chatHub.folded.some((chatWindow) => chatWindow.channel.isAiChat),
};
},
});

View File

@@ -0,0 +1,31 @@
import { ChatWindow } from "@mail/core/common/chat_window";
import { patch } from "@web/core/utils/patch";
patch(ChatWindow.prototype, {
get attClass() {
return {
...super.attClass,
"o-isAiComposer": this.channel.isAiChat,
};
},
get showAiPreviousChatSuggestion() {
return (
this.channel.isAiChat &&
this.channel.isEmpty &&
this.channel.suggestedAiChannel?.exists() &&
!this.channel.suggestedAiChannel.chatWindow?.isOpen
);
},
dismissAiPreviousChatSuggestion() {
this.channel.suggestedAiChannel = undefined;
},
async reopenSuggestedAiChannel() {
const currentChatWindow = this.props.chatWindow;
const suggestedChannel = this.channel.suggestedAiChannel;
this.dismissAiPreviousChatSuggestion();
if (this.channel.exists() && this.channel.isEmpty) {
await currentChatWindow.requestClose();
}
await suggestedChannel.openChatWindow({ focus: true });
},
});

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-inherit="mail.ChatWindow" t-inherit-mode="extension">
<xpath expr="//Thread" position="before">
<div t-if="this.showAiPreviousChatSuggestion" class="d-flex align-items-center gap-2 px-3 py-2 border-bottom text-info bg-info-subtle">
<span class="small text-truncate flex-grow-1">
New chat started.
<a href="#" class="link-info fw-semibold" t-on-click.prevent="this.reopenSuggestedAiChannel">
Resume previous chat
<i role="img" class="oi o-xsmaller ms-1" data-icon="chevron_right"/>
</a>
</span>
<button class="btn btn-link btn-sm p-0 text-muted flex-shrink-0" type="button" title="Dismiss" t-on-click="this.dismissAiPreviousChatSuggestion">
<i class="oi" data-icon="close"/>
</button>
</div>
</xpath>
</t>
</templates>

View File

@@ -0,0 +1,198 @@
import { patch } from "@web/core/utils/patch";
import {
registerComposerAction,
ComposerAction,
describeComposerActionGroup,
} from "@mail/core/common/composer_actions";
import { VoiceRecorder } from "@mail/discuss/voice_message/common/voice_recorder";
import { Component } from "@odoo/owl";
import { AiSessionToggle } from "@ai/components/ai_composer_actions_selectors/ai_session_toggle";
import { _t } from "@web/core/l10n/translation";
patch(ComposerAction.prototype, {
_getAiComposerActions() {
return [
"send-message",
"upload-files",
"voice-start",
"voice-recording",
"voice-transcribing",
"toggle-think-longer",
"toggle-restrict-to-resources",
"toggle-web-search",
"toggle-action-auto-approve",
"toggle-agent-steps",
];
},
_condition({ composer, owner }) {
if (composer.targetThread?.channel?.isAiChat) {
const hasText = !!composer.composerText;
const hasAttachments = composer.attachments && composer.attachments.length > 0;
// Replace "empty" Send button with Dictate
if (this.id === "send-message" && !hasText && !hasAttachments) {
return false;
}
// Replace Dictate with Send or Recorder
if (this.id === "voice-start" && hasText) {
return false;
}
if (this.id === "voice-start" && owner?.voiceTranscription?.isTranscribing) {
return false;
}
}
if (
composer.targetThread?.channel?.isAiChat &&
!this._getAiComposerActions().includes(this.id)
) {
return false;
}
return super._condition(...arguments);
},
_name({ composer }) {
if (composer.targetThread?.channel?.isAiChat) {
if (this.id === "send-message") {
return _t("Send (%(keyboard_command)s)", { keyboard_command: "Enter" });
}
if (this.id === "voice-start") {
return _t("Voice Message (%(keyboard_command)s)", { keyboard_command: "Alt+V" });
}
}
return super._name(...arguments);
},
_sequence({ composer }) {
if (composer.targetThread?.channel?.isAiChat && this.id === "voice-start") {
// Remove the microphone from the bottom "Extra Actions" toolbar
return undefined;
}
return super._sequence(...arguments);
},
_sequenceQuick({ composer }) {
if (composer.targetThread?.channel?.isAiChat && this.id === "voice-start") {
// Place microphone next to text input
return 25;
}
return super._sequenceQuick(...arguments);
},
});
patch(VoiceRecorder.prototype, {
get title() {
if (this.props.composer.targetThread?.channel?.isAiChat) {
return _t("Convert to text (%(keyboard_command_1)s) or Send (%(keyboard_command_2)s)", {
keyboard_command_1: "Alt+V",
keyboard_command_2: "Enter",
});
}
return super.title;
},
get cancelTitle() {
if (this.props.composer.targetThread?.channel?.isAiChat) {
return _t("Cancel (%(keyboard_command)s)", { keyboard_command: "Esc" });
}
return super.cancelTitle;
},
});
describeComposerActionGroup(20, { name: _t("AI Chat Settings") });
registerComposerAction("voice-transcribing", {
component: class VoiceMessageTranscribingSpinner extends Component {
static template = "ai.VoiceMessageTranscribingSpinner";
},
condition: ({ composer, owner }) =>
composer.targetThread?.channel?.isAiChat && owner?.voiceTranscription?.isTranscribing,
sequenceQuick: 11,
});
registerComposerAction("toggle-action-auto-approve", {
condition: ({ composer }) => composer.targetThread?.channel?.isAiChat,
closingModeAsDropdown: "none",
extraContentComponent: AiSessionToggle,
extraContentComponentProps: ({ composer }) => ({
aiSession: composer.targetThread.channel.aiSession,
configAttribute: "auto_confirm",
}),
icon: "verified",
name: _t("Auto-Approve Actions"),
onSelected({ composer }) {
const aiSession = composer.targetThread.channel.aiSession;
aiSession.updateConfig("auto_confirm", !aiSession.config["auto_confirm"]);
},
sequence: 20,
sequenceGroup: 20,
});
registerComposerAction("toggle-web-search", {
condition: ({ composer }) => composer.targetThread?.channel?.isAiChat,
closingModeAsDropdown: "none",
extraContentComponent: AiSessionToggle,
extraContentComponentProps: ({ composer }) => ({
aiSession: composer.targetThread.channel.aiSession,
configAttribute: "enable_web_search",
}),
icon: "search",
name: _t("Web Search"),
onSelected({ composer }) {
const aiSession = composer.targetThread.channel.aiSession;
aiSession.updateConfig("enable_web_search", !aiSession.config["enable_web_search"]);
},
sequence: 21,
sequenceGroup: 20,
});
registerComposerAction("toggle-restrict-to-resources", {
condition: ({ composer }) =>
composer.targetThread?.channel?.isAiChat &&
(composer.targetThread?.channel?.ai_agent_id?.sources_ids?.length ?? 0) > 0,
closingModeAsDropdown: "none",
extraContentComponent: AiSessionToggle,
extraContentComponentProps: ({ composer }) => ({
aiSession: composer.targetThread.channel.aiSession,
configAttribute: "enable_resources_only",
}),
icon: "book",
name: _t("Restrict to Sources"),
onSelected({ composer }) {
const aiSession = composer.targetThread.channel.aiSession;
aiSession.updateConfig("enable_resources_only", !aiSession.config["enable_resources_only"]);
},
sequence: 22,
sequenceGroup: 20,
});
registerComposerAction("toggle-agent-steps", {
condition: ({ composer }) => composer.targetThread?.channel?.isAiChat,
closingModeAsDropdown: "none",
extraContentComponent: AiSessionToggle,
extraContentComponentProps: ({ composer }) => ({
aiSession: composer.targetThread.channel.aiSession,
configAttribute: "show_agent_steps",
}),
icon: "checklist",
name: _t("Show Steps"),
onSelected({ composer }) {
const aiSession = composer.targetThread.channel.aiSession;
aiSession.updateConfig("show_agent_steps", !aiSession.config["show_agent_steps"]);
},
sequence: 23,
sequenceGroup: 20,
});
registerComposerAction("toggle-think-longer", {
condition: ({ composer }) => composer.targetThread?.channel?.isAiChat,
closingModeAsDropdown: "none",
extraContentComponent: AiSessionToggle,
extraContentComponentProps: ({ composer }) => ({
aiSession: composer.targetThread.channel.aiSession,
configAttribute: "enable_think_longer",
}),
icon: "lightbulb",
name: _t("Think Longer"),
onSelected({ composer }) {
const aiSession = composer.targetThread.channel.aiSession;
aiSession.updateConfig("enable_think_longer", !aiSession.config["enable_think_longer"]);
},
sequence: 24,
sequenceGroup: 20,
});

View File

@@ -0,0 +1,193 @@
import { Composer } from "@mail/core/common/composer";
import "@ai/discuss/core/common/composer_patch";
//Ensure base voice_message patch is applied before this one
import "@mail/discuss/voice_message/common/composer_patch";
import { useVoiceRecorder } from "@mail/discuss/voice_message/common/voice_recorder";
import { proxy } from "@odoo/owl";
import { _t } from "@web/core/l10n/translation";
import { rpc } from "@web/core/network/rpc";
import { user } from "@web/core/user";
import { useService } from "@web/core/utils/hooks";
import { patch } from "@web/core/utils/patch";
import { getDataURLFromFile } from "@web/core/utils/urls";
patch(Composer.prototype, {
setup() {
super.setup();
const notificationService = this.env.services.notification;
this.voiceTranscription = proxy({ isTranscribing: false });
this.uiService = useService("ui");
if (this.props.composer.targetThread?.channel?.isAiChat) {
const transcribe = async (file) => {
this.voiceTranscription.isTranscribing = true;
try {
const dataUrl = await getDataURLFromFile(file);
const base64Audio = dataUrl.split(",")[1];
const response = await rpc(
"/ai/transcription",
{
audio_base64: base64Audio,
language: user.lang?.replace("-", "_").split("_")[0],
},
{ silent: true },
);
if (response["status"] === "success") {
const text = response["text"];
// Append rather than overwrite protects existing text
const prefix = this.props.composer.composerText ? " " : "";
this.props.composer.insertText(
prefix + text,
this.props.composer.selection.start,
{ moveCursorToEnd: true },
);
}
} catch {
notificationService.add(_t("Transcription failed."), {
type: "danger",
});
} finally {
this.voiceTranscription.isTranscribing = false;
}
};
// Transcribe voice uploads instead of sending them as attachments
this.voiceRecorder = useVoiceRecorder({
maxDuration: 1200, // Stay well within 25MB limit (at 128kbps)
onRecordReady: transcribe,
});
// Restore focus after starting recording (so keybindings work)
const originalOnClick = this.voiceRecorder.onClick;
this.voiceRecorder.onClick = async (...args) => {
const res = await originalOnClick.apply(this.voiceRecorder, args);
if (this.voiceRecorder.recording) {
if (this.composerService.htmlEnabled) {
this.editor?.shared.selection.focusEditable();
} else {
this.ref()?.focus();
}
}
return res;
};
}
},
saveContent() {
if (this.props.composer.targetThread?.channel?.isAiChat) {
return; // no point in saving the content in an AI chat since chats are independent
}
super.saveContent();
},
onFocusin(ev) {
const isBusy = this.voiceRecorder?.recording || this.voiceTranscription?.isTranscribing;
// On mobile, prevent the virtual keyboard from popping up
if (
this.props.composer.targetThread?.channel?.isAiChat &&
isBusy &&
this.uiService.isSmall
) {
ev.target.blur();
return;
}
super.onFocusin(ev);
if (this.props.composer.targetThread?.channel?.isAiChat) {
if (this.composerService.htmlEnabled) {
this.editor?.shared.selection.focusEditable();
} else {
ev.target.select();
}
}
},
get isSendButtonDisabled() {
if (this.props.composer.targetThread?.channel?.isAiChat && this.voiceRecorder?.recording) {
return this.isAiAgentGenerating;
}
return super.isSendButtonDisabled;
},
get SEND_TEXT() {
if (this.props.composer.targetThread?.channel?.isAiChat) {
return _t("%(send_text)s (Enter)", {
send_text: super.SEND_TEXT,
});
}
return super.SEND_TEXT;
},
async sendMessage() {
if (
!this.isAiAgentGenerating &&
this.props.composer.targetThread?.channel?.isAiChat &&
this.voiceRecorder?.recording
) {
await this.voiceRecorder.onClick();
}
return super.sendMessage();
},
onKeydown(ev) {
if (this.props.composer.targetThread?.channel?.isAiChat) {
const isRecording = this.voiceRecorder?.recording;
const isTranscribing = this.voiceTranscription?.isTranscribing;
const isBusy = isRecording || isTranscribing;
if (ev.key === "Enter") {
if (!ev.shiftKey && isRecording) {
ev.preventDefault();
ev.stopPropagation();
this.voiceRecorder.onClick().then(() => this.sendMessage());
return;
}
}
if (ev.key === "Escape" && isRecording) {
ev.preventDefault();
ev.stopPropagation();
this.voiceRecorder.cancelRecording();
return;
}
if (ev.altKey && ev.key.toLowerCase() === "v") {
ev.preventDefault();
ev.stopPropagation();
this.voiceRecorder?.onClick();
return;
}
// We manually block character input during recording/transcribing
// instead of HTML disabled attr, which would restrict focus;
// keeping focus allows to scope shourtcut capture
if (
isBusy &&
!ev.ctrlKey &&
!ev.altKey &&
!ev.metaKey &&
ev.key !== "Tab" &&
ev.key !== "Enter"
) {
ev.preventDefault();
ev.stopPropagation();
return;
}
}
return super.onKeydown(ev);
},
get placeholder() {
if (this.props.composer.targetThread?.channel?.isAiChat && this.voiceRecorder?.recording) {
return _t("Listening…");
}
return super.placeholder;
},
get supportedFileTypes() {
if (!this.props.composer.targetThread?.channel?.isAiChat) {
return undefined;
}
// indexable files and image types supported by most AI providers
return "text/*,application/pdf,.docx,.pptx,.xlsx,.opendoc,.png,.jpg,.jpeg,.webp,.gif";
},
get wysiwygConfig() {
const config = super.wysiwygConfig;
return {
...config,
getRecordInfo: () => ({
resModel: this.thread?.model,
resId: this.thread?.id,
}),
};
},
});

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8" ?>
<templates xml:space="preserve">
<t t-name="ai.Composer" t-inherit="mail.Composer" t-inherit-mode="extension">
<xpath expr="//FileUploader" position="attributes">
<attribute name="acceptedFileExtensions">this.supportedFileTypes</attribute>
</xpath>
</t>
<t t-name="ai.VoiceMessageTranscribingSpinner">
<div class="d-flex align-items-center align-self-center text-muted mx-2 py-1 user-select-none">
<i class="oi oi-fw oi-spin me-2" data-icon="autorenew"/>
<span class="text-truncate">Transcribing...</span>
</div>
</t>
</templates>

View File

@@ -0,0 +1,55 @@
declare module "models" {
import { AiAgent as AiAgentClass } from "@ai/discuss/core/common/ai_agent_model";
import { AiComposer as AiComposerClass } from "@ai/discuss/core/common/ai_composer_model";
import { AiSession as AiSessionClass } from "@ai/discuss/core/common/ai_session_model";
import { AIPromptButton as AIPromptButtonClass } from "@ai/discuss/core/common/ai_prompt_model";
export interface AiAgent extends AiAgentClass {}
export interface AiComposer extends AiComposerClass {}
export interface AiSession extends AiSessionClass {}
export interface AIPromptButton extends AIPromptButtonClass {}
export interface ChannelMember {
isAiAgent: Readonly<boolean>;
isAiResponding: boolean;
}
export interface DiscussChannel {
ai_agent_id: AiAgent;
ai_prompt_buttons: AIPromptButton[];
ai_session_ids: AiSession[];
aiInputSession: AiSession;
aiRootSession: AiSession;
aiChatSource: number|undefined;
aiSpecialActions: Object|undefined;
are_prompts_from_local_storage: boolean;
disabledActions: Object|undefined;
fromShopExtraImage: boolean|undefined;
isAiGenerating: boolean;
isAiSubmitting: boolean;
localStoragePrompts: string|undefined;
serializedPrompts: string|undefined;
suggestedAiChannel: DiscussChannel;
targetRecord: Object|undefined;
textSelection: Object|undefined;
}
export interface ResPartner {
agent_ids: AiAgent[];
}
export interface Store {
"ai.agent": StaticMailRecord<AiAgent, typeof AiAgentClass>;
"ai.composer": StaticMailRecord<AiComposer, typeof AiComposerClass>;
"ai.prompt.button": StaticMailRecord<AIPromptButton, typeof AIPromptButtonClass>;
"ai.session": StaticMailRecord<AiSession, typeof AiSessionClass>;
aiInsertButtonTarget: number|false|undefined;
}
export interface Thread {
ai_agent_id: AiAgent;
}
export interface Models {
"ai.agent": AiAgent;
"ai.composer": AiComposer;
"ai.prompt.button": AIPromptButton;
"ai.session": AiSession;
}
}

View File

@@ -0,0 +1,17 @@
import { Record, fields } from "@mail/model/export";
export class AiAgent extends Record {
static _name = "ai.agent";
/** @type {number} */
id;
partner_id = fields.One("res.partner");
/** @type {string} */
name;
sources_ids = undefined;
/** @type {string} */
subtitle;
xml_id;
}
AiAgent.register();

View File

@@ -0,0 +1,16 @@
import { markup } from "@odoo/owl";
import { registry } from "@web/core/registry";
/** Registry of browser-side tools that an AI session can invoke. */
export const aiClientToolsRegistry = registry.category("ai.client_tools");
export async function runAiClientTool(thread, { name, params }) {
const tool = aiClientToolsRegistry.get(name, null);
if (!tool) {
throw new Error(`Unknown AI client tool: ${name}`);
}
if (name === "show_view" && params?.action?.help) {
params.action.help = markup(params.action.help);
}
return await tool(thread, params);
}

View File

@@ -0,0 +1,49 @@
import { aiSessionIdentifier } from "@ai/utils/ai_session_identifier";
import { runAiClientTool } from "@ai/discuss/core/common/ai_client_tool_registry";
import { registry } from "@web/core/registry";
export async function runOneWayClientToolBatch(store, payload) {
if (payload.aiSessionIdentifier !== aiSessionIdentifier) {
return;
}
const commands = payload.commands;
const thread = store["mail.thread"].get({
id: payload.channel_id,
model: "discuss.channel",
});
if (!thread) {
return;
}
let reloadCommand;
for (const command of commands) {
if (command.name === "reload") {
reloadCommand = command;
continue;
}
try {
await runAiClientTool(thread, command);
} catch (error) {
console.warn(`Could not run AI client tool ${command.name}: ${error.message}`);
}
}
if (reloadCommand) {
try {
await runAiClientTool(thread, reloadCommand);
} catch (error) {
console.warn(`Could not run AI client tool reload: ${error.message}`);
}
}
}
export const aiClientToolBusService = {
dependencies: ["bus_service", "mail.store"],
start(_env, services) {
services.bus_service.subscribe("ai.session/client_tools", async (payload) => {
await runOneWayClientToolBatch(services["mail.store"], payload);
});
},
};
registry.category("services").add("ai.client_tools", aiClientToolBusService);

View File

@@ -0,0 +1,12 @@
import { Record } from "@mail/model/export";
export class AiComposer extends Record {
static _name = "ai.composer";
/** @type {number} */
id;
/** @type {string} */
interface_key;
}
AiComposer.register();

View File

@@ -0,0 +1,16 @@
import { Record } from "@mail/model/export";
export class AIPromptButton extends Record {
static _name = "ai.prompt.button";
/** @type {number} */
id;
/** @type {string} */
name;
/** @type {string|undefined} */
prompt;
/** @type {number|undefined} */
sequence;
}
AIPromptButton.register();

View File

@@ -0,0 +1,159 @@
import { aiSessionIdentifier } from "@ai/utils/ai_session_identifier";
import { runAiClientTool } from "@ai/discuss/core/common/ai_client_tool_registry";
import { Record, fields } from "@mail/model/export";
export function isAiResponseInProgress(loopState) {
return ["waiting_model", "waiting_child", "waiting_client_result"].includes(loopState);
}
export class AiSession extends Record {
static _name = "ai.session";
setup() {
super.setup(...arguments);
this.onChange(
() => [this.channel_id, this.loop_state, this.userInputRequest],
function onChangeAiSessionState() {
this.syncAiSessionState();
},
{ immediate: true, initialRun: false },
);
this.onChange(
() => [this.clientToolRequest],
function onChangeClientToolRequest() {
this.processPendingClientTool();
},
{ immediate: true, initialRun: false },
);
}
/** @type {number} */
id;
ai_composer_id = fields.One("ai.composer");
agent_id = fields.One("ai.agent");
parent_session_id = fields.One("ai.session");
clientToolRequest = false;
channel_id = fields.One("discuss.channel", { inverse: "ai_session_ids" });
loop_state = "ready";
res_id = undefined;
res_model = undefined;
userInputRequest = fields.One("ai.user.input.request");
external_pending_tool = false;
resume_token = false;
config = undefined;
config_rules = undefined;
toolStatus = undefined;
_runningClientToolToken;
updateConfig(attr, newValue) {
this.ensureRequiredStates(attr, newValue);
this.config = {
...this.config,
[attr]: newValue,
};
}
ensureRequiredStates(attr, newValue) {
if (newValue && this.config_rules[attr]) {
for (const [key, value] of Object.entries(this.config_rules[attr])) {
this.config[key] = value;
}
}
}
syncAiSessionState() {
const channel = this.channel_id;
if (!channel) {
return;
}
if (!channel.aiInputSession?.userInputRequest) {
channel.aiInputSession = channel.ai_session_ids
.filter((session) => session.userInputRequest)
.sort((a, b) => a.id - b.id)[0];
}
channel.isAiGenerating = Boolean(
channel.isAiSubmitting ||
channel.ai_session_ids.some(
(session) =>
isAiResponseInProgress(session.loop_state) ||
(session.parent_session_id &&
["waiting_confirmation", "waiting_answer"].includes(session.loop_state)),
),
);
this.processPendingClientTool();
}
async cancelExternalTool() {
const resumeToken = this.resume_token;
const acknowledgement = await this.channel_id.thread.requestAiSessionAdvance(
"/ai/resume_pending_interaction",
{
session_id: this.id,
resume_token: resumeToken,
response: { kind: "skip" },
},
);
if (
acknowledgement.interactionConsumed !== false &&
this.exists() &&
this.resume_token === resumeToken
) {
this.external_pending_tool = false;
}
}
async processPendingClientTool() {
const request = this.clientToolRequest;
const thread = this.channel_id?.thread;
if (
!request ||
!thread ||
request.aiSessionIdentifier !== aiSessionIdentifier ||
this._runningClientToolToken === request.resumeToken
) {
return;
}
const resumeToken = request.resumeToken;
this._runningClientToolToken = resumeToken;
let response;
try {
const result = await runAiClientTool(thread, request);
response = {
kind: "client_result",
value: result === undefined ? "Success" : result,
};
} catch (error) {
response = { kind: "client_error", value: error?.message || String(error) };
}
try {
const acknowledgement = await thread.requestAiSessionAdvance(
"/ai/resume_pending_interaction",
{
session_id: this.id,
response,
resume_token: resumeToken,
},
);
if (
acknowledgement.interactionConsumed !== false &&
this.exists() &&
this.clientToolRequest?.resumeToken === resumeToken
) {
this.clientToolRequest = false;
}
} catch (error) {
if (this.exists()) {
this.store.env.services.notification.add(
error?.message || "The AI client tool result could not be submitted.",
{ type: "danger" },
);
}
} finally {
if (this._runningClientToolToken === resumeToken) {
this._runningClientToolToken = undefined;
}
}
}
}
AiSession.register();

View File

@@ -0,0 +1,18 @@
import { Record, fields } from "@mail/model/export";
export class AiUserInputRequest extends Record {
static _name = "ai.user.input.request";
static id = "ai_session_id";
ai_session_id = fields.One("ai.session", { inverse: "userInputRequest" });
/** @type {"question" | "confirmation"} */
type = "";
body = fields.Html("");
multiSelect = false;
allowFreeText = false;
/** @type {Array<{label: string, value: string}>} */
choices = [];
resumeToken = undefined;
}
AiUserInputRequest.register();

View File

@@ -0,0 +1,45 @@
import { ChannelMember } from "@mail/discuss/core/common/channel_member_model";
import { fields } from "@mail/model/export";
import { patch } from "@web/core/utils/patch";
/** @type {import("models").ChannelMember} */
const channelMemberPatch = {
setup() {
super.setup(...arguments);
this.isAiResponding = fields.Attr(false, {
compute() {
if (!this.isAiAgent) {
return false;
}
const channel = this.channel_id;
return Boolean(
channel?.channel_type === "livechat" &&
!channel.aiInputSession?.userInputRequest &&
channel.isAiGenerating &&
!channel.ai_session_ids.some((session) => session.external_pending_tool),
);
},
eager: true,
});
this.onChange(
() => [this.isAiResponding],
function onChangeIsAiResponding(isAiResponding) {
if (this.isAiAgent) {
this.isTyping = isAiResponding;
}
},
{ immediate: true, initialRun: false },
);
},
get isAiAgent() {
return Boolean(this.channel_id?.ai_agent_id?.partner_id?.eq(this.partner_id));
},
registerTypingTimeout() {
// no typing timeout for agent as it's used to show the current ai tool being used
if (this.isAiAgent) {
return;
}
return super.registerTypingTimeout();
},
};
patch(ChannelMember.prototype, channelMemberPatch);

View File

@@ -0,0 +1,27 @@
import { patch } from "@web/core/utils/patch";
import { ChatWindow } from "@mail/core/common/chat_window_model";
patch(ChatWindow.prototype, {
computeCanShow() {
if (this.store.aiInsertButtonTarget && this.store.discuss.isActive) {
return this.channel.isAiChat;
}
return super.computeCanShow();
},
async _onBeforeClose() {
// override of _onBeforeClose not _onClose because the latter is called from each tab
if (this.channel.isAiChat) {
this.channel.update({
// clear localStorage before delete
ai_prompt_buttons: [],
// Allow write on localStorage, in case the closing happens outside of the tab that
// created the channel.
are_prompts_from_local_storage: false,
});
if (this.channel.isLoaded && !this.channel.hasLoadingFailed && this.channel.isEmpty) {
await this.channel.deleteAiChatRpc();
}
}
return await super._onBeforeClose(...arguments);
},
});

View File

@@ -0,0 +1,17 @@
import { Composer } from "@mail/core/common/composer";
import { patch } from "@web/core/utils/patch";
patch(Composer.prototype, {
get isAiAgentGenerating() {
return Boolean(this.props.composer.targetThread?.channel?.isAiGenerating);
},
get isSendButtonDisabled() {
return this.isAiAgentGenerating || super.isSendButtonDisabled;
},
async sendMessage() {
if (this.isAiAgentGenerating) {
return;
}
return super.sendMessage();
},
});

View File

@@ -0,0 +1,141 @@
import { aiChannelDataRegistry } from "@ai/utils/ai_channel_data_registry";
import { DiscussChannel } from "@mail/discuss/core/common/discuss_channel_model";
import { fields } from "@mail/model/export";
import { patch } from "@web/core/utils/patch";
/** @type {import("models").DiscussChannel} */
const discussChannelPatch = {
setup() {
super.setup(...arguments);
this.ai_prompt_buttons = fields.Many("ai.prompt.button");
this.ai_agent_id = fields.One("ai.agent");
this.ai_session_ids = fields.Many("ai.session", { inverse: "channel_id" });
this.onChange(
() => [...this.ai_session_ids],
function onChangeAiSessions() {
this.aiRootSession?.syncAiSessionState();
},
{ immediate: true, initialRun: false },
);
this.aiInputSession = fields.One("ai.session");
this.isAiGenerating = false;
this.isAiSubmitting = false;
this.suggestedAiChannel = fields.One("discuss.channel");
/** @type {number|undefined} record the AI chat was started from */
this.aiChatSource = undefined;
/** @type {Object|undefined} actions offered by the caller of the AI chat */
this.aiSpecialActions = undefined;
/** @type {Object|undefined} */
this.targetRecord = undefined;
/** @type {Object|undefined} */
this.textSelection = undefined;
/** @type {Object|undefined} actions the AI chat disables on its thread */
this.disabledActions = undefined;
/** @type {boolean|undefined} AI chat opened from a shop extra-image media dialog */
this.fromShopExtraImage = undefined;
this.are_prompts_from_local_storage = true;
this.onChange(
() => [this.are_prompts_from_local_storage],
function onChangeArePromptsFromLocalStorage(arePromptsFromLocalStorage) {
if (arePromptsFromLocalStorage) {
this._restorePrompts();
} else {
this._savePrompts();
}
},
{ immediate: true, initialRun: false },
);
/** @type {Array<{id: number, name: string}>} */
this.serializedPrompts = this.computed(() => {
const prompts = this.ai_prompt_buttons.map((button) => ({
id: button.id,
name: button.name,
}));
return prompts.length > 0 ? prompts : undefined;
});
this.onChange(
() => [this.serializedPrompts],
function onChangeSerializedPrompts() {
if (!this.are_prompts_from_local_storage) {
this._savePrompts();
}
},
{ immediate: true, initialRun: false },
);
/**
* Prompt buttons to save on the local storage.
* Channels are synchronized with bus but random prompts are contextual and not stored on
* the database/not linked to the channel so they need to be saved in localStorage for
* proper sync cross-tab and to restore them after page refresh.
* This implies multi-device is not supported.
* They can be deleted when the channel is closed/locally deleted/no longer accessed.
*
* @type {Array<{id: number, name: string}>}
*/
this.localStoragePrompts = this.localStorage(undefined);
this.onChange(
() => [this.localStoragePrompts],
function onChangeLocalStoragePrompts() {
if (this.are_prompts_from_local_storage) {
this._restorePrompts();
}
},
{ immediate: true },
);
},
get aiRootSession() {
return this.ai_session_ids.find((session) => !session.parent_session_id);
},
get computedDisplayName() {
const displayName = super.computedDisplayName;
if (this.isAiChat && !this.name && this.ai_agent_id) {
return this.ai_agent_id.name;
}
return displayName;
},
get isAiChat() {
return this.channel_type === "ai_chat";
},
get aiSession() {
return this.aiRootSession;
},
get aiMember() {
return this.channel_member_ids?.find((member) => member.isAiAgent);
},
get chatChannelTypes() {
// overridden to show the last message of the ai chats in the messaging menu
// and show the count of AI chats with unread messages
return [...super.chatChannelTypes, "ai_chat"];
},
get showUnreadBanner() {
if (this.isAiChat) {
const newestMessage = this.newestPersistentMessage;
if (newestMessage?.aiIsAgentStep || newestMessage?.aiIsToolUse) {
return false;
}
}
return super.showUnreadBanner;
},
get importantCounter() {
if (this.isAiChat) {
const newestMessage = this.newestPersistentMessage;
if (newestMessage?.aiIsAgentStep || newestMessage?.aiIsToolUse) {
return 0;
}
}
return super.importantCounter;
},
async deleteAiChatRpc() {
const channelId = this.id;
await this.store.env.services.orm.silent.call("discuss.channel", "unlink", [channelId]);
aiChannelDataRegistry.removeData(channelId);
},
_restorePrompts() {
this.ai_prompt_buttons = this.localStoragePrompts;
},
_savePrompts() {
this.localStoragePrompts = this.serializedPrompts;
},
};
patch(DiscussChannel.prototype, discussChannelPatch);

View File

@@ -0,0 +1,39 @@
import { Message } from "@mail/core/common/message_model";
import { patch } from "@web/core/utils/patch";
patch(Message.prototype, {
/**
* Agents messages logic:
* - comment -> verbose message
* - note: intermediary message (collapsed by default)
* - discussion: final message (always shown)
* - notification -> action taken
* - note: tool use (collapsed by default)
* - discussion: other (always shown)
*/
get aiAgentAuthored() {
return (
this.channel_id?.ai_agent_id?.partner_id.eq(this.author_id) ||
this.channel_id?.ai_session_ids.some((session) =>
session.agent_id?.partner_id.eq(this.author_id),
)
);
},
get aiIsAgentStep() {
return this.aiAgentAuthored && !this.isNotification && this.isNote;
},
get aiIsAgentResponse() {
return this.aiAgentAuthored && !this.isNotification && this.isDiscussion;
},
get aiIsToolUse() {
return this.aiAgentAuthored && this.isNotification && this.isNote;
},
get aiIsAction() {
return this.aiAgentAuthored && this.isNotification && this.isDiscussion;
},
get notificationHidden() {
// tool use have their own template, should not be shown as notifications
return this.aiIsToolUse ? true : super.notificationHidden;
},
});

View File

@@ -0,0 +1,11 @@
import { NotificationMessage } from "@mail/core/common/notification_message";
import { patch } from "@web/core/utils/patch";
patch(NotificationMessage.prototype, {
get showDate() {
return this.props.message?.aiAgentAuthored ? false : super.showDate;
},
get showInlineBody() {
return this.message.notificationType == "ai_note" ? true : super.showInlineBody;
},
});

View File

@@ -0,0 +1,14 @@
import { ResPartner } from "@mail/core/common/res_partner_model";
import { fields } from "@mail/model/misc";
import { patch } from "@web/core/utils/patch";
patch(ResPartner.prototype, {
setup() {
super.setup();
this.agent_ids = fields.Many("ai.agent", { inverse: "partner_id" });
},
get isBot() {
return super.isBot || this.agent_ids?.length > 0;
},
});

View File

@@ -0,0 +1,10 @@
import { Store } from "@mail/core/common/store_service";
import { patch } from "@web/core/utils/patch";
patch(Store.prototype, {
setup() {
super.setup(...arguments);
/** @type {number|false|undefined} source id of the AI chat wanting the insert button */
this.aiInsertButtonTarget = undefined;
},
});

View File

@@ -0,0 +1,16 @@
.o_ai_preview_header {
display: block;
margin: map-get($spacers, 2) 0 map-get($spacers, 1);
font-size: $font-size-sm;
font-weight: $font-weight-semibold;
}
.o_ai_preview_link {
display: block;
}
.o-ai-tool-status {
mask-image: linear-gradient(130deg, $black 55%, rgba(0, 0, 0, 0.65) 75%, $black 95%);
mask-size: 200% 100%;
animation: placeholder-wave 2s linear infinite;
}

View File

@@ -0,0 +1,105 @@
import { aiSessionIdentifier } from "@ai/utils/ai_session_identifier";
import { Thread } from "@mail/core/common/thread_model";
import { isAiResponseInProgress } from "@ai/discuss/core/common/ai_session_model";
import { patch } from "@web/core/utils/patch";
import { getData } from "@ai/utils/bus_data_getter";
import { fields } from "@mail/model/export";
import { rpc } from "@web/core/network/rpc";
patch(Thread.prototype, {
setup() {
super.setup();
this.ai_agent_id = fields.One("ai.agent");
this.ai_session_config = {
ai_prompt_button_ref: null,
};
},
async requestAiSessionAdvance(route, body) {
const sourceSession = body.session_id
? this.store["ai.session"].get(body.session_id)
: this.channel?.aiRootSession;
let acknowledgement;
try {
acknowledgement = await rpc(route, {
channel_id: this.id,
ai_session_identifier: aiSessionIdentifier,
debug: this.store.debugMode.isActive(),
current_view_info: await getData("view"),
ai_session_config: this.channel?.aiSession?.config,
...body,
});
} catch (error) {
this.channel.isAiSubmitting = false;
const session = this.channel?.aiRootSession;
if (session) {
session.syncAiSessionState();
} else {
this.channel.isAiGenerating = false;
}
throw error;
}
const currentSession = sourceSession || (!body.session_id && this.channel?.aiRootSession);
if (currentSession?.exists()) {
currentSession.loop_state = acknowledgement.loop_state;
}
return acknowledgement;
},
async post(body, postData = {}, extraData = {}) {
const hasAiAgent = Boolean(this.channel?.ai_agent_id);
const pendingRequest =
!this.channel?.isAiGenerating && this.channel?.aiRootSession?.userInputRequest;
if (hasAiAgent) {
this.channel.isAiSubmitting = true;
this.channel.isAiGenerating = true;
}
const { ai_prompt_button_ref, ...extras } = extraData;
let message;
try {
if (pendingRequest) {
// Preserve the root prompt in history before posting the replacement message.
await this.requestAiSessionAdvance("/ai/resume_pending_interaction", {
session_id: pendingRequest.ai_session_id.id,
resume_token: pendingRequest.resumeToken,
response: { kind: "skip" },
});
}
message = await super.post(body, postData, extras);
} catch (error) {
if (hasAiAgent) {
this.channel.isAiSubmitting = false;
this.channel.isAiGenerating = false;
}
throw error;
}
if (message && hasAiAgent) {
Object.assign(this.ai_session_config, this.channel?.aiSession?.config);
this.ai_session_config.ai_prompt_button_ref = ai_prompt_button_ref;
let loopStateFromAcknowledgement;
try {
const acknowledgement = await this.requestAiSessionAdvance(
"/ai/start_session_advance",
{
ai_session_config: this.ai_session_config,
mail_message_id: message.id,
},
);
loopStateFromAcknowledgement = acknowledgement.loop_state;
} finally {
this.channel.isAiSubmitting = false;
const session = this.channel?.aiRootSession;
const loopState = session?.loop_state ?? loopStateFromAcknowledgement;
if (session) {
session.syncAiSessionState();
} else {
this.channel.isAiGenerating = isAiResponseInProgress(loopState);
}
}
} else if (hasAiAgent) {
this.channel.isAiSubmitting = false;
this.channel.isAiGenerating = false;
}
return message;
},
});

View File

@@ -0,0 +1,4 @@
import { Thread } from "@mail/core/common/thread";
import { AIUserInputRequest } from "@ai/discuss/ai_user_input_request";
Thread.components = { ...Thread.components, AIUserInputRequest };

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-inherit="mail.Thread" t-inherit-mode="extension">
<xpath expr="//t[@t-call='mail.Thread.jumpPresent']" position="before">
<AIUserInputRequest
t-if="this.channel?.aiInputSession?.userInputRequest"
t-key="this.channel.aiInputSession.userInputRequest.resumeToken"
request="this.channel.aiInputSession.userInputRequest"
thread="this.props.thread"/>
</xpath>
</t>
</templates>

View File

@@ -0,0 +1,32 @@
import { DiscussChannel } from "@mail/discuss/core/common/discuss_channel_model";
import { _t } from "@web/core/l10n/translation";
import { patch } from "@web/core/utils/patch";
patch(DiscussChannel.prototype, {
get allowedToRenameChannelTypes() {
return [...super.allowedToRenameChannelTypes, "ai_chat"];
},
get hasDeletedAiAgent() {
return this.isAiChat && !this.ai_agent_id;
},
get composerHidden() {
if (this.hasDeletedAiAgent || this.aiSessionAwaitsResponse) {
return true;
}
return super.composerHidden;
},
get composerHiddenText() {
if (this.hasDeletedAiAgent) {
return _t("This session's AI agent has been deleted.");
}
if (this.aiSessionAwaitsResponse) {
return "";
}
return super.composerHiddenText;
},
get aiSessionAwaitsResponse() {
return this.ai_session_ids.some(
(session) => session.userInputRequest || session.external_pending_tool,
);
},
});

View File

@@ -0,0 +1,112 @@
import { patch } from "@web/core/utils/patch";
import { _t } from "@web/core/l10n/translation";
import { registerMessageAction, MessageAction } from "@mail/core/common/message_actions";
import { unwrapContents } from "@html_editor/utils/dom";
import { setElementContent } from "@web/core/utils/html";
export const AIMessageActions = [
"insertToComposer",
"copy-message",
"send-message-direct",
"log-note-direct",
"media_dialog_use_this",
"regenerate_image",
];
registerMessageAction("insertToComposer", {
condition: ({ channel, message, store }) =>
!!channel?.aiSpecialActions?.insert &&
store.aiInsertButtonTarget && // after a reload both parts of the below conditions are undefined and but we don't want to button to appear
(store.aiInsertButtonTarget === channel.aiChatSource || store.env.services.ui.isSmall) &&
!message.isSelfAuthored,
name: _t("Use this"),
onSelected: ({ channel, message, store }) => {
const targetElementSelection = channel.aiSpecialActions.selectPreviousInsertion(
channel.textSelection?.selectionId
);
const fragment = document.createDocumentFragment();
const content_root = document.createElement("span");
content_root.setAttribute("data-ai-selection-id", channel.textSelection?.selectionId);
setElementContent(content_root, message.body);
// check if the content is enclosed in a <p> element, if so, unwrap it
const paragraphElements = content_root.querySelectorAll("p");
if (paragraphElements.length === 1) {
unwrapContents(paragraphElements[0]);
}
fragment.appendChild(content_root);
channel.aiSpecialActions.insert(fragment, targetElementSelection);
if (store.env.services.ui.isSmall) {
channel.closeChatWindow();
}
},
sequence: 10,
});
registerMessageAction("send-message-direct", {
condition: ({ channel, message }) =>
!!channel?.aiSpecialActions?.sendMessage && !message.isSelfAuthored && message.isDiscussion, // don't show the buttons for the user's messages,
name: _t("Send as Message"),
onSelected: ({ channel, message }) => channel.aiSpecialActions.sendMessage(message),
sequence: 20,
});
registerMessageAction("log-note-direct", {
condition: ({ channel, message }) =>
!!channel?.aiSpecialActions?.logNote && !message.isSelfAuthored && message.isDiscussion, // don't show the buttons for the user's messages
name: _t("Log as Note"),
onSelected: ({ channel, message }) => channel.aiSpecialActions.logNote(message),
sequence: 25,
});
registerMessageAction("media_dialog_use_this", {
condition: ({ channel, message }) =>
!!channel?.aiSpecialActions?.useThis &&
!message.isSelfAuthored &&
!!message.attachment_ids.filter((attachment) => attachment.mimetype.includes("image"))
.length,
name: _t("Use This"),
onSelected: ({ channel, ...args }) => {
channel.aiSpecialActions.useThis({ channel, ...args });
},
sequence: 10,
});
registerMessageAction("regenerate_image", {
condition: ({ channel, message }) =>
!message.isSelfAuthored &&
message.eq(channel?.newestMessage) &&
!!message.attachment_ids.filter(
(attachment) =>
attachment.mimetype.includes("image") && attachment.name.includes("AI Generated")
).length,
icon: "refresh",
name: _t("Try again"),
onSelected: ({ channel }) => {
channel.post("Try again", {}, { ai_prompt_button_ref: "ai.ai_prompt_regenerate_image" });
},
sequence: 15,
});
patch(MessageAction.prototype, {
_condition({ channel, message }) {
if (channel?.isAiChat) {
if (
(message.bodyEl?.querySelector(".ai_user_input_request") &&
this.id !== "copy-message") ||
!AIMessageActions.includes(this.id)
) {
return false;
}
if (this.id === "copy-message") {
return message.isDiscussion || message.isNote;
}
}
return super._condition(...arguments);
},
_sequence({ channel }) {
if (this.id === "copy-message" && channel?.isAiChat) {
return 50;
}
return super._sequence(...arguments);
},
});

View File

@@ -0,0 +1,19 @@
import { Message } from "@mail/core/common/message_model";
import { patch } from "@web/core/utils/patch";
patch(Message.prototype, {
/** Pending AI interaction associated with the newest incoming message. */
get aiUserInputRequest() {
if (
!this.thread?.channel?.ai_agent_id ||
this.isSelfAuthored ||
!this.eq(this.thread.channel.newestMessage)
) {
return undefined;
}
return this.thread.channel.aiInputSession?.userInputRequest;
},
get hasActions() {
return !this.aiUserInputRequest && super.hasActions;
},
});

View File

@@ -0,0 +1,56 @@
import { Message } from "@mail/core/common/message";
import { patch } from "@web/core/utils/patch";
patch(Message.prototype, {
get attClass() {
const attClass = super.attClass;
attClass["o-ai-agent-response"] = this.props.message.aiIsAgentResponse;
attClass["ps-2"] = this.isAIMessage && this.env.inChatWindow;
return attClass;
},
get bodyAttClass() {
const bodyAttClass = super.bodyAttClass;
bodyAttClass["px-2"] = this.isAIMessage;
bodyAttClass["text-muted"] = this.props.message.aiIsAgentStep;
return bodyAttClass;
},
get quickActionCount() {
return this.props.thread?.channel?.isAiChat ? 3 : super.quickActionCount;
},
getAvatarContainerAttClass() {
const res = super.getAvatarContainerAttClass();
if (this.props.thread?.channel?.isAiChat) {
return {
...res,
"mx-1": this.env.inChatWindow,
"mx-2": !this.env.inChatWindow,
};
}
return res;
},
get isAlignedRight() {
return (
(this.props.thread?.channel?.isAiChat && this.props.message.isSelfAuthored) ||
super.isAlignedRight
);
},
get isAIMessage() {
return this.props.message.aiAgentAuthored;
},
/**
* @override
* @param {HTMLElement} bodyEl
*/
prepareMessageBody(bodyEl) {
super.prepareMessageBody(...arguments);
if (!bodyEl) {
return;
}
const codeBlocks = bodyEl.querySelectorAll("pre code");
for (const block of codeBlocks) {
if (window.Prism) {
window.Prism.highlightElement(block, false);
}
}
},
});

View File

@@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-inherit="mail.Message" t-inherit-mode="extension">
<xpath expr="//div[hasclass('o-mail-Message-core')]" position="attributes">
<attribute name="t-attf-class" add="{{ this.isAIMessage ? 'flex-column' : '' }}" separator=" "/>
<attribute name="t-attf-class" add="{{ this.props.thread?.channel?.isAiChat and this.props.message.isSelfAuthored ? 'flex-row-reverse' : '' }}" separator=" "/>
</xpath>
<xpath expr="//div[hasclass('o-mail-Message-sidebar')]" position="attributes">
<attribute name="t-attf-class" add="{{ this.isAIMessage ? 'd-none' : '' }}" separator=" "/>
</xpath>
<xpath expr="//div[hasclass('o-mail-Message-header')]" position="attributes">
<attribute name="t-attf-style" add="{{ this.props.thread?.channel?.isAiChat and this.props.message.isSelfAuthored ? 'justify-content: flex-end;' : '' }}" separator=" "/>
</xpath>
<xpath expr="//span[hasclass('o-mail-Message-author')]" position="before">
<div t-if="this.isAIMessage" class="o-mail-Message-avatarContainer position-relative bg-inherit rounded-3" t-att-class="this.getAvatarContainerAttClass()">
<img class="o-mail-Message-avatar w-100 h-100 rounded-3" t-att-src="this.message.authorAvatarUrl" t-att-class="this.authorAvatarAttClass"/>
</div>
</xpath>
<xpath expr="//div[hasclass('o-mail-Message-bubbleTail')]" position="attributes">
<attribute name="t-attf-class" add="{{ this.isAIMessage ? 'd-none' : '' }}" separator=" "/>
</xpath>
<xpath expr="//div[hasclass('o-mail-Message-bubble')]" position="attributes">
<attribute name="t-attf-class" add="{{ this.isAIMessage ? 'd-none' : '' }}" separator=" "/>
</xpath>
<xpath expr="//div[hasclass('o-mail-Message-contentContainer')]" position="attributes">
<attribute name="t-att-class"></attribute>
<attribute name="t-attf-class" add="{{ this.props.thread?.channel?.isAiChat and this.env.inChatWindow ? 'flex-column' : '' }}" separator=" "/>
<attribute name="t-attf-class" add="{{ this.props.thread?.channel?.isAiChat and !this.env.inChatWindow and this.props.message.isSelfAuthored ? 'flex-row-reverse' : '' }}" separator=" "/>
<attribute name="t-attf-class" add="{{ !this.props.thread?.channel?.isAiChat and this.isAlignedRight ? 'flex-row-reverse' : '' }}" separator=" "/>
</xpath>
<xpath expr="//div[hasclass('o-mail-Message-textContent')]" position="attributes">
<attribute name="t-attf-class" add="{{ this.props.thread?.channel?.isAiChat and !this.env.inChatWindow ? 'flex-column' : '' }}" separator=" "/>
</xpath>
<xpath expr="//div[hasclass('o-mail-Message-textContent')]" position="after">
<t t-set="isNewestAIMessage" t-value="this.isAIMessage and this.props.message.eq(this.props.thread.channel.newestMessage)"/>
<t t-if="isNewestAIMessage">
<div
t-foreach="this.props.thread.channel.ai_session_ids.filter(session => session.external_pending_tool)"
t-as="session" t-key="session.id"
class="o_ai_external_pending_tool d-flex align-items-center gap-2 text-muted mt-1"
>
<i class="oi oi-fw oi-spin" data-icon="autorenew" aria-hidden="true"/>
<span t-if="session.parent_session_id" t-out="session.agent_id.name"/>
<span>Working...</span>
<button
class="o_ai_cancel_external btn btn-sm btn-link text-muted p-0 ms-auto"
t-on-click="() => session.cancelExternalTool()"
>Cancel</button>
</div>
</t>
</xpath>
</t>
<t t-inherit="mail.Message.actions" t-inherit-mode="extension">
<xpath expr="//*[hasclass('o-mail-Message-actions')]" position="attributes">
<attribute name="t-attf-class" add="{{ this.props.thread?.channel?.isAiChat and this.isAlignedRight ? 'flex-row-reverse' : '' }}" separator=" "/>
<attribute name="t-attf-class" add="{{ this.props.thread?.channel?.isAiChat and !this.env.inChatWindow and this.isAIMessage ? 'px-2' : '' }}" separator=" "/>
</xpath>
</t>
</templates>

View File

@@ -0,0 +1,8 @@
.o-mail-MessagingMenu-tab [data-icon='o_ai_icon']::before {
--o-ai-icon-filter: brightness(0) invert(90%);
}
.o-mail-MessagingMenu-tab.active [data-icon='o_ai_icon']::before {
--o-ai-icon-filter: invert(62%) sepia(90%) saturate(2200%) hue-rotate(140deg)
brightness(95%) contrast(95%);
}

View File

@@ -0,0 +1,7 @@
.o-mail-MessagingMenu-tab [data-icon='o_ai_icon']::before {
--o-ai-icon-filter: unset;
}
.o-mail-MessagingMenu-tab.active [data-icon='o_ai_icon']::before {
--o-ai-icon-filter: invert(42%) sepia(70%) saturate(1600%) hue-rotate(155deg) brightness(78%) contrast(95%);
}

View File

@@ -0,0 +1,58 @@
import {
MENU_TABS,
MessagingMenu,
} from "@mail/core/public_web/messaging_menu/messaging_menu_model";
import { fields } from "@mail/model/export";
import { _t } from "@web/core/l10n/translation";
import { patch } from "@web/core/utils/patch";
import { user } from "@web/core/user";
MENU_TABS.AI_CHAT = "ai-chat";
patch(MessagingMenu.prototype, {
setup() {
super.setup(...arguments);
this.aiChatTab = fields.One("MessagingMenuTab", {
compute() {
if (!user.isInternalUser) {
return;
}
return {
id: MENU_TABS.AI_CHAT,
icon: "o_ai_icon",
iconClass: "d-inline-flex justify-content-center",
label: _t("AI"),
sequence: 75,
recordType: "discuss.channel",
includesChannel: (c) => this.includesAiChatChannel(c),
filters: [
{
id: "ai_chat_unread",
text: _t("Unread"),
includesChannel: (c) => c.isUnread,
},
],
actions: [
{
id: "new-ai-chat",
icon: "add",
text: _t("Chat"),
onClick: () => this.launchAiChat(),
},
],
emptyState: { title: _t("No AI Chats yet.") },
};
},
eager: true,
});
},
includesAiChatChannel(channel) {
return channel.isAiChat;
},
launchAiChat() {
return this.store.env.services.aiChatLauncher.launchAIChat({
interfaceKey: "systray_ai_button",
});
},
});

View File

@@ -0,0 +1,49 @@
import { DiscussAvatar } from "@mail/core/common/discuss_avatar";
import { MessagingMenu } from "@mail/core/public_web/messaging_menu/messaging_menu";
import { MENU_TABS } from "@mail/core/public_web/messaging_menu/messaging_menu_model";
import { useOnChange } from "@odoo/owl";
import { CheckboxItem } from "@web/core/dropdown/checkbox_item";
import { Dropdown } from "@web/core/dropdown/dropdown";
import { patch } from "@web/core/utils/patch";
MessagingMenu.components = { ...MessagingMenu.components, CheckboxItem, Dropdown, DiscussAvatar };
patch(MessagingMenu.prototype, {
setup() {
super.setup(...arguments);
// Opening a chat from another agent should clear the filter.
useOnChange(
() => [this.store.discuss.thread],
(thread) => {
const selectedAgentFilter = this.state().selectedAgentFilter;
if (selectedAgentFilter && !thread?.channel?.ai_agent_id?.eq(selectedAgentFilter)) {
this.state().selectedAgentFilter = undefined;
}
},
{ initialRun: false }
);
},
get isAiChatTab() {
return this.activeTab().id === MENU_TABS.AI_CHAT;
},
get isAgentFilterActive() {
return Boolean(this.state().selectedAgentFilter);
},
isAgentSelected(agent) {
return Boolean(this.state().selectedAgentFilter?.eq(agent));
},
get showAgentFilterDropdown() {
return this.isAiChatTab && this.state().isSidebar && this.chatAgents.length > 0;
},
get chatAgents() {
const agents = this.store.messagingMenu.aiChatTab.channels
.map((channel) => channel.ai_agent_id)
.filter(Boolean);
return [...new Map(agents.map((agent) => [agent.id, agent])).values()];
},
selectAgentFilter(agent) {
this.state().selectedAgentFilter = agent;
},
});

View File

@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8" ?>
<templates xml:space="preserve">
<t t-inherit="mail.MessagingMenu" t-inherit-mode="extension">
<xpath expr="//DiscussSearch" position="after">
<Dropdown t-if="this.showAgentFilterDropdown">
<button class="btn btn-outline-secondary ms-1 flex-shrink-0 position-relative" aria-label="Filters" title="Filters">
<i class="oi oi-filled" data-icon="filter_alt" role="img"/>
<span t-if="this.isAgentFilterActive" class="position-absolute top-0 start-100 translate-middle p-1 rounded-circle bg-success">
<span class="visually-hidden">filters active</span>
</span>
</button>
<t t-set-slot="content">
<CheckboxItem
class="{ 'border-bottom mb-2': true, selected: !this.isAgentFilterActive }"
checked="!this.isAgentFilterActive"
onSelected="() => this.selectAgentFilter(undefined)"
>My Recent Chats</CheckboxItem>
<t t-foreach="this.chatAgents" t-as="agent" t-key="agent.id">
<CheckboxItem
class="{ selected: this.isAgentSelected(agent) }"
checked="this.isAgentSelected(agent)"
onSelected="() => this.selectAgentFilter(agent)"
>
<span class="d-flex align-items-center gap-2">
<DiscussAvatar record="agent.partner_id" size="20"/>
<span class="text-truncate" t-out="agent.name"/>
</span>
</CheckboxItem>
</t>
</t>
</Dropdown>
</xpath>
</t>
</templates>

View File

@@ -0,0 +1,38 @@
import { MENU_TABS } from "@mail/core/public_web/messaging_menu/messaging_menu_model";
import { MessagingMenuUIState } from "@mail/core/public_web/messaging_menu/messaging_menu_ui_state_model";
import { fields } from "@mail/model/export";
import { patch } from "@web/core/utils/patch";
patch(MessagingMenuUIState.prototype, {
setup() {
super.setup(...arguments);
this.selectedAgentFilter = fields.One("ai.agent");
this.onChange(
() => [this.aiChatAgentId],
function onChangeAiChatAgentId(aiChatAgentId) {
if (this.activeTab?.id !== MENU_TABS.AI_CHAT) {
this.selectedAgentFilter = null;
}
this.setPluginFilter(
"ai.agent_scope",
aiChatAgentId
? {
id: `ai_agent:${aiChatAgentId}`,
includesChannel: (c) => c.ai_agent_id?.id === aiChatAgentId,
}
: null
);
},
{ immediate: true, initialRun: false }
);
},
get aiChatAgentId() {
return this.activeTab?.id === MENU_TABS.AI_CHAT && this.selectedAgentFilter
? this.selectedAgentFilter.id
: null;
},
get isSidebar() {
return this.id === "discuss.sidebar";
},
});

View File

@@ -0,0 +1,15 @@
import { Store } from "@mail/core/common/store_service";
import { patch } from "@web/core/utils/patch";
patch(Store.prototype, {
/**
* @override
*/
tabToThreadType(tab) {
const threadTypes = super.tabToThreadType(tab);
if (tab === "aiChat") {
threadTypes.push("ai_chat");
}
return threadTypes;
},
});

View File

@@ -0,0 +1,20 @@
import { SUGGESTION_DELIMITERS } from "@mail/core/common/suggestion_hook";
import { SuggestionService } from "@mail/core/common/suggestion_service";
import { patch } from "@web/core/utils/patch";
patch(SuggestionService.prototype, {
/** @override */
searchSuggestions({ delimiter, term }, { thread } = {}) {
if (
["ai_composer", "ai_chat"].includes(thread?.channel?.channel_type) &&
delimiter === SUGGESTION_DELIMITERS.PARTNER
) {
return {
type: undefined,
suggestions: [],
};
}
return super.searchSuggestions(...arguments);
},
});

View File

@@ -0,0 +1,80 @@
import { ACTION_TAGS } from "@mail/core/common/action";
import {
registerThreadAction,
ThreadAction,
threadActionsRegistry,
} from "@mail/core/common/thread_actions";
import {
expandDiscussSequenceGroup,
expandDiscussSequenceQuick,
} from "@mail/discuss/core/web/thread_actions";
import { ConfirmationDialog } from "@web/core/confirmation_dialog/confirmation_dialog";
import { _t } from "@web/core/l10n/translation";
import { patch } from "@web/core/utils/patch";
export const aiChatsActions = [
"add-to-favorites",
"close",
"delete-ai-chat",
"expand-discuss",
"fold-chat-window",
"remove-from-favorites",
"rename-thread",
"search-messages",
];
patch(ThreadAction.prototype, {
// keep only actions that are relevant for ai chats
_condition({ action, channel }) {
if (channel?.isAiChat && !aiChatsActions.includes(action.id)) {
return false;
}
return super._condition(...arguments);
},
computeCorrespondent() {
const correspondent = super.computeCorrespondent();
if (
["ai_composer", "ai_chat"].includes(this.channel_type) &&
correspondent?.persona?.eq(this.store.self)
) {
return undefined;
}
return correspondent;
},
});
patch(threadActionsRegistry.get("expand-discuss"), {
onSelected({ channel, store }) {
// when expanding an ai chat, unfold the ai chats category and fold all the other ones
if (channel?.isAiChat) {
return store.env.services.action.doAction({
context: { active_id: channel.id, expanded_from_ai_chat: true },
type: "ir.actions.client",
tag: "mail.action_discuss",
});
}
return super.onSelected(...arguments);
},
sequenceGroup: ({ channel }) => (channel?.isAiChat ? 0 : expandDiscussSequenceGroup),
sequenceQuick: ({ channel }) => (channel?.isAiChat ? 15 : expandDiscussSequenceQuick),
});
registerThreadAction("delete-ai-chat", {
condition: ({ channel, owner }) => channel?.isAiChat && !owner.isDiscussContent,
icon: "delete",
name: _t("Delete AI chat"),
onSelected: async ({ channel, store }) => {
await channel.isLoadedPromise;
if (!channel.hasLoadingFailed && channel.isEmpty) {
return channel.deleteAiChatRpc();
}
store.env.services.dialog.add(ConfirmationDialog, {
body: _t("Are you sure you want to delete this AI chat? All its content will be lost."),
confirmLabel: _t("Delete AI chat"),
confirm: () => channel.deleteAiChatRpc(),
cancel: () => {},
});
},
sequenceGroup: 20, // same as add-to-favorite
tags: ACTION_TAGS.DANGER,
});

View File

@@ -0,0 +1,25 @@
import { threadCompareRegistry } from "@mail/core/common/thread_compare";
import { compareDatetime } from "@mail/utils/common/misc";
threadCompareRegistry.add(
"ai.ai_chat-last-activity",
/**
* AI chats are sorted on a single timeline: most recent message time, or
* (for chats with nothing said yet) creation time instead.
*
* @param {import("models").Thread} thread1
* @param {import("models").Thread} thread2
*/
(thread1, thread2) => {
if (!thread1.channel?.isAiChat || !thread2.channel?.isAiChat) {
return undefined;
}
const aTime = thread1.newestPersistentOfAllMessage?.datetime ?? thread1.channel.create_date;
const bTime = thread2.newestPersistentOfAllMessage?.datetime ?? thread2.channel.create_date;
const res = compareDatetime(bTime, aTime);
if (res !== 0) {
return res;
}
},
{ sequence: 20 }
);

View File

@@ -0,0 +1,102 @@
import { aiChannelBus } from "@ai/utils/ai_channel_bus";
import { AgentToolSummary } from "@ai/discuss/agent_tool_summary";
import { Thread } from "@mail/core/common/thread";
import { _t } from "@web/core/l10n/translation";
import { patch } from "@web/core/utils/patch";
import { useBus } from "@web/core/utils/hooks";
import { signal } from "@odoo/owl";
Thread.components = { ...Thread.components, AgentToolSummary };
patch(Thread.prototype, {
setup() {
super.setup();
this.aiStepsGroupsVisibility = signal.Map();
if (this.props.thread.channel?.isAiChat) {
useBus(aiChannelBus, "AI: Update Target Record", ({ detail }) => {
const recordModel = detail.recordModel;
const recordId = detail.recordId;
if (
detail.targetRecord &&
this.props.thread.channel.aiRootSession.res_model === recordModel &&
this.props.thread.channel.aiRootSession.res_id === recordId
) {
this.props.thread.channel.targetRecord = detail.targetRecord;
this.props.thread.channel.aiSpecialActions = {
...this.props.thread.channel.aiSpecialActions,
...this.props.thread.channel.disabledActions,
};
this.props.thread.channel.disabledActions = {};
} else {
const { product_main_image, product_extra_image, ...remainingActions } =
this.props.thread.channel.aiSpecialActions || {};
const disabledActions = {};
if (product_main_image) {
disabledActions.product_main_image = product_main_image;
}
if (product_extra_image) {
disabledActions.product_extra_image = product_extra_image;
}
this.props.thread.channel.disabledActions = disabledActions;
this.props.thread.channel.aiSpecialActions = remainingActions;
}
});
useBus(aiChannelBus, "AI: Drop UseThis Action", () => {
// ProductAddExtraImageAction reloads the editor after save which causes the useThis button to be removed.
// We want to avoid that because the useThis button doesn't rely on the editor for saving in that specific case.
if (this.props.thread.channel.fromShopExtraImage) {
return;
}
const actions = this.props.thread.channel.aiSpecialActions || {};
delete actions.useThis;
});
}
},
get startMessageChannelTypes() {
return [...super.startMessageChannelTypes, "ai_chat"];
},
get startMessageSubtitle() {
if (this.channel?.isAiChat) {
return this.channel.ai_agent_id?.subtitle || _t("Hello, what can I help you with?");
} else {
return super.startMessageSubtitle;
}
},
onClickPromptButton(button) {
this.props.thread.post(button.name, {}, { ai_prompt_button_ref: button.id });
},
get showPromptButtons() {
return this.props.thread.messages.length === 0;
},
get sortedPromptButtons() {
return (this.channel?.ai_prompt_buttons || []).sort((a, b) => a.sequence - b.sequence);
},
isSquashed(msg, prevMsg) {
if (msg.aiAgentAuthored) {
// author and date are added when starting a steps group
return true;
}
return super.isSquashed(...arguments);
},
isStepsGroupShown(groupId) {
return (
this.aiStepsGroupsVisibility().get(groupId) ??
(this.channel.aiSession?.config["show_agent_steps"] ||
!!this.props.thread.store.debugMode.isActive())
);
},
preserveScrollPosition() {
this.props.thread.scrollTop = this.scrollableRef().scrollTop;
this.lastSetValue = undefined;
},
toggleStepsGroupVisibility(groupId, preserveScroll = true) {
if (preserveScroll) {
this.preserveScrollPosition();
}
this.aiStepsGroupsVisibility().set(groupId, !this.isStepsGroupShown(groupId));
},
showNewMessageLine(msg, prevMsg) {
// only show it for the final response
return !msg.aiIsAgentStep && super.showNewMessageLine(...arguments);
},
});

Some files were not shown because too many files have changed in this diff Show More