mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 13:49:19 +08:00
feat: 拼多多发布页接入场景智能体与表单改写工具
This commit is contained in:
@@ -5,10 +5,15 @@ import { requestClient } from '#/api/request';
|
||||
/** Agent 服务走 /api/agent,开发态由 Vite 代理到 :8200 */
|
||||
|
||||
export namespace AgentVO {
|
||||
/** general=经营助手;ecom_goods_publish=拼多多商品发布 */
|
||||
export type SessionScene = 'general' | 'ecom_goods_publish' | string;
|
||||
|
||||
export interface Session {
|
||||
threadId: string;
|
||||
title: string;
|
||||
status: string;
|
||||
scene?: SessionScene;
|
||||
sceneRef?: string | null;
|
||||
llmProviderId?: number | null;
|
||||
llmModel?: string | null;
|
||||
createdAt?: string;
|
||||
@@ -16,6 +21,14 @@ export namespace AgentVO {
|
||||
lastMessageAt?: string | null;
|
||||
}
|
||||
|
||||
/** SSE client_tool:前端执行后模型侧已乐观回传 */
|
||||
export interface ClientToolCall {
|
||||
toolCallId: string;
|
||||
name: string;
|
||||
args: Record<string, unknown>;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export interface Message {
|
||||
id?: string;
|
||||
seq: number;
|
||||
@@ -60,19 +73,30 @@ export namespace AgentVO {
|
||||
}
|
||||
}
|
||||
|
||||
export async function listAgentSessionsApi() {
|
||||
return requestClient.get<{ items: AgentVO.Session[] }>('/agent/sessions');
|
||||
export async function listAgentSessionsApi(options?: {
|
||||
scene?: AgentVO.SessionScene;
|
||||
}) {
|
||||
return requestClient.get<{ items: AgentVO.Session[] }>('/agent/sessions', {
|
||||
params: { scene: options?.scene ?? 'general' },
|
||||
});
|
||||
}
|
||||
|
||||
export async function createAgentSessionApi(options?: {
|
||||
title?: string;
|
||||
llmProviderId?: number;
|
||||
llmModel?: string;
|
||||
scene?: AgentVO.SessionScene;
|
||||
sceneRef?: string;
|
||||
/** 同 scene+sceneRef 已有活跃会话则复用 */
|
||||
reuseBySceneRef?: boolean;
|
||||
}) {
|
||||
return requestClient.post<AgentVO.Session>('/agent/sessions', {
|
||||
title: options?.title,
|
||||
llmProviderId: options?.llmProviderId,
|
||||
llmModel: options?.llmModel,
|
||||
scene: options?.scene,
|
||||
sceneRef: options?.sceneRef,
|
||||
reuseBySceneRef: options?.reuseBySceneRef,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -189,12 +213,16 @@ export async function probeAgentLlmModelsApi(body: {
|
||||
export function streamAgentChat(options: {
|
||||
threadId: string;
|
||||
content: string;
|
||||
/** 发布场景:当前表单快照,供 ui_get_publish_snapshot */
|
||||
formSnapshot?: Record<string, unknown>;
|
||||
onToken: (text: string) => void;
|
||||
onTool?: (payload: {
|
||||
phase: string;
|
||||
name?: string;
|
||||
label: string;
|
||||
}) => void;
|
||||
/** 前端工具:乐观执行改表单 */
|
||||
onClientTool?: (call: AgentVO.ClientToolCall) => void;
|
||||
onDone?: () => void;
|
||||
onError?: (message: string) => void;
|
||||
}): AbortController {
|
||||
@@ -212,7 +240,12 @@ export function streamAgentChat(options: {
|
||||
Accept: 'text/event-stream',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
},
|
||||
body: JSON.stringify({ content: options.content }),
|
||||
body: JSON.stringify({
|
||||
content: options.content,
|
||||
...(options.formSnapshot
|
||||
? { formSnapshot: options.formSnapshot }
|
||||
: {}),
|
||||
}),
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!res.ok || !res.body) {
|
||||
@@ -263,6 +296,25 @@ export function streamAgentChat(options: {
|
||||
} catch {
|
||||
/* ignore malformed tool events */
|
||||
}
|
||||
} else if (event === 'client_tool') {
|
||||
try {
|
||||
const parsed = JSON.parse(data) as {
|
||||
toolCallId?: string;
|
||||
name?: string;
|
||||
args?: Record<string, unknown>;
|
||||
label?: string;
|
||||
};
|
||||
if (parsed.name) {
|
||||
options.onClientTool?.({
|
||||
toolCallId: parsed.toolCallId || parsed.name,
|
||||
name: parsed.name,
|
||||
args: parsed.args || {},
|
||||
label: parsed.label,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
/* ignore malformed client_tool events */
|
||||
}
|
||||
} else if (event === 'error') {
|
||||
try {
|
||||
const parsed = JSON.parse(data) as { message?: string };
|
||||
|
||||
@@ -3,7 +3,11 @@ import { computed, ref } from 'vue';
|
||||
import { defineStore } from 'pinia';
|
||||
|
||||
/** 三套业务侧栏各自一份布局,互不影响 */
|
||||
export type ColSidebarKind = 'company' | 'ec-shop' | 'pdd-shop';
|
||||
export type ColSidebarKind =
|
||||
| 'company'
|
||||
| 'ec-shop'
|
||||
| 'pdd-shop'
|
||||
| 'pdd-publish-agent';
|
||||
|
||||
export interface ColSidebarLayout {
|
||||
/** 展开宽度(百分比) */
|
||||
@@ -16,11 +20,17 @@ const DEFAULT_LAYOUT: ColSidebarLayout = {
|
||||
collapsed: false,
|
||||
};
|
||||
|
||||
const AGENT_DEFAULT_LAYOUT: ColSidebarLayout = {
|
||||
width: 28,
|
||||
collapsed: false,
|
||||
};
|
||||
|
||||
function createDefaultLayouts(): Record<ColSidebarKind, ColSidebarLayout> {
|
||||
return {
|
||||
'ec-shop': { ...DEFAULT_LAYOUT },
|
||||
'pdd-shop': { ...DEFAULT_LAYOUT },
|
||||
company: { ...DEFAULT_LAYOUT },
|
||||
'pdd-publish-agent': { ...AGENT_DEFAULT_LAYOUT },
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -190,7 +190,7 @@ function onSessionClick(threadId: string) {
|
||||
async function refreshSessions() {
|
||||
loadingSessions.value = true;
|
||||
try {
|
||||
const res = await listAgentSessionsApi();
|
||||
const res = await listAgentSessionsApi({ scene: 'general' });
|
||||
sessions.value = res.items || [];
|
||||
if (!composingNew.value && !activeThreadId.value && sessions.value[0]) {
|
||||
activeThreadId.value = sessions.value[0].threadId;
|
||||
@@ -281,6 +281,7 @@ async function ensureSession(): Promise<string | null> {
|
||||
const s = await createAgentSessionApi({
|
||||
llmProviderId: parsed?.providerId,
|
||||
llmModel: parsed?.model,
|
||||
scene: 'general',
|
||||
});
|
||||
composingNew.value = false;
|
||||
sessions.value = [s, ...sessions.value];
|
||||
|
||||
+130
@@ -2983,6 +2983,136 @@ function resetAll() {
|
||||
specIdCache.clear();
|
||||
}
|
||||
|
||||
/** —— 智能体命令面:读快照 / 执行 ui_* —— */
|
||||
|
||||
function getFormSnapshot() {
|
||||
return {
|
||||
goodsName: form.goodsName,
|
||||
goodsDesc: form.goodsDesc,
|
||||
pddShopId: form.pddShopId,
|
||||
catId: form.catId,
|
||||
marketPriceYuan: form.marketPriceYuan,
|
||||
costTemplateId: form.costTemplateId,
|
||||
shipmentLimitSecond: form.shipmentLimitSecond,
|
||||
twoPiecesDiscount: form.twoPiecesDiscount,
|
||||
specAxes: specAxes.value.map((a) => ({
|
||||
name: a.name,
|
||||
catalogKey: a.catalogKey,
|
||||
values: effectiveSpecValues(a).map((v) => labelOfAxisValue(a, v)),
|
||||
})),
|
||||
skuRows: skuRows.value.map((r) => ({
|
||||
skuName: r.skuName,
|
||||
outSkuSn: r.outSkuSn,
|
||||
quantity: r.quantity,
|
||||
weight: r.weight,
|
||||
saleValues: { ...r.saleValues },
|
||||
internalSkuId: r.internalSkuId,
|
||||
productName: r.productName,
|
||||
internalSkuName: r.internalSkuName,
|
||||
})),
|
||||
specCatalog: specCatalog.value.map((c) => ({
|
||||
name: c.name,
|
||||
catalogKey: c.catalogKey,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function applySetGoodsName(args: Record<string, unknown>) {
|
||||
const name = String(args.goodsName ?? '').trim();
|
||||
if (!name) return { ok: false, message: '标题为空' };
|
||||
form.goodsName = name.slice(0, 120);
|
||||
return { ok: true, message: `已写入标题:${form.goodsName}` };
|
||||
}
|
||||
|
||||
function applySetGoodsDesc(args: Record<string, unknown>) {
|
||||
form.goodsDesc = String(args.goodsDesc ?? '');
|
||||
return { ok: true, message: '已写入商品描述' };
|
||||
}
|
||||
|
||||
/** 按名称匹配类目规格目录;无目录时建自由轴 */
|
||||
function applySetSpecAxes(args: Record<string, unknown>) {
|
||||
const raw = args.axes;
|
||||
if (!Array.isArray(raw) || raw.length === 0) {
|
||||
return { ok: false, message: '规格轴为空' };
|
||||
}
|
||||
const maxAxes = Math.min(2, Math.max(1, specCatalog.value.length || 2));
|
||||
const limited = raw.slice(0, maxAxes);
|
||||
const usedCatalog = new Set<string>();
|
||||
const next: SpecAxis[] = [];
|
||||
|
||||
for (const item of limited) {
|
||||
if (!item || typeof item !== 'object') continue;
|
||||
const row = item as { name?: unknown; values?: unknown };
|
||||
const axisName = String(row.name ?? '').trim();
|
||||
const valuesRaw = Array.isArray(row.values) ? row.values : [];
|
||||
const labels = valuesRaw
|
||||
.map((v) => String(v ?? '').trim())
|
||||
.filter(Boolean);
|
||||
if (!axisName) continue;
|
||||
|
||||
const match =
|
||||
specCatalog.value.find(
|
||||
(c) =>
|
||||
!usedCatalog.has(c.catalogKey) &&
|
||||
(c.name === axisName || c.name.includes(axisName) || axisName.includes(c.name)),
|
||||
) ||
|
||||
specCatalog.value.find((c) => !usedCatalog.has(c.catalogKey));
|
||||
|
||||
if (match) {
|
||||
usedCatalog.add(match.catalogKey);
|
||||
const axis = createAxisFromCatalog(match);
|
||||
axis.selectedValues =
|
||||
labels.length > 0
|
||||
? labels.map((t) => resolveSpecValueToken(axis, t))
|
||||
: [''];
|
||||
next.push(axis);
|
||||
} else {
|
||||
const key = `agent_${axisName}_${specAxisRowSeq}`;
|
||||
next.push({
|
||||
rowId: specAxisRowSeq++,
|
||||
catalogKey: key,
|
||||
key,
|
||||
name: axisName,
|
||||
presetOptions: [],
|
||||
selectedValues: labels.length > 0 ? labels : [''],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (next.length === 0) {
|
||||
return { ok: false, message: '未能解析任何规格维' };
|
||||
}
|
||||
specAxes.value = next;
|
||||
syncSkuRowsFromSpecs();
|
||||
return {
|
||||
ok: true,
|
||||
message: `已设置 ${next.length} 个规格维,SKU 行 ${skuRows.value.length} 条`,
|
||||
};
|
||||
}
|
||||
|
||||
function applyClientTool(name: string, args: Record<string, unknown>) {
|
||||
switch (name) {
|
||||
case 'ui_get_publish_snapshot':
|
||||
return {
|
||||
ok: true,
|
||||
message: '快照已由请求体注入,无需前端写入',
|
||||
};
|
||||
case 'ui_set_goods_name':
|
||||
return applySetGoodsName(args);
|
||||
case 'ui_set_goods_desc':
|
||||
return applySetGoodsDesc(args);
|
||||
case 'ui_set_spec_axes':
|
||||
return applySetSpecAxes(args);
|
||||
default:
|
||||
return { ok: false, message: `未支持的前端工具:${name}` };
|
||||
}
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
getFormSnapshot,
|
||||
applyClientTool,
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
document.removeEventListener('pointerdown', onOverlayPointerDown, true);
|
||||
clearLocalImages();
|
||||
|
||||
@@ -0,0 +1,540 @@
|
||||
<script lang="ts" setup>
|
||||
/**
|
||||
* 拼多多发布页右侧智能体栏:一草稿一会话,执行 client_tool 改表单。
|
||||
*/
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
|
||||
import {
|
||||
MenuFoldOutlined,
|
||||
MenuUnfoldOutlined,
|
||||
SendOutlined,
|
||||
} from '@ant-design/icons-vue';
|
||||
import { Button, Empty, Input, Select, Spin, Tooltip, message } from 'ant-design-vue';
|
||||
import { ChatItem } from '@tdesign-vue-next/chat';
|
||||
import 'tdesign-vue-next/es/style/index.css';
|
||||
import '@tdesign-vue-next/chat/es/style/index.css';
|
||||
|
||||
import {
|
||||
createAgentSessionApi,
|
||||
listAgentEnabledLlmModelsApi,
|
||||
listAgentMessagesApi,
|
||||
patchAgentSessionApi,
|
||||
streamAgentChat,
|
||||
type AgentVO,
|
||||
} from '#/api/agent';
|
||||
|
||||
import type { PublishEditorAgentApi } from './publish-agent-commands';
|
||||
|
||||
defineOptions({ name: 'PddPublishAgentPanel' });
|
||||
|
||||
const props = defineProps<{
|
||||
draftId: number;
|
||||
collapsed?: boolean;
|
||||
/** 编辑器命令面(ref) */
|
||||
editorApi: PublishEditorAgentApi | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
expand: [];
|
||||
collapse: [];
|
||||
}>();
|
||||
|
||||
const SCENE = 'ecom_goods_publish' as const;
|
||||
|
||||
const starterPrompts = [
|
||||
'根据已填的 SKU 商家编码,找相似拼多多商品并生成标题',
|
||||
'参考渠道商品帮我整理规格轴',
|
||||
'把当前标题改得更适合拼多多搜索',
|
||||
];
|
||||
|
||||
type BubbleView = {
|
||||
id: string;
|
||||
role: 'user' | 'assistant';
|
||||
name: string;
|
||||
content: string;
|
||||
textLoading: boolean;
|
||||
};
|
||||
|
||||
const loadingSession = ref(true);
|
||||
const loadingMessages = ref(false);
|
||||
const sending = ref(false);
|
||||
const session = ref<AgentVO.Session | null>(null);
|
||||
const messages = ref<AgentVO.Message[]>([]);
|
||||
const streamingText = ref('');
|
||||
const toolStatusLabel = ref('');
|
||||
const toolStatusActive = ref(false);
|
||||
const draft = ref('');
|
||||
const enabledModels = ref<AgentVO.LlmModelItem[]>([]);
|
||||
const selectedModelKey = ref<string | undefined>(undefined);
|
||||
const patchingModel = ref(false);
|
||||
const messagePaneRef = ref<HTMLElement | null>(null);
|
||||
let abort: AbortController | null = null;
|
||||
let messagesLoadSeq = 0;
|
||||
|
||||
function modelKey(providerId: number, model: string) {
|
||||
return `${providerId}::${model}`;
|
||||
}
|
||||
|
||||
function parseModelKey(key: string | undefined) {
|
||||
if (!key) return null;
|
||||
const idx = key.indexOf('::');
|
||||
if (idx <= 0) return null;
|
||||
const providerId = Number(key.slice(0, idx));
|
||||
const model = key.slice(idx + 2);
|
||||
if (!Number.isFinite(providerId) || !model) return null;
|
||||
return { providerId, model };
|
||||
}
|
||||
|
||||
const modelOptions = computed(() => {
|
||||
const groups = new Map<
|
||||
string,
|
||||
{ label: string; options: Array<{ value: string; label: string }> }
|
||||
>();
|
||||
for (const m of enabledModels.value) {
|
||||
const gLabel = m.providerDisplayName || `提供商 #${m.providerId}`;
|
||||
const gKey = String(m.providerId);
|
||||
if (!groups.has(gKey)) {
|
||||
groups.set(gKey, { label: gLabel, options: [] });
|
||||
}
|
||||
groups.get(gKey)!.options.push({
|
||||
value: modelKey(m.providerId, m.model),
|
||||
label: m.label || m.model,
|
||||
});
|
||||
}
|
||||
return [...groups.values()];
|
||||
});
|
||||
|
||||
const showStarter = computed(
|
||||
() =>
|
||||
messages.value.length === 0 &&
|
||||
!loadingMessages.value &&
|
||||
!loadingSession.value,
|
||||
);
|
||||
|
||||
const bubbleViews = computed<BubbleView[]>(() =>
|
||||
messages.value.map((m, idx) => {
|
||||
const isStreamingAssistant =
|
||||
sending.value &&
|
||||
idx === messages.value.length - 1 &&
|
||||
m.role === 'assistant';
|
||||
const text = isStreamingAssistant
|
||||
? streamingText.value || m.content || ''
|
||||
: m.content || '';
|
||||
const role = m.role === 'user' ? 'user' : 'assistant';
|
||||
return {
|
||||
id: m.id || `${m.seq}-${idx}`,
|
||||
role,
|
||||
name: role === 'user' ? '我' : '发布助手',
|
||||
content: text,
|
||||
textLoading: isStreamingAssistant && !text && !toolStatusActive.value,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
function defaultModelKey() {
|
||||
const d = enabledModels.value.find((m) => m.isDefault);
|
||||
const pick = d || enabledModels.value[0];
|
||||
return pick ? modelKey(pick.providerId, pick.model) : undefined;
|
||||
}
|
||||
|
||||
function syncSelectedFromSession() {
|
||||
const s = session.value;
|
||||
if (s?.llmProviderId != null && s.llmModel) {
|
||||
selectedModelKey.value = modelKey(s.llmProviderId, s.llmModel);
|
||||
return;
|
||||
}
|
||||
if (!selectedModelKey.value) {
|
||||
selectedModelKey.value = defaultModelKey();
|
||||
}
|
||||
}
|
||||
|
||||
function scrollChatToBottom() {
|
||||
const el = messagePaneRef.value;
|
||||
if (!el) return;
|
||||
el.scrollTop = el.scrollHeight;
|
||||
}
|
||||
|
||||
async function loadEnabledModels() {
|
||||
try {
|
||||
const res = await listAgentEnabledLlmModelsApi();
|
||||
enabledModels.value = res.items || [];
|
||||
if (!selectedModelKey.value) {
|
||||
selectedModelKey.value = defaultModelKey();
|
||||
}
|
||||
} catch {
|
||||
/* 模型列表失败不阻断会话 */
|
||||
}
|
||||
}
|
||||
|
||||
/** 复用或创建本草稿的发布场景会话 */
|
||||
async function ensureSession(): Promise<string | null> {
|
||||
if (session.value?.threadId) return session.value.threadId;
|
||||
const parsed = parseModelKey(selectedModelKey.value);
|
||||
const s = await createAgentSessionApi({
|
||||
title: `发布草稿 #${props.draftId}`,
|
||||
llmProviderId: parsed?.providerId,
|
||||
llmModel: parsed?.model,
|
||||
scene: SCENE,
|
||||
sceneRef: String(props.draftId),
|
||||
reuseBySceneRef: true,
|
||||
});
|
||||
session.value = s;
|
||||
syncSelectedFromSession();
|
||||
return s.threadId;
|
||||
}
|
||||
|
||||
async function loadMessages(threadId: string) {
|
||||
const seq = ++messagesLoadSeq;
|
||||
loadingMessages.value = true;
|
||||
try {
|
||||
const res = await listAgentMessagesApi(threadId);
|
||||
if (seq !== messagesLoadSeq) return;
|
||||
messages.value = (res.items || []).filter(
|
||||
(m) => m.role === 'user' || m.role === 'assistant',
|
||||
);
|
||||
} catch (e: any) {
|
||||
if (seq !== messagesLoadSeq) return;
|
||||
message.error(e?.message || '加载消息失败');
|
||||
} finally {
|
||||
if (seq === messagesLoadSeq) loadingMessages.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function bootstrap() {
|
||||
loadingSession.value = true;
|
||||
messages.value = [];
|
||||
session.value = null;
|
||||
try {
|
||||
await loadEnabledModels();
|
||||
const threadId = await ensureSession();
|
||||
if (threadId) await loadMessages(threadId);
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '初始化发布助手失败');
|
||||
} finally {
|
||||
loadingSession.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.draftId,
|
||||
() => {
|
||||
abort?.abort();
|
||||
void bootstrap();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
async function onModelChange(key: string) {
|
||||
if (!key || !key.includes('::')) return;
|
||||
selectedModelKey.value = key;
|
||||
const parsed = parseModelKey(key);
|
||||
const threadId = session.value?.threadId;
|
||||
if (!threadId || !parsed) return;
|
||||
patchingModel.value = true;
|
||||
try {
|
||||
const s = await patchAgentSessionApi(threadId, {
|
||||
llmProviderId: parsed.providerId,
|
||||
llmModel: parsed.model,
|
||||
});
|
||||
session.value = { ...session.value!, ...s };
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '切换模型失败');
|
||||
syncSelectedFromSession();
|
||||
} finally {
|
||||
patchingModel.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function appendStreamToken(t: string) {
|
||||
if (toolStatusActive.value) {
|
||||
toolStatusActive.value = false;
|
||||
toolStatusLabel.value = '';
|
||||
}
|
||||
streamingText.value += t;
|
||||
const idx = messages.value.length - 1;
|
||||
const last = messages.value[idx];
|
||||
if (last?.role === 'assistant') {
|
||||
messages.value[idx] = { ...last, content: streamingText.value };
|
||||
}
|
||||
void nextTick().then(scrollChatToBottom);
|
||||
}
|
||||
|
||||
function onStreamTool(payload: { phase: string; label: string }) {
|
||||
if (payload.phase === 'start') {
|
||||
toolStatusActive.value = true;
|
||||
toolStatusLabel.value = payload.label;
|
||||
void nextTick().then(scrollChatToBottom);
|
||||
} else if (payload.phase === 'end') {
|
||||
toolStatusLabel.value = payload.label;
|
||||
}
|
||||
}
|
||||
|
||||
function onClientTool(call: AgentVO.ClientToolCall) {
|
||||
const api = props.editorApi;
|
||||
if (!api) return;
|
||||
if (call.name === 'ui_get_publish_snapshot') return;
|
||||
const result = api.applyClientTool(call.name, call.args || {});
|
||||
if (!result.ok) {
|
||||
message.warning(result.message || '表单写入失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function send(textOverride?: string) {
|
||||
const text = (textOverride ?? draft.value).trim();
|
||||
if (!text || sending.value) return;
|
||||
|
||||
sending.value = true;
|
||||
let threadId: string | undefined = session.value?.threadId;
|
||||
if (!threadId) {
|
||||
try {
|
||||
threadId = (await ensureSession()) ?? undefined;
|
||||
} catch (e: any) {
|
||||
sending.value = false;
|
||||
message.error(e?.message || '新建会话失败');
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!threadId) {
|
||||
sending.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
streamingText.value = '';
|
||||
toolStatusActive.value = false;
|
||||
toolStatusLabel.value = '';
|
||||
draft.value = '';
|
||||
messages.value.push({
|
||||
seq: (messages.value.at(-1)?.seq || 0) + 1,
|
||||
role: 'user',
|
||||
content: text,
|
||||
});
|
||||
messages.value.push({
|
||||
seq: (messages.value.at(-1)?.seq || 0) + 1,
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
});
|
||||
await nextTick();
|
||||
scrollChatToBottom();
|
||||
|
||||
const formSnapshot = props.editorApi?.getFormSnapshot() as
|
||||
| Record<string, unknown>
|
||||
| undefined;
|
||||
|
||||
abort?.abort();
|
||||
abort = streamAgentChat({
|
||||
threadId,
|
||||
content: text,
|
||||
formSnapshot,
|
||||
onToken: appendStreamToken,
|
||||
onTool: onStreamTool,
|
||||
onClientTool,
|
||||
onDone: () => {
|
||||
const finalText = streamingText.value;
|
||||
const idx = messages.value.length - 1;
|
||||
const last = messages.value[idx];
|
||||
if (last?.role === 'assistant') {
|
||||
messages.value[idx] = { ...last, content: finalText || last.content };
|
||||
}
|
||||
sending.value = false;
|
||||
streamingText.value = '';
|
||||
toolStatusActive.value = false;
|
||||
toolStatusLabel.value = '';
|
||||
},
|
||||
onError: (msg) => {
|
||||
sending.value = false;
|
||||
const idx = messages.value.length - 1;
|
||||
const last = messages.value[idx];
|
||||
if (last?.role === 'assistant' && !last.content && !streamingText.value) {
|
||||
messages.value[idx] = { ...last, content: `错误:${msg}` };
|
||||
}
|
||||
streamingText.value = '';
|
||||
toolStatusActive.value = false;
|
||||
toolStatusLabel.value = '';
|
||||
message.error(msg);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function applyStarterPrompt(text: string) {
|
||||
draft.value = text;
|
||||
}
|
||||
|
||||
function onStop() {
|
||||
abort?.abort();
|
||||
sending.value = false;
|
||||
toolStatusActive.value = false;
|
||||
toolStatusLabel.value = '';
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => abort?.abort());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- 收起:窄条 -->
|
||||
<div
|
||||
v-if="collapsed"
|
||||
class="border-border bg-card flex h-full w-14 shrink-0 flex-col items-center border-l py-3"
|
||||
>
|
||||
<Tooltip title="展开发布助手" placement="left">
|
||||
<Button type="text" @click="emit('expand')">
|
||||
<template #icon><MenuUnfoldOutlined /></template>
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<div
|
||||
class="text-muted-foreground mt-4 write-vertical-right text-xs tracking-widest"
|
||||
style="writing-mode: vertical-rl"
|
||||
>
|
||||
发布助手
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 展开 -->
|
||||
<aside
|
||||
v-else
|
||||
class="border-border bg-card flex h-full min-h-0 w-full min-w-[280px] flex-col border-l"
|
||||
>
|
||||
<header
|
||||
class="flex h-12 shrink-0 items-center gap-2 border-b border-border px-3"
|
||||
>
|
||||
<span class="min-w-0 flex-1 truncate text-sm font-medium">发布助手</span>
|
||||
<Select
|
||||
:value="selectedModelKey"
|
||||
:options="modelOptions"
|
||||
:loading="patchingModel"
|
||||
:disabled="sending || enabledModels.length === 0"
|
||||
placeholder="模型"
|
||||
class="w-36 shrink-0"
|
||||
size="small"
|
||||
:allow-clear="false"
|
||||
@change="(v) => onModelChange(String(v ?? ''))"
|
||||
/>
|
||||
<Tooltip title="收起">
|
||||
<Button type="text" size="small" @click="emit('collapse')">
|
||||
<template #icon><MenuFoldOutlined /></template>
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</header>
|
||||
|
||||
<div class="relative flex min-h-0 flex-1 flex-col">
|
||||
<div
|
||||
v-if="loadingSession || loadingMessages"
|
||||
class="absolute inset-0 z-10 flex items-center justify-center bg-background/50"
|
||||
>
|
||||
<Spin size="small" />
|
||||
</div>
|
||||
|
||||
<div
|
||||
ref="messagePaneRef"
|
||||
class="publish-agent-chat t-chat t-chat--normal min-h-0 flex-1 overflow-y-auto py-3"
|
||||
>
|
||||
<div
|
||||
v-if="showStarter"
|
||||
class="flex h-full flex-col justify-center px-1 py-4"
|
||||
>
|
||||
<div class="text-sm font-medium">帮你完善本页草稿</div>
|
||||
<p class="text-muted-foreground mt-2 text-xs leading-5">
|
||||
可按已填 SKU 编码查内部/拼多多商品,生成标题并写回规格轴。改表单会直接落到左侧编辑区。
|
||||
</p>
|
||||
<div class="mt-3 flex flex-col gap-1.5">
|
||||
<button
|
||||
v-for="item in starterPrompts"
|
||||
:key="item"
|
||||
type="button"
|
||||
class="hover:border-primary hover:bg-primary/5 rounded-md border border-border bg-background px-2.5 py-1.5 text-left text-xs transition-colors"
|
||||
@click="applyStarterPrompt(item)"
|
||||
>
|
||||
{{ item }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<Empty
|
||||
v-else-if="!loadingSession && !loadingMessages && messages.length === 0"
|
||||
class="mt-16"
|
||||
description="开始提问吧"
|
||||
/>
|
||||
<ChatItem
|
||||
v-for="item in bubbleViews"
|
||||
:key="item.id"
|
||||
class="publish-agent-item"
|
||||
:role="item.role"
|
||||
:name="item.name"
|
||||
:content="item.content"
|
||||
:text-loading="item.textLoading"
|
||||
variant="base"
|
||||
animation="gradient"
|
||||
/>
|
||||
<div
|
||||
v-if="toolStatusActive && toolStatusLabel"
|
||||
class="text-muted-foreground flex items-center gap-2 px-1 py-1 text-xs"
|
||||
>
|
||||
<span
|
||||
class="border-primary/40 inline-block size-3 animate-spin rounded-full border-2 border-t-transparent"
|
||||
/>
|
||||
<span>{{ toolStatusLabel }}…</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="shrink-0 border-t border-border p-2">
|
||||
<div class="flex gap-1.5">
|
||||
<Input.TextArea
|
||||
v-model:value="draft"
|
||||
:auto-size="{ minRows: 2, maxRows: 5 }"
|
||||
:disabled="sending"
|
||||
placeholder="描述你想改的标题、规格…"
|
||||
class="flex-1"
|
||||
@keydown.enter.exact.prevent="() => send()"
|
||||
/>
|
||||
<div class="flex flex-col gap-1">
|
||||
<Button
|
||||
v-if="sending"
|
||||
type="default"
|
||||
size="small"
|
||||
@click="onStop"
|
||||
>
|
||||
停止
|
||||
</Button>
|
||||
<Button
|
||||
v-else
|
||||
type="primary"
|
||||
size="small"
|
||||
:disabled="!draft.trim()"
|
||||
@click="() => send()"
|
||||
>
|
||||
<template #icon><SendOutlined /></template>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/*
|
||||
* TDesign `.t-chat { padding: 0 }` 会盖掉 Tailwind px-*,容器左右留白写这里。
|
||||
* 不要动 `.t-chat__detail` 的 padding,那是气泡内文字边距。
|
||||
*/
|
||||
.publish-agent-chat.t-chat {
|
||||
--td-bg-color-container: transparent;
|
||||
padding: 12px 16px !important;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.publish-agent-item {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.publish-agent-item :deep(.t-chat__inner) {
|
||||
box-sizing: border-box;
|
||||
padding-inline: 4px;
|
||||
}
|
||||
.publish-agent-item :deep(.t-chat__content) {
|
||||
width: auto;
|
||||
max-width: calc(100% - 8px);
|
||||
}
|
||||
.publish-agent-item :deep(.t-chat__inner.user) {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.publish-agent-item :deep(.t-chat__avatar),
|
||||
.publish-agent-item :deep(.t-chat__name) {
|
||||
display: none;
|
||||
}
|
||||
</style>
|
||||
@@ -1,10 +1,14 @@
|
||||
<script lang="ts" setup>
|
||||
import { computed } from 'vue';
|
||||
import { computed, ref } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
|
||||
import { useColSidebarLayout } from '#/store/col-sidebar-layout';
|
||||
|
||||
import PddGoodsPublishEditor from '../components/PddGoodsPublishEditor.vue';
|
||||
import PddPublishAgentPanel from './PddPublishAgentPanel.vue';
|
||||
import type { PublishEditorAgentApi } from './publish-agent-commands';
|
||||
|
||||
defineOptions({ name: 'PddGoodsPublishDeskEdit' });
|
||||
|
||||
@@ -17,6 +21,23 @@ const draftId = computed(() => {
|
||||
return Number.isFinite(n) ? n : null;
|
||||
});
|
||||
|
||||
const editorRef = ref<PublishEditorAgentApi | null>(null);
|
||||
const { width: agentWidthPct, collapsed: agentCollapsed } =
|
||||
useColSidebarLayout('pdd-publish-agent');
|
||||
|
||||
const agentPaneStyle = computed(() => {
|
||||
if (agentCollapsed.value) {
|
||||
return { width: '56px', flex: '0 0 56px' };
|
||||
}
|
||||
const pct = Math.min(42, Math.max(22, agentWidthPct.value));
|
||||
return {
|
||||
width: `${pct}%`,
|
||||
flex: `0 0 ${pct}%`,
|
||||
maxWidth: '480px',
|
||||
minWidth: '300px',
|
||||
};
|
||||
});
|
||||
|
||||
function goBack() {
|
||||
void router.push('/pdd/goods/publish');
|
||||
}
|
||||
@@ -47,15 +68,35 @@ function goBack() {
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<PddGoodsPublishEditor
|
||||
<div
|
||||
v-if="draftId"
|
||||
class="h-full min-h-0"
|
||||
variant="page"
|
||||
:open="true"
|
||||
:draft-id="draftId"
|
||||
@close="goBack"
|
||||
@success="goBack"
|
||||
@draft-saved="() => undefined"
|
||||
/>
|
||||
class="flex min-h-0 flex-1 overflow-hidden"
|
||||
>
|
||||
<div class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
|
||||
<PddGoodsPublishEditor
|
||||
ref="editorRef"
|
||||
class="h-full min-h-0"
|
||||
variant="page"
|
||||
:open="true"
|
||||
:draft-id="draftId"
|
||||
@close="goBack"
|
||||
@success="goBack"
|
||||
@draft-saved="() => undefined"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
class="flex h-full min-h-0 shrink-0 flex-col overflow-hidden"
|
||||
:style="agentPaneStyle"
|
||||
>
|
||||
<PddPublishAgentPanel
|
||||
class="h-full min-h-0"
|
||||
:draft-id="draftId"
|
||||
:collapsed="agentCollapsed"
|
||||
:editor-api="editorRef"
|
||||
@expand="agentCollapsed = false"
|
||||
@collapse="agentCollapsed = true"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Page>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* 发布编辑器暴露给智能体栏的命令面:读快照 + 执行 ui_* 前端工具。
|
||||
*/
|
||||
|
||||
export type PublishSpecAxisSnapshot = {
|
||||
name: string;
|
||||
values: string[];
|
||||
catalogKey?: string;
|
||||
};
|
||||
|
||||
export type PublishSkuRowSnapshot = {
|
||||
skuName: string;
|
||||
outSkuSn: string;
|
||||
quantity: number;
|
||||
weight: number;
|
||||
saleValues: Record<string, string>;
|
||||
internalSkuId?: number;
|
||||
productName?: string;
|
||||
internalSkuName?: string;
|
||||
};
|
||||
|
||||
/** 注入 Agent 的表单快照(瘦字段,避免图片等大对象) */
|
||||
export type PublishFormSnapshot = {
|
||||
goodsName: string;
|
||||
goodsDesc: string;
|
||||
pddShopId?: number;
|
||||
catId?: number;
|
||||
marketPriceYuan?: number;
|
||||
costTemplateId?: number;
|
||||
shipmentLimitSecond?: number;
|
||||
twoPiecesDiscount?: number;
|
||||
specAxes: PublishSpecAxisSnapshot[];
|
||||
skuRows: PublishSkuRowSnapshot[];
|
||||
/** 当前类目可选规格维,便于模型选对轴名 */
|
||||
specCatalog: Array<{ name: string; catalogKey: string }>;
|
||||
};
|
||||
|
||||
export type ClientToolResult = {
|
||||
ok: boolean;
|
||||
message: string;
|
||||
};
|
||||
|
||||
/** 编辑器 defineExpose 契约 */
|
||||
export type PublishEditorAgentApi = {
|
||||
getFormSnapshot: () => PublishFormSnapshot;
|
||||
applyClientTool: (
|
||||
name: string,
|
||||
args: Record<string, unknown>,
|
||||
) => ClientToolResult;
|
||||
};
|
||||
Reference in New Issue
Block a user