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

View File

@@ -0,0 +1,22 @@
import { fields, Record } from "@mail/model/export";
/**
* @typedef {{
* preview_key: number,
* model: string,
* records: { id: number, name: string, url: string}[],
* header: string,
* has_preview_cards: boolean,
* }} PreviewSet
*/
export class AIRecordPreviewsData extends Record {
static _name = "ai.record.previews";
static id = "message_id";
message_id = fields.One("mail.message", { inverse: "ai_record_previews" });
/** @type {PreviewSet[]} */
preview_sets = [];
}
AIRecordPreviewsData.register();

View File

@@ -0,0 +1,12 @@
import { ChatWindow } from "@mail/core/common/chat_window_model";
import { patch } from "@web/core/utils/patch";
patch(ChatWindow.prototype, {
_onClose(options = {}) {
const channel = this.channel;
super._onClose(...arguments);
if (channel) {
this.store.env.bus.trigger("CHATWINDOW_CLOSED", { channel });
}
},
});

View File

@@ -0,0 +1,19 @@
import { Message } from "@mail/core/common/message_model";
import { fields } from "@mail/model/export";
import { patch } from "@web/core/utils/patch";
import "./ai_record_previews_model";
/** @type {import("models").Message} */
const messagePatch = {
setup() {
super.setup(...arguments);
this.ai_record_previews = fields.One("ai.record.previews", {
inverse: "message_id",
onDelete: (recordPreviews) => recordPreviews?.delete(),
});
},
};
patch(Message.prototype, messagePatch);

View File

@@ -0,0 +1,84 @@
import { Component, useProps, types } from "@odoo/owl";
import { uniqueId } from "@web/core/utils/functions";
import {
CARD_SELECTOR,
INERT_PREVIEW_CONTROL_SELECTOR,
useAIPreviewCardSet,
} from "./use_ai_preview_cards";
const CARD_CLICK_BEHAVIOR = {
// These elements handle their own action
selfHandled: ["a[href]", "button", "[data-bs-toggle]"].join(", "),
inert: INERT_PREVIEW_CONTROL_SELECTOR,
// On mobile, keep chat open for in-page interactions
keepOpen: [
".o_wslides_js_slide_like_up",
".o_wslides_js_slide_like_down",
".o_wsale_attribute_previewer",
".o_add_wishlist",
].join(", "),
};
export class AIPreviewCardSet extends Component {
static template = "ai_website_livechat.AIPreviewCardSet";
setup() {
this.props = useProps({
previewSet: types.object(),
thread: types.object().optional(),
});
this.slotName = uniqueId("AICardslot");
this.previewCards = useAIPreviewCardSet(
this.props.previewSet,
this.slotName,
this.env.services["public.interactions"]
);
this.cardsHostRef = this.previewCards.cardsHostRef;
this.carousel = this.previewCards.carousel;
}
onCardClick(ev) {
const originalTarget = ev.composedPath().find((target) => target instanceof Element);
if (!originalTarget) {
return;
}
const card = originalTarget.closest(CARD_SELECTOR);
if (!card) {
return;
}
if (originalTarget.closest(CARD_CLICK_BEHAVIOR.inert)) {
return;
}
// On mobile, fold the chat unless the click targets an in-page interaction.
if (this.env.services.ui.isSmall && !originalTarget.closest(CARD_CLICK_BEHAVIOR.keepOpen)) {
this._foldChatWindow();
}
// Navigate to the card URL unless the click targets a self-handled element (link, button…).
if (!originalTarget.closest(CARD_CLICK_BEHAVIOR.selfHandled) && card.dataset.href) {
window.open(card.dataset.href, "_blank", "noopener");
}
}
_foldChatWindow() {
this.props.thread?.channel?.chatWindow?.fold();
}
}
export class AIRecordsPreview extends Component {
static template = "ai_website_livechat.AIRecordsPreview";
static components = { AIPreviewCardSet };
setup() {
this.props = useProps({
message: types.object(),
thread: types.object().optional(),
});
}
get previewSets() {
return (this.props.message.ai_record_previews?.preview_sets ?? []).filter(
({ records }) => records?.length
);
}
}

View File

@@ -0,0 +1,132 @@
.o-mail-Message-content,
.o_ai_livechat_message_content {
&:has(.o_ai_record_previews) {
.o_ai_preview_data {
display: none;
}
}
}
@mixin o-ai-preview-card-line-clamp($lines: 5) {
display: -webkit-box;
overflow: hidden;
text-overflow: ellipsis;
white-space: normal;
-webkit-box-orient: vertical;
-webkit-line-clamp: $lines;
}
.o-mail-Message-content:has(.o_ai_preview_cards_wrapper) {
width: 100%;
}
.o_ai_preview_cards_wrapper {
@media (prefers-reduced-motion: no-preference) {
animation: o-ai-preview-cards-enter nth($transition-base, 2) nth($transition-base, 3) both;
}
}
.o_ai_preview_card_set_header {
margin: map-get($spacers, 2) 0 map-get($spacers, 1);
color: inherit;
font-size: $font-size-sm;
font-weight: inherit;
}
.o_ai_preview_cards {
--o-ai-preview-card-gap: #{map-get($spacers, 2)};
--o-ai-scroll-gutter: #{map-get($spacers, 2)};
--o-ai-card-basis-wide: calc((100% - var(--o-ai-preview-card-gap)) / 2);
--o-ai-card-basis-narrow: 90%;
display: flex;
flex-wrap: nowrap;
align-items: stretch;
gap: var(--o-ai-preview-card-gap);
margin-block: map-get($spacers, 2);
padding: map-get($spacers, 3);
overflow: hidden;
scroll-snap-type: x mandatory;
scroll-behavior: smooth;
scroll-padding-inline: var(--o-ai-scroll-gutter);
@include media-breakpoint-down(lg) {
overflow-x: auto;
overflow-y: hidden;
overscroll-behavior-x: contain;
scrollbar-width: none;
-webkit-overflow-scrolling: touch;
&::-webkit-scrollbar {
display: none;
}
}
& > .o_ai_preview_card {
flex: 0 0 var(--o-ai-card-basis, var(--o-ai-card-basis-wide));
display: flex;
flex-direction: column;
overflow: hidden;
scroll-snap-align: start;
scroll-margin-inline: var(--o-ai-scroll-gutter);
container-type: inline-size;
& > * {
flex: 1 1 auto;
}
&:hover {
cursor: pointer;
}
:is(h1, h2, h3, .h1, .h2, .h3, .card-title) {
@include font-size($h5-font-size);
@include o-ai-preview-card-line-clamp(2);
line-height: $headings-line-height;
}
.o_record_cover_container {
min-height: map-get($spacers, 5) * 4;
}
}
}
.o_ai_preview_cards_root {
--o-ai-fade-size: #{map-get($spacers, 3)};
--_fade-left: black;
--_fade-right: black;
&.o-ai-has-prev {
--_fade-left: transparent;
}
&.o-ai-has-next {
--_fade-right: transparent;
}
mask-image: linear-gradient(
to right,
var(--_fade-left) 0%,
black var(--o-ai-fade-size),
black calc(100% - var(--o-ai-fade-size)),
var(--_fade-right) 100%
);
-webkit-mask-image: linear-gradient(
to right,
var(--_fade-left) 0%,
black var(--o-ai-fade-size),
black calc(100% - var(--o-ai-fade-size)),
var(--_fade-right) 100%
);
}
.o_ai_carousel_btn {
aspect-ratio: 1;
width: map-get($spacers, 4);
}
@keyframes o-ai-preview-cards-enter {
from {
opacity: 0;
transform: translateY(map-get($spacers, 1));
}
}

