feat(chat): 优化发货相关消息处理逻辑
- 在列出聊天消息时,过滤掉类型为'shipping-parse-review'的消息 - 移除不再使用的shippingConversationTaskIdCache - 更新发货决策处理逻辑,简化保存消息的参数 - 添加发货动作按钮刷新时的任务定位优先级逻辑 - 移除解析复核消息的展示逻辑,统一处理到轻量工作台 - 增加单元测试,验证发货动作按钮刷新时的任务定位优先级
This commit is contained in:
1 parent
9f5493185d
commit
6a0a51313f
18 files changed
+1230
-199
No files matched your search
@@ -985,6 +985,9 @@ def save_local_message():
|
||||
if role == 'user':
|
||||
user_query = user_query or content
|
||||
content = ''
|
||||
else:
|
||||
# 本地生成的助手/表单消息不能携带 query;历史回放会把 query 渲染成用户气泡。
|
||||
user_query = ''
|
||||
|
||||
if not message_type:
|
||||
raise ValidationError('type is required')
|
||||
|
||||
@@ -67,10 +67,11 @@ def build_hxops_context(
|
||||
normalized_refs.append({"field": field, "value": value})
|
||||
seen_fields.add(field)
|
||||
|
||||
return {
|
||||
payload: dict[str, Any] = {
|
||||
"schema_version": HXOPS_CONTEXT_SCHEMA_VERSION,
|
||||
"session": {"id": normalized_session_id},
|
||||
"request": request_payload,
|
||||
"refs": normalized_refs,
|
||||
}
|
||||
return payload
|
||||
|
||||
@@ -37,17 +37,12 @@ def _latest_batch_for_conversation(conversation_id: str) -> ShippingBatch | None
|
||||
)
|
||||
|
||||
|
||||
def _latest_task_for_conversation(conversation_id: str) -> ShippingTask | None:
|
||||
"""按会话号获取最近一个未拒绝任务,用于恢复当前任务焦点。"""
|
||||
conv_id = str(conversation_id or "").strip()
|
||||
if not conv_id:
|
||||
def _task_by_task_no(task_id: str) -> ShippingTask | None:
|
||||
"""按显式 task_id 获取任务;仅用于补齐批次 ref,禁止按会话号猜测当前任务。"""
|
||||
normalized = str(task_id or "").strip().upper()
|
||||
if not normalized:
|
||||
return None
|
||||
return (
|
||||
ShippingTask.query.filter_by(conversation_id=conv_id)
|
||||
.filter(ShippingTask.process_status.notin_(["rejected"]))
|
||||
.order_by(ShippingTask.id.desc())
|
||||
.first()
|
||||
)
|
||||
return ShippingTask.query.filter_by(task_no=normalized).first()
|
||||
|
||||
|
||||
def _build_hxops_refs(*, task: str, batch: str) -> list[dict[str, str]]:
|
||||
@@ -81,24 +76,22 @@ def build_dify_chat_inputs(
|
||||
explicit_batch = str(batch_no or "").strip().upper()
|
||||
|
||||
batch = _latest_batch_for_conversation(conv_id)
|
||||
task = _latest_task_for_conversation(conv_id)
|
||||
explicit_task_row = _task_by_task_no(explicit_task)
|
||||
|
||||
focus_task = explicit_task
|
||||
if not focus_task and batch and batch.current_focus_task_no:
|
||||
focus_task = str(batch.current_focus_task_no or "").strip().upper()
|
||||
elif not focus_task and task and task.task_no:
|
||||
focus_task = str(task.task_no or "").strip().upper()
|
||||
|
||||
focus_batch = explicit_batch
|
||||
if not focus_batch and batch and batch.batch_no:
|
||||
focus_batch = str(batch.batch_no or "").strip().upper()
|
||||
elif (
|
||||
not focus_batch
|
||||
and task
|
||||
and getattr(task, "batch", None) is not None
|
||||
and getattr(task.batch, "batch_no", None)
|
||||
and explicit_task_row
|
||||
and getattr(explicit_task_row, "batch", None) is not None
|
||||
and getattr(explicit_task_row.batch, "batch_no", None)
|
||||
):
|
||||
focus_batch = str(task.batch.batch_no or "").strip().upper()
|
||||
focus_batch = str(explicit_task_row.batch.batch_no or "").strip().upper()
|
||||
|
||||
hxops_context = build_hxops_context(
|
||||
session_id=conv_id,
|
||||
|
||||
@@ -15,8 +15,7 @@ from typing import Any
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import ChatLog, ShippingBatch, ShippingTask
|
||||
from app.services.shipping_notice.agent_resolver import resolve_chat_agent
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
CP_PARSE_OK,
|
||||
@@ -133,75 +132,13 @@ def start_task_orchestrator(task_no: str | None) -> bool:
|
||||
return _start(task_no)
|
||||
|
||||
|
||||
def _build_parse_review_chat_payload(task: ShippingTask) -> dict[str, Any]:
|
||||
return {
|
||||
"taskId": task.task_no,
|
||||
"checkpoint": "parse_review",
|
||||
"header": {
|
||||
"customer_name": task.customer_name,
|
||||
"customer_code": task.customer_code,
|
||||
"ship_to": task.ship_to,
|
||||
"po_number": task.po_number,
|
||||
"required_date": task.required_date,
|
||||
},
|
||||
"lines": task.lines_json or [],
|
||||
"saving": False,
|
||||
}
|
||||
|
||||
|
||||
def _upsert_parse_review_chat_message(task: ShippingTask) -> None:
|
||||
"""
|
||||
将 parse_review 结果直接回填到当前聊天会话。
|
||||
保留旧调用点但不再写聊天表单消息。
|
||||
|
||||
设计意图:
|
||||
- 不再依赖“前端再次发一轮消息”去索取解析结果;
|
||||
- 同任务只保留一条 shipping-parse-review 消息,重复解析时直接更新。
|
||||
核心逻辑:解析复核动作统一由当前任务动作按钮和轻量工作台承载,避免可编辑表单进入聊天历史后在其他会话复活。
|
||||
"""
|
||||
session_id = str(task.conversation_id or "").strip()
|
||||
if not session_id or not task.user_id:
|
||||
return
|
||||
agent = resolve_chat_agent()
|
||||
if not agent or not getattr(agent, "id", None):
|
||||
return
|
||||
|
||||
payload = _build_parse_review_chat_payload(task)
|
||||
content = f"请确认或修订以下解析结果。\n任务编号:{task.task_no}"
|
||||
chat_logs = (
|
||||
db.session.query(ChatLog)
|
||||
.filter_by(
|
||||
user_id=task.user_id,
|
||||
agent_id=agent.id,
|
||||
session_id=session_id,
|
||||
message_type="shipping-parse-review",
|
||||
)
|
||||
.order_by(ChatLog.created_at.desc(), ChatLog.id.desc())
|
||||
.all()
|
||||
)
|
||||
|
||||
existing = None
|
||||
for item in chat_logs:
|
||||
item_payload = item.payload if isinstance(item.payload, dict) else {}
|
||||
if str(item_payload.get("taskId") or "").strip().upper() == str(task.task_no or "").strip().upper():
|
||||
existing = item
|
||||
break
|
||||
|
||||
if existing:
|
||||
existing.answer = content
|
||||
existing.payload = payload
|
||||
return
|
||||
|
||||
db.session.add(
|
||||
ChatLog(
|
||||
user_id=task.user_id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session_id,
|
||||
session_id=session_id,
|
||||
query="",
|
||||
answer=content,
|
||||
message_type="shipping-parse-review",
|
||||
payload=payload,
|
||||
)
|
||||
)
|
||||
_ = task
|
||||
|
||||
|
||||
def recompute_batch_summary(batch: ShippingBatch | None) -> None:
|
||||
|
||||
@@ -1124,6 +1124,7 @@ def test_build_dify_chat_inputs_returns_hxops_context_only(app):
|
||||
{"field": "task", "value": "SN-20260622-DDDD0004"},
|
||||
{"field": "batch", "value": "SB-DIFY-INPUTS"},
|
||||
]
|
||||
assert "instructions" not in inputs["hxops_context"]
|
||||
|
||||
|
||||
def test_build_dify_chat_inputs_requires_local_session_not_provider_conversation(app):
|
||||
@@ -1158,6 +1159,32 @@ def test_build_dify_chat_inputs_requires_local_session_not_provider_conversation
|
||||
]
|
||||
|
||||
|
||||
def test_build_dify_chat_inputs_does_not_fallback_to_latest_task_without_explicit_anchor(app):
|
||||
"""多票/无码头场景缺少显式锚点时,不应按最近任务给 Dify 注入 task ref。"""
|
||||
with app.app_context():
|
||||
conversation_id = "conv-shipping-no-anchor-001"
|
||||
older_task = ShippingTask(
|
||||
task_no="SN-20260630-OLDER001",
|
||||
conversation_id=conversation_id,
|
||||
source_type="manual",
|
||||
process_status="created",
|
||||
)
|
||||
newer_task = ShippingTask(
|
||||
task_no="SN-20260630-NEWER001",
|
||||
conversation_id=conversation_id,
|
||||
source_type="manual",
|
||||
process_status="created",
|
||||
)
|
||||
db.session.add_all([older_task, newer_task])
|
||||
db.session.commit()
|
||||
|
||||
inputs = dify_inputs.build_dify_chat_inputs(conversation_id)
|
||||
|
||||
assert set(inputs.keys()) == {"hxops_context"}
|
||||
assert inputs["hxops_context"]["session"]["id"] == conversation_id
|
||||
assert inputs["hxops_context"]["refs"] == []
|
||||
|
||||
|
||||
def test_is_shipping_notice_chat_agent_accepts_current_dify_app_name():
|
||||
"""兼容 Dify 侧当前使用的智能发货通知Agent命名。"""
|
||||
class AgentLike:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingInventoryMapping, ShippingTask, ShippingTaskEvent
|
||||
from app.models import ChatLog, ShippingInventoryMapping, ShippingTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.match import match_notice_lines
|
||||
|
||||
|
||||
@@ -1177,6 +1177,49 @@ def test_parse_notice_blocks_when_reservation_id_missing(app, client, monkeypatc
|
||||
assert task.match_status is None
|
||||
|
||||
|
||||
@pytest.mark.auto_rpa
|
||||
def test_parse_notice_low_confidence_does_not_write_parse_review_chat_card(app, client):
|
||||
headers = _tool_headers(app)
|
||||
|
||||
with app.app_context():
|
||||
from app.models import User
|
||||
|
||||
user = User(username="parse_review_card_user", email="parse_review_card_user@example.com")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
user_id = user.id
|
||||
|
||||
create_res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers=headers,
|
||||
json={"source_type": "manual", "conversation_id": "conv-no-parse-card", "user_id": user_id},
|
||||
)
|
||||
task_id = create_res.get_json()["task_id"]
|
||||
|
||||
parse_res = client.post(
|
||||
"/api/shipping-notice/tools/parse_notice",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_id": task_id,
|
||||
"conversation_id": "conv-no-parse-card",
|
||||
"structured": {
|
||||
"customer_name": "ACME",
|
||||
"lines": [{"sku": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}],
|
||||
"confidence": 0.4,
|
||||
},
|
||||
},
|
||||
)
|
||||
parse_data = parse_res.get_json()
|
||||
assert parse_data["status"] == "needs_human"
|
||||
assert parse_data.get("checkpoint") == "parse_review"
|
||||
|
||||
with app.app_context():
|
||||
assert db.session.query(ChatLog).filter_by(
|
||||
session_id="conv-no-parse-card",
|
||||
message_type="shipping-parse-review",
|
||||
).count() == 0
|
||||
|
||||
|
||||
@pytest.mark.auto_rpa
|
||||
def test_parse_notice_auto_continue_hides_parse_confirmation_hint(app, client, monkeypatch):
|
||||
import app.services.shipping_notice.task_workflow as task_workflow
|
||||
|
||||
@@ -56,7 +56,7 @@ def test_chat_history_with_query_param(client):
|
||||
# 1. Test without agent_id (Should fail with 400)
|
||||
res = client.get('/api/chat/sessions', headers=headers)
|
||||
assert res.status_code == 400
|
||||
assert 'agent_id is required' in res.get_json()['error']
|
||||
assert res.get_json()['error']['message'] == 'agent_id is required'
|
||||
|
||||
# 2. Test with agent_id in query string (Should succeed)
|
||||
res = client.get('/api/chat/sessions?agent_id=1', headers=headers)
|
||||
@@ -86,6 +86,38 @@ def test_chat_messages_history(client):
|
||||
assert msgs[1]['content'] == 'Hello'
|
||||
|
||||
|
||||
def test_local_assistant_message_query_does_not_duplicate_user_bubble(client):
|
||||
"""助手本地消息即使误传 query,历史回放也不能多生成一条用户确认。"""
|
||||
headers = get_headers(client)
|
||||
|
||||
user_res = client.post('/api/chat/messages/local?agent_id=1', headers=headers, json={
|
||||
'conversation_id': 'conv-local-confirm',
|
||||
'role': 'user',
|
||||
'type': 'text',
|
||||
'content': '确认\n任务编号:SN-001',
|
||||
'query': '确认',
|
||||
})
|
||||
assert user_res.status_code == 200
|
||||
|
||||
assistant_res = client.post('/api/chat/messages/local?agent_id=1', headers=headers, json={
|
||||
'conversation_id': 'conv-local-confirm',
|
||||
'role': 'assistant',
|
||||
'type': 'text',
|
||||
'content': '已确认,进入下一步。',
|
||||
'query': '确认',
|
||||
})
|
||||
assert assistant_res.status_code == 200
|
||||
|
||||
res = client.get('/api/chat/messages?conversation_id=conv-local-confirm&agent_id=1', headers=headers)
|
||||
assert res.status_code == 200
|
||||
msgs = res.get_json()
|
||||
user_messages = [item for item in msgs if item['role'] == 'user']
|
||||
assert len(user_messages) == 1
|
||||
assert user_messages[0]['content'] == '确认'
|
||||
assert msgs[-1]['role'] == 'assistant'
|
||||
assert msgs[-1]['content'] == '已确认,进入下一步。'
|
||||
|
||||
|
||||
def test_chat_sessions_keep_latest_non_empty_query_as_title(client):
|
||||
headers = get_headers(client)
|
||||
|
||||
|
||||
@@ -0,0 +1,958 @@
|
||||
# Agent Runtime Context 原型方案
|
||||
|
||||
## 1. 缘起
|
||||
|
||||
HXOPS 当前的 Agent 体系正在从“纯对话问答”进入“业务流程协同”。货代发货通知 Agent 是第一个典型场景:用户在一个 Chat 会话里一次性上传多份发货通知,HXOPS 会拆成一个批次和多张任务票,再分别调用 Dify Chatflow 进行解析、确认、库存匹配、异常处理和结果生成。
|
||||
|
||||
这个模式带来了一个关键断点:
|
||||
|
||||
- 用户看到的是一个 HXOPS 对话和一个批次工作台。
|
||||
- HXOPS 后端实际维护的是 Batch、Task、TaskEvent、文件、库存匹配、人工决策等结构化状态。
|
||||
- Dify 看到的是一次次 Chatflow 调用。一次批次 8 份文件,可能就是 8 次 Dify run。
|
||||
- HXOPS 本地按钮动作,例如确认、驳回、重新匹配、重试、切换 focus task,很多并不会进入 Dify conversation memory。
|
||||
|
||||
因此,不能再把 Dify 的对话记忆当作业务记忆。Dify 只知道它参与过的那部分自然语言和工具结果;HXOPS 本地处理过的动作、状态推进、异常阻断,如果不显式告诉 Dify,后续自然语言对话就可能出现“不知道刚才发生了什么”的问题。
|
||||
|
||||
更重要的是,货代发货不是闲聊场景,而是强流程、强审计、强幂等的业务 Agent。以下事实不能由 LLM memory 承担:
|
||||
|
||||
- 当前批次是哪一个。
|
||||
- 当前聚焦任务是哪一票。
|
||||
- 某票是否已确认解析。
|
||||
- shortage 是否阻断生成 Excel。
|
||||
- 用户点过哪个恢复动作。
|
||||
- 哪个任务可以继续,哪个任务必须人工处理。
|
||||
- 多票批次里用户一句“继续”到底指哪一票。
|
||||
|
||||
这些事实必须以 HXOPS DB、状态机和事件表为准。LLM 可以辅助理解语言,但不能成为业务事实源。
|
||||
|
||||
## 2. 当前问题
|
||||
|
||||
### 2.1 Dify memory 与 HXOPS 状态不等价
|
||||
|
||||
Dify conversation memory 只覆盖 Dify 参与的消息链路。HXOPS 本地生成的消息和按钮动作,即使会展示在 ChatLog 中,也不代表 Dify 已经记住。
|
||||
|
||||
例如:
|
||||
|
||||
1. Dify 返回“待确认解析”。
|
||||
2. 用户点击 HXOPS 前端按钮“确认”。
|
||||
3. HXOPS 直连 `submit_decision`,更新 ShippingTask 状态。
|
||||
4. Chat 中展示“已确认,进入下一步”。
|
||||
|
||||
这一步业务状态有效,但 Dify memory 里未必知道“用户已确认”。如果用户后续说“继续”,Dify 仅靠自己的 memory 可能无法判断当前应继续哪一票、从哪一步继续。
|
||||
|
||||
### 2.2 一个 HXOPS 会话可能对应多次 Dify run
|
||||
|
||||
批次场景下,HXOPS 一个用户会话可能一次上传 8 份文件。对用户来说这是一个批次;对执行层来说,这是 8 个任务;对 Dify 来说,可能是 8 次 Chatflow run。
|
||||
|
||||
这不是坏事。行业最佳实践也通常把用户体验和执行单元拆开:
|
||||
|
||||
- 用户体验层:一个批次主会话。
|
||||
- 执行层:多个独立 task/run。
|
||||
- 事实源:平台 DB、状态机、事件表。
|
||||
- 展示层:Chat 主路径 + 轻量批次工作台。
|
||||
|
||||
真正缺失的是一个统一机制,把每次 Dify run 的归属、当前任务锚点和业务现场显式传给 Dify。
|
||||
|
||||
### 2.3 不应在 Dify 画布里重复写解析代码
|
||||
|
||||
如果每个 Agent 都在 Dify 代码节点里解析上下文 JSON,会出现几个问题:
|
||||
|
||||
- 每个画布各写一套解析逻辑,难维护。
|
||||
- 字段路径漂移后不容易发现。
|
||||
- 安全边界不清晰。
|
||||
- 多 Agent 无法复用。
|
||||
- Dify 画布变成“业务状态解析器”,偏离职责。
|
||||
|
||||
因此,HXOPS 应提供标准上下文协议和标准解析工具,让 Dify 只消费变量和调用工具,不在画布里重复实现解析逻辑。
|
||||
|
||||
## 3. 设计目标
|
||||
|
||||
Agent Runtime Context 的目标不是替代业务状态机,也不是替代 Dify memory,而是提供一个平台级运行态输入协议:
|
||||
|
||||
```text
|
||||
HXOPS DB / 状态机 / 事件表
|
||||
↓ 每次调用 Dify 前生成最新上下文
|
||||
agent_runtime_context
|
||||
↓ 作为 Dify Start 变量传入
|
||||
Dify Agent / LLM Prompt 显式引用
|
||||
↓ 如需字段
|
||||
Dify 调 HXOPS 标准 parse API
|
||||
```
|
||||
|
||||
目标包括:
|
||||
|
||||
- 让 Dify 每次 run 都知道当前归属哪个 HXOPS 会话、批次、任务。
|
||||
- 让 Dify 不依赖 conversation memory 猜业务状态。
|
||||
- 让多任务批次不会靠 `conversation_id` 回退到“最近一票”。
|
||||
- 让 HXOPS 本地动作后的后续自然语言对话仍然可续。
|
||||
- 让字段解析由 HXOPS 标准 API 承担,不在 Dify 代码节点重复实现。
|
||||
- 为后续其他 Agent 复用同一套平台上下文协议。
|
||||
|
||||
## 4. 核心原则
|
||||
|
||||
### 4.1 HXOPS 是唯一事实源
|
||||
|
||||
所有业务事实以 HXOPS 为准,包括:
|
||||
|
||||
- 任务状态。
|
||||
- 批次状态。
|
||||
- 当前 focus task。
|
||||
- 人工决策。
|
||||
- 文件与解析结果。
|
||||
- 库存匹配结果。
|
||||
- 阻断原因。
|
||||
- 可执行动作。
|
||||
|
||||
Dify 不拥有这些事实。Dify 只读取 HXOPS 每次提供的上下文,并通过 HXOPS 工具查询或推进状态。
|
||||
|
||||
### 4.2 Dify run 是执行单元,不等于用户主会话
|
||||
|
||||
一次 HXOPS ChatSession 可以对应多个 Dify run。尤其在批次场景下:
|
||||
|
||||
```text
|
||||
HXOPS ChatSession: conv_001
|
||||
└─ ShippingBatch: SB-001
|
||||
├─ Task SN-001 → Dify run A
|
||||
├─ Task SN-002 → Dify run B
|
||||
├─ Task SN-003 → Dify run C
|
||||
└─ Task SN-004 → Dify run D
|
||||
```
|
||||
|
||||
用户无需感知这些 Dify run。用户看到的是一个批次主会话和一个轻量工作台。HXOPS 负责把多个 run 的结果汇总到 Batch/Task 状态。
|
||||
|
||||
### 4.3 Context 是现场说明,不是业务账本
|
||||
|
||||
`agent_runtime_context` 是每次请求前由 HXOPS 生成的最新现场说明。它可以包含锚点、摘要和状态提示,但业务推进仍必须通过 HXOPS API/Tool 进入状态机。
|
||||
|
||||
### 4.4 平台统一,领域扩展
|
||||
|
||||
不为 shipping 单独设计孤岛字段。平台统一变量名:
|
||||
|
||||
```text
|
||||
agent_runtime_context
|
||||
```
|
||||
|
||||
领域差异放在 `domain` 内:
|
||||
|
||||
```text
|
||||
domain.type = "shipping_notice"
|
||||
domain.payload/state_hint/summary = 货代发货自己的运行态摘要
|
||||
```
|
||||
|
||||
未来请假、文件检核、培训、固定资产等 Agent 都可以复用同一协议。
|
||||
|
||||
## 5. 协议原型
|
||||
|
||||
第一阶段建议把 `agent_runtime_context` 作为 JSON 字符串传给 Dify,避免 Dify 对 object 类型变量支持不稳定。
|
||||
|
||||
```json
|
||||
{
|
||||
"schema_version": "1",
|
||||
"context_id": "ctx_20260701_abc123",
|
||||
"agent_code": "shipping_notice",
|
||||
"scope": "task_run",
|
||||
"platform": {
|
||||
"session_id": "conv_001",
|
||||
"parent_session_id": "conv_001",
|
||||
"request_id": "req_20260701_001",
|
||||
"locale": "zh-CN"
|
||||
},
|
||||
"refs": {
|
||||
"batch_no": "SB-20260701-001",
|
||||
"task_no": "SN-20260701-ABCD1234",
|
||||
"run_purpose": "parse_notice",
|
||||
"file_name": "notice_001.pdf"
|
||||
},
|
||||
"domain": {
|
||||
"type": "shipping_notice",
|
||||
"summary": "当前任务 SN-20260701-ABCD1234 属于批次 SB-20260701-001,本次 Dify run 用于解析发货通知 notice_001.pdf。",
|
||||
"state_hint": {
|
||||
"current_step": "parse_notice",
|
||||
"status": "running",
|
||||
"focus_task_no": "SN-20260701-ABCD1234"
|
||||
},
|
||||
"available_actions_hint": []
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 5.1 字段说明
|
||||
|
||||
| 字段 | 说明 |
|
||||
| --- | --- |
|
||||
| `schema_version` | 协议版本,便于后续兼容 |
|
||||
| `context_id` | 本次运行态上下文编号,可用于日志和排查 |
|
||||
| `agent_code` | 稳定 Agent 标识,不使用展示名称 |
|
||||
| `scope` | 上下文作用域,例如 `chat_turn`、`task_run`、`batch_summary` |
|
||||
| `platform.session_id` | HXOPS 当前 ChatSession |
|
||||
| `platform.parent_session_id` | 后台 run 归属的用户主会话 |
|
||||
| `platform.request_id` | 本次请求 ID |
|
||||
| `platform.locale` | 用户语言环境 |
|
||||
| `refs` | 稳定业务锚点 |
|
||||
| `domain.type` | 领域类型 |
|
||||
| `domain.summary` | 给 Dify 读的短摘要 |
|
||||
| `domain.state_hint` | 状态提示,不替代状态机 |
|
||||
| `domain.available_actions_hint` | 可执行动作提示,不替代后端校验 |
|
||||
|
||||
## 6. Dify 注入方式
|
||||
|
||||
### 6.1 HXOPS 请求 Dify
|
||||
|
||||
HXOPS 调用 Dify `/chat-messages` 时传:
|
||||
|
||||
```json
|
||||
{
|
||||
"inputs": {
|
||||
"agent_runtime_context": "{...JSON 字符串...}"
|
||||
},
|
||||
"query": "解析当前发货通知任务",
|
||||
"response_mode": "streaming",
|
||||
"user": "123"
|
||||
}
|
||||
```
|
||||
|
||||
### 6.2 Dify Start 节点
|
||||
|
||||
Dify Chatflow Start 节点新增变量:
|
||||
|
||||
```text
|
||||
agent_runtime_context
|
||||
类型:Paragraph / Long Text
|
||||
```
|
||||
|
||||
不建议用 object 类型作为第一阶段方案,避免变量选择器或工具入参无法稳定选择。
|
||||
|
||||
### 6.3 Dify Prompt
|
||||
|
||||
Agent/LLM 节点提示词必须显式引用:
|
||||
|
||||
```text
|
||||
以下是 HXOPS 每次请求提供的运行态上下文:
|
||||
|
||||
{{agent_runtime_context}}
|
||||
|
||||
规则:
|
||||
- 该上下文用于识别当前 HXOPS 会话、批次、任务和本次执行目的。
|
||||
- 不要依赖 Dify 对话历史猜测任务状态。
|
||||
- 如需读取上下文字段,调用 HXOPS 工具 parse_agent_runtime_context。
|
||||
- 如需推进任务状态,必须调用对应 HXOPS 业务工具。
|
||||
- 不要在正文中列出确认、驳回、重新解析等按钮清单;可点击动作由 HXOPS 前端渲染。
|
||||
```
|
||||
|
||||
如果当前 Dify 版本使用节点路径变量,应通过变量选择器插入,避免手写变量路径错误。
|
||||
|
||||
## 7. 标准解析 API 原型
|
||||
|
||||
### 7.1 定位
|
||||
|
||||
`parse_agent_runtime_context` 是给 Dify 用的只读工具。它的职责是解析 HXOPS 每次传入的 `agent_runtime_context`,按字段路径返回值,避免在 Dify 画布里写代码节点。
|
||||
|
||||
它不是业务推进接口,也不是状态机接口。
|
||||
|
||||
### 7.2 API
|
||||
|
||||
```http
|
||||
POST /api/agent-runtime-context/tools/parse
|
||||
```
|
||||
|
||||
请求:
|
||||
|
||||
```json
|
||||
{
|
||||
"agent_runtime_context": "{{agent_runtime_context}}",
|
||||
"paths": [
|
||||
"platform.session_id",
|
||||
"refs.batch_no",
|
||||
"refs.task_no",
|
||||
"refs.run_purpose",
|
||||
"domain.summary",
|
||||
"domain.state_hint.status"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
返回:
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "ok",
|
||||
"data": {
|
||||
"platform.session_id": "conv_001",
|
||||
"refs.batch_no": "SB-20260701-001",
|
||||
"refs.task_no": "SN-20260701-ABCD1234",
|
||||
"refs.run_purpose": "parse_notice",
|
||||
"domain.summary": "当前任务 SN-20260701-ABCD1234 属于批次 SB-20260701-001,本次 Dify run 用于解析发货通知 notice_001.pdf。",
|
||||
"domain.state_hint.status": "running"
|
||||
},
|
||||
"missing": []
|
||||
}
|
||||
```
|
||||
|
||||
### 7.3 安全约束
|
||||
|
||||
第一阶段必须做以下约束:
|
||||
|
||||
- 只读,不产生状态推进。
|
||||
- 限制 `agent_runtime_context` 长度。
|
||||
- 限制 `paths` 数量。
|
||||
- 限制 allowed paths 白名单。
|
||||
- 不执行表达式,不支持任意代码。
|
||||
- `schema_version` 不匹配则拒绝。
|
||||
- JSON 解析失败则返回明确错误。
|
||||
|
||||
建议首批白名单:
|
||||
|
||||
```text
|
||||
schema_version
|
||||
context_id
|
||||
agent_code
|
||||
scope
|
||||
platform.session_id
|
||||
platform.parent_session_id
|
||||
platform.request_id
|
||||
platform.locale
|
||||
refs.batch_no
|
||||
refs.task_no
|
||||
refs.run_purpose
|
||||
refs.file_name
|
||||
domain.type
|
||||
domain.summary
|
||||
domain.state_hint.current_step
|
||||
domain.state_hint.status
|
||||
domain.state_hint.focus_task_no
|
||||
domain.available_actions_hint
|
||||
```
|
||||
|
||||
## 8. 货代发货首个落地场景
|
||||
|
||||
### 8.1 批量上传 8 份文件
|
||||
|
||||
用户在 HXOPS 一个 Chat 会话里上传 8 份文件。
|
||||
|
||||
HXOPS 创建:
|
||||
|
||||
```text
|
||||
ChatSession conv_001
|
||||
ShippingBatch SB-001
|
||||
ShippingTask SN-001 ... SN-008
|
||||
```
|
||||
|
||||
后台对每票调用一次 Dify:
|
||||
|
||||
```text
|
||||
SN-001 → Dify run parse_notice
|
||||
SN-002 → Dify run parse_notice
|
||||
...
|
||||
SN-008 → Dify run parse_notice
|
||||
```
|
||||
|
||||
每次 Dify run 都带不同的 `task_no`,但相同的 `parent_session_id` 和 `batch_no`。
|
||||
|
||||
### 8.2 用户继续当前任务
|
||||
|
||||
用户在 Chat 中说:
|
||||
|
||||
```text
|
||||
继续
|
||||
```
|
||||
|
||||
HXOPS 根据当前 batch 的 `current_focus_task_no` 生成 context:
|
||||
|
||||
```json
|
||||
{
|
||||
"scope": "chat_turn",
|
||||
"refs": {
|
||||
"batch_no": "SB-001",
|
||||
"task_no": "SN-003",
|
||||
"run_purpose": "continue_task"
|
||||
},
|
||||
"domain": {
|
||||
"summary": "当前聚焦任务 SN-003 停在库存匹配,因 shortage 暂停。",
|
||||
"state_hint": {
|
||||
"current_step": "inventory_match",
|
||||
"status": "blocked",
|
||||
"focus_task_no": "SN-003"
|
||||
},
|
||||
"available_actions_hint": ["view_shortage", "rematch"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Dify 可以根据摘要回答,也可以调用 parse tool 取字段。真正的继续、重匹配、生成 Excel 仍必须调用 HXOPS shipping tools,由状态机最终判定。
|
||||
|
||||
## 9. 对话连续性与指代治理
|
||||
|
||||
`agent_runtime_context` 不只是传 `task_no`。从行业最佳实践看,流程型 Agent 必须显式治理对话连续性,否则用户一旦使用“这个、那个、刚才、上一次、继续它、还是按之前的来”等模糊表达,Dify 很容易因为缺少 HXOPS 本地上下文而误判。
|
||||
|
||||
因此,第一阶段协议需要预留 `reference_context` 与 `recent_activity_summary`。
|
||||
|
||||
### 9.1 需要覆盖的场景
|
||||
|
||||
#### 场景一:当前对象指代
|
||||
|
||||
用户说:
|
||||
|
||||
```text
|
||||
继续这个
|
||||
这个为什么卡住了
|
||||
刚才那票重新匹配
|
||||
```
|
||||
|
||||
风险:
|
||||
|
||||
- Dify memory 可能不知道 HXOPS 当前 focus task。
|
||||
- 用户最近点过的按钮可能没有进入 Dify conversation。
|
||||
- 多任务批次里可能同时存在多个“刚才处理过”的对象。
|
||||
|
||||
治理方式:
|
||||
|
||||
- HXOPS 在 context 中提供当前 focus object。
|
||||
- 推进类动作必须解析出唯一 `task_no`。
|
||||
- 无法唯一解析时必须追问或让前端弹出任务选择。
|
||||
|
||||
#### 场景二:上一轮/上一次指代
|
||||
|
||||
用户说:
|
||||
|
||||
```text
|
||||
上一次失败的是哪个
|
||||
还是按刚才那个库存源
|
||||
回到上一步
|
||||
```
|
||||
|
||||
风险:
|
||||
|
||||
- “上一次”可能指最近一次 Dify 回复、最近一次 HXOPS 按钮动作、最近一次失败事件,或者最近一次用户提到的任务。
|
||||
- 如果只靠 Dify 聊天历史,很难知道 HXOPS 本地事件顺序。
|
||||
|
||||
治理方式:
|
||||
|
||||
- HXOPS 在 TaskEvent / ChatLog payload 中记录关键动作目标。
|
||||
- context 中提供 `last_action_target`、`last_failed_target`、`last_mentioned_target`。
|
||||
- Dify 不直接猜“上一次”,而是基于 reference candidates 解释;多候选时追问。
|
||||
|
||||
#### 场景三:跨任务切换
|
||||
|
||||
用户说:
|
||||
|
||||
```text
|
||||
先处理第二个
|
||||
切到异常那票
|
||||
看一下 SN-xxx
|
||||
```
|
||||
|
||||
风险:
|
||||
|
||||
- 用户是在切换 focus task,而不是推进当前任务。
|
||||
- 如果 Dify 把这类话理解成继续当前任务,会串票。
|
||||
|
||||
治理方式:
|
||||
|
||||
- context 中列出当前批次最近任务摘要和异常候选。
|
||||
- Dify 需要调用 `switch_focus_task` 或返回明确切换建议。
|
||||
- HXOPS 工具必须校验 task 是否属于当前 batch。
|
||||
|
||||
#### 场景四:跨批次回看
|
||||
|
||||
用户说:
|
||||
|
||||
```text
|
||||
昨天那个批次怎么样了
|
||||
上个批次还有异常吗
|
||||
```
|
||||
|
||||
风险:
|
||||
|
||||
- 当前会话 focus batch 与用户指代的历史 batch 不一致。
|
||||
- Dify 可能把历史批次问题误套到当前批次。
|
||||
|
||||
治理方式:
|
||||
|
||||
- context 只提供当前 batch,不自动扩展历史批次。
|
||||
- 历史批次查询必须走显式检索工具。
|
||||
- 返回结果时明确批次号和日期,避免“当前/上个”混淆。
|
||||
|
||||
#### 场景五:本地动作未进入 Dify memory
|
||||
|
||||
用户点过:
|
||||
|
||||
```text
|
||||
确认解析
|
||||
重新匹配
|
||||
查看缺口
|
||||
切换当前任务
|
||||
重试上传
|
||||
```
|
||||
|
||||
风险:
|
||||
|
||||
- 这些动作由 HXOPS 直连 API 完成,Dify memory 不一定知道。
|
||||
- 后续用户说“继续刚才的”,Dify 可能缺少事件背景。
|
||||
|
||||
治理方式:
|
||||
|
||||
- 所有关键本地动作写入事件表或 ChatLog payload。
|
||||
- context 中不传 UI 点击流水,而传业务结果:
|
||||
- 用户已确认解析。
|
||||
- 当前任务进入库存匹配。
|
||||
- 最近一次重匹配发现 shortage。
|
||||
- 当前 focus task 已切换为 SN-xxx。
|
||||
|
||||
#### 场景六:多窗口或并发更新
|
||||
|
||||
用户可能在两个页面同时操作,或后台 worker 自动推进任务。
|
||||
|
||||
风险:
|
||||
|
||||
- Dify 收到的上下文是请求前快照。
|
||||
- 在 Dify 生成期间,HXOPS 状态可能已变化。
|
||||
|
||||
治理方式:
|
||||
|
||||
- context 负责让 Dify理解现场。
|
||||
- 状态推进必须调用 HXOPS 工具,由状态机做最终校验。
|
||||
- API 返回当前状态不允许推进时,Dify 应解释最新状态,而不是坚持旧 context。
|
||||
|
||||
#### 场景七:长批次上下文压缩
|
||||
|
||||
一个批次有很多文件时,不应把全部任务、全部事件和全部解析结果塞进 Dify。
|
||||
|
||||
风险:
|
||||
|
||||
- 上下文过长。
|
||||
- 模型注意力被旧任务污染。
|
||||
- 成本升高,响应变慢。
|
||||
|
||||
治理方式:
|
||||
|
||||
- context 只传当前 focus task、批次摘要、最近关键事件和少量候选对象。
|
||||
- 其他任务详情通过工具查询。
|
||||
- 已完成任务只传统计摘要,不传全部明细。
|
||||
|
||||
### 9.2 reference_context 原型
|
||||
|
||||
建议在 `agent_runtime_context` 中增加:
|
||||
|
||||
```json
|
||||
{
|
||||
"reference_context": {
|
||||
"current_focus": {
|
||||
"type": "shipping_task",
|
||||
"id": "SN-20260701-0003",
|
||||
"label": "当前聚焦任务"
|
||||
},
|
||||
"last_action_target": {
|
||||
"type": "shipping_task",
|
||||
"id": "SN-20260701-0003",
|
||||
"action": "confirm_parse",
|
||||
"label": "刚才确认解析的任务"
|
||||
},
|
||||
"last_failed_target": {
|
||||
"type": "shipping_task",
|
||||
"id": "SN-20260701-0002",
|
||||
"reason": "inventory_shortage",
|
||||
"label": "最近一次异常任务"
|
||||
},
|
||||
"last_mentioned_target": {
|
||||
"type": "shipping_task",
|
||||
"id": "SN-20260701-0002",
|
||||
"label": "最近在对话中提到的任务"
|
||||
},
|
||||
"recent_entities": [
|
||||
{
|
||||
"type": "shipping_task",
|
||||
"id": "SN-20260701-0003",
|
||||
"label": "当前聚焦任务,停在库存匹配"
|
||||
},
|
||||
{
|
||||
"type": "shipping_task",
|
||||
"id": "SN-20260701-0002",
|
||||
"label": "上一票异常任务,存在 shortage"
|
||||
}
|
||||
]
|
||||
},
|
||||
"recent_activity_summary": "用户刚才确认了 SN-20260701-0003 的解析结果;SN-20260701-0002 最近一次库存匹配发现 shortage。"
|
||||
}
|
||||
```
|
||||
|
||||
### 9.3 指代解析优先级
|
||||
|
||||
第一阶段建议使用以下优先级:
|
||||
|
||||
1. 用户显式输入 `task_no` / `batch_no` 时,以显式编号为准。
|
||||
2. 用户说“当前、这个、这票”时,优先绑定 `current_focus`。
|
||||
3. 用户说“刚才、上一步、刚刚处理的”时,优先绑定 `last_action_target`。
|
||||
4. 用户说“失败的、异常的、卡住的”时,优先绑定 `last_failed_target`。
|
||||
5. 用户说“上一次提到的、那个”时,参考 `last_mentioned_target` 和 `recent_entities`。
|
||||
6. 多候选或低置信时,必须追问或返回候选列表,不能推进状态。
|
||||
|
||||
### 9.4 动作风险分级
|
||||
|
||||
不是所有模糊指代都要同等严格。建议分三类:
|
||||
|
||||
| 类型 | 示例 | 处理规则 |
|
||||
| --- | --- | --- |
|
||||
| 低风险查询 | “这个卡在哪” | 可以基于 reference_context 回答,并标明对象 |
|
||||
| 中风险切换 | “切到异常那票” | 需要解析唯一候选,必要时追问 |
|
||||
| 高风险推进 | “继续它”“确认这个”“生成 Excel” | 必须有明确 task_no,并由 HXOPS 状态机最终校验 |
|
||||
|
||||
### 9.5 Prompt 规则
|
||||
|
||||
Dify Prompt 中应加入:
|
||||
|
||||
```text
|
||||
当用户使用“这个、那个、刚才、上一次、继续它”等模糊表达时:
|
||||
- 优先参考 agent_runtime_context.reference_context。
|
||||
- 回答中明确你理解的对象,例如“我按当前任务 SN-xxx 处理”。
|
||||
- 如果存在多个候选,不要推进任务,先向用户确认。
|
||||
- 涉及确认、重试、生成、匹配、切换 focus task 等动作时,必须带明确 task_no 调用 HXOPS 工具。
|
||||
```
|
||||
|
||||
### 9.6 验收场景
|
||||
|
||||
第一阶段至少补以下验收样例:
|
||||
|
||||
- 当前 focus task 为 SN-003,用户说“继续这个”,Dify 能识别 SN-003。
|
||||
- 最近失败任务为 SN-002,用户说“上一次失败的是哪个”,Dify 能回答 SN-002。
|
||||
- 存在两个异常任务,用户说“处理那个异常”,Dify 必须追问。
|
||||
- 用户先切换 focus 到 SN-004,再说“重新匹配这票”,工具调用必须带 SN-004。
|
||||
- 用户问“昨天那个批次”,Dify 不把它当成当前 batch,必须走历史查询或追问。
|
||||
- 后端状态已变化时,状态推进 API 拒绝旧动作,Dify 能解释最新状态。
|
||||
|
||||
## 10. 审计与日志口径
|
||||
|
||||
启用 `agent_runtime_context` 后,HXOPS 与 Dify 的记录不会完全一致。这是设计内的不一致,不是缺陷。
|
||||
|
||||
原因是:
|
||||
|
||||
- HXOPS 记录用户真实交互和业务状态。
|
||||
- Dify 记录模型参与过的运行过程。
|
||||
- HXOPS 本地按钮、工作台动作、后台 worker 推进,不一定会进入 Dify conversation memory。
|
||||
|
||||
因此,审计口径必须明确:
|
||||
|
||||
```text
|
||||
HXOPS ChatLog / BusinessEvent / TaskEvent = 审计事实源
|
||||
Dify conversation / run log = 模型执行日志
|
||||
```
|
||||
|
||||
### 10.1 三类日志
|
||||
|
||||
#### ChatLog
|
||||
|
||||
面向用户可见的对话历史:
|
||||
|
||||
- 用户自然语言输入。
|
||||
- HXOPS 本地生成的用户动作展示。
|
||||
- Dify 回复。
|
||||
- HXOPS 本地结果消息。
|
||||
- 表单、卡片、结果卡等可见消息。
|
||||
|
||||
ChatLog 解决“用户在界面上看到了什么、做了什么”的问题。
|
||||
|
||||
#### BusinessEvent / TaskEvent
|
||||
|
||||
面向业务审计和状态机追踪:
|
||||
|
||||
- 谁在什么时候确认、驳回、重试、切换任务。
|
||||
- 动作作用于哪个 `task_no` / `batch_no`。
|
||||
- 状态变化前后是什么。
|
||||
- 动作成功、失败还是被状态机拒绝。
|
||||
- shortage、解析失败、上传失败等阻断原因。
|
||||
|
||||
BusinessEvent / TaskEvent 是最重要的审计事实源。
|
||||
|
||||
#### AgentRunLog
|
||||
|
||||
面向模型调用审计:
|
||||
|
||||
- 本次 Dify run 的 `request_id`。
|
||||
- `agent_runtime_context.context_id`。
|
||||
- HXOPS `session_id` / `parent_session_id`。
|
||||
- Dify conversation_id / run_id / message_id。
|
||||
- input query。
|
||||
- output answer。
|
||||
- tool calls。
|
||||
- 错误信息和耗时。
|
||||
|
||||
AgentRunLog 解决“模型当时拿到了什么上下文、做了什么输出”的问题。
|
||||
|
||||
### 10.2 关联键
|
||||
|
||||
三类日志不要求内容完全相同,但必须可关联。建议统一记录以下键:
|
||||
|
||||
```text
|
||||
session_id
|
||||
parent_session_id
|
||||
request_id
|
||||
context_id
|
||||
agent_code
|
||||
batch_no
|
||||
task_no
|
||||
chat_log_id
|
||||
business_event_id
|
||||
dify_conversation_id
|
||||
dify_run_id
|
||||
```
|
||||
|
||||
按钮点击没有进入 Dify memory 时,审计链路应是:
|
||||
|
||||
```text
|
||||
用户点击按钮
|
||||
↓
|
||||
HXOPS ChatLog 记录可见动作
|
||||
↓
|
||||
BusinessEvent / TaskEvent 记录动作和状态变化
|
||||
↓
|
||||
下一次 Dify run 的 agent_runtime_context 带 recent_activity_summary / reference_context
|
||||
↓
|
||||
AgentRunLog 记录 context_id 与 Dify run_id
|
||||
```
|
||||
|
||||
这样可以清楚证明:用户做过什么、业务状态如何变化、Dify 后续是在什么上下文下回答的。
|
||||
|
||||
### 10.3 不追求 Dify 与 HXOPS 日志完全一致
|
||||
|
||||
不建议为了“记录一致”而把所有 HXOPS 本地动作都同步成 Dify 用户消息。这样会带来:
|
||||
|
||||
- Dify memory 噪音增加。
|
||||
- 多文件批次上下文膨胀。
|
||||
- UI 细节污染业务语义。
|
||||
- Dify conversation 与 HXOPS 状态仍然可能因为并发而漂移。
|
||||
|
||||
正确做法是:
|
||||
|
||||
- 原始用户交互和业务事件由 HXOPS 记录。
|
||||
- Dify 每轮读取 HXOPS 生成的运行态上下文。
|
||||
- 审计时以 HXOPS 为主,Dify run log 为辅。
|
||||
|
||||
## 11. 平台通用扩展方式
|
||||
|
||||
`agent_runtime_context` 必须作为平台能力建设,而不是 shipping 专用能力。
|
||||
|
||||
平台层统一负责:
|
||||
|
||||
- context schema。
|
||||
- context_id / request_id / session_id。
|
||||
- parse API。
|
||||
- allowed_parse_paths。
|
||||
- reference_context。
|
||||
- recent_activity_summary。
|
||||
- risk_policy。
|
||||
- AgentRunLog。
|
||||
- Dify inputs 注入。
|
||||
- 通用鉴权和审计。
|
||||
|
||||
业务 Agent 只负责实现自己的 domain adapter。
|
||||
|
||||
### 11.1 通用结构
|
||||
|
||||
```json
|
||||
{
|
||||
"schema_version": "1",
|
||||
"context_id": "ctx_xxx",
|
||||
"agent_code": "shipping_notice",
|
||||
"scope": "chat_turn",
|
||||
"platform": {
|
||||
"session_id": "conv_xxx",
|
||||
"parent_session_id": "conv_xxx",
|
||||
"request_id": "req_xxx",
|
||||
"locale": "zh-CN"
|
||||
},
|
||||
"refs": {},
|
||||
"reference_context": {},
|
||||
"recent_activity_summary": "",
|
||||
"domain": {}
|
||||
}
|
||||
```
|
||||
|
||||
### 11.2 Domain Adapter
|
||||
|
||||
每个业务 Agent 提供:
|
||||
|
||||
```text
|
||||
build_domain_context(agent_code, session_id, refs)
|
||||
build_reference_entities(...)
|
||||
build_recent_activity_summary(...)
|
||||
allowed_parse_paths
|
||||
risk_policy
|
||||
```
|
||||
|
||||
示例:
|
||||
|
||||
```text
|
||||
agent_runtime_context engine
|
||||
├─ shipping_notice adapter
|
||||
├─ leave adapter
|
||||
├─ file_check adapter
|
||||
├─ training adapter
|
||||
└─ future agent adapters
|
||||
```
|
||||
|
||||
### 11.3 allowed_parse_paths
|
||||
|
||||
`allowed_parse_paths` 定义 Dify 通过 parse API 能读取哪些字段。
|
||||
|
||||
它管的是:
|
||||
|
||||
```text
|
||||
Dify 能看什么
|
||||
```
|
||||
|
||||
目的:
|
||||
|
||||
- 防止 Dify 任意遍历 JSON。
|
||||
- 防止敏感字段泄露。
|
||||
- 防止字段路径漂移。
|
||||
- 让工具契约稳定可测。
|
||||
|
||||
货代发货第一阶段可允许:
|
||||
|
||||
```text
|
||||
schema_version
|
||||
context_id
|
||||
agent_code
|
||||
scope
|
||||
platform.session_id
|
||||
platform.parent_session_id
|
||||
platform.request_id
|
||||
platform.locale
|
||||
refs.batch_no
|
||||
refs.task_no
|
||||
refs.run_purpose
|
||||
refs.file_name
|
||||
domain.type
|
||||
domain.summary
|
||||
domain.state_hint.current_step
|
||||
domain.state_hint.status
|
||||
domain.state_hint.focus_task_no
|
||||
reference_context.current_focus.id
|
||||
reference_context.last_action_target.id
|
||||
reference_context.last_failed_target.id
|
||||
recent_activity_summary
|
||||
```
|
||||
|
||||
### 11.4 risk_policy
|
||||
|
||||
`risk_policy` 定义不同动作在模糊指代和状态推进时的处理规则。
|
||||
|
||||
它管的是:
|
||||
|
||||
```text
|
||||
Dify 能做什么
|
||||
```
|
||||
|
||||
示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"query_status": {
|
||||
"risk": "low",
|
||||
"allow_default_focus": true
|
||||
},
|
||||
"switch_focus_task": {
|
||||
"risk": "medium",
|
||||
"require_unique_candidate": true
|
||||
},
|
||||
"submit_decision": {
|
||||
"risk": "high",
|
||||
"require_explicit_task_no": true,
|
||||
"require_state_machine_check": true
|
||||
},
|
||||
"generate_excel": {
|
||||
"risk": "high",
|
||||
"require_explicit_task_no": true,
|
||||
"require_state_machine_check": true,
|
||||
"forbidden_when": ["shortage_blocked"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 12. 与轻量工作台的关系
|
||||
|
||||
`agent_runtime_context` 解决的是“Dify 每次 run 知道当前现场”的问题。
|
||||
|
||||
轻量工作台解决的是“用户看得见批次和任务状态”的问题。
|
||||
|
||||
二者都以 HXOPS DB 为事实源:
|
||||
|
||||
```text
|
||||
HXOPS DB
|
||||
├─ 生成 agent_runtime_context → 给 Dify
|
||||
└─ 生成 batch/task workspace view → 给前端
|
||||
```
|
||||
|
||||
不要让 Dify memory 反向驱动工作台状态,也不要让工作台状态依赖 Dify 自己的 conversation history。
|
||||
|
||||
## 13. 第一阶段执行清单
|
||||
|
||||
### 13.1 后端
|
||||
|
||||
- 新增平台级 builder:
|
||||
- `backend/app/services/agent_runtime_context/builder.py`
|
||||
- `backend/app/services/agent_runtime_context/parser.py`
|
||||
- `backend/app/services/agent_runtime_context/policy.py`
|
||||
- `backend/app/services/agent_runtime_context/audit.py`
|
||||
- 新增 shipping adapter:
|
||||
- `backend/app/services/shipping_notice/runtime_context.py`
|
||||
- 将 `build_dify_chat_inputs()` 输出调整为:
|
||||
- `agent_runtime_context` JSON 字符串
|
||||
- 新增 Dify 工具 API:
|
||||
- `POST /api/agent-runtime-context/tools/parse`
|
||||
- context builder 增加:
|
||||
- `reference_context`
|
||||
- `recent_activity_summary`
|
||||
- 增加 AgentRunLog 或等价运行日志,记录 `context_id` 与 Dify run 的关联。
|
||||
- 保留工具鉴权:
|
||||
- `X-Integration-Key` 或现有 Tool API Key 机制
|
||||
|
||||
### 13.2 Dify
|
||||
|
||||
- Start 节点新增:
|
||||
- `agent_runtime_context`
|
||||
- Agent/LLM Prompt 显式引用该变量。
|
||||
- 新增 OpenAPI Tool:
|
||||
- `parse_agent_runtime_context`
|
||||
- 提示词中要求:
|
||||
- 读取字段时调用 parse tool。
|
||||
- 推进状态时调用 shipping 业务 tool。
|
||||
- 模糊指代必须参考 `reference_context`,多候选时追问。
|
||||
|
||||
### 13.3 前端
|
||||
|
||||
第一阶段不要求大改 UI。只需确保:
|
||||
|
||||
- 用户动作带 `task_no`。
|
||||
- 当前 focus task 能被后端 context builder 识别。
|
||||
- Chat 中展示的本地消息仍按 `task_no` 锚定。
|
||||
- 切换 focus task、点击关键动作时写入可被 context builder 使用的事件或 payload。
|
||||
|
||||
## 14. 验收标准
|
||||
|
||||
第一阶段完成后,应满足:
|
||||
|
||||
- 每次 Dify shipping run 都能看到 `agent_runtime_context`。
|
||||
- 批量 8 文件时,每个 run 的 `task_no` 不同,`batch_no` 和 `parent_session_id` 一致。
|
||||
- Dify 不需要代码节点即可通过 parse API 获取字段。
|
||||
- `agent_runtime_context` 中不再混入无效 prompt 指令字段。
|
||||
- 多任务批次中不再依赖 `conversation_id` 猜最近任务。
|
||||
- 用户点击 HXOPS 本地按钮后,后续 Dify 对话能通过新 context 获得当前现场。
|
||||
- 用户使用“这个、那个、刚才、上一次”等模糊表达时,Dify 能基于 `reference_context` 解析或追问。
|
||||
- 审计时可以从 HXOPS ChatLog / BusinessEvent / AgentRunLog 串起一次完整链路。
|
||||
- 业务推进仍由 HXOPS 工具和状态机判定。
|
||||
|
||||
## 15. 非目标
|
||||
|
||||
第一阶段不解决以下问题:
|
||||
|
||||
- 不重写 Dify Chatflow 编排。
|
||||
- 不把所有 ChatLog 历史注入 Dify。
|
||||
- 不做长期 LLM memory 存储。
|
||||
- 不让 Dify 直接维护业务状态。
|
||||
- 不把轻量工作台变成第二条主流程。
|
||||
- 不保证所有 UI 点击原始流水进入 Dify memory;只保证关键业务结果进入 runtime context。
|
||||
- 不要求 Dify conversation log 与 HXOPS ChatLog 完全一致。
|
||||
|
||||
## 16. 一句话总结
|
||||
|
||||
`agent_runtime_context` 是 HXOPS 平台给 Dify 的统一运行态现场说明。它让每次 Dify run 都知道自己属于哪个 HXOPS 会话、批次、任务和执行目的;通过 `reference_context` 治理“这个、那个、刚才、上一次”等模糊指代;字段解析由 HXOPS 标准 parse API 提供;审计以 HXOPS ChatLog、BusinessEvent 和 AgentRunLog 为主;业务事实仍以 HXOPS DB、状态机和事件表为准。
|
||||
@@ -26,8 +26,12 @@ export const deleteAllChatSessions = (agentId: number) =>
|
||||
export const deleteChatSession = (conversationId: string, agentId: number) =>
|
||||
requestJson(`/api/chat/sessions/${conversationId}?agent_id=${agentId}`, { method: 'DELETE', ...auth() });
|
||||
|
||||
export const listChatMessages = (conversationId: string, agentId: number) =>
|
||||
requestJson<ChatMessage[]>(`/api/chat/messages?conversation_id=${conversationId}&agent_id=${agentId}`, auth());
|
||||
export const listChatMessages = async (conversationId: string, agentId: number) => {
|
||||
const messages = await requestJson<ChatMessage[]>(`/api/chat/messages?conversation_id=${conversationId}&agent_id=${agentId}`, auth());
|
||||
return Array.isArray(messages)
|
||||
? messages.filter((message) => message?.type !== 'shipping-parse-review')
|
||||
: messages;
|
||||
};
|
||||
|
||||
export const saveLocalChatMessage = (payload: Record<string, unknown>) =>
|
||||
requestJson<{ conversation_id?: string; chat_log_id?: number }>('/api/chat/messages/local', {
|
||||
|
||||
@@ -166,7 +166,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const retryingShippingPendingTasks = ref(false);
|
||||
const activeShippingTaskDetail = ref<ShippingTaskDetail | null>(null);
|
||||
const shippingFocusReason = ref('');
|
||||
const shippingConversationTaskIdCache = ref<Record<string, string>>({});
|
||||
const shippingInventorySchemaPreviewCache = ref<Record<string, unknown>>({});
|
||||
const autoResumedShippingTasks = ref<Record<string, boolean>>({});
|
||||
const lastConversationSyncKey = ref('');
|
||||
@@ -320,7 +319,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
shippingWorkspaceOpen.value = false;
|
||||
retryingShippingPendingTasks.value = false;
|
||||
activeShippingTaskDetail.value = null;
|
||||
shippingConversationTaskIdCache.value = {};
|
||||
shippingInventorySchemaPreviewCache.value = {};
|
||||
lastConversationSyncKey.value = '';
|
||||
};
|
||||
@@ -443,7 +441,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
history,
|
||||
resolvedShippingTaskId,
|
||||
shippingTaskIdFromQuery,
|
||||
shippingConversationTaskIdCache,
|
||||
getActiveBatchTaskId,
|
||||
});
|
||||
|
||||
const { pushShippingLocalUserMessage, pushShippingLocalAssistantMessage } = createShippingLocalMessages({
|
||||
|
||||
@@ -181,6 +181,7 @@ function downloadInlineFile(file: InlineDownloadFile): void {
|
||||
export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
const shouldRenderMessage = (msgItem: ChatMessage): boolean => {
|
||||
if (msgItem?.role === 'user') return true;
|
||||
if (msgItem?.type === 'shipping-parse-review') return false;
|
||||
if (msgItem?.type === 'leave-form' || msgItem?.type === 'leave-confirmation' || msgItem?.type === 'leave-result') return true;
|
||||
const content = (msgItem?.content || '').trim();
|
||||
if (content) return true;
|
||||
|
||||
@@ -47,4 +47,22 @@ describe('shippingText', () => {
|
||||
expect(result).toContain('1. SKU A001');
|
||||
expect(result).toContain('2. SKU B002');
|
||||
});
|
||||
|
||||
it('removes plain action menus generated in assistant text', () => {
|
||||
// 关键断言:即使 Dify 没有用 1/2/3 编号,只要正文手写按钮菜单,也不能露给用户。
|
||||
const result = sanitizeShippingConversationText(
|
||||
[
|
||||
'请使用下方按钮进行确认操作:',
|
||||
'确认 — 解析无误,进入下一步库存上传与匹配',
|
||||
'驳回 — 解析有误,终止当前任务',
|
||||
'重新解析 — 重新解析发货通知原始文件',
|
||||
].join('\n'),
|
||||
true,
|
||||
);
|
||||
|
||||
expect(result).not.toContain('请使用下方按钮');
|
||||
expect(result).not.toContain('确认 —');
|
||||
expect(result).not.toContain('驳回 —');
|
||||
expect(result).not.toContain('重新解析 —');
|
||||
});
|
||||
});
|
||||
@@ -28,7 +28,10 @@ const isShippingActionListContextLine = (line: string) =>
|
||||
/(?:请选择操作|选择操作|操作选项|下方按钮|按钮继续操作|以下.*方式|任一方式|库存上传|提供当前库存|提供.*库存数据)/.test(line);
|
||||
|
||||
const isShippingActionChoiceLine = (line: string) =>
|
||||
/(?:选择库存文件|上传库存|粘贴库存|重试\s*RPA|修改映射|确认字段|继续处理|查看卡点|返回修订|重新匹配|重试当前步骤|切换为当前任务)/i.test(line);
|
||||
/(?:选择库存文件|上传库存|粘贴库存|重试\s*RPA|修改映射|确认字段|继续处理|查看卡点|返回修订|重新匹配|重试当前步骤|切换为当前任务|确认|驳回|重新解析)/i.test(line);
|
||||
|
||||
const isPlainActionMenuLine = (line: string) =>
|
||||
/^\s*(?:[-*]\s*)?(?:\*\*)?(?:确认|驳回|重新解析|更正映射|重新匹配|继续处理|重试当前步骤|选择库存文件|上传库存|粘贴库存)(?:\*\*)?\s*(?:[-—-::]|$)/.test(line);
|
||||
|
||||
/**
|
||||
* 移除 Agent 正文里重复描述按钮的 1/2/3 编号动作列表。
|
||||
@@ -95,6 +98,39 @@ export function stripShippingRedundantNumberedActionList(text: string): string {
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除 Agent 正文中手写的操作菜单段落。
|
||||
*
|
||||
* 核心逻辑:结构化按钮已经由系统渲染,正文里再写“请使用下方按钮/确认/驳回/重新解析”
|
||||
* 会形成两套入口。只删除明确处在按钮/操作上下文附近的菜单行,避免误删普通业务说明。
|
||||
*/
|
||||
export function stripShippingPlainActionMenu(text: string): string {
|
||||
const lines = String(text || '').split('\n');
|
||||
const remove = new Set<number>();
|
||||
|
||||
lines.forEach((line, index) => {
|
||||
if (!isPlainActionMenuLine(line)) return;
|
||||
const nearby = lines.slice(Math.max(0, index - 4), Math.min(lines.length, index + 4));
|
||||
const hasContext = nearby.some((item) => isShippingActionListContextLine(item) || /(?:按钮|确认操作|进行确认操作|操作$)/.test(item));
|
||||
if (!hasContext) return;
|
||||
remove.add(index);
|
||||
for (let before = index - 1; before >= 0 && before >= index - 4; before -= 1) {
|
||||
const prev = lines[before] || '';
|
||||
if (!prev.trim() || isShippingActionListContextLine(prev) || /(?:按钮|确认操作|进行确认操作|操作$)/.test(prev)) {
|
||||
remove.add(before);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
return lines
|
||||
.filter((_, index) => !remove.has(index))
|
||||
.join('\n')
|
||||
.replace(/\n{3,}/g, '\n\n')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据后端 action_buttons 移除 Agent 正文中重复生成的编号操作列表。
|
||||
*
|
||||
@@ -213,7 +249,7 @@ export function sanitizeShippingConversationText(text: string, enabled: boolean)
|
||||
result = result.replace(quoted, '');
|
||||
result = result.replace(new RegExp(`\`${token}\``, 'gi'), '');
|
||||
}
|
||||
return stripShippingRedundantNumberedActionList(result.replace(/\n{3,}/g, '\n\n').trim());
|
||||
return stripShippingPlainActionMenu(stripShippingRedundantNumberedActionList(result.replace(/\n{3,}/g, '\n\n').trim()));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -92,7 +92,7 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||||
};
|
||||
ctx.messages.value.push(userMsg, assistantMsg);
|
||||
await ctx.saveLocalMessageToBackend(userMsg, userText);
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg, userText);
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg);
|
||||
if (result.message && !ctx.isShippingNoticeAgent.value) {
|
||||
ctx.msg.success(result.message);
|
||||
}
|
||||
@@ -149,7 +149,7 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||||
if (shouldAppendUser) {
|
||||
await ctx.saveLocalMessageToBackend(userMsg, userText);
|
||||
}
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg, userText);
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg);
|
||||
void ctx.refreshShippingActions();
|
||||
return true;
|
||||
} catch (e: unknown) {
|
||||
|
||||
@@ -166,7 +166,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
};
|
||||
ctx.messages.value.push(userMsg, assistantMsg);
|
||||
await ctx.saveLocalMessageToBackend(userMsg, action.message || '生成发货 Excel');
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg, action.message || '生成发货 Excel');
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg);
|
||||
void ctx.refreshShippingActions();
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '生成发货 Excel 失败';
|
||||
@@ -201,7 +201,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
};
|
||||
ctx.messages.value.push(userMsg, assistantMsg);
|
||||
await ctx.saveLocalMessageToBackend(userMsg, userText);
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg, userText);
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg);
|
||||
void ctx.refreshShippingActions();
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeRetryUploadFailed');
|
||||
@@ -246,7 +246,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
};
|
||||
ctx.messages.value.push(userMsg, assistantMsg);
|
||||
await ctx.saveLocalMessageToBackend(userMsg, userText);
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg, userText);
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg);
|
||||
void ctx.refreshShippingActions();
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '确认库存源失败';
|
||||
@@ -304,7 +304,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
};
|
||||
ctx.messages.value.push(userMsg, assistantMsg);
|
||||
await ctx.saveLocalMessageToBackend(userMsg, action.message || '匹配库存');
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg, action.message || '匹配库存');
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg);
|
||||
void ctx.refreshShippingActions();
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '匹配库存失败';
|
||||
|
||||
@@ -6,8 +6,6 @@
|
||||
*/
|
||||
import {
|
||||
addWorkspaceShippingNoticeLine,
|
||||
getShippingChatActions,
|
||||
getWorkspaceShippingTask,
|
||||
removeWorkspaceShippingNoticeLine,
|
||||
updateWorkspaceShippingNoticeFields,
|
||||
updateWorkspaceShippingNoticeLine,
|
||||
@@ -16,7 +14,6 @@ import {
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { getShippingParseReviewPayload } from './shippingParseReview';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ShippingParseReviewPayload } from '../types/shipping.types';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
export interface ShippingParseReviewContext {
|
||||
@@ -28,27 +25,6 @@ export interface ShippingParseReviewContext {
|
||||
msg: { warning: (text: string) => void };
|
||||
}
|
||||
|
||||
/** 由任务详情与 checkpoint 构建 parse_review 卡片 payload。 */
|
||||
function buildParseReviewPayload(
|
||||
taskId: string,
|
||||
detail: Awaited<ReturnType<typeof getWorkspaceShippingTask>>,
|
||||
checkpoint: string,
|
||||
): ShippingParseReviewPayload {
|
||||
return {
|
||||
taskId,
|
||||
checkpoint,
|
||||
header: {
|
||||
customer_name: detail.customer_name ?? null,
|
||||
customer_code: detail.customer_code ?? null,
|
||||
ship_to: detail.ship_to ?? null,
|
||||
po_number: detail.po_number ?? null,
|
||||
required_date: detail.required_date ?? null,
|
||||
},
|
||||
lines: Array.isArray(detail.lines) ? detail.lines : [],
|
||||
saving: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建发货通知 parse review 卡片处理器。
|
||||
*
|
||||
@@ -70,48 +46,12 @@ export function createShippingParseReviewHandlers(ctx: ShippingParseReviewContex
|
||||
}
|
||||
};
|
||||
|
||||
const upsertParseReviewMessage = async (payload: ShippingParseReviewPayload) => {
|
||||
const normalized = String(payload.taskId || '').trim().toUpperCase();
|
||||
const existing = ctx.messages.value.find((msg) => {
|
||||
const current = getShippingParseReviewPayload(msg);
|
||||
return current?.taskId?.trim().toUpperCase() === normalized;
|
||||
});
|
||||
if (existing) {
|
||||
existing.content = `请确认或修订以下解析结果。\n任务编号:${normalized}`;
|
||||
existing.payload = payload;
|
||||
existing.local_only = true;
|
||||
return;
|
||||
}
|
||||
const reviewMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'shipping-parse-review',
|
||||
content: `请确认或修订以下解析结果。\n任务编号:${normalized}`,
|
||||
payload,
|
||||
local_id: ctx.newLocalMessageId('shipping-parse-review'),
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(reviewMsg);
|
||||
await ctx.saveLocalMessageToBackend(reviewMsg);
|
||||
};
|
||||
|
||||
const syncShippingParseReviewCard = async (taskId?: string): Promise<boolean> => {
|
||||
const normalized = String(taskId || ctx.resolvedShippingTaskId.value || '').trim().toUpperCase();
|
||||
if (!normalized) return false;
|
||||
try {
|
||||
const [detail, actions] = await Promise.all([
|
||||
getWorkspaceShippingTask(normalized),
|
||||
getShippingChatActions(normalized),
|
||||
]);
|
||||
const checkpoint = String(actions.checkpoint || '').trim();
|
||||
if (checkpoint !== 'parse_review') {
|
||||
removeParseReviewMessageForTask(normalized);
|
||||
return false;
|
||||
}
|
||||
await upsertParseReviewMessage(buildParseReviewPayload(normalized, detail, checkpoint));
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
// 解析复核表单不再作为聊天历史消息展示;当前步骤操作统一放到轻量工作台/动作按钮中。
|
||||
removeParseReviewMessageForTask(normalized);
|
||||
return false;
|
||||
};
|
||||
|
||||
const updateShippingParseReviewHeader = async (
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* useChatShippingRefresh.spec.ts
|
||||
* 用途:验证发货动作按钮刷新时的任务定位优先级,避免按 conversation 猜任务导致按钮绑错票。
|
||||
* 依赖:vitest、useChatShippingRefresh 纯函数导出。
|
||||
* 逻辑:只覆盖任务编号解析优先级,不触碰 Vue 组件或网络请求。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { resolvePreferredShippingTaskId } from './useChatShippingRefresh';
|
||||
|
||||
describe('useChatShippingRefresh', () => {
|
||||
it('prefers current batch focus task over message and history fallbacks', () => {
|
||||
expect(resolvePreferredShippingTaskId({
|
||||
batchTaskId: 'sn-batch-001',
|
||||
messageTaskId: 'sn-message-001',
|
||||
resolvedTaskId: 'sn-resolved-001',
|
||||
queryTaskId: 'sn-query-001',
|
||||
historyTaskId: 'sn-history-001',
|
||||
})).toBe('SN-BATCH-001');
|
||||
});
|
||||
|
||||
it('returns empty string when no explicit task anchor is available', () => {
|
||||
expect(resolvePreferredShippingTaskId({
|
||||
batchTaskId: '',
|
||||
messageTaskId: '',
|
||||
resolvedTaskId: '',
|
||||
queryTaskId: '',
|
||||
historyTaskId: '',
|
||||
})).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -4,14 +4,12 @@
|
||||
* 依赖:shipping.api、shippingMenu、shippingTaskId、shippingNoticeActions 常量、chat.types。
|
||||
* 逻辑:由 useChatShipping 调用本文件;本文件根据当前 taskId 拉取动作配置并回写到 messages[].shipping_actions。
|
||||
*/
|
||||
import {
|
||||
getShippingChatActions,
|
||||
listWorkspaceShippingTasks,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { getShippingChatActions } from '@/features/chat/api/shipping.api';
|
||||
import { SHIPPING_TERMINAL_CHECKPOINTS } from '@/constants/shippingNoticeActions';
|
||||
import { SHIPPING_TASK_ID_RE } from '../constants/shipping';
|
||||
import { findLatestShippingTaskId } from './shippingTaskId';
|
||||
import { resolveShippingActionButtons } from './shippingMenu';
|
||||
import { stripShippingPlainActionMenu } from './shippingText';
|
||||
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
|
||||
import type { ShippingActionButton } from '../types/shipping.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
@@ -24,7 +22,32 @@ export interface ShippingRefreshContext {
|
||||
history: Ref<ChatSessionItem[]>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
shippingTaskIdFromQuery: ComputedRef<string>;
|
||||
shippingConversationTaskIdCache: Ref<Record<string, string>>;
|
||||
getActiveBatchTaskId: () => string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析当前聊天页最可靠的发货任务编号。
|
||||
*
|
||||
* 核心逻辑:优先使用批次当前焦点任务,其次才回退到消息内嵌任务号、已解析状态和路由参数;
|
||||
* 禁止再按 conversation 扫任务列表“猜”一票,避免多票会话把动作按钮挂错任务。
|
||||
* @param params - 当前聊天页中可用的任务定位线索
|
||||
* @returns 可信的任务编号;无法明确定位时返回空字符串
|
||||
*/
|
||||
export function resolvePreferredShippingTaskId(params: {
|
||||
batchTaskId?: string | null;
|
||||
messageTaskId?: string | null;
|
||||
resolvedTaskId?: string | null;
|
||||
queryTaskId?: string | null;
|
||||
historyTaskId?: string | null;
|
||||
}) {
|
||||
return String(
|
||||
params.batchTaskId
|
||||
|| params.messageTaskId
|
||||
|| params.resolvedTaskId
|
||||
|| params.queryTaskId
|
||||
|| params.historyTaskId
|
||||
|| '',
|
||||
).trim().toUpperCase();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -59,28 +82,13 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
const match = title.match(SHIPPING_TASK_ID_RE);
|
||||
return match?.[0] ? match[0].toUpperCase() : '';
|
||||
})();
|
||||
let taskId = findLatestShippingTaskId(msgs)
|
||||
|| ctx.resolvedShippingTaskId.value
|
||||
|| ctx.shippingTaskIdFromQuery.value
|
||||
|| historyTaskId;
|
||||
if (!taskId && cid && !ctx.isThinking.value) {
|
||||
const cached = ctx.shippingConversationTaskIdCache.value[cid];
|
||||
if (cached) {
|
||||
taskId = cached;
|
||||
} else {
|
||||
try {
|
||||
const rows = await listWorkspaceShippingTasks({ limit: 500 });
|
||||
const hit = rows.find((row) => String(row.conversation_id || '') === cid);
|
||||
const taskNo = hit?.task_no ? String(hit.task_no).trim().toUpperCase() : '';
|
||||
if (taskNo) {
|
||||
ctx.shippingConversationTaskIdCache.value = { ...ctx.shippingConversationTaskIdCache.value, [cid]: taskNo };
|
||||
taskId = taskNo;
|
||||
}
|
||||
} catch {
|
||||
// fall back to structured directive buttons embedded in the message
|
||||
}
|
||||
}
|
||||
}
|
||||
const taskId = resolvePreferredShippingTaskId({
|
||||
batchTaskId: ctx.getActiveBatchTaskId(),
|
||||
messageTaskId: findLatestShippingTaskId(msgs),
|
||||
resolvedTaskId: ctx.resolvedShippingTaskId.value,
|
||||
queryTaskId: ctx.shippingTaskIdFromQuery.value,
|
||||
historyTaskId,
|
||||
});
|
||||
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
|
||||
let lastOpenAssistantIndex = -1;
|
||||
for (let i = msgs.length - 1; i >= 0; i -= 1) {
|
||||
@@ -102,11 +110,9 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
if (targetAssistantIndex >= 0) {
|
||||
const target = msgs[targetAssistantIndex] as ChatMessage & { shipping_actions?: ShippingActionButton[] };
|
||||
const resolved = resolveShippingActionButtons(String(target.content || ''), null);
|
||||
if (resolved.cleanedText !== String(target.content || '').trim()) {
|
||||
target.content = resolved.cleanedText;
|
||||
}
|
||||
if (resolved.buttons.length && !target.shipping_actions?.length) {
|
||||
target.shipping_actions = resolved.buttons;
|
||||
const cleanedText = stripShippingPlainActionMenu(resolved.cleanedText);
|
||||
if (cleanedText !== String(target.content || '').trim()) {
|
||||
target.content = cleanedText;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,16 +164,20 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
apiResolved ? (apiButtons ?? []) : null,
|
||||
{ apiResolved },
|
||||
);
|
||||
if (resolved.fromDirective || resolved.cleanedText !== String(chatMsg.content || '').trim()) {
|
||||
chatMsg.content = resolved.cleanedText;
|
||||
const cleanedText = stripShippingPlainActionMenu(resolved.cleanedText);
|
||||
if (resolved.fromDirective || cleanedText !== String(chatMsg.content || '').trim()) {
|
||||
chatMsg.content = cleanedText;
|
||||
}
|
||||
buttons = resolved.buttons;
|
||||
} else if (!apiResolved) {
|
||||
const resolved = resolveShippingActionButtons(String(chatMsg.content || ''), null);
|
||||
if (resolved.fromDirective) {
|
||||
chatMsg.content = resolved.cleanedText;
|
||||
const cleanedText = stripShippingPlainActionMenu(resolved.cleanedText);
|
||||
if (resolved.fromDirective || cleanedText !== String(chatMsg.content || '').trim()) {
|
||||
chatMsg.content = cleanedText;
|
||||
}
|
||||
buttons = resolved.buttons;
|
||||
} else {
|
||||
chatMsg.content = stripShippingPlainActionMenu(String(chatMsg.content || ''));
|
||||
}
|
||||
if (chatMsg.type === 'shipping-match-result' && chatMsg.payload && typeof chatMsg.payload === 'object') {
|
||||
(chatMsg.payload as { action_buttons?: ShippingActionButton[] }).action_buttons = buttons;
|
||||
|
||||
Reference in new issue
Block a user