Workbench.tsx 36.7 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 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
import { useEffect, useMemo, useRef, useState } from 'react';
import { toast } from 'sonner';
import {
  Loader2,
  Rocket,
  Figma,
  ScrollText,
  Trash2,
  ArrowDownToLine,
  StopCircle,
  Play,
  Square,
  ExternalLink,
  RotateCw,
  MonitorSmartphone,
  Globe,
  Lock,
  LayoutDashboard,
  Layers,
  Boxes,
} from 'lucide-react';
import { api, onSSE, checkBackendHealth } from '@/lib/api';
import { cancelJob, deleteJob, startPreview as startPreviewAction, clearAllJobs } from '@/lib/jobActions';
import type { Job, LogEntry, LogLevel, PreviewState, ProjectRunState, ValidationMode, GenerationTarget, GenerationTargetMode, ProjectProfile, TechStack } from '@/lib/types';
import { STACK_PRESETS } from '@/components/project/profile-presets';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { StatusPill } from '@/components/ui/status-pill';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { modeMeta, modeLabel } from '@/lib/status';
import { cn } from '@/lib/utils';

/* ---------------- log terminal bits (ported from Logs) ---------------- */
const levelStyle: Record<LogLevel, string> = {
  info: 'text-slate-400',
  success: 'text-emerald-400',
  warn: 'text-amber-400',
  error: 'text-rose-400',
  test: 'text-zinc-500',
  log: 'text-zinc-300',
};
const levelTag: Record<LogLevel, string> = {
  info: 'INFO',
  success: 'OK',
  warn: 'WARN',
  error: 'ERR',
  test: 'TEST',
  log: 'LOG',
};

/* ---------------- embed url helpers ---------------- */
const SCHEME_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//;
function parseScheme(url: string | null): 'http' | 'https' | null {
  if (!url) return null;
  const m = /^(https?):\/\//i.exec(url);
  return m ? (m[1].toLowerCase() as 'http' | 'https') : null;
}
const stripScheme = (url: string) => url.replace(SCHEME_RE, '');

function jobProgress(j: Job): {
  value: number;
  indeterminate: boolean;
  tone: 'info' | 'success' | 'danger' | 'brand' | 'neutral';
} {
  if (j.status === 'done') return { value: 100, indeterminate: false, tone: 'success' };
  if (j.status === 'error') return { value: 100, indeterminate: false, tone: 'danger' };
  if (j.status === 'cancelled') return { value: 100, indeterminate: false, tone: 'neutral' };
  if (j.status === 'running') return { value: 0, indeterminate: true, tone: 'info' };
  return { value: 0, indeterminate: false, tone: 'brand' };
}
const isActive = (j: Job) => j.status === 'running' || j.status === 'queued';

const targetModes: { key: GenerationTargetMode; label: string; hint: string }[] = [
  { key: 'standalone', label: '独立预览', hint: '生成到独立目录,可单独预览(默认)' },
  { key: 'new-page', label: '项目内新页', hint: '在目标项目内新增一个页面' },
  { key: 'modify-slot', label: '修改区域', hint: '修改已有页面的指定区域 / 插槽' },
];

