feat(schedule):cron支持图形,RoHS检核增加进度显示
This commit is contained in:
1 parent
6d0e78be81
commit
f5aac9c893
46 files changed
+1987
-221
No files matched your search
@@ -151,7 +151,11 @@ const {
|
||||
{{ $t('admin.schedule.lastRun') }}:{{ formatDateTime(s.last_run_at) }}
|
||||
</div>
|
||||
<div class="mb-3 text-sm text-muted">
|
||||
{{ $t('admin.schedule.nextRun') }}:{{ formatDateTime(s.next_run_at) }}
|
||||
{{ $t('admin.schedule.nextRun') }}:{{
|
||||
!s.enabled
|
||||
? $t('admin.schedule.nextRunDisabled')
|
||||
: (s.next_run_at ? formatDateTime(s.next_run_at) : $t('admin.schedule.nextRunPending'))
|
||||
}}
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
|
||||
@@ -11,7 +11,7 @@ const props = defineProps<{
|
||||
}>();
|
||||
|
||||
const d = props.designer;
|
||||
const { state, cronExpr, isValid, nextRunAt, weekdayOptions } = d;
|
||||
const { state, timezone, cronExpr, cronRisky, isValid, nextRunAt, weekdayOptions } = d;
|
||||
|
||||
const handleSwitchVisual = () => {
|
||||
if (state.value.editorMode === 'visual') return;
|
||||
@@ -30,6 +30,7 @@ const handleSwitchAdvanced = () => {
|
||||
<div class="min-w-0">
|
||||
<h4 class="text-base font-bold text-primary">{{ $t('admin.schedule.form.cronTitle') }}</h4>
|
||||
<p class="mt-1 text-sm leading-relaxed text-muted">{{ $t('admin.schedule.form.cronHint') }}</p>
|
||||
<p class="mt-1 text-xs text-muted">{{ $t('admin.schedule.form.cronTimezoneHint', { tz: timezone }) }}</p>
|
||||
</div>
|
||||
<div
|
||||
class="segment-control segment-control--cols-2 segment-control--sm w-full max-w-xs"
|
||||
@@ -84,6 +85,13 @@ const handleSwitchAdvanced = () => {
|
||||
<button type="button" class="rounded-lg border border-default bg-surface px-3 py-1.5 text-xs font-medium text-secondary transition hover:border-blue-300 hover:text-primary" @click="d.setPreset('weekly')">
|
||||
{{ $t('admin.schedule.form.weekly') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default bg-surface px-3 py-1.5 text-xs font-medium text-secondary transition hover:border-blue-300 hover:text-primary"
|
||||
@click="d.applyAdvancedCron('0 12,17 * * *')"
|
||||
>
|
||||
{{ $t('admin.schedule.form.twiceDaily') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -231,6 +239,13 @@ const handleSwitchAdvanced = () => {
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<p
|
||||
v-if="cronRisky"
|
||||
class="mb-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800"
|
||||
>
|
||||
{{ $t('admin.schedule.form.cronRiskyHint') }}
|
||||
</p>
|
||||
|
||||
<div
|
||||
class="mt-4 flex flex-col gap-1.5 rounded-xl border border-dashed px-4 py-3 text-xs sm:flex-row sm:flex-wrap sm:items-center sm:gap-x-4"
|
||||
:class="isValid ? 'border-default bg-surface-soft text-secondary' : 'border-red-200 bg-red-50 text-red-700'"
|
||||
|
||||
+5
@@ -9,6 +9,7 @@ import {
|
||||
defaultCronDesignerState,
|
||||
parseCronExpr,
|
||||
toCronField,
|
||||
normalizeCronExpr,
|
||||
validateCronDesignerState,
|
||||
} from './scheduleCronDesigner.utils';
|
||||
|
||||
@@ -91,4 +92,8 @@ describe('scheduleCronDesigner.utils', () => {
|
||||
state.months = [];
|
||||
expect(validateCronDesignerState(state)).toBe(false);
|
||||
});
|
||||
|
||||
it('normalizes risky cron to fixed minute zero', () => {
|
||||
expect(normalizeCronExpr('* 12,17 * * *')).toBe('0 12,17 * * *');
|
||||
});
|
||||
});
|
||||
+20
-2
@@ -101,6 +101,24 @@ export function parseCronFieldToArray(field: string, min: number, max: number):
|
||||
return Array.from(result).sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修正常见 Cron 笔误:分钟为 * 且小时已限定(如 * 12,17 * * *)时改为整点 0 分。
|
||||
*/
|
||||
export function normalizeCronExpr(expr: string): string {
|
||||
const parts = String(expr || '').trim().split(/\s+/);
|
||||
if (parts.length === 5 && parts[0] === '*' && parts[1] && parts[1] !== '*') {
|
||||
parts[0] = '0';
|
||||
return parts.join(' ');
|
||||
}
|
||||
return String(expr || '').trim();
|
||||
}
|
||||
|
||||
/** 分钟为 * 且小时非 *:会在指定小时内每分钟执行。 */
|
||||
export function isRiskyCronExpr(expr: string): boolean {
|
||||
const parts = String(expr || '').trim().split(/\s+/);
|
||||
return parts.length === 5 && parts[0] === '*' && !!parts[1] && parts[1] !== '*';
|
||||
}
|
||||
|
||||
export function buildCronExpr(state: ScheduleCronDesignerState): string {
|
||||
const dom = toCronField(state.daysOfMonth, 1, 31);
|
||||
const month = toCronField(state.months, 1, 12);
|
||||
@@ -237,8 +255,8 @@ function isCalendarValid(values: number[] | null): boolean {
|
||||
|
||||
export function validateCronDesignerState(state: ScheduleCronDesignerState): boolean {
|
||||
if (state.editorMode === 'advanced') {
|
||||
const text = state.advancedCronExpr.trim();
|
||||
return text.length > 0 && text.split(/\s+/).length === 5;
|
||||
const text = normalizeCronExpr(state.advancedCronExpr);
|
||||
return text.length > 0 && text.split(/\s+/).length === 5 && !isRiskyCronExpr(state.advancedCronExpr);
|
||||
}
|
||||
|
||||
if (!isCalendarValid(state.months) || !isCalendarValid(state.weekdays) || !isCalendarValid(state.daysOfMonth)) {
|
||||
|
||||
+31
-2
@@ -5,11 +5,14 @@
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { CronExpressionParser } from 'cron-parser';
|
||||
import { DEFAULT_SCHEDULE_TIMEZONE } from '../constants';
|
||||
import {
|
||||
applyPreset,
|
||||
buildCronExpr,
|
||||
computeNextRunAt,
|
||||
defaultCronDesignerState,
|
||||
isRiskyCronExpr,
|
||||
normalizeCronExpr,
|
||||
parseCronExpr,
|
||||
validateCronDesignerState,
|
||||
type CronPreset,
|
||||
@@ -19,23 +22,36 @@ import {
|
||||
export function useScheduleCronDesigner() {
|
||||
const { t } = useI18n();
|
||||
const state = ref<ScheduleCronDesignerState>(defaultCronDesignerState());
|
||||
const timezone = ref(DEFAULT_SCHEDULE_TIMEZONE);
|
||||
|
||||
const cronExpr = computed(() => {
|
||||
if (state.value.editorMode === 'advanced') {
|
||||
return state.value.advancedCronExpr.trim();
|
||||
return normalizeCronExpr(state.value.advancedCronExpr);
|
||||
}
|
||||
return buildCronExpr(state.value);
|
||||
});
|
||||
|
||||
const cronRisky = computed(() =>
|
||||
state.value.editorMode === 'advanced' && isRiskyCronExpr(state.value.advancedCronExpr),
|
||||
);
|
||||
|
||||
const isValid = computed(() => validateCronDesignerState(state.value));
|
||||
|
||||
const nextRunAt = computed(() =>
|
||||
computeNextRunAt(cronExpr.value, (expr) => {
|
||||
const normalized = normalizeCronForParser(expr);
|
||||
return CronExpressionParser.parse(normalized);
|
||||
return CronExpressionParser.parse(normalized, { tz: timezone.value || DEFAULT_SCHEDULE_TIMEZONE });
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* 更新 Cron 预览计算时区。
|
||||
* @param value 排程保存的 IANA 时区;为空时回退默认业务时区。
|
||||
*/
|
||||
const setTimezone = (value: string | null | undefined) => {
|
||||
timezone.value = String(value || '').trim() || DEFAULT_SCHEDULE_TIMEZONE;
|
||||
};
|
||||
|
||||
const loadFromExpr = (expr: string | null | undefined) => {
|
||||
const result = parseCronExpr(expr);
|
||||
if (result.ok && result.state) {
|
||||
@@ -82,6 +98,15 @@ export function useScheduleCronDesigner() {
|
||||
return true;
|
||||
};
|
||||
|
||||
const applyAdvancedCron = (expr: string) => {
|
||||
state.value = {
|
||||
...defaultCronDesignerState(),
|
||||
editorMode: 'advanced',
|
||||
advancedCronExpr: normalizeCronExpr(expr),
|
||||
parseFailed: false,
|
||||
};
|
||||
};
|
||||
|
||||
const setPreset = (preset: CronPreset, options?: { everyMinutes?: number; weeklyDay?: number }) => {
|
||||
state.value = applyPreset(preset, state.value, options);
|
||||
state.value.editorMode = 'visual';
|
||||
@@ -145,13 +170,17 @@ export function useScheduleCronDesigner() {
|
||||
|
||||
return {
|
||||
state,
|
||||
timezone,
|
||||
cronExpr,
|
||||
cronRisky,
|
||||
isValid,
|
||||
nextRunAt,
|
||||
setTimezone,
|
||||
loadFromExpr,
|
||||
reset,
|
||||
switchToAdvanced,
|
||||
switchToVisual,
|
||||
applyAdvancedCron,
|
||||
setPreset,
|
||||
toggleMonth,
|
||||
toggleWeekday,
|
||||
|
||||
@@ -26,6 +26,7 @@ import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type { AdminAgentOption, AdminUserRow } from '@/features/admin/types/admin.types';
|
||||
import { useScheduleCronDesigner } from './useScheduleCronDesigner';
|
||||
import { DEFAULT_SCHEDULE_TIMEZONE } from '../constants';
|
||||
|
||||
export function useSchedulesAdmin() {
|
||||
const { t, locale } = useI18n();
|
||||
@@ -186,6 +187,18 @@ const scheduleCronDesigner = useScheduleCronDesigner();
|
||||
const scheduleCronPreview = scheduleCronDesigner.cronExpr;
|
||||
const scheduleCronValid = scheduleCronDesigner.isValid;
|
||||
|
||||
/**
|
||||
* 读取浏览器 IANA 时区,作为新建排程的 Cron 当地时间口径。
|
||||
* @returns 浏览器时区;读取失败时回退默认业务时区。
|
||||
*/
|
||||
const detectBrowserTimezone = (): string => {
|
||||
try {
|
||||
return Intl.DateTimeFormat().resolvedOptions().timeZone || DEFAULT_SCHEDULE_TIMEZONE;
|
||||
} catch {
|
||||
return DEFAULT_SCHEDULE_TIMEZONE;
|
||||
}
|
||||
};
|
||||
|
||||
const resetScheduleCreateForm = () => {
|
||||
scheduleEditingId.value = null;
|
||||
scheduleCreateForm.value = {
|
||||
@@ -228,6 +241,7 @@ const resetScheduleCreateForm = () => {
|
||||
dify_system_prompt: '',
|
||||
};
|
||||
scheduleTestResult.value = null;
|
||||
scheduleCronDesigner.setTimezone(detectBrowserTimezone());
|
||||
scheduleNotifyUserQuery.value = '';
|
||||
scheduleNotifyDropdownOpen.value = false;
|
||||
scheduleOwnerQuery.value = '';
|
||||
@@ -262,6 +276,7 @@ const openScheduleEditModal = async (task: ScheduleTask) => {
|
||||
enabled: !!task.enabled,
|
||||
data_source_type: (task.data_source_type || 'database') as 'database' | 'external_api',
|
||||
};
|
||||
scheduleCronDesigner.setTimezone(task.schedule_timezone || detectBrowserTimezone());
|
||||
|
||||
try {
|
||||
const result = await getAdminScheduleTaskConfig(task.id);
|
||||
@@ -724,6 +739,7 @@ const createSchedule = async () => {
|
||||
schedule_type: 'platform_app',
|
||||
owner_user_id: scheduleCreateForm.value.owner_user_id,
|
||||
cron_expr: scheduleCronPreview.value,
|
||||
schedule_timezone: scheduleCronDesigner.timezone.value || detectBrowserTimezone(),
|
||||
wait_seconds: Math.max(0, Number(scheduleCreateForm.value.wait_seconds || 0)),
|
||||
dify_agent_id: scheduleCreateForm.value.dify_agent_id || undefined,
|
||||
notify_user_ids_json: scheduleCreateForm.value.notify_enabled ? scheduleCreateForm.value.notify_user_ids_json : [],
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
/** 与后端 SCHEDULE_TIMEZONE 默认值保持一致 */
|
||||
export const DEFAULT_SCHEDULE_TIMEZONE = 'Asia/Shanghai';
|
||||
@@ -32,10 +32,11 @@ const {
|
||||
leaveHandlers: LeaveMessageHandlers;
|
||||
shippingHandlers: ShippingMappingHandlers;
|
||||
shouldRenderMessage: (msg: ChatMessage) => boolean;
|
||||
shouldShowToolRunProgressAfterMessage: (msg: ChatMessage) => boolean;
|
||||
shouldShowToolRunProgressAfterMessage: (msg: ChatMessage, index: number) => boolean;
|
||||
getMessageRunProgress: (msg: ChatMessage) => ToolRunProgress | null;
|
||||
getMessageRunProgressError: (msg: ChatMessage) => string;
|
||||
isMessageRunProgressLoading: (msg: ChatMessage) => boolean;
|
||||
toolRunProgress: ToolRunProgress | null;
|
||||
toolRunProgressLoading: boolean;
|
||||
toolRunProgressError: string;
|
||||
toolRunProgressTitle: string;
|
||||
/** 供父级滚动逻辑绑定 main 元素 */
|
||||
scrollContainerHolder: { el: Ref<HTMLElement | null> };
|
||||
@@ -91,10 +92,11 @@ const bindScrollContainer = (node: unknown) => {
|
||||
@open-feedback="emit('open-feedback', index)"
|
||||
/>
|
||||
<ToolRunProgressCard
|
||||
v-if="shouldRenderMessage(msg) && shouldShowToolRunProgressAfterMessage(msg)"
|
||||
:run="toolRunProgress"
|
||||
:loading="toolRunProgressLoading"
|
||||
:error="toolRunProgressError"
|
||||
v-if="shouldRenderMessage(msg) && shouldShowToolRunProgressAfterMessage(msg, index)"
|
||||
:run="getMessageRunProgress(msg)"
|
||||
:loading="isMessageRunProgressLoading(msg)"
|
||||
:waiting="false"
|
||||
:error="getMessageRunProgressError(msg)"
|
||||
:fallback-title="toolRunProgressTitle"
|
||||
/>
|
||||
</template>
|
||||
|
||||
@@ -96,9 +96,10 @@ const page = useChatPageContext();
|
||||
:shipping-handlers="page.shippingMappingHandlers"
|
||||
:should-render-message="page.shouldRenderMessage"
|
||||
:should-show-tool-run-progress-after-message="page.shouldShowToolRunProgressAfterMessage"
|
||||
:get-message-run-progress="page.getMessageRunProgress"
|
||||
:get-message-run-progress-error="page.getMessageRunProgressError"
|
||||
:is-message-run-progress-loading="page.isMessageRunProgressLoading"
|
||||
:tool-run-progress="page.toolRunProgress"
|
||||
:tool-run-progress-loading="page.toolRunProgressLoading"
|
||||
:tool-run-progress-error="page.toolRunProgressError"
|
||||
:tool-run-progress-title="page.toolRunProgressTitle"
|
||||
:scroll-container-holder="page.scrollContainerHolder"
|
||||
@copy="page.copyToClipboard($event.message, $event.index)"
|
||||
|
||||
@@ -7,6 +7,7 @@ import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
const props = defineProps<{
|
||||
run: ToolRunProgress | null;
|
||||
loading?: boolean;
|
||||
waiting?: boolean;
|
||||
error?: string;
|
||||
fallbackTitle?: string;
|
||||
}>();
|
||||
@@ -45,7 +46,11 @@ const formatTime = (value?: string | null) => {
|
||||
].join(':');
|
||||
};
|
||||
|
||||
const percent = () => Math.max(0, Math.min(Number(props.run?.progress_percent || 0), 100));
|
||||
const percent = () => {
|
||||
const value = Number(props.run?.progress_percent ?? 0);
|
||||
if (!Number.isFinite(value)) return 0;
|
||||
return Math.max(0, Math.min(value, 100));
|
||||
};
|
||||
|
||||
const kbSyncMeta = (status?: string | null) => {
|
||||
const value = String(status || '').toLowerCase();
|
||||
@@ -119,7 +124,6 @@ const downloadExcel = async () => {
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="run || loading || error"
|
||||
class="mx-auto mb-4 w-full max-w-4xl overflow-hidden rounded-2xl border border-sky-100 bg-gradient-to-br from-sky-50 via-white to-emerald-50 shadow-sm"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3 border-b border-sky-100/80 px-4 py-3">
|
||||
@@ -136,8 +140,8 @@ const downloadExcel = async () => {
|
||||
批次:{{ run.run_no }} · 状态:{{ statusLabel(run.status) }}
|
||||
<span v-if="run.error_message" class="ml-2 text-rose-700">错误信息:{{ run.error_message }}</span>
|
||||
</template>
|
||||
<template v-else-if="loading">正在查询任务进度...</template>
|
||||
<template v-else>{{ error }}</template>
|
||||
<template v-else-if="loading || waiting">正在等待检核任务启动...</template>
|
||||
<template v-else-if="error">{{ error }}</template>
|
||||
</p>
|
||||
<p v-if="run?.status === 'running' && run.current_step" class="mt-1 text-xs text-sky-700">
|
||||
当前阶段:{{ run.current_step.label || run.current_step.step }}
|
||||
@@ -173,47 +177,54 @@ const downloadExcel = async () => {
|
||||
</div>
|
||||
|
||||
<div v-if="run" class="space-y-3 px-4 py-4">
|
||||
<div v-if="downloadError" class="rounded-xl bg-rose-50 px-3 py-2 text-xs text-rose-700">
|
||||
{{ downloadError }}
|
||||
</div>
|
||||
<div v-if="downloadError" class="rounded-xl bg-rose-50 px-3 py-2 text-xs text-rose-700">
|
||||
{{ downloadError }}
|
||||
</div>
|
||||
|
||||
<div class="h-2.5 overflow-hidden rounded-full bg-slate-200">
|
||||
<div
|
||||
class="h-full rounded-full bg-gradient-to-r from-sky-500 to-emerald-500 transition-all duration-500"
|
||||
:style="{ width: `${percent()}%` }"
|
||||
></div>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2 text-xs text-slate-500">
|
||||
<span>进度 {{ percent() }}%</span>
|
||||
<span>开始:{{ formatTime(run.started_at) }} · 完成:{{ formatTime(run.finished_at) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-2 md:grid-cols-5">
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">总数</div>
|
||||
<div class="text-lg font-bold text-slate-800">{{ run.total_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">已处理</div>
|
||||
<div class="text-lg font-bold text-sky-700">{{ run.processed_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">成功</div>
|
||||
<div class="text-lg font-bold text-emerald-700">{{ run.success_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">失败</div>
|
||||
<div class="text-lg font-bold text-rose-700">{{ run.failed_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">跳过</div>
|
||||
<div class="text-lg font-bold text-amber-700">{{ run.skipped_count }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="run.knowledge_base?.error_message" class="rounded-xl bg-amber-50 px-3 py-2 text-xs text-amber-700">
|
||||
知识库同步错误:{{ run.knowledge_base.error_message }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="waiting || loading" class="space-y-3 px-4 py-4">
|
||||
<div class="h-2.5 overflow-hidden rounded-full bg-slate-200">
|
||||
<div
|
||||
class="h-full rounded-full bg-gradient-to-r from-sky-500 to-emerald-500 transition-all duration-500"
|
||||
:style="{ width: `${percent()}%` }"
|
||||
></div>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2 text-xs text-slate-500">
|
||||
<span>进度 {{ percent() }}%</span>
|
||||
<span>开始:{{ formatTime(run.started_at) }} · 完成:{{ formatTime(run.finished_at) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-2 md:grid-cols-5">
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">总数</div>
|
||||
<div class="text-lg font-bold text-slate-800">{{ run.total_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">已处理</div>
|
||||
<div class="text-lg font-bold text-sky-700">{{ run.processed_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">成功</div>
|
||||
<div class="text-lg font-bold text-emerald-700">{{ run.success_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">失败</div>
|
||||
<div class="text-lg font-bold text-rose-700">{{ run.failed_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">跳过</div>
|
||||
<div class="text-lg font-bold text-amber-700">{{ run.skipped_count }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="run.knowledge_base?.error_message" class="rounded-xl bg-amber-50 px-3 py-2 text-xs text-amber-700">
|
||||
知识库同步错误:{{ run.knowledge_base.error_message }}
|
||||
<div class="h-full w-1/3 animate-pulse rounded-full bg-gradient-to-r from-sky-400 to-emerald-400" />
|
||||
</div>
|
||||
<p class="text-xs text-slate-500">检核启动后,这里会显示实时进度。</p>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -83,6 +83,11 @@ const applyEventMetadata = (msg: ChatMessage, data: Record<string, unknown>) =>
|
||||
addAttributionParts(msg, metadata?.annotation_reply);
|
||||
addAttributionParts(msg, data?.citation);
|
||||
addAttributionParts(msg, metadata?.citation);
|
||||
|
||||
const messagePayload = data?.message_payload;
|
||||
if (messagePayload && typeof messagePayload === 'object') {
|
||||
msg.payload = messagePayload;
|
||||
}
|
||||
};
|
||||
|
||||
export function useChat() {
|
||||
@@ -124,6 +129,27 @@ export function useChat() {
|
||||
return text.replace(/\\n/g, '\n');
|
||||
};
|
||||
|
||||
const formatStreamError = (message: unknown) => {
|
||||
if (typeof message === 'string') return message;
|
||||
if (message && typeof message === 'object') {
|
||||
const record = message as Record<string, unknown>;
|
||||
const nested = record.error;
|
||||
if (typeof nested === 'string') return nested;
|
||||
if (nested && typeof nested === 'object') {
|
||||
const nestedRecord = nested as Record<string, unknown>;
|
||||
if (typeof nestedRecord.message === 'string') return nestedRecord.message;
|
||||
}
|
||||
if (typeof record.message === 'string') return record.message;
|
||||
if (typeof record.code === 'string') return record.code;
|
||||
try {
|
||||
return JSON.stringify(message);
|
||||
} catch {
|
||||
return 'Unknown error';
|
||||
}
|
||||
}
|
||||
return String(message ?? 'Unknown error');
|
||||
};
|
||||
|
||||
const sendMessage = async (
|
||||
query: string,
|
||||
agentId: number,
|
||||
@@ -269,6 +295,13 @@ export function useChat() {
|
||||
const currentBotMsg = runMessages[botMsgIndex];
|
||||
if (currentBotMsg) currentBotMsg.chat_log_id = Number(data.chat_log_id);
|
||||
}
|
||||
if (botMsgIndex !== null) {
|
||||
const runId = Number(data.run_id);
|
||||
if (Number.isFinite(runId) && runId > 0) {
|
||||
const currentBotMsg = runMessages[botMsgIndex];
|
||||
if (currentBotMsg) currentBotMsg.run_id = runId;
|
||||
}
|
||||
}
|
||||
if (typeof data.answer === 'string' && data.answer.length > 0) {
|
||||
const botMsg = ensureBotMessage();
|
||||
if (!botMsg) continue;
|
||||
@@ -286,7 +319,7 @@ export function useChat() {
|
||||
} else if (eventName === 'error') {
|
||||
const botMsg = ensureBotMessage();
|
||||
if (!botMsg) continue;
|
||||
botMsg.content += `\n[Error: ${data.message}]`;
|
||||
botMsg.content += `\n[Error: ${formatStreamError(data.message)}]`;
|
||||
run.status = 'error';
|
||||
if (messages.value === runMessages) isThinking.value = false;
|
||||
} else if (typeof data.answer === 'string' && data.answer.length > 0) {
|
||||
|
||||
@@ -287,6 +287,7 @@ export function useChatPage() {
|
||||
tryHandleLeaveSend: leave.tryHandleLeaveSend,
|
||||
tryHandleShippingSend: shipping.tryHandleShippingSend,
|
||||
refreshToolRunProgressAfterSend: toolRun.refreshToolRunProgressAfterSend,
|
||||
prepareToolRunProgressBeforeSend: toolRun.prepareToolRunProgressBeforeSend,
|
||||
msg,
|
||||
t,
|
||||
copiedIndex,
|
||||
|
||||
@@ -1,15 +1,33 @@
|
||||
import { computed, onBeforeUnmount, ref, type Ref, watch } from 'vue';
|
||||
import { getToolRunProgress, type ToolRunProgress } from '@/api/toolRunProgress';
|
||||
import { getToolRunProgress, type ToolRunProgress, type ToolRunProgressMatchSource } from '@/api/toolRunProgress';
|
||||
import { buildLogProgressUrl } from '../utils/toolRunProgressConfig';
|
||||
|
||||
export interface ToolRunProgressConfig {
|
||||
type?: string;
|
||||
title?: string;
|
||||
poll_interval_seconds?: number;
|
||||
active_url?: string;
|
||||
/** 按 chat_log_id 关联批次的轮询地址 */
|
||||
log_progress_url?: string;
|
||||
/** @deprecated 使用 log_progress_url */
|
||||
session_progress_url?: string;
|
||||
detail_url_template?: string;
|
||||
schedule_task_id?: number | string | null;
|
||||
task_id?: number | string | null;
|
||||
chat_log_id?: number | string | null;
|
||||
/** 已知批次 ID 时走 detail 轮询 */
|
||||
run_id?: number | string | null;
|
||||
/** for-session 空结果最大重试次数 */
|
||||
empty_poll_max?: number;
|
||||
/** 等待 run_id 写出前的轮询窗口(秒) */
|
||||
pending_seconds?: number;
|
||||
lock_input_when_running?: boolean;
|
||||
lock_message?: string;
|
||||
session_id?: string;
|
||||
}
|
||||
|
||||
export interface UseToolRunProgressOptions {
|
||||
allowEmptySessionPolls?: Ref<boolean>;
|
||||
}
|
||||
|
||||
const clampPollMs = (seconds: unknown) => {
|
||||
@@ -18,13 +36,35 @@ const clampPollMs = (seconds: unknown) => {
|
||||
return Math.max(1, Math.min(safe, 30)) * 1000;
|
||||
};
|
||||
|
||||
export function useToolRunProgress(configRef: Ref<ToolRunProgressConfig | null>) {
|
||||
const TERMINAL_STATUSES = new Set(['success', 'partial_failed', 'failed', 'cancelled', 'canceled']);
|
||||
|
||||
const isTerminalStatus = (status?: string | null) => TERMINAL_STATUSES.has(String(status || '').toLowerCase());
|
||||
|
||||
/**
|
||||
* 轮询任务进度:有 run_id 时走 detail;或走 for-log / active。
|
||||
*/
|
||||
export function useToolRunProgress(
|
||||
configRef: Ref<ToolRunProgressConfig | null>,
|
||||
options: UseToolRunProgressOptions = {},
|
||||
) {
|
||||
const run = ref<ToolRunProgress | null>(null);
|
||||
const matchSource = ref<ToolRunProgressMatchSource | null>(null);
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
let timer: number | undefined;
|
||||
let emptySessionPolls = 0;
|
||||
let pollSessionKey = '';
|
||||
let hasFetchedOnce = false;
|
||||
let resolvedRunId: string | null = null;
|
||||
|
||||
const enabled = computed(() => {
|
||||
const cfg = configRef.value;
|
||||
if (!cfg) return false;
|
||||
if (cfg.session_progress_url) return true;
|
||||
if (cfg.run_id && cfg.detail_url_template) return true;
|
||||
return !!cfg.active_url;
|
||||
});
|
||||
|
||||
const enabled = computed(() => !!configRef.value?.active_url || (!!configRef.value?.detail_url_template && !!configRef.value?.run_id));
|
||||
const isRunning = computed(() => run.value?.status === 'running');
|
||||
const shouldLockInput = computed(() => Boolean(configRef.value?.lock_input_when_running) && isRunning.value);
|
||||
const lockMessage = computed(() => configRef.value?.lock_message || '当前任务执行中,请等待完成');
|
||||
@@ -38,53 +78,184 @@ export function useToolRunProgress(configRef: Ref<ToolRunProgressConfig | null>)
|
||||
|
||||
const scheduleNext = () => {
|
||||
clearTimer();
|
||||
if (!enabled.value) return;
|
||||
if (!enabled.value || error.value) return;
|
||||
const interval = clampPollMs(configRef.value?.poll_interval_seconds);
|
||||
timer = window.setTimeout(() => {
|
||||
void refresh();
|
||||
}, interval);
|
||||
};
|
||||
|
||||
const resolveProgressUrl = (cfg: ToolRunProgressConfig) => {
|
||||
const runId = String(cfg.run_id || '').trim();
|
||||
if (runId && cfg.detail_url_template) {
|
||||
return cfg.detail_url_template.replace('{run_id}', encodeURIComponent(runId));
|
||||
const resolveDetailUrl = (cfg: ToolRunProgressConfig, runId: number | string) => {
|
||||
const template = String(cfg.detail_url_template || '').trim();
|
||||
if (!template) return '';
|
||||
return template.replace('{run_id}', encodeURIComponent(String(runId)));
|
||||
};
|
||||
|
||||
const fetchProgressUrl = async (url: string, silent: boolean) => {
|
||||
if (!silent) loading.value = true;
|
||||
try {
|
||||
const payload = await getToolRunProgress(url);
|
||||
error.value = '';
|
||||
matchSource.value = payload.match_source ?? null;
|
||||
return payload.run ?? null;
|
||||
} catch (e: unknown) {
|
||||
const message = e instanceof Error ? e.message : '任务进度查询失败';
|
||||
error.value = message;
|
||||
matchSource.value = null;
|
||||
clearTimer();
|
||||
return null;
|
||||
} finally {
|
||||
if (!silent) loading.value = false;
|
||||
hasFetchedOnce = true;
|
||||
}
|
||||
return cfg.active_url || '';
|
||||
};
|
||||
|
||||
const refreshByDetail = async (cfg: ToolRunProgressConfig, runId: string, silent: boolean) => {
|
||||
if (!runId || !cfg.detail_url_template) return null;
|
||||
const detailUrl = resolveDetailUrl(cfg, runId);
|
||||
if (!detailUrl) return null;
|
||||
return fetchProgressUrl(detailUrl, silent);
|
||||
};
|
||||
|
||||
const refreshBySession = async (cfg: ToolRunProgressConfig, silent: boolean) => {
|
||||
const sessionUrl = String(cfg.session_progress_url || '').trim();
|
||||
if (sessionUrl) {
|
||||
return fetchProgressUrl(sessionUrl, silent);
|
||||
}
|
||||
const taskId = Number(cfg.schedule_task_id ?? cfg.task_id);
|
||||
const sessionId = String(cfg.session_id || '').trim();
|
||||
if (!Number.isFinite(taskId) || taskId <= 0 || !sessionId) return null;
|
||||
const fallbackUrl = buildLogProgressUrl('/api/workspace/rohs-check/runs/for-log', taskId, Number(cfg.chat_log_id));
|
||||
return fetchProgressUrl(fallbackUrl, silent);
|
||||
};
|
||||
|
||||
const refresh = async () => {
|
||||
const cfg = configRef.value;
|
||||
const url = cfg ? resolveProgressUrl(cfg) : '';
|
||||
if (!url) {
|
||||
if (!cfg) {
|
||||
run.value = null;
|
||||
matchSource.value = null;
|
||||
resolvedRunId = null;
|
||||
error.value = '';
|
||||
clearTimer();
|
||||
return;
|
||||
}
|
||||
loading.value = true;
|
||||
try {
|
||||
const payload = await getToolRunProgress(url);
|
||||
run.value = payload.run;
|
||||
error.value = '';
|
||||
} catch (e: any) {
|
||||
error.value = e?.message || '任务进度查询失败';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
|
||||
if (error.value) {
|
||||
clearTimer();
|
||||
return;
|
||||
}
|
||||
|
||||
const allowEmpty = options.allowEmptySessionPolls?.value ?? false;
|
||||
const silent = hasFetchedOnce || !!run.value || allowEmpty;
|
||||
const explicitRunId = String(cfg.run_id || resolvedRunId || '').trim();
|
||||
const hasSessionUrl = !!String(cfg.session_progress_url || cfg.session_id || '').trim();
|
||||
|
||||
if (hasSessionUrl) {
|
||||
const sessionRun = await refreshBySession(cfg, silent);
|
||||
if (sessionRun) {
|
||||
run.value = sessionRun;
|
||||
resolvedRunId = String(sessionRun.run_id);
|
||||
} else if (!allowEmpty || error.value) {
|
||||
run.value = null;
|
||||
if (!allowEmpty) {
|
||||
matchSource.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (run.value?.status === 'running') {
|
||||
emptySessionPolls = 0;
|
||||
scheduleNext();
|
||||
return;
|
||||
}
|
||||
|
||||
if (run.value && isTerminalStatus(run.value.status)) {
|
||||
emptySessionPolls = 0;
|
||||
clearTimer();
|
||||
return;
|
||||
}
|
||||
|
||||
const emptyPollMax = Number(cfg.empty_poll_max) > 0 ? Number(cfg.empty_poll_max) : 30;
|
||||
if (!run.value && allowEmpty && !error.value) {
|
||||
emptySessionPolls += 1;
|
||||
if (emptySessionPolls < emptyPollMax) {
|
||||
scheduleNext();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
emptySessionPolls = 0;
|
||||
clearTimer();
|
||||
return;
|
||||
}
|
||||
|
||||
if (explicitRunId && cfg.detail_url_template) {
|
||||
const detailRun = await refreshByDetail(cfg, explicitRunId, silent);
|
||||
if (detailRun) {
|
||||
run.value = detailRun;
|
||||
}
|
||||
if (run.value?.status === 'running') {
|
||||
emptySessionPolls = 0;
|
||||
scheduleNext();
|
||||
return;
|
||||
}
|
||||
if (run.value && isTerminalStatus(run.value.status)) {
|
||||
emptySessionPolls = 0;
|
||||
clearTimer();
|
||||
return;
|
||||
}
|
||||
emptySessionPolls = 0;
|
||||
clearTimer();
|
||||
return;
|
||||
}
|
||||
|
||||
const activeUrl = String(cfg.active_url || '').trim();
|
||||
if (!activeUrl) {
|
||||
run.value = null;
|
||||
matchSource.value = null;
|
||||
clearTimer();
|
||||
return;
|
||||
}
|
||||
|
||||
const activeRun = await fetchProgressUrl(activeUrl, silent);
|
||||
if (activeRun) {
|
||||
run.value = activeRun;
|
||||
} else if (!allowEmpty || error.value) {
|
||||
run.value = null;
|
||||
matchSource.value = null;
|
||||
}
|
||||
|
||||
if (run.value?.status === 'running') {
|
||||
emptySessionPolls = 0;
|
||||
scheduleNext();
|
||||
} else {
|
||||
clearTimer();
|
||||
return;
|
||||
}
|
||||
|
||||
if (run.value && isTerminalStatus(run.value.status)) {
|
||||
emptySessionPolls = 0;
|
||||
clearTimer();
|
||||
return;
|
||||
}
|
||||
|
||||
emptySessionPolls = 0;
|
||||
clearTimer();
|
||||
};
|
||||
|
||||
watch(
|
||||
() => JSON.stringify(configRef.value || {}),
|
||||
() => {
|
||||
const cfg = configRef.value;
|
||||
return cfg
|
||||
? `${cfg.session_progress_url || ''}|${cfg.active_url || ''}|${cfg.schedule_task_id ?? cfg.task_id ?? ''}|${cfg.session_id || ''}|${cfg.run_id || ''}`
|
||||
: '';
|
||||
},
|
||||
(nextKey) => {
|
||||
if (nextKey === pollSessionKey) return;
|
||||
pollSessionKey = nextKey;
|
||||
run.value = null;
|
||||
matchSource.value = null;
|
||||
resolvedRunId = null;
|
||||
error.value = '';
|
||||
emptySessionPolls = 0;
|
||||
hasFetchedOnce = false;
|
||||
clearTimer();
|
||||
if (enabled.value) void refresh();
|
||||
},
|
||||
@@ -95,6 +266,7 @@ export function useToolRunProgress(configRef: Ref<ToolRunProgressConfig | null>)
|
||||
|
||||
return {
|
||||
run,
|
||||
matchSource,
|
||||
loading,
|
||||
error,
|
||||
isRunning,
|
||||
|
||||
@@ -39,6 +39,7 @@ export interface ChatPageSendContext {
|
||||
trimmed: string,
|
||||
) => Promise<boolean>;
|
||||
refreshToolRunProgressAfterSend: () => Promise<void>;
|
||||
prepareToolRunProgressBeforeSend: () => Promise<void>;
|
||||
msg: { warning: (text: string) => void; info: (text: string) => void };
|
||||
t: (key: string) => string;
|
||||
copiedIndex: Ref<number | null>;
|
||||
@@ -88,6 +89,7 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.clearAttachments();
|
||||
|
||||
await ctx.prepareToolRunProgressBeforeSend();
|
||||
await ctx.sendMessage(content, ctx.currentAgentId.value, ctx.selectedKb.value, files);
|
||||
await ctx.refreshHistoryAfterSend();
|
||||
await ctx.refreshToolRunProgressAfterSend();
|
||||
|
||||
@@ -1,32 +1,39 @@
|
||||
/**
|
||||
* 对话页:Agent tool_run_progress 能力轮询(RoHS 等按消息 run_id 展示进度卡片)。
|
||||
* 对话页:Agent tool_run_progress 能力轮询(RoHS 等异步任务进度卡片)。
|
||||
* 依赖:useToolRunProgress、toolRunProgressConfig、ChatMessage。
|
||||
* 逻辑:按助手消息 ChatLog.run_id 展示进度,每轮问答独立绑定。
|
||||
*/
|
||||
import { computed, nextTick } from 'vue';
|
||||
import { useToolRunProgress, type ToolRunProgressConfig } from '../composables/useToolRunProgress';
|
||||
import { computed, nextTick, ref, watch } from 'vue';
|
||||
import type { ToolRunProgress } from '@/api/toolRunProgress';
|
||||
import { getToolRunProgress } from '@/api/toolRunProgress';
|
||||
import type { ToolRunProgressConfig } from '../composables/useToolRunProgress';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { Ref } from 'vue';
|
||||
import {
|
||||
assistantMessageHasError,
|
||||
collectAssistantRunIds,
|
||||
getRunIdFromMessage,
|
||||
isRunningToolRunStatus,
|
||||
resolveScheduleTaskId,
|
||||
resolveMessageAnchorKey,
|
||||
} from '../utils/toolRunProgressConfig';
|
||||
|
||||
export interface ChatPageToolRunContext {
|
||||
currentAgent: Ref<{ extra_config?: Record<string, unknown> } | null>;
|
||||
currentAgent: Ref<{ id?: number; extra_config?: Record<string, unknown> } | null>;
|
||||
conversationId: Ref<string | null>;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
}
|
||||
|
||||
const extractToolRunIdFromContent = (content: unknown): number | null => {
|
||||
const text = String(content || '');
|
||||
const match = text.match(/(?:检核批次 ID|当前检核批次 ID|运行 ID|run_id|run id)\s*[::]\s*(\d+)/i);
|
||||
return match?.[1] ? Number(match[1]) : null;
|
||||
};
|
||||
|
||||
export function useChatPageToolRun(ctx: ChatPageToolRunContext) {
|
||||
const activeToolRunId = computed(() => {
|
||||
for (let i = ctx.messages.value.length - 1; i >= 0; i -= 1) {
|
||||
const msg = ctx.messages.value[i];
|
||||
if (msg?.role !== 'assistant') continue;
|
||||
const runId = extractToolRunIdFromContent(msg.content);
|
||||
if (runId) return runId;
|
||||
}
|
||||
return null;
|
||||
const runsById = ref<Record<number, ToolRunProgress>>({});
|
||||
const runErrors = ref<Record<number, string>>({});
|
||||
const pollingRunIds = 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>(() => {
|
||||
@@ -35,55 +42,190 @@ export function useChatPageToolRun(ctx: ChatPageToolRunContext) {
|
||||
? extra.capabilities.map((item: unknown) => String(item))
|
||||
: [];
|
||||
if (!capabilities.includes('tool_run_progress')) return null;
|
||||
const raw = extra.tool_run_progress;
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const cfg = raw as ToolRunProgressConfig;
|
||||
const cid = String(ctx.conversationId.value || '').trim();
|
||||
const runId = activeToolRunId.value;
|
||||
if (runId && cfg.detail_url_template) {
|
||||
return {
|
||||
...cfg,
|
||||
run_id: runId,
|
||||
};
|
||||
}
|
||||
if (!cid || !cfg.active_url) return null;
|
||||
const separator = cfg.active_url.includes('?') ? '&' : '?';
|
||||
const cfg = rawToolRunConfig.value;
|
||||
if (!cfg) return null;
|
||||
return {
|
||||
...cfg,
|
||||
active_url: `${cfg.active_url}${separator}conversation_id=${encodeURIComponent(cid)}`,
|
||||
run_id: null,
|
||||
schedule_task_id: resolveScheduleTaskId(cfg),
|
||||
};
|
||||
});
|
||||
|
||||
const {
|
||||
run: toolRunProgress,
|
||||
loading: toolRunProgressLoading,
|
||||
error: toolRunProgressError,
|
||||
refresh: refreshToolRunProgress,
|
||||
} = useToolRunProgress(toolRunProgressConfig);
|
||||
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 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 };
|
||||
}
|
||||
const nextErrors = { ...runErrors.value };
|
||||
delete nextErrors[runId];
|
||||
runErrors.value = nextErrors;
|
||||
} catch (e: unknown) {
|
||||
runErrors.value = {
|
||||
...runErrors.value,
|
||||
[runId]: 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 = {};
|
||||
pollingRunIds.value = [];
|
||||
return;
|
||||
}
|
||||
|
||||
const runIds = collectAssistantRunIds(ctx.messages.value);
|
||||
pollingRunIds.value = runIds;
|
||||
if (!runIds.length) {
|
||||
runsById.value = {};
|
||||
runErrors.value = {};
|
||||
return;
|
||||
}
|
||||
|
||||
await Promise.all(runIds.map((runId) => refreshRun(runId)));
|
||||
|
||||
const nextRuns: Record<number, ToolRunProgress> = {};
|
||||
for (const runId of runIds) {
|
||||
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();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
const refreshToolRunProgressAfterSend = async () => {
|
||||
await nextTick();
|
||||
void refreshToolRunProgress();
|
||||
await syncProgressState();
|
||||
};
|
||||
|
||||
const toolRunProgressTitle = computed(() => toolRunProgressConfig.value?.title ?? '');
|
||||
const prepareToolRunProgressBeforeSend = async () => {
|
||||
// 按轮 bind:发送前无需 session 级快照。
|
||||
};
|
||||
|
||||
const shouldShowToolRunProgressAfterMessage = (msg: ChatMessage) => {
|
||||
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);
|
||||
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 isMessageRunProgressLoading = (msg: ChatMessage) => {
|
||||
const runId = getRunIdFromMessage(msg);
|
||||
if (!runId) return false;
|
||||
return !runsById.value[runId] && !runErrors.value[runId];
|
||||
};
|
||||
|
||||
const shouldShowToolRunProgressAfterMessage = (msg: ChatMessage, _index: number) => {
|
||||
if (msg?.role !== 'assistant') return false;
|
||||
if (!(toolRunProgress.value || toolRunProgressLoading.value || toolRunProgressError.value)) return false;
|
||||
const messageRunId = extractToolRunIdFromContent(msg.content);
|
||||
const currentRunId = Number(toolRunProgress.value?.run_id || activeToolRunId.value || 0);
|
||||
return !!messageRunId && messageRunId === currentRunId;
|
||||
if (!toolRunProgressConfig.value) return false;
|
||||
if (assistantMessageHasError(msg)) return false;
|
||||
const runId = getRunIdFromMessage(msg);
|
||||
if (!runId) return false;
|
||||
const run = getMessageRunProgress(msg);
|
||||
if (!run || !isRunningToolRunStatus(run.status)) return false;
|
||||
if (!matchesBoundScheduleTask(run.task_id)) return false;
|
||||
return true;
|
||||
};
|
||||
|
||||
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 toolRunProgressTitle = computed(() => toolRunProgressConfig.value?.title ?? '');
|
||||
const isToolRunProgressWaiting = computed(() => false);
|
||||
|
||||
return {
|
||||
toolRunProgressConfig,
|
||||
toolRunProgress,
|
||||
toolRunProgressLoading,
|
||||
toolRunProgressError,
|
||||
toolRunProgressTitle,
|
||||
isToolRunProgressWaiting,
|
||||
shouldShowToolRunProgressAfterMessage,
|
||||
getMessageRunProgress,
|
||||
getMessageRunProgressError,
|
||||
isMessageRunProgressLoading,
|
||||
prepareToolRunProgressBeforeSend,
|
||||
refreshToolRunProgressAfterSend,
|
||||
syncProgressForCurrentConversation: syncProgressState,
|
||||
};
|
||||
}
|
||||
@@ -22,6 +22,8 @@ export interface ChatMessage {
|
||||
retriever_resources?: RetrieverResource[];
|
||||
attribution_parts?: string[];
|
||||
chat_log_id?: number;
|
||||
/** RoHS 等异步任务批次 ID(按轮问答绑定) */
|
||||
run_id?: number;
|
||||
payload?: unknown;
|
||||
local_id?: string;
|
||||
local_only?: boolean;
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* features/chat/utils/toolRunProgressConfig.ts
|
||||
* 用途:解析 Agent tool_run_progress 配置;构建 for-log / detail 轮询 URL。
|
||||
* 依赖:ToolRunProgressConfig、ChatMessage。
|
||||
* 逻辑:进度卡片由 ChatLog.run_id(按轮问答)驱动。
|
||||
*/
|
||||
import type { ToolRunProgressConfig } from '../composables/useToolRunProgress';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
|
||||
export interface ResolvedToolRunProgressOptions {
|
||||
empty_poll_max: number;
|
||||
}
|
||||
|
||||
const DEFAULT_EMPTY_POLL_MAX = 30;
|
||||
const DEFAULT_LOG_PROGRESS_URL = '/api/workspace/rohs-check/runs/for-log';
|
||||
|
||||
export function resolveToolRunProgressOptions(
|
||||
raw: Record<string, unknown> | ToolRunProgressConfig | null | undefined,
|
||||
): ResolvedToolRunProgressOptions {
|
||||
const cfg = raw && typeof raw === 'object' ? raw : {};
|
||||
const emptyRaw = Number(cfg.empty_poll_max);
|
||||
|
||||
return {
|
||||
empty_poll_max: Number.isFinite(emptyRaw) && emptyRaw > 0
|
||||
? Math.min(emptyRaw, 120)
|
||||
: DEFAULT_EMPTY_POLL_MAX,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveMessageAnchorKey(msg: ChatMessage, index: number): string {
|
||||
const logId = Number(msg.chat_log_id);
|
||||
if (Number.isFinite(logId) && logId > 0) return `log-${logId}`;
|
||||
const localId = String(msg.local_id || '').trim();
|
||||
if (localId) return `local-${localId}`;
|
||||
return `idx-${index}`;
|
||||
}
|
||||
|
||||
export function assistantMessageHasError(msg: ChatMessage | null | undefined): boolean {
|
||||
return String(msg?.content || '').includes('[Error:');
|
||||
}
|
||||
|
||||
export function resolveScheduleTaskId(cfg: ToolRunProgressConfig | null | undefined): number | null {
|
||||
if (!cfg) return null;
|
||||
const raw = cfg.schedule_task_id ?? cfg.task_id;
|
||||
const id = Number(raw);
|
||||
return Number.isFinite(id) && id > 0 ? id : null;
|
||||
}
|
||||
|
||||
export function resolveLogProgressBaseUrl(cfg: ToolRunProgressConfig): string {
|
||||
const logUrl = String(cfg.log_progress_url || cfg.session_progress_url || '').trim();
|
||||
if (logUrl) return logUrl.split('?')[0] || logUrl;
|
||||
return DEFAULT_LOG_PROGRESS_URL;
|
||||
}
|
||||
|
||||
export function buildLogProgressUrl(
|
||||
baseUrl: string,
|
||||
taskId: number,
|
||||
chatLogId: number,
|
||||
): string {
|
||||
const [rawPath = baseUrl, query = ''] = baseUrl.split('?');
|
||||
const path = rawPath || baseUrl;
|
||||
const search = new URLSearchParams(query);
|
||||
search.set('task_id', String(taskId));
|
||||
search.set('chat_log_id', String(chatLogId));
|
||||
search.delete('session_id');
|
||||
search.delete('conversation_id');
|
||||
const qs = search.toString();
|
||||
return qs ? `${path}?${qs}` : path;
|
||||
}
|
||||
|
||||
export function getRunIdFromMessage(msg: ChatMessage | null | undefined): number | null {
|
||||
const runId = Number(msg?.run_id);
|
||||
return Number.isFinite(runId) && runId > 0 ? runId : null;
|
||||
}
|
||||
|
||||
export function isRunningToolRunStatus(status?: string | null): boolean {
|
||||
return String(status || '').toLowerCase() === 'running';
|
||||
}
|
||||
|
||||
export function collectAssistantRunIds(messages: ChatMessage[]): number[] {
|
||||
const ids = new Set<number>();
|
||||
for (const msg of messages) {
|
||||
if (msg?.role !== 'assistant') continue;
|
||||
const runId = getRunIdFromMessage(msg);
|
||||
if (runId) ids.add(runId);
|
||||
}
|
||||
return [...ids];
|
||||
}
|
||||
Reference in new issue
Block a user