mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-25 05:49:20 +08:00
Compare commits
14
Commits
master
...
e136084794
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e136084794 | ||
|
|
92b6026b48 | ||
|
|
370ead39a1 | ||
|
|
5567b6d281 | ||
|
|
85bac4f710 | ||
|
|
13a2bd9274 | ||
|
|
883a1d0cfe | ||
|
|
67d01c678a | ||
|
|
a72a43cffc | ||
|
|
0b460e22b0 | ||
|
|
41f022bd63 | ||
|
|
71eca63461 | ||
|
|
d20c6a1302 | ||
|
|
9c2c1ed061 |
+22
-1
@@ -125,6 +125,7 @@ apps/agent/
|
|||||||
| `summary` | 会话滚动摘要(可选) |
|
| `summary` | 会话滚动摘要(可选) |
|
||||||
| `llm_provider_id` | 会话选用的提供商 id |
|
| `llm_provider_id` | 会话选用的提供商 id |
|
||||||
| `llm_model` | 会话选用的模型 id;与 provider 一起消歧;空则对话时回落公司默认并回写 |
|
| `llm_model` | 会话选用的模型 id;与 provider 一起消歧;空则对话时回落公司默认并回写 |
|
||||||
|
| `llm_response_chain` | 可选;Responses 续链 `{provider_id,model,previous_response_id}` |
|
||||||
| `created_at`, `updated_at`, `last_message_at` | |
|
| `created_at`, `updated_at`, `last_message_at` | |
|
||||||
|
|
||||||
唯一索引:`(company_id, user_id, thread_id)`
|
唯一索引:`(company_id, user_id, thread_id)`
|
||||||
@@ -225,6 +226,7 @@ Agent 内部:`GET /api/internal/agent/llm-runtime?companyId=&providerId=&model
|
|||||||
| GET | `/sessions` | 当前用户会话列表(含 `llmProviderId` / `llmModel`) |
|
| GET | `/sessions` | 当前用户会话列表(含 `llmProviderId` / `llmModel`) |
|
||||||
| POST | `/sessions` | 新建会话(可带选型;缺省写公司默认) |
|
| POST | `/sessions` | 新建会话(可带选型;缺省写公司默认) |
|
||||||
| PATCH | `/sessions/{thread_id}` | 改标题;或同时改 `llmProviderId`+`llmModel` |
|
| PATCH | `/sessions/{thread_id}` | 改标题;或同时改 `llmProviderId`+`llmModel` |
|
||||||
|
| DELETE | `/sessions/{thread_id}` | 软删会话(`status=deleted`),级联软删该线程消息 |
|
||||||
| GET | `/sessions/{thread_id}/messages` | 历史消息(分页/游标) |
|
| GET | `/sessions/{thread_id}/messages` | 历史消息(分页/游标) |
|
||||||
| POST | `/sessions/{thread_id}/chat` | **流式**发消息(SSE);按会话选型解析 runtime |
|
| POST | `/sessions/{thread_id}/chat` | **流式**发消息(SSE);按会话选型解析 runtime |
|
||||||
| GET | `/memories` | 查看自己的记忆条目(可透明) |
|
| GET | `/memories` | 查看自己的记忆条目(可透明) |
|
||||||
@@ -363,6 +365,25 @@ apps/agent/
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 11. 文档维护
|
## 11. Responses API 分期(多提供商)
|
||||||
|
|
||||||
|
原则:**Mongo 仍是对话真相源**;Responses 链(`previous_response_id`)只是同提供商同模型下的加速缓存,切换选型即作废并全量 rebuild。
|
||||||
|
|
||||||
|
### Responses-P0 / P1(已落地)— 运行时探测,不写死主机
|
||||||
|
|
||||||
|
原则:优先新协议;能力靠探测 + Redis 缓存(`agent:llm:cap:*`),按错误回退,不按 OpenAI/DeepSeek 主机写死。
|
||||||
|
|
||||||
|
同轮未产出 token 前的阶梯:
|
||||||
|
|
||||||
|
1. **Responses + `store=true`**(语义证实后;有会话链则只发增量 + `previous_response_id`)
|
||||||
|
2. store 未知:Responses + `store=true` + **Mongo 全量历史**,成功后再做语义探测
|
||||||
|
3. **store 证伪**:先 **无状态 Responses + Mongo 全量**,接口失败再 **Completions + Mongo 全量**
|
||||||
|
4. Responses 端点不可用 → Completions
|
||||||
|
|
||||||
|
成功后写入能力缓存。**`store=true` 认定**:独立语义探测——先让模型记住密钥,再仅用 `previous_response_id`(不带历史)追问;答对才记 true。未证实前禁止只发增量。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. 文档维护
|
||||||
|
|
||||||
落地后同步:根目录 `AGENTS.md` 增加 `apps/agent`;`apps/server/docs/Agent与MCP接入及Boot升级说明.md` 勾选 LangGraph 项并注明多租户 MCP 与租户 LLM Key 约定。
|
落地后同步:根目录 `AGENTS.md` 增加 `apps/agent`;`apps/server/docs/Agent与MCP接入及Boot升级说明.md` 勾选 LangGraph 项并注明多租户 MCP 与租户 LLM Key 约定。
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ uvicorn api.main:app --reload --host 0.0.0.0 --port 8200
|
|||||||
健康检查:`GET http://localhost:8200/health`
|
健康检查:`GET http://localhost:8200/health`
|
||||||
API 前缀:`/api/agent/...`(会话/聊天/记忆;与前端代理 `/api/agent` 对齐)
|
API 前缀:`/api/agent/...`(会话/聊天/记忆;与前端代理 `/api/agent` 对齐)
|
||||||
|
|
||||||
**模型 API 配置不在本服务**:浏览器走 Java `GET/PUT /api/company/agent-llm-settings`(凭证 + 多模型勾选;`POST .../probe-models` 拉目录);Agent 经 Redis `agent:llm:rt:{companyId}` 或内部接口拉**默认模型**明文注入。
|
**模型 API 配置不在本服务**:浏览器走 Java 提供商 CRUD(含 `apiStyle`);Agent 拉 runtime 后**运行时探测** Responses/store,结果缓存 Redis `agent:llm:cap:*`,失败阶梯为 Responses+store → Responses → Completions(见 DESIGN §11)。
|
||||||
|
|
||||||
## 分环境配置
|
## 分环境配置
|
||||||
|
|
||||||
|
|||||||
+14
-3
@@ -19,7 +19,11 @@ from infrastructure.persistence.mongo.repositories import (
|
|||||||
MongoMessageRepository,
|
MongoMessageRepository,
|
||||||
MongoSessionRepository,
|
MongoSessionRepository,
|
||||||
)
|
)
|
||||||
from infrastructure.persistence.redis.cache import RedisLlmRuntimeCache, get_redis
|
from infrastructure.persistence.redis.cache import (
|
||||||
|
RedisLlmProtocolCapabilityCache,
|
||||||
|
RedisLlmRuntimeCache,
|
||||||
|
get_redis,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
async def current_actor(
|
async def current_actor(
|
||||||
@@ -46,7 +50,11 @@ async def session_service(
|
|||||||
llm_svc: LlmRuntimeService = Depends(llm_runtime_service),
|
llm_svc: LlmRuntimeService = Depends(llm_runtime_service),
|
||||||
) -> SessionService:
|
) -> SessionService:
|
||||||
db = await get_db(settings)
|
db = await get_db(settings)
|
||||||
return SessionService(MongoSessionRepository(db), llm_runtime=llm_svc)
|
return SessionService(
|
||||||
|
MongoSessionRepository(db),
|
||||||
|
llm_runtime=llm_svc,
|
||||||
|
messages=MongoMessageRepository(db),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
async def memory_service(settings: Settings = Depends(get_settings)) -> MemoryService:
|
async def memory_service(settings: Settings = Depends(get_settings)) -> MemoryService:
|
||||||
@@ -68,5 +76,8 @@ async def chat_service(
|
|||||||
messages=MongoMessageRepository(db),
|
messages=MongoMessageRepository(db),
|
||||||
llm_runtime=llm_svc,
|
llm_runtime=llm_svc,
|
||||||
memory=mem_svc,
|
memory=mem_svc,
|
||||||
streamer=OpenAICompatibleStreamer(),
|
streamer=OpenAICompatibleStreamer(
|
||||||
|
RedisLlmProtocolCapabilityCache(get_redis(settings)),
|
||||||
|
capability_ttl_seconds=settings.llm_capability_ttl_seconds,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -120,3 +120,17 @@ async def archive_session(
|
|||||||
except LookupError as e:
|
except LookupError as e:
|
||||||
raise HTTPException(status_code=404, detail=str(e)) from e
|
raise HTTPException(status_code=404, detail=str(e)) from e
|
||||||
return ok(_session_vo(s))
|
return ok(_session_vo(s))
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{thread_id}")
|
||||||
|
async def delete_session(
|
||||||
|
thread_id: str,
|
||||||
|
actor: Actor = Depends(current_actor),
|
||||||
|
svc: SessionService = Depends(session_service),
|
||||||
|
):
|
||||||
|
"""软删会话并级联软删消息;列表与聊天不再可见。"""
|
||||||
|
try:
|
||||||
|
s = await svc.delete(actor, thread_id)
|
||||||
|
except LookupError as e:
|
||||||
|
raise HTTPException(status_code=404, detail=str(e)) from e
|
||||||
|
return ok(_session_vo(s))
|
||||||
|
|||||||
@@ -12,7 +12,13 @@ from application.memory_service import MemoryService
|
|||||||
from application.session_service import SessionService
|
from application.session_service import SessionService
|
||||||
from application.system_prompt import build_system_prompt
|
from application.system_prompt import build_system_prompt
|
||||||
from config.settings import Settings
|
from config.settings import Settings
|
||||||
from domain.models import Actor, ChatMessage, MessageRole, StreamEvent
|
from domain.models import (
|
||||||
|
Actor,
|
||||||
|
ChatMessage,
|
||||||
|
LlmResponseChain,
|
||||||
|
MessageRole,
|
||||||
|
StreamEvent,
|
||||||
|
)
|
||||||
from domain.ports import ChatStreamer, MessageRepository, SessionRepository
|
from domain.ports import ChatStreamer, MessageRepository, SessionRepository
|
||||||
|
|
||||||
|
|
||||||
@@ -63,7 +69,6 @@ class ChatService:
|
|||||||
provider_id=session.llm_provider_id,
|
provider_id=session.llm_provider_id,
|
||||||
model=session.llm_model,
|
model=session.llm_model,
|
||||||
)
|
)
|
||||||
# 回落默认或消歧后写回会话,保证列表/选框稳定
|
|
||||||
changed = False
|
changed = False
|
||||||
if session.llm_model != llm.model:
|
if session.llm_model != llm.model:
|
||||||
session.llm_model = llm.model
|
session.llm_model = llm.model
|
||||||
@@ -72,6 +77,13 @@ class ChatService:
|
|||||||
session.llm_provider_id = llm.provider_id
|
session.llm_provider_id = llm.provider_id
|
||||||
changed = True
|
changed = True
|
||||||
if changed:
|
if changed:
|
||||||
|
session.llm_response_chain = None
|
||||||
|
await self._session_repo.update(session)
|
||||||
|
|
||||||
|
# 链是否可用由 streamer 按 store 能力决定;此处只做选型匹配
|
||||||
|
chain_id = _usable_chain_id(session.llm_response_chain, llm)
|
||||||
|
if session.llm_response_chain and not chain_id:
|
||||||
|
session.llm_response_chain = None
|
||||||
await self._session_repo.update(session)
|
await self._session_repo.update(session)
|
||||||
|
|
||||||
just_saved = None
|
just_saved = None
|
||||||
@@ -120,7 +132,6 @@ class ChatService:
|
|||||||
reserve_output_tokens=self._settings.context_reserve_output_tokens,
|
reserve_output_tokens=self._settings.context_reserve_output_tokens,
|
||||||
reserve_tool_tokens=self._settings.context_reserve_tool_tokens,
|
reserve_tool_tokens=self._settings.context_reserve_tool_tokens,
|
||||||
)
|
)
|
||||||
# 本轮 tool 结果字符上限(与预留 tool token 粗对齐)
|
|
||||||
max_tool_chars = max(
|
max_tool_chars = max(
|
||||||
500, self._settings.context_reserve_tool_tokens * 2
|
500, self._settings.context_reserve_tool_tokens * 2
|
||||||
)
|
)
|
||||||
@@ -142,6 +153,7 @@ class ChatService:
|
|||||||
await self._session_repo.update(session)
|
await self._session_repo.update(session)
|
||||||
|
|
||||||
parts: list[str] = []
|
parts: list[str] = []
|
||||||
|
new_response_id: str | None = None
|
||||||
async for event in self._streamer.stream_reply(
|
async for event in self._streamer.stream_reply(
|
||||||
llm=llm,
|
llm=llm,
|
||||||
history=history,
|
history=history,
|
||||||
@@ -149,7 +161,11 @@ class ChatService:
|
|||||||
system_prompt=system_prompt,
|
system_prompt=system_prompt,
|
||||||
tools=tools or None,
|
tools=tools or None,
|
||||||
max_tool_result_chars=max_tool_chars,
|
max_tool_result_chars=max_tool_chars,
|
||||||
|
previous_response_id=chain_id,
|
||||||
):
|
):
|
||||||
|
if event.kind == "response_chain" and event.response_id:
|
||||||
|
new_response_id = event.response_id
|
||||||
|
continue
|
||||||
if event.kind == "token" and event.text:
|
if event.kind == "token" and event.text:
|
||||||
parts.append(event.text)
|
parts.append(event.text)
|
||||||
yield event
|
yield event
|
||||||
@@ -167,4 +183,26 @@ class ChatService:
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
session.last_message_at = datetime.utcnow()
|
session.last_message_at = datetime.utcnow()
|
||||||
|
if new_response_id:
|
||||||
|
session.llm_response_chain = LlmResponseChain(
|
||||||
|
provider_id=llm.provider_id,
|
||||||
|
model=llm.model,
|
||||||
|
previous_response_id=new_response_id,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
session.llm_response_chain = None
|
||||||
await self._session_repo.update(session)
|
await self._session_repo.update(session)
|
||||||
|
|
||||||
|
|
||||||
|
def _usable_chain_id(chain: LlmResponseChain | None, llm) -> str | None:
|
||||||
|
if chain is None:
|
||||||
|
return None
|
||||||
|
rid = (chain.previous_response_id or "").strip()
|
||||||
|
if not rid:
|
||||||
|
return None
|
||||||
|
if (chain.model or "") != (llm.model or ""):
|
||||||
|
return None
|
||||||
|
if chain.provider_id is not None and llm.provider_id is not None:
|
||||||
|
if int(chain.provider_id) != int(llm.provider_id):
|
||||||
|
return None
|
||||||
|
return rid
|
||||||
|
|||||||
@@ -53,6 +53,7 @@ class LlmRuntimeService:
|
|||||||
model=self._settings.llm_fallback_model,
|
model=self._settings.llm_fallback_model,
|
||||||
provider_id=None,
|
provider_id=None,
|
||||||
context_window=None,
|
context_window=None,
|
||||||
|
api_style="auto",
|
||||||
)
|
)
|
||||||
|
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ from datetime import datetime
|
|||||||
|
|
||||||
from application.llm_settings_service import LlmRuntimeService
|
from application.llm_settings_service import LlmRuntimeService
|
||||||
from domain.models import Actor, Session, SessionStatus
|
from domain.models import Actor, Session, SessionStatus
|
||||||
from domain.ports import SessionRepository
|
from domain.ports import MessageRepository, SessionRepository
|
||||||
|
|
||||||
|
|
||||||
class SessionService:
|
class SessionService:
|
||||||
@@ -15,9 +15,11 @@ class SessionService:
|
|||||||
self,
|
self,
|
||||||
sessions: SessionRepository,
|
sessions: SessionRepository,
|
||||||
llm_runtime: LlmRuntimeService | None = None,
|
llm_runtime: LlmRuntimeService | None = None,
|
||||||
|
messages: MessageRepository | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
self._sessions = sessions
|
self._sessions = sessions
|
||||||
self._llm_runtime = llm_runtime
|
self._llm_runtime = llm_runtime
|
||||||
|
self._messages = messages
|
||||||
|
|
||||||
async def create(
|
async def create(
|
||||||
self,
|
self,
|
||||||
@@ -103,11 +105,31 @@ class SessionService:
|
|||||||
if llm_provider_id is None or int(llm_provider_id) <= 0:
|
if llm_provider_id is None or int(llm_provider_id) <= 0:
|
||||||
raise ValueError("提供商不能为空")
|
raise ValueError("提供商不能为空")
|
||||||
session = await self.require_owned(actor, thread_id)
|
session = await self.require_owned(actor, thread_id)
|
||||||
|
switched = (
|
||||||
|
session.llm_provider_id != int(llm_provider_id)
|
||||||
|
or (session.llm_model or "") != model
|
||||||
|
)
|
||||||
session.llm_provider_id = int(llm_provider_id)
|
session.llm_provider_id = int(llm_provider_id)
|
||||||
session.llm_model = model
|
session.llm_model = model
|
||||||
|
if switched:
|
||||||
|
# 切换选型后厂商侧链不可复用
|
||||||
|
session.llm_response_chain = None
|
||||||
return await self._sessions.update(session)
|
return await self._sessions.update(session)
|
||||||
|
|
||||||
async def archive(self, actor: Actor, thread_id: str) -> Session:
|
async def archive(self, actor: Actor, thread_id: str) -> Session:
|
||||||
session = await self.require_owned(actor, thread_id)
|
session = await self.require_owned(actor, thread_id)
|
||||||
session.status = SessionStatus.ARCHIVED
|
session.status = SessionStatus.ARCHIVED
|
||||||
return await self._sessions.update(session)
|
return await self._sessions.update(session)
|
||||||
|
|
||||||
|
async def delete(self, actor: Actor, thread_id: str) -> Session:
|
||||||
|
"""软删会话,并级联软删该线程消息。"""
|
||||||
|
session = await self.require_owned(actor, thread_id)
|
||||||
|
session.status = SessionStatus.DELETED
|
||||||
|
session.llm_response_chain = None
|
||||||
|
session.summary = None
|
||||||
|
saved = await self._sessions.update(session)
|
||||||
|
if self._messages is not None:
|
||||||
|
await self._messages.soft_delete_by_thread(
|
||||||
|
actor.company_id, actor.user_id, thread_id
|
||||||
|
)
|
||||||
|
return saved
|
||||||
|
|||||||
@@ -12,9 +12,10 @@ _BASE_SYSTEM = (
|
|||||||
"需要经营数据时优先调用可用工具。"
|
"需要经营数据时优先调用可用工具。"
|
||||||
"工具可多轮检索,但对用户只报结论;默认不汇报检索过程、未命中关键词、搜了几轮或工具名。"
|
"工具可多轮检索,但对用户只报结论;默认不汇报检索过程、未命中关键词、搜了几轮或工具名。"
|
||||||
"不要自我纠错或评论上一轮话术(如「不该露编号」)。"
|
"不要自我纠错或评论上一轮话术(如「不该露编号」)。"
|
||||||
"你具备跨会话的用户级长期记忆,但内容不会自动注入对话。"
|
"【本会话上下文】请求里已包含本会话近期的用户与助手原文,你可以直接看见并引用;"
|
||||||
"需要称呼、偏好或用户事实时:先 memory_search,必要时再 memory_load;"
|
"禁止声称「只收到当前一句」或「前面几轮不会带过来」——那是错误描述。"
|
||||||
"禁止编造未载入的记忆,也不要声称没有长期记忆能力。"
|
"【长期记忆】跨会话的用户级记忆不会自动注入;需要称呼、偏好或用户事实时:"
|
||||||
|
"先 memory_search,必要时再 memory_load;禁止编造未载入的记忆,也不要声称没有长期记忆能力。"
|
||||||
"介绍记忆:自然语言短列表即可;禁止输出 ref、id、字段名、更新时间或表格。"
|
"介绍记忆:自然语言短列表即可;禁止输出 ref、id、字段名、更新时间或表格。"
|
||||||
"问「有哪些记忆」:有则直接列举命中摘要,无则一句「暂时没有相关记忆」;"
|
"问「有哪些记忆」:有则直接列举命中摘要,无则一句「暂时没有相关记忆」;"
|
||||||
"不必强调「就这一条」,未问勿主动建议再记店铺/商品/口径。"
|
"不必强调「就这一条」,未问勿主动建议再记店铺/商品/口径。"
|
||||||
|
|||||||
@@ -77,6 +77,8 @@ class Settings(BaseSettings):
|
|||||||
# 为模型输出与本轮 tool 预留的 token
|
# 为模型输出与本轮 tool 预留的 token
|
||||||
context_reserve_output_tokens: int = 4096
|
context_reserve_output_tokens: int = 4096
|
||||||
context_reserve_tool_tokens: int = 8192
|
context_reserve_tool_tokens: int = 8192
|
||||||
|
# Responses/store 能力缓存 TTL(秒)
|
||||||
|
llm_capability_ttl_seconds: int = 604800
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def cors_origin_list(self) -> list[str]:
|
def cors_origin_list(self) -> list[str]:
|
||||||
|
|||||||
@@ -50,6 +50,15 @@ class Actor:
|
|||||||
return role in {"owner", "admin"}
|
return role in {"owner", "admin"}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class LlmResponseChain:
|
||||||
|
"""同提供商同模型下的 Responses 续链缓存(非真相源;失效则 Mongo rebuild)。"""
|
||||||
|
|
||||||
|
provider_id: int | None
|
||||||
|
model: str
|
||||||
|
previous_response_id: str
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class Session:
|
class Session:
|
||||||
thread_id: str
|
thread_id: str
|
||||||
@@ -65,6 +74,8 @@ class Session:
|
|||||||
# 会话选用的提供商 + 模型(同名 model 靠 provider 消歧)
|
# 会话选用的提供商 + 模型(同名 model 靠 provider 消歧)
|
||||||
llm_provider_id: int | None = None
|
llm_provider_id: int | None = None
|
||||||
llm_model: str | None = None
|
llm_model: str | None = None
|
||||||
|
# Responses 续链;切换选型或链失效时清空
|
||||||
|
llm_response_chain: LlmResponseChain | None = None
|
||||||
created_at: datetime = field(default_factory=datetime.utcnow)
|
created_at: datetime = field(default_factory=datetime.utcnow)
|
||||||
updated_at: datetime = field(default_factory=datetime.utcnow)
|
updated_at: datetime = field(default_factory=datetime.utcnow)
|
||||||
last_message_at: datetime | None = None
|
last_message_at: datetime | None = None
|
||||||
@@ -118,19 +129,31 @@ class LlmRuntimeConfig:
|
|||||||
extra_headers: dict[str, str] = field(default_factory=dict)
|
extra_headers: dict[str, str] = field(default_factory=dict)
|
||||||
# 租户配置的上下文窗口;None 表示由 Agent 按模型名估计
|
# 租户配置的上下文窗口;None 表示由 Agent 按模型名估计
|
||||||
context_window: int | None = None
|
context_window: int | None = None
|
||||||
|
# API 协议:auto | completions | responses
|
||||||
|
api_style: str = "auto"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class LlmProtocolCapability:
|
||||||
|
"""按提供商缓存的协议能力;None 表示尚未验证。"""
|
||||||
|
|
||||||
|
responses: bool | None = None
|
||||||
|
store: bool | None = None
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class StreamEvent:
|
class StreamEvent:
|
||||||
"""流式片段:正文 token、服务端工具状态、或需前端执行的 client tool。"""
|
"""流式片段:正文 token、服务端工具状态、或需前端执行的 client tool。"""
|
||||||
|
|
||||||
kind: str # token | tool | client_tool | pending_client_tools
|
kind: str # token | tool | client_tool | pending_client_tools | response_chain
|
||||||
text: str | None = None
|
text: str | None = None
|
||||||
phase: str | None = None # start | end
|
phase: str | None = None # start | end
|
||||||
name: str | None = None
|
name: str | None = None
|
||||||
label: str | None = None
|
label: str | None = None
|
||||||
tool_call_id: str | None = None
|
tool_call_id: str | None = None
|
||||||
args: dict | None = None
|
args: dict | None = None
|
||||||
|
# Responses 本轮最终 response id(仅 kind=response_chain)
|
||||||
|
response_id: str | None = None
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def token(text: str) -> StreamEvent:
|
def token(text: str) -> StreamEvent:
|
||||||
@@ -159,3 +182,8 @@ class StreamEvent:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def pending_client_tools() -> StreamEvent:
|
def pending_client_tools() -> StreamEvent:
|
||||||
return StreamEvent(kind="pending_client_tools")
|
return StreamEvent(kind="pending_client_tools")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def response_chain(response_id: str) -> StreamEvent:
|
||||||
|
"""内部事件:落会话续链;不推给前端 SSE。"""
|
||||||
|
return StreamEvent(kind="response_chain", response_id=response_id)
|
||||||
|
|||||||
@@ -5,7 +5,14 @@ from __future__ import annotations
|
|||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from typing import Any, AsyncIterator
|
from typing import Any, AsyncIterator
|
||||||
|
|
||||||
from domain.models import ChatMessage, LlmRuntimeConfig, Session, StreamEvent, UserMemory
|
from domain.models import (
|
||||||
|
ChatMessage,
|
||||||
|
LlmProtocolCapability,
|
||||||
|
LlmRuntimeConfig,
|
||||||
|
Session,
|
||||||
|
StreamEvent,
|
||||||
|
UserMemory,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class SessionRepository(ABC):
|
class SessionRepository(ABC):
|
||||||
@@ -51,6 +58,13 @@ class MessageRepository(ABC):
|
|||||||
@abstractmethod
|
@abstractmethod
|
||||||
async def next_seq(self, company_id: int, user_id: str, thread_id: str) -> int: ...
|
async def next_seq(self, company_id: int, user_id: str, thread_id: str) -> int: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def soft_delete_by_thread(
|
||||||
|
self, company_id: int, user_id: str, thread_id: str
|
||||||
|
) -> int:
|
||||||
|
"""软删某会话下全部消息,返回影响条数。"""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
class MemoryRepository(ABC):
|
class MemoryRepository(ABC):
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
@@ -111,6 +125,25 @@ class LlmRuntimeGateway(ABC):
|
|||||||
) -> LlmRuntimeConfig | None: ...
|
) -> LlmRuntimeConfig | None: ...
|
||||||
|
|
||||||
|
|
||||||
|
class LlmProtocolCapabilityCache(ABC):
|
||||||
|
"""缓存某提供商(或 base_url)是否支持 Responses / store。"""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def get(
|
||||||
|
self, *, provider_id: int | None, base_url: str
|
||||||
|
) -> LlmProtocolCapability | None: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def set(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
provider_id: int | None,
|
||||||
|
base_url: str,
|
||||||
|
capability: LlmProtocolCapability,
|
||||||
|
ttl_seconds: int,
|
||||||
|
) -> None: ...
|
||||||
|
|
||||||
|
|
||||||
class ChatStreamer(ABC):
|
class ChatStreamer(ABC):
|
||||||
"""流式生成助手回复。"""
|
"""流式生成助手回复。"""
|
||||||
|
|
||||||
@@ -124,4 +157,5 @@ class ChatStreamer(ABC):
|
|||||||
system_prompt: str,
|
system_prompt: str,
|
||||||
tools: list[Any] | None = None,
|
tools: list[Any] | None = None,
|
||||||
max_tool_result_chars: int = 4000,
|
max_tool_result_chars: int = 4000,
|
||||||
|
previous_response_id: str | None = None,
|
||||||
) -> AsyncIterator[StreamEvent]: ...
|
) -> AsyncIterator[StreamEvent]: ...
|
||||||
|
|||||||
@@ -0,0 +1,128 @@
|
|||||||
|
"""协议偏好与错误分类:先验缓存 + 运行时探测回退(不写死主机)。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from domain.models import LlmProtocolCapability
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_api_style(raw: str | None) -> str:
|
||||||
|
s = (raw or "auto").strip().lower()
|
||||||
|
if s in ("auto", "completions", "responses"):
|
||||||
|
return s
|
||||||
|
return "auto"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ProtocolAttempt:
|
||||||
|
"""单次调用策略。"""
|
||||||
|
|
||||||
|
use_responses: bool
|
||||||
|
use_store: bool
|
||||||
|
use_chain: bool # 是否只发增量 + previous_response_id(须 store 已证实)
|
||||||
|
|
||||||
|
|
||||||
|
def plan_protocol_attempts(
|
||||||
|
api_style: str | None,
|
||||||
|
cap: LlmProtocolCapability | None,
|
||||||
|
*,
|
||||||
|
has_chain_id: bool,
|
||||||
|
) -> list[ProtocolAttempt]:
|
||||||
|
"""
|
||||||
|
同轮探测顺序(未产出 token 前可依次尝试):
|
||||||
|
|
||||||
|
- store 已证实:Responses+store,有链则增量续聊
|
||||||
|
- store 未知:Responses+store + **Mongo 全量**,成功后再语义探测
|
||||||
|
- store 证伪:先 **无状态 Responses + Mongo 全量**,失败再 **Completions**
|
||||||
|
- Responses 不可用:Completions
|
||||||
|
"""
|
||||||
|
style = normalize_api_style(api_style)
|
||||||
|
cap = cap or LlmProtocolCapability()
|
||||||
|
|
||||||
|
if style == "completions":
|
||||||
|
return [ProtocolAttempt(False, False, False)]
|
||||||
|
|
||||||
|
attempts: list[ProtocolAttempt] = []
|
||||||
|
|
||||||
|
if cap.store is False:
|
||||||
|
# 无真实 store:无状态 Responses(全量历史)→ Completions
|
||||||
|
if cap.responses is not False:
|
||||||
|
attempts.append(ProtocolAttempt(True, False, False))
|
||||||
|
attempts.append(ProtocolAttempt(False, False, False))
|
||||||
|
return _dedupe(attempts)
|
||||||
|
|
||||||
|
if cap.responses is not False:
|
||||||
|
if cap.store is True:
|
||||||
|
attempts.append(
|
||||||
|
ProtocolAttempt(True, True, use_chain=bool(has_chain_id))
|
||||||
|
)
|
||||||
|
# 有链失败时可降到同协议全量
|
||||||
|
attempts.append(ProtocolAttempt(True, True, use_chain=False))
|
||||||
|
else:
|
||||||
|
# store 未知:Responses+store,必须全量历史,禁止 use_chain
|
||||||
|
attempts.append(ProtocolAttempt(True, True, use_chain=False))
|
||||||
|
attempts.append(ProtocolAttempt(True, False, False))
|
||||||
|
|
||||||
|
# Completions 兜底
|
||||||
|
if style == "auto" or cap.responses is False:
|
||||||
|
attempts.append(ProtocolAttempt(False, False, False))
|
||||||
|
elif style == "responses" and cap.responses is False:
|
||||||
|
attempts.append(ProtocolAttempt(False, False, False))
|
||||||
|
|
||||||
|
return _dedupe(attempts) or [ProtocolAttempt(False, False, False)]
|
||||||
|
|
||||||
|
|
||||||
|
def _dedupe(attempts: list[ProtocolAttempt]) -> list[ProtocolAttempt]:
|
||||||
|
seen: set[tuple[bool, bool, bool]] = set()
|
||||||
|
out: list[ProtocolAttempt] = []
|
||||||
|
for a in attempts:
|
||||||
|
key = (a.use_responses, a.use_store, a.use_chain)
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
out.append(a)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def classify_protocol_error(exc: BaseException) -> str:
|
||||||
|
"""返回: store | responses | chain | other。"""
|
||||||
|
text = str(exc).lower()
|
||||||
|
status = getattr(exc, "status_code", None) or getattr(
|
||||||
|
getattr(exc, "response", None), "status_code", None
|
||||||
|
)
|
||||||
|
|
||||||
|
if "previous_response_id" in text or "previous response" in text:
|
||||||
|
return "chain"
|
||||||
|
if status == 400 and "response" in text and "not found" in text:
|
||||||
|
return "chain"
|
||||||
|
|
||||||
|
if "store" in text and any(
|
||||||
|
n in text
|
||||||
|
for n in (
|
||||||
|
"unsupported",
|
||||||
|
"unknown",
|
||||||
|
"unrecognized",
|
||||||
|
"invalid",
|
||||||
|
"not support",
|
||||||
|
"not supported",
|
||||||
|
)
|
||||||
|
):
|
||||||
|
return "store"
|
||||||
|
|
||||||
|
if status in (404, 405):
|
||||||
|
return "responses"
|
||||||
|
responses_needles = (
|
||||||
|
"/responses",
|
||||||
|
"responses api",
|
||||||
|
"unknown endpoint",
|
||||||
|
"not implemented",
|
||||||
|
"invalid pathname",
|
||||||
|
"no route",
|
||||||
|
)
|
||||||
|
if any(n in text for n in responses_needles):
|
||||||
|
return "responses"
|
||||||
|
if status == 400 and ("responses" in text or "response.create" in text):
|
||||||
|
return "responses"
|
||||||
|
|
||||||
|
return "other"
|
||||||
@@ -1,8 +1,13 @@
|
|||||||
"""按租户构建 OpenAI Compatible Chat 模型并流式输出(可带 MCP tools)。"""
|
"""按租户构建 OpenAI Compatible Chat 模型并流式输出(可带 MCP tools)。
|
||||||
|
|
||||||
|
优先 Responses+store → Responses store=false → Completions;
|
||||||
|
能力结果写入 Redis,不按主机写死。未产出 token 前可同轮回退。
|
||||||
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import logging
|
||||||
from typing import Any, AsyncIterator
|
from typing import Any, AsyncIterator
|
||||||
|
|
||||||
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage
|
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage
|
||||||
@@ -10,11 +15,36 @@ from langchain_openai import ChatOpenAI
|
|||||||
|
|
||||||
from agent.tools.labels import tool_status_label
|
from agent.tools.labels import tool_status_label
|
||||||
from agent.tools.publish_ui import is_client_tool_name
|
from agent.tools.publish_ui import is_client_tool_name
|
||||||
from domain.models import ChatMessage, LlmRuntimeConfig, MessageRole, StreamEvent
|
from domain.models import (
|
||||||
from domain.ports import ChatStreamer
|
ChatMessage,
|
||||||
|
LlmProtocolCapability,
|
||||||
|
LlmRuntimeConfig,
|
||||||
|
MessageRole,
|
||||||
|
StreamEvent,
|
||||||
|
)
|
||||||
|
from domain.ports import ChatStreamer, LlmProtocolCapabilityCache
|
||||||
|
from infrastructure.llm.api_style import (
|
||||||
|
ProtocolAttempt,
|
||||||
|
classify_protocol_error,
|
||||||
|
normalize_api_style,
|
||||||
|
plan_protocol_attempts,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_UNSET = object()
|
||||||
|
|
||||||
|
|
||||||
class OpenAICompatibleStreamer(ChatStreamer):
|
class OpenAICompatibleStreamer(ChatStreamer):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
capability_cache: LlmProtocolCapabilityCache | None = None,
|
||||||
|
*,
|
||||||
|
capability_ttl_seconds: int = 604800,
|
||||||
|
) -> None:
|
||||||
|
self._cap_cache = capability_cache
|
||||||
|
self._cap_ttl = capability_ttl_seconds
|
||||||
|
|
||||||
async def stream_reply(
|
async def stream_reply(
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
@@ -24,40 +54,331 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
|||||||
system_prompt: str,
|
system_prompt: str,
|
||||||
tools: list[Any] | None = None,
|
tools: list[Any] | None = None,
|
||||||
max_tool_result_chars: int = 8000,
|
max_tool_result_chars: int = 8000,
|
||||||
|
previous_response_id: str | None = None,
|
||||||
) -> AsyncIterator[StreamEvent]:
|
) -> AsyncIterator[StreamEvent]:
|
||||||
model = ChatOpenAI(
|
chain_id = (previous_response_id or "").strip() or None
|
||||||
api_key=llm.api_key,
|
style = normalize_api_style(llm.api_style)
|
||||||
base_url=llm.base_url,
|
# 未知 store 时先做语义探测(能否靠 previous_response_id 记住上下文)
|
||||||
model=llm.model,
|
cap = await self._ensure_protocol_capability(llm, style)
|
||||||
temperature=0.3,
|
attempts = plan_protocol_attempts(
|
||||||
streaming=True,
|
llm.api_style, cap, has_chain_id=bool(chain_id)
|
||||||
default_headers=llm.extra_headers or None,
|
|
||||||
)
|
)
|
||||||
messages: list[Any] = [SystemMessage(content=system_prompt)]
|
|
||||||
for m in history:
|
i = 0
|
||||||
if m.role == MessageRole.USER:
|
while i < len(attempts):
|
||||||
messages.append(HumanMessage(content=m.content))
|
attempt = attempts[i]
|
||||||
elif m.role == MessageRole.ASSISTANT:
|
# 仅缓存已证实 store=true 时才丢历史、纯续链
|
||||||
messages.append(AIMessage(content=m.content))
|
use_chain_id = (
|
||||||
messages.append(HumanMessage(content=user_text))
|
chain_id if (attempt.use_chain and cap and cap.store is True) else None
|
||||||
|
)
|
||||||
|
logger.warning(
|
||||||
|
"LLM attempt model=%s responses=%s store=%s chain=%s hist=%s api_style=%s",
|
||||||
|
llm.model,
|
||||||
|
attempt.use_responses,
|
||||||
|
attempt.use_store,
|
||||||
|
bool(use_chain_id),
|
||||||
|
len(history),
|
||||||
|
style,
|
||||||
|
)
|
||||||
|
yielded_any = False
|
||||||
|
got_chain_id: str | None = None
|
||||||
|
try:
|
||||||
|
async for event in self._stream_once(
|
||||||
|
llm=llm,
|
||||||
|
history=history,
|
||||||
|
user_text=user_text,
|
||||||
|
system_prompt=system_prompt,
|
||||||
|
tools=tools,
|
||||||
|
max_tool_result_chars=max_tool_result_chars,
|
||||||
|
use_responses=attempt.use_responses,
|
||||||
|
use_store=attempt.use_store,
|
||||||
|
previous_response_id=use_chain_id,
|
||||||
|
):
|
||||||
|
if event.kind == "token" and event.text:
|
||||||
|
yielded_any = True
|
||||||
|
if event.kind == "response_chain" and event.response_id:
|
||||||
|
got_chain_id = event.response_id
|
||||||
|
continue
|
||||||
|
yield event
|
||||||
|
|
||||||
|
if attempt.use_responses:
|
||||||
|
if use_chain_id:
|
||||||
|
# 已证实 store 且本轮续链成功
|
||||||
|
await self._update_cap(llm, responses=True, store=True)
|
||||||
|
if got_chain_id:
|
||||||
|
yield StreamEvent.response_chain(got_chain_id)
|
||||||
|
elif attempt.use_store:
|
||||||
|
# store 未证实或待刷新:本轮是全量历史;语义探测真伪
|
||||||
|
need_probe = cap is None or cap.store is not True
|
||||||
|
if need_probe:
|
||||||
|
store_ok = await self._probe_store_semantic(llm)
|
||||||
|
await self._update_cap(
|
||||||
|
llm, responses=True, store=store_ok
|
||||||
|
)
|
||||||
|
cap = LlmProtocolCapability(
|
||||||
|
responses=True, store=store_ok
|
||||||
|
)
|
||||||
|
if store_ok and got_chain_id:
|
||||||
|
yield StreamEvent.response_chain(got_chain_id)
|
||||||
|
else:
|
||||||
|
await self._update_cap(llm, responses=True, store=True)
|
||||||
|
if got_chain_id:
|
||||||
|
yield StreamEvent.response_chain(got_chain_id)
|
||||||
|
else:
|
||||||
|
# Responses 无 store:能通端点但不持久
|
||||||
|
await self._update_cap(llm, responses=True, store=False)
|
||||||
|
cap = LlmProtocolCapability(responses=True, store=False)
|
||||||
|
else:
|
||||||
|
# Completions:若已知有 Responses 只是无 store,不要把 responses 打成 false
|
||||||
|
if cap is not None and cap.responses is True and cap.store is False:
|
||||||
|
await self._update_cap(llm, responses=True, store=False)
|
||||||
|
elif cap is not None and cap.store is False:
|
||||||
|
await self._update_cap(llm, responses=cap.responses, store=False)
|
||||||
|
else:
|
||||||
|
await self._update_cap(llm, responses=False, store=False)
|
||||||
|
cap = LlmProtocolCapability(responses=False, store=False)
|
||||||
|
return
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
if yielded_any:
|
||||||
|
raise
|
||||||
|
kind = classify_protocol_error(e)
|
||||||
|
logger.warning(
|
||||||
|
"LLM attempt failed kind=%s model=%s err=%s",
|
||||||
|
kind,
|
||||||
|
llm.model,
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
if kind == "chain" and use_chain_id:
|
||||||
|
await self._update_cap(llm, responses=True, store=False)
|
||||||
|
cap = LlmProtocolCapability(responses=True, store=False)
|
||||||
|
nxt = ProtocolAttempt(True, False, False)
|
||||||
|
if nxt not in attempts[i + 1 :]:
|
||||||
|
attempts.insert(i + 1, nxt)
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
if kind == "store" and attempt.use_responses and attempt.use_store:
|
||||||
|
await self._update_cap(llm, responses=True, store=False)
|
||||||
|
cap = LlmProtocolCapability(responses=True, store=False)
|
||||||
|
nxt = ProtocolAttempt(True, False, False)
|
||||||
|
if nxt not in attempts[i + 1 :]:
|
||||||
|
attempts.insert(i + 1, nxt)
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
if kind == "responses" and attempt.use_responses:
|
||||||
|
await self._update_cap(llm, responses=False, store=False)
|
||||||
|
cap = LlmProtocolCapability(responses=False, store=False)
|
||||||
|
nxt = ProtocolAttempt(False, False, False)
|
||||||
|
if nxt not in attempts[i + 1 :]:
|
||||||
|
attempts.insert(i + 1, nxt)
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
if i + 1 < len(attempts):
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
if style == "responses" and attempt.use_responses:
|
||||||
|
attempts.append(ProtocolAttempt(False, False, False))
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
raise
|
||||||
|
i += 1 # pragma: no cover
|
||||||
|
|
||||||
|
async def _ensure_protocol_capability(
|
||||||
|
self, llm: LlmRuntimeConfig, style: str
|
||||||
|
) -> LlmProtocolCapability | None:
|
||||||
|
"""读取能力缓存;completions 强制走 Completions,不探测。"""
|
||||||
|
if style == "completions":
|
||||||
|
return LlmProtocolCapability(responses=False, store=False)
|
||||||
|
return await self._load_cap(llm)
|
||||||
|
|
||||||
|
async def _load_cap(self, llm: LlmRuntimeConfig) -> LlmProtocolCapability | None:
|
||||||
|
if self._cap_cache is None:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return await self._cap_cache.get(
|
||||||
|
provider_id=llm.provider_id, base_url=llm.base_url
|
||||||
|
)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
logger.exception("读取协议能力缓存失败")
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def _update_cap(
|
||||||
|
self,
|
||||||
|
llm: LlmRuntimeConfig,
|
||||||
|
*,
|
||||||
|
responses: bool | None | object = _UNSET,
|
||||||
|
store: bool | None | object = _UNSET,
|
||||||
|
) -> None:
|
||||||
|
"""更新能力缓存;参数为 _UNSET 表示不改该字段,显式 None 表示未知。"""
|
||||||
|
if self._cap_cache is None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
prev = await self._cap_cache.get(
|
||||||
|
provider_id=llm.provider_id, base_url=llm.base_url
|
||||||
|
) or LlmProtocolCapability()
|
||||||
|
new_responses = (
|
||||||
|
prev.responses if responses is _UNSET else responses # type: ignore[arg-type]
|
||||||
|
)
|
||||||
|
new_store = prev.store if store is _UNSET else store # type: ignore[arg-type]
|
||||||
|
await self._cap_cache.set(
|
||||||
|
provider_id=llm.provider_id,
|
||||||
|
base_url=llm.base_url,
|
||||||
|
capability=LlmProtocolCapability(
|
||||||
|
responses=new_responses, # type: ignore[arg-type]
|
||||||
|
store=new_store, # type: ignore[arg-type]
|
||||||
|
),
|
||||||
|
ttl_seconds=self._cap_ttl,
|
||||||
|
)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
logger.exception("写入协议能力缓存失败")
|
||||||
|
|
||||||
|
async def _probe_store_semantic(self, llm: LlmRuntimeConfig) -> bool:
|
||||||
|
"""
|
||||||
|
语义探测:先写入密钥,再用 previous_response_id 且不带历史追问。
|
||||||
|
能答对密钥 → 真支持 store 续链;否则(报错或静默丢上下文)→ false。
|
||||||
|
"""
|
||||||
|
secret = "ALPHA7X"
|
||||||
|
try:
|
||||||
|
model = ChatOpenAI(
|
||||||
|
api_key=llm.api_key,
|
||||||
|
base_url=llm.base_url,
|
||||||
|
model=llm.model,
|
||||||
|
temperature=0,
|
||||||
|
streaming=False,
|
||||||
|
default_headers=llm.extra_headers or None,
|
||||||
|
use_responses_api=True,
|
||||||
|
output_version="responses/v1",
|
||||||
|
store=True,
|
||||||
|
use_previous_response_id=True,
|
||||||
|
)
|
||||||
|
first = await model.ainvoke(
|
||||||
|
[
|
||||||
|
HumanMessage(
|
||||||
|
content=(
|
||||||
|
f"这是接口能力测试。请记住密钥:{secret}。"
|
||||||
|
"只回复一个词:OK"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
rid = _response_id_of(first)
|
||||||
|
if not rid:
|
||||||
|
logger.info("store 语义探测失败:首轮无 response.id model=%s", llm.model)
|
||||||
|
return False
|
||||||
|
second = await model.ainvoke(
|
||||||
|
[
|
||||||
|
HumanMessage(
|
||||||
|
content="接口能力测试续问:刚才的密钥是什么?只回复密钥本身。"
|
||||||
|
)
|
||||||
|
],
|
||||||
|
previous_response_id=rid,
|
||||||
|
)
|
||||||
|
text = _chunk_text(getattr(second, "content", None)).upper()
|
||||||
|
ok = secret in text.replace(" ", "").replace("-", "")
|
||||||
|
if not ok:
|
||||||
|
logger.info(
|
||||||
|
"store 语义探测未通过(静默丢上下文)model=%s reply=%s",
|
||||||
|
llm.model,
|
||||||
|
text[:80],
|
||||||
|
)
|
||||||
|
return ok
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
logger.info(
|
||||||
|
"store 语义探测异常 model=%s kind=%s err=%s",
|
||||||
|
llm.model,
|
||||||
|
classify_protocol_error(e),
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def _stream_once(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
llm: LlmRuntimeConfig,
|
||||||
|
history: list[ChatMessage],
|
||||||
|
user_text: str,
|
||||||
|
system_prompt: str,
|
||||||
|
tools: list[Any] | None,
|
||||||
|
max_tool_result_chars: int,
|
||||||
|
use_responses: bool,
|
||||||
|
use_store: bool,
|
||||||
|
previous_response_id: str | None,
|
||||||
|
) -> AsyncIterator[StreamEvent]:
|
||||||
|
kwargs: dict[str, Any] = {
|
||||||
|
"api_key": llm.api_key,
|
||||||
|
"base_url": llm.base_url,
|
||||||
|
"model": llm.model,
|
||||||
|
"temperature": 0.3,
|
||||||
|
"streaming": True,
|
||||||
|
"default_headers": llm.extra_headers or None,
|
||||||
|
"use_responses_api": use_responses,
|
||||||
|
}
|
||||||
|
if use_responses:
|
||||||
|
kwargs["output_version"] = "responses/v1"
|
||||||
|
kwargs["store"] = use_store
|
||||||
|
# 仅真正续链时打开;否则 LangChain 可能按 AIMessage.id 截断历史
|
||||||
|
kwargs["use_previous_response_id"] = bool(
|
||||||
|
previous_response_id and use_store
|
||||||
|
)
|
||||||
|
|
||||||
|
model = ChatOpenAI(**kwargs)
|
||||||
|
if previous_response_id and use_store:
|
||||||
|
# 已证实 store:只发本轮,靠 previous_response_id 续上下文
|
||||||
|
messages: list[Any] = [
|
||||||
|
SystemMessage(content=system_prompt),
|
||||||
|
HumanMessage(content=user_text),
|
||||||
|
]
|
||||||
|
first_extra: dict[str, Any] = {
|
||||||
|
"previous_response_id": previous_response_id
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
# 无 store / Completions / 未证实:Mongo 全量历史 + 本轮
|
||||||
|
messages = [SystemMessage(content=system_prompt)]
|
||||||
|
for m in history:
|
||||||
|
if m.role == MessageRole.USER:
|
||||||
|
messages.append(HumanMessage(content=m.content))
|
||||||
|
elif m.role == MessageRole.ASSISTANT:
|
||||||
|
messages.append(AIMessage(content=m.content))
|
||||||
|
messages.append(HumanMessage(content=user_text))
|
||||||
|
first_extra = {}
|
||||||
|
logger.warning(
|
||||||
|
"LLM pack full history lc_messages=%s hist_rows=%s preview=%s",
|
||||||
|
len(messages),
|
||||||
|
len(history),
|
||||||
|
[
|
||||||
|
(
|
||||||
|
m.role.value if hasattr(m, "role") else type(m).__name__,
|
||||||
|
(getattr(m, "content", None) or "")[:40],
|
||||||
|
)
|
||||||
|
for m in (
|
||||||
|
history[-4:] if len(history) > 4 else history
|
||||||
|
)
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
last_response_id: str | None = None
|
||||||
|
|
||||||
if not tools:
|
if not tools:
|
||||||
async for chunk in model.astream(messages):
|
async for chunk in model.astream(messages, **first_extra):
|
||||||
|
last_response_id = _response_id_of(chunk) or last_response_id
|
||||||
text = _chunk_text(chunk.content)
|
text = _chunk_text(chunk.content)
|
||||||
if text:
|
if text:
|
||||||
yield StreamEvent.token(text)
|
yield StreamEvent.token(text)
|
||||||
|
if use_store and last_response_id:
|
||||||
|
yield StreamEvent.response_chain(last_response_id)
|
||||||
return
|
return
|
||||||
|
|
||||||
# 工具轮:每轮用 astream 边生成边推 token;出现 tool_call 再执行工具后继续
|
|
||||||
bound = model.bind_tools(tools)
|
bound = model.bind_tools(tools)
|
||||||
tool_map = {t.name: t for t in tools if getattr(t, "name", None)}
|
tool_map = {t.name: t for t in tools if getattr(t, "name", None)}
|
||||||
tool_cap = max(500, max_tool_result_chars)
|
tool_cap = max(500, max_tool_result_chars)
|
||||||
for _ in range(5):
|
for round_idx in range(5):
|
||||||
gathered = None
|
gathered = None
|
||||||
saw_tool = False
|
saw_tool = False
|
||||||
async for chunk in bound.astream(messages):
|
call_extra = first_extra if round_idx == 0 else {}
|
||||||
|
async for chunk in bound.astream(messages, **call_extra):
|
||||||
gathered = chunk if gathered is None else gathered + chunk
|
gathered = chunk if gathered is None else gathered + chunk
|
||||||
if getattr(chunk, "tool_call_chunks", None) or getattr(chunk, "tool_calls", None):
|
if getattr(chunk, "tool_call_chunks", None) or getattr(
|
||||||
|
chunk, "tool_calls", None
|
||||||
|
):
|
||||||
saw_tool = True
|
saw_tool = True
|
||||||
continue
|
continue
|
||||||
if saw_tool:
|
if saw_tool:
|
||||||
@@ -65,12 +386,19 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
|||||||
text = _chunk_text(getattr(chunk, "content", None))
|
text = _chunk_text(getattr(chunk, "content", None))
|
||||||
if text:
|
if text:
|
||||||
yield StreamEvent.token(text)
|
yield StreamEvent.token(text)
|
||||||
|
|
||||||
if gathered is None:
|
if gathered is None:
|
||||||
yield StreamEvent.token("(模型未返回内容)")
|
yield StreamEvent.token("(模型未返回内容)")
|
||||||
|
if use_store and last_response_id:
|
||||||
|
yield StreamEvent.response_chain(last_response_id)
|
||||||
return
|
return
|
||||||
|
|
||||||
|
last_response_id = _response_id_of(gathered) or last_response_id
|
||||||
messages.append(gathered)
|
messages.append(gathered)
|
||||||
tool_calls = getattr(gathered, "tool_calls", None) or []
|
tool_calls = getattr(gathered, "tool_calls", None) or []
|
||||||
if not tool_calls:
|
if not tool_calls:
|
||||||
|
if use_store and last_response_id:
|
||||||
|
yield StreamEvent.response_chain(last_response_id)
|
||||||
return
|
return
|
||||||
|
|
||||||
seen: set[str] = set()
|
seen: set[str] = set()
|
||||||
@@ -121,19 +449,44 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
|||||||
)
|
)
|
||||||
|
|
||||||
yield StreamEvent.token("工具调用轮次过多,请缩小问题范围后重试。")
|
yield StreamEvent.token("工具调用轮次过多,请缩小问题范围后重试。")
|
||||||
|
if use_store and last_response_id:
|
||||||
|
yield StreamEvent.response_chain(last_response_id)
|
||||||
|
|
||||||
|
|
||||||
|
def _response_id_of(msg: Any) -> str | None:
|
||||||
|
meta = getattr(msg, "response_metadata", None) or {}
|
||||||
|
if isinstance(meta, dict):
|
||||||
|
rid = meta.get("id")
|
||||||
|
if isinstance(rid, str) and rid.strip():
|
||||||
|
return rid.strip()
|
||||||
|
mid = getattr(msg, "id", None)
|
||||||
|
if isinstance(mid, str) and mid.startswith("resp_"):
|
||||||
|
return mid
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _chunk_text(content: Any) -> str:
|
def _chunk_text(content: Any) -> str:
|
||||||
|
"""兼容 Completions 字符串与 Responses 结构化 content 块。"""
|
||||||
|
if content is None:
|
||||||
|
return ""
|
||||||
if isinstance(content, str):
|
if isinstance(content, str):
|
||||||
return content
|
return content
|
||||||
if isinstance(content, list):
|
if isinstance(content, list):
|
||||||
parts: list[str] = []
|
parts: list[str] = []
|
||||||
for part in content:
|
for part in content:
|
||||||
if isinstance(part, dict) and part.get("type") == "text":
|
if isinstance(part, str):
|
||||||
|
parts.append(part)
|
||||||
|
continue
|
||||||
|
if not isinstance(part, dict):
|
||||||
|
text = getattr(part, "text", None)
|
||||||
|
ptype = getattr(part, "type", None)
|
||||||
|
if text and ptype in (None, "text", "output_text"):
|
||||||
|
parts.append(str(text))
|
||||||
|
continue
|
||||||
|
ptype = part.get("type")
|
||||||
|
if ptype in (None, "text", "output_text"):
|
||||||
t = part.get("text")
|
t = part.get("text")
|
||||||
if t:
|
if t:
|
||||||
parts.append(str(t))
|
parts.append(str(t))
|
||||||
elif isinstance(part, str):
|
|
||||||
parts.append(part)
|
|
||||||
return "".join(parts)
|
return "".join(parts)
|
||||||
return ""
|
return ""
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import httpx
|
|||||||
from config.settings import Settings
|
from config.settings import Settings
|
||||||
from domain.models import LlmRuntimeConfig
|
from domain.models import LlmRuntimeConfig
|
||||||
from domain.ports import LlmRuntimeGateway
|
from domain.ports import LlmRuntimeGateway
|
||||||
|
from infrastructure.llm.api_style import normalize_api_style
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -53,6 +54,9 @@ class ServerLlmRuntimeGateway(LlmRuntimeGateway):
|
|||||||
for k, v in (data.get("extraHeaders") or {}).items()
|
for k, v in (data.get("extraHeaders") or {}).items()
|
||||||
},
|
},
|
||||||
context_window=_optional_positive_int(data.get("contextWindow")),
|
context_window=_optional_positive_int(data.get("contextWindow")),
|
||||||
|
api_style=normalize_api_style(
|
||||||
|
None if data.get("apiStyle") is None else str(data.get("apiStyle"))
|
||||||
|
),
|
||||||
)
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.exception(
|
logger.exception(
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ from motor.motor_asyncio import AsyncIOMotorDatabase
|
|||||||
|
|
||||||
from domain.models import (
|
from domain.models import (
|
||||||
ChatMessage,
|
ChatMessage,
|
||||||
|
LlmResponseChain,
|
||||||
MemoryKind,
|
MemoryKind,
|
||||||
MemoryStatus,
|
MemoryStatus,
|
||||||
MessageRole,
|
MessageRole,
|
||||||
@@ -36,6 +37,30 @@ def _optional_int(v: Any) -> int | None:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _chain_to_doc(chain: LlmResponseChain | None) -> dict[str, Any] | None:
|
||||||
|
if chain is None or not (chain.previous_response_id or "").strip():
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"provider_id": chain.provider_id,
|
||||||
|
"model": chain.model,
|
||||||
|
"previous_response_id": chain.previous_response_id.strip(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _chain_from_doc(raw: Any) -> LlmResponseChain | None:
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
return None
|
||||||
|
rid = str(raw.get("previous_response_id") or "").strip()
|
||||||
|
model = str(raw.get("model") or "").strip()
|
||||||
|
if not rid or not model:
|
||||||
|
return None
|
||||||
|
return LlmResponseChain(
|
||||||
|
provider_id=_optional_int(raw.get("provider_id")),
|
||||||
|
model=model,
|
||||||
|
previous_response_id=rid,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class MongoSessionRepository(SessionRepository):
|
class MongoSessionRepository(SessionRepository):
|
||||||
def __init__(self, db: AsyncIOMotorDatabase) -> None:
|
def __init__(self, db: AsyncIOMotorDatabase) -> None:
|
||||||
self._col = db.agent_sessions
|
self._col = db.agent_sessions
|
||||||
@@ -52,6 +77,7 @@ class MongoSessionRepository(SessionRepository):
|
|||||||
"scene_ref": session.scene_ref,
|
"scene_ref": session.scene_ref,
|
||||||
"llm_provider_id": session.llm_provider_id,
|
"llm_provider_id": session.llm_provider_id,
|
||||||
"llm_model": session.llm_model,
|
"llm_model": session.llm_model,
|
||||||
|
"llm_response_chain": _chain_to_doc(session.llm_response_chain),
|
||||||
"created_at": session.created_at,
|
"created_at": session.created_at,
|
||||||
"updated_at": session.updated_at,
|
"updated_at": session.updated_at,
|
||||||
"last_message_at": session.last_message_at,
|
"last_message_at": session.last_message_at,
|
||||||
@@ -135,6 +161,7 @@ class MongoSessionRepository(SessionRepository):
|
|||||||
"scene_ref": session.scene_ref,
|
"scene_ref": session.scene_ref,
|
||||||
"llm_provider_id": session.llm_provider_id,
|
"llm_provider_id": session.llm_provider_id,
|
||||||
"llm_model": session.llm_model,
|
"llm_model": session.llm_model,
|
||||||
|
"llm_response_chain": _chain_to_doc(session.llm_response_chain),
|
||||||
"updated_at": session.updated_at,
|
"updated_at": session.updated_at,
|
||||||
"last_message_at": session.last_message_at,
|
"last_message_at": session.last_message_at,
|
||||||
}
|
}
|
||||||
@@ -155,6 +182,7 @@ class MongoSessionRepository(SessionRepository):
|
|||||||
scene_ref=doc.get("scene_ref"),
|
scene_ref=doc.get("scene_ref"),
|
||||||
llm_provider_id=_optional_int(doc.get("llm_provider_id")),
|
llm_provider_id=_optional_int(doc.get("llm_provider_id")),
|
||||||
llm_model=doc.get("llm_model"),
|
llm_model=doc.get("llm_model"),
|
||||||
|
llm_response_chain=_chain_from_doc(doc.get("llm_response_chain")),
|
||||||
created_at=_dt(doc.get("created_at")),
|
created_at=_dt(doc.get("created_at")),
|
||||||
updated_at=_dt(doc.get("updated_at")),
|
updated_at=_dt(doc.get("updated_at")),
|
||||||
last_message_at=doc.get("last_message_at"),
|
last_message_at=doc.get("last_message_at"),
|
||||||
@@ -194,7 +222,17 @@ class MongoMessageRepository(MessageRepository):
|
|||||||
) -> list[ChatMessage]:
|
) -> list[ChatMessage]:
|
||||||
cursor = (
|
cursor = (
|
||||||
self._col.find(
|
self._col.find(
|
||||||
{"company_id": company_id, "user_id": user_id, "thread_id": thread_id}
|
{
|
||||||
|
"company_id": company_id,
|
||||||
|
"user_id": user_id,
|
||||||
|
"thread_id": thread_id,
|
||||||
|
# 兼容旧文档无 status;软删后 status=deleted
|
||||||
|
"$or": [
|
||||||
|
{"status": {"$exists": False}},
|
||||||
|
{"status": None},
|
||||||
|
{"status": {"$ne": "deleted"}},
|
||||||
|
],
|
||||||
|
}
|
||||||
)
|
)
|
||||||
.sort("seq", -1)
|
.sort("seq", -1)
|
||||||
.limit(limit)
|
.limit(limit)
|
||||||
@@ -203,6 +241,24 @@ class MongoMessageRepository(MessageRepository):
|
|||||||
rows.reverse()
|
rows.reverse()
|
||||||
return rows
|
return rows
|
||||||
|
|
||||||
|
async def soft_delete_by_thread(
|
||||||
|
self, company_id: int, user_id: str, thread_id: str
|
||||||
|
) -> int:
|
||||||
|
result = await self._col.update_many(
|
||||||
|
{
|
||||||
|
"company_id": company_id,
|
||||||
|
"user_id": user_id,
|
||||||
|
"thread_id": thread_id,
|
||||||
|
"$or": [
|
||||||
|
{"status": {"$exists": False}},
|
||||||
|
{"status": None},
|
||||||
|
{"status": {"$ne": "deleted"}},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{"$set": {"status": "deleted", "deleted_at": datetime.utcnow()}},
|
||||||
|
)
|
||||||
|
return int(result.modified_count or 0)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _to_msg(doc: dict[str, Any]) -> ChatMessage:
|
def _to_msg(doc: dict[str, Any]) -> ChatMessage:
|
||||||
return ChatMessage(
|
return ChatMessage(
|
||||||
|
|||||||
@@ -7,8 +7,9 @@ import json
|
|||||||
import redis.asyncio as redis
|
import redis.asyncio as redis
|
||||||
|
|
||||||
from config.settings import Settings
|
from config.settings import Settings
|
||||||
from domain.models import LlmRuntimeConfig
|
from domain.models import LlmProtocolCapability, LlmRuntimeConfig
|
||||||
from domain.ports import LlmRuntimeCache
|
from domain.ports import LlmProtocolCapabilityCache, LlmRuntimeCache
|
||||||
|
from infrastructure.llm.api_style import normalize_api_style
|
||||||
|
|
||||||
|
|
||||||
class RedisLlmRuntimeCache(LlmRuntimeCache):
|
class RedisLlmRuntimeCache(LlmRuntimeCache):
|
||||||
@@ -43,6 +44,7 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
|
|||||||
provider_id=_optional_int(data.get("provider_id")) or provider_id,
|
provider_id=_optional_int(data.get("provider_id")) or provider_id,
|
||||||
extra_headers=data.get("extra_headers") or {},
|
extra_headers=data.get("extra_headers") or {},
|
||||||
context_window=_optional_int(data.get("context_window")),
|
context_window=_optional_int(data.get("context_window")),
|
||||||
|
api_style=normalize_api_style(data.get("api_style")),
|
||||||
)
|
)
|
||||||
if model and cfg.model and cfg.model != model:
|
if model and cfg.model and cfg.model != model:
|
||||||
return None
|
return None
|
||||||
@@ -63,6 +65,7 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
|
|||||||
"model": config.model,
|
"model": config.model,
|
||||||
"extra_headers": config.extra_headers,
|
"extra_headers": config.extra_headers,
|
||||||
"context_window": config.context_window,
|
"context_window": config.context_window,
|
||||||
|
"api_style": normalize_api_style(config.api_style),
|
||||||
}
|
}
|
||||||
await self._r.set(
|
await self._r.set(
|
||||||
self._key(company_id, config.provider_id, config.model),
|
self._key(company_id, config.provider_id, config.model),
|
||||||
@@ -96,6 +99,53 @@ def get_redis(settings: Settings) -> redis.Redis:
|
|||||||
return _redis
|
return _redis
|
||||||
|
|
||||||
|
|
||||||
|
class RedisLlmProtocolCapabilityCache(LlmProtocolCapabilityCache):
|
||||||
|
"""按 provider_id(优先)或 base_url 缓存 Responses/store 能力。"""
|
||||||
|
|
||||||
|
def __init__(self, client: redis.Redis) -> None:
|
||||||
|
self._r = client
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _key(*, provider_id: int | None, base_url: str) -> str:
|
||||||
|
if provider_id is not None and int(provider_id) > 0:
|
||||||
|
return f"agent:llm:cap:p:{int(provider_id)}"
|
||||||
|
url = (base_url or "").rstrip("/").lower()
|
||||||
|
return f"agent:llm:cap:u:{url}"
|
||||||
|
|
||||||
|
async def get(
|
||||||
|
self, *, provider_id: int | None, base_url: str
|
||||||
|
) -> LlmProtocolCapability | None:
|
||||||
|
raw = await self._r.get(self._key(provider_id=provider_id, base_url=base_url))
|
||||||
|
if not raw:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
data = json.loads(raw)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return None
|
||||||
|
return LlmProtocolCapability(
|
||||||
|
responses=data.get("responses"),
|
||||||
|
store=data.get("store"),
|
||||||
|
)
|
||||||
|
|
||||||
|
async def set(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
provider_id: int | None,
|
||||||
|
base_url: str,
|
||||||
|
capability: LlmProtocolCapability,
|
||||||
|
ttl_seconds: int,
|
||||||
|
) -> None:
|
||||||
|
payload = {
|
||||||
|
"responses": capability.responses,
|
||||||
|
"store": capability.store,
|
||||||
|
}
|
||||||
|
await self._r.set(
|
||||||
|
self._key(provider_id=provider_id, base_url=base_url),
|
||||||
|
json.dumps(payload),
|
||||||
|
ex=max(60, ttl_seconds),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
async def close_redis() -> None:
|
async def close_redis() -> None:
|
||||||
global _redis
|
global _redis
|
||||||
if _redis is not None:
|
if _redis is not None:
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ motor>=3.6.0
|
|||||||
redis>=5.2.0
|
redis>=5.2.0
|
||||||
httpx>=0.27.0
|
httpx>=0.27.0
|
||||||
langchain-core>=0.3.0
|
langchain-core>=0.3.0
|
||||||
langchain-openai>=0.2.0
|
langchain-openai>=0.3.26
|
||||||
langchain-mcp-adapters>=0.1.0
|
langchain-mcp-adapters>=0.1.0
|
||||||
langgraph>=0.2.0
|
langgraph>=0.2.0
|
||||||
sse-starlette>=2.1.0
|
sse-starlette>=2.1.0
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
"""协议探测规划与错误分类。"""
|
||||||
|
|
||||||
|
from domain.models import LlmProtocolCapability
|
||||||
|
from infrastructure.llm.api_style import (
|
||||||
|
ProtocolAttempt,
|
||||||
|
classify_protocol_error,
|
||||||
|
normalize_api_style,
|
||||||
|
plan_protocol_attempts,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_normalize_api_style():
|
||||||
|
assert normalize_api_style(None) == "auto"
|
||||||
|
assert normalize_api_style("Responses") == "responses"
|
||||||
|
|
||||||
|
|
||||||
|
def test_plan_unknown_auto_tries_store_full_history_then_fallbacks():
|
||||||
|
attempts = plan_protocol_attempts("auto", None, has_chain_id=True)
|
||||||
|
assert attempts[0] == ProtocolAttempt(True, True, False)
|
||||||
|
assert ProtocolAttempt(True, False, False) in attempts
|
||||||
|
assert ProtocolAttempt(False, False, False) in attempts
|
||||||
|
assert not any(a.use_chain for a in attempts)
|
||||||
|
|
||||||
|
|
||||||
|
def test_plan_store_true_allows_chain():
|
||||||
|
cap = LlmProtocolCapability(responses=True, store=True)
|
||||||
|
attempts = plan_protocol_attempts("auto", cap, has_chain_id=True)
|
||||||
|
assert attempts[0] == ProtocolAttempt(True, True, True)
|
||||||
|
assert ProtocolAttempt(True, True, False) in attempts
|
||||||
|
|
||||||
|
|
||||||
|
def test_plan_store_false_prefers_stateless_responses_then_completions():
|
||||||
|
"""store 证伪:无状态 Responses(全量历史)→ Completions。"""
|
||||||
|
cap = LlmProtocolCapability(responses=True, store=False)
|
||||||
|
attempts = plan_protocol_attempts("auto", cap, has_chain_id=True)
|
||||||
|
assert attempts == [
|
||||||
|
ProtocolAttempt(True, False, False),
|
||||||
|
ProtocolAttempt(False, False, False),
|
||||||
|
]
|
||||||
|
assert not any(a.use_chain or a.use_store for a in attempts)
|
||||||
|
|
||||||
|
|
||||||
|
def test_plan_store_false_forced_responses_same_ladder():
|
||||||
|
cap = LlmProtocolCapability(responses=True, store=False)
|
||||||
|
attempts = plan_protocol_attempts("responses", cap, has_chain_id=False)
|
||||||
|
assert attempts[0] == ProtocolAttempt(True, False, False)
|
||||||
|
assert ProtocolAttempt(False, False, False) in attempts
|
||||||
|
|
||||||
|
|
||||||
|
def test_plan_completions_only():
|
||||||
|
assert plan_protocol_attempts("completions", None, has_chain_id=True) == [
|
||||||
|
ProtocolAttempt(False, False, False)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_plan_responses_known_unsupported_falls_to_completions():
|
||||||
|
cap = LlmProtocolCapability(responses=False, store=False)
|
||||||
|
attempts = plan_protocol_attempts("auto", cap, has_chain_id=False)
|
||||||
|
assert attempts == [ProtocolAttempt(False, False, False)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_classify_protocol_error():
|
||||||
|
assert classify_protocol_error(Exception("Invalid previous_response_id")) == "chain"
|
||||||
|
assert (
|
||||||
|
classify_protocol_error(Exception("Unsupported parameter: store")) == "store"
|
||||||
|
)
|
||||||
|
assert classify_protocol_error(Exception("404 /v1/responses not found")) == "responses"
|
||||||
|
assert classify_protocol_error(Exception("rate limit")) == "other"
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
"""会话链选型匹配。"""
|
||||||
|
|
||||||
|
from domain.models import LlmResponseChain, LlmRuntimeConfig
|
||||||
|
from application.chat_service import _usable_chain_id
|
||||||
|
|
||||||
|
|
||||||
|
def test_usable_chain_id_matches():
|
||||||
|
llm = LlmRuntimeConfig(
|
||||||
|
base_url="https://api.openai.com/v1",
|
||||||
|
api_key="k",
|
||||||
|
model="gpt-4o-mini",
|
||||||
|
provider_id=3,
|
||||||
|
api_style="auto",
|
||||||
|
)
|
||||||
|
chain = LlmResponseChain(
|
||||||
|
provider_id=3, model="gpt-4o-mini", previous_response_id="resp_abc"
|
||||||
|
)
|
||||||
|
assert _usable_chain_id(chain, llm) == "resp_abc"
|
||||||
|
|
||||||
|
|
||||||
|
def test_usable_chain_id_clears_on_model_switch():
|
||||||
|
llm = LlmRuntimeConfig(
|
||||||
|
base_url="https://api.openai.com/v1",
|
||||||
|
api_key="k",
|
||||||
|
model="gpt-4o",
|
||||||
|
provider_id=3,
|
||||||
|
api_style="auto",
|
||||||
|
)
|
||||||
|
chain = LlmResponseChain(
|
||||||
|
provider_id=3, model="gpt-4o-mini", previous_response_id="resp_abc"
|
||||||
|
)
|
||||||
|
assert _usable_chain_id(chain, llm) is None
|
||||||
@@ -16,6 +16,7 @@ CREATE TABLE IF NOT EXISTS `agent_company_llm_provider` (
|
|||||||
`api_key_encrypted` varchar(2000) NOT NULL COMMENT 'API Key 密文',
|
`api_key_encrypted` varchar(2000) NOT NULL COMMENT 'API Key 密文',
|
||||||
`api_key_suffix` varchar(16) NOT NULL DEFAULT '' COMMENT 'Key 末几位(展示掩码)',
|
`api_key_suffix` varchar(16) NOT NULL DEFAULT '' COMMENT 'Key 末几位(展示掩码)',
|
||||||
`display_name` varchar(100) NULL COMMENT '展示名,如 DeepSeek',
|
`display_name` varchar(100) NULL COMMENT '展示名,如 DeepSeek',
|
||||||
|
`api_style` varchar(32) NOT NULL DEFAULT 'auto' COMMENT 'API协议:auto|completions|responses',
|
||||||
`extra_headers_json` json NULL COMMENT '可选额外请求头',
|
`extra_headers_json` json NULL COMMENT '可选额外请求头',
|
||||||
`create_by` bigint UNSIGNED NULL COMMENT '创建人用户ID',
|
`create_by` bigint UNSIGNED NULL COMMENT '创建人用户ID',
|
||||||
`update_by` bigint UNSIGNED NULL COMMENT '更新人用户ID',
|
`update_by` bigint UNSIGNED NULL COMMENT '更新人用户ID',
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
-- 提供商增加 API 协议风格:auto | completions | responses
|
||||||
|
ALTER TABLE `agent_company_llm_provider`
|
||||||
|
ADD COLUMN `api_style` varchar(32) NOT NULL DEFAULT 'auto'
|
||||||
|
COMMENT 'API协议:auto=按base_url推断;completions;responses'
|
||||||
|
AFTER `display_name`;
|
||||||
+5
@@ -16,4 +16,9 @@ public class CreateAgentLlmProviderDTO {
|
|||||||
private String apiKey;
|
private String apiKey;
|
||||||
|
|
||||||
private String displayName;
|
private String displayName;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* API 协议:auto | completions | responses;空则 auto
|
||||||
|
*/
|
||||||
|
private String apiStyle;
|
||||||
}
|
}
|
||||||
|
|||||||
+5
@@ -16,4 +16,9 @@ public class UpdateAgentLlmProviderDTO {
|
|||||||
|
|
||||||
/** 传 null 表示不改;传空串可清空备注 */
|
/** 传 null 表示不改;传空串可清空备注 */
|
||||||
private String displayName;
|
private String displayName;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* API 协议:auto | completions | responses;null 不改
|
||||||
|
*/
|
||||||
|
private String apiStyle;
|
||||||
}
|
}
|
||||||
|
|||||||
+6
@@ -33,6 +33,12 @@ public class AgentCompanyLlmProviderPO {
|
|||||||
@TableField("display_name")
|
@TableField("display_name")
|
||||||
private String displayName;
|
private String displayName;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* API 协议:auto | completions | responses
|
||||||
|
*/
|
||||||
|
@TableField("api_style")
|
||||||
|
private String apiStyle;
|
||||||
|
|
||||||
@TableField("extra_headers_json")
|
@TableField("extra_headers_json")
|
||||||
private String extraHeadersJson;
|
private String extraHeadersJson;
|
||||||
|
|
||||||
|
|||||||
+4
@@ -16,5 +16,9 @@ public class AgentLlmProviderVO {
|
|||||||
private String displayName;
|
private String displayName;
|
||||||
private String apiKeyMasked;
|
private String apiKeyMasked;
|
||||||
private String updateTime;
|
private String updateTime;
|
||||||
|
/**
|
||||||
|
* API 协议:auto | completions | responses
|
||||||
|
*/
|
||||||
|
private String apiStyle;
|
||||||
private List<AgentLlmModelVO> models = new ArrayList<>();
|
private List<AgentLlmModelVO> models = new ArrayList<>();
|
||||||
}
|
}
|
||||||
|
|||||||
+4
@@ -15,5 +15,9 @@ public class AgentLlmRuntimeVO {
|
|||||||
private String model;
|
private String model;
|
||||||
/** 上下文窗口 token;可能为 null */
|
/** 上下文窗口 token;可能为 null */
|
||||||
private Integer contextWindow;
|
private Integer contextWindow;
|
||||||
|
/**
|
||||||
|
* API 协议:auto | completions | responses
|
||||||
|
*/
|
||||||
|
private String apiStyle;
|
||||||
private Map<String, String> extraHeaders;
|
private Map<String, String> extraHeaders;
|
||||||
}
|
}
|
||||||
|
|||||||
+20
@@ -98,6 +98,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
po.setApiKeyEncrypted(crypto.encrypt(plain));
|
po.setApiKeyEncrypted(crypto.encrypt(plain));
|
||||||
po.setApiKeySuffix(plain.length() >= 4 ? plain.substring(plain.length() - 4) : plain);
|
po.setApiKeySuffix(plain.length() >= 4 ? plain.substring(plain.length() - 4) : plain);
|
||||||
po.setDisplayName(trimToNull(dto.getDisplayName()));
|
po.setDisplayName(trimToNull(dto.getDisplayName()));
|
||||||
|
po.setApiStyle(normalizeApiStyle(dto.getApiStyle()));
|
||||||
po.setCreateBy(userId);
|
po.setCreateBy(userId);
|
||||||
po.setUpdateBy(userId);
|
po.setUpdateBy(userId);
|
||||||
providerMapper.insert(po);
|
providerMapper.insert(po);
|
||||||
@@ -123,6 +124,9 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
if (dto.getDisplayName() != null) {
|
if (dto.getDisplayName() != null) {
|
||||||
existing.setDisplayName(trimToNull(dto.getDisplayName()));
|
existing.setDisplayName(trimToNull(dto.getDisplayName()));
|
||||||
}
|
}
|
||||||
|
if (dto.getApiStyle() != null) {
|
||||||
|
existing.setApiStyle(normalizeApiStyle(dto.getApiStyle()));
|
||||||
|
}
|
||||||
existing.setUpdateBy(userId);
|
existing.setUpdateBy(userId);
|
||||||
providerMapper.updateById(existing);
|
providerMapper.updateById(existing);
|
||||||
evictRuntimeCache(companyId);
|
evictRuntimeCache(companyId);
|
||||||
@@ -432,6 +436,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
vo.setApiKey(crypto.decrypt(provider.getApiKeyEncrypted()));
|
vo.setApiKey(crypto.decrypt(provider.getApiKeyEncrypted()));
|
||||||
vo.setModel(model.getModel());
|
vo.setModel(model.getModel());
|
||||||
vo.setContextWindow(model.getContextWindow());
|
vo.setContextWindow(model.getContextWindow());
|
||||||
|
vo.setApiStyle(normalizeApiStyle(provider.getApiStyle()));
|
||||||
vo.setExtraHeaders(parseHeaders(provider.getExtraHeadersJson()));
|
vo.setExtraHeaders(parseHeaders(provider.getExtraHeadersJson()));
|
||||||
return vo;
|
return vo;
|
||||||
}
|
}
|
||||||
@@ -450,6 +455,17 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static String normalizeApiStyle(String raw) {
|
||||||
|
if (!StringUtils.hasText(raw)) {
|
||||||
|
return "auto";
|
||||||
|
}
|
||||||
|
String s = raw.trim().toLowerCase();
|
||||||
|
if ("auto".equals(s) || "completions".equals(s) || "responses".equals(s)) {
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
throw new BusinessException("apiStyle 必须是 auto / completions / responses");
|
||||||
|
}
|
||||||
|
|
||||||
private static Integer normalizeContextWindow(Integer raw) {
|
private static Integer normalizeContextWindow(Integer raw) {
|
||||||
if (raw == null || raw <= 0) {
|
if (raw == null || raw <= 0) {
|
||||||
return null;
|
return null;
|
||||||
@@ -546,6 +562,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
vo.setConfigured(true);
|
vo.setConfigured(true);
|
||||||
vo.setBaseUrl(provider.getBaseUrl());
|
vo.setBaseUrl(provider.getBaseUrl());
|
||||||
vo.setDisplayName(provider.getDisplayName());
|
vo.setDisplayName(provider.getDisplayName());
|
||||||
|
vo.setApiStyle(normalizeApiStyle(provider.getApiStyle()));
|
||||||
vo.setApiKeyMasked("****" + (provider.getApiKeySuffix() == null ? "" : provider.getApiKeySuffix()));
|
vo.setApiKeyMasked("****" + (provider.getApiKeySuffix() == null ? "" : provider.getApiKeySuffix()));
|
||||||
if (provider.getUpdateTime() != null) {
|
if (provider.getUpdateTime() != null) {
|
||||||
vo.setUpdateTime(provider.getUpdateTime().format(ISO));
|
vo.setUpdateTime(provider.getUpdateTime().format(ISO));
|
||||||
@@ -570,6 +587,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
payload.put("api_key", runtime.getApiKey());
|
payload.put("api_key", runtime.getApiKey());
|
||||||
payload.put("model", runtime.getModel());
|
payload.put("model", runtime.getModel());
|
||||||
payload.put("context_window", runtime.getContextWindow());
|
payload.put("context_window", runtime.getContextWindow());
|
||||||
|
payload.put("api_style", runtime.getApiStyle() == null ? "auto" : runtime.getApiStyle());
|
||||||
payload.put("extra_headers",
|
payload.put("extra_headers",
|
||||||
runtime.getExtraHeaders() == null ? Map.of() : runtime.getExtraHeaders());
|
runtime.getExtraHeaders() == null ? Map.of() : runtime.getExtraHeaders());
|
||||||
stringRedisTemplate.opsForValue().set(
|
stringRedisTemplate.opsForValue().set(
|
||||||
@@ -612,6 +630,8 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
} else {
|
} else {
|
||||||
vo.setContextWindow(null);
|
vo.setContextWindow(null);
|
||||||
}
|
}
|
||||||
|
Object style = map.get("api_style");
|
||||||
|
vo.setApiStyle(style == null ? "auto" : normalizeApiStyle(String.valueOf(style)));
|
||||||
Object headers = map.get("extra_headers");
|
Object headers = map.get("extra_headers");
|
||||||
if (headers instanceof Map<?, ?> m) {
|
if (headers instanceof Map<?, ?> m) {
|
||||||
Map<String, String> h = new HashMap<>();
|
Map<String, String> h = new HashMap<>();
|
||||||
|
|||||||
@@ -53,6 +53,8 @@ export namespace AgentVO {
|
|||||||
configured: boolean;
|
configured: boolean;
|
||||||
baseUrl?: string | null;
|
baseUrl?: string | null;
|
||||||
displayName?: string | null;
|
displayName?: string | null;
|
||||||
|
/** auto | completions | responses */
|
||||||
|
apiStyle?: string | null;
|
||||||
apiKeyMasked?: string | null;
|
apiKeyMasked?: string | null;
|
||||||
models?: LlmModelItem[];
|
models?: LlmModelItem[];
|
||||||
updateTime?: string;
|
updateTime?: string;
|
||||||
@@ -110,6 +112,11 @@ export async function patchAgentSessionApi(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 软删会话(级联软删消息) */
|
||||||
|
export async function deleteAgentSessionApi(threadId: string) {
|
||||||
|
return requestClient.delete<AgentVO.Session>(`/agent/sessions/${threadId}`);
|
||||||
|
}
|
||||||
|
|
||||||
export async function listAgentMessagesApi(threadId: string) {
|
export async function listAgentMessagesApi(threadId: string) {
|
||||||
return requestClient.get<{ items: AgentVO.Message[] }>(
|
return requestClient.get<{ items: AgentVO.Message[] }>(
|
||||||
`/agent/sessions/${threadId}/messages`,
|
`/agent/sessions/${threadId}/messages`,
|
||||||
@@ -140,6 +147,7 @@ export async function createAgentLlmProviderApi(body: {
|
|||||||
baseUrl: string;
|
baseUrl: string;
|
||||||
apiKey: string;
|
apiKey: string;
|
||||||
displayName?: string;
|
displayName?: string;
|
||||||
|
apiStyle?: string;
|
||||||
}) {
|
}) {
|
||||||
return requestClient.post<AgentVO.LlmProvider>(
|
return requestClient.post<AgentVO.LlmProvider>(
|
||||||
'/company/agent-llm-providers',
|
'/company/agent-llm-providers',
|
||||||
@@ -149,7 +157,12 @@ export async function createAgentLlmProviderApi(body: {
|
|||||||
|
|
||||||
export async function updateAgentLlmProviderApi(
|
export async function updateAgentLlmProviderApi(
|
||||||
providerId: number,
|
providerId: number,
|
||||||
body: { baseUrl?: string; apiKey?: string; displayName?: string },
|
body: {
|
||||||
|
baseUrl?: string;
|
||||||
|
apiKey?: string;
|
||||||
|
displayName?: string;
|
||||||
|
apiStyle?: string;
|
||||||
|
},
|
||||||
) {
|
) {
|
||||||
return requestClient.put<AgentVO.LlmProvider>(
|
return requestClient.put<AgentVO.LlmProvider>(
|
||||||
`/company/agent-llm-providers/${providerId}`,
|
`/company/agent-llm-providers/${providerId}`,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ export {
|
|||||||
createAgentSessionApi,
|
createAgentSessionApi,
|
||||||
deleteAgentLlmProviderApi,
|
deleteAgentLlmProviderApi,
|
||||||
deleteAgentMemoryApi,
|
deleteAgentMemoryApi,
|
||||||
|
deleteAgentSessionApi,
|
||||||
getAgentLlmProviderApi,
|
getAgentLlmProviderApi,
|
||||||
listAgentEnabledLlmModelsApi,
|
listAgentEnabledLlmModelsApi,
|
||||||
listAgentLlmProvidersApi,
|
listAgentLlmProvidersApi,
|
||||||
|
|||||||
@@ -113,10 +113,8 @@ const UserIcon = createIconifyIcon('lucide:user');
|
|||||||
const MemoryIcon = createIconifyIcon('lucide:brain');
|
const MemoryIcon = createIconifyIcon('lucide:brain');
|
||||||
// 意见反馈图标
|
// 意见反馈图标
|
||||||
const FeedbackIcon = createIconifyIcon('lucide:message-square-plus');
|
const FeedbackIcon = createIconifyIcon('lucide:message-square-plus');
|
||||||
// 锁图标
|
|
||||||
const LockIcon = createIconifyIcon('lucide:lock');
|
|
||||||
|
|
||||||
/** 是否具备智能助手聊天权限(用于「我的记忆」入口;含超管) */
|
/** 是否具备智能助手聊天权限(用于「助手记忆」入口;含超管) */
|
||||||
const canUseAgentChat = computed(() => hasPermission('agent:chat'));
|
const canUseAgentChat = computed(() => hasPermission('agent:chat'));
|
||||||
|
|
||||||
/** 当前用户可切换的可用公司数 */
|
/** 当前用户可切换的可用公司数 */
|
||||||
@@ -128,22 +126,22 @@ const companyCount = computed(() => {
|
|||||||
const menus = computed(() => {
|
const menus = computed(() => {
|
||||||
const menuItems = [];
|
const menuItems = [];
|
||||||
|
|
||||||
// 个人信息
|
// 个人中心
|
||||||
menuItems.push({
|
menuItems.push({
|
||||||
handler: () => {
|
handler: () => {
|
||||||
router.push('/system/profile');
|
router.push('/system/profile');
|
||||||
},
|
},
|
||||||
icon: UserIcon,
|
icon: UserIcon,
|
||||||
text: '个人信息',
|
text: '个人中心',
|
||||||
});
|
});
|
||||||
// 我的记忆(有助手聊天权才显示)
|
// 助手记忆(有助手聊天权才显示)
|
||||||
if (canUseAgentChat.value) {
|
if (canUseAgentChat.value) {
|
||||||
menuItems.push({
|
menuItems.push({
|
||||||
handler: () => {
|
handler: () => {
|
||||||
router.push('/agent/memories');
|
router.push('/agent/memories');
|
||||||
},
|
},
|
||||||
icon: MemoryIcon,
|
icon: MemoryIcon,
|
||||||
text: '我的记忆',
|
text: '助手记忆',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
// 意见反馈
|
// 意见反馈
|
||||||
@@ -154,14 +152,6 @@ const menus = computed(() => {
|
|||||||
icon: FeedbackIcon,
|
icon: FeedbackIcon,
|
||||||
text: '意见反馈',
|
text: '意见反馈',
|
||||||
});
|
});
|
||||||
// 修改密码
|
|
||||||
menuItems.push({
|
|
||||||
handler: () => {
|
|
||||||
router.push('/system/change-password');
|
|
||||||
},
|
|
||||||
icon: LockIcon,
|
|
||||||
text: '修改密码',
|
|
||||||
});
|
|
||||||
|
|
||||||
// 可切换公司数大于 1 时显示切换公司
|
// 可切换公司数大于 1 时显示切换公司
|
||||||
if (companyCount.value > 1) {
|
if (companyCount.value > 1) {
|
||||||
|
|||||||
@@ -1,16 +1,13 @@
|
|||||||
import type { RouteRecordRaw } from 'vue-router';
|
import type { RouteRecordRaw } from 'vue-router';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 修改密码静态路由
|
* 修改密码:并入个人中心,保留旧路径兼容跳转
|
||||||
*/
|
*/
|
||||||
const staticRoutes: RouteRecordRaw[] = [
|
const staticRoutes: RouteRecordRaw[] = [
|
||||||
{
|
{
|
||||||
name: 'ChangePassword',
|
name: 'ChangePassword',
|
||||||
path: '/system/change-password',
|
path: '/system/change-password',
|
||||||
component: () =>
|
redirect: '/system/profile?tab=password',
|
||||||
import(
|
|
||||||
'#/views/sys/profile/modules/ChangePasswordModal.vue'
|
|
||||||
),
|
|
||||||
meta: {
|
meta: {
|
||||||
title: '修改密码',
|
title: '修改密码',
|
||||||
hideInMenu: true,
|
hideInMenu: true,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { RouteRecordRaw } from 'vue-router';
|
import type { RouteRecordRaw } from 'vue-router';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 用户记忆管理(头像下拉入口;不进侧栏菜单)
|
* 助手长期记忆管理(头像下拉「助手记忆」入口;不进侧栏菜单)
|
||||||
*/
|
*/
|
||||||
const staticRoutes: RouteRecordRaw[] = [
|
const staticRoutes: RouteRecordRaw[] = [
|
||||||
{
|
{
|
||||||
@@ -10,7 +10,7 @@ const staticRoutes: RouteRecordRaw[] = [
|
|||||||
component: () => import('#/views/agent/memories/index.vue'),
|
component: () => import('#/views/agent/memories/index.vue'),
|
||||||
meta: {
|
meta: {
|
||||||
icon: 'lucide:brain',
|
icon: 'lucide:brain',
|
||||||
title: '我的记忆',
|
title: '助手记忆',
|
||||||
hideInMenu: true,
|
hideInMenu: true,
|
||||||
ignoreAccess: true,
|
ignoreAccess: true,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -5,14 +5,16 @@ import type { RouteRecordRaw } from 'vue-router';
|
|||||||
*/
|
*/
|
||||||
const staticRoutes: RouteRecordRaw[] = [
|
const staticRoutes: RouteRecordRaw[] = [
|
||||||
{
|
{
|
||||||
name: 'PersonalProfile',
|
name: 'PersonalCenter',
|
||||||
path: '/system/profile',
|
path: '/system/profile',
|
||||||
component: () => import('#/views/sys/profile/index.vue'),
|
component: () => import('#/views/sys/profile/index.vue'),
|
||||||
meta: {
|
meta: {
|
||||||
icon: 'lucide:user',
|
icon: 'lucide:user',
|
||||||
title: '个人信息',
|
title: '个人中心',
|
||||||
hideInMenu: true,
|
hideInMenu: true,
|
||||||
ignoreAccess: true,
|
ignoreAccess: true,
|
||||||
|
// 页内 ?tab= 不另开系统标签
|
||||||
|
fullPathKey: false,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||||
|
|
||||||
import { message } from 'ant-design-vue';
|
import { createIconifyIcon } from '@vben/icons';
|
||||||
|
import { Tooltip, message } from 'ant-design-vue';
|
||||||
import { ChatSender } from '@tdesign-vue-next/chat';
|
import { ChatSender } from '@tdesign-vue-next/chat';
|
||||||
|
|
||||||
import { getProductPageApi } from '#/api/ec/product';
|
import { getProductPageApi } from '#/api/ec/product';
|
||||||
@@ -19,13 +20,24 @@ import {
|
|||||||
type CatalogCiteKind,
|
type CatalogCiteKind,
|
||||||
} from './catalog-cite';
|
} from './catalog-cite';
|
||||||
|
|
||||||
|
const ArrowUpIcon = createIconifyIcon('lucide:arrow-up');
|
||||||
|
const ExpandIcon = createIconifyIcon('lucide:maximize-2');
|
||||||
|
const CollapseIcon = createIconifyIcon('lucide:minimize-2');
|
||||||
|
|
||||||
/** 包一层 ChatSender:@ 先选分类,选中后在输入行内嵌标签。 */
|
/** 包一层 ChatSender:@ 先选分类,选中后在输入行内嵌标签。 */
|
||||||
const draft = defineModel<string>({ required: true });
|
const draft = defineModel<string>({ required: true });
|
||||||
const cites = defineModel<CatalogCite[]>('cites', { required: true });
|
const cites = defineModel<CatalogCite[]>('cites', { required: true });
|
||||||
|
|
||||||
defineProps<{
|
const props = withDefaults(
|
||||||
loading?: boolean;
|
defineProps<{
|
||||||
}>();
|
loading?: boolean;
|
||||||
|
/** 输入框占位;默认面向通用助手 */
|
||||||
|
placeholder?: string;
|
||||||
|
}>(),
|
||||||
|
{
|
||||||
|
placeholder: '问点什么,或用 @ 引用店铺 / 商品 / SKU',
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
send: [value: string];
|
send: [value: string];
|
||||||
@@ -39,6 +51,10 @@ const dismissed = ref(false);
|
|||||||
const loadingList = ref(false);
|
const loadingList = ref(false);
|
||||||
const activeKey = ref('');
|
const activeKey = ref('');
|
||||||
const items = ref<CatalogCite[]>([]);
|
const items = ref<CatalogCite[]>([]);
|
||||||
|
/** 输入框是否已手动展开 */
|
||||||
|
const expanded = ref(false);
|
||||||
|
/** 内容是否超过 1 行(用于显示右上角展开按钮) */
|
||||||
|
const multiLine = ref(false);
|
||||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||||
let seq = 0;
|
let seq = 0;
|
||||||
|
|
||||||
@@ -47,6 +63,19 @@ const menuOpen = computed(
|
|||||||
() => mentionQuery.value !== null && !dismissed.value,
|
() => mentionQuery.value !== null && !dismissed.value,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/** 未展开:1~14 行自动增高;展开后再抬高上限 */
|
||||||
|
const textareaAutosize = computed(() =>
|
||||||
|
expanded.value
|
||||||
|
? { minRows: 8, maxRows: 28 }
|
||||||
|
: { minRows: 1, maxRows: 14 },
|
||||||
|
);
|
||||||
|
|
||||||
|
const showExpandToggle = computed(() => expanded.value || multiLine.value);
|
||||||
|
|
||||||
|
const canSend = computed(
|
||||||
|
() => !props.loading && !!(draft.value || '').trim(),
|
||||||
|
);
|
||||||
|
|
||||||
watch(mentionQuery, (query, prev) => {
|
watch(mentionQuery, (query, prev) => {
|
||||||
if (query !== prev) {
|
if (query !== prev) {
|
||||||
dismissed.value = false;
|
dismissed.value = false;
|
||||||
@@ -67,6 +96,14 @@ watch(kind, () => {
|
|||||||
scheduleSearch(mentionQuery.value);
|
scheduleSearch(mentionQuery.value);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
watch(draft, () => {
|
||||||
|
checkMultiLine();
|
||||||
|
});
|
||||||
|
|
||||||
|
watch(expanded, () => {
|
||||||
|
void nextTick(() => checkMultiLine());
|
||||||
|
});
|
||||||
|
|
||||||
function scheduleSearch(query: string) {
|
function scheduleSearch(query: string) {
|
||||||
if (timer) clearTimeout(timer);
|
if (timer) clearTimeout(timer);
|
||||||
loadingList.value = true;
|
loadingList.value = true;
|
||||||
@@ -131,7 +168,93 @@ async function safeList(task: Promise<CatalogCite[]>) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 按可视行数判断:超过 1 行就稳定显示展开按钮(不依赖 scroll overflow,避免 autosize 时闪烁消失) */
|
||||||
|
function checkMultiLine() {
|
||||||
|
const run = () => {
|
||||||
|
const el = rootRef.value?.querySelector('textarea');
|
||||||
|
if (!el) {
|
||||||
|
multiLine.value = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (expanded.value) {
|
||||||
|
multiLine.value = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const text = draft.value || '';
|
||||||
|
if (!text) {
|
||||||
|
multiLine.value = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 显式换行
|
||||||
|
if (text.includes('\n')) {
|
||||||
|
multiLine.value = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const style = window.getComputedStyle(el);
|
||||||
|
const lineHeight = parseFloat(style.lineHeight);
|
||||||
|
const fontSize = parseFloat(style.fontSize) || 14;
|
||||||
|
const lh =
|
||||||
|
Number.isFinite(lineHeight) && lineHeight > 0 ? lineHeight : fontSize * 1.5;
|
||||||
|
const padY =
|
||||||
|
(parseFloat(style.paddingTop) || 0) +
|
||||||
|
(parseFloat(style.paddingBottom) || 0);
|
||||||
|
// scrollHeight 在 autosize 下仍反映内容总高度
|
||||||
|
const rows = Math.max(1, Math.round((el.scrollHeight - padY) / lh));
|
||||||
|
multiLine.value = rows > 1;
|
||||||
|
};
|
||||||
|
// 等 autosize 改完高度再量,避免中间态误判
|
||||||
|
void nextTick(() => {
|
||||||
|
requestAnimationFrame(run);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleExpand() {
|
||||||
|
expanded.value = !expanded.value;
|
||||||
|
focusInput();
|
||||||
|
}
|
||||||
|
|
||||||
|
function onSendClick() {
|
||||||
|
const text = draft.value;
|
||||||
|
if (!text?.trim() || props.loading) return;
|
||||||
|
emit('send', text);
|
||||||
|
resetExpandAfterSend();
|
||||||
|
}
|
||||||
|
|
||||||
|
function onChatSend(value: string) {
|
||||||
|
emit('send', value);
|
||||||
|
resetExpandAfterSend();
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetExpandAfterSend() {
|
||||||
|
expanded.value = false;
|
||||||
|
multiLine.value = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function onStopClick() {
|
||||||
|
emit('stop');
|
||||||
|
}
|
||||||
|
|
||||||
function onKeydown(event: KeyboardEvent) {
|
function onKeydown(event: KeyboardEvent) {
|
||||||
|
// 光标在输入框开头(或内容为空)时,Backspace 删掉最后一个引用 chip
|
||||||
|
if (
|
||||||
|
event.key === 'Backspace' &&
|
||||||
|
!event.isComposing &&
|
||||||
|
event.keyCode !== 229 &&
|
||||||
|
cites.value.length > 0
|
||||||
|
) {
|
||||||
|
const el = rootRef.value?.querySelector('textarea');
|
||||||
|
if (el) {
|
||||||
|
const atStart = el.selectionStart === 0 && el.selectionEnd === 0;
|
||||||
|
if (atStart || !draft.value) {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
const last = cites.value[cites.value.length - 1];
|
||||||
|
if (last) removeCite(last.key);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (!menuOpen.value || event.isComposing || event.keyCode === 229) return;
|
if (!menuOpen.value || event.isComposing || event.keyCode === 229) return;
|
||||||
if (event.key === 'ArrowDown') {
|
if (event.key === 'ArrowDown') {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
@@ -228,17 +351,40 @@ onBeforeUnmount(() => {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div ref="rootRef" class="catalog-cite-sender relative" @keydown.capture="onKeydown">
|
<div
|
||||||
|
ref="rootRef"
|
||||||
|
class="catalog-cite-sender relative"
|
||||||
|
:class="{ 'catalog-cite-sender--expandable': showExpandToggle }"
|
||||||
|
@keydown.capture="onKeydown"
|
||||||
|
>
|
||||||
|
<!-- 展开/收起固定在输入框右上角 -->
|
||||||
|
<Tooltip
|
||||||
|
v-if="showExpandToggle"
|
||||||
|
:title="expanded ? '收起输入框' : '展开输入框'"
|
||||||
|
placement="top"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="sender-expand-corner text-muted-foreground hover:text-foreground hover:bg-muted"
|
||||||
|
:aria-label="expanded ? '收起输入框' : '展开输入框'"
|
||||||
|
@mousedown.prevent
|
||||||
|
@click="toggleExpand"
|
||||||
|
>
|
||||||
|
<CollapseIcon v-if="expanded" class="size-4" />
|
||||||
|
<ExpandIcon v-else class="size-4" />
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
v-if="menuOpen"
|
v-if="menuOpen"
|
||||||
class="border-border bg-card absolute bottom-full left-0 z-20 mb-2 w-80 overflow-hidden rounded-lg border shadow-lg"
|
class="border-border bg-popover absolute bottom-full left-0 z-20 mb-2 w-80 overflow-hidden rounded-lg border shadow-lg"
|
||||||
>
|
>
|
||||||
<div class="flex gap-1 p-1.5">
|
<div class="flex shrink-0 gap-1 p-1.5">
|
||||||
<button
|
<button
|
||||||
v-for="item in kinds"
|
v-for="item in kinds"
|
||||||
:key="item"
|
:key="item"
|
||||||
type="button"
|
type="button"
|
||||||
class="flex-1 rounded-md px-2 py-1.5 text-xs"
|
class="flex-1 cursor-pointer rounded-md px-2 py-1.5 text-xs"
|
||||||
:class="
|
:class="
|
||||||
item === kind
|
item === kind
|
||||||
? 'bg-primary/10 text-primary font-medium'
|
? 'bg-primary/10 text-primary font-medium'
|
||||||
@@ -249,16 +395,17 @@ onBeforeUnmount(() => {
|
|||||||
{{ catalogCiteLabel(item) }}
|
{{ catalogCiteLabel(item) }}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="max-h-72 overflow-y-auto py-1">
|
<!-- 固定高度,避免加载前后弹层跳动 -->
|
||||||
|
<div class="cite-menu-list h-72 overflow-y-auto py-1">
|
||||||
<div
|
<div
|
||||||
v-if="loadingList && items.length === 0"
|
v-if="loadingList && items.length === 0"
|
||||||
class="text-muted-foreground px-3 py-6 text-center text-xs"
|
class="text-muted-foreground flex h-full items-center justify-center px-3 text-center text-xs"
|
||||||
>
|
>
|
||||||
搜索中…
|
搜索中…
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
v-else-if="items.length === 0"
|
v-else-if="items.length === 0"
|
||||||
class="text-muted-foreground px-3 py-6 text-center text-xs"
|
class="text-muted-foreground flex h-full items-center justify-center px-3 text-center text-xs"
|
||||||
>
|
>
|
||||||
这个分类下没有匹配
|
这个分类下没有匹配
|
||||||
</div>
|
</div>
|
||||||
@@ -268,7 +415,7 @@ onBeforeUnmount(() => {
|
|||||||
:key="item.key"
|
:key="item.key"
|
||||||
type="button"
|
type="button"
|
||||||
:data-cite-key="item.key"
|
:data-cite-key="item.key"
|
||||||
class="flex w-full flex-col px-3 py-1.5 text-left"
|
class="flex w-full cursor-pointer flex-col px-3 py-1.5 text-left"
|
||||||
:class="item.key === activeKey ? 'bg-primary/10' : 'hover:bg-muted'"
|
:class="item.key === activeKey ? 'bg-primary/10' : 'hover:bg-muted'"
|
||||||
@mouseenter="activeKey = item.key"
|
@mouseenter="activeKey = item.key"
|
||||||
@mousedown.prevent="pick(item)"
|
@mousedown.prevent="pick(item)"
|
||||||
@@ -284,7 +431,7 @@ onBeforeUnmount(() => {
|
|||||||
</template>
|
</template>
|
||||||
</div>
|
</div>
|
||||||
<div class="text-muted-foreground border-border border-t px-3 py-1.5 text-[11px]">
|
<div class="text-muted-foreground border-border border-t px-3 py-1.5 text-[11px]">
|
||||||
↑↓ 选择 · Enter 引用 · Esc 关闭
|
↑↓ 选择 · Enter 引用 · Esc 关闭 · ⌫ 删引用
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -292,9 +439,9 @@ onBeforeUnmount(() => {
|
|||||||
v-model="draft"
|
v-model="draft"
|
||||||
class="agent-td-sender"
|
class="agent-td-sender"
|
||||||
:loading="loading"
|
:loading="loading"
|
||||||
placeholder="输入问题,@ 引用店铺、商品或 SKU"
|
:placeholder="placeholder"
|
||||||
:textarea-props="{ autosize: { minRows: 2, maxRows: 6 } }"
|
:textarea-props="{ autosize: textareaAutosize }"
|
||||||
@send="emit('send', $event)"
|
@send="onChatSend"
|
||||||
@stop="emit('stop')"
|
@stop="emit('stop')"
|
||||||
>
|
>
|
||||||
<template #input-prefix>
|
<template #input-prefix>
|
||||||
@@ -308,7 +455,7 @@ onBeforeUnmount(() => {
|
|||||||
<span class="truncate">{{ cite.title }}</span>
|
<span class="truncate">{{ cite.title }}</span>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="opacity-60 hover:opacity-100"
|
class="cursor-pointer opacity-60 hover:opacity-100"
|
||||||
aria-label="移除引用"
|
aria-label="移除引用"
|
||||||
@mousedown.prevent
|
@mousedown.prevent
|
||||||
@click="removeCite(cite.key)"
|
@click="removeCite(cite.key)"
|
||||||
@@ -319,13 +466,44 @@ onBeforeUnmount(() => {
|
|||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
<template #footer-prefix>
|
<template #footer-prefix>
|
||||||
<button
|
<div class="catalog-cite-footer flex min-w-0 flex-1 items-center gap-2">
|
||||||
type="button"
|
<button
|
||||||
class="text-muted-foreground hover:text-primary rounded px-1 py-1 text-xs"
|
type="button"
|
||||||
@click="insertMention"
|
class="text-muted-foreground hover:text-primary shrink-0 cursor-pointer rounded px-1 py-1 text-xs"
|
||||||
>
|
@click="insertMention"
|
||||||
@ 引用
|
>
|
||||||
</button>
|
@ 引用
|
||||||
|
</button>
|
||||||
|
<slot name="footer-extra"></slot>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template #suffix>
|
||||||
|
<div class="sender-suffix flex items-center gap-1">
|
||||||
|
<Tooltip v-if="loading" title="停止生成">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="sender-send-btn sender-send-btn--stop"
|
||||||
|
aria-label="停止生成"
|
||||||
|
@mousedown.prevent
|
||||||
|
@click="onStopClick"
|
||||||
|
>
|
||||||
|
<span class="sender-stop-square" />
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
<Tooltip v-else title="发送">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="sender-send-btn"
|
||||||
|
:class="{ 'sender-send-btn--disabled': !canSend }"
|
||||||
|
:disabled="!canSend"
|
||||||
|
aria-label="发送"
|
||||||
|
@mousedown.prevent
|
||||||
|
@click="onSendClick"
|
||||||
|
>
|
||||||
|
<ArrowUpIcon class="size-4" />
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</ChatSender>
|
</ChatSender>
|
||||||
</div>
|
</div>
|
||||||
@@ -334,15 +512,42 @@ onBeforeUnmount(() => {
|
|||||||
<style scoped>
|
<style scoped>
|
||||||
.agent-td-sender {
|
.agent-td-sender {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
|
padding: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.agent-td-sender :deep(.t-chat-sender__textarea) {
|
||||||
|
border: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-td-sender :deep(.t-chat-sender__textarea--focus) {
|
||||||
|
box-shadow: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
.catalog-cite-sender :deep(.t-chat-sender__textarea__wrapper) {
|
.catalog-cite-sender :deep(.t-chat-sender__textarea__wrapper) {
|
||||||
align-items: flex-start;
|
align-items: flex-start;
|
||||||
|
padding: 0;
|
||||||
|
margin-bottom: 0 !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
.catalog-cite-sender :deep(.t-textarea) {
|
.catalog-cite-sender :deep(.t-textarea) {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
width: auto;
|
width: auto;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.catalog-cite-sender :deep(.t-textarea__inner) {
|
||||||
|
padding: 0 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.catalog-cite-sender--expandable :deep(.t-textarea__inner) {
|
||||||
|
/* 给右上角展开按钮留出点击空间,避免文字压住图标 */
|
||||||
|
padding-right: 28px !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.catalog-cite-sender :deep(.t-chat-sender__footer) {
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
.cite-inline {
|
.cite-inline {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
@@ -354,4 +559,62 @@ onBeforeUnmount(() => {
|
|||||||
margin-right: 8px;
|
margin-right: 8px;
|
||||||
overflow-x: auto;
|
overflow-x: auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.sender-expand-corner {
|
||||||
|
position: absolute;
|
||||||
|
top: 8px;
|
||||||
|
right: 8px;
|
||||||
|
z-index: 5;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 28px;
|
||||||
|
height: 28px;
|
||||||
|
cursor: pointer;
|
||||||
|
border: none;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: transparent;
|
||||||
|
transition:
|
||||||
|
background-color 0.15s,
|
||||||
|
color 0.15s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sender-send-btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 32px;
|
||||||
|
height: 32px;
|
||||||
|
cursor: pointer;
|
||||||
|
border: none;
|
||||||
|
border-radius: 999px;
|
||||||
|
color: hsl(var(--primary-foreground, 0 0% 100%));
|
||||||
|
background: hsl(var(--primary));
|
||||||
|
transition:
|
||||||
|
opacity 0.15s,
|
||||||
|
transform 0.15s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sender-send-btn:hover:not(:disabled) {
|
||||||
|
opacity: 0.9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sender-send-btn--disabled,
|
||||||
|
.sender-send-btn:disabled {
|
||||||
|
cursor: not-allowed;
|
||||||
|
opacity: 0.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sender-send-btn--stop {
|
||||||
|
color: hsl(var(--foreground));
|
||||||
|
background: hsl(var(--muted));
|
||||||
|
}
|
||||||
|
|
||||||
|
.sender-stop-square {
|
||||||
|
display: block;
|
||||||
|
width: 10px;
|
||||||
|
height: 10px;
|
||||||
|
border-radius: 2px;
|
||||||
|
background: currentColor;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,16 +1,37 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
import { computed, h, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||||
|
|
||||||
import { Page } from '@vben/common-ui';
|
import { EllipsisText, Page } from '@vben/common-ui';
|
||||||
import { PlusOutlined } from '@ant-design/icons-vue';
|
import { createIconifyIcon } from '@vben/icons';
|
||||||
|
import {
|
||||||
|
BarChartOutlined,
|
||||||
|
CalendarOutlined,
|
||||||
|
FundOutlined,
|
||||||
|
PlusOutlined,
|
||||||
|
RiseOutlined,
|
||||||
|
} from '@ant-design/icons-vue';
|
||||||
|
import dayjs from 'dayjs';
|
||||||
|
|
||||||
import { Button, Empty, Select, Spin, message } from 'ant-design-vue';
|
import type { MenuProps } from 'ant-design-vue';
|
||||||
import { ChatItem } from '@tdesign-vue-next/chat';
|
|
||||||
|
import {
|
||||||
|
Dropdown,
|
||||||
|
Empty,
|
||||||
|
Menu,
|
||||||
|
Modal,
|
||||||
|
Popover,
|
||||||
|
Select,
|
||||||
|
Spin,
|
||||||
|
Tooltip,
|
||||||
|
message,
|
||||||
|
} from 'ant-design-vue';
|
||||||
|
import { ChatItem, ChatLoading } from '@tdesign-vue-next/chat';
|
||||||
import 'tdesign-vue-next/es/style/index.css';
|
import 'tdesign-vue-next/es/style/index.css';
|
||||||
import '@tdesign-vue-next/chat/es/style/index.css';
|
import '@tdesign-vue-next/chat/es/style/index.css';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
createAgentSessionApi,
|
createAgentSessionApi,
|
||||||
|
deleteAgentSessionApi,
|
||||||
listAgentEnabledLlmModelsApi,
|
listAgentEnabledLlmModelsApi,
|
||||||
listAgentMessagesApi,
|
listAgentMessagesApi,
|
||||||
listAgentSessionsApi,
|
listAgentSessionsApi,
|
||||||
@@ -20,6 +41,7 @@ import {
|
|||||||
} from '#/api/agent';
|
} from '#/api/agent';
|
||||||
|
|
||||||
import CatalogCiteSender from './catalog-cite-sender.vue';
|
import CatalogCiteSender from './catalog-cite-sender.vue';
|
||||||
|
import SessionSearchModal from './session-search-modal.vue';
|
||||||
import {
|
import {
|
||||||
composeMessageWithCites,
|
composeMessageWithCites,
|
||||||
stripTrailingMention,
|
stripTrailingMention,
|
||||||
@@ -28,14 +50,43 @@ import {
|
|||||||
|
|
||||||
defineOptions({ name: 'AgentChat' });
|
defineOptions({ name: 'AgentChat' });
|
||||||
|
|
||||||
/** 新对话空态快捷提示:点击只填入输入框,不直接发送 */
|
const AgentBrandIcon = createIconifyIcon('lucide:bot');
|
||||||
|
const SearchIcon = createIconifyIcon('lucide:search');
|
||||||
|
const PanelCloseIcon = createIconifyIcon('lucide:panel-left-close');
|
||||||
|
const PanelOpenIcon = createIconifyIcon('lucide:panel-left');
|
||||||
|
const NewChatIcon = createIconifyIcon('lucide:square-pen');
|
||||||
|
const RecentChatIcon = createIconifyIcon('lucide:message-square');
|
||||||
|
const MoreIcon = createIconifyIcon('lucide:ellipsis');
|
||||||
|
const TrashIcon = createIconifyIcon('lucide:trash-2');
|
||||||
|
|
||||||
|
const SIDER_COLLAPSED_KEY = 'agent-chat-sider-collapsed';
|
||||||
|
|
||||||
|
/** 空态快捷 chips:短标签展示,点击填入完整提问 */
|
||||||
const starterPrompts = [
|
const starterPrompts = [
|
||||||
'近7天的销售额、单量、净利和费比分别是多少',
|
{
|
||||||
'昨天的经营情况怎么样',
|
label: '近7天经营概览',
|
||||||
'本周销售额和净利帮我汇总一下',
|
prompt: '近7天的销售额、单量、净利和费比分别是多少',
|
||||||
'近30天单量和费比有什么变化',
|
icon: BarChartOutlined,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '昨天经营情况',
|
||||||
|
prompt: '昨天的经营情况怎么样',
|
||||||
|
icon: CalendarOutlined,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '本周销售与净利',
|
||||||
|
prompt: '本周销售额和净利帮我汇总一下',
|
||||||
|
icon: RiseOutlined,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '近30天费比变化',
|
||||||
|
prompt: '近30天单量和费比有什么变化',
|
||||||
|
icon: FundOutlined,
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
type SessionGroup = { key: string; label: string; items: AgentVO.Session[] };
|
||||||
|
|
||||||
/** 消息气泡视图模型(走 Vue ChatItem,避免 ChatList→WebComponent 丢正文) */
|
/** 消息气泡视图模型(走 Vue ChatItem,避免 ChatList→WebComponent 丢正文) */
|
||||||
type BubbleView = {
|
type BubbleView = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -52,6 +103,14 @@ const sessions = ref<AgentVO.Session[]>([]);
|
|||||||
const activeThreadId = ref<string | null>(null);
|
const activeThreadId = ref<string | null>(null);
|
||||||
/** 点了「新对话」但还没发出第一条消息,此时不请求后端 */
|
/** 点了「新对话」但还没发出第一条消息,此时不请求后端 */
|
||||||
const composingNew = ref(false);
|
const composingNew = ref(false);
|
||||||
|
/** 侧栏收起状态(localStorage 持久化) */
|
||||||
|
const siderCollapsed = ref(
|
||||||
|
typeof localStorage !== 'undefined' &&
|
||||||
|
localStorage.getItem(SIDER_COLLAPSED_KEY) === '1',
|
||||||
|
);
|
||||||
|
/** 收起态:最近会话浮层 */
|
||||||
|
const collapsedRecentOpen = ref(false);
|
||||||
|
const sessionSearchModalRef = ref<{ open: () => void } | null>(null);
|
||||||
const messages = ref<AgentVO.Message[]>([]);
|
const messages = ref<AgentVO.Message[]>([]);
|
||||||
/** 当前流式助手正文(与 messages 末条同步) */
|
/** 当前流式助手正文(与 messages 末条同步) */
|
||||||
const streamingText = ref('');
|
const streamingText = ref('');
|
||||||
@@ -110,7 +169,7 @@ const showMessageLoading = computed(
|
|||||||
() => loadingMessages.value && !sending.value && messages.value.length === 0,
|
() => loadingMessages.value && !sending.value && messages.value.length === 0,
|
||||||
);
|
);
|
||||||
|
|
||||||
/** 新对话草稿,或还没有任何会话时,展示能力引导 */
|
/** 新对话草稿,或还没有任何会话时,展示居中空态 */
|
||||||
const showStarter = computed(
|
const showStarter = computed(
|
||||||
() =>
|
() =>
|
||||||
messages.value.length === 0 &&
|
messages.value.length === 0 &&
|
||||||
@@ -119,6 +178,86 @@ const showStarter = computed(
|
|||||||
(!loadingSessions.value && !activeThreadId.value)),
|
(!loadingSessions.value && !activeThreadId.value)),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const greeting = computed(() => {
|
||||||
|
const h = dayjs().hour();
|
||||||
|
if (h < 12) return '早上好,今天想看点什么?';
|
||||||
|
if (h < 18) return '下午好,今天想看点什么?';
|
||||||
|
return '晚上好,今天想看点什么?';
|
||||||
|
});
|
||||||
|
|
||||||
|
function sessionTime(s: AgentVO.Session) {
|
||||||
|
const raw = s.lastMessageAt || s.updatedAt;
|
||||||
|
const d = raw ? dayjs(raw) : null;
|
||||||
|
return d?.isValid() ? d : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setSiderCollapsed(next: boolean) {
|
||||||
|
siderCollapsed.value = next;
|
||||||
|
try {
|
||||||
|
localStorage.setItem(SIDER_COLLAPSED_KEY, next ? '1' : '0');
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
if (!next) {
|
||||||
|
collapsedRecentOpen.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 居中弹窗搜索会话(展开/收起侧栏共用入口) */
|
||||||
|
function openSessionSearch() {
|
||||||
|
sessionSearchModalRef.value?.open();
|
||||||
|
}
|
||||||
|
|
||||||
|
function onCollapsedRecentOpenChange(open: boolean) {
|
||||||
|
collapsedRecentOpen.value = open;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 收起态浮层 / 搜索弹窗点选会话 */
|
||||||
|
function pickSessionFromOverlay(threadId: string) {
|
||||||
|
collapsedRecentOpen.value = false;
|
||||||
|
onSessionClick(threadId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 收起态「最近」列表(按接口顺序,最多 20 条) */
|
||||||
|
const recentSessions = computed(() => sessions.value.slice(0, 20));
|
||||||
|
|
||||||
|
/** 侧栏按「今天 / 昨天 / 近7天 / 更早」分组,对齐常见助手布局 */
|
||||||
|
const sessionGroups = computed<SessionGroup[]>(() => {
|
||||||
|
const buckets: Record<
|
||||||
|
'today' | 'yesterday' | 'week' | 'earlier',
|
||||||
|
AgentVO.Session[]
|
||||||
|
> = {
|
||||||
|
today: [],
|
||||||
|
yesterday: [],
|
||||||
|
week: [],
|
||||||
|
earlier: [],
|
||||||
|
};
|
||||||
|
const startToday = dayjs().startOf('day');
|
||||||
|
const startYesterday = startToday.subtract(1, 'day');
|
||||||
|
const startWeek = startToday.subtract(6, 'day');
|
||||||
|
for (const s of sessions.value) {
|
||||||
|
const t = sessionTime(s);
|
||||||
|
if (!t || !t.isBefore(startToday)) {
|
||||||
|
buckets.today.push(s);
|
||||||
|
} else if (!t.isBefore(startYesterday)) {
|
||||||
|
buckets.yesterday.push(s);
|
||||||
|
} else if (!t.isBefore(startWeek)) {
|
||||||
|
buckets.week.push(s);
|
||||||
|
} else {
|
||||||
|
buckets.earlier.push(s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const labels: Array<[keyof typeof buckets, string]> = [
|
||||||
|
['today', '今天'],
|
||||||
|
['yesterday', '昨天'],
|
||||||
|
['week', '近 7 天'],
|
||||||
|
['earlier', '更早'],
|
||||||
|
];
|
||||||
|
return labels
|
||||||
|
.map(([key, label]) => ({ key, label, items: buckets[key] }))
|
||||||
|
.filter((g) => g.items.length > 0);
|
||||||
|
});
|
||||||
|
|
||||||
const bubbleViews = computed<BubbleView[]>(() =>
|
const bubbleViews = computed<BubbleView[]>(() =>
|
||||||
messages.value.map((m, idx) => {
|
messages.value.map((m, idx) => {
|
||||||
const isStreamingAssistant =
|
const isStreamingAssistant =
|
||||||
@@ -210,6 +349,71 @@ function onSessionClick(threadId: string) {
|
|||||||
activeThreadId.value = threadId;
|
activeThreadId.value = threadId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const deletingThreadId = ref<string | null>(null);
|
||||||
|
/** 打开中的会话操作菜单;用于悬停三点在菜单打开时保持可见 */
|
||||||
|
const sessionMenuOpenThreadId = ref<string | null>(null);
|
||||||
|
|
||||||
|
const sessionMenuItems: MenuProps['items'] = [
|
||||||
|
{
|
||||||
|
key: 'delete',
|
||||||
|
danger: true,
|
||||||
|
label: '删除',
|
||||||
|
icon: () => h(TrashIcon, { class: 'size-3.5' }),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
function onSessionMenuOpenChange(threadId: string, open: boolean) {
|
||||||
|
sessionMenuOpenThreadId.value = open ? threadId : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function onSessionMenuClick(
|
||||||
|
threadId: string,
|
||||||
|
info: Parameters<NonNullable<MenuProps['onClick']>>[0],
|
||||||
|
) {
|
||||||
|
sessionMenuOpenThreadId.value = null;
|
||||||
|
if (info.key === 'delete') {
|
||||||
|
confirmDeleteSession(threadId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 确认后软删会话;若删的是当前会话则回到新对话空态 */
|
||||||
|
function confirmDeleteSession(threadId: string) {
|
||||||
|
Modal.confirm({
|
||||||
|
title: '删除会话',
|
||||||
|
content: '删除后无法在列表中恢复,确定删除该会话?',
|
||||||
|
okText: '删除',
|
||||||
|
okType: 'danger',
|
||||||
|
cancelText: '取消',
|
||||||
|
async onOk() {
|
||||||
|
await onDeleteSession(threadId);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onDeleteSession(threadId: string) {
|
||||||
|
if (sending.value) {
|
||||||
|
message.warning('回复生成中,请稍候再删除');
|
||||||
|
return Promise.reject(new Error('busy'));
|
||||||
|
}
|
||||||
|
if (deletingThreadId.value) {
|
||||||
|
return Promise.reject(new Error('deleting'));
|
||||||
|
}
|
||||||
|
deletingThreadId.value = threadId;
|
||||||
|
try {
|
||||||
|
await deleteAgentSessionApi(threadId);
|
||||||
|
sessions.value = sessions.value.filter((s) => s.threadId !== threadId);
|
||||||
|
if (activeThreadId.value === threadId) {
|
||||||
|
beginNewChat();
|
||||||
|
}
|
||||||
|
message.success('会话已删除');
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e?.message || '删除会话失败');
|
||||||
|
return Promise.reject(e);
|
||||||
|
} finally {
|
||||||
|
deletingThreadId.value = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function refreshSessions() {
|
async function refreshSessions() {
|
||||||
loadingSessions.value = true;
|
loadingSessions.value = true;
|
||||||
try {
|
try {
|
||||||
@@ -469,182 +673,495 @@ void loadEnabledModels().then(() => refreshSessions());
|
|||||||
|
|
||||||
<template>
|
<template>
|
||||||
<Page auto-content-height content-class="!p-0">
|
<Page auto-content-height content-class="!p-0">
|
||||||
<div class="flex h-full min-h-0 w-full overflow-hidden">
|
<div class="agent-shell flex h-full min-h-0 w-full overflow-hidden">
|
||||||
|
<!-- 左轨:顶栏标题/搜索/收起;收起后为图标轨(展开/新建/搜索/最近) -->
|
||||||
<aside
|
<aside
|
||||||
class="flex w-64 shrink-0 flex-col border-r border-border bg-card"
|
class="agent-sider flex shrink-0 flex-col border-r border-border transition-[width] duration-200"
|
||||||
|
:class="siderCollapsed ? 'w-[56px]' : 'w-[260px]'"
|
||||||
>
|
>
|
||||||
<div class="border-b border-border p-3">
|
<div
|
||||||
<Button type="primary" block @click="beginNewChat">
|
v-if="!siderCollapsed"
|
||||||
<template #icon><PlusOutlined /></template>
|
class="flex h-12 shrink-0 items-center gap-1 px-3"
|
||||||
新对话
|
>
|
||||||
</Button>
|
<div class="min-w-0 flex-1 truncate text-sm font-semibold">
|
||||||
|
智能助手
|
||||||
|
</div>
|
||||||
|
<Tooltip title="搜索会话">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="hover:bg-muted text-muted-foreground hover:text-foreground flex size-9 items-center justify-center rounded-lg transition-colors"
|
||||||
|
aria-label="搜索会话"
|
||||||
|
@click="openSessionSearch"
|
||||||
|
>
|
||||||
|
<SearchIcon class="size-5" />
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
<Tooltip title="收起侧栏">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="hover:bg-muted text-muted-foreground hover:text-foreground flex size-9 items-center justify-center rounded-lg transition-colors"
|
||||||
|
aria-label="收起侧栏"
|
||||||
|
@click="setSiderCollapsed(true)"
|
||||||
|
>
|
||||||
|
<PanelCloseIcon class="size-5" />
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
</div>
|
</div>
|
||||||
<div class="relative min-h-0 flex-1">
|
<div
|
||||||
<div
|
v-else
|
||||||
v-if="loadingSessions"
|
class="flex min-h-0 flex-1 flex-col items-center gap-1 px-1.5 pt-0 pb-3"
|
||||||
class="absolute inset-0 z-10 flex items-center justify-center bg-background/50"
|
>
|
||||||
|
<Tooltip title="展开侧栏" placement="right">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="agent-sider-brand-btn hover:bg-muted group flex size-10 items-center justify-center rounded-lg transition-colors"
|
||||||
|
aria-label="展开侧栏"
|
||||||
|
@click="setSiderCollapsed(false)"
|
||||||
|
>
|
||||||
|
<AgentBrandIcon class="size-5 group-hover:hidden" />
|
||||||
|
<PanelOpenIcon class="hidden size-5 group-hover:block" />
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
<Tooltip title="新对话" placement="right">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="hover:bg-muted text-muted-foreground hover:text-foreground flex size-10 items-center justify-center rounded-lg transition-colors"
|
||||||
|
aria-label="新对话"
|
||||||
|
@click="beginNewChat"
|
||||||
|
>
|
||||||
|
<NewChatIcon class="size-5" />
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
<Tooltip title="搜索会话" placement="right">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="hover:bg-muted text-muted-foreground hover:text-foreground flex size-10 items-center justify-center rounded-lg transition-colors"
|
||||||
|
aria-label="搜索会话"
|
||||||
|
@click="openSessionSearch"
|
||||||
|
>
|
||||||
|
<SearchIcon class="size-5" />
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
<Popover
|
||||||
|
:open="collapsedRecentOpen"
|
||||||
|
trigger="click"
|
||||||
|
placement="rightTop"
|
||||||
|
:overlay-style="{ padding: 0 }"
|
||||||
|
@update:open="onCollapsedRecentOpenChange"
|
||||||
>
|
>
|
||||||
<Spin size="small" />
|
<template #content>
|
||||||
</div>
|
<div class="agent-sider-pop flex w-64 flex-col p-2">
|
||||||
<Empty
|
<div class="text-muted-foreground px-1 pb-2 text-xs font-medium">
|
||||||
v-if="!loadingSessions && sessions.length === 0 && !composingNew"
|
最近聊天
|
||||||
class="mt-10 px-2"
|
</div>
|
||||||
description="暂无会话"
|
<div class="max-h-72 overflow-y-auto">
|
||||||
/>
|
<Empty
|
||||||
<div v-else class="h-full space-y-1 overflow-y-auto px-3 py-2">
|
v-if="recentSessions.length === 0"
|
||||||
<button
|
class="py-6"
|
||||||
v-if="composingNew"
|
description="暂无会话"
|
||||||
type="button"
|
:image="Empty.PRESENTED_IMAGE_SIMPLE"
|
||||||
class="bg-primary/10 text-primary mb-1 w-full rounded-lg px-3 py-2 text-left text-sm"
|
/>
|
||||||
>
|
<button
|
||||||
<div class="truncate font-medium">新对话</div>
|
v-for="s in recentSessions"
|
||||||
<div class="text-muted-foreground mt-0.5 truncate text-xs">
|
:key="s.threadId"
|
||||||
尚未发送
|
type="button"
|
||||||
|
class="agent-session-item mb-0.5 w-full cursor-pointer rounded-lg px-2.5 py-2 text-left text-sm transition-colors"
|
||||||
|
:class="
|
||||||
|
s.threadId === activeThreadId
|
||||||
|
? 'agent-session-item--active'
|
||||||
|
: ''
|
||||||
|
"
|
||||||
|
@click="pickSessionFromOverlay(s.threadId)"
|
||||||
|
>
|
||||||
|
<EllipsisText :tooltip-when-ellipsis="true" class="w-full">
|
||||||
|
{{ s.title || '新对话' }}
|
||||||
|
</EllipsisText>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</button>
|
</template>
|
||||||
<button
|
<Tooltip
|
||||||
v-for="s in sessions"
|
:title="collapsedRecentOpen ? '' : '最近聊天'"
|
||||||
:key="s.threadId"
|
placement="right"
|
||||||
type="button"
|
|
||||||
class="w-full rounded-lg px-3 py-2 text-left text-sm transition-colors"
|
|
||||||
:class="
|
|
||||||
s.threadId === activeThreadId
|
|
||||||
? 'bg-primary/10 text-primary'
|
|
||||||
: 'hover:bg-muted text-foreground'
|
|
||||||
"
|
|
||||||
@click="onSessionClick(s.threadId)"
|
|
||||||
>
|
>
|
||||||
<div class="truncate font-medium">{{ s.title || '新对话' }}</div>
|
<button
|
||||||
<div
|
type="button"
|
||||||
v-if="s.updatedAt || s.lastMessageAt"
|
class="hover:bg-muted text-muted-foreground hover:text-foreground flex size-10 items-center justify-center rounded-lg transition-colors"
|
||||||
class="text-muted-foreground mt-0.5 truncate text-xs"
|
:class="collapsedRecentOpen ? 'bg-muted text-foreground' : ''"
|
||||||
|
aria-label="最近聊天"
|
||||||
>
|
>
|
||||||
{{ s.updatedAt || s.lastMessageAt }}
|
<RecentChatIcon class="size-5" />
|
||||||
</div>
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
</Popover>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-if="!siderCollapsed">
|
||||||
|
<div class="px-3 pb-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="hover:bg-muted flex h-9 w-full items-center gap-2 rounded-lg px-3 text-sm font-medium transition-colors"
|
||||||
|
@click="beginNewChat"
|
||||||
|
>
|
||||||
|
<PlusOutlined />
|
||||||
|
新对话
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<div class="relative min-h-0 flex-1">
|
||||||
|
<div
|
||||||
|
v-if="loadingSessions"
|
||||||
|
class="absolute inset-0 z-10 flex items-center justify-center bg-background/50"
|
||||||
|
>
|
||||||
|
<Spin size="small" />
|
||||||
|
</div>
|
||||||
|
<Empty
|
||||||
|
v-if="!loadingSessions && sessions.length === 0 && !composingNew"
|
||||||
|
class="mt-12 px-3"
|
||||||
|
description="暂无会话"
|
||||||
|
/>
|
||||||
|
<div v-else class="h-full overflow-y-auto px-2 pb-4">
|
||||||
|
<button
|
||||||
|
v-if="composingNew"
|
||||||
|
type="button"
|
||||||
|
class="bg-muted mb-3 w-full rounded-lg px-3 py-2 text-left text-sm font-medium"
|
||||||
|
>
|
||||||
|
新对话
|
||||||
|
</button>
|
||||||
|
<div
|
||||||
|
v-for="group in sessionGroups"
|
||||||
|
:key="group.key"
|
||||||
|
class="mb-3"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class="text-muted-foreground px-3 pb-1 pt-2 text-xs font-medium"
|
||||||
|
>
|
||||||
|
{{ group.label }}
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-for="s in group.items"
|
||||||
|
:key="s.threadId"
|
||||||
|
class="agent-session-item group mb-0.5 flex w-full cursor-pointer items-center gap-1 rounded-lg px-2 py-1.5 text-left text-sm transition-colors"
|
||||||
|
:class="
|
||||||
|
s.threadId === activeThreadId
|
||||||
|
? 'agent-session-item--active'
|
||||||
|
: ''
|
||||||
|
"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="min-w-0 flex-1 truncate px-1 py-0.5 text-left"
|
||||||
|
@click="onSessionClick(s.threadId)"
|
||||||
|
>
|
||||||
|
<EllipsisText :tooltip-when-ellipsis="true" class="w-full">
|
||||||
|
{{ s.title || '新对话' }}
|
||||||
|
</EllipsisText>
|
||||||
|
</button>
|
||||||
|
<Dropdown
|
||||||
|
:trigger="['click']"
|
||||||
|
:open="sessionMenuOpenThreadId === s.threadId"
|
||||||
|
@open-change="
|
||||||
|
(open: boolean) =>
|
||||||
|
onSessionMenuOpenChange(s.threadId, open)
|
||||||
|
"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="text-muted-foreground hover:bg-accent hover:text-foreground flex size-7 shrink-0 items-center justify-center rounded-md opacity-0 transition-opacity group-hover:opacity-100"
|
||||||
|
:class="
|
||||||
|
sessionMenuOpenThreadId === s.threadId ||
|
||||||
|
s.threadId === activeThreadId
|
||||||
|
? 'opacity-100'
|
||||||
|
: ''
|
||||||
|
"
|
||||||
|
aria-label="会话操作"
|
||||||
|
@click.stop
|
||||||
|
>
|
||||||
|
<MoreIcon class="size-3.5" />
|
||||||
|
</button>
|
||||||
|
<template #overlay>
|
||||||
|
<Menu
|
||||||
|
:items="sessionMenuItems"
|
||||||
|
@click="
|
||||||
|
(info) => onSessionMenuClick(s.threadId, info)
|
||||||
|
"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
</Dropdown>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
<section class="agent-chat-main flex min-h-0 min-w-0 flex-1 flex-col">
|
<!-- 主区:空态居中 / 对话时消息 + 底栏输入 -->
|
||||||
<header
|
<section class="agent-main relative flex min-h-0 min-w-0 flex-1 flex-col">
|
||||||
class="flex h-12 shrink-0 items-center gap-3 border-b border-border px-4"
|
<div
|
||||||
|
v-if="showMessageLoading"
|
||||||
|
class="text-muted-foreground absolute inset-0 z-10 flex items-center justify-center bg-background/60 text-sm"
|
||||||
>
|
>
|
||||||
<span class="min-w-0 flex-1 truncate font-medium">
|
加载消息…
|
||||||
{{
|
</div>
|
||||||
composingNew
|
|
||||||
? '新对话'
|
|
||||||
: activeSession?.title || '智能助手'
|
|
||||||
}}
|
|
||||||
</span>
|
|
||||||
<Select
|
|
||||||
:value="selectedModelKey"
|
|
||||||
:options="modelOptions"
|
|
||||||
:loading="patchingModel"
|
|
||||||
:disabled="sending || enabledModels.length === 0"
|
|
||||||
placeholder="选择模型"
|
|
||||||
class="w-64 shrink-0"
|
|
||||||
:allow-clear="false"
|
|
||||||
@change="(v) => onModelChange(String(v ?? ''))"
|
|
||||||
/>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<div class="relative flex min-h-0 flex-1 flex-col">
|
<!-- 空态:问候 + 居中输入 + chips -->
|
||||||
<div
|
<div
|
||||||
v-if="showMessageLoading"
|
v-if="showStarter"
|
||||||
class="text-muted-foreground absolute inset-0 z-10 flex items-center justify-center bg-background/60 text-sm"
|
class="flex min-h-0 flex-1 flex-col items-center justify-center px-4 pb-16 pt-8"
|
||||||
>
|
>
|
||||||
加载消息…
|
<h1 class="mb-10 text-center text-3xl font-semibold tracking-tight">
|
||||||
</div>
|
{{ greeting }}
|
||||||
<Empty
|
</h1>
|
||||||
v-if="!showStarter && !showMessageLoading && messages.length === 0"
|
<div class="agent-composer w-full max-w-[720px]">
|
||||||
class="absolute inset-0 flex items-center justify-center"
|
|
||||||
description="开始提问吧(需先在「模型管理」配置 API)"
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
ref="messagePaneRef"
|
|
||||||
class="agent-td-chat t-chat t-chat--normal min-h-0 flex-1 overflow-y-auto py-4"
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
v-if="showStarter"
|
|
||||||
class="mx-auto flex h-full max-w-xl flex-col justify-center px-2 py-6"
|
|
||||||
>
|
|
||||||
<div class="text-base font-medium">智能助手可以帮你看经营数据</div>
|
|
||||||
<p class="text-muted-foreground mt-2 text-sm leading-6">
|
|
||||||
直接问销售额、单量、净利、费比。说「近7天」「昨天」「本周」「本月」即可,不必自己换算日期。查某家店或某个商品时,带上店铺名或商品名。
|
|
||||||
</p>
|
|
||||||
<ul
|
|
||||||
class="text-muted-foreground mt-3 list-disc space-y-1 pl-5 text-sm leading-6"
|
|
||||||
>
|
|
||||||
<li>工作台概览:销售额、单量、净利、费比</li>
|
|
||||||
<li>店铺 / 商品:销量、ROI、目标达成</li>
|
|
||||||
</ul>
|
|
||||||
<div class="mt-4 flex flex-col gap-2">
|
|
||||||
<button
|
|
||||||
v-for="item in starterPrompts"
|
|
||||||
:key="item"
|
|
||||||
type="button"
|
|
||||||
class="hover:border-primary hover:bg-primary/5 rounded-lg border border-border bg-card px-3 py-2 text-left text-sm transition-colors"
|
|
||||||
@click="applyStarterPrompt(item)"
|
|
||||||
>
|
|
||||||
{{ item }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<ChatItem
|
|
||||||
v-for="item in bubbleViews"
|
|
||||||
:key="item.id"
|
|
||||||
class="agent-td-item"
|
|
||||||
:role="item.role"
|
|
||||||
:name="item.name"
|
|
||||||
:content="item.content"
|
|
||||||
:text-loading="item.textLoading"
|
|
||||||
variant="base"
|
|
||||||
animation="gradient"
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
v-if="toolStatusActive && toolStatusLabel"
|
|
||||||
class="text-muted-foreground mx-auto flex max-w-3xl items-center gap-2 px-4 py-1 text-xs"
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
class="border-primary/40 inline-block size-3 animate-spin rounded-full border-2 border-t-transparent"
|
|
||||||
/>
|
|
||||||
<span>{{ toolStatusLabel }}…</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="shrink-0 border-t border-border p-3">
|
|
||||||
<CatalogCiteSender
|
<CatalogCiteSender
|
||||||
v-model="draft"
|
v-model="draft"
|
||||||
v-model:cites="citations"
|
v-model:cites="citations"
|
||||||
:loading="sending"
|
:loading="sending"
|
||||||
@send="onSenderSend"
|
@send="onSenderSend"
|
||||||
@stop="onSenderStop"
|
@stop="onSenderStop"
|
||||||
/>
|
>
|
||||||
|
<template #footer-extra>
|
||||||
|
<Select
|
||||||
|
:value="selectedModelKey"
|
||||||
|
:options="modelOptions"
|
||||||
|
:loading="patchingModel"
|
||||||
|
:disabled="sending || enabledModels.length === 0"
|
||||||
|
placeholder="模型"
|
||||||
|
size="small"
|
||||||
|
class="agent-model-select min-w-0 max-w-[200px] flex-1"
|
||||||
|
:allow-clear="false"
|
||||||
|
@change="(v) => onModelChange(String(v ?? ''))"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
</CatalogCiteSender>
|
||||||
|
<div class="mt-5 flex flex-wrap justify-center gap-2">
|
||||||
|
<Tooltip
|
||||||
|
v-for="item in starterPrompts"
|
||||||
|
:key="item.label"
|
||||||
|
:title="item.prompt"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="hover:bg-muted border-border text-foreground/80 hover:text-foreground inline-flex cursor-pointer items-center gap-2 rounded-full border bg-card px-3.5 py-1.5 text-sm transition-colors"
|
||||||
|
@click="applyStarterPrompt(item.prompt)"
|
||||||
|
>
|
||||||
|
<component :is="item.icon" class="text-muted-foreground" />
|
||||||
|
{{ item.label }}
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- 对话态:可滚动消息 + 底部输入 -->
|
||||||
|
<template v-else>
|
||||||
|
<div
|
||||||
|
ref="messagePaneRef"
|
||||||
|
class="agent-td-chat t-chat t-chat--normal min-h-0 flex-1 overflow-y-auto px-4 pb-4 pt-6"
|
||||||
|
>
|
||||||
|
<Empty
|
||||||
|
v-if="!showMessageLoading && messages.length === 0"
|
||||||
|
class="mt-24"
|
||||||
|
description="开始提问吧(需先在「模型管理」配置 API)"
|
||||||
|
/>
|
||||||
|
<div class="mx-auto max-w-[760px]">
|
||||||
|
<ChatItem
|
||||||
|
v-for="item in bubbleViews"
|
||||||
|
:key="item.id"
|
||||||
|
class="agent-td-item"
|
||||||
|
:class="[
|
||||||
|
item.role === 'user'
|
||||||
|
? 'agent-td-item--user'
|
||||||
|
: 'agent-td-item--assistant',
|
||||||
|
{ 'agent-td-item--loading': item.textLoading },
|
||||||
|
]"
|
||||||
|
:role="item.role"
|
||||||
|
:name="item.name"
|
||||||
|
:content="item.textLoading ? undefined : item.content"
|
||||||
|
:text-loading="false"
|
||||||
|
variant="base"
|
||||||
|
>
|
||||||
|
<!-- ChatItem.animation 无 dots,等待首包时用 ChatLoading -->
|
||||||
|
<template v-if="item.textLoading" #content>
|
||||||
|
<ChatLoading animation="dots" />
|
||||||
|
</template>
|
||||||
|
</ChatItem>
|
||||||
|
<div
|
||||||
|
v-if="toolStatusActive && toolStatusLabel"
|
||||||
|
class="agent-tool-status text-muted-foreground flex items-center gap-2 px-2 py-1 text-xs"
|
||||||
|
>
|
||||||
|
<ChatLoading animation="dots" :text="`${toolStatusLabel}…`" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="agent-composer-dock shrink-0 px-4 pb-5 pt-2">
|
||||||
|
<div class="agent-composer mx-auto max-w-[720px]">
|
||||||
|
<CatalogCiteSender
|
||||||
|
v-model="draft"
|
||||||
|
v-model:cites="citations"
|
||||||
|
:loading="sending"
|
||||||
|
@send="onSenderSend"
|
||||||
|
@stop="onSenderStop"
|
||||||
|
>
|
||||||
|
<template #footer-extra>
|
||||||
|
<Select
|
||||||
|
:value="selectedModelKey"
|
||||||
|
:options="modelOptions"
|
||||||
|
:loading="patchingModel"
|
||||||
|
:disabled="sending || enabledModels.length === 0"
|
||||||
|
placeholder="模型"
|
||||||
|
size="small"
|
||||||
|
class="agent-model-select min-w-0 max-w-[200px] flex-1"
|
||||||
|
:allow-clear="false"
|
||||||
|
@change="(v) => onModelChange(String(v ?? ''))"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
</CatalogCiteSender>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
<SessionSearchModal
|
||||||
|
ref="sessionSearchModalRef"
|
||||||
|
:sessions="sessions"
|
||||||
|
:active-thread-id="activeThreadId"
|
||||||
|
@pick="pickSessionFromOverlay"
|
||||||
|
/>
|
||||||
</Page>
|
</Page>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.agent-td-chat {
|
/* 浅色:侧栏略深于主区;深色沿用 background-deep */
|
||||||
--td-bg-color-container: transparent;
|
.agent-sider {
|
||||||
padding-inline: 28px;
|
background: hsl(var(--muted) / 0.45);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
html.dark .agent-sider,
|
||||||
|
.dark .agent-sider {
|
||||||
|
background: hsl(var(--background-deep, var(--background)));
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-session-item:hover {
|
||||||
|
background: hsl(var(--accent));
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-session-item,
|
||||||
|
.agent-session-item :deep(*) {
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-session-item--active {
|
||||||
|
background: hsl(var(--background));
|
||||||
|
font-weight: 500;
|
||||||
|
box-shadow: 0 0 0 1px hsl(var(--border));
|
||||||
|
}
|
||||||
|
|
||||||
|
html.dark .agent-session-item--active,
|
||||||
|
.dark .agent-session-item--active {
|
||||||
|
background: hsl(var(--muted));
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-composer :deep(.t-chat-sender) {
|
||||||
|
border-radius: 24px;
|
||||||
|
box-shadow: 0 0 0 1px hsl(var(--border) / 0.8);
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-composer :deep(.t-chat-sender__textarea__wrapper) {
|
||||||
|
border-radius: 24px;
|
||||||
|
padding: 0;
|
||||||
|
margin-bottom: 0 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-model-select :deep(.ant-select-selector) {
|
||||||
|
border-radius: 999px !important;
|
||||||
|
}
|
||||||
|
|
||||||
.agent-td-item {
|
.agent-td-item {
|
||||||
margin-bottom: 12px;
|
/* ChatItem 根节点即 .t-chat__inner,样式打在本类上 */
|
||||||
}
|
display: flex;
|
||||||
/* 气泡按内容收缩,左右再留一截,避免贴边铺满 */
|
|
||||||
.agent-td-item :deep(.t-chat__inner) {
|
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
padding-inline: 4px;
|
width: 100%;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
padding-inline: 20px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.agent-td-item :deep(.t-chat__content) {
|
.agent-td-item :deep(.t-chat__content) {
|
||||||
width: auto;
|
flex: 0 1 auto !important;
|
||||||
max-width: min(720px, calc(100% - 32px));
|
width: fit-content !important;
|
||||||
|
max-width: min(680px, 100%);
|
||||||
|
justify-content: flex-start !important;
|
||||||
}
|
}
|
||||||
.agent-td-item :deep(.t-chat__inner.user) {
|
|
||||||
|
.agent-td-item--assistant {
|
||||||
|
justify-content: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-td-item--assistant :deep(.t-chat__content) {
|
||||||
|
align-self: flex-start;
|
||||||
|
align-items: flex-start !important;
|
||||||
|
margin-right: auto;
|
||||||
|
margin-left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-td-item--user {
|
||||||
justify-content: flex-end;
|
justify-content: flex-end;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.agent-td-item--user :deep(.t-chat__content) {
|
||||||
|
align-self: flex-end;
|
||||||
|
align-items: flex-end !important;
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-td-item :deep(.t-chat__detail) {
|
||||||
|
width: fit-content;
|
||||||
|
max-width: 100%;
|
||||||
|
margin-inline: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-td-item :deep(.t-chat__text__name) {
|
||||||
|
opacity: 0.55;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-tool-status {
|
||||||
|
justify-content: flex-start;
|
||||||
|
padding-inline: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 浅色:给气泡补边框与底色,避免与主背景糊在一起 */
|
||||||
|
.agent-td-item :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
.agent-td-item :deep(.t-chat__detail) {
|
||||||
|
border: 1px solid hsl(var(--border));
|
||||||
|
border-radius: 12px;
|
||||||
|
background: hsl(var(--muted) / 0.65);
|
||||||
|
padding-block: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-td-item--user :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
.agent-td-item--user :deep(.t-chat__detail),
|
||||||
|
.agent-td-item.user :deep(.t-chat__detail) {
|
||||||
|
background: hsl(var(--primary) / 0.1);
|
||||||
|
border-color: hsl(var(--primary) / 0.22);
|
||||||
|
}
|
||||||
|
|
||||||
|
html.dark .agent-td-item :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
html.dark .agent-td-item :deep(.t-chat__detail),
|
||||||
|
.dark .agent-td-item :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
.dark .agent-td-item :deep(.t-chat__detail) {
|
||||||
|
border-color: transparent;
|
||||||
|
background: hsl(var(--muted) / 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
|
html.dark .agent-td-item--user :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
html.dark .agent-td-item--user :deep(.t-chat__detail),
|
||||||
|
html.dark .agent-td-item.user :deep(.t-chat__detail),
|
||||||
|
.dark .agent-td-item--user :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
.dark .agent-td-item--user :deep(.t-chat__detail),
|
||||||
|
.dark .agent-td-item.user :deep(.t-chat__detail) {
|
||||||
|
background: hsl(var(--primary) / 0.22);
|
||||||
|
border-color: transparent;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
/**
|
||||||
|
* 会话搜索弹窗:居中打开,按标题过滤;点选后回传 threadId。
|
||||||
|
*/
|
||||||
|
import { computed, nextTick, ref } from 'vue';
|
||||||
|
|
||||||
|
import { EllipsisText, useVbenModal } from '@vben/common-ui';
|
||||||
|
|
||||||
|
import { Empty, Input } from 'ant-design-vue';
|
||||||
|
|
||||||
|
import type { AgentVO } from '#/api/agent';
|
||||||
|
|
||||||
|
defineOptions({ name: 'AgentSessionSearchModal' });
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
sessions: AgentVO.Session[];
|
||||||
|
activeThreadId?: string | null;
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const emit = defineEmits<{
|
||||||
|
pick: [threadId: string];
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const query = ref('');
|
||||||
|
const inputRef = ref<{ focus?: () => void } | null>(null);
|
||||||
|
|
||||||
|
const hits = computed(() => {
|
||||||
|
const q = query.value.trim().toLowerCase();
|
||||||
|
const list = props.sessions || [];
|
||||||
|
if (!q) return list.slice(0, 30);
|
||||||
|
return list
|
||||||
|
.filter((s) => (s.title || '新对话').toLowerCase().includes(q))
|
||||||
|
.slice(0, 30);
|
||||||
|
});
|
||||||
|
|
||||||
|
const [Modal, modalApi] = useVbenModal({
|
||||||
|
title: '搜索会话',
|
||||||
|
class: 'w-[520px]',
|
||||||
|
draggable: true,
|
||||||
|
footer: false,
|
||||||
|
showConfirmButton: false,
|
||||||
|
showCancelButton: false,
|
||||||
|
onOpenChange(isOpen: boolean) {
|
||||||
|
if (!isOpen) {
|
||||||
|
query.value = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
query.value = '';
|
||||||
|
void nextTick(() => inputRef.value?.focus?.());
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
function open() {
|
||||||
|
modalApi.open();
|
||||||
|
}
|
||||||
|
|
||||||
|
function pick(threadId: string) {
|
||||||
|
emit('pick', threadId);
|
||||||
|
modalApi.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
defineExpose({ open });
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Modal>
|
||||||
|
<div class="flex flex-col gap-3">
|
||||||
|
<Input
|
||||||
|
ref="inputRef"
|
||||||
|
v-model:value="query"
|
||||||
|
allow-clear
|
||||||
|
placeholder="按会话标题搜索"
|
||||||
|
size="large"
|
||||||
|
/>
|
||||||
|
<div class="max-h-[360px] min-h-[120px] overflow-y-auto">
|
||||||
|
<Empty
|
||||||
|
v-if="hits.length === 0"
|
||||||
|
class="py-10"
|
||||||
|
:description="query.trim() ? '无匹配会话' : '暂无会话'"
|
||||||
|
:image="Empty.PRESENTED_IMAGE_SIMPLE"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
v-for="s in hits"
|
||||||
|
:key="s.threadId"
|
||||||
|
type="button"
|
||||||
|
class="mb-0.5 w-full rounded-lg px-3 py-2.5 text-left text-sm transition-colors"
|
||||||
|
:class="
|
||||||
|
s.threadId === activeThreadId
|
||||||
|
? 'bg-muted font-medium'
|
||||||
|
: 'hover:bg-muted/70'
|
||||||
|
"
|
||||||
|
@click="pick(s.threadId)"
|
||||||
|
>
|
||||||
|
<EllipsisText :tooltip-when-ellipsis="true" class="w-full">
|
||||||
|
{{ s.title || '新对话' }}
|
||||||
|
</EllipsisText>
|
||||||
|
<div
|
||||||
|
v-if="s.updatedAt || s.lastMessageAt"
|
||||||
|
class="text-muted-foreground mt-0.5 text-xs"
|
||||||
|
>
|
||||||
|
{{ s.updatedAt || s.lastMessageAt }}
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
</template>
|
||||||
+22
-1
@@ -10,6 +10,7 @@ import {
|
|||||||
FormItem,
|
FormItem,
|
||||||
Input,
|
Input,
|
||||||
InputPassword,
|
InputPassword,
|
||||||
|
Select,
|
||||||
message,
|
message,
|
||||||
} from 'ant-design-vue';
|
} from 'ant-design-vue';
|
||||||
|
|
||||||
@@ -28,8 +29,18 @@ const form = ref({
|
|||||||
baseUrl: '',
|
baseUrl: '',
|
||||||
apiKey: '',
|
apiKey: '',
|
||||||
displayName: '',
|
displayName: '',
|
||||||
|
apiStyle: 'auto',
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const apiStyleOptions = [
|
||||||
|
{
|
||||||
|
value: 'auto',
|
||||||
|
label: '自动(优先 Responses+store,失败再降级)',
|
||||||
|
},
|
||||||
|
{ value: 'completions', label: 'Chat Completions' },
|
||||||
|
{ value: 'responses', label: 'Responses API' },
|
||||||
|
];
|
||||||
|
|
||||||
const isEdit = computed(() => !!editing.value);
|
const isEdit = computed(() => !!editing.value);
|
||||||
const modalTitle = computed(() =>
|
const modalTitle = computed(() =>
|
||||||
isEdit.value ? '编辑提供商' : '添加提供商',
|
isEdit.value ? '编辑提供商' : '添加提供商',
|
||||||
@@ -52,7 +63,8 @@ function open(row?: AgentVO.LlmProvider) {
|
|||||||
baseUrl: row?.baseUrl || '',
|
baseUrl: row?.baseUrl || '',
|
||||||
apiKey: '',
|
apiKey: '',
|
||||||
displayName: row?.displayName || '',
|
displayName: row?.displayName || '',
|
||||||
};
|
apiStyle: row?.apiStyle || 'auto',
|
||||||
|
};
|
||||||
modalApi.setState({ title: modalTitle.value });
|
modalApi.setState({ title: modalTitle.value });
|
||||||
modalApi.open();
|
modalApi.open();
|
||||||
}
|
}
|
||||||
@@ -74,6 +86,7 @@ async function handleSubmit() {
|
|||||||
baseUrl: form.value.baseUrl.trim(),
|
baseUrl: form.value.baseUrl.trim(),
|
||||||
apiKey: form.value.apiKey.trim() || undefined,
|
apiKey: form.value.apiKey.trim() || undefined,
|
||||||
displayName: form.value.displayName.trim(),
|
displayName: form.value.displayName.trim(),
|
||||||
|
apiStyle: form.value.apiStyle,
|
||||||
});
|
});
|
||||||
message.success('已保存');
|
message.success('已保存');
|
||||||
} else {
|
} else {
|
||||||
@@ -81,6 +94,7 @@ async function handleSubmit() {
|
|||||||
baseUrl: form.value.baseUrl.trim(),
|
baseUrl: form.value.baseUrl.trim(),
|
||||||
apiKey: form.value.apiKey.trim(),
|
apiKey: form.value.apiKey.trim(),
|
||||||
displayName: form.value.displayName.trim() || undefined,
|
displayName: form.value.displayName.trim() || undefined,
|
||||||
|
apiStyle: form.value.apiStyle,
|
||||||
});
|
});
|
||||||
message.success('已创建');
|
message.success('已创建');
|
||||||
}
|
}
|
||||||
@@ -116,6 +130,13 @@ defineExpose({ open });
|
|||||||
>
|
>
|
||||||
<InputPassword v-model:value="form.apiKey" placeholder="sk-..." />
|
<InputPassword v-model:value="form.apiKey" placeholder="sk-..." />
|
||||||
</FormItem>
|
</FormItem>
|
||||||
|
<FormItem label="API 协议">
|
||||||
|
<Select
|
||||||
|
v-model:value="form.apiStyle"
|
||||||
|
:options="apiStyleOptions"
|
||||||
|
class="w-full"
|
||||||
|
/>
|
||||||
|
</FormItem>
|
||||||
<FormItem label="备注(可选)">
|
<FormItem label="备注(可选)">
|
||||||
<Input v-model:value="form.displayName" placeholder="如 DeepSeek" />
|
<Input v-model:value="form.displayName" placeholder="如 DeepSeek" />
|
||||||
</FormItem>
|
</FormItem>
|
||||||
|
|||||||
@@ -65,6 +65,19 @@ const baseColumns: VxeGridProps<ProviderRow>['columns'] = [
|
|||||||
minWidth: 220,
|
minWidth: 220,
|
||||||
showOverflow: 'tooltip',
|
showOverflow: 'tooltip',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
field: 'apiStyle',
|
||||||
|
title: 'API 协议',
|
||||||
|
minWidth: 120,
|
||||||
|
formatter: ({ row }) => {
|
||||||
|
const m: Record<string, string> = {
|
||||||
|
auto: '自动',
|
||||||
|
completions: 'Completions',
|
||||||
|
responses: 'Responses',
|
||||||
|
};
|
||||||
|
return m[row.apiStyle || 'auto'] || row.apiStyle || '自动';
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
field: 'apiKeyMasked',
|
field: 'apiKeyMasked',
|
||||||
title: 'API Key',
|
title: 'API Key',
|
||||||
|
|||||||
@@ -1,10 +1,16 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import { onMounted, ref } from 'vue';
|
/**
|
||||||
|
* 助手长期记忆:Page + VXE 表格(与反馈/API Key 等列表页一致)。
|
||||||
|
*/
|
||||||
|
import type { VxeGridProps } from '#/adapter/vxe-table';
|
||||||
|
|
||||||
import { Page } from '@vben/common-ui';
|
import { ref } from 'vue';
|
||||||
|
|
||||||
import { Button, Card, Empty, Spin, message } from 'ant-design-vue';
|
import { EllipsisText, Page } from '@vben/common-ui';
|
||||||
|
|
||||||
|
import { Alert, Button, Modal, Popconfirm, Space, Tag, message } from 'ant-design-vue';
|
||||||
|
|
||||||
|
import { useVbenVxeGrid } from '#/adapter/vxe-table';
|
||||||
import {
|
import {
|
||||||
deleteAgentMemoryApi,
|
deleteAgentMemoryApi,
|
||||||
listAgentMemoriesApi,
|
listAgentMemoriesApi,
|
||||||
@@ -13,79 +19,193 @@ import {
|
|||||||
|
|
||||||
defineOptions({ name: 'AgentMemories' });
|
defineOptions({ name: 'AgentMemories' });
|
||||||
|
|
||||||
const loading = ref(true);
|
const loading = ref(false);
|
||||||
const memories = ref<AgentVO.Memory[]>([]);
|
|
||||||
|
|
||||||
async function loadMemories() {
|
const KIND_META: Record<string, { color: string; label: string }> = {
|
||||||
loading.value = true;
|
note: { color: 'blue', label: '笔记' },
|
||||||
try {
|
preference: { color: 'purple', label: '偏好' },
|
||||||
const res = await listAgentMemoriesApi();
|
fact: { color: 'green', label: '事实' },
|
||||||
memories.value = res.items || [];
|
};
|
||||||
} catch (e: any) {
|
|
||||||
message.error(e?.message || '加载记忆失败');
|
function kindMeta(kind?: string) {
|
||||||
} finally {
|
const k = (kind || 'note').trim() || 'note';
|
||||||
loading.value = false;
|
return KIND_META[k] || { color: 'default', label: k };
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function removeMemory(id: string) {
|
function formatTime(raw?: string) {
|
||||||
|
if (!raw) return '—';
|
||||||
|
// 后端多为 ISO;展示时去掉过长毫秒/Z
|
||||||
|
return raw.replace('T', ' ').replace(/\.\d+Z?$/, '').replace(/Z$/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
const gridOptions: VxeGridProps<AgentVO.Memory> = {
|
||||||
|
columns: [
|
||||||
|
{ type: 'seq', width: 56, title: '序号' },
|
||||||
|
{
|
||||||
|
field: 'kind',
|
||||||
|
title: '类型',
|
||||||
|
width: 96,
|
||||||
|
slots: { default: 'kind' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
field: 'summary',
|
||||||
|
title: '摘要',
|
||||||
|
minWidth: 200,
|
||||||
|
slots: { default: 'summary' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
field: 'text',
|
||||||
|
title: '原文',
|
||||||
|
minWidth: 240,
|
||||||
|
slots: { default: 'text' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
field: 'key',
|
||||||
|
title: '键',
|
||||||
|
width: 120,
|
||||||
|
showOverflow: 'tooltip',
|
||||||
|
formatter: ({ cellValue }) => cellValue || '—',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
field: 'updatedAt',
|
||||||
|
title: '更新时间',
|
||||||
|
width: 176,
|
||||||
|
formatter: ({ cellValue }) => formatTime(cellValue),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
width: 96,
|
||||||
|
fixed: 'right',
|
||||||
|
slots: { default: 'action' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
height: 'auto',
|
||||||
|
border: true,
|
||||||
|
stripe: true,
|
||||||
|
rowConfig: { isHover: true },
|
||||||
|
showOverflow: true,
|
||||||
|
size: 'small',
|
||||||
|
toolbarConfig: {
|
||||||
|
custom: true,
|
||||||
|
refresh: true,
|
||||||
|
zoom: true,
|
||||||
|
},
|
||||||
|
pagerConfig: {
|
||||||
|
enabled: true,
|
||||||
|
pageSizes: [10, 20, 50],
|
||||||
|
layouts: ['Total', 'Sizes', 'PrevPage', 'Number', 'NextPage'],
|
||||||
|
},
|
||||||
|
proxyConfig: {
|
||||||
|
ajax: {
|
||||||
|
query: async ({ page }) => {
|
||||||
|
loading.value = true;
|
||||||
|
try {
|
||||||
|
const res = await listAgentMemoriesApi();
|
||||||
|
const all = res.items || [];
|
||||||
|
const pageSize = page.pageSize || 20;
|
||||||
|
const current = page.currentPage || 1;
|
||||||
|
const start = (current - 1) * pageSize;
|
||||||
|
return {
|
||||||
|
items: all.slice(start, start + pageSize),
|
||||||
|
total: all.length,
|
||||||
|
};
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e?.message || '加载记忆失败');
|
||||||
|
return { items: [], total: 0 };
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });
|
||||||
|
|
||||||
|
async function removeMemory(row: AgentVO.Memory) {
|
||||||
try {
|
try {
|
||||||
await deleteAgentMemoryApi(id);
|
await deleteAgentMemoryApi(row.id);
|
||||||
memories.value = memories.value.filter((m) => m.id !== id);
|
message.success('已删除');
|
||||||
message.success('已删除记忆');
|
await gridApi.reload();
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
message.error(e?.message || '删除失败');
|
message.error(e?.message || '删除失败');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(() => {
|
function clearAll() {
|
||||||
void loadMemories();
|
Modal.confirm({
|
||||||
});
|
title: '清空全部助手记忆?',
|
||||||
|
content: '将逐条删除当前列表中的记忆,且不可恢复。',
|
||||||
|
okText: '清空',
|
||||||
|
okType: 'danger',
|
||||||
|
cancelText: '取消',
|
||||||
|
async onOk() {
|
||||||
|
const res = await listAgentMemoriesApi();
|
||||||
|
const items = res.items || [];
|
||||||
|
for (const m of items) {
|
||||||
|
await deleteAgentMemoryApi(m.id);
|
||||||
|
}
|
||||||
|
message.success(items.length ? `已清空 ${items.length} 条` : '暂无记忆');
|
||||||
|
await gridApi.reload();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<Page auto-content-height>
|
<Page
|
||||||
<div class="relative mx-auto max-w-3xl pb-8">
|
auto-content-height
|
||||||
<div
|
title="助手记忆"
|
||||||
v-if="loading"
|
description="智能助手跨会话保存的称呼、偏好与事实,按需检索,不会默认整包注入对话。"
|
||||||
class="absolute inset-0 z-10 flex items-center justify-center bg-background/50"
|
>
|
||||||
>
|
<Alert
|
||||||
<Spin />
|
type="info"
|
||||||
</div>
|
show-icon
|
||||||
|
class="mb-4"
|
||||||
|
message="在智能助手里发送「记住:……」即可写入;不需要的条目可随时删除。"
|
||||||
|
/>
|
||||||
|
|
||||||
<Card title="我的记忆" :bordered="false">
|
<Grid :loading="loading">
|
||||||
<p class="text-muted-foreground mb-4 text-sm">
|
<template #toolbar-tools>
|
||||||
在智能助手对话中发送「记住:…」可写入;助手按需检索,不会默认注入全部记忆。
|
<Space>
|
||||||
</p>
|
<Button danger @click="clearAll">清空全部</Button>
|
||||||
<Empty
|
</Space>
|
||||||
v-if="!loading && memories.length === 0"
|
</template>
|
||||||
description="暂无记忆"
|
|
||||||
/>
|
<template #kind="{ row }">
|
||||||
<div
|
<Tag :color="kindMeta(row.kind).color">
|
||||||
v-for="m in memories"
|
{{ kindMeta(row.kind).label }}
|
||||||
:key="m.id"
|
</Tag>
|
||||||
class="mb-2 flex items-start gap-2 rounded-md bg-muted/50 px-3 py-2 text-sm"
|
</template>
|
||||||
|
|
||||||
|
<template #summary="{ row }">
|
||||||
|
<EllipsisText :max-width="360" tooltip-when-ellipsis>
|
||||||
|
{{ row.summary || row.text || '—' }}
|
||||||
|
</EllipsisText>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template #text="{ row }">
|
||||||
|
<EllipsisText
|
||||||
|
v-if="row.summary && row.text && row.summary !== row.text"
|
||||||
|
:max-width="420"
|
||||||
|
tooltip-when-ellipsis
|
||||||
>
|
>
|
||||||
<div class="min-w-0 flex-1">
|
{{ row.text }}
|
||||||
<div class="break-words">{{ m.summary || m.text }}</div>
|
</EllipsisText>
|
||||||
<div
|
<span v-else class="text-muted-foreground">—</span>
|
||||||
v-if="m.summary && m.text && m.summary !== m.text"
|
</template>
|
||||||
class="text-muted-foreground mt-1 break-words text-xs"
|
|
||||||
>
|
<template #action="{ row }">
|
||||||
{{ m.text }}
|
<Popconfirm
|
||||||
</div>
|
title="确定删除这条记忆?"
|
||||||
<div
|
ok-text="删除"
|
||||||
v-if="m.updatedAt"
|
cancel-text="取消"
|
||||||
class="text-muted-foreground mt-1 text-xs"
|
ok-type="danger"
|
||||||
>
|
@confirm="removeMemory(row)"
|
||||||
{{ m.updatedAt }}
|
>
|
||||||
</div>
|
<Button type="link" size="small" danger>删除</Button>
|
||||||
</div>
|
</Popconfirm>
|
||||||
<Button type="link" size="small" danger @click="removeMemory(m.id)">
|
</template>
|
||||||
删除
|
</Grid>
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
</Page>
|
</Page>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
+321
-146
@@ -1,16 +1,13 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
/**
|
/**
|
||||||
* 拼多多发布页右侧智能体栏:一草稿一会话,执行 client_tool 改表单。
|
* 拼多多发布页右侧智能体栏:一草稿一会话,执行 client_tool 改表单。
|
||||||
|
* UI 对齐通用智能助手(气泡、加载、底栏输入与模型选择)。
|
||||||
*/
|
*/
|
||||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||||
|
|
||||||
import {
|
import { createIconifyIcon } from '@vben/icons';
|
||||||
MenuFoldOutlined,
|
import { Empty, Select, Spin, Tooltip, message } from 'ant-design-vue';
|
||||||
MenuUnfoldOutlined,
|
import { ChatItem, ChatLoading } from '@tdesign-vue-next/chat';
|
||||||
SendOutlined,
|
|
||||||
} from '@ant-design/icons-vue';
|
|
||||||
import { Button, Empty, Input, Select, Spin, Tooltip, message } from 'ant-design-vue';
|
|
||||||
import { ChatItem } from '@tdesign-vue-next/chat';
|
|
||||||
import 'tdesign-vue-next/es/style/index.css';
|
import 'tdesign-vue-next/es/style/index.css';
|
||||||
import '@tdesign-vue-next/chat/es/style/index.css';
|
import '@tdesign-vue-next/chat/es/style/index.css';
|
||||||
|
|
||||||
@@ -22,13 +19,24 @@ import {
|
|||||||
streamAgentChat,
|
streamAgentChat,
|
||||||
type AgentVO,
|
type AgentVO,
|
||||||
} from '#/api/agent';
|
} from '#/api/agent';
|
||||||
|
import CatalogCiteSender from '#/views/agent/chat/catalog-cite-sender.vue';
|
||||||
|
import {
|
||||||
|
composeMessageWithCites,
|
||||||
|
stripTrailingMention,
|
||||||
|
type CatalogCite,
|
||||||
|
} from '#/views/agent/chat/catalog-cite';
|
||||||
|
|
||||||
import type { PublishEditorAgentApi } from './commands';
|
import type { PublishEditorAgentApi } from './commands';
|
||||||
|
|
||||||
defineOptions({ name: 'PddPublishAgentPanel' });
|
defineOptions({ name: 'PddPublishAgentPanel' });
|
||||||
|
|
||||||
|
const AgentBrandIcon = createIconifyIcon('lucide:bot');
|
||||||
|
const PanelCloseIcon = createIconifyIcon('lucide:panel-left-close');
|
||||||
|
const PanelOpenIcon = createIconifyIcon('lucide:panel-left');
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
draftId: number;
|
/** 系统草稿 ID;null 表示尚未落库的新建编辑 */
|
||||||
|
draftId: number | null;
|
||||||
collapsed?: boolean;
|
collapsed?: boolean;
|
||||||
/** 编辑器命令面(ref) */
|
/** 编辑器命令面(ref) */
|
||||||
editorApi: PublishEditorAgentApi | null;
|
editorApi: PublishEditorAgentApi | null;
|
||||||
@@ -41,10 +49,38 @@ const emit = defineEmits<{
|
|||||||
|
|
||||||
const SCENE = 'ecom_goods_publish' as const;
|
const SCENE = 'ecom_goods_publish' as const;
|
||||||
|
|
||||||
|
/** 未落库时用本地 sceneRef,落库后切到草稿 ID */
|
||||||
|
const localSceneKey = `local-${
|
||||||
|
typeof crypto !== 'undefined' && crypto.randomUUID
|
||||||
|
? crypto.randomUUID()
|
||||||
|
: `${Date.now()}-${Math.random().toString(36).slice(2)}`
|
||||||
|
}`;
|
||||||
|
|
||||||
|
const sceneRef = computed(() =>
|
||||||
|
props.draftId != null && props.draftId > 0
|
||||||
|
? String(props.draftId)
|
||||||
|
: localSceneKey,
|
||||||
|
);
|
||||||
|
|
||||||
|
const sessionTitle = computed(() =>
|
||||||
|
props.draftId != null && props.draftId > 0
|
||||||
|
? `发布草稿 #${props.draftId}`
|
||||||
|
: '发布草稿(未保存)',
|
||||||
|
);
|
||||||
|
|
||||||
const starterPrompts = [
|
const starterPrompts = [
|
||||||
'根据已填的 SKU 商家编码,找相似拼多多商品并生成标题',
|
{
|
||||||
'参考渠道商品帮我整理规格轴',
|
label: '按编码生成标题',
|
||||||
'把当前标题改得更适合拼多多搜索',
|
prompt: '根据已填的 SKU 商家编码,找相似拼多多商品并生成标题',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '整理规格轴',
|
||||||
|
prompt: '参考渠道商品帮我整理规格轴',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '优化标题',
|
||||||
|
prompt: '把当前标题改得更适合拼多多搜索',
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
type BubbleView = {
|
type BubbleView = {
|
||||||
@@ -64,6 +100,7 @@ const streamingText = ref('');
|
|||||||
const toolStatusLabel = ref('');
|
const toolStatusLabel = ref('');
|
||||||
const toolStatusActive = ref(false);
|
const toolStatusActive = ref(false);
|
||||||
const draft = ref('');
|
const draft = ref('');
|
||||||
|
const citations = ref<CatalogCite[]>([]);
|
||||||
const enabledModels = ref<AgentVO.LlmModelItem[]>([]);
|
const enabledModels = ref<AgentVO.LlmModelItem[]>([]);
|
||||||
const selectedModelKey = ref<string | undefined>(undefined);
|
const selectedModelKey = ref<string | undefined>(undefined);
|
||||||
const patchingModel = ref(false);
|
const patchingModel = ref(false);
|
||||||
@@ -111,6 +148,12 @@ const showStarter = computed(
|
|||||||
!loadingSession.value,
|
!loadingSession.value,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const showMessageLoading = computed(
|
||||||
|
() =>
|
||||||
|
(loadingSession.value || loadingMessages.value) &&
|
||||||
|
messages.value.length === 0,
|
||||||
|
);
|
||||||
|
|
||||||
const bubbleViews = computed<BubbleView[]>(() =>
|
const bubbleViews = computed<BubbleView[]>(() =>
|
||||||
messages.value.map((m, idx) => {
|
messages.value.map((m, idx) => {
|
||||||
const isStreamingAssistant =
|
const isStreamingAssistant =
|
||||||
@@ -148,6 +191,11 @@ function syncSelectedFromSession() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function clearToolStatus() {
|
||||||
|
toolStatusActive.value = false;
|
||||||
|
toolStatusLabel.value = '';
|
||||||
|
}
|
||||||
|
|
||||||
/** 滚到消息区底部;多拍几次等 ChatItem 异步撑高后再定住 */
|
/** 滚到消息区底部;多拍几次等 ChatItem 异步撑高后再定住 */
|
||||||
function scrollChatToBottom() {
|
function scrollChatToBottom() {
|
||||||
const run = () => {
|
const run = () => {
|
||||||
@@ -194,11 +242,11 @@ async function ensureSession(): Promise<string | null> {
|
|||||||
if (session.value?.threadId) return session.value.threadId;
|
if (session.value?.threadId) return session.value.threadId;
|
||||||
const parsed = parseModelKey(selectedModelKey.value);
|
const parsed = parseModelKey(selectedModelKey.value);
|
||||||
const s = await createAgentSessionApi({
|
const s = await createAgentSessionApi({
|
||||||
title: `发布草稿 #${props.draftId}`,
|
title: sessionTitle.value,
|
||||||
llmProviderId: parsed?.providerId,
|
llmProviderId: parsed?.providerId,
|
||||||
llmModel: parsed?.model,
|
llmModel: parsed?.model,
|
||||||
scene: SCENE,
|
scene: SCENE,
|
||||||
sceneRef: String(props.draftId),
|
sceneRef: sceneRef.value,
|
||||||
reuseBySceneRef: true,
|
reuseBySceneRef: true,
|
||||||
});
|
});
|
||||||
session.value = s;
|
session.value = s;
|
||||||
@@ -232,6 +280,8 @@ async function bootstrap() {
|
|||||||
loadingSession.value = true;
|
loadingSession.value = true;
|
||||||
messages.value = [];
|
messages.value = [];
|
||||||
session.value = null;
|
session.value = null;
|
||||||
|
draft.value = '';
|
||||||
|
citations.value = [];
|
||||||
try {
|
try {
|
||||||
await loadEnabledModels();
|
await loadEnabledModels();
|
||||||
const threadId = await ensureSession();
|
const threadId = await ensureSession();
|
||||||
@@ -245,7 +295,11 @@ async function bootstrap() {
|
|||||||
|
|
||||||
watch(
|
watch(
|
||||||
() => props.draftId,
|
() => props.draftId,
|
||||||
() => {
|
(id, prev) => {
|
||||||
|
// 新建落库后仅 URL 从 new→id:沿用当前会话,避免打断
|
||||||
|
if (prev == null && id != null && id > 0 && session.value?.threadId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
abort?.abort();
|
abort?.abort();
|
||||||
void bootstrap();
|
void bootstrap();
|
||||||
},
|
},
|
||||||
@@ -275,8 +329,7 @@ async function onModelChange(key: string) {
|
|||||||
|
|
||||||
function appendStreamToken(t: string) {
|
function appendStreamToken(t: string) {
|
||||||
if (toolStatusActive.value) {
|
if (toolStatusActive.value) {
|
||||||
toolStatusActive.value = false;
|
clearToolStatus();
|
||||||
toolStatusLabel.value = '';
|
|
||||||
}
|
}
|
||||||
streamingText.value += t;
|
streamingText.value += t;
|
||||||
const idx = messages.value.length - 1;
|
const idx = messages.value.length - 1;
|
||||||
@@ -293,9 +346,7 @@ function onStreamTool(payload: { phase: string; label: string }) {
|
|||||||
toolStatusLabel.value = payload.label;
|
toolStatusLabel.value = payload.label;
|
||||||
void nextTick().then(scrollChatToBottom);
|
void nextTick().then(scrollChatToBottom);
|
||||||
} else if (payload.phase === 'end') {
|
} else if (payload.phase === 'end') {
|
||||||
// 结束后清状态,避免卡在「读取发布表单…」直到下一段 token
|
clearToolStatus();
|
||||||
toolStatusActive.value = false;
|
|
||||||
toolStatusLabel.value = '';
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -312,8 +363,12 @@ async function onClientTool(call: AgentVO.ClientToolCall) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function send(textOverride?: string) {
|
async function send(rawOverride?: string) {
|
||||||
const text = (textOverride ?? draft.value).trim();
|
const raw = (rawOverride ?? draft.value).trim();
|
||||||
|
const text = composeMessageWithCites(
|
||||||
|
stripTrailingMention(raw),
|
||||||
|
citations.value,
|
||||||
|
);
|
||||||
if (!text || sending.value) return;
|
if (!text || sending.value) return;
|
||||||
|
|
||||||
sending.value = true;
|
sending.value = true;
|
||||||
@@ -333,9 +388,9 @@ async function send(textOverride?: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
streamingText.value = '';
|
streamingText.value = '';
|
||||||
toolStatusActive.value = false;
|
clearToolStatus();
|
||||||
toolStatusLabel.value = '';
|
|
||||||
draft.value = '';
|
draft.value = '';
|
||||||
|
citations.value = [];
|
||||||
messages.value.push({
|
messages.value.push({
|
||||||
seq: (messages.value.at(-1)?.seq || 0) + 1,
|
seq: (messages.value.at(-1)?.seq || 0) + 1,
|
||||||
role: 'user',
|
role: 'user',
|
||||||
@@ -376,8 +431,7 @@ async function send(textOverride?: string) {
|
|||||||
}
|
}
|
||||||
sending.value = false;
|
sending.value = false;
|
||||||
streamingText.value = '';
|
streamingText.value = '';
|
||||||
toolStatusActive.value = false;
|
clearToolStatus();
|
||||||
toolStatusLabel.value = '';
|
|
||||||
},
|
},
|
||||||
onError: (msg) => {
|
onError: (msg) => {
|
||||||
sending.value = false;
|
sending.value = false;
|
||||||
@@ -387,40 +441,48 @@ async function send(textOverride?: string) {
|
|||||||
messages.value[idx] = { ...last, content: `错误:${msg}` };
|
messages.value[idx] = { ...last, content: `错误:${msg}` };
|
||||||
}
|
}
|
||||||
streamingText.value = '';
|
streamingText.value = '';
|
||||||
toolStatusActive.value = false;
|
clearToolStatus();
|
||||||
toolStatusLabel.value = '';
|
|
||||||
message.error(msg);
|
message.error(msg);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function onSenderSend(value: string) {
|
||||||
|
void send(value);
|
||||||
|
}
|
||||||
|
|
||||||
function applyStarterPrompt(text: string) {
|
function applyStarterPrompt(text: string) {
|
||||||
draft.value = text;
|
draft.value = text;
|
||||||
}
|
}
|
||||||
|
|
||||||
function onStop() {
|
function onSenderStop() {
|
||||||
abort?.abort();
|
abort?.abort();
|
||||||
sending.value = false;
|
sending.value = false;
|
||||||
toolStatusActive.value = false;
|
clearToolStatus();
|
||||||
toolStatusLabel.value = '';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onBeforeUnmount(() => abort?.abort());
|
onBeforeUnmount(() => abort?.abort());
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<!-- 收起:窄条 -->
|
<!-- 收起:窄条(悬停 bot→展开图标,对齐智能助手) -->
|
||||||
<div
|
<div
|
||||||
v-if="collapsed"
|
v-if="collapsed"
|
||||||
class="border-border bg-card flex h-full w-14 shrink-0 flex-col items-center border-l py-3"
|
class="publish-agent-rail border-border flex h-full w-14 shrink-0 flex-col items-center border-l px-1.5 py-2"
|
||||||
>
|
>
|
||||||
<Tooltip title="展开发布助手" placement="left">
|
<Tooltip title="展开发布助手" placement="left">
|
||||||
<Button type="text" @click="emit('expand')">
|
<button
|
||||||
<template #icon><MenuUnfoldOutlined /></template>
|
type="button"
|
||||||
</Button>
|
class="hover:bg-muted group flex size-10 items-center justify-center rounded-lg transition-colors"
|
||||||
|
aria-label="展开发布助手"
|
||||||
|
@click="emit('expand')"
|
||||||
|
>
|
||||||
|
<AgentBrandIcon class="size-5 group-hover:hidden" />
|
||||||
|
<PanelOpenIcon class="hidden size-5 group-hover:block" />
|
||||||
|
</button>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
<div
|
<div
|
||||||
class="text-muted-foreground mt-4 write-vertical-right text-xs tracking-widest"
|
class="text-muted-foreground mt-3 text-xs tracking-widest"
|
||||||
style="writing-mode: vertical-rl"
|
style="writing-mode: vertical-rl"
|
||||||
>
|
>
|
||||||
发布助手
|
发布助手
|
||||||
@@ -430,150 +492,263 @@ onBeforeUnmount(() => abort?.abort());
|
|||||||
<!-- 展开 -->
|
<!-- 展开 -->
|
||||||
<aside
|
<aside
|
||||||
v-else
|
v-else
|
||||||
class="border-border bg-card flex h-full min-h-0 w-full min-w-[280px] flex-col border-l"
|
class="publish-agent-panel border-border flex h-full min-h-0 w-full min-w-[280px] flex-col border-l"
|
||||||
>
|
>
|
||||||
<header
|
<header class="flex h-12 shrink-0 items-center gap-1 px-3">
|
||||||
class="flex h-12 shrink-0 items-center gap-2 border-b border-border px-3"
|
<div class="min-w-0 flex-1 truncate text-sm font-semibold">发布助手</div>
|
||||||
>
|
|
||||||
<span class="min-w-0 flex-1 truncate text-sm font-medium">发布助手</span>
|
|
||||||
<Select
|
|
||||||
:value="selectedModelKey"
|
|
||||||
:options="modelOptions"
|
|
||||||
:loading="patchingModel"
|
|
||||||
:disabled="sending || enabledModels.length === 0"
|
|
||||||
placeholder="模型"
|
|
||||||
class="w-36 shrink-0"
|
|
||||||
size="small"
|
|
||||||
:allow-clear="false"
|
|
||||||
@change="(v) => onModelChange(String(v ?? ''))"
|
|
||||||
/>
|
|
||||||
<Tooltip title="收起">
|
<Tooltip title="收起">
|
||||||
<Button type="text" size="small" @click="emit('collapse')">
|
<button
|
||||||
<template #icon><MenuFoldOutlined /></template>
|
type="button"
|
||||||
</Button>
|
class="hover:bg-muted text-muted-foreground hover:text-foreground flex size-9 items-center justify-center rounded-lg transition-colors"
|
||||||
|
aria-label="收起发布助手"
|
||||||
|
@click="emit('collapse')"
|
||||||
|
>
|
||||||
|
<PanelCloseIcon class="size-5" />
|
||||||
|
</button>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<div class="relative flex min-h-0 flex-1 flex-col">
|
<section class="relative flex min-h-0 flex-1 flex-col">
|
||||||
<div
|
<div
|
||||||
v-if="loadingSession || loadingMessages"
|
v-if="showMessageLoading"
|
||||||
class="absolute inset-0 z-10 flex items-center justify-center bg-background/50"
|
class="text-muted-foreground absolute inset-0 z-10 flex items-center justify-center bg-background/60 text-sm"
|
||||||
>
|
>
|
||||||
<Spin size="small" />
|
<Spin size="small" class="mr-2" />
|
||||||
|
加载中…
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- 空态:说明 + 居中输入 + chips -->
|
||||||
<div
|
<div
|
||||||
ref="messagePaneRef"
|
v-if="showStarter"
|
||||||
class="publish-agent-chat t-chat t-chat--normal min-h-0 flex-1 overflow-y-auto py-3"
|
class="flex min-h-0 flex-1 flex-col justify-center px-3 pb-6 pt-4"
|
||||||
>
|
>
|
||||||
<div
|
<div class="mb-5 px-1">
|
||||||
v-if="showStarter"
|
<div class="text-base font-semibold tracking-tight">
|
||||||
class="flex h-full flex-col justify-center px-1 py-4"
|
帮你完善本页草稿
|
||||||
>
|
</div>
|
||||||
<div class="text-sm font-medium">帮你完善本页草稿</div>
|
<p class="text-muted-foreground mt-1.5 text-xs leading-5">
|
||||||
<p class="text-muted-foreground mt-2 text-xs leading-5">
|
可按已填 SKU 编码查商品、生成标题并写回规格轴;改表单会落到左侧编辑区。
|
||||||
可按已填 SKU 编码查内部/拼多多商品,生成标题并写回规格轴。改表单会直接落到左侧编辑区。
|
|
||||||
</p>
|
</p>
|
||||||
<div class="mt-3 flex flex-col gap-1.5">
|
|
||||||
<button
|
|
||||||
v-for="item in starterPrompts"
|
|
||||||
:key="item"
|
|
||||||
type="button"
|
|
||||||
class="hover:border-primary hover:bg-primary/5 rounded-md border border-border bg-background px-2.5 py-1.5 text-left text-xs transition-colors"
|
|
||||||
@click="applyStarterPrompt(item)"
|
|
||||||
>
|
|
||||||
{{ item }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
<Empty
|
<div class="publish-agent-composer w-full">
|
||||||
v-else-if="!loadingSession && !loadingMessages && messages.length === 0"
|
<CatalogCiteSender
|
||||||
class="mt-16"
|
v-model="draft"
|
||||||
description="开始提问吧"
|
v-model:cites="citations"
|
||||||
/>
|
:loading="sending"
|
||||||
<ChatItem
|
placeholder="描述想改的标题、规格,或用 @ 引用"
|
||||||
v-for="item in bubbleViews"
|
@send="onSenderSend"
|
||||||
:key="item.id"
|
@stop="onSenderStop"
|
||||||
class="publish-agent-item"
|
>
|
||||||
:role="item.role"
|
<template #footer-extra>
|
||||||
:name="item.name"
|
<Select
|
||||||
:content="item.content"
|
:value="selectedModelKey"
|
||||||
:text-loading="item.textLoading"
|
:options="modelOptions"
|
||||||
variant="base"
|
:loading="patchingModel"
|
||||||
animation="gradient"
|
:disabled="sending || enabledModels.length === 0"
|
||||||
/>
|
placeholder="模型"
|
||||||
<div
|
size="small"
|
||||||
v-if="toolStatusActive && toolStatusLabel"
|
class="publish-agent-model-select min-w-0 max-w-[160px] flex-1"
|
||||||
class="text-muted-foreground flex items-center gap-2 px-1 py-1 text-xs"
|
:allow-clear="false"
|
||||||
>
|
@change="(v) => onModelChange(String(v ?? ''))"
|
||||||
<span
|
/>
|
||||||
class="border-primary/40 inline-block size-3 animate-spin rounded-full border-2 border-t-transparent"
|
</template>
|
||||||
/>
|
</CatalogCiteSender>
|
||||||
<span>{{ toolStatusLabel }}…</span>
|
<div class="mt-4 flex flex-wrap gap-2">
|
||||||
|
<Tooltip
|
||||||
|
v-for="item in starterPrompts"
|
||||||
|
:key="item.label"
|
||||||
|
:title="item.prompt"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="hover:bg-muted border-border text-foreground/80 hover:text-foreground inline-flex cursor-pointer items-center rounded-full border bg-card px-3 py-1.5 text-xs transition-colors"
|
||||||
|
@click="applyStarterPrompt(item.prompt)"
|
||||||
|
>
|
||||||
|
{{ item.label }}
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="shrink-0 border-t border-border p-2">
|
<!-- 对话态 -->
|
||||||
<div class="flex gap-1.5">
|
<template v-else>
|
||||||
<Input.TextArea
|
<div
|
||||||
v-model:value="draft"
|
ref="messagePaneRef"
|
||||||
:auto-size="{ minRows: 2, maxRows: 5 }"
|
class="publish-agent-chat t-chat t-chat--normal min-h-0 flex-1 overflow-y-auto px-3 pb-3 pt-4"
|
||||||
:disabled="sending"
|
>
|
||||||
placeholder="描述你想改的标题、规格…"
|
<Empty
|
||||||
class="flex-1"
|
v-if="!showMessageLoading && messages.length === 0"
|
||||||
@keydown.enter.exact.prevent="() => send()"
|
class="mt-16"
|
||||||
|
description="开始提问吧"
|
||||||
/>
|
/>
|
||||||
<div class="flex flex-col gap-1">
|
<ChatItem
|
||||||
<Button
|
v-for="item in bubbleViews"
|
||||||
v-if="sending"
|
:key="item.id"
|
||||||
type="default"
|
class="publish-agent-item"
|
||||||
size="small"
|
:class="[
|
||||||
@click="onStop"
|
item.role === 'user'
|
||||||
>
|
? 'publish-agent-item--user'
|
||||||
停止
|
: 'publish-agent-item--assistant',
|
||||||
</Button>
|
{ 'publish-agent-item--loading': item.textLoading },
|
||||||
<Button
|
]"
|
||||||
v-else
|
:role="item.role"
|
||||||
type="primary"
|
:name="item.name"
|
||||||
size="small"
|
:content="item.textLoading ? undefined : item.content"
|
||||||
:disabled="!draft.trim()"
|
:text-loading="false"
|
||||||
@click="() => send()"
|
variant="base"
|
||||||
>
|
>
|
||||||
<template #icon><SendOutlined /></template>
|
<template v-if="item.textLoading" #content>
|
||||||
</Button>
|
<ChatLoading animation="dots" />
|
||||||
|
</template>
|
||||||
|
</ChatItem>
|
||||||
|
<div
|
||||||
|
v-if="toolStatusActive && toolStatusLabel"
|
||||||
|
class="text-muted-foreground flex items-center gap-2 px-1 py-1 text-xs"
|
||||||
|
>
|
||||||
|
<ChatLoading animation="dots" :text="`${toolStatusLabel}…`" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
</div>
|
<div class="publish-agent-composer shrink-0 px-3 pb-3 pt-1">
|
||||||
|
<CatalogCiteSender
|
||||||
|
v-model="draft"
|
||||||
|
v-model:cites="citations"
|
||||||
|
:loading="sending"
|
||||||
|
placeholder="描述想改的标题、规格,或用 @ 引用"
|
||||||
|
@send="onSenderSend"
|
||||||
|
@stop="onSenderStop"
|
||||||
|
>
|
||||||
|
<template #footer-extra>
|
||||||
|
<Select
|
||||||
|
:value="selectedModelKey"
|
||||||
|
:options="modelOptions"
|
||||||
|
:loading="patchingModel"
|
||||||
|
:disabled="sending || enabledModels.length === 0"
|
||||||
|
placeholder="模型"
|
||||||
|
size="small"
|
||||||
|
class="publish-agent-model-select min-w-0 max-w-[160px] flex-1"
|
||||||
|
:allow-clear="false"
|
||||||
|
@change="(v) => onModelChange(String(v ?? ''))"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
</CatalogCiteSender>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</section>
|
||||||
</aside>
|
</aside>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
.publish-agent-rail,
|
||||||
|
.publish-agent-panel {
|
||||||
|
background: hsl(var(--muted) / 0.45);
|
||||||
|
}
|
||||||
|
|
||||||
|
html.dark .publish-agent-rail,
|
||||||
|
html.dark .publish-agent-panel,
|
||||||
|
.dark .publish-agent-rail,
|
||||||
|
.dark .publish-agent-panel {
|
||||||
|
background: hsl(var(--background-deep, var(--background)));
|
||||||
|
}
|
||||||
|
|
||||||
|
.publish-agent-composer :deep(.t-chat-sender) {
|
||||||
|
border-radius: 20px;
|
||||||
|
box-shadow: 0 0 0 1px hsl(var(--border) / 0.8);
|
||||||
|
}
|
||||||
|
|
||||||
|
.publish-agent-composer :deep(.t-chat-sender__textarea__wrapper) {
|
||||||
|
border-radius: 20px;
|
||||||
|
padding: 0;
|
||||||
|
margin-bottom: 0 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.publish-agent-model-select :deep(.ant-select-selector) {
|
||||||
|
border-radius: 999px !important;
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* TDesign `.t-chat { padding: 0 }` 会盖掉 Tailwind px-*,容器左右留白写这里。
|
* ChatItem 根节点就是 .t-chat__inner,padding / justify 必须打在本类上。
|
||||||
* 不要动 `.t-chat__detail` 的 padding,那是气泡内文字边距。
|
|
||||||
*/
|
*/
|
||||||
.publish-agent-chat.t-chat {
|
|
||||||
--td-bg-color-container: transparent;
|
|
||||||
padding: 12px 16px !important;
|
|
||||||
box-sizing: border-box;
|
|
||||||
}
|
|
||||||
.publish-agent-item {
|
.publish-agent-item {
|
||||||
margin-bottom: 10px;
|
display: flex;
|
||||||
}
|
|
||||||
.publish-agent-item :deep(.t-chat__inner) {
|
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
padding-inline: 4px;
|
width: 100%;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
padding-inline: 12px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.publish-agent-item :deep(.t-chat__content) {
|
.publish-agent-item :deep(.t-chat__content) {
|
||||||
width: auto;
|
flex: 0 1 auto !important;
|
||||||
max-width: calc(100% - 8px);
|
width: fit-content !important;
|
||||||
|
max-width: calc(100% - 4px);
|
||||||
|
justify-content: flex-start !important;
|
||||||
}
|
}
|
||||||
.publish-agent-item :deep(.t-chat__inner.user) {
|
|
||||||
|
.publish-agent-item--assistant {
|
||||||
|
justify-content: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.publish-agent-item--assistant :deep(.t-chat__content) {
|
||||||
|
align-self: flex-start;
|
||||||
|
align-items: flex-start !important;
|
||||||
|
margin-right: auto;
|
||||||
|
margin-left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.publish-agent-item--user {
|
||||||
justify-content: flex-end;
|
justify-content: flex-end;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.publish-agent-item--user :deep(.t-chat__content) {
|
||||||
|
align-self: flex-end;
|
||||||
|
align-items: flex-end !important;
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.publish-agent-item :deep(.t-chat__detail) {
|
||||||
|
width: fit-content;
|
||||||
|
max-width: 100%;
|
||||||
|
margin-inline: 0;
|
||||||
|
}
|
||||||
|
|
||||||
.publish-agent-item :deep(.t-chat__avatar),
|
.publish-agent-item :deep(.t-chat__avatar),
|
||||||
.publish-agent-item :deep(.t-chat__name) {
|
.publish-agent-item :deep(.t-chat__name) {
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 浅色:气泡边框与底色,避免与侧栏糊在一起 */
|
||||||
|
.publish-agent-item :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
.publish-agent-item :deep(.t-chat__detail) {
|
||||||
|
border: 1px solid hsl(var(--border));
|
||||||
|
border-radius: 12px;
|
||||||
|
background: hsl(var(--background));
|
||||||
|
padding-block: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.publish-agent-item--user :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
.publish-agent-item--user :deep(.t-chat__detail),
|
||||||
|
.publish-agent-item.user :deep(.t-chat__detail) {
|
||||||
|
background: hsl(var(--primary) / 0.1);
|
||||||
|
border-color: hsl(var(--primary) / 0.22);
|
||||||
|
}
|
||||||
|
|
||||||
|
html.dark .publish-agent-item :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
html.dark .publish-agent-item :deep(.t-chat__detail),
|
||||||
|
.dark .publish-agent-item :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
.dark .publish-agent-item :deep(.t-chat__detail) {
|
||||||
|
border-color: transparent;
|
||||||
|
background: hsl(var(--muted) / 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
|
html.dark .publish-agent-item--user :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
html.dark .publish-agent-item--user :deep(.t-chat__detail),
|
||||||
|
html.dark .publish-agent-item.user :deep(.t-chat__detail),
|
||||||
|
.dark .publish-agent-item--user :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
.dark .publish-agent-item--user :deep(.t-chat__detail),
|
||||||
|
.dark .publish-agent-item.user :deep(.t-chat__detail) {
|
||||||
|
background: hsl(var(--primary) / 0.22);
|
||||||
|
border-color: transparent;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
+26
-5
@@ -255,6 +255,24 @@ onMounted(() => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/** 路由 draftId 变化(含 new→真实 ID):已绑定同一草稿则跳过 hydrate */
|
||||||
|
watch(
|
||||||
|
() => props.draftId,
|
||||||
|
(id, prev) => {
|
||||||
|
if (
|
||||||
|
(prev == null || prev === undefined) &&
|
||||||
|
id != null &&
|
||||||
|
id > 0 &&
|
||||||
|
draft.boundDraftId.value === id
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (id != null && id > 0 && id !== draft.boundDraftId.value) {
|
||||||
|
void draft.hydrateFromDraft(id);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
function resetAll() {
|
function resetAll() {
|
||||||
draft.submitting.value = false;
|
draft.submitting.value = false;
|
||||||
Object.assign(form, createEmptyPublishForm());
|
Object.assign(form, createEmptyPublishForm());
|
||||||
@@ -390,7 +408,7 @@ function onSkuTableWrapRef(el: HTMLElement | null) {
|
|||||||
<Teleport defer to="#pdd-publish-edit-header-fields">
|
<Teleport defer to="#pdd-publish-edit-header-fields">
|
||||||
<div class="w-full min-w-0 space-y-2">
|
<div class="w-full min-w-0 space-y-2">
|
||||||
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
|
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
|
||||||
<div class="min-w-0">
|
<div class="min-w-0 w-full">
|
||||||
<div class="mb-1 text-sm font-medium">
|
<div class="mb-1 text-sm font-medium">
|
||||||
渠道店铺 <span class="text-destructive">*</span>
|
渠道店铺 <span class="text-destructive">*</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -405,7 +423,7 @@ function onSkuTableWrapRef(el: HTMLElement | null) {
|
|||||||
@search="(kw: string) => loadShops(kw)"
|
@search="(kw: string) => loadShops(kw)"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div class="min-w-0">
|
<div class="min-w-0 w-full">
|
||||||
<div class="mb-1 flex items-center gap-1.5 text-sm font-medium">
|
<div class="mb-1 flex items-center gap-1.5 text-sm font-medium">
|
||||||
<span>
|
<span>
|
||||||
叶子类目 <span class="text-destructive">*</span>
|
叶子类目 <span class="text-destructive">*</span>
|
||||||
@@ -436,10 +454,12 @@ function onSkuTableWrapRef(el: HTMLElement | null) {
|
|||||||
/>
|
/>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</div>
|
</div>
|
||||||
|
<!-- Cascader 默认不吃满格子,需显式 100% 与店铺 Select 对齐 -->
|
||||||
<Cascader
|
<Cascader
|
||||||
v-model:value="form.catPath"
|
v-model:value="form.catPath"
|
||||||
v-model:search-value="catCascaderSearch"
|
v-model:search-value="catCascaderSearch"
|
||||||
class="w-full"
|
class="w-full"
|
||||||
|
:style="{ width: '100%' }"
|
||||||
:options="displayCatOptions"
|
:options="displayCatOptions"
|
||||||
:load-data="catLoadData"
|
:load-data="catLoadData"
|
||||||
:show-search="{
|
:show-search="{
|
||||||
@@ -640,9 +660,10 @@ function onSkuTableWrapRef(el: HTMLElement | null) {
|
|||||||
v-model:value="form.twoPiecesDiscount"
|
v-model:value="form.twoPiecesDiscount"
|
||||||
class="w-full"
|
class="w-full"
|
||||||
:min="0"
|
:min="0"
|
||||||
:max="100"
|
:max="10"
|
||||||
:precision="0"
|
:precision="1"
|
||||||
placeholder="95 表示 95 折,0 取消"
|
:step="0.1"
|
||||||
|
placeholder="9.5 表示 9.5 折,0 取消"
|
||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+25
-23
@@ -18,12 +18,14 @@ import {
|
|||||||
updatePddPublishDeskDraftApi,
|
updatePddPublishDeskDraftApi,
|
||||||
} from '#/api/channel/pdd/goods';
|
} from '#/api/channel/pdd/goods';
|
||||||
|
|
||||||
import type {
|
import {
|
||||||
PersistedUpload,
|
twoPiecesDiscountFromStored,
|
||||||
PublishFormFields,
|
twoPiecesDiscountToApi,
|
||||||
SpecAxis,
|
type PersistedUpload,
|
||||||
SpecCatalogItem,
|
type PublishFormFields,
|
||||||
SkuRow,
|
type SpecAxis,
|
||||||
|
type SpecCatalogItem,
|
||||||
|
type SkuRow,
|
||||||
} from '../types';
|
} from '../types';
|
||||||
|
|
||||||
type EmitDraft = {
|
type EmitDraft = {
|
||||||
@@ -185,9 +187,9 @@ export function usePublishDraft(options: {
|
|||||||
if (
|
if (
|
||||||
form.twoPiecesDiscount == null ||
|
form.twoPiecesDiscount == null ||
|
||||||
form.twoPiecesDiscount < 0 ||
|
form.twoPiecesDiscount < 0 ||
|
||||||
form.twoPiecesDiscount > 100
|
form.twoPiecesDiscount > 10
|
||||||
) {
|
) {
|
||||||
message.warning('请填写满两件折扣(0-100,95表示95折)');
|
message.warning('请填写正常折扣(0-10,9.5 表示 9.5 折)');
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
for (const p of nonSaleProps.value) {
|
for (const p of nonSaleProps.value) {
|
||||||
@@ -362,7 +364,7 @@ export function usePublishDraft(options: {
|
|||||||
isPreSale: form.isPreSale,
|
isPreSale: form.isPreSale,
|
||||||
isRefundable: form.isRefundable,
|
isRefundable: form.isRefundable,
|
||||||
secondHand: form.secondHand,
|
secondHand: form.secondHand,
|
||||||
twoPiecesDiscount: form.twoPiecesDiscount,
|
twoPiecesDiscount: twoPiecesDiscountToApi(form.twoPiecesDiscount),
|
||||||
carouselImages: carouselFileIds.map(String),
|
carouselImages: carouselFileIds.map(String),
|
||||||
detailImages: detailFileIds.map(String),
|
detailImages: detailFileIds.map(String),
|
||||||
goodsProperties,
|
goodsProperties,
|
||||||
@@ -459,7 +461,7 @@ export function usePublishDraft(options: {
|
|||||||
}
|
}
|
||||||
if (typeof es.secondHand === 'boolean') form.secondHand = es.secondHand;
|
if (typeof es.secondHand === 'boolean') form.secondHand = es.secondHand;
|
||||||
if (typeof es.twoPiecesDiscount === 'number') {
|
if (typeof es.twoPiecesDiscount === 'number') {
|
||||||
form.twoPiecesDiscount = es.twoPiecesDiscount;
|
form.twoPiecesDiscount = twoPiecesDiscountFromStored(es.twoPiecesDiscount);
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
es.goodsPropValues &&
|
es.goodsPropValues &&
|
||||||
@@ -777,8 +779,12 @@ export function usePublishDraft(options: {
|
|||||||
async function handleSubmit() {
|
async function handleSubmit() {
|
||||||
if (!validateForm()) return;
|
if (!validateForm()) return;
|
||||||
submitting.value = true;
|
submitting.value = true;
|
||||||
const hide = message.loading('正在上传图片并发布…', 0);
|
const hide = message.loading('正在保存并发布…', 0);
|
||||||
try {
|
try {
|
||||||
|
// 先落/更新系统草稿(含 publishPayload),再发布以便回写 goods_commit_id / goods_id
|
||||||
|
const saved = await saveDeskDraft(true, { silentSuccess: true });
|
||||||
|
if (!saved?.id) return;
|
||||||
|
|
||||||
const pendingThumbs = skuRows.value
|
const pendingThumbs = skuRows.value
|
||||||
.map((row) => ({ rowKey: row.key, file: row.thumbFileList[0] }))
|
.map((row) => ({ rowKey: row.key, file: row.thumbFileList[0] }))
|
||||||
.filter((x): x is { rowKey: number; file: UploadFile } => !!x.file);
|
.filter((x): x is { rowKey: number; file: UploadFile } => !!x.file);
|
||||||
@@ -797,8 +803,8 @@ export function usePublishDraft(options: {
|
|||||||
const thumbPersisted = persistedAll.slice(p);
|
const thumbPersisted = persistedAll.slice(p);
|
||||||
const thumbFileIdBySkuKey = new Map<number, number>();
|
const thumbFileIdBySkuKey = new Map<number, number>();
|
||||||
pendingThumbs.forEach((item, i) => {
|
pendingThumbs.forEach((item, i) => {
|
||||||
const saved = thumbPersisted[i];
|
const savedThumb = thumbPersisted[i];
|
||||||
if (saved) thumbFileIdBySkuKey.set(item.rowKey, saved.fileId);
|
if (savedThumb) thumbFileIdBySkuKey.set(item.rowKey, savedThumb.fileId);
|
||||||
});
|
});
|
||||||
|
|
||||||
const payload = await buildPublishPayload(
|
const payload = await buildPublishPayload(
|
||||||
@@ -806,17 +812,13 @@ export function usePublishDraft(options: {
|
|||||||
detailFileIds,
|
detailFileIds,
|
||||||
thumbFileIdBySkuKey,
|
thumbFileIdBySkuKey,
|
||||||
);
|
);
|
||||||
// 确保有系统草稿并回传 ID,发布结果才能写入 goods_commit_id
|
payload.systemDraftId = saved.id;
|
||||||
if (boundDraftId.value) {
|
|
||||||
payload.systemDraftId = boundDraftId.value;
|
|
||||||
} else if (form.pddShopId) {
|
|
||||||
const saved = await saveDeskDraft(true, { silentSuccess: true });
|
|
||||||
if (saved?.id) {
|
|
||||||
payload.systemDraftId = saved.id;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const res = await publishPddGoodsApi(payload);
|
const res = await publishPddGoodsApi(payload);
|
||||||
message.success(`发布成功,goodsId=${res.goodsId}`);
|
message.success(
|
||||||
|
res.goodsId != null
|
||||||
|
? `发布成功,goodsId=${res.goodsId}`
|
||||||
|
: '发布成功',
|
||||||
|
);
|
||||||
emit('success');
|
emit('success');
|
||||||
closeEditor();
|
closeEditor();
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
/**
|
/**
|
||||||
* 发布编辑页路由入口(editor/index):Page 布局 + 左侧表单 + 右侧 Agent。
|
* 发布编辑页路由入口(editor/index):Page 布局 + 左侧表单 + 右侧 Agent。
|
||||||
* 表单实现见同目录 PddPublishEditor;智能体见 ../agent。
|
* 表单实现见同目录 PddPublishEditor;智能体见 ../agent。
|
||||||
|
* draftId=new 表示尚未落库的空编辑;保存/推送/发布时再创建系统草稿。
|
||||||
*/
|
*/
|
||||||
import { computed, ref } from 'vue';
|
import { computed, ref } from 'vue';
|
||||||
import { useRoute, useRouter } from 'vue-router';
|
import { useRoute, useRouter } from 'vue-router';
|
||||||
@@ -19,10 +20,20 @@ defineOptions({ name: 'PddGoodsPublishDeskEdit' });
|
|||||||
const route = useRoute();
|
const route = useRoute();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
|
/** 数字 ID;new / 非法 → null(尚未创建系统草稿) */
|
||||||
const draftId = computed(() => {
|
const draftId = computed(() => {
|
||||||
const raw = route.params.draftId;
|
const raw = route.params.draftId;
|
||||||
const n = Number(Array.isArray(raw) ? raw[0] : raw);
|
const s = String(Array.isArray(raw) ? raw[0] : raw ?? '');
|
||||||
return Number.isFinite(n) ? n : null;
|
if (!s || s === 'new') return null;
|
||||||
|
const n = Number(s);
|
||||||
|
return Number.isFinite(n) && n > 0 ? n : null;
|
||||||
|
});
|
||||||
|
|
||||||
|
const presetPddShopId = computed(() => {
|
||||||
|
const raw = route.query.shopId;
|
||||||
|
const s = String(Array.isArray(raw) ? raw[0] : raw ?? '');
|
||||||
|
const n = Number(s);
|
||||||
|
return Number.isFinite(n) && n > 0 ? n : null;
|
||||||
});
|
});
|
||||||
|
|
||||||
const editorRef = ref<PublishEditorAgentApi | null>(null);
|
const editorRef = ref<PublishEditorAgentApi | null>(null);
|
||||||
@@ -47,6 +58,15 @@ const agentPaneStyle = computed(() => {
|
|||||||
function goBack() {
|
function goBack() {
|
||||||
void router.push('/pdd/goods/publish');
|
void router.push('/pdd/goods/publish');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 首次落库后把 URL 换成真实草稿 ID,便于刷新续编与 Agent 绑定 */
|
||||||
|
function onDraftSaved(id: number) {
|
||||||
|
if (!id || draftId.value === id) return;
|
||||||
|
void router.replace({
|
||||||
|
path: `/pdd/goods/publish/editor/${id}`,
|
||||||
|
query: {},
|
||||||
|
});
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -60,33 +80,22 @@ function goBack() {
|
|||||||
>
|
>
|
||||||
<template #title>
|
<template #title>
|
||||||
<div class="w-full space-y-3">
|
<div class="w-full space-y-3">
|
||||||
<div class="mb-0 flex items-baseline text-lg font-semibold">
|
|
||||||
编辑系统草稿
|
|
||||||
<span
|
|
||||||
v-if="draftId"
|
|
||||||
class="text-muted-foreground ml-2 text-sm font-normal"
|
|
||||||
>
|
|
||||||
#{{ draftId }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<!-- Editor Teleport:店铺 / 类目 -->
|
<!-- Editor Teleport:店铺 / 类目 -->
|
||||||
<div id="pdd-publish-edit-header-fields" class="w-full min-w-0"></div>
|
<div id="pdd-publish-edit-header-fields" class="w-full min-w-0"></div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<div
|
<div class="flex min-h-0 flex-1 overflow-hidden">
|
||||||
v-if="draftId"
|
|
||||||
class="flex min-h-0 flex-1 overflow-hidden"
|
|
||||||
>
|
|
||||||
<div class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
|
<div class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
|
||||||
<PddPublishEditor
|
<PddPublishEditor
|
||||||
ref="editorRef"
|
ref="editorRef"
|
||||||
class="h-full min-h-0"
|
class="h-full min-h-0"
|
||||||
:open="true"
|
:open="true"
|
||||||
:draft-id="draftId"
|
:draft-id="draftId"
|
||||||
|
:preset-pdd-shop-id="presetPddShopId"
|
||||||
@close="goBack"
|
@close="goBack"
|
||||||
@success="goBack"
|
@success="goBack"
|
||||||
@draft-saved="() => undefined"
|
@draft-saved="onDraftSaved"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
|
|||||||
@@ -101,10 +101,23 @@ export type PublishFormFields = {
|
|||||||
isPreSale: boolean;
|
isPreSale: boolean;
|
||||||
isRefundable: boolean;
|
isRefundable: boolean;
|
||||||
secondHand: boolean;
|
secondHand: boolean;
|
||||||
|
/** 表单展示用折扣:0–10,9.5=9.5折;提交接口时 *10 */
|
||||||
twoPiecesDiscount: number;
|
twoPiecesDiscount: number;
|
||||||
goodsPropValues: Record<string, string>;
|
goodsPropValues: Record<string, string>;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 表单折扣 → 拼多多接口整数(9.5 → 95) */
|
||||||
|
export function twoPiecesDiscountToApi(ui: number | null | undefined): number {
|
||||||
|
if (ui == null || Number.isNaN(ui)) return 95;
|
||||||
|
return Math.round(ui * 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 接口/旧草稿整数 → 表单折扣(95 → 9.5;已是 0–10 则原样) */
|
||||||
|
export function twoPiecesDiscountFromStored(raw: number): number {
|
||||||
|
if (raw > 10) return Math.round((raw / 10) * 10) / 10;
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
|
||||||
/** 创建空白发布表单字段 */
|
/** 创建空白发布表单字段 */
|
||||||
export function createEmptyPublishForm(): PublishFormFields {
|
export function createEmptyPublishForm(): PublishFormFields {
|
||||||
return {
|
return {
|
||||||
@@ -117,11 +130,11 @@ export function createEmptyPublishForm(): PublishFormFields {
|
|||||||
costTemplateId: undefined,
|
costTemplateId: undefined,
|
||||||
marketPriceYuan: undefined,
|
marketPriceYuan: undefined,
|
||||||
shipmentLimitSecond: 172800,
|
shipmentLimitSecond: 172800,
|
||||||
isFolt: true,
|
isFolt: false,
|
||||||
isPreSale: false,
|
isPreSale: false,
|
||||||
isRefundable: true,
|
isRefundable: true,
|
||||||
secondHand: false,
|
secondHand: false,
|
||||||
twoPiecesDiscount: 95,
|
twoPiecesDiscount: 9.5,
|
||||||
goodsPropValues: {},
|
goodsPropValues: {},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ import {
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
clonePddPublishDeskDraftApi,
|
clonePddPublishDeskDraftApi,
|
||||||
createPddPublishDeskDraftApi,
|
|
||||||
createPddPublishDeskJobApi,
|
createPddPublishDeskJobApi,
|
||||||
deletePddPublishDeskDraftApi,
|
deletePddPublishDeskDraftApi,
|
||||||
getPddPublishDeskJobApi,
|
getPddPublishDeskJobApi,
|
||||||
@@ -315,18 +314,15 @@ function selectUnassigned() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function createDraft() {
|
async function createDraft() {
|
||||||
try {
|
const query =
|
||||||
const draft = await createPddPublishDeskDraftApi({
|
selectedShopId.value != null && selectedShopId.value > 0
|
||||||
title: '未命名草稿',
|
? { shopId: String(selectedShopId.value) }
|
||||||
pddShopId: selectedShopId.value,
|
: undefined;
|
||||||
status: 'EDITING',
|
// 先进空编辑页,用户保存/推送/发布时再落系统草稿
|
||||||
skuCount: 0,
|
await router.push({
|
||||||
});
|
path: '/pdd/goods/publish/editor/new',
|
||||||
message.success('已创建系统草稿');
|
query,
|
||||||
await router.push(`/pdd/goods/publish/editor/${draft.id}`);
|
});
|
||||||
} catch (e: any) {
|
|
||||||
message.error(e?.message || '创建失败');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function openEdit(id: number) {
|
function openEdit(id: number) {
|
||||||
|
|||||||
@@ -1,279 +1,87 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import type { UserDTO, UserVO } from '#/api/sys/user/types';
|
import type { MenuProps } from 'ant-design-vue';
|
||||||
|
|
||||||
import { computed, reactive, ref } from 'vue';
|
import { computed, onMounted, ref } from 'vue';
|
||||||
import { useRouter } from 'vue-router';
|
import { useRoute, useRouter } from 'vue-router';
|
||||||
|
|
||||||
import { Page } from '@vben/common-ui';
|
import { Page } from '@vben/common-ui';
|
||||||
|
import { createIconifyIcon } from '@vben/icons';
|
||||||
|
|
||||||
import { Button, Form, Input, message, Spin, Upload } from 'ant-design-vue';
|
import { Menu } from 'ant-design-vue';
|
||||||
|
|
||||||
import { getUserInfoApi, updateUserInfoApi } from '#/api/sys/user';
|
import ChangePasswordCard from './modules/ChangePasswordCard.vue';
|
||||||
import { FileCategory } from '#/constants/file-category';
|
import ProfileInfoCard from './modules/ProfileInfoCard.vue';
|
||||||
import { uploadFile } from '#/utils/upload-file';
|
|
||||||
|
|
||||||
defineOptions({ name: 'PersonalProfile' });
|
defineOptions({ name: 'PersonalCenter' });
|
||||||
|
|
||||||
|
type TabKey = 'password' | 'profile';
|
||||||
|
|
||||||
|
const route = useRoute();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
const loading = ref(false);
|
const ProfileIcon = createIconifyIcon('lucide:user');
|
||||||
const submitting = ref(false);
|
const LockIcon = createIconifyIcon('lucide:lock');
|
||||||
const userInfo = ref<UserVO.UserInfoVO | null>(null);
|
|
||||||
const avatarLoading = ref(false);
|
|
||||||
|
|
||||||
// 待上传的头像文件(用户选择后先缓存,保存时再上传)
|
const activeTab = ref<TabKey>('profile');
|
||||||
const pendingAvatarFile = ref<File | null>(null);
|
const selectedKeys = computed(() => [activeTab.value]);
|
||||||
|
|
||||||
// 计算属性:头像显示优先级:本地预览 > 已保存的头像 > 初始头像
|
/**
|
||||||
const avatarSrc = computed(() => {
|
* 页内切换只改本地状态,不要改 query。
|
||||||
if (pendingAvatarFile.value) {
|
* tabbar 用 fullPath 做标签 key,带 ?tab= 会开出两个系统标签。
|
||||||
return URL.createObjectURL(pendingAvatarFile.value);
|
*/
|
||||||
|
const onMenuClick: MenuProps['onClick'] = ({ key }) => {
|
||||||
|
activeTab.value = key === 'password' ? 'password' : 'profile';
|
||||||
|
};
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
// 兼容 /system/change-password → ?tab=password:读一次后清掉 query
|
||||||
|
if (route.query.tab === 'password') {
|
||||||
|
activeTab.value = 'password';
|
||||||
|
void router.replace({ path: route.path, query: {} });
|
||||||
}
|
}
|
||||||
if (userInfo.value?.avatar) {
|
|
||||||
return userInfo.value.avatar;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// 表单数据(与更新接口 DTO 一致,头像 ID 用 undefined 表示未变更/未上传)
|
|
||||||
const formData = reactive<UserDTO.UpdateUserInfoDTO>({
|
|
||||||
username: '',
|
|
||||||
realName: '',
|
|
||||||
phone: '',
|
|
||||||
remark: '',
|
|
||||||
});
|
|
||||||
|
|
||||||
const formRef = ref<any>(null);
|
|
||||||
|
|
||||||
async function fetchUserInfo() {
|
|
||||||
try {
|
|
||||||
loading.value = true;
|
|
||||||
const data = await getUserInfoApi();
|
|
||||||
userInfo.value = data;
|
|
||||||
formData.username = data.username || '';
|
|
||||||
formData.realName = data.realName || '';
|
|
||||||
formData.phone = data.phone || '';
|
|
||||||
formData.remark = data.remark || '';
|
|
||||||
// 重置待上传的头像
|
|
||||||
pendingAvatarFile.value = null;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('获取用户信息失败:', error);
|
|
||||||
message.error('获取用户信息失败');
|
|
||||||
} finally {
|
|
||||||
loading.value = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleAvatarChange({ file }: { file: any }) {
|
|
||||||
// 获取实际文件对象
|
|
||||||
const actualFile = file.originFileObj || file;
|
|
||||||
if (!actualFile) return;
|
|
||||||
|
|
||||||
if (!actualFile.type.startsWith('image/')) {
|
|
||||||
message.error('只能上传图片文件');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (actualFile.size > 2 * 1024 * 1024) {
|
|
||||||
message.error('图片大小不能超过 2MB');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 缓存头像文件,预览由 computed avatarSrc 自动处理
|
|
||||||
pendingAvatarFile.value = actualFile;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleSubmit() {
|
|
||||||
try {
|
|
||||||
await formRef.value?.validate();
|
|
||||||
submitting.value = true;
|
|
||||||
|
|
||||||
// 如果有待上传的头像,先上传
|
|
||||||
if (pendingAvatarFile.value) {
|
|
||||||
avatarLoading.value = true;
|
|
||||||
try {
|
|
||||||
const fileInfo = await uploadFile(pendingAvatarFile.value, {
|
|
||||||
category: FileCategory.AVATAR,
|
|
||||||
errorMessage: '头像上传失败',
|
|
||||||
});
|
|
||||||
formData.avatarImageId = fileInfo.id;
|
|
||||||
} finally {
|
|
||||||
avatarLoading.value = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
await updateUserInfoApi(formData);
|
|
||||||
message.success('保存成功');
|
|
||||||
formData.avatarImageId = undefined;
|
|
||||||
await fetchUserInfo();
|
|
||||||
} catch (error: any) {
|
|
||||||
if (error?.errorFields) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
console.error('保存失败:', error);
|
|
||||||
message.error('保存失败');
|
|
||||||
} finally {
|
|
||||||
submitting.value = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleReset() {
|
|
||||||
if (userInfo.value) {
|
|
||||||
formData.username = userInfo.value.username || '';
|
|
||||||
formData.realName = userInfo.value.realName || '';
|
|
||||||
formData.phone = userInfo.value.phone || '';
|
|
||||||
formData.remark = userInfo.value.remark || '';
|
|
||||||
}
|
|
||||||
formData.avatarImageId = undefined;
|
|
||||||
formRef.value?.resetFields();
|
|
||||||
pendingAvatarFile.value = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
fetchUserInfo();
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<Page
|
<Page auto-content-height content-class="flex min-h-0 flex-col">
|
||||||
title="个人信息"
|
<div
|
||||||
auto-content-height
|
class="flex min-h-0 flex-1 overflow-hidden rounded-2xl border border-slate-200/80 bg-white shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
||||||
class="bg-[#f8fafc] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
>
|
||||||
>
|
<aside
|
||||||
<div class="mx-auto max-w-2xl">
|
class="flex w-52 shrink-0 flex-col border-r border-slate-100 bg-slate-50/60 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]"
|
||||||
<Spin :spinning="loading">
|
>
|
||||||
<div
|
<div
|
||||||
class="overflow-hidden rounded-2xl border border-slate-200/80 bg-white shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
class="border-b border-slate-100 px-4 py-4 text-sm font-medium text-slate-600 dark:border-[hsl(240deg_3.7%_22%)] dark:text-[hsl(240deg_5%_64.9%)]"
|
||||||
>
|
>
|
||||||
<!-- 头部 -->
|
设置
|
||||||
<div class="border-b border-slate-100 bg-slate-50/50 px-8 py-6 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]">
|
|
||||||
<div class="flex items-start justify-between gap-3">
|
|
||||||
<div>
|
|
||||||
<h2 class="text-xl font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
|
||||||
个人信息
|
|
||||||
</h2>
|
|
||||||
<p class="mt-1 text-sm text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
|
|
||||||
编辑您的个人信息和头像
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Button type="link" class="!px-0" @click="router.push('/feedback')">
|
|
||||||
意见反馈
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 表单 -->
|
|
||||||
<div class="px-8 py-6">
|
|
||||||
<Form
|
|
||||||
ref="formRef"
|
|
||||||
:model="formData"
|
|
||||||
layout="vertical"
|
|
||||||
class="space-y-6"
|
|
||||||
>
|
|
||||||
<!-- 头像 -->
|
|
||||||
<div class="flex items-center">
|
|
||||||
<div class="mr-6">
|
|
||||||
<Upload
|
|
||||||
@change="handleAvatarChange"
|
|
||||||
:show-upload-list="false"
|
|
||||||
accept="image/*"
|
|
||||||
>
|
|
||||||
<div class="relative cursor-pointer">
|
|
||||||
<Spin
|
|
||||||
v-if="avatarLoading"
|
|
||||||
class="absolute inset-0 z-10 flex items-center justify-center bg-white/80"
|
|
||||||
/>
|
|
||||||
<img
|
|
||||||
v-if="avatarSrc"
|
|
||||||
:src="avatarSrc"
|
|
||||||
alt="头像"
|
|
||||||
class="h-24 w-24 rounded-full object-cover"
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
v-else
|
|
||||||
class="flex h-24 w-24 items-center justify-center rounded-full bg-slate-200 text-2xl text-slate-400 dark:bg-[hsl(240deg_3.7%_22%)] dark:text-[hsl(240deg_5%_64.9%)]"
|
|
||||||
>
|
|
||||||
{{ userInfo?.realName?.charAt(0) || '?' }}
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
class="absolute inset-0 flex items-center justify-center rounded-full bg-black/40 opacity-0 transition-opacity hover:opacity-100"
|
|
||||||
>
|
|
||||||
<span class="text-sm text-white">点击更换</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Upload>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p class="font-medium text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
|
||||||
头像
|
|
||||||
</p>
|
|
||||||
<p class="mt-1 text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
|
|
||||||
点击选择新头像,保存后生效,建议大小不超过 2MB
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 登录用户名(可选,用于账号登录) -->
|
|
||||||
<Form.Item
|
|
||||||
label="登录用户名"
|
|
||||||
name="username"
|
|
||||||
:rules="[
|
|
||||||
{ min: 3, max: 20, message: '登录用户名长度为3-20个字符' },
|
|
||||||
{
|
|
||||||
pattern: /^$|^[a-zA-Z0-9_]+$/,
|
|
||||||
message: '登录用户名只能包含字母、数字和下划线',
|
|
||||||
},
|
|
||||||
]"
|
|
||||||
>
|
|
||||||
<Input
|
|
||||||
v-model:value="formData.username"
|
|
||||||
placeholder="可选,设置后可用账号登录"
|
|
||||||
allow-clear
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
|
|
||||||
<!-- 真实姓名 -->
|
|
||||||
<Form.Item
|
|
||||||
label="真实姓名"
|
|
||||||
name="realName"
|
|
||||||
:rules="[{ required: true, message: '请输入真实姓名' }]"
|
|
||||||
>
|
|
||||||
<Input v-model:value="formData.realName" placeholder="请输入真实姓名" />
|
|
||||||
</Form.Item>
|
|
||||||
|
|
||||||
<!-- 手机号 -->
|
|
||||||
<Form.Item
|
|
||||||
label="手机号"
|
|
||||||
name="phone"
|
|
||||||
:rules="[
|
|
||||||
{ required: true, message: '请输入手机号' },
|
|
||||||
{ pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' },
|
|
||||||
]"
|
|
||||||
>
|
|
||||||
<Input
|
|
||||||
v-model:value="formData.phone"
|
|
||||||
placeholder="请输入手机号"
|
|
||||||
:maxlength="11"
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
|
|
||||||
<!-- 备注 -->
|
|
||||||
<Form.Item label="备注" name="remark">
|
|
||||||
<Input.TextArea
|
|
||||||
v-model:value="formData.remark"
|
|
||||||
placeholder="请输入备注"
|
|
||||||
:rows="3"
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
</Form>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 底部按钮 -->
|
|
||||||
<div class="flex justify-end gap-3 border-t border-slate-100 bg-slate-50/50 px-8 py-4 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]">
|
|
||||||
<Button @click="handleReset">重置</Button>
|
|
||||||
<Button type="primary" :loading="submitting" @click="handleSubmit">
|
|
||||||
保存
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</Spin>
|
<Menu
|
||||||
|
:selected-keys="selectedKeys"
|
||||||
|
mode="inline"
|
||||||
|
class="!border-none !bg-transparent"
|
||||||
|
@click="onMenuClick"
|
||||||
|
>
|
||||||
|
<Menu.Item key="profile">
|
||||||
|
<template #icon>
|
||||||
|
<ProfileIcon class="size-4" />
|
||||||
|
</template>
|
||||||
|
个人信息
|
||||||
|
</Menu.Item>
|
||||||
|
<Menu.Item key="password">
|
||||||
|
<template #icon>
|
||||||
|
<LockIcon class="size-4" />
|
||||||
|
</template>
|
||||||
|
修改密码
|
||||||
|
</Menu.Item>
|
||||||
|
</Menu>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<div class="min-h-0 min-w-0 flex-1 overflow-y-auto p-6">
|
||||||
|
<div class="mx-auto max-w-2xl">
|
||||||
|
<ProfileInfoCard v-if="activeTab === 'profile'" />
|
||||||
|
<ChangePasswordCard v-else />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Page>
|
</Page>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import type { FormItemProps } from 'ant-design-vue';
|
||||||
|
|
||||||
|
import { reactive, ref } from 'vue';
|
||||||
|
|
||||||
|
import { Button, Form, Input, message } from 'ant-design-vue';
|
||||||
|
|
||||||
|
import { changePasswordApi } from '#/api/core/auth';
|
||||||
|
|
||||||
|
defineOptions({ name: 'ChangePasswordCard' });
|
||||||
|
|
||||||
|
const loading = ref(false);
|
||||||
|
const formRef = ref<any>(null);
|
||||||
|
const formData = reactive({
|
||||||
|
oldPassword: '',
|
||||||
|
newPassword: '',
|
||||||
|
confirmPassword: '',
|
||||||
|
});
|
||||||
|
|
||||||
|
/** 确认密码校验放在 script,避免模板内 Promise 被误解析 */
|
||||||
|
const confirmPasswordRules: NonNullable<FormItemProps['rules']> = [
|
||||||
|
{
|
||||||
|
required: true,
|
||||||
|
async validator(_rule: unknown, value: string) {
|
||||||
|
if (!value?.trim()) {
|
||||||
|
throw new Error('请确认密码');
|
||||||
|
}
|
||||||
|
if (value !== formData.newPassword) {
|
||||||
|
throw new Error('两次输入的密码不一致');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
trigger: 'change',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
async function handleSubmit() {
|
||||||
|
try {
|
||||||
|
await formRef.value?.validate();
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
loading.value = true;
|
||||||
|
try {
|
||||||
|
await changePasswordApi({
|
||||||
|
oldPassword: formData.oldPassword,
|
||||||
|
newPassword: formData.newPassword,
|
||||||
|
});
|
||||||
|
message.success('密码修改成功');
|
||||||
|
handleReset();
|
||||||
|
} catch (err: any) {
|
||||||
|
message.error(err?.message || '密码修改失败');
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleReset() {
|
||||||
|
formRef.value?.resetFields();
|
||||||
|
formData.oldPassword = '';
|
||||||
|
formData.newPassword = '';
|
||||||
|
formData.confirmPassword = '';
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<div class="mb-6">
|
||||||
|
<h2 class="text-lg font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
||||||
|
修改密码
|
||||||
|
</h2>
|
||||||
|
<p class="mt-1 text-sm text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
|
||||||
|
请妥善保管您的新密码
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Form ref="formRef" :model="formData" layout="vertical">
|
||||||
|
<Form.Item
|
||||||
|
label="旧密码"
|
||||||
|
name="oldPassword"
|
||||||
|
:rules="[{ required: true, message: '请输入旧密码' }]"
|
||||||
|
>
|
||||||
|
<Input.Password
|
||||||
|
v-model:value="formData.oldPassword"
|
||||||
|
placeholder="请输入旧密码"
|
||||||
|
autocomplete="current-password"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item
|
||||||
|
label="新密码"
|
||||||
|
name="newPassword"
|
||||||
|
:rules="[
|
||||||
|
{ required: true, message: '请输入新密码' },
|
||||||
|
{ min: 6, max: 20, message: '密码长度为6-20个字符' },
|
||||||
|
]"
|
||||||
|
>
|
||||||
|
<Input.Password
|
||||||
|
v-model:value="formData.newPassword"
|
||||||
|
placeholder="请输入新密码"
|
||||||
|
autocomplete="new-password"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item
|
||||||
|
label="确认密码"
|
||||||
|
name="confirmPassword"
|
||||||
|
:rules="confirmPasswordRules"
|
||||||
|
>
|
||||||
|
<Input.Password
|
||||||
|
v-model:value="formData.confirmPassword"
|
||||||
|
placeholder="请再次输入新密码"
|
||||||
|
autocomplete="new-password"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
|
||||||
|
<div class="mt-2 flex justify-end gap-3">
|
||||||
|
<Button @click="handleReset">重置</Button>
|
||||||
|
<Button type="primary" :loading="loading" @click="handleSubmit">
|
||||||
|
确定
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -1,147 +0,0 @@
|
|||||||
<script lang="ts" setup>
|
|
||||||
import { reactive, ref } from 'vue';
|
|
||||||
import { useRouter } from 'vue-router';
|
|
||||||
|
|
||||||
import { Page } from '@vben/common-ui';
|
|
||||||
|
|
||||||
import type { FormItemProps } from 'ant-design-vue';
|
|
||||||
|
|
||||||
import { Button, Form, Input, message, Spin } from 'ant-design-vue';
|
|
||||||
|
|
||||||
import { changePasswordApi } from '#/api/core/auth';
|
|
||||||
|
|
||||||
defineOptions({ name: 'ChangePassword' });
|
|
||||||
|
|
||||||
const router = useRouter();
|
|
||||||
const loading = ref(false);
|
|
||||||
|
|
||||||
const formRef = ref<any>(null);
|
|
||||||
const formData = reactive({
|
|
||||||
oldPassword: '',
|
|
||||||
newPassword: '',
|
|
||||||
confirmPassword: '',
|
|
||||||
});
|
|
||||||
|
|
||||||
/** 放在 script 中,避免模板内联 validator 里 Promise 被误解析为组件属性 */
|
|
||||||
const confirmPasswordRules: NonNullable<FormItemProps['rules']> = [
|
|
||||||
{
|
|
||||||
required: true,
|
|
||||||
async validator(_rule: unknown, value: string) {
|
|
||||||
if (!value?.trim()) {
|
|
||||||
throw new Error('请确认密码');
|
|
||||||
}
|
|
||||||
if (value !== formData.newPassword) {
|
|
||||||
throw new Error('两次输入的密码不一致');
|
|
||||||
}
|
|
||||||
},
|
|
||||||
trigger: 'change',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
async function handleSubmit() {
|
|
||||||
try {
|
|
||||||
await formRef.value?.validate();
|
|
||||||
} catch {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
loading.value = true;
|
|
||||||
try {
|
|
||||||
await changePasswordApi({
|
|
||||||
oldPassword: formData.oldPassword,
|
|
||||||
newPassword: formData.newPassword,
|
|
||||||
});
|
|
||||||
message.success('密码修改成功');
|
|
||||||
formRef.value?.resetFields();
|
|
||||||
router.push('/system/profile');
|
|
||||||
} catch (err: any) {
|
|
||||||
message.error(err?.message || '密码修改失败');
|
|
||||||
} finally {
|
|
||||||
loading.value = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleReset() {
|
|
||||||
formRef.value?.resetFields();
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<Page
|
|
||||||
title="修改密码"
|
|
||||||
auto-content-height
|
|
||||||
class="bg-[#f8fafc] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
|
||||||
>
|
|
||||||
<div class="mx-auto max-w-2xl">
|
|
||||||
<div
|
|
||||||
class="overflow-hidden rounded-2xl border border-slate-200/80 bg-white shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
|
||||||
>
|
|
||||||
<!-- 头部 -->
|
|
||||||
<div class="border-b border-slate-100 bg-slate-50/50 px-8 py-6 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]">
|
|
||||||
<h2 class="text-xl font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
|
||||||
修改密码
|
|
||||||
</h2>
|
|
||||||
<p class="mt-1 text-sm text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
|
|
||||||
请妥善保管您的新密码
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 表单 -->
|
|
||||||
<div class="px-8 py-6">
|
|
||||||
<Spin :spinning="loading">
|
|
||||||
<Form
|
|
||||||
ref="formRef"
|
|
||||||
:model="formData"
|
|
||||||
layout="vertical"
|
|
||||||
class="space-y-6"
|
|
||||||
>
|
|
||||||
<!-- 旧密码 -->
|
|
||||||
<Form.Item
|
|
||||||
label="旧密码"
|
|
||||||
name="oldPassword"
|
|
||||||
:rules="[{ required: true, message: '请输入旧密码' }]"
|
|
||||||
>
|
|
||||||
<Input.Password
|
|
||||||
v-model:value="formData.oldPassword"
|
|
||||||
placeholder="请输入旧密码"
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
|
|
||||||
<!-- 新密码 -->
|
|
||||||
<Form.Item
|
|
||||||
label="新密码"
|
|
||||||
name="newPassword"
|
|
||||||
:rules="[{ required: true, message: '请输入新密码' }]"
|
|
||||||
>
|
|
||||||
<Input.Password
|
|
||||||
v-model:value="formData.newPassword"
|
|
||||||
placeholder="请输入新密码"
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
|
|
||||||
<!-- 确认密码 -->
|
|
||||||
<Form.Item
|
|
||||||
label="确认密码"
|
|
||||||
name="confirmPassword"
|
|
||||||
:rules="confirmPasswordRules"
|
|
||||||
>
|
|
||||||
<Input.Password
|
|
||||||
v-model:value="formData.confirmPassword"
|
|
||||||
placeholder="请再次输入新密码"
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
</Form>
|
|
||||||
</Spin>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 底部按钮 -->
|
|
||||||
<div class="flex justify-end gap-3 border-t border-slate-100 bg-slate-50/50 px-8 py-4 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]">
|
|
||||||
<Button @click="handleReset">重置</Button>
|
|
||||||
<Button type="primary" :loading="loading" @click="handleSubmit">
|
|
||||||
确定
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Page>
|
|
||||||
</template>
|
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import type { UserDTO, UserVO } from '#/api/sys/user/types';
|
||||||
|
|
||||||
|
import { computed, reactive, ref } from 'vue';
|
||||||
|
|
||||||
|
import { Button, Form, Input, message, Spin, Upload } from 'ant-design-vue';
|
||||||
|
|
||||||
|
import { getUserInfoApi, updateUserInfoApi } from '#/api/sys/user';
|
||||||
|
import { FileCategory } from '#/constants/file-category';
|
||||||
|
import { useAuthStore } from '#/store';
|
||||||
|
import { uploadFile } from '#/utils/upload-file';
|
||||||
|
|
||||||
|
defineOptions({ name: 'ProfileInfoCard' });
|
||||||
|
|
||||||
|
const authStore = useAuthStore();
|
||||||
|
|
||||||
|
const loading = ref(false);
|
||||||
|
const submitting = ref(false);
|
||||||
|
const userInfo = ref<UserVO.UserInfoVO | null>(null);
|
||||||
|
const avatarLoading = ref(false);
|
||||||
|
const pendingAvatarFile = ref<File | null>(null);
|
||||||
|
|
||||||
|
const avatarSrc = computed(() => {
|
||||||
|
if (pendingAvatarFile.value) {
|
||||||
|
return URL.createObjectURL(pendingAvatarFile.value);
|
||||||
|
}
|
||||||
|
if (userInfo.value?.avatar) {
|
||||||
|
return userInfo.value.avatar;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
|
||||||
|
const formData = reactive<UserDTO.UpdateUserInfoDTO>({
|
||||||
|
username: '',
|
||||||
|
realName: '',
|
||||||
|
phone: '',
|
||||||
|
remark: '',
|
||||||
|
});
|
||||||
|
|
||||||
|
const formRef = ref<any>(null);
|
||||||
|
|
||||||
|
async function fetchUserInfo() {
|
||||||
|
try {
|
||||||
|
loading.value = true;
|
||||||
|
const data = await getUserInfoApi();
|
||||||
|
userInfo.value = data;
|
||||||
|
formData.username = data.username || '';
|
||||||
|
formData.realName = data.realName || '';
|
||||||
|
formData.phone = data.phone || '';
|
||||||
|
formData.remark = data.remark || '';
|
||||||
|
pendingAvatarFile.value = null;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('获取用户信息失败:', error);
|
||||||
|
message.error('获取用户信息失败');
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleAvatarChange({ file }: { file: any }) {
|
||||||
|
const actualFile = file.originFileObj || file;
|
||||||
|
if (!actualFile) return;
|
||||||
|
|
||||||
|
if (!actualFile.type.startsWith('image/')) {
|
||||||
|
message.error('只能上传图片文件');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (actualFile.size > 2 * 1024 * 1024) {
|
||||||
|
message.error('图片大小不能超过 2MB');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
pendingAvatarFile.value = actualFile;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSubmit() {
|
||||||
|
try {
|
||||||
|
await formRef.value?.validate();
|
||||||
|
submitting.value = true;
|
||||||
|
|
||||||
|
if (pendingAvatarFile.value) {
|
||||||
|
avatarLoading.value = true;
|
||||||
|
try {
|
||||||
|
const fileInfo = await uploadFile(pendingAvatarFile.value, {
|
||||||
|
category: FileCategory.AVATAR,
|
||||||
|
errorMessage: '头像上传失败',
|
||||||
|
});
|
||||||
|
formData.avatarImageId = fileInfo.id;
|
||||||
|
} finally {
|
||||||
|
avatarLoading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await updateUserInfoApi(formData);
|
||||||
|
message.success('保存成功');
|
||||||
|
formData.avatarImageId = undefined;
|
||||||
|
await fetchUserInfo();
|
||||||
|
await authStore.fetchUserInfo();
|
||||||
|
} catch (error: any) {
|
||||||
|
if (error?.errorFields) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.error('保存失败:', error);
|
||||||
|
message.error('保存失败');
|
||||||
|
} finally {
|
||||||
|
submitting.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleReset() {
|
||||||
|
if (userInfo.value) {
|
||||||
|
formData.username = userInfo.value.username || '';
|
||||||
|
formData.realName = userInfo.value.realName || '';
|
||||||
|
formData.phone = userInfo.value.phone || '';
|
||||||
|
formData.remark = userInfo.value.remark || '';
|
||||||
|
}
|
||||||
|
formData.avatarImageId = undefined;
|
||||||
|
formRef.value?.resetFields();
|
||||||
|
pendingAvatarFile.value = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchUserInfo();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<div class="mb-6">
|
||||||
|
<h2 class="text-lg font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
||||||
|
个人信息
|
||||||
|
</h2>
|
||||||
|
<p class="mt-1 text-sm text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
|
||||||
|
编辑头像、登录用户名与联系方式
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Spin :spinning="loading">
|
||||||
|
<Form ref="formRef" :model="formData" layout="vertical">
|
||||||
|
<div class="mb-6 flex items-center">
|
||||||
|
<div class="mr-5">
|
||||||
|
<Upload
|
||||||
|
accept="image/*"
|
||||||
|
:show-upload-list="false"
|
||||||
|
@change="handleAvatarChange"
|
||||||
|
>
|
||||||
|
<div class="relative cursor-pointer">
|
||||||
|
<Spin
|
||||||
|
v-if="avatarLoading"
|
||||||
|
class="absolute inset-0 z-10 flex items-center justify-center bg-white/80"
|
||||||
|
/>
|
||||||
|
<img
|
||||||
|
v-if="avatarSrc"
|
||||||
|
:src="avatarSrc"
|
||||||
|
alt="头像"
|
||||||
|
class="h-20 w-20 rounded-full object-cover"
|
||||||
|
/>
|
||||||
|
<div
|
||||||
|
v-else
|
||||||
|
class="flex h-20 w-20 items-center justify-center rounded-full bg-slate-200 text-xl text-slate-400 dark:bg-[hsl(240deg_3.7%_22%)] dark:text-[hsl(240deg_5%_64.9%)]"
|
||||||
|
>
|
||||||
|
{{ userInfo?.realName?.charAt(0) || '?' }}
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="absolute inset-0 flex items-center justify-center rounded-full bg-black/40 opacity-0 transition-opacity hover:opacity-100"
|
||||||
|
>
|
||||||
|
<span class="text-xs text-white">更换</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Upload>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p class="font-medium text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
||||||
|
头像
|
||||||
|
</p>
|
||||||
|
<p
|
||||||
|
class="mt-1 text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
|
||||||
|
>
|
||||||
|
点击更换,保存后生效,不超过 2MB
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Form.Item
|
||||||
|
label="登录用户名"
|
||||||
|
name="username"
|
||||||
|
:rules="[
|
||||||
|
{ min: 3, max: 20, message: '登录用户名长度为3-20个字符' },
|
||||||
|
{
|
||||||
|
pattern: /^$|^[a-zA-Z0-9_]+$/,
|
||||||
|
message: '登录用户名只能包含字母、数字和下划线',
|
||||||
|
},
|
||||||
|
]"
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
v-model:value="formData.username"
|
||||||
|
allow-clear
|
||||||
|
placeholder="可选,设置后可用账号登录"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item
|
||||||
|
label="真实姓名"
|
||||||
|
name="realName"
|
||||||
|
:rules="[{ required: true, message: '请输入真实姓名' }]"
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
v-model:value="formData.realName"
|
||||||
|
placeholder="请输入真实姓名"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item
|
||||||
|
label="手机号"
|
||||||
|
name="phone"
|
||||||
|
:rules="[
|
||||||
|
{ required: true, message: '请输入手机号' },
|
||||||
|
{ pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' },
|
||||||
|
]"
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
v-model:value="formData.phone"
|
||||||
|
:maxlength="11"
|
||||||
|
placeholder="请输入手机号"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item label="备注" name="remark">
|
||||||
|
<Input.TextArea
|
||||||
|
v-model:value="formData.remark"
|
||||||
|
:rows="3"
|
||||||
|
placeholder="请输入备注"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
</Spin>
|
||||||
|
|
||||||
|
<div class="mt-2 flex justify-end gap-3">
|
||||||
|
<Button @click="handleReset">重置</Button>
|
||||||
|
<Button type="primary" :loading="submitting" @click="handleSubmit">
|
||||||
|
保存
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
Reference in New Issue
Block a user