Compare commits

17 Commits
Author SHA1 Message Date
qinghua 4e956eadcd fix: 修复助手输入框长引用标签溢出导致后续文字叠字 2026-09-28 11:11:03 +08:00
qinghua 3e49d6e9c9 feat: 用户消息中的实体引用展示为标签 2026-09-28 11:00:31 +08:00
qinghua 59881dcb68 feat: 助手引用改为行内标签样式并可自由插入 2026-09-28 10:57:14 +08:00
qinghua e136084794 feat: 发布工作台改为保存/推送/发布时再创建系统草稿 2026-09-28 10:11:57 +08:00
qinghua 92b6026b48 fix: 发布编辑器折扣改为正常折扣并由前端换算后提交 2026-09-28 10:01:39 +08:00
qinghua 370ead39a1 style: 优化智能助手sender样式 2026-09-26 17:15:44 +08:00
qinghua 5567b6d281 feat: 发布草稿助手 UI 对齐智能助手页交互 2026-09-26 16:58:04 +08:00
qinghua 85bac4f710 feat: 智能助手支持软删会话并级联隐藏消息 2026-09-26 16:47:01 +08:00
qinghua 13a2bd9274 refactor: 更换对话加载动画 2026-09-26 00:34:28 +08:00
qinghua 883a1d0cfe fix: 优化助手输入区发送/展开与浅色对比,并精简侧栏展开态图标 2026-09-26 00:19:36 +08:00
qinghua 67d01c678a refactor: 智能助手侧栏支持收起图标轨与居中可拖拽会话搜索 2026-09-25 23:56:19 +08:00
qinghua a72a43cffc refactor: 智能助手页对齐 ChatGPT 式侧栏分组与居中空态布局 2026-09-25 23:38:13 +08:00
qinghua 0b460e22b0 refactor: 助手记忆页改用 VXE 表格与 Alert 对齐系统列表风格 2026-09-25 00:35:36 +08:00
qinghua 41f022bd63 fix: store 证伪时优先无状态 Responses,失败再降 Completions 2026-09-25 00:29:51 +08:00
qinghua 71eca63461 fix: 探测 Responses/store 能力并在无状态时用 Completions 带全量历史 2026-09-25 00:23:28 +08:00
qinghua d20c6a1302 feat: 支持 Completions/Responses 双协议,并在同选型下续链加速 2026-09-24 17:10:34 +08:00
qinghua 9c2c1ed061 feat: 个人中心两栏布局整合资料与改密 2026-09-23 17:40:07 +08:00
51 changed files with 3926 additions and 980 deletions
+22 -1
View File
@@ -125,6 +125,7 @@ apps/agent/
| `summary` | 会话滚动摘要(可选) |
| `llm_provider_id` | 会话选用的提供商 id |
| `llm_model` | 会话选用的模型 id;与 provider 一起消歧;空则对话时回落公司默认并回写 |
| `llm_response_chain` | 可选;Responses 续链 `{provider_id,model,previous_response_id}` |
| `created_at`, `updated_at`, `last_message_at` | |
唯一索引:`(company_id, user_id, thread_id)`
@@ -225,6 +226,7 @@ Agent 内部:`GET /api/internal/agent/llm-runtime?companyId=&providerId=&model
| GET | `/sessions` | 当前用户会话列表(含 `llmProviderId` / `llmModel`) |
| POST | `/sessions` | 新建会话(可带选型;缺省写公司默认) |
| PATCH | `/sessions/{thread_id}` | 改标题;或同时改 `llmProviderId`+`llmModel` |
| DELETE | `/sessions/{thread_id}` | 软删会话(`status=deleted`),级联软删该线程消息 |
| GET | `/sessions/{thread_id}/messages` | 历史消息(分页/游标) |
| POST | `/sessions/{thread_id}/chat` | **流式**发消息(SSE);按会话选型解析 runtime |
| 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 约定。
+1 -1
View File
@@ -16,7 +16,7 @@ uvicorn api.main:app --reload --host 0.0.0.0 --port 8200
健康检查:`GET http://localhost:8200/health`
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
View File
@@ -19,7 +19,11 @@ from infrastructure.persistence.mongo.repositories import (
MongoMessageRepository,
MongoSessionRepository,
)
from infrastructure.persistence.redis.cache import RedisLlmRuntimeCache, get_redis
from infrastructure.persistence.redis.cache import (
RedisLlmProtocolCapabilityCache,
RedisLlmRuntimeCache,
get_redis,
)
async def current_actor(
@@ -46,7 +50,11 @@ async def session_service(
llm_svc: LlmRuntimeService = Depends(llm_runtime_service),
) -> SessionService:
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:
@@ -68,5 +76,8 @@ async def chat_service(
messages=MongoMessageRepository(db),
llm_runtime=llm_svc,
memory=mem_svc,
streamer=OpenAICompatibleStreamer(),
streamer=OpenAICompatibleStreamer(
RedisLlmProtocolCapabilityCache(get_redis(settings)),
capability_ttl_seconds=settings.llm_capability_ttl_seconds,
),
)
+14
View File
@@ -120,3 +120,17 @@ async def archive_session(
except LookupError as e:
raise HTTPException(status_code=404, detail=str(e)) from e
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))
+41 -3
View File
@@ -12,7 +12,13 @@ from application.memory_service import MemoryService
from application.session_service import SessionService
from application.system_prompt import build_system_prompt
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
@@ -63,7 +69,6 @@ class ChatService:
provider_id=session.llm_provider_id,
model=session.llm_model,
)
# 回落默认或消歧后写回会话,保证列表/选框稳定
changed = False
if session.llm_model != llm.model:
session.llm_model = llm.model
@@ -72,6 +77,13 @@ class ChatService:
session.llm_provider_id = llm.provider_id
changed = True
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)
just_saved = None
@@ -120,7 +132,6 @@ class ChatService:
reserve_output_tokens=self._settings.context_reserve_output_tokens,
reserve_tool_tokens=self._settings.context_reserve_tool_tokens,
)
# 本轮 tool 结果字符上限(与预留 tool token 粗对齐)
max_tool_chars = max(
500, self._settings.context_reserve_tool_tokens * 2
)
@@ -142,6 +153,7 @@ class ChatService:
await self._session_repo.update(session)
parts: list[str] = []
new_response_id: str | None = None
async for event in self._streamer.stream_reply(
llm=llm,
history=history,
@@ -149,7 +161,11 @@ class ChatService:
system_prompt=system_prompt,
tools=tools or None,
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:
parts.append(event.text)
yield event
@@ -167,4 +183,26 @@ class ChatService:
)
)
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)
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,
provider_id=None,
context_window=None,
api_style="auto",
)
raise HTTPException(
+23 -1
View File
@@ -7,7 +7,7 @@ from datetime import datetime
from application.llm_settings_service import LlmRuntimeService
from domain.models import Actor, Session, SessionStatus
from domain.ports import SessionRepository
from domain.ports import MessageRepository, SessionRepository
class SessionService:
@@ -15,9 +15,11 @@ class SessionService:
self,
sessions: SessionRepository,
llm_runtime: LlmRuntimeService | None = None,
messages: MessageRepository | None = None,
) -> None:
self._sessions = sessions
self._llm_runtime = llm_runtime
self._messages = messages
async def create(
self,
@@ -103,11 +105,31 @@ class SessionService:
if llm_provider_id is None or int(llm_provider_id) <= 0:
raise ValueError("提供商不能为空")
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_model = model
if switched:
# 切换选型后厂商侧链不可复用
session.llm_response_chain = None
return await self._sessions.update(session)
async def archive(self, actor: Actor, thread_id: str) -> Session:
session = await self.require_owned(actor, thread_id)
session.status = SessionStatus.ARCHIVED
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
+4 -3
View File
@@ -12,9 +12,10 @@ _BASE_SYSTEM = (
"需要经营数据时优先调用可用工具。"
"工具可多轮检索,但对用户只报结论;默认不汇报检索过程、未命中关键词、搜了几轮或工具名。"
"不要自我纠错或评论上一轮话术(如「不该露编号」)。"
"你具备跨会话的用户级长期记忆,但内容不会自动注入对话。"
"需要称呼、偏好或用户事实时:先 memory_search,必要时再 memory_load;"
"禁止编造未载入的记忆,也不要声称没有长期记忆能力。"
"【本会话上下文】请求里已包含本会话近期的用户与助手原文,你可以直接看见并引用;"
"禁止声称「只收到当前一句」或「前面几轮不会带过来」——那是错误描述。"
"【长期记忆】跨会话的用户级记忆不会自动注入;需要称呼、偏好或用户事实时:"
"先 memory_search,必要时再 memory_load;禁止编造未载入的记忆,也不要声称没有长期记忆能力。"
"介绍记忆:自然语言短列表即可;禁止输出 ref、id、字段名、更新时间或表格。"
"问「有哪些记忆」:有则直接列举命中摘要,无则一句「暂时没有相关记忆」;"
"不必强调「就这一条」,未问勿主动建议再记店铺/商品/口径。"
+2
View File
@@ -77,6 +77,8 @@ class Settings(BaseSettings):
# 为模型输出与本轮 tool 预留的 token
context_reserve_output_tokens: int = 4096
context_reserve_tool_tokens: int = 8192
# Responses/store 能力缓存 TTL(秒)
llm_capability_ttl_seconds: int = 604800
@property
def cors_origin_list(self) -> list[str]:
+29 -1
View File
@@ -50,6 +50,15 @@ class Actor:
return role in {"owner", "admin"}
@dataclass
class LlmResponseChain:
"""同提供商同模型下的 Responses 续链缓存(非真相源;失效则 Mongo rebuild)。"""
provider_id: int | None
model: str
previous_response_id: str
@dataclass
class Session:
thread_id: str
@@ -65,6 +74,8 @@ class Session:
# 会话选用的提供商 + 模型(同名 model 靠 provider 消歧)
llm_provider_id: int | None = None
llm_model: str | None = None
# Responses 续链;切换选型或链失效时清空
llm_response_chain: LlmResponseChain | None = None
created_at: datetime = field(default_factory=datetime.utcnow)
updated_at: datetime = field(default_factory=datetime.utcnow)
last_message_at: datetime | None = None
@@ -118,19 +129,31 @@ class LlmRuntimeConfig:
extra_headers: dict[str, str] = field(default_factory=dict)
# 租户配置的上下文窗口;None 表示由 Agent 按模型名估计
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)
class StreamEvent:
"""流式片段:正文 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
phase: str | None = None # start | end
name: str | None = None
label: str | None = None
tool_call_id: str | None = None
args: dict | None = None
# Responses 本轮最终 response id(仅 kind=response_chain)
response_id: str | None = None
@staticmethod
def token(text: str) -> StreamEvent:
@@ -159,3 +182,8 @@ class StreamEvent:
@staticmethod
def pending_client_tools() -> StreamEvent:
return StreamEvent(kind="pending_client_tools")
@staticmethod
def response_chain(response_id: str) -> StreamEvent:
"""内部事件:落会话续链;不推给前端 SSE。"""
return StreamEvent(kind="response_chain", response_id=response_id)
+35 -1
View File
@@ -5,7 +5,14 @@ from __future__ import annotations
from abc import ABC, abstractmethod
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):
@@ -51,6 +58,13 @@ class MessageRepository(ABC):
@abstractmethod
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):
@abstractmethod
@@ -111,6 +125,25 @@ class LlmRuntimeGateway(ABC):
) -> 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):
"""流式生成助手回复。"""
@@ -124,4 +157,5 @@ class ChatStreamer(ABC):
system_prompt: str,
tools: list[Any] | None = None,
max_tool_result_chars: int = 4000,
previous_response_id: str | None = None,
) -> AsyncIterator[StreamEvent]: ...
+128
View File
@@ -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"
+378 -25
View File
@@ -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
import json
import logging
from typing import Any, AsyncIterator
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.publish_ui import is_client_tool_name
from domain.models import ChatMessage, LlmRuntimeConfig, MessageRole, StreamEvent
from domain.ports import ChatStreamer
from domain.models import (
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):
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(
self,
*,
@@ -24,40 +54,331 @@ class OpenAICompatibleStreamer(ChatStreamer):
system_prompt: str,
tools: list[Any] | None = None,
max_tool_result_chars: int = 8000,
previous_response_id: str | None = None,
) -> AsyncIterator[StreamEvent]:
model = ChatOpenAI(
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,
chain_id = (previous_response_id or "").strip() or None
style = normalize_api_style(llm.api_style)
# 未知 store 时先做语义探测(能否靠 previous_response_id 记住上下文)
cap = await self._ensure_protocol_capability(llm, style)
attempts = plan_protocol_attempts(
llm.api_style, cap, has_chain_id=bool(chain_id)
)
messages: list[Any] = [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))
i = 0
while i < len(attempts):
attempt = attempts[i]
# 仅缓存已证实 store=true 时才丢历史、纯续链
use_chain_id = (
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:
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)
if text:
yield StreamEvent.token(text)
if use_store and last_response_id:
yield StreamEvent.response_chain(last_response_id)
return
# 工具轮:每轮用 astream 边生成边推 token;出现 tool_call 再执行工具后继续
bound = model.bind_tools(tools)
tool_map = {t.name: t for t in tools if getattr(t, "name", None)}
tool_cap = max(500, max_tool_result_chars)
for _ in range(5):
for round_idx in range(5):
gathered = None
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
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
continue
if saw_tool:
@@ -65,12 +386,19 @@ class OpenAICompatibleStreamer(ChatStreamer):
text = _chunk_text(getattr(chunk, "content", None))
if text:
yield StreamEvent.token(text)
if gathered is None:
yield StreamEvent.token("(模型未返回内容)")
if use_store and last_response_id:
yield StreamEvent.response_chain(last_response_id)
return
last_response_id = _response_id_of(gathered) or last_response_id
messages.append(gathered)
tool_calls = getattr(gathered, "tool_calls", None) or []
if not tool_calls:
if use_store and last_response_id:
yield StreamEvent.response_chain(last_response_id)
return
seen: set[str] = set()
@@ -121,19 +449,44 @@ class OpenAICompatibleStreamer(ChatStreamer):
)
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:
"""兼容 Completions 字符串与 Responses 结构化 content 块。"""
if content is None:
return ""
if isinstance(content, str):
return content
if isinstance(content, list):
parts: list[str] = []
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")
if t:
parts.append(str(t))
elif isinstance(part, str):
parts.append(part)
return "".join(parts)
return ""
+4
View File
@@ -9,6 +9,7 @@ import httpx
from config.settings import Settings
from domain.models import LlmRuntimeConfig
from domain.ports import LlmRuntimeGateway
from infrastructure.llm.api_style import normalize_api_style
logger = logging.getLogger(__name__)
@@ -53,6 +54,9 @@ class ServerLlmRuntimeGateway(LlmRuntimeGateway):
for k, v in (data.get("extraHeaders") or {}).items()
},
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:
logger.exception(
@@ -11,6 +11,7 @@ from motor.motor_asyncio import AsyncIOMotorDatabase
from domain.models import (
ChatMessage,
LlmResponseChain,
MemoryKind,
MemoryStatus,
MessageRole,
@@ -36,6 +37,30 @@ def _optional_int(v: Any) -> int | 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):
def __init__(self, db: AsyncIOMotorDatabase) -> None:
self._col = db.agent_sessions
@@ -52,6 +77,7 @@ class MongoSessionRepository(SessionRepository):
"scene_ref": session.scene_ref,
"llm_provider_id": session.llm_provider_id,
"llm_model": session.llm_model,
"llm_response_chain": _chain_to_doc(session.llm_response_chain),
"created_at": session.created_at,
"updated_at": session.updated_at,
"last_message_at": session.last_message_at,
@@ -135,6 +161,7 @@ class MongoSessionRepository(SessionRepository):
"scene_ref": session.scene_ref,
"llm_provider_id": session.llm_provider_id,
"llm_model": session.llm_model,
"llm_response_chain": _chain_to_doc(session.llm_response_chain),
"updated_at": session.updated_at,
"last_message_at": session.last_message_at,
}
@@ -155,6 +182,7 @@ class MongoSessionRepository(SessionRepository):
scene_ref=doc.get("scene_ref"),
llm_provider_id=_optional_int(doc.get("llm_provider_id")),
llm_model=doc.get("llm_model"),
llm_response_chain=_chain_from_doc(doc.get("llm_response_chain")),
created_at=_dt(doc.get("created_at")),
updated_at=_dt(doc.get("updated_at")),
last_message_at=doc.get("last_message_at"),
@@ -194,7 +222,17 @@ class MongoMessageRepository(MessageRepository):
) -> list[ChatMessage]:
cursor = (
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)
.limit(limit)
@@ -203,6 +241,24 @@ class MongoMessageRepository(MessageRepository):
rows.reverse()
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
def _to_msg(doc: dict[str, Any]) -> ChatMessage:
return ChatMessage(
@@ -7,8 +7,9 @@ import json
import redis.asyncio as redis
from config.settings import Settings
from domain.models import LlmRuntimeConfig
from domain.ports import LlmRuntimeCache
from domain.models import LlmProtocolCapability, LlmRuntimeConfig
from domain.ports import LlmProtocolCapabilityCache, LlmRuntimeCache
from infrastructure.llm.api_style import normalize_api_style
class RedisLlmRuntimeCache(LlmRuntimeCache):
@@ -43,6 +44,7 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
provider_id=_optional_int(data.get("provider_id")) or provider_id,
extra_headers=data.get("extra_headers") or {},
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:
return None
@@ -63,6 +65,7 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
"model": config.model,
"extra_headers": config.extra_headers,
"context_window": config.context_window,
"api_style": normalize_api_style(config.api_style),
}
await self._r.set(
self._key(company_id, config.provider_id, config.model),
@@ -96,6 +99,53 @@ def get_redis(settings: Settings) -> redis.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:
global _redis
if _redis is not None:
+1 -1
View File
@@ -8,7 +8,7 @@ motor>=3.6.0
redis>=5.2.0
httpx>=0.27.0
langchain-core>=0.3.0
langchain-openai>=0.2.0
langchain-openai>=0.3.26
langchain-mcp-adapters>=0.1.0
langgraph>=0.2.0
sse-starlette>=2.1.0
+68
View File
@@ -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"
+32
View File
@@ -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_suffix` varchar(16) NOT NULL DEFAULT '' COMMENT 'Key 末几位(展示掩码)',
`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 '可选额外请求头',
`create_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`;
@@ -16,4 +16,9 @@ public class CreateAgentLlmProviderDTO {
private String apiKey;
private String displayName;
/**
* API 协议:auto | completions | responses;空则 auto
*/
private String apiStyle;
}
@@ -16,4 +16,9 @@ public class UpdateAgentLlmProviderDTO {
/** 传 null 表示不改;传空串可清空备注 */
private String displayName;
/**
* API 协议:auto | completions | responses;null 不改
*/
private String apiStyle;
}
@@ -33,6 +33,12 @@ public class AgentCompanyLlmProviderPO {
@TableField("display_name")
private String displayName;
/**
* API 协议:auto | completions | responses
*/
@TableField("api_style")
private String apiStyle;
@TableField("extra_headers_json")
private String extraHeadersJson;
@@ -16,5 +16,9 @@ public class AgentLlmProviderVO {
private String displayName;
private String apiKeyMasked;
private String updateTime;
/**
* API 协议:auto | completions | responses
*/
private String apiStyle;
private List<AgentLlmModelVO> models = new ArrayList<>();
}
@@ -15,5 +15,9 @@ public class AgentLlmRuntimeVO {
private String model;
/** 上下文窗口 token;可能为 null */
private Integer contextWindow;
/**
* API 协议:auto | completions | responses
*/
private String apiStyle;
private Map<String, String> extraHeaders;
}
@@ -98,6 +98,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
po.setApiKeyEncrypted(crypto.encrypt(plain));
po.setApiKeySuffix(plain.length() >= 4 ? plain.substring(plain.length() - 4) : plain);
po.setDisplayName(trimToNull(dto.getDisplayName()));
po.setApiStyle(normalizeApiStyle(dto.getApiStyle()));
po.setCreateBy(userId);
po.setUpdateBy(userId);
providerMapper.insert(po);
@@ -123,6 +124,9 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
if (dto.getDisplayName() != null) {
existing.setDisplayName(trimToNull(dto.getDisplayName()));
}
if (dto.getApiStyle() != null) {
existing.setApiStyle(normalizeApiStyle(dto.getApiStyle()));
}
existing.setUpdateBy(userId);
providerMapper.updateById(existing);
evictRuntimeCache(companyId);
@@ -432,6 +436,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
vo.setApiKey(crypto.decrypt(provider.getApiKeyEncrypted()));
vo.setModel(model.getModel());
vo.setContextWindow(model.getContextWindow());
vo.setApiStyle(normalizeApiStyle(provider.getApiStyle()));
vo.setExtraHeaders(parseHeaders(provider.getExtraHeadersJson()));
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) {
if (raw == null || raw <= 0) {
return null;
@@ -546,6 +562,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
vo.setConfigured(true);
vo.setBaseUrl(provider.getBaseUrl());
vo.setDisplayName(provider.getDisplayName());
vo.setApiStyle(normalizeApiStyle(provider.getApiStyle()));
vo.setApiKeyMasked("****" + (provider.getApiKeySuffix() == null ? "" : provider.getApiKeySuffix()));
if (provider.getUpdateTime() != null) {
vo.setUpdateTime(provider.getUpdateTime().format(ISO));
@@ -570,6 +587,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
payload.put("api_key", runtime.getApiKey());
payload.put("model", runtime.getModel());
payload.put("context_window", runtime.getContextWindow());
payload.put("api_style", runtime.getApiStyle() == null ? "auto" : runtime.getApiStyle());
payload.put("extra_headers",
runtime.getExtraHeaders() == null ? Map.of() : runtime.getExtraHeaders());
stringRedisTemplate.opsForValue().set(
@@ -612,6 +630,8 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
} else {
vo.setContextWindow(null);
}
Object style = map.get("api_style");
vo.setApiStyle(style == null ? "auto" : normalizeApiStyle(String.valueOf(style)));
Object headers = map.get("extra_headers");
if (headers instanceof Map<?, ?> m) {
Map<String, String> h = new HashMap<>();
+14 -1
View File
@@ -53,6 +53,8 @@ export namespace AgentVO {
configured: boolean;
baseUrl?: string | null;
displayName?: string | null;
/** auto | completions | responses */
apiStyle?: string | null;
apiKeyMasked?: string | null;
models?: LlmModelItem[];
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) {
return requestClient.get<{ items: AgentVO.Message[] }>(
`/agent/sessions/${threadId}/messages`,
@@ -140,6 +147,7 @@ export async function createAgentLlmProviderApi(body: {
baseUrl: string;
apiKey: string;
displayName?: string;
apiStyle?: string;
}) {
return requestClient.post<AgentVO.LlmProvider>(
'/company/agent-llm-providers',
@@ -149,7 +157,12 @@ export async function createAgentLlmProviderApi(body: {
export async function updateAgentLlmProviderApi(
providerId: number,
body: { baseUrl?: string; apiKey?: string; displayName?: string },
body: {
baseUrl?: string;
apiKey?: string;
displayName?: string;
apiStyle?: string;
},
) {
return requestClient.put<AgentVO.LlmProvider>(
`/company/agent-llm-providers/${providerId}`,
@@ -4,6 +4,7 @@ export {
createAgentSessionApi,
deleteAgentLlmProviderApi,
deleteAgentMemoryApi,
deleteAgentSessionApi,
getAgentLlmProviderApi,
listAgentEnabledLlmModelsApi,
listAgentLlmProvidersApi,
+5 -15
View File
@@ -113,10 +113,8 @@ const UserIcon = createIconifyIcon('lucide:user');
const MemoryIcon = createIconifyIcon('lucide:brain');
// 意见反馈图标
const FeedbackIcon = createIconifyIcon('lucide:message-square-plus');
// 锁图标
const LockIcon = createIconifyIcon('lucide:lock');
/** 是否具备智能助手聊天权限(用于「我的记忆」入口;含超管) */
/** 是否具备智能助手聊天权限(用于「助手记忆」入口;含超管) */
const canUseAgentChat = computed(() => hasPermission('agent:chat'));
/** 当前用户可切换的可用公司数 */
@@ -128,22 +126,22 @@ const companyCount = computed(() => {
const menus = computed(() => {
const menuItems = [];
// 个人信息
// 个人中心
menuItems.push({
handler: () => {
router.push('/system/profile');
},
icon: UserIcon,
text: '个人信息',
text: '个人中心',
});
// 我的记忆(有助手聊天权才显示)
// 助手记忆(有助手聊天权才显示)
if (canUseAgentChat.value) {
menuItems.push({
handler: () => {
router.push('/agent/memories');
},
icon: MemoryIcon,
text: '我的记忆',
text: '助手记忆',
});
}
// 意见反馈
@@ -154,14 +152,6 @@ const menus = computed(() => {
icon: FeedbackIcon,
text: '意见反馈',
});
// 修改密码
menuItems.push({
handler: () => {
router.push('/system/change-password');
},
icon: LockIcon,
text: '修改密码',
});
// 可切换公司数大于 1 时显示切换公司
if (companyCount.value > 1) {
@@ -1,16 +1,13 @@
import type { RouteRecordRaw } from 'vue-router';
/**
* 修改密码静态路由
* 修改密码:并入个人中心,保留旧路径兼容跳转
*/
const staticRoutes: RouteRecordRaw[] = [
{
name: 'ChangePassword',
path: '/system/change-password',
component: () =>
import(
'#/views/sys/profile/modules/ChangePasswordModal.vue'
),
redirect: '/system/profile?tab=password',
meta: {
title: '修改密码',
hideInMenu: true,
@@ -1,7 +1,7 @@
import type { RouteRecordRaw } from 'vue-router';
/**
* 用户记忆管理(头像下拉入口;不进侧栏菜单)
* 助手长期记忆管理(头像下拉「助手记忆」入口;不进侧栏菜单)
*/
const staticRoutes: RouteRecordRaw[] = [
{
@@ -10,7 +10,7 @@ const staticRoutes: RouteRecordRaw[] = [
component: () => import('#/views/agent/memories/index.vue'),
meta: {
icon: 'lucide:brain',
title: '我的记忆',
title: '助手记忆',
hideInMenu: true,
ignoreAccess: true,
},
@@ -5,14 +5,16 @@ import type { RouteRecordRaw } from 'vue-router';
*/
const staticRoutes: RouteRecordRaw[] = [
{
name: 'PersonalProfile',
name: 'PersonalCenter',
path: '/system/profile',
component: () => import('#/views/sys/profile/index.vue'),
meta: {
icon: 'lucide:user',
title: '个人信息',
title: '个人中心',
hideInMenu: true,
ignoreAccess: true,
// 页内 ?tab= 不另开系统标签
fullPathKey: false,
},
},
];
@@ -0,0 +1,70 @@
<script lang="ts" setup>
import { computed } from 'vue';
import {
catalogCiteLabel,
parseMessageCiteSegments,
} from './catalog-cite';
/** 把消息正文里的实体引用渲染成标签(兼容 token / 展开 line)。 */
const props = defineProps<{
text: string;
}>();
const segments = computed(() => parseMessageCiteSegments(props.text || ''));
const hasCite = computed(() => segments.value.some((s) => s.type === 'cite'));
</script>
<template>
<span class="cite-rich-text" :class="{ 'cite-rich-text--plain': !hasCite }">
<template v-for="(seg, index) in segments" :key="index">
<span v-if="seg.type === 'text'" class="cite-rich-text__text">{{
seg.value
}}</span>
<span
v-else
class="cite-msg-chip"
:title="seg.id != null ? `id=${seg.id}` : undefined"
>
<span class="cite-msg-chip__kind">{{ catalogCiteLabel(seg.kind) }}</span>
<span class="cite-msg-chip__title">{{ seg.title }}</span>
</span>
</template>
</span>
</template>
<style scoped>
.cite-rich-text {
display: inline;
word-break: break-word;
white-space: pre-wrap;
}
.cite-msg-chip {
display: inline-flex;
max-width: 14rem;
align-items: center;
gap: 4px;
margin: 0 2px;
padding: 0 6px;
overflow: hidden;
vertical-align: middle;
font-size: 12px;
line-height: 20px;
color: hsl(var(--primary));
white-space: nowrap;
background: hsl(var(--primary) / 0.12);
border-radius: 6px;
}
.cite-msg-chip__kind {
flex-shrink: 0;
opacity: 0.7;
}
.cite-msg-chip__title {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
File diff suppressed because it is too large Load Diff
@@ -10,25 +10,100 @@ export interface CatalogCite {
line: string;
}
/** 光标处未完成的 @ 查询区间 */
export interface MentionHit {
start: number;
end: number;
query: string;
}
const KIND_LABEL: Record<CatalogCiteKind, string> = {
shop: '店铺',
product: '商品',
sku: 'SKU',
};
const LABEL_KIND: Record<string, CatalogCiteKind> = {
店铺: 'shop',
商品: 'product',
SKU: 'sku',
};
/** 行内引用:@[店铺#123·名称](每次新建,避免 /g lastIndex 串扰) */
function inlineCitePattern() {
return /@\[(店铺|商品|SKU)#(\d+)·([^\]]*)\]/g;
}
/** 草稿分段:纯文本 / 已选引用(供 contenteditable 渲染标签) */
export type DraftSegment =
| { type: 'text'; value: string }
| { type: 'cite'; key: string };
export function parseDraftSegments(text: string): DraftSegment[] {
const segments: DraftSegment[] = [];
let last = 0;
for (const m of text.matchAll(inlineCitePattern())) {
if (m.index == null) continue;
if (m.index > last) {
segments.push({ type: 'text', value: text.slice(last, m.index) });
}
const label = m[1];
const id = Number(m[2]);
const kind = label ? LABEL_KIND[label] : undefined;
if (kind && Number.isFinite(id)) {
segments.push({ type: 'cite', key: `${kind}:${id}` });
} else {
segments.push({ type: 'text', value: m[0] });
}
last = m.index + m[0].length;
}
if (last < text.length) {
segments.push({ type: 'text', value: text.slice(last) });
}
if (segments.length === 0) {
segments.push({ type: 'text', value: '' });
}
return segments;
}
export function catalogCiteLabel(kind: CatalogCiteKind) {
return KIND_LABEL[kind];
}
/** 输入框末尾的 @ 查询;没有则 null。空字符串表示刚输入 @。 */
export function trailingMentionQuery(text: string): null | string {
const matched = text.match(/(^|\s)@([^\s@]*)$/);
return matched ? matched[2] ?? '' : null;
/** 在光标前查找未完成的 @查询(支持正文任意位置)。 */
export function mentionQueryAt(
text: string,
cursor: number,
): MentionHit | null {
const pos = Math.max(0, Math.min(cursor, text.length));
const before = text.slice(0, pos);
const matched = before.match(/(^|[\s\n])@([^\s@\[]*)$/);
if (!matched) return null;
const index = matched.index;
if (index == null) return null;
const prefix = matched[1] ?? '';
return {
start: index + prefix.length,
end: pos,
query: matched[2] ?? '',
};
}
/** 发送前去掉还没选中的 @查询。 */
/** @deprecated 兼容旧调用:等价于光标在末尾 */
export function trailingMentionQuery(text: string): null | string {
return mentionQueryAt(text, text.length)?.query ?? null;
}
/** 发送前去掉仍未选中的残缺 @查询(末尾)。 */
export function stripTrailingMention(text: string) {
return text.replace(/(^|\s)@[^\s@]*$/, '$1').replace(/\s+$/, '');
return text.replace(/(^|[\s\n])@[^\s@\[]*$/u, '$1').replace(/\s+$/u, '');
}
/** 输入框内展示用标记(嵌 id,发送时按位置展开)。 */
export function formatInlineCite(cite: CatalogCite): string {
const raw = cite.title.trim() || String(cite.id);
const title = raw.length > 24 ? `${raw.slice(0, 23)}…` : raw;
return `@[${KIND_LABEL[cite.kind]}#${cite.id}·${title}]`;
}
export function toShopCite(shop: {
@@ -85,12 +160,125 @@ export function toSkuCite(sku: {
};
}
/** 正文后面附上引用 id。标签只在输入框里显示,不占一行正文。 */
/**
* 按正文中的行内标记位置展开引用;标记不在文中的 cite 仍附在末尾 [引用] 块(兼容旧数据)。
*/
export function composeMessageWithCites(text: string, cites: CatalogCite[]) {
const body = text.trim();
if (cites.length === 0) return body;
const block = ['[引用]', ...cites.map((item) => item.line)].join('\n');
return body ? `${body}\n${block}` : block;
const body = stripTrailingMention(text);
if (!body && cites.length === 0) return '';
const used = new Set<string>();
const expanded = body.replace(
inlineCitePattern(),
(_raw, label: string, idStr: string) => {
const kind = LABEL_KIND[label];
const id = Number(idStr);
if (!kind || !Number.isFinite(id)) return _raw;
const hit =
cites.find((c) => c.kind === kind && c.id === id) ||
cites.find((c) => c.key === `${kind}:${id}`);
if (!hit) return _raw;
used.add(hit.key);
return hit.line;
},
);
const orphans = cites.filter((c) => !used.has(c.key));
if (orphans.length === 0) return expanded.trim();
const block = ['[引用]', ...orphans.map((item) => item.line)].join('\n');
const trimmed = expanded.trim();
return trimmed ? `${trimmed}\n${block}` : block;
}
/** 消息气泡展示用分段(token / 展开后的 line 都能识别) */
export type MessageCiteSegment =
| { type: 'text'; value: string }
| { type: 'cite'; kind: CatalogCiteKind; id?: number; title: string };
/**
* 把消息正文拆成文本 + 引用标签。
* 支持 `@[店铺#1·名]` 与 `店铺「名」 id=1 平台=…` 两种形态。
*/
export function parseMessageCiteSegments(text: string): MessageCiteSegment[] {
const source = text.replace(/^\s*\[引用\]\s*/m, '');
if (!source) return [{ type: 'text', value: '' }];
// token 或已展开 line;attrs 吃掉 key=value,直到下一个引用
const re =
/@\[(店铺|商品|SKU)#(\d+)·([^\]]*)\]|(店铺|商品|SKU)「([^」]*)」\s+id=(\d+)((?:\s+[^\s「=]+=\S+)*)/g;
const segments: MessageCiteSegment[] = [];
let last = 0;
for (const m of source.matchAll(re)) {
if (m.index == null) continue;
if (m.index > last) {
segments.push({ type: 'text', value: source.slice(last, m.index) });
}
if (m[1]) {
const kind = LABEL_KIND[m[1]];
if (kind) {
segments.push({
type: 'cite',
kind,
id: Number(m[2]),
title: (m[3] || '').trim() || String(m[2]),
});
} else {
segments.push({ type: 'text', value: m[0] });
}
} else {
const kind = LABEL_KIND[m[4] || ''];
if (kind) {
segments.push({
type: 'cite',
kind,
id: Number(m[6]),
title: (m[5] || '').trim() || String(m[6]),
});
} else {
segments.push({ type: 'text', value: m[0] });
}
}
last = m.index + m[0].length;
}
if (last < source.length) {
segments.push({ type: 'text', value: source.slice(last) });
}
return segments.length > 0 ? segments : [{ type: 'text', value: source }];
}
/** 正文里仍存在的引用 key(用于删字后同步 cites)。 */
export function inlineCiteKeysInText(text: string): Set<string> {
const keys = new Set<string>();
for (const m of text.matchAll(inlineCitePattern())) {
const label = m[1];
const id = Number(m[2]);
const kind = label ? LABEL_KIND[label] : undefined;
if (kind && Number.isFinite(id)) keys.add(`${kind}:${id}`);
}
return keys;
}
/**
* 光标落在某个行内引用上(含紧挨标记末尾)时返回其区间,便于 ⌫ 整段删除。
*/
export function inlineCiteRangeAt(
text: string,
cursor: number,
): { start: number; end: number; key: string } | null {
for (const m of text.matchAll(inlineCitePattern())) {
if (m.index == null) continue;
const start = m.index;
const end = start + m[0].length;
if (cursor > start && cursor <= end) {
const label = m[1];
const id = Number(m[2]);
const kind = label ? LABEL_KIND[label] : undefined;
if (!kind || !Number.isFinite(id)) continue;
return { start, end, key: `${kind}:${id}` };
}
}
return null;
}
function joinLine(kind: string, title: string, id: number, extra: string) {
@@ -1,16 +1,37 @@
<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 { PlusOutlined } from '@ant-design/icons-vue';
import { EllipsisText, Page } from '@vben/common-ui';
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 { ChatItem } from '@tdesign-vue-next/chat';
import type { MenuProps } from 'ant-design-vue';
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/chat/es/style/index.css';
import {
createAgentSessionApi,
deleteAgentSessionApi,
listAgentEnabledLlmModelsApi,
listAgentMessagesApi,
listAgentSessionsApi,
@@ -20,6 +41,8 @@ import {
} from '#/api/agent';
import CatalogCiteSender from './catalog-cite-sender.vue';
import CatalogCiteRichText from './catalog-cite-rich-text.vue';
import SessionSearchModal from './session-search-modal.vue';
import {
composeMessageWithCites,
stripTrailingMention,
@@ -28,14 +51,43 @@ import {
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 = [
'近7天的销售额、单量、净利和费比分别是多少',
'昨天的经营情况怎么样',
'本周销售额和净利帮我汇总一下',
'近30天单量和费比有什么变化',
{
label: '近7天经营概览',
prompt: '近7天的销售额、单量、净利和费比分别是多少',
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 丢正文) */
type BubbleView = {
id: string;
@@ -52,6 +104,14 @@ const sessions = ref<AgentVO.Session[]>([]);
const activeThreadId = ref<string | null>(null);
/** 点了「新对话」但还没发出第一条消息,此时不请求后端 */
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[]>([]);
/** 当前流式助手正文(与 messages 末条同步) */
const streamingText = ref('');
@@ -110,7 +170,7 @@ const showMessageLoading = computed(
() => loadingMessages.value && !sending.value && messages.value.length === 0,
);
/** 新对话草稿,或还没有任何会话时,展示能力引导 */
/** 新对话草稿,或还没有任何会话时,展示居中空态 */
const showStarter = computed(
() =>
messages.value.length === 0 &&
@@ -119,6 +179,86 @@ const showStarter = computed(
(!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[]>(() =>
messages.value.map((m, idx) => {
const isStreamingAssistant =
@@ -210,6 +350,71 @@ function onSessionClick(threadId: string) {
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() {
loadingSessions.value = true;
try {
@@ -469,182 +674,502 @@ void loadEnabledModels().then(() => refreshSessions());
<template>
<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
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">
<Button type="primary" block @click="beginNewChat">
<template #icon><PlusOutlined /></template>
新对话
</Button>
<div
v-if="!siderCollapsed"
class="flex h-12 shrink-0 items-center gap-1 px-3"
>
<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 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"
<div
v-else
class="flex min-h-0 flex-1 flex-col items-center gap-1 px-1.5 pt-0 pb-3"
>
<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" />
</div>
<Empty
v-if="!loadingSessions && sessions.length === 0 && !composingNew"
class="mt-10 px-2"
description="暂无会话"
/>
<div v-else class="h-full space-y-1 overflow-y-auto px-3 py-2">
<button
v-if="composingNew"
type="button"
class="bg-primary/10 text-primary mb-1 w-full rounded-lg px-3 py-2 text-left text-sm"
>
<div class="truncate font-medium">新对话</div>
<div class="text-muted-foreground mt-0.5 truncate text-xs">
尚未发送
<template #content>
<div class="agent-sider-pop flex w-64 flex-col p-2">
<div class="text-muted-foreground px-1 pb-2 text-xs font-medium">
最近聊天
</div>
<div class="max-h-72 overflow-y-auto">
<Empty
v-if="recentSessions.length === 0"
class="py-6"
description="暂无会话"
:image="Empty.PRESENTED_IMAGE_SIMPLE"
/>
<button
v-for="s in recentSessions"
: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>
</button>
<button
v-for="s in sessions"
:key="s.threadId"
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)"
</template>
<Tooltip
:title="collapsedRecentOpen ? '' : '最近聊天'"
placement="right"
>
<div class="truncate font-medium">{{ s.title || '新对话' }}</div>
<div
v-if="s.updatedAt || s.lastMessageAt"
class="text-muted-foreground mt-0.5 truncate text-xs"
<button
type="button"
class="hover:bg-muted text-muted-foreground hover:text-foreground flex size-10 items-center justify-center rounded-lg transition-colors"
:class="collapsedRecentOpen ? 'bg-muted text-foreground' : ''"
aria-label="最近聊天"
>
{{ s.updatedAt || s.lastMessageAt }}
</div>
<RecentChatIcon class="size-5" />
</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>
</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>
<section class="agent-chat-main flex min-h-0 min-w-0 flex-1 flex-col">
<header
class="flex h-12 shrink-0 items-center gap-3 border-b border-border px-4"
<!-- 主区:空态居中 / 对话时消息 + 底栏输入 -->
<section class="agent-main relative flex min-h-0 min-w-0 flex-1 flex-col">
<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">
{{
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>
<div class="relative flex min-h-0 flex-1 flex-col">
<div
v-if="showMessageLoading"
class="text-muted-foreground absolute inset-0 z-10 flex items-center justify-center bg-background/60 text-sm"
>
加载消息…
</div>
<Empty
v-if="!showStarter && !showMessageLoading && messages.length === 0"
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">
<!-- 空态:问候 + 居中输入 + chips -->
<div
v-if="showStarter"
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">
{{ greeting }}
</h1>
<div class="agent-composer w-full 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 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>
<!-- 对话态:可滚动消息 + 底部输入 -->
<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 || item.role === 'user'
? undefined
: item.content
"
:text-loading="false"
variant="base"
>
<!-- ChatItem.animation 无 dots,等待首包时用 ChatLoading -->
<template v-if="item.textLoading" #content>
<ChatLoading animation="dots" />
</template>
<template v-else-if="item.role === 'user'" #content>
<CatalogCiteRichText :text="item.content" />
</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>
</div>
<SessionSearchModal
ref="sessionSearchModalRef"
:sessions="sessions"
:active-thread-id="activeThreadId"
@pick="pickSessionFromOverlay"
/>
</Page>
</template>
<style scoped>
.agent-td-chat {
--td-bg-color-container: transparent;
padding-inline: 28px;
/* 浅色:侧栏略深于主区;深色沿用 background-deep */
.agent-sider {
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 {
margin-bottom: 12px;
}
/* 气泡按内容收缩,左右再留一截,避免贴边铺满 */
.agent-td-item :deep(.t-chat__inner) {
/* ChatItem 根节点即 .t-chat__inner,样式打在本类上 */
display: flex;
box-sizing: border-box;
padding-inline: 4px;
width: 100%;
margin-bottom: 16px;
padding-inline: 20px;
}
.agent-td-item :deep(.t-chat__content) {
width: auto;
max-width: min(720px, calc(100% - 32px));
flex: 0 1 auto !important;
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;
}
.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>
@@ -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>
@@ -10,6 +10,7 @@ import {
FormItem,
Input,
InputPassword,
Select,
message,
} from 'ant-design-vue';
@@ -28,8 +29,18 @@ const form = ref({
baseUrl: '',
apiKey: '',
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 modalTitle = computed(() =>
isEdit.value ? '编辑提供商' : '添加提供商',
@@ -52,7 +63,8 @@ function open(row?: AgentVO.LlmProvider) {
baseUrl: row?.baseUrl || '',
apiKey: '',
displayName: row?.displayName || '',
};
apiStyle: row?.apiStyle || 'auto',
};
modalApi.setState({ title: modalTitle.value });
modalApi.open();
}
@@ -74,6 +86,7 @@ async function handleSubmit() {
baseUrl: form.value.baseUrl.trim(),
apiKey: form.value.apiKey.trim() || undefined,
displayName: form.value.displayName.trim(),
apiStyle: form.value.apiStyle,
});
message.success('已保存');
} else {
@@ -81,6 +94,7 @@ async function handleSubmit() {
baseUrl: form.value.baseUrl.trim(),
apiKey: form.value.apiKey.trim(),
displayName: form.value.displayName.trim() || undefined,
apiStyle: form.value.apiStyle,
});
message.success('已创建');
}
@@ -116,6 +130,13 @@ defineExpose({ open });
>
<InputPassword v-model:value="form.apiKey" placeholder="sk-..." />
</FormItem>
<FormItem label="API 协议">
<Select
v-model:value="form.apiStyle"
:options="apiStyleOptions"
class="w-full"
/>
</FormItem>
<FormItem label="备注(可选)">
<Input v-model:value="form.displayName" placeholder="如 DeepSeek" />
</FormItem>
@@ -65,6 +65,19 @@ const baseColumns: VxeGridProps<ProviderRow>['columns'] = [
minWidth: 220,
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',
title: 'API Key',
@@ -1,10 +1,16 @@
<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 {
deleteAgentMemoryApi,
listAgentMemoriesApi,
@@ -13,79 +19,193 @@ import {
defineOptions({ name: 'AgentMemories' });
const loading = ref(true);
const memories = ref<AgentVO.Memory[]>([]);
const loading = ref(false);
async function loadMemories() {
loading.value = true;
try {
const res = await listAgentMemoriesApi();
memories.value = res.items || [];
} catch (e: any) {
message.error(e?.message || '加载记忆失败');
} finally {
loading.value = false;
}
const KIND_META: Record<string, { color: string; label: string }> = {
note: { color: 'blue', label: '笔记' },
preference: { color: 'purple', label: '偏好' },
fact: { color: 'green', label: '事实' },
};
function kindMeta(kind?: string) {
const k = (kind || 'note').trim() || 'note';
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 {
await deleteAgentMemoryApi(id);
memories.value = memories.value.filter((m) => m.id !== id);
message.success('已删除记忆');
await deleteAgentMemoryApi(row.id);
message.success('已删除');
await gridApi.reload();
} catch (e: any) {
message.error(e?.message || '删除失败');
}
}
onMounted(() => {
void loadMemories();
});
function clearAll() {
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>
<template>
<Page auto-content-height>
<div class="relative mx-auto max-w-3xl pb-8">
<div
v-if="loading"
class="absolute inset-0 z-10 flex items-center justify-center bg-background/50"
>
<Spin />
</div>
<Page
auto-content-height
title="助手记忆"
description="智能助手跨会话保存的称呼、偏好与事实,按需检索,不会默认整包注入对话。"
>
<Alert
type="info"
show-icon
class="mb-4"
message="在智能助手里发送「记住:……」即可写入;不需要的条目可随时删除。"
/>
<Card title="我的记忆" :bordered="false">
<p class="text-muted-foreground mb-4 text-sm">
在智能助手对话中发送「记住:…」可写入;助手按需检索,不会默认注入全部记忆。
</p>
<Empty
v-if="!loading && memories.length === 0"
description="暂无记忆"
/>
<div
v-for="m in memories"
:key="m.id"
class="mb-2 flex items-start gap-2 rounded-md bg-muted/50 px-3 py-2 text-sm"
<Grid :loading="loading">
<template #toolbar-tools>
<Space>
<Button danger @click="clearAll">清空全部</Button>
</Space>
</template>
<template #kind="{ row }">
<Tag :color="kindMeta(row.kind).color">
{{ kindMeta(row.kind).label }}
</Tag>
</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">
<div class="break-words">{{ m.summary || m.text }}</div>
<div
v-if="m.summary && m.text && m.summary !== m.text"
class="text-muted-foreground mt-1 break-words text-xs"
>
{{ m.text }}
</div>
<div
v-if="m.updatedAt"
class="text-muted-foreground mt-1 text-xs"
>
{{ m.updatedAt }}
</div>
</div>
<Button type="link" size="small" danger @click="removeMemory(m.id)">
删除
</Button>
</div>
</Card>
</div>
{{ row.text }}
</EllipsisText>
<span v-else class="text-muted-foreground">—</span>
</template>
<template #action="{ row }">
<Popconfirm
title="确定删除这条记忆?"
ok-text="删除"
cancel-text="取消"
ok-type="danger"
@confirm="removeMemory(row)"
>
<Button type="link" size="small" danger>删除</Button>
</Popconfirm>
</template>
</Grid>
</Page>
</template>
@@ -1,16 +1,13 @@
<script lang="ts" setup>
/**
* 拼多多发布页右侧智能体栏:一草稿一会话,执行 client_tool 改表单。
* UI 对齐通用智能助手(气泡、加载、底栏输入与模型选择)。
*/
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import {
MenuFoldOutlined,
MenuUnfoldOutlined,
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 { createIconifyIcon } from '@vben/icons';
import { Empty, 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/chat/es/style/index.css';
@@ -22,13 +19,25 @@ import {
streamAgentChat,
type AgentVO,
} from '#/api/agent';
import CatalogCiteSender from '#/views/agent/chat/catalog-cite-sender.vue';
import CatalogCiteRichText from '#/views/agent/chat/catalog-cite-rich-text.vue';
import {
composeMessageWithCites,
stripTrailingMention,
type CatalogCite,
} from '#/views/agent/chat/catalog-cite';
import type { PublishEditorAgentApi } from './commands';
defineOptions({ name: 'PddPublishAgentPanel' });
const AgentBrandIcon = createIconifyIcon('lucide:bot');
const PanelCloseIcon = createIconifyIcon('lucide:panel-left-close');
const PanelOpenIcon = createIconifyIcon('lucide:panel-left');
const props = defineProps<{
draftId: number;
/** 系统草稿 ID;null 表示尚未落库的新建编辑 */
draftId: number | null;
collapsed?: boolean;
/** 编辑器命令面(ref) */
editorApi: PublishEditorAgentApi | null;
@@ -41,10 +50,38 @@ const emit = defineEmits<{
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 = [
'根据已填的 SKU 商家编码,找相似拼多多商品并生成标题',
'参考渠道商品帮我整理规格轴',
'把当前标题改得更适合拼多多搜索',
{
label: '按编码生成标题',
prompt: '根据已填的 SKU 商家编码,找相似拼多多商品并生成标题',
},
{
label: '整理规格轴',
prompt: '参考渠道商品帮我整理规格轴',
},
{
label: '优化标题',
prompt: '把当前标题改得更适合拼多多搜索',
},
];
type BubbleView = {
@@ -64,6 +101,7 @@ const streamingText = ref('');
const toolStatusLabel = ref('');
const toolStatusActive = ref(false);
const draft = ref('');
const citations = ref<CatalogCite[]>([]);
const enabledModels = ref<AgentVO.LlmModelItem[]>([]);
const selectedModelKey = ref<string | undefined>(undefined);
const patchingModel = ref(false);
@@ -111,6 +149,12 @@ const showStarter = computed(
!loadingSession.value,
);
const showMessageLoading = computed(
() =>
(loadingSession.value || loadingMessages.value) &&
messages.value.length === 0,
);
const bubbleViews = computed<BubbleView[]>(() =>
messages.value.map((m, idx) => {
const isStreamingAssistant =
@@ -148,6 +192,11 @@ function syncSelectedFromSession() {
}
}
function clearToolStatus() {
toolStatusActive.value = false;
toolStatusLabel.value = '';
}
/** 滚到消息区底部;多拍几次等 ChatItem 异步撑高后再定住 */
function scrollChatToBottom() {
const run = () => {
@@ -194,11 +243,11 @@ async function ensureSession(): Promise<string | null> {
if (session.value?.threadId) return session.value.threadId;
const parsed = parseModelKey(selectedModelKey.value);
const s = await createAgentSessionApi({
title: `发布草稿 #${props.draftId}`,
title: sessionTitle.value,
llmProviderId: parsed?.providerId,
llmModel: parsed?.model,
scene: SCENE,
sceneRef: String(props.draftId),
sceneRef: sceneRef.value,
reuseBySceneRef: true,
});
session.value = s;
@@ -232,6 +281,8 @@ async function bootstrap() {
loadingSession.value = true;
messages.value = [];
session.value = null;
draft.value = '';
citations.value = [];
try {
await loadEnabledModels();
const threadId = await ensureSession();
@@ -245,7 +296,11 @@ async function bootstrap() {
watch(
() => props.draftId,
() => {
(id, prev) => {
// 新建落库后仅 URL 从 new→id:沿用当前会话,避免打断
if (prev == null && id != null && id > 0 && session.value?.threadId) {
return;
}
abort?.abort();
void bootstrap();
},
@@ -275,8 +330,7 @@ async function onModelChange(key: string) {
function appendStreamToken(t: string) {
if (toolStatusActive.value) {
toolStatusActive.value = false;
toolStatusLabel.value = '';
clearToolStatus();
}
streamingText.value += t;
const idx = messages.value.length - 1;
@@ -293,9 +347,7 @@ function onStreamTool(payload: { phase: string; label: string }) {
toolStatusLabel.value = payload.label;
void nextTick().then(scrollChatToBottom);
} else if (payload.phase === 'end') {
// 结束后清状态,避免卡在「读取发布表单…」直到下一段 token
toolStatusActive.value = false;
toolStatusLabel.value = '';
clearToolStatus();
}
}
@@ -312,8 +364,12 @@ async function onClientTool(call: AgentVO.ClientToolCall) {
}
}
async function send(textOverride?: string) {
const text = (textOverride ?? draft.value).trim();
async function send(rawOverride?: string) {
const raw = (rawOverride ?? draft.value).trim();
const text = composeMessageWithCites(
stripTrailingMention(raw),
citations.value,
);
if (!text || sending.value) return;
sending.value = true;
@@ -333,9 +389,9 @@ async function send(textOverride?: string) {
}
streamingText.value = '';
toolStatusActive.value = false;
toolStatusLabel.value = '';
clearToolStatus();
draft.value = '';
citations.value = [];
messages.value.push({
seq: (messages.value.at(-1)?.seq || 0) + 1,
role: 'user',
@@ -376,8 +432,7 @@ async function send(textOverride?: string) {
}
sending.value = false;
streamingText.value = '';
toolStatusActive.value = false;
toolStatusLabel.value = '';
clearToolStatus();
},
onError: (msg) => {
sending.value = false;
@@ -387,40 +442,48 @@ async function send(textOverride?: string) {
messages.value[idx] = { ...last, content: `错误:${msg}` };
}
streamingText.value = '';
toolStatusActive.value = false;
toolStatusLabel.value = '';
clearToolStatus();
message.error(msg);
},
});
}
function onSenderSend(value: string) {
void send(value);
}
function applyStarterPrompt(text: string) {
draft.value = text;
}
function onStop() {
function onSenderStop() {
abort?.abort();
sending.value = false;
toolStatusActive.value = false;
toolStatusLabel.value = '';
clearToolStatus();
}
onBeforeUnmount(() => abort?.abort());
</script>
<template>
<!-- 收起:窄条 -->
<!-- 收起:窄条(悬停 bot→展开图标,对齐智能助手) -->
<div
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">
<Button type="text" @click="emit('expand')">
<template #icon><MenuUnfoldOutlined /></template>
</Button>
<button
type="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>
<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"
>
发布助手
@@ -430,150 +493,270 @@ onBeforeUnmount(() => abort?.abort());
<!-- 展开 -->
<aside
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
class="flex h-12 shrink-0 items-center gap-2 border-b border-border px-3"
>
<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 ?? ''))"
/>
<header class="flex h-12 shrink-0 items-center gap-1 px-3">
<div class="min-w-0 flex-1 truncate text-sm font-semibold">发布助手</div>
<Tooltip title="收起">
<Button type="text" size="small" @click="emit('collapse')">
<template #icon><MenuFoldOutlined /></template>
</Button>
<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="emit('collapse')"
>
<PanelCloseIcon class="size-5" />
</button>
</Tooltip>
</header>
<div class="relative flex min-h-0 flex-1 flex-col">
<section class="relative flex min-h-0 flex-1 flex-col">
<div
v-if="loadingSession || loadingMessages"
class="absolute inset-0 z-10 flex items-center justify-center bg-background/50"
v-if="showMessageLoading"
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>
<!-- 空态:说明 + 居中输入 + chips -->
<div
ref="messagePaneRef"
class="publish-agent-chat t-chat t-chat--normal min-h-0 flex-1 overflow-y-auto py-3"
v-if="showStarter"
class="flex min-h-0 flex-1 flex-col justify-center px-3 pb-6 pt-4"
>
<div
v-if="showStarter"
class="flex h-full flex-col justify-center px-1 py-4"
>
<div class="text-sm font-medium">帮你完善本页草稿</div>
<p class="text-muted-foreground mt-2 text-xs leading-5">
可按已填 SKU 编码查内部/拼多多商品,生成标题并写回规格轴。改表单会直接落到左侧编辑区。
<div class="mb-5 px-1">
<div class="text-base font-semibold tracking-tight">
帮你完善本页草稿
</div>
<p class="text-muted-foreground mt-1.5 text-xs leading-5">
可按已填 SKU 编码查商品、生成标题并写回规格轴;改表单会落到左侧编辑区。
</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>
<Empty
v-else-if="!loadingSession && !loadingMessages && messages.length === 0"
class="mt-16"
description="开始提问吧"
/>
<ChatItem
v-for="item in bubbleViews"
:key="item.id"
class="publish-agent-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 flex items-center gap-2 px-1 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 class="publish-agent-composer w-full">
<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 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 class="shrink-0 border-t border-border p-2">
<div class="flex gap-1.5">
<Input.TextArea
v-model:value="draft"
:auto-size="{ minRows: 2, maxRows: 5 }"
:disabled="sending"
placeholder="描述你想改的标题、规格…"
class="flex-1"
@keydown.enter.exact.prevent="() => send()"
<!-- 对话态 -->
<template v-else>
<div
ref="messagePaneRef"
class="publish-agent-chat t-chat t-chat--normal min-h-0 flex-1 overflow-y-auto px-3 pb-3 pt-4"
>
<Empty
v-if="!showMessageLoading && messages.length === 0"
class="mt-16"
description="开始提问吧"
/>
<div class="flex flex-col gap-1">
<Button
v-if="sending"
type="default"
size="small"
@click="onStop"
>
停止
</Button>
<Button
v-else
type="primary"
size="small"
:disabled="!draft.trim()"
@click="() => send()"
>
<template #icon><SendOutlined /></template>
</Button>
<ChatItem
v-for="item in bubbleViews"
:key="item.id"
class="publish-agent-item"
:class="[
item.role === 'user'
? 'publish-agent-item--user'
: 'publish-agent-item--assistant',
{ 'publish-agent-item--loading': item.textLoading },
]"
:role="item.role"
:name="item.name"
:content="
item.textLoading || item.role === 'user'
? undefined
: item.content
"
:text-loading="false"
variant="base"
>
<template v-if="item.textLoading" #content>
<ChatLoading animation="dots" />
</template>
<template v-else-if="item.role === 'user'" #content>
<CatalogCiteRichText :text="item.content" />
</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 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>
</template>
<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-*,容器左右留白写这里。
* 不要动 `.t-chat__detail` 的 padding,那是气泡内文字边距。
* ChatItem 根节点就是 .t-chat__inner,padding / justify 必须打在本类上。
*/
.publish-agent-chat.t-chat {
--td-bg-color-container: transparent;
padding: 12px 16px !important;
box-sizing: border-box;
}
.publish-agent-item {
margin-bottom: 10px;
}
.publish-agent-item :deep(.t-chat__inner) {
display: flex;
box-sizing: border-box;
padding-inline: 4px;
width: 100%;
margin-bottom: 12px;
padding-inline: 12px;
}
.publish-agent-item :deep(.t-chat__content) {
width: auto;
max-width: calc(100% - 8px);
flex: 0 1 auto !important;
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;
}
.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__name) {
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>
@@ -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() {
draft.submitting.value = false;
Object.assign(form, createEmptyPublishForm());
@@ -390,7 +408,7 @@ function onSkuTableWrapRef(el: HTMLElement | null) {
<Teleport defer to="#pdd-publish-edit-header-fields">
<div class="w-full min-w-0 space-y-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">
渠道店铺 <span class="text-destructive">*</span>
</div>
@@ -405,7 +423,7 @@ function onSkuTableWrapRef(el: HTMLElement | null) {
@search="(kw: string) => loadShops(kw)"
/>
</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">
<span>
叶子类目 <span class="text-destructive">*</span>
@@ -436,10 +454,12 @@ function onSkuTableWrapRef(el: HTMLElement | null) {
/>
</Tooltip>
</div>
<!-- Cascader 默认不吃满格子,需显式 100% 与店铺 Select 对齐 -->
<Cascader
v-model:value="form.catPath"
v-model:search-value="catCascaderSearch"
class="w-full"
:style="{ width: '100%' }"
:options="displayCatOptions"
:load-data="catLoadData"
:show-search="{
@@ -640,9 +660,10 @@ function onSkuTableWrapRef(el: HTMLElement | null) {
v-model:value="form.twoPiecesDiscount"
class="w-full"
:min="0"
:max="100"
:precision="0"
placeholder="95 表示 95 折,0 取消"
:max="10"
:precision="1"
:step="0.1"
placeholder="9.5 表示 9.5 折,0 取消"
/>
</Form.Item>
</div>
@@ -18,12 +18,14 @@ import {
updatePddPublishDeskDraftApi,
} from '#/api/channel/pdd/goods';
import type {
PersistedUpload,
PublishFormFields,
SpecAxis,
SpecCatalogItem,
SkuRow,
import {
twoPiecesDiscountFromStored,
twoPiecesDiscountToApi,
type PersistedUpload,
type PublishFormFields,
type SpecAxis,
type SpecCatalogItem,
type SkuRow,
} from '../types';
type EmitDraft = {
@@ -185,9 +187,9 @@ export function usePublishDraft(options: {
if (
form.twoPiecesDiscount == null ||
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;
}
for (const p of nonSaleProps.value) {
@@ -362,7 +364,7 @@ export function usePublishDraft(options: {
isPreSale: form.isPreSale,
isRefundable: form.isRefundable,
secondHand: form.secondHand,
twoPiecesDiscount: form.twoPiecesDiscount,
twoPiecesDiscount: twoPiecesDiscountToApi(form.twoPiecesDiscount),
carouselImages: carouselFileIds.map(String),
detailImages: detailFileIds.map(String),
goodsProperties,
@@ -459,7 +461,7 @@ export function usePublishDraft(options: {
}
if (typeof es.secondHand === 'boolean') form.secondHand = es.secondHand;
if (typeof es.twoPiecesDiscount === 'number') {
form.twoPiecesDiscount = es.twoPiecesDiscount;
form.twoPiecesDiscount = twoPiecesDiscountFromStored(es.twoPiecesDiscount);
}
if (
es.goodsPropValues &&
@@ -777,8 +779,12 @@ export function usePublishDraft(options: {
async function handleSubmit() {
if (!validateForm()) return;
submitting.value = true;
const hide = message.loading('正在上传图片并发布…', 0);
const hide = message.loading('正在保存并发布…', 0);
try {
// 先落/更新系统草稿(含 publishPayload),再发布以便回写 goods_commit_id / goods_id
const saved = await saveDeskDraft(true, { silentSuccess: true });
if (!saved?.id) return;
const pendingThumbs = skuRows.value
.map((row) => ({ rowKey: row.key, file: row.thumbFileList[0] }))
.filter((x): x is { rowKey: number; file: UploadFile } => !!x.file);
@@ -797,8 +803,8 @@ export function usePublishDraft(options: {
const thumbPersisted = persistedAll.slice(p);
const thumbFileIdBySkuKey = new Map<number, number>();
pendingThumbs.forEach((item, i) => {
const saved = thumbPersisted[i];
if (saved) thumbFileIdBySkuKey.set(item.rowKey, saved.fileId);
const savedThumb = thumbPersisted[i];
if (savedThumb) thumbFileIdBySkuKey.set(item.rowKey, savedThumb.fileId);
});
const payload = await buildPublishPayload(
@@ -806,17 +812,13 @@ export function usePublishDraft(options: {
detailFileIds,
thumbFileIdBySkuKey,
);
// 确保有系统草稿并回传 ID,发布结果才能写入 goods_commit_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;
}
}
payload.systemDraftId = saved.id;
const res = await publishPddGoodsApi(payload);
message.success(`发布成功,goodsId=${res.goodsId}`);
message.success(
res.goodsId != null
? `发布成功,goodsId=${res.goodsId}`
: '发布成功',
);
emit('success');
closeEditor();
} catch (e: any) {
@@ -2,6 +2,7 @@
/**
* 发布编辑页路由入口(editor/index):Page 布局 + 左侧表单 + 右侧 Agent。
* 表单实现见同目录 PddPublishEditor;智能体见 ../agent。
* draftId=new 表示尚未落库的空编辑;保存/推送/发布时再创建系统草稿。
*/
import { computed, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
@@ -19,10 +20,20 @@ defineOptions({ name: 'PddGoodsPublishDeskEdit' });
const route = useRoute();
const router = useRouter();
/** 数字 ID;new / 非法 → null(尚未创建系统草稿) */
const draftId = computed(() => {
const raw = route.params.draftId;
const n = Number(Array.isArray(raw) ? raw[0] : raw);
return Number.isFinite(n) ? n : null;
const s = String(Array.isArray(raw) ? raw[0] : raw ?? '');
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);
@@ -47,6 +58,15 @@ const agentPaneStyle = computed(() => {
function goBack() {
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>
<template>
@@ -60,33 +80,22 @@ function goBack() {
>
<template #title>
<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:店铺 / 类目 -->
<div id="pdd-publish-edit-header-fields" class="w-full min-w-0"></div>
</div>
</template>
<div
v-if="draftId"
class="flex min-h-0 flex-1 overflow-hidden"
>
<div class="flex min-h-0 flex-1 overflow-hidden">
<div class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
<PddPublishEditor
ref="editorRef"
class="h-full min-h-0"
:open="true"
:draft-id="draftId"
:preset-pdd-shop-id="presetPddShopId"
@close="goBack"
@success="goBack"
@draft-saved="() => undefined"
@draft-saved="onDraftSaved"
/>
</div>
<div
@@ -101,10 +101,23 @@ export type PublishFormFields = {
isPreSale: boolean;
isRefundable: boolean;
secondHand: boolean;
/** 表单展示用折扣:0–10,9.5=9.5折;提交接口时 *10 */
twoPiecesDiscount: number;
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 {
return {
@@ -117,11 +130,11 @@ export function createEmptyPublishForm(): PublishFormFields {
costTemplateId: undefined,
marketPriceYuan: undefined,
shipmentLimitSecond: 172800,
isFolt: true,
isFolt: false,
isPreSale: false,
isRefundable: true,
secondHand: false,
twoPiecesDiscount: 95,
twoPiecesDiscount: 9.5,
goodsPropValues: {},
};
}
@@ -23,7 +23,6 @@ import {
import {
clonePddPublishDeskDraftApi,
createPddPublishDeskDraftApi,
createPddPublishDeskJobApi,
deletePddPublishDeskDraftApi,
getPddPublishDeskJobApi,
@@ -315,18 +314,15 @@ function selectUnassigned() {
}
async function createDraft() {
try {
const draft = await createPddPublishDeskDraftApi({
title: '未命名草稿',
pddShopId: selectedShopId.value,
status: 'EDITING',
skuCount: 0,
});
message.success('已创建系统草稿');
await router.push(`/pdd/goods/publish/editor/${draft.id}`);
} catch (e: any) {
message.error(e?.message || '创建失败');
}
const query =
selectedShopId.value != null && selectedShopId.value > 0
? { shopId: String(selectedShopId.value) }
: undefined;
// 先进空编辑页,用户保存/推送/发布时再落系统草稿
await router.push({
path: '/pdd/goods/publish/editor/new',
query,
});
}
function openEdit(id: number) {
@@ -1,279 +1,87 @@
<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 { useRouter } from 'vue-router';
import { computed, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
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 { FileCategory } from '#/constants/file-category';
import { uploadFile } from '#/utils/upload-file';
import ChangePasswordCard from './modules/ChangePasswordCard.vue';
import ProfileInfoCard from './modules/ProfileInfoCard.vue';
defineOptions({ name: 'PersonalProfile' });
defineOptions({ name: 'PersonalCenter' });
type TabKey = 'password' | 'profile';
const route = useRoute();
const router = useRouter();
const loading = ref(false);
const submitting = ref(false);
const userInfo = ref<UserVO.UserInfoVO | null>(null);
const avatarLoading = ref(false);
const ProfileIcon = createIconifyIcon('lucide:user');
const LockIcon = createIconifyIcon('lucide:lock');
// 待上传的头像文件(用户选择后先缓存,保存时再上传)
const pendingAvatarFile = ref<File | null>(null);
const activeTab = ref<TabKey>('profile');
const selectedKeys = computed(() => [activeTab.value]);
// 计算属性:头像显示优先级:本地预览 > 已保存的头像 > 初始头像
const avatarSrc = computed(() => {
if (pendingAvatarFile.value) {
return URL.createObjectURL(pendingAvatarFile.value);
/**
* 页内切换只改本地状态,不要改 query。
* tabbar 用 fullPath 做标签 key,带 ?tab= 会开出两个系统标签。
*/
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>
<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">
<Spin :spinning="loading">
<Page auto-content-height content-class="flex min-h-0 flex-col">
<div
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%)]"
>
<aside
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%)]"
>
<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>
</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>
</Page>
</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>