View File

@@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="ai_website_livechat.AIRecordsPreview" owl="1">
<div t-if="this.previewSets.length" class="o_ai_record_previews">
<t t-foreach="this.previewSets" t-as="previewSet" t-key="previewSet.preview_key">
<h6 t-if="previewSet.header" class="o_ai_preview_card_set_header" t-out="previewSet.header"/>
<AIPreviewCardSet
t-if="previewSet.has_preview_cards"
previewSet="previewSet"
thread="this.props.thread"
/>
<t t-elif="previewSet.records.length">
<t t-call="ai_website_livechat.AIRecordPreviewLinks"/>
</t>
</t>
</div>
</t>
<t t-name="ai_website_livechat.AIRecordPreviewLinks" owl="1">
<div>
<t t-foreach="previewSet.records" t-as="record" t-key="record.id">
<span class="o_ai_preview_link">
<a t-if="record.url !== '#'" t-att-href="record.url" target="_blank" rel="noopener noreferrer"><t t-out="record.name"/></a>
<span t-else="" t-out="record.name"/>
</span>
</t>
</div>
</t>
<t t-name="ai_website_livechat.AIPreviewCardSet" owl="1">
<div t-if="this.previewCards.html" class="o_ai_preview_cards_wrapper o_ai_preview_card_set" t-on-click="this.onCardClick">
<div class="o_ai_preview_cards_container d-flex align-items-center gap-1 overflow-hidden">
<button t-if="this.carousel.state.canScroll" class="o_ai_carousel_btn o_ai_carousel_prev btn btn-light btn-sm rounded-circle border p-0 flex-shrink-0 d-flex align-items-center justify-content-center align-self-center" type="button"
t-att-class="{ invisible: !this.carousel.hasPrev }" t-att-disabled="!this.carousel.hasPrev"
t-on-click="() => this.carousel.prev()">
<i class="oi" data-icon="chevron_left"/>
</button>
<div t-ref="this.cardsHostRef" class="o_ai_preview_cards_root flex-grow-1 min-w-0" t-att-class="{ 'o-ai-has-next': this.carousel.hasNext, 'o-ai-has-prev': this.carousel.hasPrev }">
<slot t-att-name="this.slotName"/>
</div>
<button t-if="this.carousel.state.canScroll" class="o_ai_carousel_btn o_ai_carousel_next btn btn-light btn-sm rounded-circle border p-0 flex-shrink-0 d-flex align-items-center justify-content-center align-self-center" type="button"
t-att-class="{ invisible: !this.carousel.hasNext }" t-att-disabled="!this.carousel.hasNext"
t-on-click="() => this.carousel.next()">
<i class="oi" data-icon="chevron_right"/>
</button>
</div>
</div>
<t t-elif="this.props.previewSet.records.length">
<t t-set="previewSet" t-value="this.props.previewSet"/>
<t t-call="ai_website_livechat.AIRecordPreviewLinks"/>
</t>
</t>
</templates>

View File

@@ -0,0 +1,164 @@
import { markup, onWillStart, signal, useEffect } from "@odoo/owl";
import { rpc } from "@web/core/network/rpc";
import { Cache } from "@web/core/utils/cache";
import { setElementContent } from "@web/core/utils/html";
import { useCarousel } from "./use_carousel";
export const CARD_SELECTOR = ".o_ai_preview_card";
const INERT_PREVIEW_CONTROL_CLASS = "o_ai_preview_inert_control";
export const INERT_PREVIEW_CONTROL_SELECTOR = `.${INERT_PREVIEW_CONTROL_CLASS}`;
const WEBSITE_FILTER_CONTROL_SELECTOR = ".o_ai_preview_card .post_link";
/**
* Hook that loads and displays a set of AI preview cards.
*
* - Fetches card HTML from the cache before the component mounts.
* - After mount, injects the HTML into the DOM, sets up responsive layout,
* and starts any website interactions.
*/
export function useAIPreviewCardSet(previewSet, slotName, interactions) {
const cardsHostRef = signal.ref();
const cardsContainerRef = signal.ref();
const carousel = useCarousel(cardsContainerRef, CARD_SELECTOR);
const previewCards = {
html: "",
cardsHostRef,
carousel,
};
// Fetch card HTML before the component renders so it's ready to inject.
onWillStart(async () => {
const { model, records } = previewSet;
const recordIds = records.map((record) => record.id);
if (!model || !recordIds.length) {
return;
}
const result = await previewCardsCache.read(model, recordIds);
if (result?.count > 0) {
previewCards.html = result.html;
}
});
// Once the host element is in the DOM and we have HTML, inject the cards
// and wire up layout + interactions.
useEffect(() => {
const cardsHost = cardsHostRef();
if (!cardsHost || !previewCards.html) {
return;
}
const container = insertPreviewCardsHtml(cardsHost, previewCards.html, slotName);
cardsContainerRef.set(container);
const cleanupLayout = setupPreviewCardsLayout(cardsHost, container, carousel.update);
const cleanupInteractions = setupPreviewCardsInteractions(container, interactions);
return () => {
cleanupLayout();
cleanupInteractions();
container.remove();
cardsContainerRef.set(null);
};
});
return previewCards;
}
export const previewCardsCache = new Cache((model, recordIds) =>
rpc("/ai/preview_cards", { model, record_ids: recordIds }).then(
(result) => {
if (!result?.html || typeof result.html !== "string") {
return null;
}
return { html: markup(result.html), count: result.count };
},
() => null
)
);
// Creates the card container from server HTML and inserts it into the DOM.
function insertPreviewCardsHtml(cardsHost, html, slotName) {
const container = createPreviewCardsContainer(html);
mountPreviewCardsContainer(cardsHost, container, slotName);
return container;
}
//Turns raw server HTML into a safe, ready-to-mount container.
function createPreviewCardsContainer(html) {
const container = document.createElement("div");
container.style.display = "contents";
setElementContent(container, html || "");
openLinksInNewTab(container);
makeWebsiteFilterControlsInert(container);
return container;
}
/**
* Mounts the card container in the right place depending on context.
* - Livechat widget uses a shadow DOM, so the container goes through a named
* slot on the shadow host.
* - Backend chat is a regular DOM, so we just append directly to the host.
*/
function mountPreviewCardsContainer(cardsHost, container, slotName) {
const rootNode = cardsHost.getRootNode();
if (rootNode instanceof ShadowRoot) {
container.slot = slotName;
rootNode.host.appendChild(container);
} else {
cardsHost.appendChild(container);
}
}
// Starts public website interactions inside the injected cards.
function setupPreviewCardsInteractions(cardsContainer, interactions) {
interactions?.startInteractions(cardsContainer);
return () => interactions?.stopInteractions(cardsContainer);
}
/**
* Keeps the carousel in sync with the card container's size and scroll position.
* - A ResizeObserver watches the host and switches between wide/narrow card
* sizing at 420 px.
* - A scroll listener on the inner card row updates the carousel nav state.
*/
function setupPreviewCardsLayout(cardsHost, cardsContainer, updateCarousel) {
const inner = cardsContainer.querySelector(".o_ai_preview_cards");
const updateLayout = () => {
if (inner) {
const isNarrow = cardsHost.offsetWidth < 420;
inner.style.setProperty(
"--o-ai-card-basis",
isNarrow ? "var(--o-ai-card-basis-narrow)" : "var(--o-ai-card-basis-wide)"
);
}
updateCarousel();
};
const ro = new ResizeObserver(updateLayout);
ro.observe(cardsHost);
updateLayout();
inner?.addEventListener("scroll", updateCarousel, { passive: true });
return () => {
ro.disconnect();
inner?.removeEventListener("scroll", updateCarousel);
};
}
// Forces every link inside the cards to open in a new tab.
function openLinksInNewTab(root) {
for (const el of root.querySelectorAll("a[href]")) {
el.target = "_blank";
el.rel = "noopener noreferrer";
}
}
// Strips the click/navigation behavior from website filter badges (.post_link).
function makeWebsiteFilterControlsInert(root) {
for (const el of root.querySelectorAll(WEBSITE_FILTER_CONTROL_SELECTOR)) {
el.removeAttribute("href");
el.removeAttribute("data-post");
el.classList.remove("post_link", "cursor-pointer", "o_badge_clickable");
el.classList.add(INERT_PREVIEW_CONTROL_CLASS);
}
}