export default function Workbench() {
  /* ----- generate form ----- */
  const [figmaUrl, setFigmaUrl] = useState('');
  const [mode, setMode] = useState<ValidationMode>('code');
  const [target, setTarget] = useState<GenerationTarget>({ mode: 'standalone' });
  const [stack, setStack] = useState<TechStack | null>(() => {
    try {
      const saved = localStorage.getItem('coderio.workbench.stack');
      if (saved) return JSON.parse(saved) as TechStack;
    } catch {
      /* ignore */
    }
    // 首次进入默认采用用户常用的 Vue 3 + Element Plus,避免「独立预览忘选技术栈
    // → 静默回退成 React」的踩坑;随后每次选择都会持久化到 localStorage。
    return STACK_PRESETS.find((s) => s.id === 'vue-elementplus') ?? null;
  });
  const [fillContainer, setFillContainer] = useState(true);
  const [projectProfile, setProjectProfile] = useState<ProjectProfile | null>(null);
  const [submitting, setSubmitting] = useState(false);
  // 后端就绪门控:重启后端后引擎加载 + sqlite 初始化完成前端口未开,
  // 此时点「开始生成」会 ECONNREFUSED。boot 期间轮询 /api/health,就绪前禁用按钮。
  const [backendReady, setBackendReady] = useState(true);

  // 持久化技术栈选择,避免刷新 / HMR 后丢失导致「独立预览意外生成 React」。
  useEffect(() => {
    try {
      if (stack) localStorage.setItem('coderio.workbench.stack', JSON.stringify(stack));
      else localStorage.removeItem('coderio.workbench.stack');
    } catch {
      /* ignore */
    }
  }, [stack]);

  // 后端就绪探测:挂载后若后端尚未就绪(刚重启),持续轮询 /api/health,
  // 就绪后放开「开始生成」。后端已在线时首轮即 true,不阻塞正常操作。
  useEffect(() => {
    let alive = true;
    let timer: ReturnType<typeof setTimeout> | undefined;
    const tick = async () => {
      const ok = await checkBackendHealth();
      if (!alive) return;
      if (ok) {
        setBackendReady(true);
        return;
      }
      setBackendReady(false);
      timer = setTimeout(tick, 1500);
    };
    void tick();
    return () => {
      alive = false;
      if (timer) clearTimeout(timer);
    };
  }, []);

  const handleSubmit = async () => {
    if (!figmaUrl.trim()) return toast.error('请填写 Figma 链接');
    if (!figmaUrl.includes('node-id=')) return toast.error('Figma 链接必须包含 ?node-id= 参数');
    if (!backendReady) return toast.error('后端启动中,请稍候…', { description: '引擎与数据库初始化完成后即可生成' });
    setSubmitting(true);
    try {
      const res = await api.generate({
        figmaUrl: figmaUrl.trim(),
        mode,
        target,
        // 仅独立预览时附带自选技术栈;项目模式由「项目接入」画像决定
        stack: target.mode === 'standalone' ? stack : null,
        // 默认撑满容器;固定宽度设计稿可取消
        fillContainer,
      });
      toast.success('已提交生成任务', { description: res.message });
    } catch (e) {
      toast.error('提交失败', { description: e instanceof Error ? e.message : String(e) });
    } finally {
      setSubmitting(false);
    }
  };

  /* ----- logs ----- */
  const [logs, setLogs] = useState<LogEntry[]>([]);
  const [autoScroll, setAutoScroll] = useState(true);
  const logRef = useRef<HTMLDivElement>(null);
  const autoRef = useRef(autoScroll);
  autoRef.current = autoScroll;

  /* ----- jobs ----- */
  const [jobs, setJobs] = useState<Job[]>([]);

  /* ----- preview ----- */
  const [state, setState] = useState<PreviewState | null>(null);
  const [projectRun, setProjectRun] = useState<ProjectRunState | null>(null);
  const [previewSource, setPreviewSource] = useState<'coderio' | 'target'>('coderio');
  const [busy, setBusy] = useState(false);
  const [reloadKey, setReloadKey] = useState(0);

  useEffect(() => {
    api.listJobs().then((r) => setJobs(r.jobs)).catch(() => {});
    api.getLogs().then((r) => setLogs(r.logs.slice(-2000))).catch(() => {});
    api.getPreview().then(setState).catch(() => {});
    api.getProjectRun().then(setProjectRun).catch(() => {});
    api.getProjectProfile().then((r) => setProjectProfile(r.profile ?? null)).catch(() => {});

    const unsubLog = onSSE('log', (d) => setLogs((prev) => [...prev, d as LogEntry].slice(-2000)));
    const unsubJobs = onSSE('jobs', (d) => setJobs(d as Job[]));
    const unsubPreview = onSSE('preview', (d) => setState(d as PreviewState));
    const unsubProjRun = onSSE('projectRun', (d) => setProjectRun(d as ProjectRunState));
    return () => {
      unsubLog();
      unsubJobs();
      unsubPreview();
      unsubProjRun();
    };
  }, []);

  useEffect(() => {
    if (autoScroll && logRef.current) {
      logRef.current.scrollTop = logRef.current.scrollHeight;
    }
  }, [logs, autoScroll]);

  const activeCount = useMemo(
    () => jobs.filter((j) => j.status === 'running' || j.status === 'queued').length,
    [jobs],
  );

  const startPreview = async () => {
    setBusy(true);
    try {
      await startPreviewAction('预览服务启动中…');
    } finally {
      setBusy(false);
    }
  };
  const stopPreview = async () => {
    setBusy(true);
    try {
      await api.stopPreview();
      toast.success('预览已停止');
    } finally {
      setBusy(false);
    }
  };
  const startTarget = async () => {
    setBusy(true);
    try {
      // dir 留空:后端回退到已配置画像根目录
      const r = await api.startProject('');
      if (!r.ok) toast.error('启动目标项目失败', { description: r.error });
      else toast.success('目标项目启动中…(识别到端口后自动显示)');
    } catch (e) {
      toast.error('启动目标项目失败', { description: e instanceof Error ? e.message : String(e) });
    } finally {
      setBusy(false);
    }
  };
  const stopTarget = async () => {
    setBusy(true);
    try {
      await api.stopProject();
      toast.success('目标项目已停止');
    } catch (e) {
      toast.error('停止目标项目失败', { description: e instanceof Error ? e.message : String(e) });
    } finally {
      setBusy(false);
    }
  };
  const coderioUrl = state?.localUrl ?? state?.url ?? null;
  const targetUrl = projectRun?.localUrl ?? projectRun?.url ?? null;
  const [overrideUrl, setOverrideUrl] = useState<string | null>(null);
  const [scheme, setScheme] = useState<'http' | 'https'>('http');
  const embedUrl = overrideUrl ?? (previewSource === 'target' ? targetUrl : coderioUrl);
  const [embedUrlValue, setEmbedUrlValue] = useState(embedUrl ? stripScheme(embedUrl) : '');
  // 切换预览源时清除自定义地址
  useEffect(() => {
    setOverrideUrl(null);
  }, [previewSource]);
  // 未使用自定义地址时,跟随自动检测地址更新输入框
  useEffect(() => {
    if (overrideUrl) return;
    const u = previewSource === 'target' ? targetUrl : coderioUrl;
    setEmbedUrlValue(u ? stripScheme(u) : '');
    const s = parseScheme(u);
    if (s) setScheme(s);
  }, [previewSource, targetUrl, coderioUrl, overrideUrl]);
  const running = previewSource === 'target' ? !!projectRun?.running : !!state?.running;

  return (
    <div className="flex h-full flex-col">
      {/* ===== Generate bar ===== */}
      <div className="shrink-0 border-b border-border/70 bg-background/70 px-6 py-4 glass dark:shadow-[0_1px_0_0_rgba(255,255,255,0.05)]">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-end">
          <div className="flex-1 space-y-1.5">
            <Label htmlFor="figmaUrl" className="flex items-center gap-1.5 text-xs">
              <Figma className="h-3.5 w-3.5 text-primary" /> Figma 链接
              <span className="text-rose-400">*</span>
            </Label>
            <div className="relative">
              <Input
                id="figmaUrl"
                className="pl-9 font-mono text-[13px]"
                placeholder="https://www.figma.com/design/xxx/Name?node-id=1-2"
                value={figmaUrl}
                onChange={(e) => setFigmaUrl(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && handleSubmit()}
              />
              <Figma className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            </div>
          </div>

          <div className="flex items-center gap-1.5 rounded-xl border border-border bg-card p-1">
            {(Object.keys(modeMeta) as ValidationMode[]).map((key) => {
              const m = modeMeta[key];
              const active = mode === key;
              return (
                <button
                  key={key}
                  type="button"
                  onClick={() => setMode(key)}
                  title={m.desc}
                  className={cn(
                    'rounded-lg px-3 py-1.5 text-xs font-medium transition-colors',
                    active
                      ? 'bg-primary/15 text-primary'
                      : 'text-muted-foreground hover:bg-accent hover:text-foreground',
                  )}
                >
                  {m.short}
                </button>
              );
            })}
          </div>

          <Button
            className="h-10 brand-gradient shadow-lg shadow-primary/25 transition-transform hover:scale-[1.01]"
            onClick={handleSubmit}
            disabled={submitting || !backendReady}
          >
            {!backendReady ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : submitting ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <Rocket className="h-4 w-4" />
            )}
            {!backendReady ? '后端启动中…' : submitting ? '提交中…' : '开始生成'}
          </Button>
          <p className="mt-1.5 text-[11px] text-muted-foreground">
            {!backendReady ? (
              <span className="text-amber-500">后端正在初始化(引擎加载 + 数据库准备),就绪后按钮自动亮起</span>
            ) : target.mode === 'standalone' ? (
              stack && stack.framework ? (
                <>
                  将使用技术栈:
                  <span className="font-medium text-foreground">
                    {stack.framework}
                    {stack.componentLibrary ? ` + ${stack.componentLibrary}` : ''}
                  </span>
                </>
              ) : (
                <span className="text-amber-500">未选择技术栈,将默认生成 React</span>
              )
            ) : (
              <>独立预览技术栈取自「设置 → 项目接入」</>
            )}
          </p>
        </div>
        {/* ----- 生成目标 (target) ----- */}
        <div className="flex flex-col gap-2  pt-3 lg:flex-row lg:items-center">
          <span className="flex items-center gap-1.5 text-xs text-muted-foreground">
            <Layers className="h-3.5 w-3.5 text-primary" /> 生成目标
          </span>
          <div className="flex items-center gap-1.5 rounded-xl border border-border bg-card p-1">
            {targetModes.map((t) => {
              const active = target.mode === t.key;
              return (
                <button
                  key={t.key}
                  type="button"
                  title={t.hint}
                  onClick={() =>
                    setTarget((prev) => ({
                      mode: t.key,
                      page: t.key === 'standalone' ? undefined : prev.page,
                      slot: t.key === 'modify-slot' ? prev.slot : undefined,
                    }))
                  }
                  className={cn(
                    'rounded-lg px-3 py-1.5 text-xs font-medium transition-colors',
                    active
                      ? 'bg-primary/15 text-primary'
                      : 'text-muted-foreground hover:bg-accent hover:text-foreground',
                  )}
                >
                  {t.label}
                </button>
              );
            })}
          </div>
          {target.mode === 'new-page' && (
            <Input
              className="h-9 flex-1 font-mono text-[12px]"
              placeholder="页面路径,如 features/dashboard/page.tsx"
              value={target.page ?? ''}
              onChange={(e) => setTarget((prev) => ({ ...prev, page: e.target.value }))}
            />
          )}
          {target.mode === 'modify-slot' && (
            <>
              <Input
                className="h-9 w-56 font-mono text-[12px]"
                placeholder="页面,如 features/dashboard/page.tsx"
                value={target.page ?? ''}
                onChange={(e) => setTarget((prev) => ({ ...prev, page: e.target.value }))}
              />
              <Input
                className="h-9 flex-1 font-mono text-[12px]"
                placeholder="区域 / 插槽标识,如 <Header/> 或 #hero"
                value={target.slot ?? ''}
                onChange={(e) => setTarget((prev) => ({ ...prev, slot: e.target.value }))}
              />
            </>
          )}
        </div>
        {/* ----- 技术栈 (tech stack) ----- */}
        <div className="flex flex-col gap-2  pt-3 lg:flex-row lg:items-center">
          <span className="flex items-center gap-1.5 text-xs text-muted-foreground">
            <Boxes className="h-3.5 w-3.5 text-primary" /> 技术栈
          </span>
          {target.mode === 'standalone' ? (
            <div className="flex flex-wrap items-center gap-1.5">
              {STACK_PRESETS.map((s) => {
                const active =
                  stack != null &&
                  stack.framework === s.framework &&
                  (stack.componentLibrary ?? '') === (s.componentLibrary ?? '');
                return (
                  <button
                    key={s.id}
                    type="button"
                    onClick={() =>
                      setStack({
                        framework: s.framework,
                        styling: s.styling,
                        componentLibrary: s.componentLibrary,
                      })
                    }
                    className={cn(
                      'rounded-lg border px-2.5 py-1.5 text-xs font-medium transition-colors',
                      active
                        ? 'border-primary/40 bg-primary/15 text-primary'
                        : 'border-border bg-card text-muted-foreground hover:bg-accent hover:text-foreground',
                    )}
                  >
                    {s.label}
                  </button>
                );
              })}
              <button
                type="button"
                onClick={() =>
                  setStack((prev) =>
                    prev && prev.framework === '' ? null : { framework: '', styling: '', componentLibrary: '' },
                  )
                }
                className={cn(
                  'rounded-lg border px-2.5 py-1.5 text-xs font-medium transition-colors',
                  stack && stack.framework === ''
                    ? 'border-primary/40 bg-primary/15 text-primary'
                    : 'border-dashed border-border text-muted-foreground hover:bg-accent hover:text-foreground',
                )}
              >
                ➕ 自定义
              </button>
              {stack && stack.framework === '' && (
                <div className="flex flex-wrap items-center gap-1.5">
                  <select
                    className="h-8 rounded-md border border-border bg-card px-2 text-xs text-foreground"
                    value={stack.framework}
                    onChange={(e) => setStack((p) => ({ ...(p as TechStack), framework: e.target.value }))}
                  >
                    <option value="">框架…</option>
                    <option value="React 18">React 18</option>
                    <option value="React 19">React 19</option>
                    <option value="Vue 3">Vue 3</option>
                  </select>
                  <select
                    className="h-8 rounded-md border border-border bg-card px-2 text-xs text-foreground"
                    value={stack.styling ?? ''}
                    onChange={(e) => setStack((p) => ({ ...(p as TechStack), styling: e.target.value }))}
                  >
                    <option value="">样式…</option>
                    <option value="Tailwind CSS">Tailwind CSS</option>
                    <option value="CSS Modules">CSS Modules</option>
                    <option value="Less">Less</option>
                    <option value="原生 CSS">原生 CSS</option>
                  </select>
                  <select
                    className="h-8 rounded-md border border-border bg-card px-2 text-xs text-foreground"
                    value={stack.componentLibrary ?? ''}
                    onChange={(e) => setStack((p) => ({ ...(p as TechStack), componentLibrary: e.target.value }))}
                  >
                    <option value="">组件库…</option>
                    <option value="Ant Design">Ant Design</option>
                    <option value="Element Plus">Element Plus</option>
                    <option value="Ant Design Vue">Ant Design Vue</option>
                    <option value="无(原生元素)">无(原生元素)</option>
                  </select>
                </div>
              )}
            </div>
          ) : (
            <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
              <span className="rounded-lg border border-border bg-card px-2.5 py-1.5">
                {projectProfile?.framework || '未配置'} + {projectProfile?.componentLibrary || '未配置'}
              </span>
              <span>取自「设置 → 项目接入」</span>
            </div>
          )}
        </div>

        {/* ----- 撑满容器 (fill container) ----- */}
        <div className="flex flex-col gap-2  pt-3 lg:flex-row lg:items-center">
          <span className="flex items-center gap-1.5 text-xs text-muted-foreground">
            <MonitorSmartphone className="h-3.5 w-3.5 text-primary" /> 撑满容器
          </span>
          <button
            type="button"
            onClick={() => setFillContainer((v) => !v)}
            className={cn(
              'rounded-lg px-3 py-1.5 text-xs font-medium transition-colors',
              fillContainer
                ? 'bg-primary/15 text-primary'
                : 'border border-border bg-card text-muted-foreground hover:bg-accent hover:text-foreground',
            )}
            title="关闭后按 Figma 帧原始宽度居中渲染,适合固定宽度的设计稿"
          >
            {fillContainer ? '撑满(默认)' : '按设计稿宽度'}
          </button>
          <span className="text-[11px] text-muted-foreground">
            关闭后按 Figma 帧原始宽度居中,适合固定宽度设计稿
          </span>
        </div>

        <p className="mt-2 flex items-center gap-3 text-[11px] text-muted-foreground">
          <span>链接需包含 <code className="rounded bg-muted px-1">?node-id=</code> 以定位画板</span>
          <span className="flex items-center gap-1">
            <Lock className="h-3 w-3" /> 密钥由服务端统一管理,前端不接触凭证
          </span>
        </p>
      </div>

      {/* ===== Content: left = logs + queue, right = preview ===== */}
      <div className="flex min-h-0 flex-1 flex-col gap-4 p-4 lg:flex-row">
        {/* ---------- Left column (compact) ---------- */}
        <div className="flex min-h-0 flex-col gap-4 lg:w-[26%] lg:shrink-0">
          {/* Logs */}
          <section className="flex min-h-0 flex-1 flex-col min-h-[240px] lg:min-h-0">
            <div className="flex items-center justify-between rounded-t-xl border border-b-0 border-border bg-card px-4 py-2.5">
              <div className="flex items-center gap-2">
                <span className="flex gap-1.5">
                  <span className="h-3 w-3 rounded-full bg-rose-500/80" />
                  <span className="h-3 w-3 rounded-full bg-amber-500/80" />
                  <span className="h-3 w-3 rounded-full bg-emerald-500/80" />
                </span>
                <span className="ml-2 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
                  <ScrollText className="h-3.5 w-3.5" /> 运行日志
                </span>
              </div>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => setAutoScroll((v) => !v)}
                  className={cn(
                    'flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors',
                    autoScroll
                      ? 'text-primary'
                      : 'text-muted-foreground hover:bg-accent',
                  )}
                  title="自动滚动"
                >
                  <ArrowDownToLine className="h-3.5 w-3.5" />
                </button>
              </div>
            </div>
            <div
              ref={logRef}
              onScroll={(e) => {
                const el = e.currentTarget;
                autoRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 48;
              }}
              className="log-terminal scrollbar-thin flex-1 overflow-auto rounded-b-xl border border-border bg-[#0b0e14] p-3 text-zinc-100"
            >
              {logs.length === 0 ? (
                <div className="text-zinc-500">
                  暂无日志。提交生成任务后将实时显示引擎输出…
                </div>
              ) : (
                logs.map((l, i) => (
                  <div key={i} className="border-b border-white/5 py-1 last:border-0">
                    <div className="flex items-center gap-2 text-[10px] leading-none text-zinc-600">
                      <span className={cn('font-semibold', levelStyle[l.level])}>
                        {levelTag[l.level]}
                      </span>
                      <span className="select-none">[{l.timestamp}]</span>
                    </div>
                    <div
                      className={cn(
                        'mt-0.5 whitespace-pre-wrap break-words text-[12px] leading-snug',
                        levelStyle[l.level],
                      )}
                    >
                      {l.message}
                    </div>
                  </div>
                ))
              )}
            </div>
          </section>

          {/* Queue */}
          <section className="flex min-h-0 flex-1 flex-col min-h-[240px] lg:min-h-0">
            <div className="mb-2 flex items-center justify-between">
              <h3 className="flex items-center gap-1.5 text-sm font-medium text-muted-foreground">
                任务队列
                <Badge variant="neutral">{jobs.length}</Badge>
                {activeCount > 0 && (
                  <span className="text-[11px] text-primary">· {activeCount} 进行中</span>
                )}
              </h3>
              <Button
                variant="ghost"
                size="sm"
                className="h-7 px-2 text-xs text-muted-foreground hover:text-rose-400"
                onClick={() => { void clearAllJobs(); }}
                disabled={jobs.length === 0}
                title="清空全部"
              >
                <Trash2 className="h-3.5 w-3.5" /> 清空
              </Button>
            </div>
            <div className="scrollbar-thin flex-1 space-y-2.5 overflow-auto pr-1">
              {jobs.length === 0 ? (
                <div className="rounded-xl border border-dashed border-border p-8 text-center text-sm text-muted-foreground">
                  暂无任务
                </div>
              ) : (
                jobs.map((j) => {
                  const p = jobProgress(j);
                  return (
                    <div
                      key={j.id}
                      className="animate-fade-in rounded-xl border border-border bg-card p-3"
                    >
                      <div className="mb-1.5 flex items-center justify-between gap-2">
                        <StatusPill status={j.status} />
                        <span className="flex items-center gap-1.5 text-xs text-muted-foreground">
                          {j.target?.mode === 'new-page' && <span className="rounded bg-primary/10 px-1.5 py-0.5 text-primary">新页</span>}
                          {j.target?.mode === 'modify-slot' && <span className="rounded bg-primary/10 px-1.5 py-0.5 text-primary">改区</span>}
                          {j.target?.mode === 'standalone' && j.stack && (
                            <span className="rounded bg-emerald-500/10 px-1.5 py-0.5 text-emerald-400">
                              {j.stack.framework}{j.stack.componentLibrary ? ` + ${j.stack.componentLibrary}` : ''}
                            </span>
                          )}
                          {modeLabel[j.mode]}
                        </span>
                      </div>
                      <div className="truncate text-sm font-medium" title={j.appName}>
                        {j.appName || '未命名应用'}
                      </div>
                      <div
                        className="mt-0.5 truncate text-[11px] text-muted-foreground"
                        title={j.figmaUrl}
                      >
                        {j.figmaUrl}
                      </div>
                      <div className="mt-2">
                        <Progress value={p.value} indeterminate={p.indeterminate} tone={p.tone} />
                      </div>
                      <div className="mt-2 flex items-center justify-between">
                        <span className="text-[11px] text-zinc-500">
                          {j.startedAt ? j.startedAt.slice(11, 19) : '—'}
                          {j.pid ? ` · pid ${j.pid}` : ''}
                        </span>
                        <div className="flex items-center gap-1">
                          {isActive(j) && (
                            <button
                              onClick={() => { void cancelJob(j.id); }}
                              className="flex items-center gap-1 rounded-md border border-border px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:border-rose-500/40 hover:bg-rose-500/10 hover:text-rose-400"
                            >
                              <StopCircle className="h-3.5 w-3.5" /> 结束
                            </button>
                          )}
                          <button
                            onClick={() => { void deleteJob(j.id); }}
                            className="flex items-center gap-1 rounded-md border border-border px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:border-rose-500/40 hover:bg-rose-500/10 hover:text-rose-400"
                            title="删除记录"
                          >
                            <Trash2 className="h-3.5 w-3.5" /> 删除
                          </button>
                        </div>
                      </div>
                      {j.error && (
                        <div className="mt-2 break-words rounded-md bg-rose-500/10 px-2 py-1.5 text-[11px] text-rose-400">
                          {j.error}
                        </div>
                      )}
                    </div>
                  );
                })
              )}
            </div>
          </section>
        </div>

        {/* Preview */}
        <section className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-2xl border border-border bg-card shadow-sm min-h-[60vh] lg:min-h-0">
          <div className="flex items-center justify-between gap-3 border-b border-border bg-muted/40 px-4 py-2.5">
            <div className="flex items-center gap-3">
              <div className="flex items-center gap-2 text-sm font-medium">
                <MonitorSmartphone className="h-4 w-4 text-primary" /> 预览
                {running ? (
                  <Badge variant="success" className="px-2 py-0.5">运行中</Badge>
                ) : (
                  <Badge variant="neutral" className="px-2 py-0.5">已停止</Badge>
                )}
              </div>
              <div className="flex items-center gap-1 rounded-lg border border-border bg-card p-0.5">
                <button
                  onClick={() => setPreviewSource('coderio')}
                  className={cn(
                    'rounded-md px-2.5 py-1 text-xs font-medium transition-colors',
                    previewSource === 'coderio' ? 'bg-primary/15 text-primary' : 'text-muted-foreground hover:bg-accent',
                  )}
                >
                  Coderio 预览
                </button>
                <button
                  onClick={() => setPreviewSource('target')}
                  className={cn(
                    'rounded-md px-2.5 py-1 text-xs font-medium transition-colors',
                    previewSource === 'target' ? 'bg-primary/15 text-primary' : 'text-muted-foreground hover:bg-accent',
                  )}
                >
                  目标项目
                </button>
              </div>
            </div>
            <div className="flex-1 flex">
            <div className="flex min-w-0 flex-1 items-center gap-3 border-r border-border bg-muted/30 px-4">
              <Globe className="h-4 w-4 shrink-0 text-muted-foreground" />
              <button
                onClick={() => setScheme((s) => (s === 'http' ? 'https' : 'http'))}
                className="flex h-8 shrink-0 items-center rounded-md border border-border bg-card px-2 font-mono text-[11px] font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
                title={`切换协议,当前 ${scheme}://`}
              >
                {scheme}://
              </button>
              <Input
                value={embedUrlValue}
                onChange={(e) => setEmbedUrlValue(e.target.value)}
                placeholder="输入地址,无需填写协议头"
                className="w-full h-8 px-2.5 py-1 text-xs font-medium text-muted-foreground"
              />
            </div>
              <div className="flex items-center gap-1 px-2">
              <button
                title="确定"
                onClick={() => {
                  const raw = embedUrlValue?.trim();
                  if (!raw) return;
                  const v = SCHEME_RE.test(raw) ? raw : `${scheme}://${raw}`;
                  setOverrideUrl(v);
                  setReloadKey((k) => k + 1);
                }}
                disabled={!embedUrlValue?.trim()}
                className="flex h-8 items-center justify-center rounded-lg border border-border px-2.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40"
              >
                确定
              </button>
              <button
                disabled={!running}
                onClick={() => setReloadKey((k) => k + 1)}
                className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40"
                title="刷新"
              >
                <RotateCw className="h-4 w-4" />
              </button>
              <a
                href={embedUrl ?? undefined}
                target="_blank"
                rel="noreferrer"
                className={cn(
                  'flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-accent hover:text-foreground',
                  !embedUrl && 'pointer-events-none opacity-40',
                )}
                title="新窗口打开"
              >
                <ExternalLink className="h-4 w-4" />
              </a>
            </div>
            </div>
            <div className="flex items-center gap-2">
              {!running ? (
                <Button
                  size="sm"
                  onClick={previewSource === 'target' ? startTarget : startPreview}
                  disabled={busy}
                >
                  {busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
                  {previewSource === 'target' ? '启动项目' : '启动预览'}
                </Button>
              ) : (
                <Button
                  size="sm"
                  variant="destructive"
                  onClick={previewSource === 'target' ? stopTarget : stopPreview}
                  disabled={busy}
                >
                  {busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Square className="h-4 w-4" />}
                  停止
                </Button>
              )}
            </div>
            
          </div>

          {state?.error && (
            <div className="px-4 pt-2">
              <div className="rounded-lg border border-rose-500/30 bg-rose-500/10 p-2 text-xs text-rose-500">
                {state.error}
              </div>
            </div>
          )}
          <div className="relative min-h-0 flex-1 bg-white">
            {embedUrl ? (
              <iframe key={reloadKey} title="preview" src={embedUrl} className="h-full w-full border-0" />
            ) : (
              <div className="flex h-full flex-col items-center justify-center gap-2 p-4 text-center">
                <div className="brand-gradient flex h-12 w-12 items-center justify-center rounded-2xl shadow-lg shadow-primary/25">
                  <LayoutDashboard className="h-6 w-6 text-white" />
                </div>
                <p className="text-sm font-medium">{previewSource === 'target' ? '目标项目未启动' : '尚未启动预览'}</p>
                <p className="max-w-sm text-xs text-muted-foreground">
                  {previewSource === 'target'
                    ? '在「设置 → 项目接入」选择工作目录后,点「启动项目」即可在此实时预览目标项目运行效果。'
                    : '完成一次生成后点击「启动预览」,即可在此实时查看运行效果。'}
                </p>
              </div>
            )}
          </div>
        </section>
      </div>
    </div>
  );
}