mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
feat: 发布页前端工具改为等待浏览器回执后再继续模型
This commit is contained in:
@@ -1,4 +1,8 @@
|
||||
"""发布场景前端写工具:读快照注入 system;写工具由 streamer 推 client_tool 事件。"""
|
||||
"""发布场景前端写工具。
|
||||
|
||||
只向模型注册 schema。真正写入发生在浏览器;streamer 推 client_tool 后等待回执,
|
||||
不把这里的占位返回值当成 ToolMessage。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
@@ -8,9 +8,11 @@ from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from sse_starlette.sse import EventSourceResponse
|
||||
|
||||
from api.deps import chat_service, current_actor
|
||||
from api.deps import chat_service, current_actor, session_service
|
||||
from api.response import ok
|
||||
from application.chat_service import ChatService
|
||||
from application.client_tool_gate import get_client_tool_gate
|
||||
from application.session_service import SessionService
|
||||
from domain.models import Actor
|
||||
|
||||
router = APIRouter(prefix="/sessions", tags=["chat"])
|
||||
@@ -22,6 +24,14 @@ class ChatBody(BaseModel):
|
||||
formSnapshot: dict | None = None
|
||||
|
||||
|
||||
class ClientToolResultBody(BaseModel):
|
||||
"""浏览器执行 ui_set_* 后的真实结果,唤醒挂起的工具轮。"""
|
||||
|
||||
toolCallId: str = Field(min_length=1, max_length=200)
|
||||
ok: bool
|
||||
message: str = Field(default="", max_length=2000)
|
||||
|
||||
|
||||
@router.get("/{thread_id}/messages")
|
||||
async def list_messages(
|
||||
thread_id: str,
|
||||
@@ -115,3 +125,24 @@ async def chat_stream(
|
||||
},
|
||||
ping=15,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{thread_id}/client-tool-results")
|
||||
async def submit_client_tool_result(
|
||||
thread_id: str,
|
||||
body: ClientToolResultBody,
|
||||
actor: Actor = Depends(current_actor),
|
||||
sessions: SessionService = Depends(session_service),
|
||||
):
|
||||
"""前端工具回执。对上当前轮等待则 accepted=true;迟到或未知 id 仍 200,避免打断页面。"""
|
||||
try:
|
||||
await sessions.require_owned(actor, thread_id)
|
||||
except LookupError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e)) from e
|
||||
accepted = get_client_tool_gate().submit(
|
||||
thread_id,
|
||||
body.toolCallId.strip(),
|
||||
body.ok,
|
||||
body.message,
|
||||
)
|
||||
return ok({"accepted": accepted})
|
||||
|
||||
@@ -6,6 +6,7 @@ from datetime import datetime
|
||||
from typing import AsyncIterator
|
||||
|
||||
from agent.runtime import load_tools_for_turn
|
||||
from application.client_tool_gate import BoundClientToolTurn, get_client_tool_gate
|
||||
from application.context_window import resolve_context_window, trim_history_to_budget
|
||||
from application.llm_settings_service import LlmRuntimeService
|
||||
from application.memory_service import MemoryService
|
||||
@@ -154,21 +155,28 @@ class ChatService:
|
||||
|
||||
parts: list[str] = []
|
||||
new_response_id: str | None = None
|
||||
async for event in self._streamer.stream_reply(
|
||||
llm=llm,
|
||||
history=history,
|
||||
user_text=text,
|
||||
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
|
||||
gate = get_client_tool_gate()
|
||||
epoch = gate.begin(thread_id)
|
||||
turn = BoundClientToolTurn(gate, thread_id, epoch)
|
||||
try:
|
||||
async for event in self._streamer.stream_reply(
|
||||
llm=llm,
|
||||
history=history,
|
||||
user_text=text,
|
||||
system_prompt=system_prompt,
|
||||
tools=tools or None,
|
||||
max_tool_result_chars=max_tool_chars,
|
||||
previous_response_id=chain_id,
|
||||
client_tool_turn=turn,
|
||||
):
|
||||
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
|
||||
finally:
|
||||
gate.end(thread_id, epoch)
|
||||
|
||||
full = "".join(parts).strip() or "(模型未返回内容)"
|
||||
a_seq = await self._messages.next_seq(actor.company_id, actor.user_id, thread_id)
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
"""前端工具回执门闩:进程内按会话代次等待,供 SSE 挂起后由 POST 唤醒。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from dataclasses import dataclass
|
||||
|
||||
# 前端写入应很快返回;超时后模型拿到失败,避免 SSE 一直挂着
|
||||
_DEFAULT_TIMEOUT_SECONDS = 20.0
|
||||
|
||||
|
||||
def format_client_tool_result(ok: bool, message: str) -> str:
|
||||
"""写成模型可读的 ToolMessage。失败统一前缀,便于提示词识别。"""
|
||||
text = (message or "").strip()
|
||||
if ok:
|
||||
return text or "已写入"
|
||||
return f"写入失败:{text or '未知原因'}"
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Waiter:
|
||||
epoch: int
|
||||
future: asyncio.Future[tuple[bool, str]]
|
||||
|
||||
|
||||
class ClientToolGate:
|
||||
"""单进程等待表。多 worker 时回执可能打到别的进程,当前部署按单进程使用。"""
|
||||
|
||||
def __init__(self, timeout_seconds: float = _DEFAULT_TIMEOUT_SECONDS) -> None:
|
||||
self._timeout = timeout_seconds
|
||||
self._epoch: dict[str, int] = {}
|
||||
self._waiters: dict[tuple[str, str], _Waiter] = {}
|
||||
|
||||
def begin(self, thread_id: str) -> int:
|
||||
"""新开一轮:抬高代次,并结束该会话上一代尚未完成的等待。"""
|
||||
epoch = self._epoch.get(thread_id, 0) + 1
|
||||
self._epoch[thread_id] = epoch
|
||||
self._settle(thread_id, only_epoch=None, keep_epoch=epoch, message="本轮已取消")
|
||||
return epoch
|
||||
|
||||
def end(self, thread_id: str, epoch: int) -> None:
|
||||
"""本轮流结束或断开:只结算这一代,避免误伤已开始的下一轮。"""
|
||||
self._settle(thread_id, only_epoch=epoch, keep_epoch=None, message="本轮已取消")
|
||||
|
||||
def arm(self, thread_id: str, epoch: int, tool_call_id: str) -> None:
|
||||
"""在向浏览器推 client_tool 之前登记,避免回执先到。"""
|
||||
if self._epoch.get(thread_id) != epoch:
|
||||
return
|
||||
key = (thread_id, tool_call_id)
|
||||
loop = asyncio.get_running_loop()
|
||||
previous = self._waiters.get(key)
|
||||
if previous is not None and not previous.future.done():
|
||||
previous.future.set_result((False, "本轮已取消"))
|
||||
self._waiters[key] = _Waiter(epoch=epoch, future=loop.create_future())
|
||||
|
||||
async def wait(self, thread_id: str, epoch: int, tool_call_id: str) -> tuple[bool, str]:
|
||||
key = (thread_id, tool_call_id)
|
||||
waiter = self._waiters.get(key)
|
||||
if waiter is None or waiter.epoch != epoch:
|
||||
return False, "本轮已取消"
|
||||
future = waiter.future
|
||||
try:
|
||||
# shield:超时或断流时不把 Future 一起取消,便于区分迟到回执
|
||||
return await asyncio.wait_for(asyncio.shield(future), self._timeout)
|
||||
except asyncio.TimeoutError:
|
||||
if not future.done():
|
||||
future.set_result((False, "前端未回执"))
|
||||
return False, "前端未回执"
|
||||
finally:
|
||||
current = self._waiters.get(key)
|
||||
if current is not None and current.future is future:
|
||||
self._waiters.pop(key, None)
|
||||
|
||||
def submit(self, thread_id: str, tool_call_id: str, ok: bool, message: str) -> bool:
|
||||
"""对上当前代次的等待则唤醒。迟到或未知 id 返回 False。"""
|
||||
key = (thread_id, tool_call_id)
|
||||
waiter = self._waiters.get(key)
|
||||
epoch = self._epoch.get(thread_id)
|
||||
if waiter is None or epoch is None or waiter.epoch != epoch or waiter.future.done():
|
||||
return False
|
||||
waiter.future.set_result((bool(ok), message or ""))
|
||||
return True
|
||||
|
||||
def _settle(
|
||||
self,
|
||||
thread_id: str,
|
||||
*,
|
||||
only_epoch: int | None,
|
||||
keep_epoch: int | None,
|
||||
message: str,
|
||||
) -> None:
|
||||
for key, waiter in list(self._waiters.items()):
|
||||
if key[0] != thread_id:
|
||||
continue
|
||||
if only_epoch is not None and waiter.epoch != only_epoch:
|
||||
continue
|
||||
if keep_epoch is not None and waiter.epoch == keep_epoch:
|
||||
continue
|
||||
self._waiters.pop(key, None)
|
||||
if not waiter.future.done():
|
||||
waiter.future.set_result((False, message))
|
||||
|
||||
|
||||
_gate: ClientToolGate | None = None
|
||||
|
||||
|
||||
def get_client_tool_gate() -> ClientToolGate:
|
||||
global _gate
|
||||
if _gate is None:
|
||||
_gate = ClientToolGate()
|
||||
return _gate
|
||||
|
||||
|
||||
class BoundClientToolTurn:
|
||||
"""绑定到一次 stream_chat 的代次。"""
|
||||
|
||||
def __init__(self, gate: ClientToolGate, thread_id: str, epoch: int) -> None:
|
||||
self._gate = gate
|
||||
self._thread_id = thread_id
|
||||
self._epoch = epoch
|
||||
|
||||
def arm(self, tool_call_id: str) -> None:
|
||||
self._gate.arm(self._thread_id, self._epoch, tool_call_id)
|
||||
|
||||
async def wait_result(self, tool_call_id: str) -> str:
|
||||
ok, message = await self._gate.wait(self._thread_id, self._epoch, tool_call_id)
|
||||
return format_client_tool_result(ok, message)
|
||||
@@ -34,6 +34,7 @@ _PUBLISH_SYSTEM = (
|
||||
"你是电商 DMB 的拼多多商品发布助手,帮助用户在系统草稿里完善标题、规格轴、属性与价格等。"
|
||||
"当前表单快照已在下方【当前发布表单】中给出,直接根据快照改表,不要再去「读取」表单。"
|
||||
"改表单必须调用 ui_set_goods_name / ui_set_goods_desc / ui_set_spec_axes,不要只口头说已修改。"
|
||||
"这些工具的返回值是页面真实写入结果;以「写入失败」开头时说明原因,不要声称已经改好。"
|
||||
"查内部商品/SKU:catalog_search、catalog_sku_detail(按 skuCode)。"
|
||||
"查已同步的拼多多渠道商品:pdd_goods_search、pdd_goods_detail(只查本地库)。"
|
||||
"常见流程:根据表单已有 SKU 编码 → catalog_sku_detail / pdd_goods_search → "
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any, AsyncIterator
|
||||
from typing import Any, AsyncIterator, Protocol
|
||||
|
||||
from domain.models import (
|
||||
ChatMessage,
|
||||
@@ -144,6 +144,14 @@ class LlmProtocolCapabilityCache(ABC):
|
||||
) -> None: ...
|
||||
|
||||
|
||||
class ClientToolTurn(Protocol):
|
||||
"""一轮聊天里前端工具的回执等待:先 arm 再推 SSE,再 wait_result。"""
|
||||
|
||||
def arm(self, tool_call_id: str) -> None: ...
|
||||
|
||||
async def wait_result(self, tool_call_id: str) -> str: ...
|
||||
|
||||
|
||||
class ChatStreamer(ABC):
|
||||
"""流式生成助手回复。"""
|
||||
|
||||
@@ -158,4 +166,5 @@ class ChatStreamer(ABC):
|
||||
tools: list[Any] | None = None,
|
||||
max_tool_result_chars: int = 4000,
|
||||
previous_response_id: str | None = None,
|
||||
client_tool_turn: ClientToolTurn | None = None,
|
||||
) -> AsyncIterator[StreamEvent]: ...
|
||||
|
||||
@@ -22,7 +22,7 @@ from domain.models import (
|
||||
MessageRole,
|
||||
StreamEvent,
|
||||
)
|
||||
from domain.ports import ChatStreamer, LlmProtocolCapabilityCache
|
||||
from domain.ports import ChatStreamer, ClientToolTurn, LlmProtocolCapabilityCache
|
||||
from infrastructure.llm.api_style import (
|
||||
ProtocolAttempt,
|
||||
classify_protocol_error,
|
||||
@@ -55,6 +55,7 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
||||
tools: list[Any] | None = None,
|
||||
max_tool_result_chars: int = 8000,
|
||||
previous_response_id: str | None = None,
|
||||
client_tool_turn: ClientToolTurn | None = None,
|
||||
) -> AsyncIterator[StreamEvent]:
|
||||
chain_id = (previous_response_id or "").strip() or None
|
||||
style = normalize_api_style(llm.api_style)
|
||||
@@ -93,6 +94,7 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
||||
use_responses=attempt.use_responses,
|
||||
use_store=attempt.use_store,
|
||||
previous_response_id=use_chain_id,
|
||||
client_tool_turn=client_tool_turn,
|
||||
):
|
||||
if event.kind == "token" and event.text:
|
||||
yielded_any = True
|
||||
@@ -302,6 +304,7 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
||||
use_responses: bool,
|
||||
use_store: bool,
|
||||
previous_response_id: str | None,
|
||||
client_tool_turn: ClientToolTurn | None = None,
|
||||
) -> AsyncIterator[StreamEvent]:
|
||||
kwargs: dict[str, Any] = {
|
||||
"api_key": llm.api_key,
|
||||
@@ -417,24 +420,32 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
||||
name = tc.get("name") or ""
|
||||
args = tc.get("args") or {}
|
||||
call_id = tc.get("id") or name
|
||||
if is_client_tool_name(name):
|
||||
yield StreamEvent.client_tool(
|
||||
tool_call_id=str(call_id),
|
||||
name=name,
|
||||
args=args if isinstance(args, dict) else {},
|
||||
label=tool_status_label(name),
|
||||
)
|
||||
tool = tool_map.get(name)
|
||||
try:
|
||||
if tool is None:
|
||||
result = f"未知工具: {name}"
|
||||
if is_client_tool_name(name):
|
||||
# 占位函数不代表页面已写入;先登记等待再推事件,回执到达后才进 ToolMessage
|
||||
tool_args = args if isinstance(args, dict) else {}
|
||||
if client_tool_turn is None:
|
||||
result = "写入失败:前端回执通道未配置"
|
||||
else:
|
||||
client_tool_turn.arm(str(call_id))
|
||||
yield StreamEvent.client_tool(
|
||||
tool_call_id=str(call_id),
|
||||
name=name,
|
||||
args=tool_args,
|
||||
label=tool_status_label(name),
|
||||
)
|
||||
result = await client_tool_turn.wait_result(str(call_id))
|
||||
else:
|
||||
raw = await tool.ainvoke(args)
|
||||
result = (
|
||||
raw
|
||||
if isinstance(raw, str)
|
||||
else json.dumps(raw, ensure_ascii=False, default=str)
|
||||
)
|
||||
tool = tool_map.get(name)
|
||||
if tool is None:
|
||||
result = f"未知工具: {name}"
|
||||
else:
|
||||
raw = await tool.ainvoke(args)
|
||||
result = (
|
||||
raw
|
||||
if isinstance(raw, str)
|
||||
else json.dumps(raw, ensure_ascii=False, default=str)
|
||||
)
|
||||
except Exception as e: # noqa: BLE001
|
||||
result = f"工具执行失败: {e}"
|
||||
messages.append(
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
"""前端工具回执门闩:代次隔离、超时与迟到提交。"""
|
||||
|
||||
import asyncio
|
||||
|
||||
from application.client_tool_gate import (
|
||||
ClientToolGate,
|
||||
format_client_tool_result,
|
||||
)
|
||||
|
||||
|
||||
def test_format_failure_prefix():
|
||||
assert format_client_tool_result(True, "已写入标题") == "已写入标题"
|
||||
assert format_client_tool_result(False, "标题为空").startswith("写入失败")
|
||||
|
||||
|
||||
def test_submit_wakes_current_epoch_only():
|
||||
gate = ClientToolGate(timeout_seconds=1)
|
||||
|
||||
async def scenario():
|
||||
epoch = gate.begin("t1")
|
||||
gate.arm("t1", epoch, "call-1")
|
||||
late = gate.begin("t1")
|
||||
assert late != epoch
|
||||
assert gate.submit("t1", "call-1", True, "旧轮") is False
|
||||
gate.arm("t1", late, "call-2")
|
||||
assert gate.submit("t1", "call-2", True, "已写入标题") is True
|
||||
ok, message = await gate.wait("t1", late, "call-2")
|
||||
assert ok is True
|
||||
assert message == "已写入标题"
|
||||
assert gate.submit("t1", "call-2", True, "再次") is False
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_timeout_when_no_submit():
|
||||
gate = ClientToolGate(timeout_seconds=0.05)
|
||||
|
||||
async def scenario():
|
||||
epoch = gate.begin("t2")
|
||||
gate.arm("t2", epoch, "call")
|
||||
ok, message = await gate.wait("t2", epoch, "call")
|
||||
assert ok is False
|
||||
assert message == "前端未回执"
|
||||
|
||||
asyncio.run(scenario())
|
||||
@@ -21,7 +21,7 @@ export namespace AgentVO {
|
||||
lastMessageAt?: string | null;
|
||||
}
|
||||
|
||||
/** SSE client_tool:前端执行后模型侧已乐观回传 */
|
||||
/** SSE client_tool:前端执行后需把真实结果 POST 回当前轮 */
|
||||
export interface ClientToolCall {
|
||||
toolCallId: string;
|
||||
name: string;
|
||||
@@ -102,6 +102,17 @@ export async function createAgentSessionApi(options?: {
|
||||
});
|
||||
}
|
||||
|
||||
/** 前端工具真实结果,唤醒 Agent 当前轮里挂起的 ui_set_* */
|
||||
export async function submitAgentClientToolResultApi(
|
||||
threadId: string,
|
||||
body: { toolCallId: string; ok: boolean; message: string },
|
||||
) {
|
||||
return requestClient.post<{ accepted: boolean }>(
|
||||
`/agent/sessions/${threadId}/client-tool-results`,
|
||||
body,
|
||||
);
|
||||
}
|
||||
|
||||
export async function patchAgentSessionApi(
|
||||
threadId: string,
|
||||
body: { title?: string; llmProviderId?: number; llmModel?: string },
|
||||
@@ -234,7 +245,7 @@ export function streamAgentChat(options: {
|
||||
name?: string;
|
||||
label: string;
|
||||
}) => void;
|
||||
/** 前端工具:乐观执行改表单(可返回 Promise,流式侧会 await 以串行动画) */
|
||||
/** 前端工具:执行后应尽快 POST 回执;打字动画不要堵在这个回调里 */
|
||||
onClientTool?: (
|
||||
call: AgentVO.ClientToolCall,
|
||||
) => void | Promise<void>;
|
||||
|
||||
@@ -15,6 +15,7 @@ export {
|
||||
probeAgentLlmModelsApi,
|
||||
setAgentLlmModelEnabledApi,
|
||||
streamAgentChat,
|
||||
submitAgentClientToolResultApi,
|
||||
updateAgentLlmProviderApi,
|
||||
upsertAgentLlmProviderModelsApi,
|
||||
} from './apis';
|
||||
|
||||
+27
-7
@@ -1,6 +1,6 @@
|
||||
<script lang="ts" setup>
|
||||
/**
|
||||
* 拼多多发布页右侧智能体栏:一草稿一会话,执行 client_tool 改表单。
|
||||
* 拼多多发布页右侧智能体栏:一草稿一会话,执行 client_tool 后立刻回执。
|
||||
* UI 对齐通用智能助手(气泡、加载、底栏输入与模型选择)。
|
||||
*/
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
listAgentMessagesApi,
|
||||
patchAgentSessionApi,
|
||||
streamAgentChat,
|
||||
submitAgentClientToolResultApi,
|
||||
type AgentVO,
|
||||
} from '#/api/agent';
|
||||
import CatalogCiteSender from '#/views/agent/chat/catalog-cite-sender.vue';
|
||||
@@ -353,14 +354,33 @@ function onStreamTool(payload: { phase: string; label: string }) {
|
||||
|
||||
async function onClientTool(call: AgentVO.ClientToolCall) {
|
||||
const api = props.editorApi;
|
||||
if (!api) return;
|
||||
try {
|
||||
const result = await api.applyClientTool(call.name, call.args || {});
|
||||
if (!result.ok) {
|
||||
message.warning(result.message || '表单写入失败');
|
||||
let result = {
|
||||
ok: false,
|
||||
message: api ? '表单写入失败' : '编辑器未就绪',
|
||||
};
|
||||
if (!api) {
|
||||
message.warning(result.message);
|
||||
} else {
|
||||
try {
|
||||
result = await api.applyClientTool(call.name, call.args || {});
|
||||
if (!result.ok) {
|
||||
message.warning(result.message || '表单写入失败');
|
||||
}
|
||||
} catch (e: any) {
|
||||
result = { ok: false, message: e?.message || '表单写入失败' };
|
||||
message.warning(result.message);
|
||||
}
|
||||
}
|
||||
const threadId = session.value?.threadId;
|
||||
if (!threadId || !call.toolCallId) return;
|
||||
try {
|
||||
await submitAgentClientToolResultApi(threadId, {
|
||||
toolCallId: call.toolCallId,
|
||||
ok: result.ok,
|
||||
message: result.message,
|
||||
});
|
||||
} catch (e: any) {
|
||||
message.warning(e?.message || '表单写入失败');
|
||||
message.warning(e?.message || '工具结果回传失败');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+79
-77
@@ -528,59 +528,82 @@ function onSkuTableWrapRef(el: HTMLElement | null) {
|
||||
|
||||
<Card size="small" class="publish-editor-section" title="规格与库存">
|
||||
<div
|
||||
v-if="form.catId"
|
||||
data-agent-field="spec"
|
||||
class="publish-editor-spec-stack"
|
||||
:class="{ 'agent-typing-field': agentTypingField === 'spec' }"
|
||||
>
|
||||
<SpecAxesCard
|
||||
:spec-catalog="specCatalog"
|
||||
:spec-axes="specAxes"
|
||||
:can-add-spec-axis="canAddSpecAxis"
|
||||
:catalog-options-for-axis="catalogOptionsForAxis"
|
||||
:spec-value-display="specValueDisplay"
|
||||
:spec-value-auto-options="specValueAutoOptions"
|
||||
@set-list-ref="onSpecAxesListRef"
|
||||
@axis-catalog-change="onAxisCatalogChange"
|
||||
@spec-value-input="onSpecValueInput"
|
||||
@spec-value-commit="onSpecValueCommit"
|
||||
@spec-value-enter="onSpecValueEnter"
|
||||
@add-spec-value="addSpecValueSlot"
|
||||
@remove-spec-value="removeSpecValue"
|
||||
@remove-spec-axis="removeSpecAxis"
|
||||
@add-spec-axis="addSpecAxis"
|
||||
<template v-if="form.catId">
|
||||
<SpecAxesCard
|
||||
:spec-catalog="specCatalog"
|
||||
:spec-axes="specAxes"
|
||||
:can-add-spec-axis="canAddSpecAxis"
|
||||
:catalog-options-for-axis="catalogOptionsForAxis"
|
||||
:spec-value-display="specValueDisplay"
|
||||
:spec-value-auto-options="specValueAutoOptions"
|
||||
@set-list-ref="onSpecAxesListRef"
|
||||
@axis-catalog-change="onAxisCatalogChange"
|
||||
@spec-value-input="onSpecValueInput"
|
||||
@spec-value-commit="onSpecValueCommit"
|
||||
@spec-value-enter="onSpecValueEnter"
|
||||
@add-spec-value="addSpecValueSlot"
|
||||
@remove-spec-value="removeSpecValue"
|
||||
@remove-spec-axis="removeSpecAxis"
|
||||
@add-spec-axis="addSpecAxis"
|
||||
/>
|
||||
|
||||
<SkuTableCard
|
||||
v-model:bind-pick-sku-ids="bindPickSkuIds"
|
||||
:sku-select-options="skuSelectOptions"
|
||||
:sku-rows="skuRows"
|
||||
:spec-axes-length="specAxes.length"
|
||||
:sku-table-columns="skuTableColumns"
|
||||
:sku-table-scroll-x="skuTableScrollX"
|
||||
:sku-spec-cell-display="skuSpecCellDisplay"
|
||||
:sku-spec-cell-auto-options="skuSpecCellAutoOptions"
|
||||
:before-upload-sku="beforeUploadSku"
|
||||
:on-preview-upload-file="onPreviewUploadFile"
|
||||
@search="debouncedLoadSkuCandidates"
|
||||
@dropdown-visible-change="onSkuSelectDropdownOpen"
|
||||
@apply-internal-skus="applyInternalSkusInOrder"
|
||||
@clear-internal-skus="clearInternalSkuBindings"
|
||||
@set-table-wrap-ref="onSkuTableWrapRef"
|
||||
@sku-spec-input="onSkuSpecCellInput"
|
||||
@sku-spec-commit="onSkuSpecCellCommit"
|
||||
@out-sku-sn-change="onOutSkuSnChange"
|
||||
@out-sku-sn-blur="onOutSkuSnBlur"
|
||||
@bind-internal-sku="bindInternalSku"
|
||||
@sku-thumb-file-list-change="onSkuThumbFileListChange"
|
||||
@apply-batch="applySkuBatchFields"
|
||||
/>
|
||||
</template>
|
||||
<Empty
|
||||
v-else
|
||||
description="请先选择叶子类目"
|
||||
:image="Empty.PRESENTED_IMAGE_SIMPLE"
|
||||
/>
|
||||
|
||||
<SkuTableCard
|
||||
v-model:bind-pick-sku-ids="bindPickSkuIds"
|
||||
:sku-select-options="skuSelectOptions"
|
||||
:sku-rows="skuRows"
|
||||
:spec-axes-length="specAxes.length"
|
||||
:sku-table-columns="skuTableColumns"
|
||||
:sku-table-scroll-x="skuTableScrollX"
|
||||
:sku-spec-cell-display="skuSpecCellDisplay"
|
||||
:sku-spec-cell-auto-options="skuSpecCellAutoOptions"
|
||||
:before-upload-sku="beforeUploadSku"
|
||||
:on-preview-upload-file="onPreviewUploadFile"
|
||||
@search="debouncedLoadSkuCandidates"
|
||||
@dropdown-visible-change="onSkuSelectDropdownOpen"
|
||||
@apply-internal-skus="applyInternalSkusInOrder"
|
||||
@clear-internal-skus="clearInternalSkuBindings"
|
||||
@set-table-wrap-ref="onSkuTableWrapRef"
|
||||
@sku-spec-input="onSkuSpecCellInput"
|
||||
@sku-spec-commit="onSkuSpecCellCommit"
|
||||
@out-sku-sn-change="onOutSkuSnChange"
|
||||
@out-sku-sn-blur="onOutSkuSnBlur"
|
||||
@bind-internal-sku="bindInternalSku"
|
||||
@sku-thumb-file-list-change="onSkuThumbFileListChange"
|
||||
@apply-batch="applySkuBatchFields"
|
||||
/>
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<Form.Item label="参考价(元)" required>
|
||||
<InputNumber
|
||||
v-model:value="form.marketPriceYuan"
|
||||
class="w-full"
|
||||
:min="0.01"
|
||||
:precision="2"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label="满两件折扣" required>
|
||||
<InputNumber
|
||||
v-model:value="form.twoPiecesDiscount"
|
||||
class="w-full"
|
||||
:min="0"
|
||||
:max="10"
|
||||
:precision="1"
|
||||
:step="0.1"
|
||||
placeholder="9.5 表示 9.5 折,0 取消"
|
||||
/>
|
||||
</Form.Item>
|
||||
</div>
|
||||
</div>
|
||||
<Empty
|
||||
v-else
|
||||
description="请先选择叶子类目"
|
||||
:image="Empty.PRESENTED_IMAGE_SIMPLE"
|
||||
/>
|
||||
</Card>
|
||||
|
||||
<Card size="small" class="publish-editor-section" title="服务与承诺">
|
||||
@@ -700,37 +723,16 @@ function onSkuTableWrapRef(el: HTMLElement | null) {
|
||||
</Spin>
|
||||
</Card>
|
||||
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<Form.Item label="参考价(元)" required>
|
||||
<InputNumber
|
||||
v-model:value="form.marketPriceYuan"
|
||||
class="w-full"
|
||||
:min="0.01"
|
||||
:precision="2"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label="发货时限" required>
|
||||
<Select
|
||||
v-model:value="form.shipmentLimitSecond"
|
||||
class="w-full"
|
||||
:options="[
|
||||
{ label: '24小时', value: 86400 },
|
||||
{ label: '48小时', value: 172800 },
|
||||
]"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label="满两件折扣" required>
|
||||
<InputNumber
|
||||
v-model:value="form.twoPiecesDiscount"
|
||||
class="w-full"
|
||||
:min="0"
|
||||
:max="10"
|
||||
:precision="1"
|
||||
:step="0.1"
|
||||
placeholder="9.5 表示 9.5 折,0 取消"
|
||||
/>
|
||||
</Form.Item>
|
||||
</div>
|
||||
<Form.Item label="发货时限" required>
|
||||
<Select
|
||||
v-model:value="form.shipmentLimitSecond"
|
||||
class="max-w-md w-full"
|
||||
:options="[
|
||||
{ label: '24小时', value: 86400 },
|
||||
{ label: '48小时', value: 172800 },
|
||||
]"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<div class="flex flex-wrap gap-6">
|
||||
<Form.Item label="假一赔十" required>
|
||||
|
||||
+44
-45
@@ -175,7 +175,9 @@ export function usePublishAgent(options: {
|
||||
if (form.goodsName === next) {
|
||||
return { ok: true, message: `标题未变:${next}` };
|
||||
}
|
||||
const { gen } = await runTypingTask('goodsName', 'goodsName', (signal) =>
|
||||
const message = `已写入标题:${next}`;
|
||||
// 回执不等动画:先告诉模型已写入,逐字效果在后台播
|
||||
void runTypingTask('goodsName', 'goodsName', (signal) =>
|
||||
typewriterReplace(
|
||||
() => form.goodsName,
|
||||
(v) => {
|
||||
@@ -184,14 +186,13 @@ export function usePublishAgent(options: {
|
||||
next,
|
||||
{ signal },
|
||||
),
|
||||
);
|
||||
// 被更新的写入覆盖时不落旧值;最新一代无论动画是否被打断都强制提交
|
||||
if (!isLatestTyping('goodsName', gen)) {
|
||||
return { ok: true, message: `已写入标题:${next}` };
|
||||
}
|
||||
form.goodsName = next;
|
||||
agentTypingField.value = null;
|
||||
return { ok: true, message: `已写入标题:${next}` };
|
||||
).then(({ gen }) => {
|
||||
if (!isLatestTyping('goodsName', gen)) return;
|
||||
form.goodsName = next;
|
||||
agentTypingField.value = null;
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return { ok: true, message };
|
||||
}
|
||||
|
||||
async function applySetGoodsDesc(
|
||||
@@ -201,7 +202,7 @@ export function usePublishAgent(options: {
|
||||
if (form.goodsDesc === desc) {
|
||||
return { ok: true, message: '描述未变' };
|
||||
}
|
||||
const { gen } = await runTypingTask('goodsDesc', 'goodsDesc', (signal) =>
|
||||
void runTypingTask('goodsDesc', 'goodsDesc', (signal) =>
|
||||
typewriterReplace(
|
||||
() => form.goodsDesc,
|
||||
(v) => {
|
||||
@@ -210,12 +211,12 @@ export function usePublishAgent(options: {
|
||||
desc,
|
||||
{ signal, eraseIntervalMs: 10, typeIntervalMs: 18 },
|
||||
),
|
||||
);
|
||||
if (!isLatestTyping('goodsDesc', gen)) {
|
||||
return { ok: true, message: '已写入商品描述' };
|
||||
}
|
||||
form.goodsDesc = desc;
|
||||
agentTypingField.value = null;
|
||||
).then(({ gen }) => {
|
||||
if (!isLatestTyping('goodsDesc', gen)) return;
|
||||
form.goodsDesc = desc;
|
||||
agentTypingField.value = null;
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return { ok: true, message: '已写入商品描述' };
|
||||
}
|
||||
|
||||
@@ -237,7 +238,7 @@ export function usePublishAgent(options: {
|
||||
|
||||
/**
|
||||
* 按名称匹配类目规格目录;无目录时建自由轴。同轴按位置复用槽位 id,改文案保留 SKU。
|
||||
* 文案变更先落轴结构(临时旧 token),逐字打完再 sync SKU。
|
||||
* 先按最终文案落轴并 sync SKU,再后台逐字;回执不等动画。
|
||||
*/
|
||||
async function applySetSpecAxes(
|
||||
args: Record<string, unknown>,
|
||||
@@ -308,7 +309,6 @@ export function usePublishAgent(options: {
|
||||
const to = slot.token;
|
||||
if (from !== to) {
|
||||
animations.push({ axisIdx, slotIdx, from, to });
|
||||
slot.token = from;
|
||||
}
|
||||
});
|
||||
next.push(axis);
|
||||
@@ -327,7 +327,6 @@ export function usePublishAgent(options: {
|
||||
const to = slot.token;
|
||||
if (from !== to) {
|
||||
animations.push({ axisIdx, slotIdx, from, to });
|
||||
slot.token = from;
|
||||
}
|
||||
});
|
||||
next.push({
|
||||
@@ -347,8 +346,23 @@ export function usePublishAgent(options: {
|
||||
|
||||
specAxes.value = next;
|
||||
|
||||
// 有编码绑定时关闭行序兜底,完全按 agent 的 outSkuSn 对齐
|
||||
const deferredOrphans = syncSkuRowsFromSpecs({
|
||||
orphanByIndex: assignments.length === 0,
|
||||
});
|
||||
const bound =
|
||||
assignments.length > 0
|
||||
? applySkuAssignmentsByOutSkuSn(assignments, prevSkuRows)
|
||||
: 0;
|
||||
for (const orphan of deferredOrphans) {
|
||||
const adopted = skuRows.value.some((r) => r.key === orphan.key);
|
||||
if (!adopted) {
|
||||
revokeUploadFiles(orphan.thumbFileList);
|
||||
}
|
||||
}
|
||||
|
||||
if (animations.length > 0) {
|
||||
const { gen } = await runTypingTask('spec', 'spec', async (signal) => {
|
||||
void runTypingTask('spec', 'spec', async (signal) => {
|
||||
for (const anim of animations) {
|
||||
if (signal.aborted) break;
|
||||
const axis = specAxes.value[anim.axisIdx];
|
||||
@@ -364,33 +378,18 @@ export function usePublishAgent(options: {
|
||||
{ signal, eraseIntervalMs: 14, typeIntervalMs: 22 },
|
||||
);
|
||||
}
|
||||
});
|
||||
// 被同字段新写入打断时,由新一轮接管轴与 SKU,避免踩踏
|
||||
if (!isLatestTyping('spec', gen)) {
|
||||
return { ok: true, message: '规格写入已被更新覆盖' };
|
||||
}
|
||||
for (const anim of animations) {
|
||||
const slot =
|
||||
specAxes.value[anim.axisIdx]?.selectedValues[anim.slotIdx];
|
||||
if (slot) slot.token = anim.to;
|
||||
}
|
||||
agentTypingField.value = null;
|
||||
}).then(({ gen }) => {
|
||||
if (!isLatestTyping('spec', gen)) return;
|
||||
for (const anim of animations) {
|
||||
const slot =
|
||||
specAxes.value[anim.axisIdx]?.selectedValues[anim.slotIdx];
|
||||
if (slot) slot.token = anim.to;
|
||||
}
|
||||
agentTypingField.value = null;
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
// 有编码绑定时关闭行序兜底,完全按 agent 的 outSkuSn 对齐
|
||||
const deferredOrphans = syncSkuRowsFromSpecs({
|
||||
orphanByIndex: assignments.length === 0,
|
||||
});
|
||||
const bound =
|
||||
assignments.length > 0
|
||||
? applySkuAssignmentsByOutSkuSn(assignments, prevSkuRows)
|
||||
: 0;
|
||||
for (const orphan of deferredOrphans) {
|
||||
const adopted = skuRows.value.some((r) => r.key === orphan.key);
|
||||
if (!adopted) {
|
||||
revokeUploadFiles(orphan.thumbFileList);
|
||||
}
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
message:
|
||||
|
||||
Reference in New Issue
Block a user