feat(rohs-check): 新增 RoHS 对话轮次注册与检核批次绑定功能

This commit is contained in:
hugo committed 2026-06-15 16:30:17 +08:00
1 parent 9cba517bff
commit fa0cdee8df
20 files changed
+1050 -201

No files matched your search

@@ -1,231 +1,685 @@
/**
* 对话页:Agent tool_run_progress 能力轮询(RoHS 等异步任务进度卡片)。
* 依赖:useToolRunProgress、toolRunProgressConfig、ChatMessage。
* 逻辑:按助手消息 ChatLog.run_id 展示进度,每轮问答独立绑定。
* 逻辑:按助手消息 ChatLog.run_id 展示进度,每轮问答独立绑定;无 run_id 时不展示进度卡片。
*/
import { computed, nextTick, ref, watch } from 'vue';
import type { ToolRunProgress } from '@/api/toolRunProgress';
import { getToolRunProgress } from '@/api/toolRunProgress';
import type { ToolRunProgress } from '../api/toolRunProgress.api';
import { getToolRunProgress } from '../api/toolRunProgress.api';
import type { ToolRunProgressConfig } from '../composables/useToolRunProgress';
import type { ChatMessage } from '../types/chat.types';
import type { Ref } from 'vue';
import {
assistantMessageHasError,
collectAssistantRunIds,
buildLogProgressUrl,
collectAssistantProgressTargets,
getChatLogIdFromMessage,
getRunIdFromMessage,
isRunningToolRunStatus,
resolveLogProgressBaseUrl,
resolveScheduleTaskId,
resolveMessageAnchorKey,
} from '../utils/toolRunProgressConfig';
export interface ChatPageToolRunContext {
currentAgent: Ref<{ id?: number; extra_config?: Record<string, unknown> } | null>;
conversationId: Ref<string | null>;
messages: Ref<ChatMessage[]>;
}
export function useChatPageToolRun(ctx: ChatPageToolRunContext) {
const runsById = ref<Record<number, ToolRunProgress>>({});
const runErrors = ref<Record<number, string>>({});
const chatLogRunMap = ref<Record<number, number>>({});
const chatLogErrors = ref<Record<number, string>>({});
const pollingRunIds = ref<number[]>([]);
const pollingChatLogIds = ref<number[]>([]);
let pollTimer: number | undefined;
const rawToolRunConfig = computed(() => {
const extra = ctx.currentAgent.value?.extra_config || {};
const raw = extra.tool_run_progress;
return raw && typeof raw === 'object' ? (raw as ToolRunProgressConfig) : null;
});
const toolRunProgressConfig = computed<ToolRunProgressConfig | null>(() => {
const extra = ctx.currentAgent.value?.extra_config || {};
const capabilities = Array.isArray(extra.capabilities)
? extra.capabilities.map((item: unknown) => String(item))
: [];
if (!capabilities.includes('tool_run_progress')) return null;
const cfg = rawToolRunConfig.value;
if (!cfg) return null;
return {
...cfg,
schedule_task_id: resolveScheduleTaskId(cfg),
};
});
const boundScheduleTaskId = computed(() => resolveScheduleTaskId(rawToolRunConfig.value));
const clearPollTimer = () => {
if (pollTimer !== undefined) {
window.clearTimeout(pollTimer);
pollTimer = undefined;
}
};
const resolveDetailUrl = (runId: number) => {
const template = String(rawToolRunConfig.value?.detail_url_template || '').trim();
if (!template) return '';
return template.replace('{run_id}', encodeURIComponent(String(runId)));
};
const resolveForLogUrl = (chatLogId: number) => {
const taskId = boundScheduleTaskId.value;
if (!taskId) return '';
const base = resolveLogProgressBaseUrl(rawToolRunConfig.value || {});
return buildLogProgressUrl(base, taskId, chatLogId);
};
/**
* 解析消息对应的检核批次 ID(消息 run_id 优先,其次 for-log 映射)。
*/
const resolveMessageRunId = (msg: ChatMessage): number | null => {
const direct = getRunIdFromMessage(msg);
if (direct) return direct;
const chatLogId = getChatLogIdFromMessage(msg);
if (!chatLogId) return null;
const mapped = chatLogRunMap.value[chatLogId];
return mapped && mapped > 0 ? mapped : null;
};
const storeRunPayload = (run: ToolRunProgress, chatLogId?: number | null) => {
const runId = Number(run.run_id);
if (!Number.isFinite(runId) || runId <= 0) return;
runsById.value = { ...runsById.value, [runId]: run };
const nextErrors = { ...runErrors.value };
delete nextErrors[runId];
runErrors.value = nextErrors;
if (chatLogId && chatLogId > 0) {
chatLogRunMap.value = { ...chatLogRunMap.value, [chatLogId]: runId };
const nextChatLogErrors = { ...chatLogErrors.value };
delete nextChatLogErrors[chatLogId];
chatLogErrors.value = nextChatLogErrors;
}
};
const refreshRun = async (runId: number) => {
const url = resolveDetailUrl(runId);
if (!url) return;
try {
const payload = await getToolRunProgress(url);
if (payload.run) {
runsById.value = { ...runsById.value, [runId]: payload.run };
storeRunPayload(payload.run);
}
const nextErrors = { ...runErrors.value };
delete nextErrors[runId];
runErrors.value = nextErrors;
} catch (e: unknown) {
runErrors.value = {
...runErrors.value,
[runId]: e instanceof Error ? e.message : '任务进度查询失败',
};
}
};
/**
* 按 chat_log_id 走 for-log 解析批次;成功时回写消息 run_id 供后续 detail 轮询。
*/
const refreshRunByChatLog = async (chatLogId: number, messageIndex: number) => {
const url = resolveForLogUrl(chatLogId);
if (!url) return;
try {
const payload = await getToolRunProgress(url);
if (payload.run) {
storeRunPayload(payload.run, chatLogId);
const msg = ctx.messages.value[messageIndex];
if (msg && !getRunIdFromMessage(msg)) {
msg.run_id = Number(payload.run.run_id);
}
}
const nextErrors = { ...chatLogErrors.value };
delete nextErrors[chatLogId];
chatLogErrors.value = nextErrors;
} catch (e: unknown) {
chatLogErrors.value = {
...chatLogErrors.value,
[chatLogId]: e instanceof Error ? e.message : '任务进度查询失败',
};
}
};
const schedulePoll = () => {
clearPollTimer();
const intervalSec = Number(rawToolRunConfig.value?.poll_interval_seconds);
const intervalMs = Math.max(1, Math.min(Number.isFinite(intervalSec) ? intervalSec : 2, 30)) * 1000;
pollTimer = window.setTimeout(() => {
void syncProgressState();
}, intervalMs);
};
const syncProgressState = async () => {
clearPollTimer();
if (!toolRunProgressConfig.value) {
runsById.value = {};
runErrors.value = {};
chatLogRunMap.value = {};
chatLogErrors.value = {};
pollingRunIds.value = [];
pollingChatLogIds.value = [];
return;
}
const runIds = collectAssistantRunIds(ctx.messages.value);
const targets = collectAssistantProgressTargets(ctx.messages.value);
const runIds = [...new Set(targets.map((item) => item.runId).filter((id): id is number => !!id))];
const chatLogIds = [...new Set(
targets
.filter((item) => !item.runId && item.chatLogId)
.map((item) => item.chatLogId as number),
)];
pollingRunIds.value = runIds;
if (!runIds.length) {
pollingChatLogIds.value = chatLogIds;
if (!targets.length) {
runsById.value = {};
runErrors.value = {};
chatLogRunMap.value = {};
chatLogErrors.value = {};
return;
}
await Promise.all(runIds.map((runId) => refreshRun(runId)));
await Promise.all([
...runIds.map((runId) => refreshRun(runId)),
...targets
.filter((item) => !item.runId && item.chatLogId)
.map((item) => refreshRunByChatLog(item.chatLogId as number, item.messageIndex)),
]);
const activeRunIds = new Set<number>();
for (const target of targets) {
const runId = resolveMessageRunId(target.message);
if (runId) activeRunIds.add(runId);
}
const nextRuns: Record<number, ToolRunProgress> = {};
for (const runId of runIds) {
for (const runId of activeRunIds) {
const run = runsById.value[runId];
if (run) nextRuns[runId] = run;
}
runsById.value = nextRuns;
const hasRunning = Object.values(nextRuns).some((run) => isRunningToolRunStatus(run.status));
if (hasRunning) schedulePoll();
};
watch(
() => [ctx.currentAgent.value?.id, ctx.conversationId.value] as const,
() => {
runsById.value = {};
runErrors.value = {};
pollingRunIds.value = [];
clearPollTimer();
},
);
watch(
() => ctx.messages.value.map((msg, index) => (
msg?.role === 'assistant'
? `${resolveMessageAnchorKey(msg, index)}:${getRunIdFromMessage(msg) ?? ''}`
: ''
)).join('|'),
async () => {
await nextTick();
await syncProgressState();
() => [ctx.currentAgent.value?.id, ctx.conversationId.value] as const,
() => {
runsById.value = {};
runErrors.value = {};
chatLogRunMap.value = {};
chatLogErrors.value = {};
pollingRunIds.value = [];
pollingChatLogIds.value = [];
clearPollTimer();
},
{ immediate: true },
);
watch(
() => ctx.messages.value.map((msg, index) => (
msg?.role === 'assistant'
? `${resolveMessageAnchorKey(msg, index)}:${getRunIdFromMessage(msg) ?? ''}:${getChatLogIdFromMessage(msg) ?? ''}`
: ''
)).join('|'),
async () => {
await nextTick();
await syncProgressState();
},
{ immediate: true },
);
const refreshToolRunProgressAfterSend = async () => {
await nextTick();
await syncProgressState();
};
const prepareToolRunProgressBeforeSend = async () => {
// 按轮 bind:发送前无需 session 级快照。
};
const matchesBoundScheduleTask = (taskId: unknown): boolean => {
const expected = boundScheduleTaskId.value;
if (!expected) return true;
const actual = Number(taskId);
return Number.isFinite(actual) && actual === expected;
};
const getMessageRunProgress = (msg: ChatMessage) => {
const runId = getRunIdFromMessage(msg);
const runId = resolveMessageRunId(msg);
if (!runId) return null;
return runsById.value[runId] ?? null;
};
const getMessageRunProgressError = (msg: ChatMessage) => {
const runId = getRunIdFromMessage(msg);
if (!runId) return '';
return runErrors.value[runId] || '';
const runId = resolveMessageRunId(msg);
if (runId && runErrors.value[runId]) return runErrors.value[runId];
const chatLogId = getChatLogIdFromMessage(msg);
if (chatLogId && chatLogErrors.value[chatLogId]) return chatLogErrors.value[chatLogId];
return '';
};
const isMessageRunProgressLoading = (msg: ChatMessage) => {
const runId = getRunIdFromMessage(msg);
const runId = resolveMessageRunId(msg);
if (!runId) return false;
return !runsById.value[runId] && !runErrors.value[runId];
};
/**
* 判断是否在该助手消息后展示进度卡片。
* 核心逻辑:已解析到 run_id 时展示;执行中、已完成、加载中或查询报错均保留卡片,无 run_id 不展示。
*/
const shouldShowToolRunProgressAfterMessage = (msg: ChatMessage, _index: number) => {
if (msg?.role !== 'assistant') return false;
if (!toolRunProgressConfig.value) return false;
if (assistantMessageHasError(msg)) return false;
const runId = getRunIdFromMessage(msg);
const runId = resolveMessageRunId(msg);
if (!runId) return false;
const error = getMessageRunProgressError(msg);
if (error) return true;
const loading = isMessageRunProgressLoading(msg);
if (loading) return true;
const run = getMessageRunProgress(msg);
if (!run || !isRunningToolRunStatus(run.status)) return false;
if (!matchesBoundScheduleTask(run.task_id)) return false;
return true;
if (!run) return false;
return matchesBoundScheduleTask(run.task_id);
};
const toolRunProgress = computed(() => {
for (let i = ctx.messages.value.length - 1; i >= 0; i -= 1) {
const msg = ctx.messages.value[i];
if (!msg || !shouldShowToolRunProgressAfterMessage(msg, i)) continue;
return getMessageRunProgress(msg);
}
return null;
});
const toolRunProgressLoading = computed(() => pollingRunIds.value.length > 0 && !toolRunProgress.value);
const toolRunProgressError = computed(() => {
const ids = pollingRunIds.value;
for (const runId of ids) {
const err = runErrors.value[runId];
if (err) return err;
}
return '';
const toolRunProgressLoading = computed(() => {
if (toolRunProgress.value) return false;
return pollingRunIds.value.length > 0 || pollingChatLogIds.value.length > 0;
});
const toolRunProgressError = computed(() => {
for (const runId of pollingRunIds.value) {
const err = runErrors.value[runId];
if (err) return err;
}
for (const chatLogId of pollingChatLogIds.value) {
const err = chatLogErrors.value[chatLogId];
if (err) return err;
}
return '';
});
const toolRunProgressTitle = computed(() => toolRunProgressConfig.value?.title ?? '');
const isToolRunProgressWaiting = computed(() => false);
return {
toolRunProgressConfig,
toolRunProgress,
toolRunProgressLoading,
toolRunProgressError,
toolRunProgressTitle,
isToolRunProgressWaiting,
shouldShowToolRunProgressAfterMessage,
getMessageRunProgress,
getMessageRunProgressError,
isMessageRunProgressLoading,
prepareToolRunProgressBeforeSend,
refreshToolRunProgressAfterSend,
syncProgressForCurrentConversation: syncProgressState,
};
}