All files / src/components/Automation ExecutionResult.tsx

0% Statements 0/277
0% Branches 0/1
0% Functions 0/1
0% Lines 0/277

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
/**
 * ExecutionResult - Execution Result Display Component
 *
 * Displays the result of hand or workflow executions with
 * status, output, and error information.
 *
 * @module components/Automation/ExecutionResult
 */
 
import { useState, useCallback, useMemo } from 'react';
import type { RunInfo } from '../../types/automation';
import {
  CheckCircle,
  XCircle,
  Clock,
  AlertTriangle,
  ChevronDown,
  ChevronUp,
  Copy,
  Download,
  RefreshCw,
  ExternalLink,
  FileText,
  Code,
  Image,
  FileSpreadsheet,
} from 'lucide-react';
import { useToast } from '../ui/Toast';
 
// === Status Config ===
 
const STATUS_CONFIG = {
  completed: {
    label: '完成',
    icon: CheckCircle,
    className: 'text-green-500',
    bgClass: 'bg-green-50 dark:bg-green-900/20',
  },
  failed: {
    label: '失败',
    icon: XCircle,
    className: 'text-red-500',
    bgClass: 'bg-red-50 dark:bg-red-900/20',
  },
  running: {
    label: '运行中',
    icon: RefreshCw,
    className: 'text-blue-500 animate-spin',
    bgClass: 'bg-blue-50 dark:bg-blue-900/20',
  },
  needs_approval: {
    label: '待审批',
    icon: AlertTriangle,
    className: 'text-yellow-500',
    bgClass: 'bg-yellow-50 dark:bg-yellow-900/20',
  },
  cancelled: {
    label: '已取消',
    icon: XCircle,
    className: 'text-gray-500',
    bgClass: 'bg-gray-50 dark:bg-gray-900/20',
  },
};
 
// === Component Props ===
 
interface ExecutionResultProps {
  run: RunInfo;
  itemType: 'hand' | 'workflow';
  itemName: string;
  onRerun?: () => void;
  onViewDetails?: () => void;
  compact?: boolean;
}
 
// === Helper Functions ===
 
