初始提交

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,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();
}
}