View File

@@ -0,0 +1,89 @@
import { proxy } from "@odoo/owl";
// Sub-pixel rounding and fractional scroll positions can make scrollLeft
// differ from the theoretical maximum by a small amount; 2 px absorbs that.
const SCROLL_TOLERANCE_PX = 2;
/**
* Reactive carousel state and navigation for a horizontally-scrollable
* card container.
*
* @param {Function} rootRef - Signal containing the root whose descendants
* include the scrollable `.o_ai_preview_cards` wrapper.
* @param {string} cardSelector - CSS selector matching individual card
* elements inside the wrapper.
*/
export function useCarousel(rootRef, cardSelector) {
const state = proxy({
current: 0,
canScroll: false,
visibleCount: 1,
hasPrev: false,
hasNext: false,
});
function getInner() {
return rootRef()?.querySelector(".o_ai_preview_cards") ?? null;
}
function getCards(inner = getInner()) {
return inner ? inner.querySelectorAll(cardSelector) : [];
}
/**
* Sync reactive state with the current scroll position.
* Called on scroll events and when the container resizes.
*/
function update() {
const inner = getInner();
if (!inner) {
return;
}
const cards = getCards(inner);
const scrollMax = inner.scrollWidth - inner.clientWidth;
state.canScroll = scrollMax > SCROLL_TOLERANCE_PX;
state.hasPrev = inner.scrollLeft > SCROLL_TOLERANCE_PX;
state.hasNext = inner.scrollLeft < scrollMax - SCROLL_TOLERANCE_PX;
const card = cards[0];
const gap = parseFloat(getComputedStyle(inner).columnGap) || 0;
const step = (card?.offsetWidth ?? 0) + gap;
state.current = step ? Math.round(inner.scrollLeft / step) : 0;
state.visibleCount = card?.offsetWidth
? Math.max(1, Math.floor(inner.clientWidth / card.offsetWidth))
: 1;
}
/**
* Smooth-scroll so that the card at `index` is visible.
* The last card aligns to the end so no trailing gap is shown.
*/
function goTo(index) {
const inner = getInner();
if (!inner) {
return;
}
const cards = getCards(inner);
state.current = Math.max(0, Math.min(index, cards.length - 1));
const target = cards[state.current];
if (!target) {
return;
}
const inline = state.current === cards.length - 1 ? "end" : "start";
target.scrollIntoView({ behavior: "smooth", block: "nearest", inline });
}
return {
state,
update,
get hasPrev() {
return state.hasPrev;
},
get hasNext() {
return state.hasNext;
},
goTo,
prev: () => goTo(state.current - state.visibleCount),
next: () => goTo(state.current + state.visibleCount),
};
}

View File

@@ -0,0 +1,11 @@
import { Message } from "@mail/core/common/message";
import { AIRecordsPreview } from "@ai_website_livechat/discuss/core/common/preview_records/ai_records_preview";
import { patch } from "@web/core/utils/patch";
Message.components = { ...Message.components, AIRecordsPreview };
patch(Message.prototype, {
get hasRecordPreviews() {
return Boolean(this.props.message?.ai_record_previews?.preview_sets?.length);
},
});

View File

@@ -0,0 +1,8 @@
<?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-textContent')]" position="after">
<AIRecordsPreview t-if="this.hasRecordPreviews" message="this.props.message" thread="this.props.thread"/>
</xpath>
</t>
</templates>

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-inherit="mail.Thread" t-inherit-mode="extension">
<xpath expr="//div[@data-name='LivechatWelcomeMessage']" position="replace">
<t t-if="this.props.thread.channel?.livechatWelcomeMessage and !this.props.thread?.messages.length">
<t>$0</t>
</t>
</xpath>
</t>
</templates>

View File

@@ -0,0 +1,8 @@
import { Message } from "@mail/core/common/message";
import { patch } from "@web/core/utils/patch";
patch(Message.prototype, {
get hasRecordPreviews() {
return false;
},
});

View File

