CallMonitor.tsx 12.3 KB
import { useEffect, useState } from 'react';
import { Tabs, Table, Card, Tag, Space, Button, Tooltip, message, Modal, Input } 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 /> },
};

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}」吗?`,
    okText: '取消任务',
    okType: 'danger',
    cancelText: '返回',
    onOk: async () => {
      try {
        await useAsyncTaskStore.getState().cancelTask(record.id);
        message.success('任务已取消');
      } 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 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();
    } else {
      fetchTasks();
    }
  }, [activeTab, fetchRecords, fetchTasks]);

  const handleRefresh = () => {
    if (activeTab === 'calls') {
      fetchRecords();
    } else {
      fetchTasks({ task_id: taskSearchId || undefined });
    }
  };

  const handleTaskSearch = (value: string) => {
    setTaskSearchId(value);
    fetchTasks({ page: 1, task_id: value || undefined });
  };

  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: (
                <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 }),
                  }}
                />
              ),
            },
            {
              key: 'tasks',
              label: (
                <span>
                  <SwapOutlined /> 异步任务
                </span>
              ),
              children: (
                <div>
                  <div className="task-search-bar">
                    <Input.Search
                      placeholder="搜索任务 ID..."
                      allowClear
                      value={taskSearchId}
                      onChange={(e) => setTaskSearchId(e.target.value)}
                      onSearch={handleTaskSearch}
                      style={{ width: 320 }}
                      enterButton
                    />
                  </div>
                  <Table
                    dataSource={tasks}
                    columns={taskColumns}
                    rowKey="id"
                    loading={atLoading}
                    className="page-table"
                    style={{ borderTop: '1px solid var(--color-border-light)' }}
                  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) => fetchTasks({ page: p, page_size: ps, task_id: taskSearchId || undefined }),
                  }}
                />
                </div>
              ),
            },
          ]}
        />
      </Card>

      <CallAssemblyDetail
        open={detailOpen}
        callId={detailCallId}
        onClose={() => {
          setDetailOpen(false);
          setDetailCallId(null);
        }}
      />
    </>
  );
}