This commit is contained in:
2026-11-25 11:58:57 +08:00
parent 5fc4382687
commit 88b4fe3d59
3210 changed files with 11146 additions and 601197 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

@@ -0,0 +1,63 @@
import struct
import zlib
import os
# Minimal 256x256 RGBA PNG: a violet rounded square with a white "spark".
W = H = 256
BG = (124, 58, 237, 255) # violet-600
FG = (255, 255, 255, 255)
TRANSPARENT = (0, 0, 0, 0)
def inside_rounded(x, y, r=44):
if r <= x < W - r or r <= y < H - r:
return 0 <= x < W and 0 <= y < H
cx = r if x < r else W - 1 - r
cy = r if y < r else H - 1 - r
return (x - cx) ** 2 + (y - cy) ** 2 <= r * r
def spark(x, y):
"""A four-point star centred in the tile."""
cx, cy = W / 2, H / 2
dx, dy = abs(x - cx), abs(y - cy)
# diamond body
if dx + dy < 62:
return True
# thin cross arms
if dx < 9 and dy < 104:
return True
if dy < 9 and dx < 104:
return True
return False
rows = []
for y in range(H):
row = bytearray([0]) # PNG filter type 0
for x in range(W):
if not inside_rounded(x, y):
row.extend(TRANSPARENT)
elif spark(x, y):
row.extend(FG)
else:
row.extend(BG)
rows.append(bytes(row))
raw = b"".join(rows)
def chunk(tag, data):
return (struct.pack(">I", len(data)) + tag + data
+ struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF))
png = (b"\x89PNG\r\n\x1a\n"
+ chunk(b"IHDR", struct.pack(">IIBBBBB", W, H, 8, 6, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(raw, 9))
+ chunk(b"IEND", b""))
out = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icon.png")
with open(out, "wb") as fh:
fh.write(png)
print("written", out, len(png), "bytes")

View File

@@ -0,0 +1,71 @@
/** @odoo-module **/
import { _t } from "@web/core/l10n/translation";
/**
* Upload one file to an AI conversation.
*
* Uses a plain `fetch` with `FormData` because the payload is binary: the
* regular RPC helper serialises JSON and cannot carry a file. The route is an
* `http` one (not `jsonrpc`) and validates the CSRF token, hence the explicit
* field below.
*
* @param {number} channelId
* @param {File} file
* @returns {Promise<object>} `{id, name, mimetype, size, kind, readable}`
* @throws {Error} with a user-readable message on any failure
*/
export async function uploadDnAiAttachment(channelId, file) {
const formData = new FormData();
formData.append("csrf_token", odoo.csrf_token);
formData.append("channel_id", channelId);
formData.append("ufile", file, file.name);
const response = await fetch("/dn_ai/upload_attachment", {
method: "POST",
body: formData,
});
if (!response.ok) {
throw new Error(_t("The upload failed (HTTP %s).", response.status));
}
let data;
try {
data = await response.json();
} catch {
// A redirect to the login page yields HTML; surface that as an error
// instead of a confusing "Unexpected token <" in the console.
throw new Error(_t("The upload failed. Please reload the page and try again."));
}
if (data.error) {
throw new Error(data.error);
}
return data;
}
/**
* Human readable file size, mirroring the server side helper.
*/
export function dnAiFormatSize(size) {
const value = size || 0;
if (value < 1024) {
return `${value} B`;
}
if (value < 1024 * 1024) {
return `${(value / 1024).toFixed(1)} kB`;
}
return `${(value / (1024 * 1024)).toFixed(1)} MB`;
}
/**
* Icon name for a file, from a small set that exists in the Odoo 20 icon
* wishlist (`fa-*` renders nothing here).
*/
export function dnAiFileIcon(attachment) {
const mimetype = attachment.mimetype || "";
if (mimetype.startsWith("image/")) {
return "image";
}
if (mimetype === "application/pdf") {
return "description";
}
return "attach_file";
}

View File

@@ -0,0 +1,453 @@
/** @odoo-module **/
import {
Component,
markup,
onMounted,
onPatched,
onWillStart,
proxy,
signal,
t,
useProps,
} from "@odoo/owl";
import { registry } from "@web/core/registry";
import { useService } from "@web/core/utils/hooks";
import { _t } from "@web/core/l10n/translation";
import { runDnAiClientTools } from "./client_tools";
import {
dnAiFileIcon,
dnAiFormatSize,
uploadDnAiAttachment,
} from "./attachment_utils";
/**
* Standalone AI chat panel.
*
* Kept outside of the Discuss internals on purpose: the agent loop posts plain
* chatter messages, so any surface able to read a channel can render the
* conversation. This gives us a stable place to show tool progress,
* confirmation cards and question cards.
*/
export class DnAiChat extends Component {
static template = "dn_ai.Chat";
props = useProps({
action: t.object().optional(),
actionId: t.any().optional(),
className: t.string().optional(),
state: t.object().optional(),
// Chatter button can open the dialog on a specific conversation.
channelId: t.number().optional(),
// The floating panel renders its own title bar, so the panel inside it
// hides this one to avoid two stacked headers.
hideHeader: t.boolean().optional(),
});
// Literal text in an Owl template is invisible to the PO extractor, so
// every user-facing string goes through a getter backed by _t().
get labels() {
return {
agentFallback: _t("AI"),
emptyTitle: _t("Ask about your records, or tell me what to change."),
emptyHint: _t("The assistant reads and writes data with your own access rights."),
thinking: _t("Thinking…"),
send: _t("Send"),
attachFile: _t("Attach files"),
removeFile: _t("Remove"),
dropHint: _t("Drop the files here"),
steps: _t("Working steps"),
};
}
// Owl 3 dropped `useRef`: refs are signals created up-front and bound from
// the template with t-ref="this.scrollRef".
scrollRef = signal.ref();
fileInputRef = signal.ref();
setup() {
this.orm = useService("orm");
this.notification = useService("notification");
const params = this.props.action?.params || {};
// The dialog passes the channel through sub-env because Owl 3 slots
// have their own scope and cannot read the parent component's props.
const envChannel = this.env.dnAiChannelId || false;
this.state = proxy({
channelId: envChannel || this.props.channelId || params.channel_id || false,
agentName: "",
messages: [],
rows: [],
input: "",
busy: false,
sessionId: false,
pending: false,
attachments: [],
dragActive: false,
stepsOpen: false,
});
// A depth counter, not a boolean: `dragleave` fires every time the
// pointer crosses a child element, which would flicker the overlay.
this._dragDepth = 0;
// Scroll after Owl has actually written the transcript to the DOM.
//
// `onMounted` covers the first paint (the panel is re-created every
// time it is opened, so this is the common case); `onPatched` covers
// later refreshes. A bare `requestAnimationFrame` inside `refresh()`
// is not enough: it races the initial render and measures the empty
// list, which is exactly why the panel used to open at the very top.
onMounted(() => this._scrollToBottomNow());
onPatched(() => {
if (this._scrollPending) {
this._scrollPending = false;
this._scrollToBottomNow();
}
});
onWillStart(async () => {
await this.loadChannel();
});
}
async loadChannel() {
if (!this.state.channelId) {
const data = await this.orm.call("ai.agent", "dn_ai_get_default_channel", []);
if (!data) {
return;
}
this.state.channelId = data.channel_id;
this.state.agentName = data.agent_name;
this.state.sessionId = data.session_id;
}
await this.refresh();
}
async refresh() {
if (!this.state.channelId) {
return;
}
const data = await this.orm.call("discuss.channel", "dn_ai_fetch_messages", [
this.state.channelId,
]);
// Chatter bodies are sanitised server-side; `markup` keeps the HTML
// instead of escaping the tags into visible text.
// Only label the first message of a consecutive run by the same author,
// like every other chat UI does.
let previousAuthor = null;
this.state.messages = data.messages.map((message) => {
const showAuthor = message.author_name !== previousAuthor;
previousAuthor = message.author_name;
return {
...message,
body: markup(message.body || ""),
attachments: message.attachments || [],
is_step: Boolean(message.is_step),
showAuthor,
};
});
this.state.rows = this._buildRows(this.state.messages);
this.state.agentName = data.agent_name || this.state.agentName;
this.state.sessionId = data.session_id;
this.state.pending = data.pending;
this.scrollToBottom();
}
/**
* Fold runs of tool steps into groups.
*
* An agent answering a request like "create this sales order" posts ten
* one-line progress messages ("搜索 Contact", "已创建 Product", …) and one
* answer. Rendered as bubbles they bury the answer. A run of steps becomes
* a single collapsible line: collapsed by default when it is in the past,
* so the transcript reads as question → answer with the machinery tucked
* away, but still one click from the full trail.
*/
_buildRows(messages) {
const rows = [];
let group = null;
for (const message of messages) {
if (message.is_step) {
if (!group) {
group = { isGroup: true, id: `steps-${message.id}`, steps: [] };
rows.push(group);
}
group.steps.push(message);
continue;
}
group = null;
rows.push(message);
}
return rows;
}
get stepRows() {
return this.state.rows.filter((row) => row.isGroup);
}
/**
* A group is expanded when the agent is still working (its steps are the
* only feedback) or when the user opened it by hand.
*/
isGroupOpen(group) {
if (this.state.stepsOpen) {
return true;
}
// The last row being a group means the turn is still in progress.
return this.state.busy && this.state.rows[this.state.rows.length - 1] === group;
}
toggleSteps() {
this.state.stepsOpen = !this.state.stepsOpen;
}
/**
* Request a scroll to the latest message.
*
* The actual scroll happens in `onPatched`, once Owl has written the new
* messages into the DOM — measuring any earlier gives the *previous*
* transcript height. The rAF below is only a safety net for refreshes that
* change nothing (no patch is scheduled then).
*/
scrollToBottom() {
this._scrollPending = true;
requestAnimationFrame(() => {
if (this._scrollPending) {
this._scrollPending = false;
this._scrollToBottomNow();
}
});
}
_scrollToBottomNow() {
const el = this.scrollRef();
if (!el) {
return;
}
el.scrollTop = el.scrollHeight;
// Messages arrive as HTML: images and web fonts can still change the
// height right after the patch, which would leave us a few lines short
// of the bottom. Re-apply on the next two frames; the operation is
// idempotent and cheap.
requestAnimationFrame(() => {
el.scrollTop = el.scrollHeight;
requestAnimationFrame(() => {
el.scrollTop = el.scrollHeight;
});
});
}
get placeholder() {
return _t("Ask anything about your data…");
}
get sendDisabled() {
const hasContent = (this.state.input || "").trim() ||
this.state.attachments.some((file) => !file.uploading);
return Boolean(this.state.busy) || !hasContent;
}
fileIcon(file) {
return dnAiFileIcon(file);
}
fileSize(file) {
return dnAiFormatSize(file.size);
}
async onKeydown(ev) {
if (ev.key === "Enter" && !ev.shiftKey) {
ev.preventDefault();
await this.send();
}
}
// ------------------------------------------------------------------
// attachments
// ------------------------------------------------------------------
openFilePicker() {
const input = this.fileInputRef();
if (input) {
input.click();
}
}
async onFilePicked(ev) {
const files = Array.from(ev.target.files || []);
// Reset immediately: picking the same file twice must fire `change`
// again, which it does not while the value is kept.
ev.target.value = "";
await this.uploadFiles(files);
}
onPaste(ev) {
// Screenshots are pasted, not selected. Handling `paste` here is the
// only way to attach one without a detour through the file system.
const items = Array.from(ev.clipboardData?.items || []);
const files = items
.filter((item) => item.kind === "file")
.map((item) => item.getAsFile())
.filter(Boolean);
if (files.length) {
ev.preventDefault();
this.uploadFiles(files);
}
}
onDragOver(ev) {
if (!ev.dataTransfer?.types?.includes("Files")) {
return;
}
this._dragDepth += 1;
this.state.dragActive = true;
}
onDragLeave() {
this._dragDepth = Math.max(0, this._dragDepth - 1);
if (!this._dragDepth) {
this.state.dragActive = false;
}
}
async onDrop(ev) {
this._dragDepth = 0;
this.state.dragActive = false;
if (this.state.busy) {
return;
}
const files = Array.from(ev.dataTransfer?.files || []);
if (files.length) {
await this.uploadFiles(files);
}
}
/**
* Upload every file, showing a chip per file straight away.
*
* The chip appears *before* the request completes so a slow upload still
* gives feedback; it is marked `uploading` until the server answers, and is
* dropped again if that answer is an error.
*/
async uploadFiles(files) {
if (!files.length || !this.state.channelId) {
return;
}
const pending = files.map((file) => ({
id: `tmp-${Date.now()}-${file.name}-${Math.random().toString(36).slice(2, 8)}`,
name: file.name,
size: file.size,
mimetype: file.type || "",
uploading: true,
}));
this.state.attachments.push(...pending);
await Promise.all(pending.map(async (placeholder, index) => {
try {
const attachment = await uploadDnAiAttachment(this.state.channelId, files[index]);
const target = this.state.attachments.find((item) => item.id === placeholder.id);
if (!target) {
return; // removed by the user while uploading
}
Object.assign(target, {
id: attachment.id,
name: attachment.name,
size: attachment.size,
mimetype: attachment.mimetype,
uploading: false,
});
} catch (error) {
this.removeAttachment(placeholder.id);
this.notification.add(error.message || _t("The upload failed."), {
type: "danger",
});
}
}));
}
removeAttachment(id) {
this.state.attachments = this.state.attachments.filter((file) => file.id !== id);
}
async send() {
const body = (this.state.input || "").trim();
const uploaded = this.state.attachments.filter((file) => !file.uploading);
if ((!body && !uploaded.length) || this.state.busy) {
return;
}
if (this.state.attachments.some((file) => file.uploading)) {
this.notification.add(_t("Please wait for the uploads to finish."), {
type: "warning",
});
return;
}
this.state.busy = true;
this.state.input = "";
// Clear the chips optimistically: the message is about to be posted and
// the files become part of the transcript, so keeping them in the input
// would let the user send them twice.
this.state.attachments = [];
try {
const result = await this.orm.call("ai.session", "dn_ai_send_message", [
this.state.channelId,
body,
], {
// keyword argument of the model method: the files the model has
// to read for this turn.
attachment_ids: uploaded.map((file) => file.id),
});
this.state.sessionId = result.session_id;
this.state.pending = result.pending;
await this.refresh();
await this._runClientTools(result.client_tools);
} catch (error) {
// Put the draft back so a failed turn does not silently eat the
// message (or the attached files) the user just composed.
this.state.input = body;
this.state.attachments = uploaded;
this.notification.add(error.message || _t("The AI request failed."), {
type: "danger",
});
} finally {
this.state.busy = false;
}
}
async onChoice(value) {
if (this.state.busy || !this.state.sessionId) {
return;
}
this.state.busy = true;
try {
const kind = this.state.pending?.type === "question" ? "question" : "confirmation";
const result = await this.orm.call("ai.session", "dn_ai_resume", [
this.state.sessionId,
{ kind, value },
]);
this.state.pending = result.pending;
await this.refresh();
await this._runClientTools(result.client_tools);
} catch (error) {
this.notification.add(error.message || _t("The AI request failed."), {
type: "danger",
});
} finally {
this.state.busy = false;
}
}
/**
* Execute the browser actions the server queued for this turn.
*
* The transcript is refreshed *before* this runs on purpose: opening a
* view unmounts the panel, and any state update after that point is lost.
*/
async _runClientTools(clientTools) {
if (!clientTools || !clientTools.length) {
return;
}
await runDnAiClientTools(this.env, clientTools);
}
}
registry.category("actions").add("dn_ai.chat", DnAiChat);

View File

@@ -0,0 +1,352 @@
.o_dn_ai_chat {
min-height: 0;
// Positioning context for the drop overlay.
position: relative;
.o_dn_ai_chat_messages {
background-color: var(--body-bg, #fff);
// A flex child does not shrink below its content by default, so without
// `min-height: 0` the message list grows and the scroll container is
// the panel — `scrollTop` on this element then does nothing.
min-height: 0;
overflow-y: auto;
}
.o_dn_ai_bubble {
max-width: 80%;
white-space: normal;
overflow-wrap: anywhere;
.o_dn_ai_body {
:last-child {
margin-bottom: 0;
}
}
// A table or a code block needs more room than a sentence, and the
// bubble above is capped at 80% to keep chat bubbles readable. Widening
// only the bubbles that hold one keeps prose narrow without squeezing
// the content that actually needs the width.
&:has(.o_dn_ai_table_wrap),
&:has(.o_dn_ai_code) {
max-width: 100%;
width: 100%;
}
}
// ---------------------------------------------------------------
// rendered markdown
// ---------------------------------------------------------------
.o_dn_ai_body {
line-height: 1.55;
// -- tables -------------------------------------------------
.o_dn_ai_table_wrap {
// Wide tables scroll sideways instead of forcing the panel to
// grow: the chat column is narrow by design.
overflow-x: auto;
margin: 0.5rem 0;
border: 1px solid var(--border-color, #dee2e6);
border-radius: 0.375rem;
}
.o_dn_ai_table {
width: 100%;
margin: 0;
border-collapse: collapse;
font-size: 0.875rem;
// Numbers line up under each other, which is the whole point of
// showing an order line table.
font-variant-numeric: tabular-nums;
th,
td {
padding: 0.375rem 0.625rem;
border-bottom: 1px solid var(--border-color, #dee2e6);
text-align: left;
vertical-align: top;
white-space: nowrap;
}
thead th {
background-color: var(--o-gray-200, #eef1f3);
font-weight: 600;
// The header stays put while a long table scrolls under it.
position: sticky;
top: 0;
z-index: 1;
}
tbody tr:last-child td {
border-bottom: 0;
}
tbody tr:hover {
background-color: rgba(0, 0, 0, 0.03);
}
}
// -- headings ------------------------------------------------
.o_dn_ai_h {
font-size: 0.9375rem;
font-weight: 600;
margin: 0.75rem 0 0.375rem;
&:first-child {
margin-top: 0;
}
}
// -- lists ---------------------------------------------------
ul,
ol {
margin: 0.375rem 0;
padding-left: 1.25rem;
}
li {
margin-bottom: 0.125rem;
}
// -- quotes, rules -------------------------------------------
blockquote {
margin: 0.5rem 0;
padding: 0.25rem 0.75rem;
border-left: 3px solid var(--o-brand-primary, #714b67);
background-color: rgba(0, 0, 0, 0.03);
color: var(--body-color, #212529);
opacity: 0.9;
}
hr {
margin: 0.75rem 0;
border-color: var(--border-color, #dee2e6);
opacity: 1;
}
// -- code ----------------------------------------------------
code.ai-code-response {
padding: 0.1em 0.35em;
font-size: 0.85em;
background-color: rgba(0, 0, 0, 0.07);
border-radius: 0.25rem;
}
.o_dn_ai_code pre,
pre.ai-pre-response {
margin: 0.5rem 0;
padding: 0.625rem 0.75rem;
background-color: rgba(0, 0, 0, 0.05);
border-radius: 0.375rem;
font-size: 0.8125rem;
overflow-x: auto;
white-space: pre;
}
a {
text-decoration: underline;
}
}
// The user's own bubble is dark, so the same rendered markdown has to
// invert its surfaces instead of stacking grey on grey.
.o_dn_ai_bubble.bg-primary {
.o_dn_ai_table {
th,
td {
border-color: rgba(255, 255, 255, 0.25);
}
thead th {
background-color: rgba(255, 255, 255, 0.15);
}
tbody tr:hover {
background-color: rgba(255, 255, 255, 0.08);
}
}
.o_dn_ai_table_wrap {
border-color: rgba(255, 255, 255, 0.25);
}
blockquote {
border-left-color: rgba(255, 255, 255, 0.6);
background-color: rgba(255, 255, 255, 0.1);
color: inherit;
}
code.ai-code-response,
.o_dn_ai_code pre,
pre.ai-pre-response {
background-color: rgba(255, 255, 255, 0.15);
color: inherit;
}
hr {
border-color: rgba(255, 255, 255, 0.4);
}
}
// ---------------------------------------------------------------
// tool steps
// ---------------------------------------------------------------
.o_dn_ai_steps {
margin: 0 0 0.75rem;
.o_dn_ai_steps_head {
display: inline-flex;
align-items: center;
gap: 0.375rem;
padding: 0.125rem 0.5rem;
border: 1px solid var(--border-color, #dee2e6);
border-radius: 1rem;
background-color: transparent;
color: var(--text-muted, #6c757d);
font-size: 0.8125rem;
line-height: 1.4;
&:hover {
background-color: var(--o-gray-200, #eef1f3);
color: var(--body-color, #212529);
}
}
.o_dn_ai_steps_icon {
font-size: 1rem;
}
.o_dn_ai_steps_count {
padding: 0 0.375rem;
border-radius: 0.75rem;
background-color: var(--o-gray-300, #dee2e6);
font-size: 0.75rem;
}
// The trail runs down a vertical line, like a build log: each entry is
// a completed step, not a message from the assistant.
.o_dn_ai_steps_body {
margin-top: 0.5rem;
padding-left: 0.75rem;
border-left: 2px solid var(--border-color, #dee2e6);
.o_dn_ai_step {
margin-bottom: 0.25rem;
font-size: 0.8125rem;
color: var(--text-muted, #6c757d);
// The server emits each step as a div with an icon; flatten it
// into a single muted line so ten of them stay scannable.
.o_ai_tool_summary {
display: flex;
align-items: center;
gap: 0.375rem;
}
&:last-child {
margin-bottom: 0;
}
}
}
}
.o_dn_ai_textarea {
resize: none;
}
// Material Symbols replaced FontAwesome in Odoo 20; there is no built-in
// `fa-spin` equivalent, so the "thinking" icon needs its own animation.
.o_dn_ai_spin {
display: inline-block;
animation: o_dn_ai_spin 1s linear infinite;
}
// ---------------------------------------------------------------
// attachments
// ---------------------------------------------------------------
.o_dn_ai_attach {
// Sits inside the input group; keeping the border thin avoids the
// "double button" look next to the textarea.
border-color: var(--border-color, #dee2e6);
}
.o_dn_ai_file_input {
display: none;
}
.o_dn_ai_message_files {
.o_dn_ai_file_card {
background-color: rgba(0, 0, 0, 0.06);
border: 1px solid rgba(0, 0, 0, 0.08);
max-width: 320px;
&:hover {
background-color: rgba(0, 0, 0, 0.1);
}
}
.o_dn_ai_file_name {
// The name is the only part allowed to shrink; icon and size must
// stay readable on long file names.
min-width: 0;
}
}
.o_dn_ai_pending_files {
.o_dn_ai_chip {
background-color: var(--o-gray-200, #eef1f3);
border: 1px solid var(--border-color, #dee2e6);
max-width: 260px;
font-size: 0.875rem;
}
.o_dn_ai_chip_loading {
opacity: 0.7;
}
.o_dn_ai_chip_name {
min-width: 0;
}
.o_dn_ai_chip_remove {
color: inherit;
text-decoration: none;
line-height: 1;
&:hover {
color: var(--o-danger, #dc3545);
}
}
}
&.o_dn_ai_dragging .o_dn_ai_chat_input {
// A dashed outline on the input area alone would be too subtle to
// notice while dragging; the overlay below makes it unmistakable.
border-color: var(--o-brand-primary, #714b67);
}
.o_dn_ai_drop_hint {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background-color: rgba(113, 75, 103, 0.08);
border: 2px dashed var(--o-brand-primary, #714b67);
border-radius: 0.5rem;
color: var(--o-brand-primary, #714b67);
font-weight: 600;
// The overlay must not swallow the drop event itself, or the browser
// opens the file in a new tab instead of uploading it.
pointer-events: none;
}
}
@keyframes o_dn_ai_spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

View File

@@ -0,0 +1,145 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="dn_ai.Chat">
<div t-attf-class="o_dn_ai_chat d-flex flex-column h-100 {{ this.state.dragActive ? 'o_dn_ai_dragging' : '' }}"
t-on-dragover.prevent="this.onDragOver"
t-on-dragleave.prevent="this.onDragLeave"
t-on-drop.prevent="this.onDrop">
<!-- Odoo 20 dropped FontAwesome: icons are Material Symbols
(`class="oi"` + `data-icon`). `fa fa-*` renders nothing. -->
<div t-if="!this.props.hideHeader"
class="o_dn_ai_chat_header d-flex align-items-center px-3 py-2 border-bottom">
<span class="oi oi-filled me-2 text-primary" data-icon="wand_stars"/>
<span class="fw-bold" t-out="this.state.agentName || this.labels.agentFallback"/>
</div>
<div class="o_dn_ai_chat_messages flex-grow-1 overflow-auto px-3 py-3" t-ref="this.scrollRef">
<div t-if="!this.state.messages.length" class="text-center text-muted py-5">
<span class="oi d-block mb-3 opacity-50" style="font-size: 3rem" data-icon="forum"/>
<p class="mb-1" t-out="this.labels.emptyTitle"/>
<p class="small mb-0" t-out="this.labels.emptyHint"/>
</div>
<t t-foreach="this.state.rows" t-as="row" t-key="row.id">
<!-- A run of tool progress lines, folded into one
collapsible strip. Expanded while the agent is still
working, collapsed once the answer has landed. -->
<div t-if="row.isGroup" class="o_dn_ai_steps">
<button type="button"
class="o_dn_ai_steps_head"
t-on-click="this.toggleSteps">
<span class="oi o_dn_ai_steps_icon"
t-attf-data-icon="{{ this.isGroupOpen(row) ? 'expand_less' : 'expand_more' }}"/>
<span t-out="this.labels.steps"/>
<span class="o_dn_ai_steps_count" t-out="row.steps.length"/>
</button>
<div t-if="this.isGroupOpen(row)" class="o_dn_ai_steps_body">
<t t-foreach="row.steps" t-as="step" t-key="step.id">
<div class="o_dn_ai_step" t-out="step.body"/>
</t>
</div>
</div>
<div t-else=""
t-attf-class="o_dn_ai_message mb-3 d-flex {{ row.is_agent ? 'justify-content-start' : 'justify-content-end' }}">
<div t-attf-class="o_dn_ai_bubble p-2 px-3 rounded-3 {{ row.is_agent ? 'bg-body-tertiary' : 'bg-primary text-white' }}">
<div class="o_dn_ai_author small opacity-75 mb-1" t-if="row.showAuthor" t-out="row.author_name"/>
<div class="o_dn_ai_body" t-if="row.body" t-out="row.body"/>
<!-- Attachments travel with the transcript, not
inside the body: extracted text can be tens of
thousands of characters and has no business in
a chat bubble. -->
<div t-if="row.attachments and row.attachments.length"
t-attf-class="o_dn_ai_message_files d-flex flex-column gap-1 {{ row.body ? 'mt-2' : '' }}">
<t t-foreach="row.attachments" t-as="file" t-key="file.id">
<a class="o_dn_ai_file_card d-flex align-items-center text-decoration-none rounded-2 px-2 py-1"
t-attf-class="{{ row.is_agent ? 'text-reset' : 'text-white' }}"
t-att-href="file.url"
t-att-title="file.name"
target="_blank" rel="noopener">
<span class="oi oi-fw me-2" t-att-data-icon="this.fileIcon(file)"/>
<span class="o_dn_ai_file_name text-truncate" t-out="file.name"/>
<span class="small opacity-75 ms-2 flex-shrink-0" t-out="this.fileSize(file)"/>
</a>
</t>
</div>
</div>
</div>
</t>
<div t-if="this.state.busy" class="text-muted small">
<span class="oi me-1 o_dn_ai_spin" data-icon="progress_activity"/><t t-out="this.labels.thinking"/>
</div>
</div>
<div class="o_dn_ai_chat_pending border-top px-3 py-2" t-if="this.state.pending">
<div class="small text-muted mb-1" t-out="this.state.pending.body"/>
<div class="d-flex flex-wrap gap-2">
<t t-foreach="this.state.pending.choices" t-as="choice" t-key="choice.value">
<button type="button"
t-attf-class="btn btn-sm o_dn_ai_choice {{ choice.value === 'decline' ? 'btn-outline-secondary' : 'btn-primary' }}"
t-att-disabled="this.state.busy"
t-on-click="() => this.onChoice(choice.value)"
t-out="choice.label"/>
</t>
</div>
</div>
<div class="o_dn_ai_chat_input border-top p-2">
<!-- Files picked but not sent yet. Shown above the textarea so
the user sees exactly what will travel with the next
message, and can drop one without clearing everything. -->
<div t-if="this.state.attachments.length"
class="o_dn_ai_pending_files d-flex flex-wrap gap-2 mb-2">
<t t-foreach="this.state.attachments" t-as="file" t-key="file.id">
<div t-attf-class="o_dn_ai_chip d-flex align-items-center rounded-pill px-2 py-1 {{ file.uploading ? 'o_dn_ai_chip_loading' : '' }}">
<span class="oi oi-fw me-1" t-att-data-icon="this.fileIcon(file)"/>
<span class="o_dn_ai_chip_name text-truncate" t-out="file.name"/>
<span t-if="!file.uploading" class="small opacity-75 ms-2" t-out="this.fileSize(file)"/>
<span t-if="file.uploading" class="oi oi-fw o_dn_ai_spin ms-2" data-icon="progress_activity"/>
<button type="button"
class="btn btn-link btn-sm p-0 ms-2 o_dn_ai_chip_remove"
t-att-title="this.labels.removeFile"
t-on-click="() => this.removeAttachment(file.id)">
<span class="oi" data-icon="close"/>
</button>
</div>
</t>
</div>
<div class="input-group">
<button type="button"
class="btn btn-outline-secondary o_dn_ai_attach"
t-att-disabled="this.state.busy || !this.state.channelId"
t-att-title="this.labels.attachFile"
t-on-click="this.openFilePicker">
<span class="oi" data-icon="attach_file"/>
</button>
<textarea class="form-control o_dn_ai_textarea"
rows="2"
t-att-placeholder="this.placeholder"
t-model.proxy="this.state.input"
t-on-keydown="this.onKeydown"
t-on-paste="this.onPaste"/>
<button type="button"
class="btn btn-primary"
t-att-disabled="this.sendDisabled"
t-att-title="this.labels.send"
t-on-click="this.send">
<span class="oi" data-icon="send"/>
</button>
</div>
<!-- The native input lives outside the flex row: it must never
take space, and a hidden `display:none` input can still be
clicked programmatically in every browser we target. -->
<input type="file" multiple="multiple"
class="o_dn_ai_file_input"
t-ref="this.fileInputRef"
t-on-change="this.onFilePicked"/>
<div t-if="this.state.dragActive" class="o_dn_ai_drop_hint">
<span class="oi me-2" data-icon="attach_file"/><t t-out="this.labels.dropHint"/>
</div>
</div>
</div>
</t>
</templates>

View File

@@ -0,0 +1,35 @@
/** @odoo-module **/
import { Component, t, useProps } from "@odoo/owl";
import { useSubEnv } from "@web/owl2/utils";
import { Dialog } from "@web/core/dialog/dialog";
import { _t } from "@web/core/l10n/translation";
import { DnAiChat } from "./chat";
/**
* The chat panel wrapped in a modal dialog.
*
* `dialog.add(DnAiChatDialog, {...})` gives us a consistent Odoo dialog
* (header, close button, focus handling) while the conversation itself stays
* in the reusable DnAiChat component.
*/
export class DnAiChatDialog extends Component {
static template = "dn_ai.ChatDialog";
static components = { Dialog, DnAiChat };
props = useProps({
channelId: t.number().optional(),
close: t.function().optional(),
});
setup() {
// Owl 3 slots have their own scope, so the chat component cannot read
// this.props directly. Publish the channel through the sub environment,
// which is inherited by every child of the dialog.
useSubEnv({ dnAiChannelId: this.props.channelId || false });
}
get title() {
return _t("Ask AI");
}
}

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="dn_ai.ChatDialog">
<Dialog size="'md'" title="this.title"
contentClass="'o_dn_ai_chat_dialog'" bodyClass="'p-0'"
withBodyPadding="false">
<t t-set-slot="default">
<DnAiChat/>
</t>
</Dialog>
</t>
</templates>

View File

@@ -0,0 +1,21 @@
/** @odoo-module **/
import { fields, Record } from "@mail/model/export";
/**
* Minimal mail-store model for `ai.agent`.
*
* `discuss.channel.ai_agent_id` is a relational field inside the mail store,
* and the store refuses relations pointing at unknown models ("No target model
* ai.agent exists"). Defining the Record class registers it in the
* `discuss.model` registry, which is what the store iterates over.
*/
export class AiAgent extends Record {
static _name = "ai.agent";
/** @type {string} */
name;
/** @type {string} */
subtitle;
}
AiAgent.register();

View File

@@ -0,0 +1,75 @@
/** @odoo-module **/
import { _t } from "@web/core/l10n/translation";
import { registry } from "@web/core/registry";
/**
* Open an AI conversation in Odoo's own chat window.
*
* Every surface that used to build a bespoke panel (the floating button, the
* "Ask AI" action in a chatter, the AI menu entry) funnels through this
* service, so they all end up in the same native `mail.ChatWindow` the
* Enterprise assistant uses.
*
* Why the native window instead of a hand-rolled panel:
* - messages are rendered by `mail.Message`, so markdown, tables, images,
* attachment cards, replies and reactions all behave exactly as they do in
* the rest of Odoo, and improvements to the mail client apply for free;
* - the composer is `mail.Composer`, which already handles HTML, mentions,
* attachments, paste and drag & drop;
* - the window docks, folds, remembers its position and survives navigation
* between views, which a floating panel anchored to the DOM cannot do.
*/
export const dnAiChatLauncher = {
dependencies: ["mail.store", "orm", "notification"],
start(env, services) {
const { orm, notification } = services;
const store = services["mail.store"];
/**
* Open `channelId` in a native chat window, creating it when absent.
*
* `getOrFetch` (not `openChatWindow` on a bare id) is what makes this
* work for a conversation the store has never seen: it fetches the
* channel, its members and its last messages first.
*/
async function openChannel(channelId) {
const channel = await store["discuss.channel"].getOrFetch(channelId);
if (!channel) {
throw new Error(_t("This AI conversation does not exist."));
}
await channel.openChatWindow({ focus: true });
return channel;
}
return {
async openDefault() {
const data = await orm.call("ai.agent", "dn_ai_get_default_channel", []);
if (!data) {
return;
}
return openChannel(data.channel_id);
},
/** Open the conversation bound to one record (chatter "Ask AI"). */
async openForRecord(resModel, resId) {
const data = await orm.call("ai.session", "dn_ai_get_record_channel", [
resModel,
resId,
]);
return openChannel(data.channel_id);
},
openChannel,
/** Report a failure without leaving the user with a dead button. */
reportError(error) {
notification.add(error?.message || _t("The AI chat could not be opened."), {
type: "danger",
});
},
};
},
};
registry.category("services").add("dn_ai.chat_launcher", dnAiChatLauncher);

View File

@@ -0,0 +1,68 @@
/** @odoo-module **/
import { Component, proxy } from "@odoo/owl";
import { registry } from "@web/core/registry";
import { _t } from "@web/core/l10n/translation";
import { useService } from "@web/core/utils/hooks";
import { user } from "@web/core/user";
/**
* Bottom-right entry point for the AI assistant.
*
* The button no longer owns a chat UI: it opens the conversation in the native
* `mail.ChatWindow` (see `ai_chat_launcher.js`), which is what the Enterprise
* assistant does as well. Everything the previous floating panel had to
* reimplement — message rendering, markdown tables, attachment previews, the
* composer, folding, position memory — now comes from `mail` itself.
*
* It stays a fixed action button rather than a systray item: a systray entry
* lives inside the navbar and collapses into the burger menu on small screens,
* where the icon then "disappears".
*/
export class DnAiAssistant extends Component {
static template = "dn_ai.Assistant";
setup() {
this.store = useService("mail.store");
this.launcher = useService("dn_ai.chat_launcher");
this.state = proxy({ busy: false });
}
get title() {
return _t("Ask AI");
}
get isAvailable() {
return user.isRegularUser;
}
/**
* Step aside while the chat hub owns this corner.
*
* Native chat windows and their folded bubbles are anchored bottom-right,
* exactly where this button lives. Hiding the button while one is on
* screen avoids covering the composer; it comes back as soon as the user
* closes the conversation.
*/
get isHidden() {
const hub = this.store.chatHub;
return hub.opened.length + hub.folded.length > 0;
}
async onClick() {
if (this.state.busy) {
return;
}
this.state.busy = true;
try {
await this.launcher.openDefault();
} catch (error) {
this.launcher.reportError(error);
} finally {
this.state.busy = false;
}
}
}
registry.category("main_components").add("dn_ai.assistant", {
Component: DnAiAssistant,
});

View File

@@ -0,0 +1,78 @@
// Bottom-right entry point of the AI assistant.
//
// The widget lives in `main_components`, i.e. directly under
// `.o-main-components-container`, which is a full-size overlay with
// `pointer-events: none` in the backend. Children must opt back in, otherwise
// the button is visible but dead.
//
// The panel itself is no longer rendered here: the conversation opens in the
// native `mail.ChatWindow`, which is positioned by `mail.ChatHub` in this same
// corner. Only the launcher button remains.
.o_dn_ai_assistant {
position: fixed;
// Above the native chat hub, whose windows dock at the bottom-right with a
// margin of their own (`ChatHub.BUBBLE_OUTER`); 20px keeps the button clear
// of a folded bubble without drifting away from the corner.
right: 20px;
bottom: 20px;
z-index: 1040; // above the list/form controls, below dialogs (1055)
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 12px;
pointer-events: none; // let clicks through the empty area
> * {
pointer-events: auto;
}
}
.o_dn_ai_fab {
width: 52px;
height: 52px;
padding: 0;
border: 0;
border-radius: 50%;
display: inline-flex;
align-items: center;
justify-content: center;
// `--primary` is the theme colour Bootstrap actually exposes at runtime;
// the older `--o-brand-*` names no longer exist in Odoo 20, so using them
// froze the button at the fallback purple and it ignored theme changes.
background: var(--primary, #714b67);
color: #fff;
font-size: 1.5rem;
line-height: 1;
cursor: pointer;
transition: transform 0.15s ease, filter 0.15s ease;
&:hover,
&:focus-visible {
filter: brightness(0.9);
transform: translateY(-2px);
outline: none;
}
// The launch is one RPC away: the button must not look clickable while the
// channel is being fetched, or a double click opens two windows.
&:disabled,
&.o_dn_ai_fab_busy {
opacity: 0.6;
cursor: progress;
transform: none;
}
.oi {
font-size: 1.5rem;
}
}
// Narrow screens: keep the button clear of the edge on phones, where the thumb
// needs room. The chat window itself goes full-screen on its own (`ui.isSmall`).
@media (max-width: 575.98px) {
.o_dn_ai_assistant {
right: 12px;
bottom: 12px;
}
}

View File

@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="dn_ai.Assistant">
<!--
Odoo 20 no longer ships FontAwesome: `fa fa-*` classes render
nothing at all. Icons must be Material Symbols via `class="oi"`
plus `data-icon="name"`.
A single button: the conversation itself opens in the native chat
window, which docks in this very corner on its own. The button
therefore steps aside while a chat window (or a folded bubble) is
present, instead of covering its composer.
-->
<div t-if="this.isAvailable and !this.isHidden" class="o_dn_ai_assistant">
<button type="button"
t-attf-class="o_dn_ai_fab shadow {{ this.state.busy ? 'o_dn_ai_fab_busy' : '' }}"
t-att-title="this.title"
t-att-aria-label="this.title"
t-att-disabled="this.state.busy"
t-on-click="this.onClick">
<span class="oi oi-filled" data-icon="wand_stars"/>
</button>
</div>
</t>
</templates>

View File

@@ -0,0 +1,49 @@
/** @odoo-module **/
import { Component, onWillStart, proxy } from "@odoo/owl";
import { registry } from "@web/core/registry";
import { _t } from "@web/core/l10n/translation";
import { useService } from "@web/core/utils/hooks";
/**
* Client action behind the "AI" menu.
*
* The conversation is shown by the native chat window, which floats above the
* current screen. This action is therefore only a backdrop: it opens the window
* on arrival, and offers a button to reopen it if the user closed it, instead of
* leaving the content area empty.
*/
export class DnAiChatAction extends Component {
static template = "dn_ai.ChatAction";
setup() {
this.launcher = useService("dn_ai.chat_launcher");
this.state = proxy({ busy: false });
onWillStart(() => this.open());
}
get labels() {
return {
title: _t("AI Assistant"),
subtitle: _t(
"The conversation is shown in the chat window, so you can keep working on the current screen."
),
open: _t("Open the assistant"),
};
}
async open() {
if (this.state.busy) {
return;
}
this.state.busy = true;
try {
await this.launcher.openDefault();
} catch (error) {
this.launcher.reportError(error);
} finally {
this.state.busy = false;
}
}
}
registry.category("actions").add("dn_ai.chat", DnAiChatAction);

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<!-- Backdrop of the AI menu entry. The conversation itself is shown by the
native chat window, so this page only explains that and reopens the
window if the user closed it. -->
<t t-name="dn_ai.ChatAction">
<div class="o_dn_ai_chat_action d-flex flex-column align-items-center justify-content-center h-100 text-center px-4">
<span class="oi oi-2x mb-3 opacity-50 text-primary" data-icon="wand_stars"/>
<h4 class="mb-2" t-out="this.labels.title"/>
<p class="text-muted mb-3" style="max-width: 32rem" t-out="this.labels.subtitle"/>
<button type="button" class="btn btn-primary"
t-att-disabled="this.state.busy"
t-on-click="this.open"
t-out="this.labels.open"/>
</div>
</t>
</templates>

View File

@@ -0,0 +1,31 @@
/** @odoo-module **/
import { _t } from "@web/core/l10n/translation";
import { registerComposerAction } from "@mail/core/common/composer_actions";
/**
* "Ask AI" action inside a record's chatter.
*
* Opens the record-scoped conversation in the native chat window, exactly like
* the Enterprise assistant: the message the user is writing stays in the
* chatter, and the AI answers next to it instead of in a modal that hides the
* form being discussed.
*/
registerComposerAction("dn_ai_ask", {
icon: "star",
name: () => _t("Ask AI"),
sequence: 15,
sequenceQuick: 15,
condition: ({ composer, owner }) =>
Boolean(owner.env.inChatter && composer.targetThread?.model &&
composer.targetThread?.id),
onSelected: async ({ composer, owner }, ev) => {
ev?.stopPropagation?.();
const thread = composer.targetThread;
const launcher = owner.env.services["dn_ai.chat_launcher"];
try {
await launcher.openForRecord(thread.model, thread.id);
} catch (error) {
launcher.reportError(error);
}
},
});

View File

@@ -0,0 +1,94 @@
/** @odoo-module **/
import { registry } from "@web/core/registry";
/**
* Browser-side tools that an AI session can trigger.
*
* A tool runs on the server (it touches the ORM), but opening a view or
* refining a search can only happen in the browser. The server therefore
* returns a `client_tool` payload, and this module is what actually executes
* it — without it the transcript claims "opened the list view" while the
* screen never changes.
*
* Tools receive `(env, params)` and may return a value; a return value is sent
* back to the server as the tool result for two-way tools.
*/
export const dnAiClientTools = registry.category("dn_ai.client_tools");
/**
* Open a window action and keep the menu in sync.
*
* `params.action` must be a **full action dictionary** (server side uses
* `action._get_action_dict()`); passing a bare id renders nothing.
*
* The action may carry `res_id`, which is what makes a form view open the
* record the assistant just created. Without it the browser would land on the
* list and the user would have to find the new row themselves.
*/
dnAiClientTools.add("show_view", async (env, params) => {
const { action, options = {}, menuId = null } = params;
if (!action) {
throw new Error("show_view requires a complete action description");
}
const actionOptions = { ...options };
if (menuId) {
// Dropping the breadcrumb keeps the back button from showing a trail of
// AI-opened views, and `onActionReady` highlights the right menu entry.
actionOptions.clearBreadcrumbs = true;
actionOptions.onActionReady = () => env.services.menu?.setCurrentMenu(menuId);
}
await env.services.action.doAction(action, actionOptions);
return "Success";
});
/**
* Refine the search view of the current action (filters, group bys, order…).
*
* The search model lives inside the list/kanban controller, so the panels
* listen to this bus event instead of trying to reach into another component.
*/
dnAiClientTools.add("adjust_view", async (env, params) => {
const { switchViewType } = params;
if (switchViewType) {
try {
await env.services.action.switchView(switchViewType);
} catch {
// Not in an action window (or the view type is unavailable): fall
// through to the search refinement, which still applies.
env.services.notification?.add(
`Cannot switch to ${switchViewType} here.`,
{ type: "warning" }
);
}
}
env.bus.trigger("DN_AI_ADJUST_SEARCH", params);
return "Success";
});
/**
* Run every action queued by the server for the current turn.
*
* A navigation is the last thing to happen: once `doAction` runs, the chat
* component that called us may be unmounted, so anything after it would be
* lost.
*/
export async function runDnAiClientTools(env, clientTools) {
const results = [];
for (const tool of clientTools || []) {
const { name, params } = tool;
const handler = dnAiClientTools.get(name, null);
if (!handler) {
console.warn(`dn_ai: unknown client tool "${name}"`);
results.push({ name, error: `Unknown client tool: ${name}` });
continue;
}
try {
const value = await handler(env, params || {});
results.push({ name, value: value === undefined ? "Success" : value });
} catch (error) {
console.warn(`dn_ai: client tool "${name}" failed`, error);
results.push({ name, error: error?.message || String(error) });
}
}
return results;
}

View File

@@ -0,0 +1,41 @@
/** @odoo-module **/
import { Composer } from "@mail/core/common/composer";
import { _t } from "@web/core/l10n/translation";
import { patch } from "@web/core/utils/patch";
/**
* Make the native composer behave around a running agent turn.
*
* Two things a plain chat does not need:
* - the send button must be inert while the agent is answering, otherwise a
* second question lands in the middle of a turn;
* - the placeholder should say what is happening, because the wait can last
* several seconds and a silent frozen composer looks broken.
*/
patch(Composer.prototype, {
get isDnAiBusy() {
return Boolean(this.props.composer.targetThread?.isAiGenerating);
},
get isSendButtonDisabled() {
return this.isDnAiBusy || super.isSendButtonDisabled;
},
async sendMessage() {
if (this.isDnAiBusy) {
this.env.services.notification.add(
_t("Please wait for the assistant to finish its answer."),
{ type: "warning" }
);
return;
}
return super.sendMessage();
},
get placeholder() {
if (this.isDnAiBusy) {
return _t("The assistant is answering…");
}
return super.placeholder;
},
});

View File

@@ -0,0 +1,26 @@
/** @odoo-module **/
import { DiscussChannel } from "@mail/discuss/core/common/discuss_channel_model";
import { fields } from "@mail/model/export";
import { patch } from "@web/core/utils/patch";
/**
* Teach the mail store about AI conversations.
*
* The mail client only renders threads whose `channel_type` is listed in
* `chatChannelTypes`; without this patch an `ai_chat` channel exists in the
* database but never shows up in the Discuss sidebar.
*/
patch(DiscussChannel.prototype, {
setup() {
super.setup(...arguments);
this.ai_agent_id = fields.One("ai.agent");
},
get chatChannelTypes() {
return [...super.chatChannelTypes, "ai_chat"];
},
get isAiChat() {
return this.channel_type === "ai_chat";
},
});

View File

@@ -0,0 +1,123 @@
/** @odoo-module **/
import { Component, proxy, t, useProps } from "@odoo/owl";
import { _t } from "@web/core/l10n/translation";
import { useService } from "@web/core/utils/hooks";
import { patch } from "@web/core/utils/patch";
import { ChatWindow } from "@mail/core/common/chat_window";
import { runDnAiClientTools } from "./client_tools";
/**
* Confirmation / question card inside the native chat window.
*
* The agent pauses when a tool needs approval or when it needs an answer; the
* choices have to be live buttons, which a chat message cannot provide (message
* bodies are sanitised on the way in and a stored `<button>` loses its
* behaviour). The card is therefore rendered by the chat window itself from
* `channel.dn_ai_pending`, while the message keeps a written trace of what was
* asked.
*/
export class DnAiPendingRequest extends Component {
static template = "dn_ai.PendingRequest";
props = useProps({
thread: t.object(),
});
setup() {
this.store = useService("mail.store");
this.orm = useService("orm");
this.notification = useService("notification");
this.state = proxy({ busy: false, freeText: "" });
}
get request() {
return this.props.thread?.channel?.dn_ai_pending || false;
}
get isQuestion() {
return this.request?.type === "question";
}
get title() {
return this.isQuestion ? _t("The assistant has a question") : _t("Confirm the action");
}
get labels() {
return {
send: _t("Send"),
freeText: _t("Or type your own answer…"),
};
}
async onChoice(value) {
if (this.state.busy) {
return;
}
await this._submit({
kind: this.isQuestion ? "question" : "confirmation",
value,
});
}
async onFreeText() {
const value = (this.state.freeText || "").trim();
if (!value || this.state.busy) {
return;
}
await this._submit({
kind: this.isQuestion ? "question" : "confirmation",
value: this.isQuestion ? [value] : value,
});
}
async _submit(response) {
this.state.busy = true;
try {
const payload = await this.orm.call("ai.session", "dn_ai_resume", [
this.request.session_id,
response,
]);
this.state.freeText = "";
// `dn_ai_pending` travels with the channel payload, so the channel
// has to be re-read for the card to disappear; the messages are
// fetched as well so the agent's next steps show up immediately.
// `getOrFetch` is cached on `fetchChannelInfoState`, which has to be
// invalidated first or the stale payload is returned.
const channel = this.props.thread.channel;
channel.fetchChannelInfoState = "not_fetched";
await this.store["discuss.channel"].getOrFetch(channel.id);
await this.props.thread.fetchMessages();
// Answering can trigger the same browser actions a typed message
// does ("yes, open it"): run them here too, or the agent would
// announce a navigation that never happens.
await runDnAiClientTools(this.env, payload?.client_tools);
} catch (error) {
this.notification.add(error?.message || _t("The AI request failed."), {
type: "danger",
});
} finally {
this.state.busy = false;
}
}
}
ChatWindow.components = { ...ChatWindow.components, DnAiPendingRequest };
patch(ChatWindow.prototype, {
get dnAiPendingRequest() {
return this.channel?.channel_type === "ai_chat" ? this.channel.dn_ai_pending : false;
},
get attClass() {
// The agent answers in Markdown, which produces tables and code blocks
// that the plain mail look leaves unstyled (a table renders with no
// borders and 1px padding, i.e. as a run-on wall of text). The marker
// class scopes that styling to this window only: ordinary chat windows
// must keep the stock look.
return {
...super.attClass,
o_dn_ai_chat_window: this.channel?.channel_type === "ai_chat",
};
},
});

View File

@@ -0,0 +1,148 @@
// Confirmation / question card of an AI conversation, shown above the composer
// of the native chat window.
//
// Only the card itself is styled here: everything around it (bubbles, avatar,
// composer, attachment cards) is `mail`'s own markup and must not be overridden,
// which is the whole point of using the native window.
.o_dn_ai_pending {
.o_dn_ai_pending_card {
background-color: var(--gray-100, #f8f9fa);
border-color: var(--border-color, #dee2e6) !important;
}
.o_dn_ai_pending_title {
color: var(--body-color, #212529);
}
// The agent's own text may contain markdown that the server already turned
// into HTML; keep paragraphs from collapsing against each other.
.o_dn_ai_pending_body p:last-child {
margin-bottom: 0;
}
.o_dn_ai_pending_choices .btn {
// Long choice labels (record names) must wrap instead of stretching the
// card beyond the window width.
white-space: normal;
text-align: start;
}
}
// The agent answers in Markdown, so its messages contain structures the plain
// mail look has no styling for: a table came out with `border: 0` and 1px
// padding, i.e. as a run-on wall of text. These rules apply to the AI window
// only (`o_dn_ai_chat_window` is set on the window itself, see
// `pending_request.js`); ordinary chat windows keep the stock look.
//
// Colours go through Bootstrap's `--gray-*` / `--border-color` custom
// properties rather than the Sass `$o-gray-*` variables: only the custom
// properties exist at runtime, and they are the ones a dark theme overrides.
// Writing `--o-gray-200` by mistake resolves to nothing and silently falls back
// to the hard-coded value, which breaks dark mode.
.o_dn_ai_chat_window {
.o-mail-Message-body {
// The server already wraps Markdown tables in this container, so the
// scroll behaviour belongs on the wrapper; the `display: block` fallback
// on `table` below covers tables that arrive without it (pasted HTML,
// or an agent that emits a raw <table>).
.o_dn_ai_table_wrap {
max-width: 100%;
overflow-x: auto;
margin-bottom: 0.5rem;
}
.o_dn_ai_table_wrap > table {
margin-bottom: 0;
}
table {
border-collapse: collapse;
margin-bottom: 0.5rem;
// Wide tables must scroll inside the bubble instead of stretching
// the window and pushing the composer off screen.
display: block;
max-width: 100%;
overflow-x: auto;
th,
td {
border: 1px solid var(--border-color, #dee2e6);
padding: 0.25rem 0.5rem;
text-align: start;
vertical-align: top;
}
th {
background-color: var(--gray-200, #e9ecef);
font-weight: 600;
white-space: nowrap;
}
// Zebra stripes: the agent often returns long comparison tables,
// and without them the eye loses the row it was reading.
tbody tr:nth-child(even) td {
background-color: var(--gray-100, #f8f9fa);
}
}
// Fenced code blocks arrive as `<div class="o_dn_ai_code"><pre>…`
// from the server-side Markdown renderer, so both the wrapper and a
// bare `<pre>` have to be covered.
.o_dn_ai_code pre,
pre {
margin: 0.5rem 0;
padding: 0.5rem 0.75rem;
border-radius: 0.375rem;
// A translucent black tint follows the theme (it darkens a light
// bubble and lightens a dark one) instead of pinning a grey that
// only works in one of the two.
background-color: rgba(0, 0, 0, 0.05);
overflow-x: auto;
font-size: 0.8125rem;
white-space: pre;
}
.o_dn_ai_code {
max-width: 100%;
}
// Headings produced by the server-side Markdown renderer. mail gives
// them no size of their own, so they would read as plain paragraphs.
.o_dn_ai_h {
font-size: 0.9375rem;
font-weight: 600;
margin: 0.75rem 0 0.375rem;
}
code {
font-size: 0.8125rem;
word-break: break-word;
}
// Inline code inside a paragraph needs a hint of background to stand
// apart from the surrounding prose; block code is already boxed above.
:not(pre) > code {
padding: 0.0625rem 0.25rem;
border-radius: 0.25rem;
background-color: rgba(0, 0, 0, 0.05);
}
// Long lists and quotes: keep the rhythm readable in a narrow window.
blockquote {
padding-inline-start: 0.75rem;
border-inline-start: 3px solid var(--border-color, #dee2e6);
color: var(--gray-600, #6c757d);
margin-bottom: 0.5rem;
}
p:last-child,
ul:last-child,
ol:last-child,
table:last-child,
pre:last-child,
.o_dn_ai_table_wrap:last-child {
margin-bottom: 0;
}
}
}

View File

@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="dn_ai.PendingRequest">
<div t-if="this.request" class="o_dn_ai_pending px-2 pb-2">
<div class="o_dn_ai_pending_card border rounded-3 p-2">
<div class="o_dn_ai_pending_title fw-bold small mb-1" t-out="this.title"/>
<div t-if="this.request.body" class="o_dn_ai_pending_body small mb-2" t-out="this.request.body"/>
<div class="o_dn_ai_pending_choices d-flex flex-wrap gap-2">
<t t-foreach="this.request.choices" t-as="choice" t-key="choice['value']">
<button type="button"
t-attf-class="btn btn-sm {{ choice['value'] === 'decline' ? 'btn-outline-secondary' : 'btn-primary' }}"
t-att-disabled="this.state.busy"
t-on-click="() => this.onChoice(choice['value'])"
t-out="choice['label']"/>
</t>
</div>
<div t-if="this.request.allow_free_text" class="input-group input-group-sm mt-2">
<input type="text"
class="form-control"
t-att-placeholder="this.labels.freeText"
t-model.proxy="this.state.freeText"
t-on-keydown="(ev) => ev.key === 'Enter' and this.onFreeText()"/>
<button type="button" class="btn btn-outline-primary"
t-att-disabled="this.state.busy or !(this.state.freeText or '').trim()"
t-on-click="this.onFreeText"
t-out="this.labels.send"/>
</div>
</div>
</div>
</t>
<!-- Pinned right above the composer of a chat window, not inside the
scrollable thread: a long answer must not push the choices out of
reach, because they are the only way to continue the turn. -->
<t t-inherit="mail.ChatWindow" t-inherit-mode="extension">
<xpath expr="//Composer" position="before">
<DnAiPendingRequest t-if="this.dnAiPendingRequest" thread="this.channel.thread"/>
</xpath>
</t>
</templates>

View File

@@ -0,0 +1,77 @@
/** @odoo-module **/
import { Thread } from "@mail/core/common/thread_model";
import { _t } from "@web/core/l10n/translation";
import { patch } from "@web/core/utils/patch";
import { runDnAiClientTools } from "./client_tools";
/**
* Let the native composer drive the agent loop.
*
* In Odoo 20's mail, sending a message from a chat window goes through
* `Thread.post()`: it posts to the server, inserts the result in the store and
* renders it. For an AI conversation there is one extra step — the agent has to
* answer — which is what this patch adds.
*
* The order matters and mirrors the Enterprise module:
* 1. `super.post()` first, so the user's own message is stored and rendered
* immediately. The agent can take several seconds, and a message that only
* appears once the answer is ready feels broken.
* 2. Then the agent runs, receiving the id of the message that was just
* stored — no need to re-send the text, and the attachments are read from
* where the composer put them.
*
* `isAiGenerating` is a UI-only flag: it disables the send button and changes
* the composer placeholder while the loop runs, so a second message cannot be
* sent into a turn that is still in flight.
*/
patch(Thread.prototype, {
setup() {
super.setup(...arguments);
this.isAiGenerating = false;
},
get isDnAiChat() {
return this.channel?.channel_type === "ai_chat";
},
async post(body, postData = {}, extraData = {}) {
const message = await super.post(body, postData, extraData);
if (!message || !this.isDnAiChat || this.isAiGenerating) {
// Nothing was posted, this is not an AI conversation, or a turn is
// already running (only reachable programmatically: the composer is
// disabled meanwhile). Interleaving two turns in one session would
// corrupt the agent's history, so the extra message is just posted.
return message;
}
const { orm, notification } = this.store.env.services;
this.isAiGenerating = true;
try {
const payload = await orm.call("ai.session", "dn_ai_submit_message", [
this.channel.id,
message.id,
]);
// The agent posts its steps and answer as regular messages. They
// also arrive over the bus, but that is asynchronous and can be
// delayed; fetching once right away makes the answer appear the
// moment the request completes.
await this.fetchMessages({ fetchParams: { after: message.id } });
// `dn_ai_pending` (the confirmation card) travels with the channel
// payload, so a turn that ends in a question needs a channel re-read
// — `getOrFetch` caches on `fetchChannelInfoState`, hence the reset.
this.channel.fetchChannelInfoState = "not_fetched";
await this.store["discuss.channel"].getOrFetch(this.channel.id);
// Browser actions (open a view, refine a search) can only run here.
// `payload.client_tools` is drained server-side, so this happens
// exactly once per turn.
await runDnAiClientTools(this.store.env, payload?.client_tools);
} catch (error) {
notification.add(error?.message || _t("The AI request failed."), {
type: "danger",
});
} finally {
this.isAiGenerating = false;
}
return message;
},
});

View File

@@ -0,0 +1,43 @@
/** @odoo-module **/
import { patch } from "@web/core/utils/patch";
import { useBus } from "@web/core/utils/hooks";
import { GraphController } from "@web/views/graph/graph_controller";
import { GraphModel } from "@web/views/graph/graph_model";
/**
* Let `adjust_view` switch the graph's measure, chart type and ordering.
*
* A graph only renders one measure at a time, so a list of measures is read as
* "the first one wins" instead of being toggled like on a pivot.
*/
patch(GraphController.prototype, {
setup() {
super.setup(...arguments);
useBus(this.env.bus, "DN_AI_ADJUST_MODEL", async ({ detail }) => {
if (!(this.model instanceof GraphModel)) {
return;
}
const { measures, mode, order, stacked, cumulated } = detail || {};
const defaults = this.model._buildMetaData({});
const metaData = this.model._buildMetaData({
measure: measures?.[0] ?? defaults.measure,
mode: mode ?? defaults.mode,
order: order ?? defaults.order,
stacked: stacked ?? defaults.stacked,
cumulated: cumulated ?? defaults.cumulated,
});
const measure = measures?.[0];
// Only reload the data points when the measure actually changed;
// mode/order/stacked are pure re-renders of what we already have.
if (measure && measure in metaData.measures && measure !== defaults.measure) {
await this.model.updateMetaData({ measure });
}
await this.model.updateMetaData({
mode: mode ?? metaData.mode,
order: order ?? metaData.order,
stacked: stacked ?? metaData.stacked,
cumulated: cumulated ?? metaData.cumulated,
});
});
},
});

View File

@@ -0,0 +1,49 @@
/** @odoo-module **/
import { patch } from "@web/core/utils/patch";
import { useBus } from "@web/core/utils/hooks";
import { PivotController } from "@web/views/pivot/pivot_controller";
import { PivotModel } from "@web/views/pivot/pivot_model";
import { computeReportMeasures } from "@web/views/utils";
/**
* Let `adjust_view` change which measures a pivot shows.
*
* The measure row is part of the pivot metadata, which lives on the model, so
* the only way to reach it from a bus event is through the controller. This is
* a no-op when the current view isn't a pivot.
*/
patch(PivotController.prototype, {
setup() {
super.setup(...arguments);
useBus(this.env.bus, "DN_AI_ADJUST_MODEL", async ({ detail }) => {
const { measures } = detail || {};
if (!(this.model instanceof PivotModel) || !measures?.length) {
return;
}
// A load may be in flight; toggling on top of it would write into
// metadata that is about to be replaced.
await Promise.resolve(this.model.race.getCurrentProm());
const metaData = this.model._buildMetaData();
const knownMeasures = computeReportMeasures(
metaData.fields,
metaData.fieldAttrs,
[...(metaData.activeMeasures || [])]
);
const wanted = measures.filter((measure) => measure in knownMeasures);
if (!wanted.length) {
return;
}
const active = metaData.activeMeasures || [];
// Toggling is symmetric, so deactivate the ones that must go too —
// otherwise the AI would only ever add measures.
const toToggle = new Set([
...wanted.filter((measure) => !active.includes(measure)),
...active.filter((measure) => !wanted.includes(measure)),
]);
for (const measure of toToggle) {
await this.model.toggleMeasure(measure);
}
});
},
});

View File

@@ -0,0 +1,60 @@
/** @odoo-module **/
import { SearchBar } from "@web/search/search_bar/search_bar";
import { patch } from "@web/core/utils/patch";
import { useBus } from "@web/core/utils/hooks";
/**
* Bridge between the `adjust_view` client tool and the search panel.
*
* `client_tools.js` only knows about the bus: the search model lives inside the
* list/kanban controller, out of reach from a tool handler. So the handler
* emits `DN_AI_ADJUST_SEARCH` and this patch translates it into real search
* model calls.
*/
patch(SearchBar.prototype, {
setup() {
super.setup(...arguments);
useBus(this.env.bus, "DN_AI_ADJUST_SEARCH", async ({ detail }) => {
const searchModel = this.env.searchModel;
const {
removeFacets,
toggleFilters,
toggleGroupBys,
applySearches,
customDomain,
measures,
mode,
order,
stacked,
cumulated,
} = detail || {};
for (const facetGroupId of removeFacets || []) {
searchModel.deactivateGroup(facetGroupId);
}
await searchModel.dnAiApplySearch({
filters: toggleFilters,
groupBys: toggleGroupBys,
fieldSearches: applySearches,
customDomain,
});
// Measures/mode only make sense on pivot and graph; those
// controllers listen for their own event so this stays a no-op on
// list and kanban.
const hasModelChanges = [mode, order, stacked, cumulated].some(
(value) => value !== undefined && value !== null
);
if ((measures && measures.length) || hasModelChanges) {
this.env.bus.trigger("DN_AI_ADJUST_MODEL", {
measures: measures || [],
mode,
order,
stacked,
cumulated,
});
}
});
},
});

View File

@@ -0,0 +1,153 @@
/** @odoo-module **/
import { SearchModel } from "@web/search/search_model";
import { GROUPABLE_TYPES } from "@web/search/utils/misc";
import { patch } from "@web/core/utils/patch";
/**
* Let an AI turn reshape the current search, not just navigate.
*
* The Community `SearchModel` has no notion of "apply this filter by name", so
* `adjust_view` had nowhere to land: the client tool fired a bus event that no
* component listened to. These helpers translate the tool's declarative
* parameters (filter names, field searches, a raw domain) into the imperative
* toggles the search model already exposes.
*
* Every entry point is defensive: an AI may name a filter that the current
* search view doesn't define (it looked at another action, or the view was
* customised). Dropping the unknown entry is far better than throwing inside a
* bus handler, which would silently abort the remaining adjustments.
*/
const CHAR_FIELDS = ["char", "html", "many2many", "many2one", "one2many", "text", "properties"];
patch(SearchModel.prototype, {
/**
* A field can become an ad-hoc group by only if it is groupable and of a
* type the group-by machinery understands. The Community model doesn't
* expose such a predicate, so provide one.
*/
dnAiCanGroupBy(fieldName, field) {
return Boolean(
field && field.groupable !== false && fieldName !== "id" && GROUPABLE_TYPES.includes(field.type)
);
},
/**
* Apply the declarative payload produced by the `adjust_view` client tool.
*
* @param {Object} params
* @param {Array} [params.filters] names (or `{field_name, selected_periods}`)
* @param {Array} [params.groupBys] names (or `{field_name, intervals}`)
* @param {Array} [params.fieldSearches] `{search_field, value}` pairs
* @param {Array} [params.customDomain] a domain in JSON-ish form
*/
async dnAiApplySearch({ filters, groupBys, fieldSearches, customDomain } = {}) {
for (const filter of filters || []) {
if (typeof filter === "string") {
const [searchItem] = this.getSearchItems(
(item) => item.type === "filter" && [item.name, item.fieldName].includes(filter)
);
if (searchItem && !searchItem.isActive) {
this.toggleSearchItem(searchItem.id);
}
} else if (filter && filter.field_name && filter.selected_periods) {
// A date filter names its generator ids; toggling the same
// period twice would cancel itself out, hence the Set.
const [searchItem] = this.getSearchItems(
(item) => item.type === "dateFilter" && item.fieldName === filter.field_name
);
if (searchItem) {
for (const periodId of new Set(filter.selected_periods)) {
this.toggleParentFilter(searchItem.id, periodId);
}
}
}
}
for (const groupBy of groupBys || []) {
if (typeof groupBy === "string") {
const [searchItem] = this.getSearchItems(
(item) => item.type === "groupBy" && [item.name, item.fieldName].includes(groupBy)
);
if (searchItem && !searchItem.isActive) {
this.toggleSearchItem(searchItem.id);
} else if (!searchItem) {
const field = this.searchViewFields[groupBy];
if (!this.dnAiCanGroupBy(groupBy, field)) {
continue;
}
this.createNewGroupBy(groupBy);
}
} else if (groupBy && groupBy.field_name && groupBy.intervals) {
const [firstInterval, ...otherIntervals] = groupBy.intervals;
if (!firstInterval) {
continue;
}
const findItem = () =>
this.getSearchItems(
(item) =>
item.type === "dateGroupBy" && item.fieldName === groupBy.field_name
)[0];
let intervalsToToggle = groupBy.intervals;
if (!findItem()) {
// No date group by exists yet: create one on the first
// interval, then toggle only the remaining intervals.
const field = this.searchViewFields[groupBy.field_name];
if (field && ["date", "datetime"].includes(field.type)) {
this.createNewGroupBy(groupBy.field_name, { interval: firstInterval });
}
intervalsToToggle = otherIntervals;
}
const searchItem = findItem();
for (const interval of intervalsToToggle) {
if (searchItem) {
this.toggleDateGroupBy(searchItem.id, interval);
}
}
}
}
for (const searchObject of fieldSearches || []) {
const { search_field: fieldName, value } = searchObject || {};
if (!fieldName) {
continue;
}
const [searchItem] = this.getSearchItems(
(item) => item.type === "field" && item.fieldName === fieldName
);
if (!searchItem) {
continue;
}
this.addAutoCompletionValues(searchItem.id, {
value,
label: `${value}`,
operator:
searchItem.operator ||
(CHAR_FIELDS.includes(searchItem.fieldType) ? "ilike" : "="),
});
}
if (customDomain && customDomain.length) {
await this.splitAndAddDomain(customDomain);
}
},
/**
* Honour `props.ai` handed to the view when it is first opened.
*
* Only applies on a cold load: when `config.state` is present the user is
* coming back to a saved search, and replaying the AI filters on top would
* duplicate them.
*/
async load(config, ...rest) {
const result = await super.load(config, ...rest);
if (config.ai && !config.state) {
await this.dnAiApplySearch({
filters: config.ai.selectedFilters,
groupBys: config.ai.selectedGroupBys,
fieldSearches: config.ai.search,
customDomain: config.ai.customDomain,
});
}
return result;
},
});

View File

@@ -0,0 +1,100 @@
/** @odoo-module **/
import { patch } from "@web/core/utils/patch";
import { withSearchProps } from "@web/search/with_search/with_search";
import { View } from "@web/views/view";
import { useSubEnv } from "@web/owl2/utils";
import { t } from "@odoo/owl";
/**
* Carry the `ai` payload from the action options down to the two places that
* actually use it.
*
* The Community `View` is built around whitelists, and the payload has to
* survive both of them:
*
* 1. `View.loadView` rebuilds `withSearchProps` and then deletes every key that
* isn't declared in the module-level `withSearchProps` shape. `ai` isn't
* declared, so it is dropped before `WithSearch` ever sees it — and
* `SearchModel.load` (where filters, group-bys and the domain are applied)
* is only reachable through those props. Declaring the key is what fixes it.
* 2. Pivot and graph freeze their measures and grouping into `modelParams`,
* built from the arch while the controller is being created. Those values
* can't be expressed as a search facet, so they have to be injected here.
*/
if (!("ai" in withSearchProps)) {
withSearchProps.ai = t.object().optional();
}
/** Turn `["a", "b"]` or `[{field_name, intervals}]` into `"a"` / `"b:month"`. */
function toGroupBySpecs(groupBys) {
const specs = [];
for (const groupBy of groupBys || []) {
if (typeof groupBy === "string") {
specs.push(groupBy);
} else if (groupBy?.field_name) {
for (const interval of groupBy.intervals || []) {
specs.push(`${groupBy.field_name}:${interval}`);
}
}
}
return specs;
}
patch(View.prototype, {
setup() {
super.setup(...arguments);
if (this.props.ai) {
// The user is talking to the AI, not typing in the search bar;
// stealing the focus would interrupt the conversation.
useSubEnv({
config: {
...this.env.config,
disableSearchBarAutofocus: true,
},
});
}
},
async loadView(props) {
const result = await super.loadView(...arguments);
const aiProps = props.ai;
if (!aiProps || !this.componentProps) {
return result;
}
const modelParams = this.componentProps.modelParams;
if (modelParams) {
if (props.type === "pivot") {
if (aiProps.measures?.length) {
modelParams.metaData.activeMeasures = aiProps.measures;
}
const colGroupBys = toGroupBySpecs(aiProps.colGroupBys);
if (colGroupBys.length) {
modelParams.metaData.colGroupBys = colGroupBys;
}
if (aiProps.sortedColumn) {
// An empty groupId means "sort on the total column".
modelParams.metaData.sortedColumn = {
groupId: [[], []],
measure: aiProps.sortedColumn.measure,
order: aiProps.sortedColumn.order,
};
}
} else if (props.type === "graph") {
// A graph shows one measure and one mode, unlike pivot.
for (const key of ["measure", "mode", "order", "stacked", "cumulated"]) {
if (aiProps[key] !== undefined && aiProps[key] !== null) {
modelParams[key] = aiProps[key];
}
}
if (aiProps.groupBys?.length) {
modelParams.groupBy = aiProps.groupBys;
}
}
}
// Downstream code must not mistake the payload for a view prop.
delete this.componentProps.ai;
return result;
},
});