@@ -0,0 +1,352 @@
import { _t } from "@web/core/l10n/translation";
import { rpc } from "@web/core/network/rpc";
import { useService, useBus } from "@web/core/utils/hooks";
import {
Component,
onWillStart,
onMounted,
onPatched,
signal,
t,
useEffect,
untrack,
useProps,
} from "@odoo/owl";
import { browser } from "@web/core/browser/browser";
import { registry } from "@web/core/registry";
import { convertBrToLineBreak } from "@mail/utils/common/format";
import { AIRecordsPreview } from "@ai_website_livechat/discuss/core/common/preview_records/ai_records_preview";
export class AILivechatComponent extends Component {
static template = "ai_website_livechat.AILivechatComponent";
static components = { AIRecordsPreview };
props = useProps({
agentId: t.number(),
livechatChannelId: t.number().optional(),
chatStyle: t.string().optional(),
promptPlaceholder: t.string().optional(),
hasFallbackButton: t.boolean(),
fallbackButtonText: t.string(),
fallbackButtonURL: t.string(),
});
prompt = signal("");
messages = signal.Array([]);
assistantThinking = signal(false);
otherElementsHidden = signal(false);
promptInputRef = signal.ref();
messagesDivRef = signal.ref();
setup() {
this.notificationService = useService("notification");
this.store = useService("mail.store");
this.livechatService = useService("im_livechat.livechat");
this.channel = undefined;
onWillStart(this.isLivechatAvailable.bind(this));
onMounted(() => {
const aiLivechatSnippet = document.querySelector(this.SNIPPET_SELECTOR);
this.snippetParent = aiLivechatSnippet.parentNode;
this.snippetNextSibling = aiLivechatSnippet.nextElementSibling;
});
useBus(this.env.bus, "discuss.channel/new_message", this.onMessagePosted.bind(this));
useBus(this.env.bus, "CHATWINDOW_CLOSED", async (payload) => {
await this.onChatWindowClosed(payload);
});
useEffect(() => {
void this.prompt();
if (this.promptInputRef()) {
// Resize textarea to fit its content.
this.promptInputRef().style.height = 0;
this.promptInputRef().style.height = this.promptInputRef().scrollHeight + "px";
}
});
let scrollToLatest = false;
useEffect(() => {
void this.messages().length;
const selectorToHide = ["footer", ".o-livechat-root"];
if (this.messagesDivRef()) {
scrollToLatest = true;
if (!untrack(() => this.otherElementsHidden())) {
for (const s of selectorToHide) {
document.querySelector(s)?.classList.add("d-none");
}
this.hideOtherSnippets();
this.centerAndApplyWidthHeight();
this.otherElementsHidden.set(true);
}
} else if (untrack(() => this.otherElementsHidden())) {
for (const s of selectorToHide) {
document.querySelector(s)?.classList.remove("d-none");
}
this.showOtherSnippets();
this.restorePositionAndWidthHeight();
this.otherElementsHidden.set(false);
}
});
onPatched(() => {
if (scrollToLatest) {
scrollToLatest = false;
this.messagesDivRef()?.lastElementChild?.scrollIntoView({
block: "start",
inline: "nearest",
behavior: "smooth",
});
if (this.props.chatStyle === "fullscreen") {
this.promptInputRef()?.focus({ preventScroll: true });
}
}
});
}
async isLivechatAvailable() {
this.livechatAvailable = await rpc("/ai_website_livechat/is_livechat_operator_available", {
livechat_channel_id: this.props.livechatChannelId,
});
}
onMessagePosted({ detail: { message } }) {
if (!message.channel_id?.eq(this.channel) || message.isSelfAuthored) {
return;
}
this.processResponse(message);
}
processResponse(message) {
if (
this.props.chatStyle !== "fullscreen" ||
!this.channel.ai_agent_id ||
!message.aiIsAgentResponse
) {
return;
}
this.messages().push({
author: "assistant",
text: message.body,
id: message.id,
ai_record_previews: message.ai_record_previews,
});
this.assistantThinking.set(false);
}
async onChatWindowClosed({ detail }) {
if (detail.channel.eq(this.channel)) {
// leaveLivechatSession = false => User has already left the livechat session.
await this.closeConversation(false);
}
}
async closeConversation(leaveLivechatSession = true) {
if (leaveLivechatSession && this.channel?.channel_type === "livechat") {
await this.livechatService.leave(this.channel);
}
this.resetState();
this.channel = undefined;
}
resetState() {
this.messages.set([]);
this.prompt.set("");
this.assistantThinking.set(false);
}
showOtherSnippets() {
const aiLivechatSnippet = document.querySelector(this.SNIPPET_SELECTOR);
if (aiLivechatSnippet) {
this.snippetParent.insertBefore(aiLivechatSnippet, this.snippetNextSibling);
}
const snippetsToShow = document.querySelectorAll(this.ALL_SNIPPETS_SELECTOR);
for (const snippet of snippetsToShow) {
snippet.classList.remove("d-none");
}
}
restorePositionAndWidthHeight() {
const aiLivechatContainer = document
.querySelector(this.SNIPPET_SELECTOR)
.querySelector('[data-name="ai_livechat_container"]');
const aiLivechatSnippetEl = document.querySelector(this.SNIPPET_SELECTOR);
if (aiLivechatContainer) {
aiLivechatContainer.classList.remove("o_ai_livechat_container");
}
aiLivechatSnippetEl.classList.remove("s_ai_livechat_fullscreen");
}
hideOtherSnippets() {
// Hiding all snippets other than the aiLivechatSnippet may result in hiding the aiLivechatSnippet if it is embedded into another snippet.
// Instead, all the snippets will be hidden and the aiLivechatSnippet will be added to the '#wrap' div which wraps all the snippets.
const snippetsToHide = document.querySelectorAll(this.ALL_SNIPPETS_SELECTOR);
for (const snippet of snippetsToHide) {
snippet.classList.add("d-none");
}
const aiLivechatSnippet = document.querySelector(this.SNIPPET_SELECTOR);
if (aiLivechatSnippet) {
aiLivechatSnippet.classList.remove("d-none");
document
.querySelector(this.SNIPPETS_WRAPPER_DIV_SELECTOR)
.appendChild(aiLivechatSnippet);
}
}
centerAndApplyWidthHeight() {
const aiLivechatContainer = document
.querySelector(this.SNIPPET_SELECTOR)
.querySelector('[data-name="ai_livechat_container"]');
const aiLivechatSnippetEl = document.querySelector(this.SNIPPET_SELECTOR);
if (aiLivechatContainer) {
aiLivechatContainer.classList.add("o_ai_livechat_container");
}
aiLivechatSnippetEl.classList.add("s_ai_livechat_fullscreen");
aiLivechatSnippetEl.scrollIntoView({ behavior: "smooth" });
}
onTextareaKeydown(ev) {
if (ev.key === "Enter" && !ev.shiftKey) {
ev.stopImmediatePropagation();
if (this.prompt().trim().length) {
this.submitPrompt(ev);
}
}
}
async submitPrompt(ev) {
ev?.preventDefault();
if (!this.props.agentId) {
this.notificationService.add(_t("Oops, there is no Agent linked to this block!"));
return;
}
if (this.channel && !this.channel.ai_agent_id) {
return;
}
await this.createChannel(this.props.chatStyle === "popup");
if (!this.isChannelActive) {
return;
}
this.channel?.post(this.prompt());
if (this.props.chatStyle === "fullscreen") {
const sanitizedPrompt = DOMPurify.sanitize(this.prompt());
this.messages().push({
author: "user",
text: new DOMParser().parseFromString(sanitizedPrompt, "text/html").body
.textContent,
});
this.assistantThinking.set(true);
}
this.prompt.set("");
}
async createChannel(openChatWindow) {
if (this.isChannelActive) {
return;
}
let archivedAgent = false;
if (this.livechatAvailable) {
const livechatChannelOptions = {
persist: true,
channel_id: this.props.livechatChannelId,
ai_agent_id: this.props.agentId,
};
this.channel = await this.livechatService._createChannel({
options: livechatChannelOptions,
});
// If an ai_agent is set on the website snippet and then that ai_agent became archived and wasn't removed
// from the snippet, the created channel won't have ai_agent_id.
if (!this.channel.ai_agent_id) {
this.channel = undefined;
archivedAgent = true;
}
} else {
const channel_params = { ai_agent_id: this.props.agentId };
const result = await rpc("/ai_website_livechat/create_chat_channel", channel_params);
if (result) {
this.store.insert(result["store_data"]);
this.channel = this.store["discuss.channel"].get(result["channel_id"]);
} else {
archivedAgent = true;
}
}
if (archivedAgent) {
this.notificationService.add(_t("Oops, the Agent linked to this block is archived!"));
return;
}
if (openChatWindow) {
await this.channel.openChatWindow({ focus: true });
}
}
async askHuman(ev) {
await this.createChannel(false);
if (!this.isChannelActive || !this.channel.ai_agent_id) {
return;
}
const result = await rpc("/ai_livechat/forward_operator", {
channel_id: this.channel.id,
});
if (result["store_data"]) {
this.store.insert(result["store_data"]);
}
if (result["notification"]) {
this.store.env.services.notification.add(result["notification"], {
type: result["notification_type"],
});
}
if (result["success"] === true) {
this.channel.resolveReadyToSwap();
await this.channel.openChatWindow({ focus: true });
// Reset the state to show other snippets. The livechat with a human will always open in a chat window popup not fullscreen.
this.resetState();
}
}
async copyAnswer(message_index) {
const message_content_markdown = convertBrToLineBreak(this.messages()[message_index].text);
const message_content_html = this.messages()[message_index].text;
await browser.navigator.clipboard?.write([
new ClipboardItem({
"text/html": new Blob([message_content_html], { type: "text/html" }),
"text/plain": new Blob([message_content_markdown], { type: "text/plain" }),
}),
]);
}
get fallbackButtonActive() {
return !this.livechatAvailable && this.props.hasFallbackButton;
}
get isChannelActive() {
return Boolean(
this.channel &&
(this.channel.isAiChat ||
(this.channel.channel_type == "livechat" && !this.channel.livechat_end_dt))
);
}
hasRecordPreviews(message) {
return Boolean(message?.ai_record_previews?.preview_sets?.length);
}
get SNIPPET_SELECTOR() {
return ".s_ai_livechat";
}
get ALL_SNIPPETS_SELECTOR() {
return `${this.SNIPPETS_WRAPPER_DIV_SELECTOR} > *`;
}
get SNIPPETS_WRAPPER_DIV_SELECTOR() {
return "#wrap";
}
get thinkingText() {
return this.channel?.ai_session_ids?.[0]?.toolStatus;
}
}
registry
.category("public_components")
.add("ai_website_livechat.ai_livechat_component", AILivechatComponent);