function formatDuration(startedAt: string, completedAt?: string): string {
  const start = new Date(startedAt).getTime();
  const end = completedAt ? new Date(completedAt).getTime() : Date.now();
  const diffMs = end - start;
 
  const seconds = Math.floor(diffMs / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
 
  if (hours > 0) {
    return `${hours}h ${minutes % 60}m`;
  }
  if (minutes > 0) {
    return `${minutes}m ${seconds % 60}s`;
  }
  return `${seconds}s`;
}
 
function detectOutputType(output: unknown): 'text' | 'json' | 'markdown' | 'code' | 'image' | 'data' {
  if (!output) return 'text';
 
  if (typeof output === 'string') {
    // Check for image URL
    if (output.match(/\.(png|jpg|jpeg|gif|webp|svg)$/i)) {
      return 'image';
    }
    // Check for markdown
    if (output.includes('#') || output.includes('**') || output.includes('```')) {
      return 'markdown';
    }
    // Check for code
    if (output.includes('function ') || output.includes('import ') || output.includes('class ')) {
      return 'code';
    }
    // Try to parse as JSON
    try {
      JSON.parse(output);
      return 'json';
    } catch {
      return 'text';
    }
  }
 
  // Object/array types
  if (typeof output === 'object') {
    return 'json';
  }
 
  return 'text';
}
 
function formatOutput(output: unknown, type: string): string {
  if (!output) return '无输出';
 
  if (type === 'json') {
    try {
      return JSON.stringify(output, null, 2);
    } catch {
      return String(output);
    }
  }
 
  return String(output);
}
 
// === Output Viewer Component ===
 
interface OutputViewerProps {
  output: unknown;
  type: string;
}
 
function OutputViewer({ output, type }: OutputViewerProps) {
  const [copied, setCopied] = useState(false);
  const { toast } = useToast();
 
  const handleCopy = useCallback(async () => {
    const text = formatOutput(output, type);
    await navigator.clipboard.writeText(text);
    setCopied(true);
    toast('已复制到剪贴板', 'success');
    setTimeout(() => setCopied(false), 2000);
  }, [output, type, toast]);
 
  const handleDownload = useCallback(() => {
    const text = formatOutput(output, type);
    const blob = new Blob([text], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `output-${Date.now()}.${type === 'json' ? 'json' : 'txt'}`;
    a.click();
    URL.revokeObjectURL(url);
  }, [output, type]);
 
  // Image preview
  if (type === 'image' && typeof output === 'string') {
    return (
      <div className="relative">
        <img
          src={output}
          alt="Output"
          className="max-w-full rounded-lg"
        />
        <div className="absolute top-2 right-2 flex gap-1">
          <button
            onClick={() => window.open(output, '_blank')}
            className="p-1.5 bg-black/50 rounded hover:bg-black/70 text-white"
          >
            <ExternalLink className="w-4 h-4" />
          </button>
        </div>
      </div>
    );
  }
 
  // Text/JSON/Code output
  const content = formatOutput(output, type);
 
  return (
    <div className="relative">
      <pre className="p-3 bg-gray-900 dark:bg-gray-950 rounded-lg text-sm text-gray-100 overflow-x-auto max-h-64 overflow-y-auto">
        {content}
      </pre>
      <div className="absolute top-2 right-2 flex gap-1">
        <button
          onClick={handleCopy}
          className="p-1.5 bg-gray-700 rounded hover:bg-gray-600 text-gray-300"
          title="复制"
        >
          {copied ? <CheckCircle className="w-4 h-4 text-green-400" /> : <Copy className="w-4 h-4" />}
        </button>
        <button
          onClick={handleDownload}
          className="p-1.5 bg-gray-700 rounded hover:bg-gray-600 text-gray-300"
          title="下载"
        >
          <Download className="w-4 h-4" />
        </button>
      </div>
    </div>
  );
}
 
// === Main Component ===
 
export function ExecutionResult({
  run,
  itemType,
  itemName,
  onRerun,
  onViewDetails,
  compact = false,
}: ExecutionResultProps) {
  const [expanded, setExpanded] = useState(!compact);
 
  const statusConfig = STATUS_CONFIG[run.status as keyof typeof STATUS_CONFIG] || STATUS_CONFIG.completed;
  const StatusIcon = statusConfig.icon;
 
  // Safely extract error message as string
  const getErrorMessage = (): string | null => {
    if (typeof run.error === 'string' && run.error.length > 0) {
      return run.error;
    }
    return null;
  };
  const errorMessage = getErrorMessage();
 
  const outputType = useMemo(() => detectOutputType(run.output), [run.output]);
  const duration = useMemo(() => {
    if (run.duration) return `${run.duration}s`;
    if (run.completedAt && run.startedAt) {
      return formatDuration(run.startedAt, run.completedAt);
    }
    return null;
  }, [run.duration, run.startedAt, run.completedAt]);
 
  // Compact mode
  if (compact && !expanded) {
    return (
      <div
        className={`flex items-center gap-3 p-3 rounded-lg ${statusConfig.bgClass} cursor-pointer`}
        onClick={() => setExpanded(true)}
      >
        <StatusIcon className={`w-5 h-5 ${statusConfig.className}`} />
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2">
            <span className="font-medium text-gray-900 dark:text-white truncate">
              {itemName}
            </span>
            <span className={`text-xs ${statusConfig.className}`}>
              {statusConfig.label}
            </span>
          </div>
          {duration && (
            <span className="text-xs text-gray-500 dark:text-gray-400">
              耗时: {duration}
            </span>
          )}
        </div>
        <ChevronDown className="w-4 h-4 text-gray-400" />
      </div>
    );
  }
 
  return (
    <div className={`rounded-lg border ${statusConfig.bgClass} border-gray-200 dark:border-gray-700 overflow-hidden`}>
      {/* Header */}
      <div
        className="flex items-center justify-between px-4 py-3 cursor-pointer"
        onClick={compact ? () => setExpanded(false) : undefined}
      >
        <div className="flex items-center gap-3">
          <StatusIcon className={`w-5 h-5 ${statusConfig.className}`} />
          <div>
            <div className="flex items-center gap-2">
              <span className="font-medium text-gray-900 dark:text-white">
                {itemName}
              </span>
              <span className={`text-xs px-2 py-0.5 rounded-full ${statusConfig.className} ${statusConfig.bgClass}`}>
                {statusConfig.label}
              </span>
              <span className="text-xs text-gray-500 dark:text-gray-400">
                {itemType === 'hand' ? '自主能力' : '工作流'}
              </span>
            </div>
            {run.runId && (
              <span className="text-xs text-gray-400 dark:text-gray-500">
                执行ID: {run.runId}
              </span>
            )}
          </div>
        </div>
 
        <div className="flex items-center gap-2">
          {duration && (
            <span className="text-xs text-gray-500 dark:text-gray-400">
              耗时: {duration}
            </span>
          )}
          {compact && (
            <ChevronUp className="w-4 h-4 text-gray-400" />
          )}
        </div>
      </div>
 
      {/* Body */}
      {expanded && (
        <div className="px-4 pb-4 space-y-3">
          {/* Error */}
          {(() => {
            if (!errorMessage) return null;
            return (
              <div className="p-3 bg-red-50 dark:bg-red-900/20 rounded-lg">
                <p className="text-sm font-medium text-red-700 dark:text-red-400 mb-1">错误信息</p>
                <p className="text-sm text-red-600 dark:text-red-300">{errorMessage}</p>
              </div>
            );
          })()}
 
          {/* Output */}
          {run.output !== undefined && run.output !== null && (
            <div>
              <div className="flex items-center justify-between mb-2">
                <p className="text-sm font-medium text-gray-700 dark:text-gray-300">输出结果</p>
                <span className="text-xs text-gray-500 dark:text-gray-400 flex items-center gap-1">
                  {outputType === 'json' && <Code className="w-3 h-3" />}
                  {outputType === 'markdown' && <FileText className="w-3 h-3" />}
                  {outputType === 'image' && <Image className="w-3 h-3" />}
                  {outputType === 'data' && <FileSpreadsheet className="w-3 h-3" />}
                  {outputType.toUpperCase()}
                </span>
              </div>
              <OutputViewer output={run.output} type={outputType} />
            </div>
          )}
 
          {/* Timestamps */}
          <div className="flex items-center gap-4 text-xs text-gray-500 dark:text-gray-400">
            <span className="flex items-center gap-1">
              <Clock className="w-3 h-3" />
              开始: {new Date(run.startedAt).toLocaleString('zh-CN')}
            </span>
            {run.completedAt && (
              <span>
                完成: {new Date(run.completedAt).toLocaleString('zh-CN')}
              </span>
            )}
          </div>
 
          {/* Actions */}
          <div className="flex items-center gap-2 pt-2">
            {onRerun && (
              <button
                onClick={onRerun}
                className="px-3 py-1.5 text-sm bg-orange-500 text-white rounded-md hover:bg-orange-600 flex items-center gap-1"
              >
                <RefreshCw className="w-3.5 h-3.5" />
                重新执行
              </button>
            )}
            {onViewDetails && (
              <button
                onClick={onViewDetails}
                className="px-3 py-1.5 text-sm border border-gray-200 dark:border-gray-700 rounded-md hover:bg-gray-50 dark:hover:bg-gray-800 text-gray-700 dark:text-gray-300 flex items-center gap-1"
              >
                <ExternalLink className="w-3.5 h-3.5" />
                查看详情
              </button>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
 
export default ExecutionResult;