CallMonitor.tsx
22.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
import { useEffect, useState } from 'react';
import dayjs from 'dayjs';
import { Tabs, Table, Card, Tag, Space, Button, Tooltip, message, Modal, Input, Select, DatePicker, Row, Col } from 'antd';
import {
ReloadOutlined, StopOutlined, ThunderboltOutlined,
CheckCircleOutlined, CloseCircleOutlined, ClockCircleOutlined,
SwapOutlined, MinusCircleOutlined,
} from '@ant-design/icons';
import { useCallRecordStore } from '../../stores/callRecordStore';
import { useAsyncTaskStore } from '../../stores/asyncTaskStore';
import CallAssemblyDetail from './CallAssemblyDetail';
import type { CallRecord, AsyncTask } from '../../types';
const CALL_STATUS_MAP: Record<string, { label: string; color: string; icon: React.ReactNode }> = {
pending: { label: '待调度', color: 'default', icon: <ClockCircleOutlined /> },
success: { label: '成功', color: 'success', icon: <CheckCircleOutlined /> },
failed: { label: '失败', color: 'error', icon: <CloseCircleOutlined /> },
cancelled: { label: '已取消', color: 'warning', icon: <MinusCircleOutlined /> },
};
const TASK_STATUS_MAP: Record<string, { label: string; color: string; icon: React.ReactNode }> = {
pending: { label: '等待中', color: 'default', icon: <ClockCircleOutlined /> },
processing: { label: '处理中', color: 'processing', icon: <SwapOutlined /> },
success: { label: '已完成', color: 'success', icon: <CheckCircleOutlined /> },
failed: { label: '失败', color: 'error', icon: <CloseCircleOutlined /> },
cancelled: { label: '已取消', color: 'warning', icon: <MinusCircleOutlined /> },
};
function renderTokenBadge(tokens: number) {
const color = tokens > 1000 ? 'var(--color-warning)' : tokens > 100 ? 'var(--color-primary)' : 'var(--color-text-tertiary)';
return <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 13, fontWeight: 600, color }}>{tokens.toLocaleString()}</span>;
}
function renderDuration(ms: number) {
const s = (ms / 1000).toFixed(2);
return <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 13 }}>{s}s</span>;
}
const callColumns = [
{
title: '模型名称',
dataIndex: 'model_name',
key: 'model_name',
width: 140,
render: (val: string) => (
<Space>
<ThunderboltOutlined style={{ color: 'var(--color-primary)' }} />
<span style={{ fontWeight: 500 }}>{val}</span>
</Space>
),
},
{
title: '账号',
dataIndex: 'account_name',
key: 'account_name',
width: 120,
render: (val: string | null) =>
val ? (
<span style={{ color: 'var(--color-text-secondary)' }}>{val}</span>
) : (
<span style={{ color: 'var(--color-text-tertiary)', fontSize: 12 }}>-</span>
),
},
{
title: '状态',
dataIndex: 'status',
key: 'status',
width: 100,
render: (val: string) => {
const s = CALL_STATUS_MAP[val] || { label: val, color: 'default', icon: null };
return (
<Tag color={s.color} className="status-tag">
{s.icon} <span style={{ marginLeft: 4 }}>{s.label}</span>
</Tag>
);
},
},
{
title: 'Token 消耗',
key: 'tokens',
width: 220,
render: (_: unknown, r: CallRecord) => (
<Space size="small">
<span style={{ fontSize: 12, color: 'var(--color-text-tertiary)' }}>P:</span>
{renderTokenBadge(r.prompt_tokens)}
<span style={{ fontSize: 12, color: 'var(--color-text-tertiary)' }}>C:</span>
{renderTokenBadge(r.completion_tokens)}
<span style={{ fontSize: 12, color: 'var(--color-text-tertiary)' }}>Σ:</span>
{renderTokenBadge(r.total_tokens)}
</Space>
),
},
{
title: '耗时',
dataIndex: 'duration_ms',
key: 'duration_ms',
width: 90,
render: renderDuration,
},
{
title: '业务编码',
dataIndex: 'biz_type',
key: 'biz_type',
width: 100,
render: (val: string | null) =>
val ? <Tag>{val}</Tag> : <span style={{ color: 'var(--color-text-tertiary)', fontSize: 12 }}>-</span>,
},
{
title: '调用时间',
dataIndex: 'called_at',
key: 'called_at',
width: 170,
render: (val: string) => {
const d = new Date(val);
return (
<span style={{ fontSize: 13, fontFamily: "'JetBrains Mono', monospace", color: 'var(--color-text-secondary)' }}>
{d.toLocaleString()}
</span>
);
},
},
];
const taskColumns = [
{
title: '任务 ID',
dataIndex: 'id',
key: 'id',
width: 130,
render: (val: string) => (
<Tooltip title={val}>
<code
style={{ fontSize: 12, fontFamily: "'JetBrains Mono', monospace", color: 'var(--color-primary)', fontWeight: 600, cursor: 'pointer' }}
onClick={(e) => { e.stopPropagation(); navigator.clipboard?.writeText(val); }}
>
{val.slice(0, 8)}
</code>
</Tooltip>
),
},
{
title: 'Celery 任务 ID',
dataIndex: 'celery_task_id',
key: 'celery_task_id',
width: 200,
render: (val: string) => (
<code style={{ fontSize: 12, fontFamily: "'JetBrains Mono', monospace", color: 'var(--color-text-secondary)' }}>
{val || '-'}
</code>
),
},
{
title: '状态',
dataIndex: 'status',
key: 'status',
width: 100,
render: (val: string) => {
const s = TASK_STATUS_MAP[val] || { label: val, color: 'default', icon: null };
return (
<Tag color={s.color} className="status-tag">
{s.icon} <span style={{ marginLeft: 4 }}>{s.label}</span>
</Tag>
);
},
},
{
title: '进度',
dataIndex: 'progress',
key: 'progress',
width: 160,
render: (val: number) => (
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<div style={{ flex: 1, height: 6, background: 'var(--color-surface-subtle)', borderRadius: 3, overflow: 'hidden' }}>
<div style={{ width: `${val}%`, height: '100%', background: 'var(--color-primary)', borderRadius: 3, transition: 'width 0.3s' }} />
</div>
<span style={{ fontSize: 12, fontFamily: "'JetBrains Mono', monospace", color: 'var(--color-text-secondary)', minWidth: 30, textAlign: 'right' }}>
{val}%
</span>
</div>
),
},
{
title: '提交时间',
dataIndex: 'submitted_at',
key: 'submitted_at',
width: 170,
render: (val: string) => (
<span style={{ fontSize: 13, fontFamily: "'JetBrains Mono', monospace", color: 'var(--color-text-secondary)' }}>
{new Date(val).toLocaleString()}
</span>
),
},
{
title: '操作',
key: 'action',
width: 100,
render: (_: unknown, record: AsyncTask) =>
(record.status === 'pending' || record.status === 'processing') ? (
<Tooltip title="取消任务">
<Button
type="link"
size="small"
icon={<StopOutlined />}
danger
onClick={() => handleCancel(record)}
className="action-btn"
>
取消
</Button>
</Tooltip>
) : null,
},
];
function handleCancel(record: AsyncTask) {
Modal.confirm({
title: '取消任务',
content: `确定要取消任务「${record.celery_task_id || record.id.slice(0, 8)}」吗?`,
okText: '取消任务',
okType: 'danger',
cancelText: '返回',
onOk: async () => {
try {
await useAsyncTaskStore.getState().cancelTask(record.id);
message.success('任务已取消');
} catch {
message.error('取消失败');
}
},
});
}
function handleBatchCancel(taskIds: string[], setTaskIds: (ids: string[]) => void) {
if (taskIds.length === 0) {
message.warning('请先选择要取消的任务');
return;
}
Modal.confirm({
title: '批量取消任务',
content: `确定要取消选中的 ${taskIds.length} 个任务吗?`,
okText: '批量取消',
okType: 'danger',
cancelText: '返回',
onOk: async () => {
try {
const result = await useAsyncTaskStore.getState().batchCancelTasks(taskIds);
message.success(`批量取消完成:成功 ${result.success_count} 个${result.failed_count ? `,失败 ${result.failed_count} 个` : ''}`);
setTaskIds([]);
} catch {
message.error('批量取消失败');
}
},
});
}
function handleCancelAll(filters?: {
status?: string;
biz_type?: string;
task_id?: string;
start_time?: string;
end_time?: string;
}) {
const hasFilters = filters && Object.values(filters).some(v => v !== undefined);
const filterDesc = hasFilters ? '当前筛选条件下的' : '所有';
Modal.confirm({
title: '取消全部任务',
content: `确定要取消${filterDesc}等待中和处理中的任务吗?此操作不可撤销。`,
okText: '取消全部',
okType: 'danger',
cancelText: '返回',
onOk: async () => {
try {
const result = await useAsyncTaskStore.getState().cancelAllTasks(filters);
message.success(`已取消 ${result.total} 个任务${result.batch_count ? `(分 ${result.batch_count} 批处理)` : ''}`);
} catch {
message.error('取消全部失败');
}
},
});
}
export default function CallMonitor() {
const { records, total: crTotal, page: crPage, pageSize: crPageSize, loading: crLoading, fetchRecords } = useCallRecordStore();
const { tasks, total: atTotal, page: atPage, pageSize: atPageSize, loading: atLoading, fetchTasks } = useAsyncTaskStore();
const [activeTab, setActiveTab] = useState('calls');
const [detailOpen, setDetailOpen] = useState(false);
const [detailCallId, setDetailCallId] = useState<string | null>(null);
const [taskSearchId, setTaskSearchId] = useState('');
const [selectedTaskIds, setSelectedTaskIds] = useState<string[]>([]);
// 调用记录筛选状态
const [filterBizType, setFilterBizType] = useState<string | undefined>(undefined);
const [filterStatus, setFilterStatus] = useState<string | undefined>(undefined);
const [filterAccountName, setFilterAccountName] = useState<string | undefined>(undefined);
const [filterModelName, setFilterModelName] = useState<string | undefined>(undefined);
const [filterDateRange, setFilterDateRange] = useState<[string, string] | null>(null);
const callFilterOptions = useCallRecordStore((s) => s.filterOptions);
const fetchFilterOptions = useCallRecordStore((s) => s.fetchFilterOptions);
// 异步任务筛选状态
const [filterTaskBizType, setFilterTaskBizType] = useState<string | undefined>(undefined);
const [filterTaskStatus, setFilterTaskStatus] = useState<string | undefined>(undefined);
const [filterTaskDateRange, setFilterTaskDateRange] = useState<[string, string] | null>(null);
const buildCallFilterParams = () => ({
biz_type: filterBizType,
status: filterStatus,
account_name: filterAccountName || undefined,
model_name: filterModelName || undefined,
start_time: filterDateRange?.[0],
end_time: filterDateRange?.[1],
});
const buildTaskFilterParams = () => ({
biz_type: filterTaskBizType,
status: filterTaskStatus,
task_id: taskSearchId || undefined,
start_time: filterTaskDateRange?.[0],
end_time: filterTaskDateRange?.[1],
});
const handleRowClick = (record: CallRecord) => {
setDetailCallId(record.id);
setDetailOpen(true);
};
const handleTaskRowClick = (record: AsyncTask) => {
if (record.call_record_id) {
setDetailCallId(record.call_record_id);
setDetailOpen(true);
}
};
useEffect(() => {
if (activeTab === 'calls') {
fetchRecords({ ...buildCallFilterParams() });
} else {
fetchTasks({ ...buildTaskFilterParams() });
}
}, [activeTab, fetchRecords, fetchTasks]);
// 页面加载时获取筛选选项
useEffect(() => {
fetchFilterOptions();
}, [fetchFilterOptions]);
const handleRefresh = () => {
if (activeTab === 'calls') {
fetchRecords({ page: 1, ...buildCallFilterParams() });
} else {
fetchTasks({ page: 1, ...buildTaskFilterParams() });
}
};
const handleCallSearch = () => {
fetchRecords({ page: 1, ...buildCallFilterParams() });
};
const handleTaskFilter = () => {
fetchTasks({ page: 1, ...buildTaskFilterParams() });
};
const handleCallFilterReset = () => {
setFilterBizType(undefined);
setFilterStatus(undefined);
setFilterAccountName(undefined);
setFilterModelName(undefined);
setFilterDateRange(null);
fetchRecords({ page: 1 });
};
const handleTaskFilterReset = () => {
setFilterTaskBizType(undefined);
setFilterTaskStatus(undefined);
setFilterTaskDateRange(null);
setTaskSearchId('');
fetchTasks({ page: 1 });
};
const handleTaskSearch = (value: string) => {
setTaskSearchId(value);
fetchTasks({ page: 1, task_id: value || undefined, ...buildTaskFilterParams() });
};
return (
<>
<div className="page-header">
<div className="page-header-left">
<h4 className="page-header-title">模型调用</h4>
<span className="page-header-desc">监控模型调用记录和异步任务执行状态</span>
</div>
<div className="page-header-actions">
<Button icon={<ReloadOutlined />} onClick={handleRefresh} className="action-btn">刷新</Button>
</div>
</div>
<Card className="page-card" styles={{ body: { padding: 0 } }}>
<Tabs
activeKey={activeTab}
onChange={setActiveTab}
style={{ margin: 0, padding: '0 24px' }}
items={[
{
key: 'calls',
label: (
<span>
<ThunderboltOutlined /> 调用记录
</span>
),
children: (
<div>
{/* 调用记录筛选栏 */}
<div className="filter-bar" style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', padding: '12px 0', borderTop: '1px solid var(--color-border-light)' }}>
<Select
allowClear
placeholder="业务编码"
value={filterBizType}
onChange={(val) => { setFilterBizType(val); }}
style={{ width: 130 }}
options={callFilterOptions.biz_types.map((b) => ({ label: b, value: b }))}
/>
<Select
allowClear
placeholder="状态"
value={filterStatus}
onChange={(val) => { setFilterStatus(val); }}
style={{ width: 110 }}
>
<Select.Option value="success">成功</Select.Option>
<Select.Option value="failed">失败</Select.Option>
<Select.Option value="pending">待调度</Select.Option>
<Select.Option value="cancelled">已取消</Select.Option>
</Select>
<Input
placeholder="账号"
allowClear
value={filterAccountName}
onChange={(e) => setFilterAccountName(e.target.value)}
style={{ width: 130 }}
/>
<Input
placeholder="模型"
allowClear
value={filterModelName}
onChange={(e) => setFilterModelName(e.target.value)}
style={{ width: 140 }}
/>
<DatePicker.RangePicker
value={filterDateRange ? [dayjs(filterDateRange[0]), dayjs(filterDateRange[1])] : null}
onChange={(dates) => {
if (dates && dates[0] && dates[1]) {
setFilterDateRange([dates[0].toISOString(), dates[1].toISOString()]);
} else {
setFilterDateRange(null);
}
}}
style={{ width: 230 }}
/>
<Button type="primary" onClick={handleCallSearch}>查询</Button>
<Button onClick={handleCallFilterReset}>重置</Button>
</div>
<Table
dataSource={records}
columns={callColumns}
rowKey="id"
loading={crLoading}
className="page-table"
style={{ borderTop: '1px solid var(--color-border-light)' }}
onRow={(record: CallRecord) => ({
onClick: () => handleRowClick(record),
style: { cursor: 'pointer' },
})}
pagination={{
current: crPage,
pageSize: crPageSize,
total: crTotal,
showSizeChanger: true,
showQuickJumper: true,
pageSizeOptions: ['10', '20', '50'],
showTotal: (t) => `共 ${t} 条`,
onChange: (p, ps) => fetchRecords({ page: p, page_size: ps, ...buildCallFilterParams() }),
}}
/>
</div>
),
},
{
key: 'tasks',
label: (
<span>
<SwapOutlined /> 异步任务
</span>
),
children: (
<div>
{/* 异步任务筛选栏 */}
<div className="filter-bar" style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', padding: '12px 0', borderTop: '1px solid var(--color-border-light)' }}>
<Select
allowClear
placeholder="业务编码"
value={filterTaskBizType}
onChange={(val) => { setFilterTaskBizType(val); }}
style={{ width: 130 }}
options={callFilterOptions.biz_types.map((b) => ({ label: b, value: b }))}
/>
<Select
allowClear
placeholder="状态"
value={filterTaskStatus}
onChange={(val) => { setFilterTaskStatus(val); }}
style={{ width: 120 }}
>
<Select.Option value="pending">等待中</Select.Option>
<Select.Option value="processing">处理中</Select.Option>
<Select.Option value="success">已完成</Select.Option>
<Select.Option value="failed">失败</Select.Option>
<Select.Option value="cancelled">已取消</Select.Option>
</Select>
<DatePicker.RangePicker
value={filterTaskDateRange ? [dayjs(filterTaskDateRange[0]), dayjs(filterTaskDateRange[1])] : null}
onChange={(dates) => {
if (dates && dates[0] && dates[1]) {
setFilterTaskDateRange([dates[0].toISOString(), dates[1].toISOString()]);
} else {
setFilterTaskDateRange(null);
}
}}
style={{ width: 230 }}
/>
<Button type="primary" onClick={handleTaskFilter}>查询</Button>
<Button onClick={handleTaskFilterReset}>重置</Button>
</div>
<div className="task-search-bar" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '0 0 12px 0' }}>
<Input.Search
placeholder="搜索任务 ID..."
allowClear
value={taskSearchId}
onChange={(e) => setTaskSearchId(e.target.value)}
onSearch={handleTaskSearch}
style={{ width: 320 }}
enterButton
/>
<div style={{ flex: 1 }} />
{selectedTaskIds.length > 0 && (
<span style={{ fontSize: 13, color: 'var(--color-text-secondary)' }}>
已选 {selectedTaskIds.length} 项
</span>
)}
<Button
icon={<StopOutlined />}
danger
disabled={selectedTaskIds.length === 0}
onClick={() => handleBatchCancel(selectedTaskIds, setSelectedTaskIds)}
>
批量取消
</Button>
<Button
icon={<MinusCircleOutlined />}
danger
onClick={() => handleCancelAll(buildTaskFilterParams())}
>
取消全部
</Button>
</div>
<Table
dataSource={tasks}
columns={taskColumns}
rowKey="id"
loading={atLoading}
className="page-table"
style={{ borderTop: '1px solid var(--color-border-light)' }}
rowSelection={{
selectedRowKeys: selectedTaskIds,
onChange: (keys) => setSelectedTaskIds(keys as string[]),
getCheckboxProps: (record: AsyncTask) => ({
disabled: record.status !== 'pending' && record.status !== 'processing',
}),
}}
onRow={(record: AsyncTask) => ({
onClick: () => handleTaskRowClick(record),
style: { cursor: record.call_record_id ? 'pointer' : 'default' },
})}
pagination={{
current: atPage,
pageSize: atPageSize,
total: atTotal,
showSizeChanger: true,
showQuickJumper: true,
pageSizeOptions: ['10', '20', '50'],
showTotal: (t) => `共 ${t} 条`,
onChange: (p, ps) => {
setSelectedTaskIds([]);
fetchTasks({ page: p, page_size: ps, ...buildTaskFilterParams() });
},
}}
/>
</div>
),
},
]}
/>
</Card>
<CallAssemblyDetail
open={detailOpen}
callId={detailCallId}
onClose={() => {
setDetailOpen(false);
setDetailCallId(null);
}}
/>
</>
);
}