View File

@@ -0,0 +1,96 @@
.o_ai_livechat_message_content {
p {
margin-bottom: 0 !important;
}
}
.o_show_on_message_hover {
visibility: hidden;
}
.o_ai_livechat_message_with_copy_button:hover {
.o_show_on_message_hover {
visibility: visible;
}
}
.s_ai_livechat {
.ai_website_livechat_form {
&:focus-within {
// Use BS default :focus rules but apply them on :focus-within to
// ensure that the wrapper is correctly focused.
color: $input-focus-color;
background-color: $input-focus-bg;
border-color: $input-focus-border-color;
outline: 0;
@if $enable-shadows {
@include box-shadow($input-box-shadow, $input-focus-box-shadow);
} @else {
box-shadow: $input-focus-box-shadow;
}
}
textarea {
background: inherit;
color: inherit;
padding: 0;
min-height: $input-font-size * $line-height-base;
}
.ai_website_livechat_form_button {
--btn-color: inherit;
--btn-disabled-opacity: 0.5;
&:not(:hover):not(.disabled) {
opacity: 0.8;
}
}
}
// ==== The full-screen chatter mode is active
&.s_ai_livechat_fullscreen {
padding-top: 0!important; // override user settings
padding-bottom: 0!important;
.o_ai_livechat_container {
transition: all .6s ease-in-out;
}
.o_ai_livechat_container {
--o_ai_livechat_gap: #{map-get($spacers, 2)};
min-height: calc(100dvh - calc(var(--o_ai_livechat_gap) * 2));
padding-top: var(--o_ai_livechat_gap);
padding-bottom: var(--o_ai_livechat_gap);
@include media-breakpoint-up(lg) {
--o_ai_livechat_gap: #{map-get($spacers, 3)};
}
@include media-breakpoint-up(xl) {
--o_ai_livechat_gap: #{map-get($spacers, 4)};
}
.ai_livechat_component {
display: flex;
flex-direction: column;
flex-grow: 1;
}
.o_ai_livechat_form_container_sticky {
bottom: var(--o_ai_livechat_gap);
}
}
.o_we_shape {
// Decrease but keep visible any background shape
opacity: .4;
}
}
// ==== Edit Mode
.ai_livechat_component > br {
// Hide editor elements suggesting user edition is places where we don't
// want to.
display: none;
}
}

View File

@@ -0,0 +1,79 @@
<templates id="template" xml:space="preserve">
<t t-name="ai_website_livechat.AILivechatComponent">
<div class="flex-grow-1" t-ref="this.messagesDivRef" t-if="this.messages().length">
<div t-foreach="this.messages()" t-as="message" t-key="message_index"
class="py-1 overflow-x-auto o_ai_livechat_message_with_copy_button"
t-att-class="{
'mt-2': message_index,
'mt-0': !message_index,
'justify-content-end d-flex': message.author === 'user'
}"
>
<div class="rounded text-break py-2 o_ai_livechat_message_content"
t-att-class="{'px-3 bg-200': message.author === 'user'}"
>
<t t-out="message.text"/>
<AIRecordsPreview
t-if="this.hasRecordPreviews(message)"
message="message"
/>
</div>
<div class="o_show_on_message_hover" t-if="message.author === 'assistant'">
<button class="btn p-0 border-0" t-on-click="() => this.copyAnswer(message_index)">
<i class="oi oi-fw text-muted" data-icon="content_copy"></i>
</button>
</div>
</div>
<div t-if="this.assistantThinking()" class="d-flex align mb-3">
<img src="/web/static/img/spin.svg" alt="Loading..." class="me-2"
style="filter:invert(1); opacity: 0.5; width: 30px; height: 30px;"/>
<p class="m-0 text-muted align-self-center">
<em t-if="this.thinkingText" t-out="thinkingText"/>
<em t-else="">Thinking</em>
</p>
</div>
</div>
<div class="d-flex m-0 gap-2 gap-xl-4" t-att-class="{'o_ai_livechat_form_container_sticky position-sticky': this.messages().length}">
<div class="flex-column flex-grow-1">
<div class="mb-1" t-att-class="{'d-none': !this.messages().length,}">
<button t-if="this.livechatAvailable" class="btn btn-primary small rounded-2 py-1 px-3 me-3" t-att-disabled="this.assistantThinking()" t-on-click="this.askHuman">Ask a Human</button>
<a t-elif="this.fallbackButtonActive" class="btn btn-primary small rounded-2 py-1 px-3 me-3" t-att-disabled="this.assistantThinking()" t-att-href="this.props.fallbackButtonURL">
<t t-out="this.props.fallbackButtonText"/>
</a>
<button class="btn btn-dark small rounded-2 py-1 px-3 me-3" t-att-disabled="this.assistantThinking()" t-on-click="this.closeConversation">Close</button>
</div>
<div class="ai_website_livechat_form form-control d-flex align-items-center w-100 py-0 ps-lg-3 ps-xl-4 pe-lg-2">
<textarea type="text" t-ref="this.promptInputRef"
name="promptInput" t-on-keydown="this.onTextareaKeydown"
class="flex-grow-1 overflow-hidden form-control-plaintext border-0 shadow-none"
t-att-disabled="this.assistantThinking()"
rows="1"
style="resize:none;"
t-att-placeholder="this.props.promptPlaceholder"
autocomplete="off"
t-model="this.prompt" required="required">
</textarea>
<div class="align-self-baseline py-2">
<t t-set="isEmpty" t-value="this.prompt().trim() === ''"/>
<button
class="ai_website_livechat_form_button btn btn-sm border-0"
t-att-class="{'disabled': isEmpty}"
t-att-disabled="isEmpty"
t-on-click="this.submitPrompt"
title="Submit"
>
<i class="oi oi-fw oi-lg oi-filled fs-5" data-icon="send" style="scale: .75;" role="presentation"/>
</button>
</div>
</div>
</div>
<div t-if="this.livechatAvailable || this.fallbackButtonActive" class="flex-grow-0 d-flex gap-2 gap-xl-4 align-items-center text-nowrap" t-att-class="{'d-none': this.messages().length}">
<span class="text-muted">or</span>
<button t-if="this.livechatAvailable" class="btn btn-primary w-lg-100 ask-human" t-on-click="this.askHuman">Ask a Human</button>
<a t-elif="this.fallbackButtonActive" class="btn btn-primary w-lg-100 fallback-btn" role="button" t-att-href="this.props.fallbackButtonURL">
<t t-out="this.props.fallbackButtonText"/>
</a>
</div>
</div>
</t>
</templates>

