feat(file-check): 增加文件检核进度展示功能及相关配置

This commit is contained in:
hugo committed 2026-06-16 17:34:25 +08:00
1 parent d3cfd24d6f
commit 9b36ced288
11 files changed
+361 -13

No files matched your search

@@ -2,13 +2,17 @@
services/file_check_tools/chat_log_run_resolver.py
用途:按 ChatLog.run_id 解析文件检核进度(按轮问答)。
依赖:ChatLog、ScheduleRun。
逻辑:由 for-log API 调用;run_id 在 message_end 写入 chat_logs 表。
依赖:ChatLog、ScheduleRun、chat_log_run_binding、chat_turn_registry。
逻辑:for-log API 调用;优先读 chat_logs.run_id,缺失时按 session/query 兜底匹配并懒回写。
"""
from __future__ import annotations
from app import db
from app.models import ChatLog, ScheduleRun
from app.services.file_check_tools.chat_log_run_binding import (
resolve_run_id_for_chat_log,
update_chat_log_run_id,
)
def find_run_for_chat_log(
@@ -30,10 +34,24 @@ def find_run_for_chat_log(
return None
log = db.session.get(ChatLog, chat_log_id)
if not log or not log.run_id:
if not log:
return None
run = db.session.get(ScheduleRun, log.run_id)
run_id = int(log.run_id) if log.run_id else None
if not run_id:
# [STEP 1] message_end 可能早于 Tool 启动完成,按 session/query 从注册表或 ScheduleRun 兜底
resolved = resolve_run_id_for_chat_log(
session_id=log.session_id,
query=log.query,
)
if resolved:
update_chat_log_run_id(chat_log_id, resolved)
run_id = resolved
if not run_id:
return None
run = db.session.get(ScheduleRun, run_id)
if run and run.schedule_task_id == task_id:
return run
return None
+45
View File
@@ -653,6 +653,51 @@ def test_workspace_file_check_run_for_log_returns_null_when_unbound(app, client)
assert payload.get('match_source') is None
def test_workspace_file_check_run_for_log_lazy_binds_via_session_query(app, client):
"""chat_log 尚无 run_id 时,for-log 应按 session/query 兜底匹配并回写。"""
with app.app_context():
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-LAZY',
schedule_task_id=task.id,
status='running',
trigger_type='dify_chatflow',
api_request_json={
'bind_session_id': 'sess-lazy-bind',
'bind_user_message': '立即执行文件检核',
},
)
db.session.add(run)
db.session.commit()
log = ChatLog(
user_id=admin.id,
agent_id=1,
query='立即执行文件检核',
answer='检核已启动',
session_id='sess-lazy-bind',
)
db.session.add(log)
db.session.commit()
task_id = task.id
chat_log_id = log.id
run_id = run.id
res = client.get(
f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
headers={'X-Username': 'admin'},
)
assert res.status_code == 200
payload = res.get_json()
assert payload['run']['run_id'] == run_id
assert payload['match_source'] == 'chat_log'
with app.app_context():
rebound = db.session.get(ChatLog, chat_log_id)
assert rebound.run_id == run_id
def test_workspace_file_check_run_for_log_reads_bound_run_id(app, client):
with app.app_context():
admin = _mk_admin()
@@ -12,12 +12,14 @@ import { Bot, Plus, Trash2, Users } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import AgentPermissionModal from './components/AgentPermissionModal.vue';
import AgentTestModal from './components/AgentTestModal.vue';
import AgentToolRunProgressConfig from './components/AgentToolRunProgressConfig.vue';
import { useAgentsAdmin } from './composables/useAgentsAdmin';
const { t } = useI18n();
const {
agents,
scheduleTasks,
activeUsers,
isLoading,
isSaving,
@@ -195,6 +197,12 @@ onMounted(() => {
</div>
</div>
</div>
<AgentToolRunProgressConfig
v-if="form.type === 'api' && form.dify_app_type !== 'workflow'"
:form="form"
:schedule-tasks="scheduleTasks"
/>
</div>
<div class="flex justify-end">
<button type="button" class="btn-primary btn-lg" @click="submitAgent">
@@ -0,0 +1,75 @@
/**
* features/admin/modules/agents/components/AgentToolRunProgressConfig.vue
* 用途:应用管理表单中的 tool_run_progress 能力配置区块。
* 依赖:agent.types AgentFormState、schedule.types ScheduleTask、vue-i18n。
* 逻辑:AgentsPage 在 API 集成类型下挂载本组件;schedule_task_id 写入 extra_config.tool_run_progress。
*/
<script setup lang="ts">
import type { AgentFormState } from '@/features/admin/types/agent.types';
import type { ScheduleTask } from '@/shared/types/schedule.types';
defineProps<{
form: AgentFormState;
scheduleTasks: ScheduleTask[];
}>();
</script>
<template>
<div class="col-span-1 md:col-span-2 rounded-2xl border border-default bg-surface-soft/40 p-5 space-y-4">
<div class="flex items-start justify-between gap-3">
<div>
<h4 class="text-sm font-semibold text-primary">{{ $t('admin.agent.toolRunProgress.title') }}</h4>
<p class="mt-1 text-xs text-muted">{{ $t('admin.agent.toolRunProgress.subtitle') }}</p>
</div>
<label class="inline-flex items-center gap-2 text-sm text-secondary shrink-0">
<input v-model="form.tool_run_progress_enabled" type="checkbox" class="admin-checkbox" />
<span>{{ $t('admin.agent.toolRunProgress.enable') }}</span>
</label>
</div>
<template v-if="form.tool_run_progress_enabled">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">
{{ $t('admin.agent.toolRunProgress.scheduleTaskId') }}
</label>
<select
v-model="form.schedule_task_id"
class="w-full input-field text-sm"
:disabled="scheduleTasks.length === 0"
>
<option :value="null">
{{ scheduleTasks.length === 0
? $t('admin.agent.toolRunProgress.noScheduleTasks')
: $t('admin.agent.toolRunProgress.selectScheduleTask') }}
</option>
<option v-for="task in scheduleTasks" :key="task.id" :value="task.id">
{{ task.name }}
</option>
</select>
<p class="text-xs text-muted">{{ $t('admin.agent.toolRunProgress.scheduleTaskHint') }}</p>
</div>
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">
{{ $t('admin.agent.toolRunProgress.pollInterval') }}
</label>
<input
v-model.number="form.poll_interval_seconds"
type="number"
min="1"
max="30"
class="w-full input-field text-sm"
/>
</div>
<div class="md:col-span-2">
<label class="inline-flex items-center gap-2 text-sm text-secondary">
<input v-model="form.lock_input_when_running" type="checkbox" class="admin-checkbox" />
<span>{{ $t('admin.agent.toolRunProgress.lockInput') }}</span>
</label>
</div>
</div>
</template>
</div>
</template>
@@ -16,10 +16,12 @@ import {
testAdminAgent,
updateAdminAgent,
} from '@/features/admin/api/admin.api';
import { listAdminSchedules } from '@/features/admin/api/schedule.api';
import { useMessage } from '@/shared/composables/useMessage';
import type { AdminUserRow } from '@/features/admin/types/admin.types';
import type { AgentFormState, AgentRow, AgentSuggestedQuestionItem, AgentTestResult } from '@/features/admin/types/agent.types';
import { createEmptyAgentForm } from '@/features/admin/types/agent.types';
import type { ScheduleTask } from '@/shared/types/schedule.types';
const normalizeSuggestedQuestions = (value: unknown): AgentSuggestedQuestionItem[] => {
if (!Array.isArray(value)) return [];
@@ -37,12 +39,65 @@ const normalizeSuggestedQuestions = (value: unknown): AgentSuggestedQuestionItem
.filter((item): item is AgentSuggestedQuestionItem => !!item);
};
/**
* 从 Agent extra_config 解析 tool_run_progress 表单字段。
* 核心逻辑:capabilities 含 tool_run_progress 时视为启用;task_id 与 schedule_task_id 等价。
*/
const parseToolRunProgressFromExtra = (extra: Record<string, unknown> | undefined) => {
const capabilities = Array.isArray(extra?.capabilities)
? extra.capabilities.map((item) => String(item))
: [];
const enabled = capabilities.includes('tool_run_progress');
const cfg = extra?.tool_run_progress && typeof extra.tool_run_progress === 'object'
? (extra.tool_run_progress as Record<string, unknown>)
: {};
const rawTaskId = cfg.schedule_task_id ?? cfg.task_id;
const parsedTaskId = rawTaskId != null && rawTaskId !== '' ? Number(rawTaskId) : null;
const pollRaw = Number(cfg.poll_interval_seconds);
return {
tool_run_progress_enabled: enabled,
schedule_task_id: Number.isFinite(parsedTaskId) && parsedTaskId! > 0 ? parsedTaskId : null,
poll_interval_seconds: Number.isFinite(pollRaw) && pollRaw > 0 ? Math.min(pollRaw, 30) : 2,
lock_input_when_running: cfg.lock_input_when_running !== false,
};
};
/**
* 将表单中的 tool_run_progress 字段写入 extra_config。
* 核心逻辑:启用时追加 capabilities 并写入 schedule_task_id;禁用时移除能力声明。
*/
const applyToolRunProgressToExtra = (extraConfig: Record<string, unknown>, form: AgentFormState): void => {
const capabilities = Array.isArray(extraConfig.capabilities)
? extraConfig.capabilities.map((item) => String(item)).filter((item) => item !== 'tool_run_progress')
: [];
if (form.tool_run_progress_enabled) {
capabilities.push('tool_run_progress');
extraConfig.capabilities = capabilities;
extraConfig.tool_run_progress = {
type: 'file_check',
schedule_task_id: form.schedule_task_id,
poll_interval_seconds: form.poll_interval_seconds,
lock_input_when_running: form.lock_input_when_running,
};
return;
}
if (capabilities.length) {
extraConfig.capabilities = capabilities;
} else {
delete extraConfig.capabilities;
}
delete extraConfig.tool_run_progress;
};
export function useAgentsAdmin() {
const { t } = useI18n();
const msg = useMessage();
const agents = ref<AgentRow[]>([]);
const users = ref<AdminUserRow[]>([]);
const scheduleTasks = ref<ScheduleTask[]>([]);
const isLoading = ref(true);
const isSaving = ref(false);
const isEditing = ref(false);
@@ -82,9 +137,18 @@ export function useAgentsAdmin() {
}
};
const loadScheduleTasks = async (): Promise<void> => {
try {
scheduleTasks.value = await listAdminSchedules();
} catch (e) {
console.error('Error loading schedule tasks:', e);
scheduleTasks.value = [];
}
};
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await Promise.all([loadAgents(), loadUsers()]);
await Promise.all([loadAgents(), loadUsers(), loadScheduleTasks()]);
isLoading.value = false;
};
@@ -95,6 +159,10 @@ export function useAgentsAdmin() {
};
const selectAgent = (agent: AgentRow): void => {
const extra = (agent.extra_config && typeof agent.extra_config === 'object')
? agent.extra_config
: {};
const toolRunProgress = parseToolRunProgressFromExtra(extra);
selectedAgentId.value = agent.id;
form.value = {
id: agent.id,
@@ -109,6 +177,7 @@ export function useAgentsAdmin() {
suggested_questions_style: agent.extra_config?.suggested_questions_style === 'styled' ? 'styled' : 'plain',
suggested_questions: normalizeSuggestedQuestions(agent.extra_config?.suggested_questions),
is_active: agent.is_active,
...toolRunProgress,
};
isEditing.value = true;
};
@@ -141,14 +210,30 @@ export function useAgentsAdmin() {
msg.warning(t('admin.dept.msg.nameRequired'));
return;
}
const supportsToolRunProgress = form.value.type === 'api' && form.value.dify_app_type !== 'workflow';
if (supportsToolRunProgress && form.value.tool_run_progress_enabled && !form.value.schedule_task_id) {
msg.warning(t('admin.agent.toolRunProgress.scheduleTaskRequired'));
return;
}
isSaving.value = true;
const extra_config: Record<string, unknown> = {};
const editingAgent = isEditing.value
? agents.value.find((agent) => agent.id === form.value.id)
: null;
const extra_config: Record<string, unknown> = {
...(editingAgent?.extra_config && typeof editingAgent.extra_config === 'object'
? editingAgent.extra_config
: {}),
};
if (form.value.type === 'iframe' && form.value.iframe_url) {
extra_config.iframe_url = form.value.iframe_url;
} else {
delete extra_config.iframe_url;
}
if (form.value.type === 'api') {
extra_config.dify_app_type = form.value.dify_app_type === 'workflow' ? 'workflow' : 'chatflow';
} else {
delete extra_config.dify_app_type;
}
extra_config.suggested_questions_style = form.value.suggested_questions_style === 'styled' ? 'styled' : 'plain';
extra_config.suggested_questions = form.value.suggested_questions
@@ -157,6 +242,11 @@ export function useAgentsAdmin() {
group: String(item.group || '').trim(),
}))
.filter((item) => item.question);
if (supportsToolRunProgress) {
applyToolRunProgressToExtra(extra_config, form.value);
} else {
applyToolRunProgressToExtra(extra_config, { ...form.value, tool_run_progress_enabled: false });
}
try {
const editingId = isEditing.value ? Number(form.value.id) : null;
@@ -310,6 +400,7 @@ export function useAgentsAdmin() {
return {
agents,
users,
scheduleTasks,
activeUsers,
isLoading,
isSaving,
@@ -46,6 +46,12 @@ export interface AgentFormState {
suggested_questions_style: 'plain' | 'styled';
suggested_questions: AgentSuggestedQuestionItem[];
is_active: boolean;
/** 是否启用 extra_config.capabilities 中的 tool_run_progress */
tool_run_progress_enabled: boolean;
/** 对应 ScheduleTask.id,写入 extra_config.tool_run_progress.schedule_task_id */
schedule_task_id: number | null;
poll_interval_seconds: number;
lock_input_when_running: boolean;
}
export const createEmptyAgentForm = (): AgentFormState => ({
@@ -60,4 +66,8 @@ export const createEmptyAgentForm = (): AgentFormState => ({
suggested_questions_style: 'plain',
suggested_questions: [],
is_active: true,
tool_run_progress_enabled: false,
schedule_task_id: null,
poll_interval_seconds: 2,
lock_input_when_running: true,
});
@@ -4,7 +4,7 @@
* 依赖:useToolRunProgress、toolRunProgressConfig、ChatMessage。
* 逻辑:按助手消息 ChatLog.run_id 展示进度,每轮问答独立绑定;无 run_id 时不展示进度卡片。
* 逻辑:仅当 chat_logs.run_id 已绑定(消息含 run_id 或 for-log 已解析到批次)时展示进度卡片;未绑定时不展示等待条,后台仍轮询 for-log。
*/
@@ -32,6 +32,7 @@ import {
isRunningToolRunStatus,
resolveScheduleTaskId,
resolveMessageAnchorKey,
resolveToolRunProgressOptions,
} from '../utils/toolRunProgressConfig';
@@ -62,6 +63,8 @@ export function useChatPageToolRun(ctx: ChatPageToolRunContext) {
const pollingChatLogIds = ref<number[]>([]);
const emptyPollCounts = ref<Record<number, number>>({});
let pollTimer: number | undefined;
@@ -108,6 +111,8 @@ export function useChatPageToolRun(ctx: ChatPageToolRunContext) {
const boundScheduleTaskId = computed(() => resolveScheduleTaskId(rawToolRunConfig.value));
const progressPollOptions = computed(() => resolveToolRunProgressOptions(rawToolRunConfig.value));
const clearPollTimer = () => {
@@ -246,6 +251,12 @@ export function useChatPageToolRun(ctx: ChatPageToolRunContext) {
storeRunPayload(payload.run, chatLogId);
const nextEmptyCounts = { ...emptyPollCounts.value };
delete nextEmptyCounts[chatLogId];
emptyPollCounts.value = nextEmptyCounts;
const msg = ctx.messages.value[messageIndex];
if (msg && !getRunIdFromMessage(msg)) {
@@ -254,6 +265,32 @@ export function useChatPageToolRun(ctx: ChatPageToolRunContext) {
}
} else {
const nextCount = (emptyPollCounts.value[chatLogId] || 0) + 1;
emptyPollCounts.value = {
...emptyPollCounts.value,
[chatLogId]: nextCount,
};
const emptyPollMax = progressPollOptions.value.empty_poll_max;
if (nextCount >= emptyPollMax) {
chatLogErrors.value = {
...chatLogErrors.value,
[chatLogId]: '暂未找到关联的检核任务,请稍后刷新或查看排程执行记录',
};
}
}
const nextErrors = { ...chatLogErrors.value };
@@ -314,6 +351,8 @@ export function useChatPageToolRun(ctx: ChatPageToolRunContext) {
pollingChatLogIds.value = [];
emptyPollCounts.value = {};
return;
}
@@ -398,7 +437,19 @@ export function useChatPageToolRun(ctx: ChatPageToolRunContext) {
const hasRunning = Object.values(nextRuns).some((run) => isRunningToolRunStatus(run.status));
if (hasRunning) schedulePoll();
const emptyPollMax = progressPollOptions.value.empty_poll_max;
const hasPendingChatLogs = chatLogIds.some((chatLogId) => {
if (chatLogRunMap.value[chatLogId]) return false;
if (chatLogErrors.value[chatLogId]) return false;
return (emptyPollCounts.value[chatLogId] || 0) < emptyPollMax;
});
if (hasRunning || hasPendingChatLogs) schedulePoll();
};
@@ -424,6 +475,8 @@ export function useChatPageToolRun(ctx: ChatPageToolRunContext) {
clearPollTimer();
emptyPollCounts.value = {};
},
);
@@ -532,7 +585,7 @@ export function useChatPageToolRun(ctx: ChatPageToolRunContext) {
* 判断是否在该助手消息后展示进度卡片。
* 核心逻辑:已解析到 run_id 时展示;执行中、已完成、加载中或查询报错均保留卡片,无 run_id 不展示。
* 核心逻辑:chat_logs.run_id 未绑定时不展示;已解析到 run_id 后展示进度/加载/报错状态。
*/
+13 -1
View File
@@ -181,7 +181,19 @@
"testDone": "Test completed.",
"testFailed": "Test failed.",
"testFailedRequestException": "Test failed: request exception occurred.",
"networkError": "Network error"
"networkError": "Network error",
"toolRunProgress": {
"title": "Task Progress",
"subtitle": "When enabled, users can track long-running tasks such as file checks in real time during chat",
"enable": "Show task progress",
"scheduleTaskId": "Linked schedule",
"selectScheduleTask": "Select a schedule to link",
"noScheduleTasks": "No schedules available. Create one in Schedule Management first",
"scheduleTaskHint": "Choose the check schedule for this app to match progress and history",
"pollInterval": "Progress refresh interval (seconds)",
"lockInput": "Prevent sending new messages while a task is running",
"scheduleTaskRequired": "Please select a linked schedule first"
}
},
"question": {
"title": "Common Questions",
+13 -1
View File
@@ -181,7 +181,19 @@
"testDone": "ทดสอบเสร็จสิ้น",
"testFailed": "ทดสอบล้มเหลว",
"testFailedRequestException": "ทดสอบล้มเหลว: เกิดข้อผิดพลาดระหว่างการร้องขอ",
"networkError": "เครือข่ายผิดพลาด"
"networkError": "เครือข่ายผิดพลาด",
"toolRunProgress": {
"title": "ความคืบหน้างาน",
"subtitle": "เมื่อเปิดใช้ ผู้ใช้สามารถติดตามงานที่ใช้เวลานาน เช่น การตรวจไฟล์ ได้แบบเรียลไทม์ในแชท",
"enable": "แสดงความคืบหน้างาน",
"scheduleTaskId": "เชื่อมกับตารางงาน",
"selectScheduleTask": "เลือกตารางงานที่ต้องการเชื่อม",
"noScheduleTasks": "ยังไม่มีตารางงาน โปรดสร้างในเมนูจัดการตารางงานก่อน",
"scheduleTaskHint": "เลือกตารางงานตรวจสอบที่สอดคล้องกับแอปนี้ เพื่อจับคู่ความคืบหน้าและประวัติ",
"pollInterval": "ช่วงรีเฟรชความคืบหน้า (วินาที)",
"lockInput": "ห้ามส่งข้อความใหม่ขณะงานกำลังทำงาน",
"scheduleTaskRequired": "โปรดเลือกตารางงานที่เชื่อมก่อน"
}
},
"question": {
"title": "คำถามทั่วไป",
+13 -1
View File
@@ -182,7 +182,19 @@
"testDone": "测试已完成。",
"testFailed": "测试失败。",
"testFailedRequestException": "测试失败:请求过程出现异常。",
"networkError": "网络错误"
"networkError": "网络错误",
"toolRunProgress": {
"title": "任务进度",
"subtitle": "开启后,用户在对话中发起检核等耗时任务时,可实时查看执行进度",
"enable": "显示任务进度",
"scheduleTaskId": "关联排程任务",
"selectScheduleTask": "请选择要关联的排程任务",
"noScheduleTasks": "暂无可选排程,请先在「排程管理」中创建",
"scheduleTaskHint": "选择该应用对应的检核排程,用于匹配任务进度与历史记录",
"pollInterval": "进度刷新间隔(秒)",
"lockInput": "任务执行期间禁止发送新消息",
"scheduleTaskRequired": "请先选择关联的排程任务"
}
},
"question": {
"title": "常用问题",
+13 -1
View File
@@ -181,7 +181,19 @@
"testDone": "測試已完成。",
"testFailed": "測試失敗。",
"testFailedRequestException": "測試失敗:請求過程發生異常。",
"networkError": "網路錯誤"
"networkError": "網路錯誤",
"toolRunProgress": {
"title": "任務進度",
"subtitle": "開啟後,使用者在對話中發起檢核等耗時任務時,可即時查看執行進度",
"enable": "顯示任務進度",
"scheduleTaskId": "關聯排程任務",
"selectScheduleTask": "請選擇要關聯的排程任務",
"noScheduleTasks": "暫無可選排程,請先在「排程管理」中建立",
"scheduleTaskHint": "選擇該應用對應的檢核排程,用於匹配任務進度與歷史記錄",
"pollInterval": "進度刷新間隔(秒)",
"lockInput": "任務執行期間禁止發送新訊息",
"scheduleTaskRequired": "請先選擇關聯的排程任務"
}
},
"question": {
"title": "常用問題",