Compare commits

8 Commits
41 changed files with 2442 additions and 703 deletions
+21 -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)`
@@ -363,6 +364,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)。
## 分环境配置
+9 -2
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(
@@ -68,5 +72,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,
),
)
+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(
@@ -103,8 +103,15 @@ 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:
+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)
+28 -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):
@@ -111,6 +118,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 +150,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"),
@@ -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<>();
+9 -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;
@@ -140,6 +142,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 +152,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}`,
+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,
},
},
];
@@ -1,7 +1,8 @@
<script lang="ts" setup>
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import { createIconifyIcon } from '@vben/icons';
import { Tooltip, message } from 'ant-design-vue';
import { ChatSender } from '@tdesign-vue-next/chat';
import { getProductPageApi } from '#/api/ec/product';
@@ -19,11 +20,15 @@ import {
type CatalogCiteKind,
} from './catalog-cite';
const ArrowUpIcon = createIconifyIcon('lucide:arrow-up');
const ExpandIcon = createIconifyIcon('lucide:maximize-2');
const CollapseIcon = createIconifyIcon('lucide:minimize-2');
/** 包一层 ChatSender:@ 先选分类,选中后在输入行内嵌标签。 */
const draft = defineModel<string>({ required: true });
const cites = defineModel<CatalogCite[]>('cites', { required: true });
defineProps<{
const props = defineProps<{
loading?: boolean;
}>();
@@ -39,6 +44,10 @@ const dismissed = ref(false);
const loadingList = ref(false);
const activeKey = ref('');
const items = ref<CatalogCite[]>([]);
/** 输入框是否已手动展开 */
const expanded = ref(false);
/** 内容是否超过 1 行(用于显示右上角展开按钮) */
const multiLine = ref(false);
let timer: ReturnType<typeof setTimeout> | undefined;
let seq = 0;
@@ -47,6 +56,19 @@ const menuOpen = computed(
() => mentionQuery.value !== null && !dismissed.value,
);
/** 未展开:1~14 行自动增高;展开后再抬高上限 */
const textareaAutosize = computed(() =>
expanded.value
? { minRows: 8, maxRows: 28 }
: { minRows: 1, maxRows: 14 },
);
const showExpandToggle = computed(() => expanded.value || multiLine.value);
const canSend = computed(
() => !props.loading && !!(draft.value || '').trim(),
);
watch(mentionQuery, (query, prev) => {
if (query !== prev) {
dismissed.value = false;
@@ -67,6 +89,14 @@ watch(kind, () => {
scheduleSearch(mentionQuery.value);
});
watch(draft, () => {
checkMultiLine();
});
watch(expanded, () => {
void nextTick(() => checkMultiLine());
});
function scheduleSearch(query: string) {
if (timer) clearTimeout(timer);
loadingList.value = true;
@@ -131,7 +161,93 @@ async function safeList(task: Promise<CatalogCite[]>) {
}
}
/** 按可视行数判断:超过 1 行就稳定显示展开按钮(不依赖 scroll overflow,避免 autosize 时闪烁消失) */
function checkMultiLine() {
const run = () => {
const el = rootRef.value?.querySelector('textarea');
if (!el) {
multiLine.value = false;
return;
}
if (expanded.value) {
multiLine.value = true;
return;
}
const text = draft.value || '';
if (!text) {
multiLine.value = false;
return;
}
// 显式换行
if (text.includes('\n')) {
multiLine.value = true;
return;
}
const style = window.getComputedStyle(el);
const lineHeight = parseFloat(style.lineHeight);
const fontSize = parseFloat(style.fontSize) || 14;
const lh =
Number.isFinite(lineHeight) && lineHeight > 0 ? lineHeight : fontSize * 1.5;
const padY =
(parseFloat(style.paddingTop) || 0) +
(parseFloat(style.paddingBottom) || 0);
// scrollHeight 在 autosize 下仍反映内容总高度
const rows = Math.max(1, Math.round((el.scrollHeight - padY) / lh));
multiLine.value = rows > 1;
};
// 等 autosize 改完高度再量,避免中间态误判
void nextTick(() => {
requestAnimationFrame(run);
});
}
function toggleExpand() {
expanded.value = !expanded.value;
focusInput();
}
function onSendClick() {
const text = draft.value;
if (!text?.trim() || props.loading) return;
emit('send', text);
resetExpandAfterSend();
}
function onChatSend(value: string) {
emit('send', value);
resetExpandAfterSend();
}
function resetExpandAfterSend() {
expanded.value = false;
multiLine.value = false;
}
function onStopClick() {
emit('stop');
}
function onKeydown(event: KeyboardEvent) {
// 光标在输入框开头(或内容为空)时,Backspace 删掉最后一个引用 chip
if (
event.key === 'Backspace' &&
!event.isComposing &&
event.keyCode !== 229 &&
cites.value.length > 0
) {
const el = rootRef.value?.querySelector('textarea');
if (el) {
const atStart = el.selectionStart === 0 && el.selectionEnd === 0;
if (atStart || !draft.value) {
event.preventDefault();
event.stopPropagation();
const last = cites.value[cites.value.length - 1];
if (last) removeCite(last.key);
return;
}
}
}
if (!menuOpen.value || event.isComposing || event.keyCode === 229) return;
if (event.key === 'ArrowDown') {
event.preventDefault();
@@ -228,17 +344,40 @@ onBeforeUnmount(() => {
</script>
<template>
<div ref="rootRef" class="catalog-cite-sender relative" @keydown.capture="onKeydown">
<div
ref="rootRef"
class="catalog-cite-sender relative"
:class="{ 'catalog-cite-sender--expandable': showExpandToggle }"
@keydown.capture="onKeydown"
>
<!-- 展开/收起固定在输入框右上角 -->
<Tooltip
v-if="showExpandToggle"
:title="expanded ? '收起输入框' : '展开输入框'"
placement="top"
>
<button
type="button"
class="sender-expand-corner text-muted-foreground hover:text-foreground hover:bg-muted"
:aria-label="expanded ? '收起输入框' : '展开输入框'"
@mousedown.prevent
@click="toggleExpand"
>
<CollapseIcon v-if="expanded" class="size-4" />
<ExpandIcon v-else class="size-4" />
</button>
</Tooltip>
<div
v-if="menuOpen"
class="border-border bg-card absolute bottom-full left-0 z-20 mb-2 w-80 overflow-hidden rounded-lg border shadow-lg"
class="border-border bg-popover absolute bottom-full left-0 z-20 mb-2 w-80 overflow-hidden rounded-lg border shadow-lg"
>
<div class="flex gap-1 p-1.5">
<div class="flex shrink-0 gap-1 p-1.5">
<button
v-for="item in kinds"
:key="item"
type="button"
class="flex-1 rounded-md px-2 py-1.5 text-xs"
class="flex-1 cursor-pointer rounded-md px-2 py-1.5 text-xs"
:class="
item === kind
? 'bg-primary/10 text-primary font-medium'
@@ -249,16 +388,17 @@ onBeforeUnmount(() => {
{{ catalogCiteLabel(item) }}
</button>
</div>
<div class="max-h-72 overflow-y-auto py-1">
<!-- 固定高度,避免加载前后弹层跳动 -->
<div class="cite-menu-list h-72 overflow-y-auto py-1">
<div
v-if="loadingList && items.length === 0"
class="text-muted-foreground px-3 py-6 text-center text-xs"
class="text-muted-foreground flex h-full items-center justify-center px-3 text-center text-xs"
>
搜索中…
</div>
<div
v-else-if="items.length === 0"
class="text-muted-foreground px-3 py-6 text-center text-xs"
class="text-muted-foreground flex h-full items-center justify-center px-3 text-center text-xs"
>
这个分类下没有匹配
</div>
@@ -268,7 +408,7 @@ onBeforeUnmount(() => {
:key="item.key"
type="button"
:data-cite-key="item.key"
class="flex w-full flex-col px-3 py-1.5 text-left"
class="flex w-full cursor-pointer flex-col px-3 py-1.5 text-left"
:class="item.key === activeKey ? 'bg-primary/10' : 'hover:bg-muted'"
@mouseenter="activeKey = item.key"
@mousedown.prevent="pick(item)"
@@ -284,7 +424,7 @@ onBeforeUnmount(() => {
</template>
</div>
<div class="text-muted-foreground border-border border-t px-3 py-1.5 text-[11px]">
↑↓ 选择 · Enter 引用 · Esc 关闭
↑↓ 选择 · Enter 引用 · Esc 关闭 · ⌫ 删引用
</div>
</div>
@@ -292,9 +432,9 @@ onBeforeUnmount(() => {
v-model="draft"
class="agent-td-sender"
:loading="loading"
placeholder="输入问题,@ 引用店铺、商品或 SKU"
:textarea-props="{ autosize: { minRows: 2, maxRows: 6 } }"
@send="emit('send', $event)"
placeholder="问点什么,或用 @ 引用店铺 / 商品 / SKU"
:textarea-props="{ autosize: textareaAutosize }"
@send="onChatSend"
@stop="emit('stop')"
>
<template #input-prefix>
@@ -308,7 +448,7 @@ onBeforeUnmount(() => {
<span class="truncate">{{ cite.title }}</span>
<button
type="button"
class="opacity-60 hover:opacity-100"
class="cursor-pointer opacity-60 hover:opacity-100"
aria-label="移除引用"
@mousedown.prevent
@click="removeCite(cite.key)"
@@ -319,13 +459,44 @@ onBeforeUnmount(() => {
</div>
</template>
<template #footer-prefix>
<button
type="button"
class="text-muted-foreground hover:text-primary rounded px-1 py-1 text-xs"
@click="insertMention"
>
@ 引用
</button>
<div class="catalog-cite-footer flex min-w-0 flex-1 items-center gap-2">
<button
type="button"
class="text-muted-foreground hover:text-primary shrink-0 cursor-pointer rounded px-1 py-1 text-xs"
@click="insertMention"
>
@ 引用
</button>
<slot name="footer-extra"></slot>
</div>
</template>
<template #suffix>
<div class="sender-suffix flex items-center gap-1">
<Tooltip v-if="loading" title="停止生成">
<button
type="button"
class="sender-send-btn sender-send-btn--stop"
aria-label="停止生成"
@mousedown.prevent
@click="onStopClick"
>
<span class="sender-stop-square" />
</button>
</Tooltip>
<Tooltip v-else title="发送">
<button
type="button"
class="sender-send-btn"
:class="{ 'sender-send-btn--disabled': !canSend }"
:disabled="!canSend"
aria-label="发送"
@mousedown.prevent
@click="onSendClick"
>
<ArrowUpIcon class="size-4" />
</button>
</Tooltip>
</div>
</template>
</ChatSender>
</div>
@@ -335,14 +506,32 @@ onBeforeUnmount(() => {
.agent-td-sender {
width: 100%;
}
.catalog-cite-sender :deep(.t-chat-sender__textarea__wrapper) {
align-items: flex-start;
padding: 0;
margin-bottom: 0 !important;
}
.catalog-cite-sender :deep(.t-textarea) {
flex: 1;
width: auto;
min-width: 0;
}
.catalog-cite-sender :deep(.t-textarea__inner) {
padding: 0 !important;
}
.catalog-cite-sender--expandable :deep(.t-textarea__inner) {
/* 给右上角展开按钮留出点击空间,避免文字压住图标 */
padding-right: 28px !important;
}
.catalog-cite-sender :deep(.t-chat-sender__footer) {
align-items: center;
}
.cite-inline {
display: flex;
flex-shrink: 0;
@@ -354,4 +543,62 @@ onBeforeUnmount(() => {
margin-right: 8px;
overflow-x: auto;
}
.sender-expand-corner {
position: absolute;
top: 8px;
right: 8px;
z-index: 5;
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
cursor: pointer;
border: none;
border-radius: 999px;
background: transparent;
transition:
background-color 0.15s,
color 0.15s;
}
.sender-send-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
cursor: pointer;
border: none;
border-radius: 999px;
color: hsl(var(--primary-foreground, 0 0% 100%));
background: hsl(var(--primary));
transition:
opacity 0.15s,
transform 0.15s;
}
.sender-send-btn:hover:not(:disabled) {
opacity: 0.9;
}
.sender-send-btn--disabled,
.sender-send-btn:disabled {
cursor: not-allowed;
opacity: 0.4;
}
.sender-send-btn--stop {
color: hsl(var(--foreground));
background: hsl(var(--muted));
}
.sender-stop-square {
display: block;
width: 10px;
height: 10px;
border-radius: 2px;
background: currentColor;
}
</style>
@@ -1,10 +1,18 @@
<script lang="ts" setup>
import { computed, 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 { Empty, Popover, Select, Spin, Tooltip, message } from 'ant-design-vue';
import { ChatItem } from '@tdesign-vue-next/chat';
import 'tdesign-vue-next/es/style/index.css';
import '@tdesign-vue-next/chat/es/style/index.css';
@@ -20,6 +28,7 @@ import {
} from '#/api/agent';
import CatalogCiteSender from './catalog-cite-sender.vue';
import SessionSearchModal from './session-search-modal.vue';
import {
composeMessageWithCites,
stripTrailingMention,
@@ -28,14 +37,41 @@ 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 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 +88,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 +154,7 @@ const showMessageLoading = computed(
() => loadingMessages.value && !sending.value && messages.value.length === 0,
);
/** 新对话草稿,或还没有任何会话时,展示能力引导 */
/** 新对话草稿,或还没有任何会话时,展示居中空态 */
const showStarter = computed(
() =>
messages.value.length === 0 &&
@@ -119,6 +163,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 =
@@ -469,182 +593,420 @@ 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>
<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-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">
尚未发送
</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)"
>
<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"
>
{{ s.updatedAt || s.lastMessageAt }}
</div>
</button>
</div>
</div>
</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"
<div
v-if="!siderCollapsed"
class="flex h-12 shrink-0 items-center gap-1 px-3"
>
<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 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 class="min-w-0 flex-1 truncate text-sm font-semibold">
智能助手
</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"
<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"
>
<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"
<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
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"
>
<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>
</template>
<Tooltip
:title="collapsedRecentOpen ? '' : '最近聊天'"
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"
:class="collapsedRecentOpen ? 'bg-muted text-foreground' : ''"
aria-label="最近聊天"
>
<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)"
<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 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"
>
{{ item }}
{{ group.label }}
</div>
<button
v-for="s in group.items"
:key="s.threadId"
type="button"
class="agent-session-item mb-0.5 w-full cursor-pointer rounded-lg px-3 py-2 text-left text-sm transition-colors"
:class="
s.threadId === activeThreadId
? 'agent-session-item--active'
: ''
"
@click="onSessionClick(s.threadId)"
>
<EllipsisText :tooltip-when-ellipsis="true" class="w-full">
{{ s.title || '新对话' }}
</EllipsisText>
</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">
</template>
</aside>
<!-- 主区:空态居中 / 对话时消息 + 底栏输入 -->
<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"
>
加载消息…
</div>
<!-- 空态:问候 + 居中输入 + 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"
: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-2 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>
<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;
margin-bottom: 16px;
}
/* 气泡按内容收缩,左右再留一截,避免贴边铺满 */
/* 气泡按内容收缩,避免贴边铺满 */
.agent-td-item :deep(.t-chat__inner) {
box-sizing: border-box;
padding-inline: 4px;
}
.agent-td-item :deep(.t-chat__content) {
width: auto;
max-width: min(720px, calc(100% - 32px));
max-width: min(680px, calc(100% - 24px));
}
.agent-td-item :deep(.t-chat__inner.user) {
justify-content: flex-end;
}
.agent-td-item :deep(.t-chat__text__name) {
opacity: 0.55;
font-size: 12px;
}
/* 浅色:给气泡补边框与底色,避免与主背景糊在一起 */
.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 :deep(.t-chat__inner.user .t-chat__text--variant--base .t-chat__detail),
.agent-td-item :deep(.t-chat__inner.user .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 :deep(.t-chat__inner.user .t-chat__text--variant--base .t-chat__detail),
html.dark .agent-td-item :deep(.t-chat__inner.user .t-chat__detail),
.dark .agent-td-item :deep(.t-chat__inner.user .t-chat__text--variant--base .t-chat__detail),
.dark .agent-td-item :deep(.t-chat__inner.user .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,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>