View File

@@ -0,0 +1,29 @@
import { Interaction } from "@web/public/interaction";
import { registry } from "@web/core/registry";
import { AILivechatComponent } from "@ai_website_livechat/website/components/ai_livechat_component/ai_livechat";
import { _t } from "@web/core/l10n/translation";
export class AILivechat extends Interaction {
static selector = ".s_ai_livechat";
dynamicContent = {
".ai_livechat_component": {
"t-component": () => {
return [
AILivechatComponent,
{
'chatStyle': this.el.dataset.chatStyle ? this.el.dataset.chatStyle : 'fullscreen',
'agentId': parseInt(this.el.dataset.agentId),
'livechatChannelId': parseInt(this.el.dataset.livechatChannelId),
'promptPlaceholder': this.el.dataset.promptPlaceholder ? this.el.dataset.promptPlaceholder : _t('Ask AI'),
'hasFallbackButton': this.el.dataset.hasFallbackButton === 'true' ? true : false,
'fallbackButtonText': this.el.dataset.fallbackButtonText ? this.el.dataset.fallbackButtonText : _t('Contact Us'),
'fallbackButtonURL': this.el.dataset.fallbackButtonURL || '',
}
]
}
}
};
}
registry.category("public.interactions").add("ai_website_livechat.ai_livechat", AILivechat);

View File

@@ -0,0 +1,28 @@
import { Interaction } from "@web/public/interaction";
import { registry } from "@web/core/registry";
import { _t } from "@web/core/l10n/translation";
export class AILivechatEdit extends Interaction {
static selector = ".s_ai_livechat";
setup() {
this.renderAt("ai_website_livechat.s_ai_livechat_edit", {
livechatAvailable: this.livechatAvailable,
fallbackButtonActive: this.fallbackButtonActive,
fallbackButtonURL: this.el.dataset.fallbackButtonURL,
fallbackButtonText: this.el.dataset.fallbackButtonText || _t('Contact Us'),
}, this.el.querySelector(".ai_livechat_component"))
this.el.querySelector('.ai_livechat_prompt_textarea').setAttribute('placeholder', this.el.dataset.promptPlaceholder || _t('Ask AI'));
}
get livechatAvailable() {
return this.el.dataset.livechatChannelId;
}
get fallbackButtonActive() {
return this.el.dataset.hasFallbackButton === "true";
}
}
registry.category("public.interactions.edit").add("ai_website_livechat.ai_livechat_edit", {
Interaction: AILivechatEdit,
});

View File

@@ -0,0 +1,37 @@
<templates id="template" xml:space="preserve">
<t t-name="ai_website_livechat.s_ai_livechat_edit">
<div class="d-flex m-0 gap-2 gap-xl-4">
<div class="flex-column flex-grow-1">
<div class="ai_website_livechat_form form-control d-flex align-items-center w-100 py-0 ps-lg-3 ps-xl-4 pe-lg-2">
<textarea type="text"
class="ai_livechat_prompt_textarea flex-grow-1 overflow-hidden form-control-plaintext border-0 shadow-none"
autocomplete="off"
readonly=""
rows="1"
style="resize:none;"
/>
<div class="align-self-baseline py-2">
<button class="ai_website_livechat_form_button btn btn-sm border-0 disabled">
<i
class="oi oi-fw oi-lg oi-filled fs-5"
data-icon="send"
style="scale: .75;"
role="presentation"
/>
</button>
</div>
</div>
</div>
<div
t-if="livechatAvailable || fallbackButtonActive"
class="flex-grow-0 d-flex gap-2 gap-xl-4 align-items-center text-nowrap"
>
<span class="text-muted">or</span>
<button t-if="livechatAvailable and !fallbackButtonActive" class="btn btn-primary w-lg-100 ask-human">Ask a Human</button>
<a t-elif="fallbackButtonActive" class="btn btn-primary w-lg-100 fallback-btn" role="button" t-att-href="fallbackButtonURL">
<t t-out="fallbackButtonText"/>
</a>
</div>
</div>
</t>
</templates>

View File

@@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="ai_website_livechat.AILivechatOption">
<BuilderRow label.translate="Chat Style">
<BuilderSelect action="'setChatStyle'" preview="false">
<BuilderSelectItem actionParam="'popup'" title.translate="Popup Window">Popup Window</BuilderSelectItem>
<BuilderSelectItem actionParam="'fullscreen'" title.translate="Fullscreen">Fullscreen</BuilderSelectItem>
</BuilderSelect>
</BuilderRow>
<BuilderRow label.translate="AI Agent">
<BuilderMany2One action="'setAIAgent'" model="'ai.agent'" domain="[['is_system_agent', '=', false]]"/>
</BuilderRow>
<BuilderRow label.translate="Live Chat Channel" tooltip.translate="Displayed only when a support person is available">
<BuilderMany2One action="'setLivechatChannel'" model="'im_livechat.channel'"/>
</BuilderRow>
<BuilderRow label.translate="Prompt Placeholder">
<BuilderTextInput action="'setPromptPlaceholder'" placeholder.translate="e.g. Ask AI"/>
</BuilderRow>
<BuilderRow label.translate="Fallback Button" tooltip.translate="Displayed when there are no support personnel online">
<BuilderCheckbox action="'toggleHasFallbackButton'" id="'aiLivechatFallbackButton'"/>
</BuilderRow>
<BuilderRow label.translate="Text" level="1" t-if="this.isActiveItem('aiLivechatFallbackButton')">
<BuilderTextInput action="'setFallbackButtonText'" placeholder.translate="e.g. Contact Us" default="''"/>
</BuilderRow>
<BuilderRow label.translate="URL" level="1" t-if="this.isActiveItem('aiLivechatFallbackButton')">
<BuilderUrlPicker action="'setFallbackButtonURL'" placeholder.translate="e.g. /contactus" default="''"/>
</BuilderRow>
<hr/>
</t>
<t t-inherit="website.BuilderOptions" t-inherit-mode="extension">
<xpath expr="//t[@id='snippet_specific_options']" position="after">
<ai_livechat_option
template="ai_website_livechat.AILivechatOption"
selector=".s_ai_livechat"/>
</xpath>
</t>
</templates>

