import { computed, onBeforeUnmount, ref, type Ref, watch } from 'vue'; import { buildFileCheckLogProgressUrl } from '../utils/toolRunProgressConfig'; import { getToolRunProgress, type ToolRunProgress } from '../api/toolRunProgress.api'; import type { ToolRunProgressMatchSource } from '../types/tool-run-progress.types'; 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; } const clampPollMs = (seconds: unknown) => { const raw = Number(seconds); const safe = Number.isFinite(raw) ? raw : 2; return Math.max(1, Math.min(safe, 30)) * 1000; }; 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, options: UseToolRunProgressOptions = {}, ) { const run = ref(null); const matchSource = ref(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 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 || '当前任务执行中,请等待完成'); const clearTimer = () => { if (timer !== undefined) { window.clearTimeout(timer); timer = undefined; } }; const scheduleNext = () => { clearTimer(); if (!enabled.value || error.value) return; const interval = clampPollMs(configRef.value?.poll_interval_seconds); timer = window.setTimeout(() => { void refresh(); }, interval); }; 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; } }; 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 chatLogId = Number(cfg.chat_log_id); if (!Number.isFinite(taskId) || taskId <= 0 || !Number.isFinite(chatLogId) || chatLogId <= 0) { return null; } return fetchProgressUrl(buildFileCheckLogProgressUrl(taskId, chatLogId), silent); }; const refresh = async () => { const cfg = configRef.value; if (!cfg) { run.value = null; matchSource.value = null; resolvedRunId = null; error.value = ''; clearTimer(); return; } 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(); return; } if (run.value && isTerminalStatus(run.value.status)) { emptySessionPolls = 0; clearTimer(); return; } emptySessionPolls = 0; clearTimer(); }; watch( () => { 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(); }, { immediate: true }, ); onBeforeUnmount(clearTimer); return { run, matchSource, loading, error, isRunning, shouldLockInput, lockMessage, refresh, }; }