# -*- coding: utf-8 -*- from datetime import timedelta from odoo import api, fields, models from odoo.exceptions import UserError from odoo.addons.mail.tools.discuss import Store class DiscussChannel(models.Model): """Make Discuss aware of AI conversations.""" _inherit = "discuss.channel" channel_type = fields.Selection( selection_add=[("ai_chat", "AI chat")], ondelete={"ai_chat": "cascade"}, ) ai_agent_id = fields.Many2one( "ai.agent", index="btree_not_null", groups=fields.NO_ACCESS, help="Agent driving this conversation. Only written by controlled flows.", ) ai_session_ids = fields.One2many('ai.session', inverse_name='channel_id') _ai_channel_type_check = models.Constraint( "CHECK(ai_agent_id IS NULL OR channel_type = 'ai_chat')", 'An AI agent can only be attached to an AI chat.', ) def _compute_display_name(self): super()._compute_display_name() for channel in self: # The conversation is named after its agent, so renaming the agent # renames the chat; the stored `name` is only there because the # column is NOT NULL. if channel.channel_type == 'ai_chat': agent = channel.sudo().ai_agent_id if agent: channel.display_name = agent.name @api.depends("channel_type", "image_128", "ai_agent_id.partner_id.avatar_128") def _compute_avatar_128(self): base_channels = self.env['discuss.channel'] for channel in self: if (channel.channel_type == 'ai_chat' and not channel.image_128 and (agent := channel.sudo().ai_agent_id)): channel.avatar_128 = agent.partner_id.avatar_128 else: base_channels |= channel super(DiscussChannel, base_channels)._compute_avatar_128() @api.autovacuum def _remove_ai_chat_channels(self): self.sudo().search([ ('channel_type', '=', 'ai_chat'), ('has_message', '=', False), ('create_date', '<', fields.Datetime.now() - timedelta(days=2)), ]).unlink() def _store_channel_fields(self, res: Store.FieldList): super()._store_channel_fields(res) res.one("ai_agent_id", "_store_agent_fields", sudo=True, predicate=lambda c: c.channel_type == 'ai_chat') res.attr("create_date", predicate=lambda c: c.channel_type == 'ai_chat') # The confirmation / question card has to be rendered by the chat # window itself: the choices are interactive, and a stored message body # cannot carry working buttons (it is sanitised on the way in). res.attr("dn_ai_pending", predicate=lambda c: c.channel_type == 'ai_chat') dn_ai_pending = fields.Json( "Pending AI interaction", compute="_compute_dn_ai_pending", help="Confirmation or question the agent is waiting for, surfaced to " "the chat window so it can render clickable choices.", ) @api.depends("channel_type", "ai_session_ids.loop_state", "ai_session_ids.pending_tool_call", "ai_session_ids.parent_session_id") def _compute_dn_ai_pending(self): sessions = self.env['ai.session'].sudo().search([ ('channel_id', 'in', self.ids), ('parent_session_id', '=', False), ]) by_channel = {session.channel_id.id: session for session in sessions} for channel in self: session = by_channel.get(channel.id) if channel.channel_type != 'ai_chat' or not session: channel.dn_ai_pending = False continue request = (session.pending_tool_call or {}).get('request') or {} if not request or session.loop_state not in ( 'waiting_confirmation', 'waiting_answer', ): channel.dn_ai_pending = False continue channel.dn_ai_pending = { 'session_id': session.id, 'type': 'question' if request.get('type') == 'question' else 'confirmation', 'body': request.get('body') or request.get('question') or '', 'choices': request.get('choices') or [], 'multi_select': bool(request.get('multi_select')), 'allow_free_text': request.get('allow_free_text', True), } # ------------------------------------------------------------------ # RPC used by the standalone chat panel (static/src/chat.js) # ------------------------------------------------------------------ def dn_ai_fetch_messages(self, limit=60): """Return the transcript plus the pending interaction, if any. Kept as a plain server call so the chat panel does not need to know anything about the mail store / websocket protocol. """ self.ensure_one() self.check_access('read') if self.channel_type != 'ai_chat': raise UserError(self.env._("This conversation is not an AI chat.")) session = self.env['ai.session'].sudo()._get_channel_session(self) agent = session.agent_id if session else self.sudo().ai_agent_id agent_partner = agent.partner_id messages = [] for message in self.sudo().message_ids.sorted('id')[-limit:]: author = message.author_id body = message.body or '' messages.append({ 'id': message.id, 'body': body, # A tool summary is one line of progress ("搜索 Contact"), # posted as its own message by the loop. Flagging it lets the # panel fold consecutive steps into a single collapsible # timeline instead of a wall of speech bubbles that buries the # actual answer. 'is_step': 'o_ai_tool_summary' in body, 'author_name': author.name or self.env._('System'), 'is_agent': bool(agent_partner and author == agent_partner), 'date': fields.Datetime.to_string(message.date), # The panel renders its own bubble instead of the mail chatter, # so the attachment cards have to travel with the message. 'attachments': [ { 'id': attachment.id, 'name': attachment.name, 'mimetype': attachment.mimetype or '', 'size': attachment.file_size or 0, # Internal users read their own uploads through the # regular ACL, no access token needed. 'url': f"/web/content/{attachment.id}?download=true", 'is_image': (attachment.mimetype or '').startswith('image/'), } for attachment in message.attachment_ids.sudo() ], }) pending = False if session: request = (session.pending_tool_call or {}).get('request') or {} if request and session.loop_state in ( 'waiting_confirmation', 'waiting_answer', ): pending = { 'type': 'question' if request.get('type') == 'question' else 'confirmation', 'body': request.get('body') or request.get('question') or '', 'choices': request.get('choices') or [], 'multi_select': bool(request.get('multi_select')), 'allow_free_text': request.get('allow_free_text', True), } return { 'messages': messages, 'agent_name': (agent.name if agent else '') or '', 'session_id': session.id if session else False, 'pending': pending, 'loop_state': session.loop_state if session else False, }