View File

@@ -0,0 +1,194 @@
import { Plugin } from "@html_editor/plugin";
import { registry } from "@web/core/registry";
import { BuilderAction } from "@html_builder/core/builder_action";
async function update_website_snippet_agent({ ormService, newAgentId = null, oldAgentId = null }) {
const agent_ids = {};
if (newAgentId) {
agent_ids.new_agent_id = parseInt(newAgentId);
}
if (oldAgentId) {
agent_ids.old_agent_id = parseInt(oldAgentId);
}
await ormService.call("ai.agent", "update_website_snippet_agent", [], agent_ids);
}
export class AILivechatOptionPlugin extends Plugin {
static id = "aiLivechatOption";
resources = {
so_content_addition_selectors: [".s_ai_livechat"],
builder_actions: {
SetChatStyleAction,
SetAIAgentAction,
SetLivechatChannelAction,
SetPromptPlaceholderAction,
ToggleHasFallbackButtonAction,
SetFallbackButtonTextAction,
SetFallbackButtonURLAction,
},
on_snippet_dropped_handlers: this.onSnippetDropped.bind(this),
on_will_remove_handlers: this.onWillRemove.bind(this),
};
async onSnippetDropped({ snippetEl }) {
if (snippetEl.matches(".s_ai_livechat:has(.s_ai_livechat_preview)")) {
snippetEl.querySelector(".s_ai_livechat_preview").remove();
const aiAgentId = await this.services.orm.search(
"ai.agent",
[
"|",
["livechat_channel_rule_ids", "!=", false],
["used_on_website_snippet", "=", true],
],
{ limit: 1 }
);
if (aiAgentId) {
snippetEl.dataset.agentId = aiAgentId;
}
}
}
async onWillRemove(toRemoveEl) {
if (toRemoveEl.matches(".s_ai_livechat")) {
const aiAgentId = toRemoveEl.dataset.agentId;
if (aiAgentId) {
await update_website_snippet_agent({
ormService: this.services.orm,
oldAgentId: aiAgentId,
});
}
}
}
}
export class SetAIAgentAction extends BuilderAction {
static id = "setAIAgent";
getValue({ editingElement }) {
const agentId = editingElement.dataset.agentId;
if (!agentId) {
return undefined;
}
return JSON.stringify({ id: parseInt(agentId) });
}
async apply({ editingElement, value }) {
const id = value ? JSON.parse(value).id : "";
editingElement.dataset.agentId = id;
await update_website_snippet_agent({
ormService: this.services.orm,
newAgentId: id,
oldAgentId: editingElement.dataset.agentId,
});
}
async clean({ editingElement }) {
const oldAgentId = editingElement.dataset.agentId;
editingElement.dataset.agentId = "";
await update_website_snippet_agent({
ormService: this.services.orm,
oldAgentId: oldAgentId,
});
}
}
export class SetLivechatChannelAction extends BuilderAction {
static id = "setLivechatChannel";
getValue({ editingElement }) {
const livechatChannelId = editingElement.dataset.livechatChannelId;
if (!livechatChannelId) {
return undefined;
}
return JSON.stringify({ id: parseInt(livechatChannelId) });
}
apply({ editingElement, value }) {
const id = value ? JSON.parse(value).id : "";
editingElement.dataset.livechatChannelId = id;
}
clean({ editingElement }) {
editingElement.dataset.livechatChannelId = "";
}
}
export class SetChatStyleAction extends BuilderAction {
static id = "setChatStyle";
isApplied({ editingElement, params: { mainParam: chatStyle } }) {
if (!editingElement.dataset.chatStyle) {
editingElement.dataset.chatStyle = "fullscreen";
}
return editingElement.dataset.chatStyle === chatStyle;
}
apply({ editingElement, params: { mainParam: chatStyle } }) {
editingElement.dataset.chatStyle = chatStyle;
}
}
export class SetPromptPlaceholderAction extends BuilderAction {
static id = "setPromptPlaceholder";
getValue({ editingElement }) {
const promptPlaceholder = editingElement.dataset.promptPlaceholder;
if (!promptPlaceholder) {
return "";
}
return promptPlaceholder;
}
apply({ editingElement, value }) {
editingElement.dataset.promptPlaceholder = value;
}
}
export class ToggleHasFallbackButtonAction extends BuilderAction {
static id = "toggleHasFallbackButton";
isApplied({ editingElement }) {
return editingElement.dataset.hasFallbackButton === "true";
}
apply({ editingElement }) {
const value = editingElement.dataset.hasFallbackButton === "true" ? false : true;
editingElement.dataset.hasFallbackButton = value;
}
}
export class SetFallbackButtonTextAction extends BuilderAction {
static id = "setFallbackButtonText";
getValue({ editingElement }) {
const fallbackButtonText = editingElement.dataset.fallbackButtonText;
if (!fallbackButtonText) {
return "";
}
return fallbackButtonText;
}
apply({ editingElement, value }) {
editingElement.dataset.fallbackButtonText = value;
}
}
export class SetFallbackButtonURLAction extends BuilderAction {
static id = "setFallbackButtonURL";
getValue({ editingElement }) {
const fallbackButtonURL = editingElement.dataset.fallbackButtonURL;
if (!fallbackButtonURL) {
return "";
}
return fallbackButtonURL;
}
apply({ editingElement, value }) {
editingElement.dataset.fallbackButtonURL = value;
}
}
registry.category("website-plugins").add(AILivechatOptionPlugin.id, AILivechatOptionPlugin);

View File

