feat:代码优化与Mock数据清理

This commit is contained in:
liailing1026
2026-01-30 15:27:00 +08:00
parent 6e4d8f0b6d
commit 1682a8892d
24 changed files with 1364 additions and 3193 deletions

View File

@@ -1,21 +1,7 @@
import request from '@/utils/request'
import websocket from '@/utils/websocket'
import type { Agent, IApiStepTask, IRawPlanResponse, IRawStepTask } from '@/stores'
import {
mockBackendAgentSelectModifyInit,
mockBackendAgentSelectModifyAddAspect,
type BackendAgentScoreResponse,
} from '@/layout/components/Main/TaskTemplate/TaskSyllabus/components/mock/AgentAssignmentBackendMock'
import {
mockBackendFillAgentTaskProcess,
type RawAgentTaskProcessResponse,
} from '@/layout/components/Main/TaskTemplate/TaskProcess/components/mock/AgentTaskProcessBackendMock'
import { mockBranchPlanOutlineAPI } from '@/layout/components/Main/TaskTemplate/TaskSyllabus/Branch/mock/branchPlanOutlineMock'
import { mockFillStepTaskAPI } from '@/layout/components/Main/TaskTemplate/TaskSyllabus/Branch/mock/fill-step-task-mock'
import {
mockBranchTaskProcessAPI,
type BranchAction,
} from '@/layout/components/Main/TaskTemplate/TaskSyllabus/Branch/mock/branchTaskProcessMock'
import { withRetry } from '@/utils/retry'
export interface ActionHistory {
ID: string
@@ -26,6 +12,14 @@ export interface ActionHistory {
Action_Result: string
}
export interface BranchAction {
ID: string
ActionType: string
AgentName: string
Description: string
ImportantInput: string[]
}
export type IExecuteRawResponse = {
LogNodeType: string
NodeId: string
@@ -86,7 +80,10 @@ class Api {
// 默认使用WebSocket
private useWebSocketDefault = true
setAgents = (data: Pick<Agent, 'Name' | 'Profile' | 'apiUrl' | 'apiKey' | 'apiModel'>[], useWebSocket: boolean = this.useWebSocketDefault) => {
setAgents = (
data: Pick<Agent, 'Name' | 'Profile' | 'apiUrl' | 'apiKey' | 'apiModel'>[],
useWebSocket: boolean = this.useWebSocketDefault,
) => {
// 如果启用WebSocket且已连接使用WebSocket
if (useWebSocket && websocket.connected) {
return websocket.send('set_agents', data)
@@ -107,19 +104,29 @@ class Api {
apiKey?: string
apiModel?: string
useWebSocket?: boolean
onProgress?: (progress: { status: string; stage?: string; message?: string; [key: string]: any }) => void
onProgress?: (progress: {
status: string
stage?: string
message?: string
[key: string]: any
}) => void
}) => {
const useWs = data.useWebSocket !== undefined ? data.useWebSocket : this.useWebSocketDefault
// 如果启用WebSocket且已连接使用WebSocket
if (useWs && websocket.connected) {
return websocket.send('generate_base_plan', {
'General Goal': data.goal,
'Initial Input Object': data.inputs,
apiUrl: data.apiUrl,
apiKey: data.apiKey,
apiModel: data.apiModel,
}, undefined, data.onProgress)
return websocket.send(
'generate_base_plan',
{
'General Goal': data.goal,
'Initial Input Object': data.inputs,
apiUrl: data.apiUrl,
apiKey: data.apiKey,
apiModel: data.apiModel,
},
undefined,
data.onProgress,
)
}
// 否则使用REST API
@@ -180,18 +187,18 @@ class Api {
enableDynamic?: boolean,
onExecutionStarted?: (executionId: string) => void,
executionId?: string,
restartFromStepIndex?: number, // 新增:从指定步骤重新执行的索引
rehearsalLog?: any[], // 新增:传递截断后的 RehearsalLog
restartFromStepIndex?: number, // 新增:从指定步骤重新执行的索引
rehearsalLog?: any[], // 新增:传递截断后的 RehearsalLog
) => {
const useWs = useWebSocket !== undefined ? useWebSocket : this.useWebSocketDefault
const data = {
RehearsalLog: rehearsalLog || [], // ✅ 使用传递的 RehearsalLog
RehearsalLog: rehearsalLog || [], // ✅ 使用传递的 RehearsalLog
num_StepToRun: null,
existingKeyObjects: existingKeyObjects || {},
enable_dynamic: enableDynamic || false,
execution_id: executionId || null,
restart_from_step_index: restartFromStepIndex ?? null, // 新增:传递重新执行索引
restart_from_step_index: restartFromStepIndex ?? null, // 新增:传递重新执行索引
plan: {
'Initial Input Object': plan['Initial Input Object'],
'General Goal': plan['General Goal'],
@@ -253,7 +260,7 @@ class Api {
// onError
(error) => {
onError?.(error)
}
},
)
return
}
@@ -323,20 +330,30 @@ class Api {
initialInputs: string[]
goal: string
useWebSocket?: boolean
onProgress?: (progress: { status: string; stage?: string; message?: string; [key: string]: any }) => void
onProgress?: (progress: {
status: string
stage?: string
message?: string
[key: string]: any
}) => void
}) => {
const useWs = data.useWebSocket !== undefined ? data.useWebSocket : this.useWebSocketDefault
// 如果启用WebSocket且已连接使用WebSocket
if (useWs && websocket.connected) {
return websocket.send('branch_plan_outline', {
branch_Number: data.branch_Number,
Modification_Requirement: data.Modification_Requirement,
Existing_Steps: data.Existing_Steps,
Baseline_Completion: data.Baseline_Completion,
'Initial Input Object': data.initialInputs,
'General Goal': data.goal,
}, undefined, data.onProgress)
return websocket.send(
'branch_plan_outline',
{
branch_Number: data.branch_Number,
Modification_Requirement: data.Modification_Requirement,
Existing_Steps: data.Existing_Steps,
Baseline_Completion: data.Baseline_Completion,
'Initial Input Object': data.initialInputs,
'General Goal': data.goal,
},
undefined,
data.onProgress,
)
}
// 否则使用REST API
@@ -365,20 +382,30 @@ class Api {
stepTaskExisting: any
goal: string
useWebSocket?: boolean
onProgress?: (progress: { status: string; stage?: string; message?: string; [key: string]: any }) => void
onProgress?: (progress: {
status: string
stage?: string
message?: string
[key: string]: any
}) => void
}) => {
const useWs = data.useWebSocket !== undefined ? data.useWebSocket : this.useWebSocketDefault
// 如果启用WebSocket且已连接使用WebSocket
if (useWs && websocket.connected) {
return websocket.send('branch_task_process', {
branch_Number: data.branch_Number,
Modification_Requirement: data.Modification_Requirement,
Existing_Steps: data.Existing_Steps,
Baseline_Completion: data.Baseline_Completion,
stepTaskExisting: data.stepTaskExisting,
'General Goal': data.goal,
}, undefined, data.onProgress)
return websocket.send(
'branch_task_process',
{
branch_Number: data.branch_Number,
Modification_Requirement: data.Modification_Requirement,
Existing_Steps: data.Existing_Steps,
Baseline_Completion: data.Baseline_Completion,
stepTaskExisting: data.stepTaskExisting,
'General Goal': data.goal,
},
undefined,
data.onProgress,
)
}
// 否则使用REST API
@@ -400,20 +427,30 @@ class Api {
goal: string
stepTask: any
useWebSocket?: boolean
onProgress?: (progress: { status: string; stage?: string; message?: string; [key: string]: any }) => void
onProgress?: (progress: {
status: string
stage?: string
message?: string
[key: string]: any
}) => void
}): Promise<IRawStepTask> => {
const useWs = data.useWebSocket !== undefined ? data.useWebSocket : this.useWebSocketDefault
let response: any
// 如果启用WebSocket且已连接使用WebSocket
if (useWs && websocket.connected) {
response = await websocket.send('fill_step_task', {
'General Goal': data.goal,
stepTask: data.stepTask,
}, undefined, data.onProgress)
} else {
// 定义实际的 API 调用逻辑
const executeRequest = async (): Promise<any> => {
if (useWs && websocket.connected) {
return await websocket.send(
'fill_step_task',
{
'General Goal': data.goal,
stepTask: data.stepTask,
},
undefined,
data.onProgress,
)
}
// 否则使用REST API
response = await request<
return await request<
{
'General Goal': string
stepTask: any
@@ -446,6 +483,15 @@ class Api {
})
}
// 使用重试机制执行请求
const response = await withRetry(executeRequest, {
maxRetries: 3,
initialDelayMs: 2000,
onRetry: (error, attempt, delay) => {
console.warn(`⚠️ [fillStepTask] 第${attempt}次重试,等待 ${delay}ms...`, error?.message)
},
})
const vec2Hsl = (color: number[]): string => {
const [h, s, l] = color
return `hsl(${h}, ${s}%, ${l}%)`
@@ -455,9 +501,9 @@ class Api {
if (response.Collaboration_Brief_FrontEnd?.data) {
for (const [key, value] of Object.entries(response.Collaboration_Brief_FrontEnd.data)) {
briefData[key] = {
text: value.text,
text: (value as { text: string; color: number[] }).text,
style: {
background: vec2Hsl(value.color),
background: vec2Hsl((value as { text: string; color: number[] }).color),
},
}
}
@@ -485,26 +531,36 @@ class Api {
stepTask: IApiStepTask
agents: string[]
useWebSocket?: boolean
onProgress?: (progress: { status: string; stage?: string; message?: string; [key: string]: any }) => void
onProgress?: (progress: {
status: string
stage?: string
message?: string
[key: string]: any
}) => void
}): Promise<IApiStepTask> => {
const useWs = data.useWebSocket !== undefined ? data.useWebSocket : this.useWebSocketDefault
let response: any
// 如果启用WebSocket且已连接使用WebSocket
if (useWs && websocket.connected) {
response = await websocket.send('fill_step_task_process', {
'General Goal': data.goal,
stepTask_lackTaskProcess: {
StepName: data.stepTask.name,
TaskContent: data.stepTask.content,
InputObject_List: data.stepTask.inputs,
OutputObject: data.stepTask.output,
AgentSelection: data.agents,
},
}, undefined, data.onProgress)
} else {
// 定义实际的 API 调用逻辑
const executeRequest = async (): Promise<any> => {
if (useWs && websocket.connected) {
return await websocket.send(
'fill_step_task_process',
{
'General Goal': data.goal,
stepTask_lackTaskProcess: {
StepName: data.stepTask.name,
TaskContent: data.stepTask.content,
InputObject_List: data.stepTask.inputs,
OutputObject: data.stepTask.output,
AgentSelection: data.agents,
},
},
undefined,
data.onProgress,
)
}
// 否则使用REST API
response = await request<
return await request<
{
'General Goal': string
stepTask_lackTaskProcess: {
@@ -549,6 +605,15 @@ class Api {
})
}
// 使用重试机制执行请求
const response = await withRetry(executeRequest, {
maxRetries: 3,
initialDelayMs: 2000,
onRetry: (error, attempt, delay) => {
console.warn(`⚠️ [fillStepTaskTaskProcess] 第${attempt}次重试,等待 ${delay}ms...`, error?.message)
},
})
const vec2Hsl = (color: number[]): string => {
const [h, s, l] = color
return `hsl(${h}, ${s}%, ${l}%)`
@@ -558,9 +623,9 @@ class Api {
if (response.Collaboration_Brief_FrontEnd?.data) {
for (const [key, value] of Object.entries(response.Collaboration_Brief_FrontEnd.data)) {
briefData[key] = {
text: value.text,
text: (value as { text: string; color: number[] }).text,
style: {
background: vec2Hsl(value.color),
background: vec2Hsl((value as { text: string; color: number[] }).color),
},
}
}
@@ -589,31 +654,51 @@ class Api {
}
/**
* 为每个智能体评分
* 为每个智能体评分(带重试机制)
*/
agentSelectModifyInit = async (data: {
goal: string
stepTask: any
useWebSocket?: boolean
onProgress?: (progress: { status: string; stage?: string; message?: string; [key: string]: any }) => void
onProgress?: (progress: {
status: string
stage?: string
message?: string
[key: string]: any
}) => void
}): Promise<Record<string, Record<string, { reason: string; score: number }>>> => {
const useWs = data.useWebSocket !== undefined ? data.useWebSocket : this.useWebSocketDefault
let response: Record<string, Record<string, { Reason: string; Score: number }>>
// 如果启用WebSocket且已连接使用WebSocket
if (useWs && websocket.connected) {
response = await websocket.send('agent_select_modify_init', {
'General Goal': data.goal,
stepTask: {
StepName: data.stepTask.StepName || data.stepTask.name,
TaskContent: data.stepTask.TaskContent || data.stepTask.content,
InputObject_List: data.stepTask.InputObject_List || data.stepTask.inputs,
OutputObject: data.stepTask.OutputObject || data.stepTask.output,
},
}, undefined, data.onProgress)
} else {
// 调试日志:打印请求参数
const requestPayload = {
'General Goal': data.goal,
stepTask: {
StepName: data.stepTask.StepName || data.stepTask.name,
TaskContent: data.stepTask.TaskContent || data.stepTask.content,
InputObject_List: data.stepTask.InputObject_List || data.stepTask.inputs,
OutputObject: data.stepTask.OutputObject || data.stepTask.output,
},
}
console.log('🔍 [agentSelectModifyInit] 请求参数:', {
goal: requestPayload['General Goal'],
stepTaskName: requestPayload.stepTask.StepName,
stepTaskContentLength: requestPayload.stepTask.TaskContent?.length,
useWebSocket: useWs && websocket.connected,
wsConnected: websocket.connected,
})
// 定义实际的 API 调用逻辑
const executeRequest = async (): Promise<Record<string, Record<string, { Reason: string; Score: number }>>> => {
if (useWs && websocket.connected) {
return await websocket.send(
'agent_select_modify_init',
requestPayload,
undefined,
data.onProgress,
)
}
// 否则使用REST API
response = await request<
return await request<
{
'General Goal': string
stepTask: any
@@ -622,18 +707,19 @@ class Api {
>({
url: '/agentSelectModify_init',
method: 'POST',
data: {
'General Goal': data.goal,
stepTask: {
StepName: data.stepTask.StepName || data.stepTask.name,
TaskContent: data.stepTask.TaskContent || data.stepTask.content,
InputObject_List: data.stepTask.InputObject_List || data.stepTask.inputs,
OutputObject: data.stepTask.OutputObject || data.stepTask.output,
},
},
data: requestPayload,
})
}
// 使用重试机制执行请求
const response = await withRetry(executeRequest, {
maxRetries: 3,
initialDelayMs: 2000,
onRetry: (error, attempt, delay) => {
console.warn(`⚠️ [agentSelectModifyInit] 第${attempt}次重试,等待 ${delay}ms...`, error?.message)
},
})
const transformedData: Record<string, Record<string, { reason: string; score: number }>> = {}
for (const [aspect, agents] of Object.entries(response)) {
@@ -657,7 +743,12 @@ class Api {
agentSelectModifyAddAspect = async (data: {
aspectList: string[]
useWebSocket?: boolean
onProgress?: (progress: { status: string; stage?: string; message?: string; [key: string]: any }) => void
onProgress?: (progress: {
status: string
stage?: string
message?: string
[key: string]: any
}) => void
}): Promise<{
aspectName: string
agentScores: Record<string, { score: number; reason: string }>
@@ -667,9 +758,14 @@ class Api {
// 如果启用WebSocket且已连接使用WebSocket
if (useWs && websocket.connected) {
response = await websocket.send('agent_select_modify_add_aspect', {
aspectList: data.aspectList,
}, undefined, data.onProgress)
response = await websocket.send(
'agent_select_modify_add_aspect',
{
aspectList: data.aspectList,
},
undefined,
data.onProgress,
)
} else {
// 否则使用REST API
response = await request<
@@ -711,164 +807,6 @@ class Api {
agentScores,
}
}
/**
* ==================== Mock API开发阶段使用====================
*为每个智能体评分
*/
mockAgentSelectModifyInit = async (): Promise<
Record<string, Record<string, { reason: string; score: number }>>
> => {
const response: BackendAgentScoreResponse = await mockBackendAgentSelectModifyInit()
const transformedData: Record<string, Record<string, { reason: string; score: number }>> = {}
for (const [aspect, agents] of Object.entries(response)) {
for (const [agentName, scoreInfo] of Object.entries(agents)) {
if (!transformedData[agentName]) {
transformedData[agentName] = {}
}
transformedData[agentName][aspect] = {
reason: scoreInfo.Reason,
score: scoreInfo.Score,
}
}
}
return transformedData
}
mockAgentSelectModifyAddAspect = async (data: {
aspectList: string[]
}): Promise<{
aspectName: string
agentScores: Record<string, { score: number; reason: string }>
}> => {
const response: BackendAgentScoreResponse = await mockBackendAgentSelectModifyAddAspect(
data.aspectList,
)
const newAspect = data.aspectList[data.aspectList.length - 1]
if (!newAspect) {
throw new Error('aspectList is empty')
}
const newAspectAgents = response[newAspect]
const agentScores: Record<string, { score: number; reason: string }> = {}
if (newAspectAgents) {
for (const [agentName, scoreInfo] of Object.entries(newAspectAgents)) {
agentScores[agentName] = {
score: scoreInfo.Score,
reason: scoreInfo.Reason,
}
}
}
return {
aspectName: newAspect,
agentScores,
}
}
mockFillStepTaskTaskProcess = async (data: {
goal: string
stepTask: IApiStepTask
agents: string[]
}): Promise<IApiStepTask> => {
const response: RawAgentTaskProcessResponse = await mockBackendFillAgentTaskProcess(
data.goal,
data.stepTask,
data.agents,
)
const vec2Hsl = (color: number[]): string => {
const [h, s, l] = color
return `hsl(${h}, ${s}%, ${l}%)`
}
const briefData: Record<string, { text: string; style: { background: string } }> = {}
if (response.Collaboration_Brief_frontEnd?.data) {
for (const [key, value] of Object.entries(response.Collaboration_Brief_frontEnd.data)) {
briefData[key] = {
text: value.text,
style: {
background: vec2Hsl(value.color),
},
}
}
}
const process = (response.TaskProcess || []).map((action) => ({
id: action.ID,
type: action.ActionType,
agent: action.AgentName,
description: action.Description,
inputs: action.ImportantInput,
}))
return {
name: response.StepName || '',
content: response.TaskContent || '',
inputs: response.InputObject_List || [],
output: response.OutputObject || '',
agents: response.AgentSelection || [],
brief: {
template: response.Collaboration_Brief_frontEnd?.template || '',
data: briefData,
},
process,
}
}
mockBranchPlanOutline = async (data: {
branch_Number: number
Modification_Requirement: string
Existing_Steps: IRawStepTask[]
Baseline_Completion: number
initialInputs: string[]
goal: string
}): Promise<IRawPlanResponse> => {
const response = await mockBranchPlanOutlineAPI({
branch_Number: data.branch_Number,
Modification_Requirement: data.Modification_Requirement,
Existing_Steps: data.Existing_Steps,
Baseline_Completion: data.Baseline_Completion,
InitialObject_List: data.initialInputs,
General_Goal: data.goal,
})
return response
}
mockFillStepTask = async (data: { goal: string; stepTask: any }): Promise<any> => {
const response = await mockFillStepTaskAPI({
General_Goal: data.goal,
stepTask: data.stepTask,
})
return response
}
mockBranchTaskProcess = async (data: {
branch_Number: number
Modification_Requirement: string
Existing_Steps: BranchAction[]
Baseline_Completion: number
stepTaskExisting: any
goal: string
}): Promise<BranchAction[][]> => {
const response = await mockBranchTaskProcessAPI({
branch_Number: data.branch_Number,
Modification_Requirement: data.Modification_Requirement,
Existing_Steps: data.Existing_Steps,
Baseline_Completion: data.Baseline_Completion,
stepTaskExisting: data.stepTaskExisting,
General_Goal: data.goal,
})
return response
}
/**
* 向正在执行的任务追加新步骤
* @param executionId 执行ID
@@ -880,16 +818,16 @@ class Api {
throw new Error('WebSocket未连接')
}
const response = await websocket.send('add_steps_to_execution', {
const response = (await websocket.send('add_steps_to_execution', {
execution_id: executionId,
new_steps: newSteps.map(step => ({
new_steps: newSteps.map((step) => ({
StepName: step.StepName,
TaskContent: step.TaskContent,
InputObject_List: step.InputObject_List,
OutputObject: step.OutputObject,
AgentSelection: step.AgentSelection,
Collaboration_Brief_frontEnd: step.Collaboration_Brief_frontEnd,
TaskProcess: step.TaskProcess.map(action => ({
TaskProcess: step.TaskProcess.map((action) => ({
ActionType: action.ActionType,
AgentName: action.AgentName,
Description: action.Description,
@@ -897,7 +835,7 @@ class Api {
ImportantInput: action.ImportantInput,
})),
})),
}) as { added_count: number }
})) as { added_count: number }
return response?.added_count || 0
}