@@ -0,0 +1,251 @@
import { AIRecordsPreview } from "@ai_website_livechat/discuss/core/common/preview_records/ai_records_preview";
import { previewCardsCache } from "@ai_website_livechat/discuss/core/common/preview_records/use_ai_preview_cards";
import { defineMailModels } from "@mail/../tests/mail_test_helpers";
import { expect, getFixture, test } from "@odoo/hoot";
import { click, waitFor } from "@odoo/hoot-dom";
import {
mountWithCleanup,
mockService,
onRpc,
patchWithCleanup,
preventResizeObserverError,
} from "@web/../tests/web_test_helpers";
preventResizeObserverError();
defineMailModels();
test("AIRecordsPreview fetches and injects preview cards", async () => {
previewCardsCache.invalidate();
mockService("public.interactions", () => ({
startInteractions(root) {
expect.step(`start:${root.querySelectorAll(".o_ai_preview_card").length}`);
},
stopInteractions() {},
}));
onRpc("/ai/preview_cards", async (request) => {
const { params } = await request.json();
expect.step("fetch-cards");
expect(params).toEqual({ model: "product.template", record_ids: [10, 11] });
return {
count: 2,
html: `
<div class="o_ai_preview_cards">
<div class="o_ai_preview_card" data-href="/shop/product/desk">
<a href="/shop/product/desk">Desk</a>
</div>
<div class="o_ai_preview_card" data-href="/shop/product/chair">
<button type="button">Configure</button>
<a class="o_add_wishlist" href="/shop/wishlist">Wishlist</a>
</div>
</div>
`,
};
});
const message = {
id: 42,
ai_record_previews: {
preview_sets: [
{
preview_key: 0,
model: "product.template",
has_preview_cards: true,
records: [
{ id: 10, url: "/shop/product/desk", name: "Desk" },
{ id: 11, url: "/shop/product/chair", name: "Chair" },
],
header: "",
},
],
},
};
const fixture = getFixture();
fixture.innerHTML = `
<div class="o_ai_livechat_message_content">
<span class="o_ai_preview_data">
<a href="/shop/product/desk">Desk</a>
<a href="/shop/product/chair">Chair</a>
</span>
</div>
`;
await mountWithCleanup(AIRecordsPreview, {
target: fixture.querySelector(".o_ai_livechat_message_content"),
props: { message },
});
await waitFor(".o_ai_preview_cards_wrapper");
expect(".o_ai_preview_card").toHaveCount(2);
expect(".o_ai_preview_data").not.toBeVisible();
expect(".o_ai_preview_card a[href='/shop/product/desk']").toHaveAttribute("target", "_blank");
expect(".o_ai_preview_card a[href='/shop/product/desk']").toHaveAttribute(
"rel",
"noopener noreferrer"
);
expect.verifySteps(["fetch-cards", "start:2"]);
});
test("AIRecordsPreview opens plain card clicks and leaves controls alone", async () => {
previewCardsCache.invalidate();
mockService("public.interactions", () => ({
startInteractions() {},
stopInteractions() {},
}));
onRpc("/ai/preview_cards", () => ({
count: 2,
html: `
<div class="o_ai_preview_cards">
<div class="o_ai_preview_card" data-href="/shop/product/desk">
<span class="plain">Desk</span>
</div>
<div class="o_ai_preview_card" data-href="/shop/product/chair">
<button type="button">Configure</button>
<a href="/shop/product/chair">Chair</a>
<a class="badge text-bg-primary" href="/slides/course/tag/tools">Tools</a>
<a class="badge post_link text-decoration-none o_tag o_color_1" href="/blog">Blog</a>
</div>
</div>
`,
}));
patchWithCleanup(window, {
open(url, target, features) {
expect.step(`${url}:${target}:${features}`);
},
});
const message = {
id: 43,
ai_record_previews: {
preview_sets: [
{
preview_key: 0,
model: "product.template",
has_preview_cards: true,
records: [
{ id: 10, url: "/shop/product/desk", name: "Desk" },
{ id: 11, url: "/shop/product/chair", name: "Chair" },
],
header: "",
},
],
},
};
const fixture = getFixture();
fixture.innerHTML = `
<div class="o_ai_livechat_message_content">
<span class="o_ai_preview_data">
<a href="/shop/product/desk">Desk</a>
<a href="/shop/product/chair">Chair</a>
</span>
</div>
`;
await mountWithCleanup(AIRecordsPreview, {
target: fixture.querySelector(".o_ai_livechat_message_content"),
props: { message },
});
await waitFor(".o_ai_preview_card .plain");
expect(".o_ai_preview_inert_control").toHaveCount(1);
expect(".o_ai_preview_inert_control").not.toHaveAttribute("href");
expect(".o_ai_preview_card .post_link").toHaveCount(0);
await click(".o_ai_preview_card .plain");
await click(".o_ai_preview_card button");
await click(".o_ai_preview_card a[href='/shop/product/chair']");
await click(".o_ai_preview_inert_control");
expect.verifySteps(["/shop/product/desk:_blank:noopener"]);
});
test("AIRecordsPreview shows links for non-previewable records", async () => {
const fixture = getFixture();
fixture.innerHTML = `
<div class="o_ai_livechat_message_content">
<span class="o_ai_preview_data">
<a href="/web#model=res.partner&amp;id=7">Azure Interior</a>
</span>
</div>
`;
await mountWithCleanup(AIRecordsPreview, {
target: fixture.querySelector(".o_ai_livechat_message_content"),
props: {
message: {
id: 44,
ai_record_previews: {
preview_sets: [
{
preview_key: 0,
model: "res.partner",
has_preview_cards: false,
records: [
{
id: 7,
url: "/web#model=res.partner&id=7",
name: "Azure Interior",
},
],
header: "",
},
],
},
},
},
});
expect(".o_ai_preview_cards_wrapper").toHaveCount(0);
expect(".o_ai_record_previews .o_ai_preview_link a").toHaveText("Azure Interior");
expect(".o_ai_record_previews .o_ai_preview_link a").toBeVisible();
expect(".o_ai_preview_data").not.toBeVisible();
});
test("AIRecordsPreview shows links fallback when fetched HTML has no cards", async () => {
previewCardsCache.invalidate();
mockService("public.interactions", () => ({
startInteractions() {},
stopInteractions() {},
}));
onRpc("/ai/preview_cards", () => {
expect.step("fetch-empty");
return {
count: 0,
html: `<div class="o_ai_preview_cards"></div>`,
};
});
const fixture = getFixture();
fixture.innerHTML = `
<div class="o_ai_livechat_message_content">
<span class="o_ai_preview_data"><a href="/shop/product/desk">Desk</a></span>
</div>
`;
await mountWithCleanup(AIRecordsPreview, {
target: fixture.querySelector(".o_ai_livechat_message_content"),
props: {
message: {
id: 46,
ai_record_previews: {
preview_sets: [
{
preview_key: 0,
model: "product.template",
has_preview_cards: true,
records: [{ id: 10, url: "/shop/product/desk", name: "Desk" }],
header: "",
},
],
},
},
},
});
await waitFor(".o_ai_record_previews .o_ai_preview_link a[href='/shop/product/desk']");
expect(".o_ai_preview_cards_wrapper").toHaveCount(0);
// Falls back to links since cards fetch returned empty
expect(".o_ai_record_previews .o_ai_preview_link a[href='/shop/product/desk']").toHaveText(
"Desk"
);
expect(".o_ai_preview_data").not.toBeVisible();
expect.verifySteps(["fetch-empty"]);
});

View File

@@ -0,0 +1,37 @@
import { deliverAIResults, setupAIResults } from "@ai/../tests/tours/ai_tour_helpers";
import {
registerWebsitePreviewTour,
insertSnippet,
clickOnSnippet,
changeOptionInPopover,
clickOnSave,
} from "@website/js/tours/tour_utils";
registerWebsitePreviewTour(
"ai_livechat_snippet_tour",
{
edition: true,
},
() => [
...insertSnippet({
id: "s_ai_livechat",
name: "AI Live Chat",
groupName: "Contact & Forms",
}),
...clickOnSnippet({ id: "s_ai_livechat", name: "AI Live Chat" }),
...changeOptionInPopover("AI Live Chat", "AI Agent", "Test Agent"),
...clickOnSave(),
setupAIResults(":iframe .s_ai_livechat .ai_website_livechat_form textarea"),
{
content: "Enter a prompt",
trigger: ":iframe .s_ai_livechat .ai_website_livechat_form textarea",
run: "edit Hello && press Enter",
},
deliverAIResults(),
{
content: "Verify that the response is as expected",
trigger:
":iframe .o_ai_livechat_message_with_copy_button:contains('This is a test response from AI.')",
},
],
);