Workbench.tsx
38.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
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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
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 { GenerateSchema } from '@coderio/shared';
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, '');
type Tone = 'info' | 'success' | 'danger' | 'brand' | 'neutral';
/**
* 真实进度:running 时优先使用引擎在生成各阶段上报的 phase / progress,
* 不再只有「0 / 100」两步。无上报时回退为不确定态。
*/
function jobProgress(j: Job): {
value: number;
indeterminate: boolean;
tone: Tone;
phase: string;
} {
if (j.status === 'done') return { value: 100, indeterminate: false, tone: 'success', phase: '已完成' };
if (j.status === 'error') return { value: j.progress ?? 100, indeterminate: false, tone: 'danger', phase: j.phase ?? '失败' };
if (j.status === 'cancelled') return { value: j.progress ?? 0, indeterminate: false, tone: 'neutral', phase: '已取消' };
if (j.status === 'queued') return { value: 0, indeterminate: false, tone: 'brand', phase: '排队中' };
const pct = j.progress ?? 0;
return {
value: pct,
indeterminate: pct === 0,
tone: 'info',
phase: j.phase ?? '生成中',
};
}
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 */
}
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);
const [backendReady, setBackendReady] = useState(true);
useEffect(() => {
try {
if (stack) localStorage.setItem('coderio.workbench.stack', JSON.stringify(stack));
else localStorage.removeItem('coderio.workbench.stack');
} catch {
/* ignore */
}
}, [stack]);
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 () => {
const payload = {
figmaUrl: figmaUrl.trim(),
mode,
target,
stack: target.mode === 'standalone' ? stack : null,
fillContainer,
};
const parsed = GenerateSchema.safeParse(payload);
if (!parsed.success) {
const issue = parsed.error.issues[0];
return toast.error(issue?.message ?? '参数校验失败');
}
if (!backendReady) return toast.error('后端启动中,请稍候…', { description: '引擎与数据库初始化完成后即可生成' });
setSubmitting(true);
try {
const res = await api.generate(parsed.data);
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 {
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('目标项目已停止');
} 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 bg-muted/30">
{/* ===== 生成配置面板 ===== */}
<section className="shrink-0 border-b border-border bg-background">
<div className="mx-auto max-w-[1440px] px-6 py-5">
<div className="flex flex-col gap-4 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 font-medium">
<Figma className="h-3.5 w-3.5 text-emerald-600" /> Figma 链接
<span className="text-rose-500">*</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-muted/40 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-emerald-600/15 text-emerald-700 dark:text-emerald-400'
: 'text-muted-foreground hover:bg-accent hover:text-foreground',
)}
>
{m.short}
</button>
);
})}
</div>
<Button
className="h-10 bg-emerald-600 text-white shadow-sm shadow-emerald-600/20 transition-colors hover:bg-emerald-700"
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>
</div>
{/* ----- 配置组:目标 / 技术栈 / 撑满容器 ----- */}
<div className="mt-4 grid gap-4 lg:grid-cols-3">
{/* 生成目标 */}
<div className="rounded-xl border border-border bg-muted/40 p-3">
<div className="mb-2 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
<Layers className="h-3.5 w-3.5 text-emerald-600" /> 生成目标
</div>
<div className="flex flex-wrap items-center gap-1.5">
{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-2.5 py-1.5 text-xs font-medium transition-colors',
active
? 'bg-emerald-600/15 text-emerald-700 dark:text-emerald-400'
: 'border border-border bg-card text-muted-foreground hover:bg-accent hover:text-foreground',
)}
>
{t.label}
</button>
);
})}
</div>
{target.mode === 'new-page' && (
<Input
className="mt-2 h-8 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' && (
<div className="mt-2 flex flex-col gap-1.5">
<Input
className="h-8 font-mono text-[12px]"
placeholder="页面,如 features/dashboard/page.tsx"
value={target.page ?? ''}
onChange={(e) => setTarget((prev) => ({ ...prev, page: e.target.value }))}
/>
<Input
className="h-8 flex-1 font-mono text-[12px]"
placeholder="区域 / 插槽标识,如 <Header/> 或 #hero"
value={target.slot ?? ''}
onChange={(e) => setTarget((prev) => ({ ...prev, slot: e.target.value }))}
/>
</div>
)}
</div>
{/* 技术栈 */}
<div className="rounded-xl border border-border bg-muted/40 p-3">
<div className="mb-2 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
<Boxes className="h-3.5 w-3.5 text-emerald-600" /> 技术栈
</div>
{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-emerald-600/40 bg-emerald-600/15 text-emerald-700 dark:text-emerald-400'
: '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-emerald-600/40 bg-emerald-600/15 text-emerald-700 dark:text-emerald-400'
: 'border-dashed border-border text-muted-foreground hover:bg-accent hover:text-foreground',
)}
>
➕ 自定义
</button>
{stack && stack.framework === '' && (
<div className="mt-2 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>
{/* 撑满容器 + 提示 */}
<div className="rounded-xl border border-border bg-muted/40 p-3">
<div className="mb-2 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
<MonitorSmartphone className="h-3.5 w-3.5 text-emerald-600" /> 布局
</div>
<button
type="button"
onClick={() => setFillContainer((v) => !v)}
className={cn(
'rounded-lg px-3 py-1.5 text-xs font-medium transition-colors',
fillContainer
? 'bg-emerald-600/15 text-emerald-700 dark:text-emerald-400'
: 'border border-border bg-card text-muted-foreground hover:bg-accent hover:text-foreground',
)}
title="关闭后按 Figma 帧原始宽度居中渲染,适合固定宽度的设计稿"
>
{fillContainer ? '撑满容器(默认)' : '按设计稿宽度'}
</button>
<p className="mt-3 flex items-center gap-1.5 text-[11px] leading-relaxed text-muted-foreground">
<Lock className="h-3 w-3 shrink-0" />
密钥由服务端统一管理,前端不接触凭证
</p>
</div>
</div>
</div>
</section>
{/* ===== 主体:左=任务+日志,右=预览 ===== */}
<div className="min-h-0 flex-1">
<div className="mx-auto grid h-full max-w-[1440px] gap-4 p-4 lg:grid-cols-[minmax(0,420px)_minmax(0,1fr)]">
{/* ---------- 左侧列 ---------- */}
<div className="flex min-h-0 flex-col gap-4">
{/* 任务队列 */}
<section className="flex min-h-0 flex-1 flex-col">
<div className="flex items-center justify-between gap-3 rounded-t-xl border border-b-0 border-border bg-card px-4 py-2.5">
<h3 className="flex items-center gap-1.5 text-sm font-semibold text-foreground">
任务队列
<Badge variant="neutral">{jobs.length}</Badge>
{activeCount > 0 && (
<span className="text-[11px] font-normal text-emerald-600">{activeCount} 进行中</span>
)}
</h3>
<Button
variant="ghost"
size="sm"
className="h-7 px-2 text-xs text-muted-foreground hover:text-rose-500"
onClick={() => { void clearAllJobs(); }}
disabled={jobs.length === 0}
title="清空全部"
>
<Trash2 className="h-3.5 w-3.5" /> 清空
</Button>
</div>
<div className="scrollbar-thin flex-1 overflow-auto rounded-b-xl border border-border bg-card">
{jobs.length === 0 ? (
<div className="px-4 py-10 text-center text-sm text-muted-foreground">
暂无任务,填写 Figma 链接后点击「开始生成」
</div>
) : (
<div className="divide-y divide-border">
{jobs.map((j) => {
const p = jobProgress(j);
return (
<div
key={j.id}
className="animate-fade-in px-4 py-3 transition-colors hover:bg-muted/40"
>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<div className="truncate text-sm font-semibold text-foreground" title={j.appName}>
{j.appName || '未命名应用'}
</div>
<div className="mt-0.5 truncate text-[11px] text-muted-foreground" title={j.figmaUrl}>
{j.figmaUrl}
</div>
</div>
<StatusPill status={j.status} />
</div>
<div className="mt-2 flex flex-wrap items-center gap-1.5">
{j.model && (
<span
className={cn(
'rounded-md px-1.5 py-0.5 text-[11px] font-medium',
j.modelSource === 'local'
? 'bg-emerald-500/10 text-emerald-600'
: 'bg-sky-500/10 text-sky-600',
)}
title={j.modelSource === 'local' ? '本地模型(Ollama)' : '外部 API 模型'}
>
{j.modelSource === 'local' ? '本地' : '外部'} · {j.model}
</span>
)}
{j.target?.mode === 'new-page' && (
<span className="rounded bg-emerald-600/10 px-1.5 py-0.5 text-[11px] text-emerald-600">新页</span>
)}
{j.target?.mode === 'modify-slot' && (
<span className="rounded bg-emerald-600/10 px-1.5 py-0.5 text-[11px] text-emerald-600">改区</span>
)}
{j.target?.mode === 'standalone' && j.stack && (
<span className="rounded bg-emerald-600/10 px-1.5 py-0.5 text-[11px] text-emerald-600">
{j.stack.framework}{j.stack.componentLibrary ? ` + ${j.stack.componentLibrary}` : ''}
</span>
)}
<span className="rounded bg-muted px-1.5 py-0.5 text-[11px] text-muted-foreground">
{modeLabel[j.mode]}
</span>
</div>
{/* 真实进度:阶段 + 百分比 */}
<div className="mt-3">
<div className="mb-1 flex items-center justify-between text-[11px]">
<span className="text-muted-foreground">{p.phase}</span>
{j.status === 'running' && p.value > 0 && (
<span className="font-medium text-foreground">{p.value}%</span>
)}
</div>
<Progress value={p.value} indeterminate={p.indeterminate} tone={p.tone} />
</div>
<div className="mt-2.5 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-500"
>
<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-500"
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-500">
{j.error}
</div>
)}
</div>
);
})}
</div>
)}
</div>
</section>
{/* 运行日志 */}
<section className="flex min-h-0 flex-1 flex-col">
<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-2.5 w-2.5 rounded-full bg-rose-500/80" />
<span className="h-2.5 w-2.5 rounded-full bg-amber-500/80" />
<span className="h-2.5 w-2.5 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>
<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-emerald-600' : 'text-muted-foreground hover:bg-accent',
)}
title="自动滚动"
>
<ArrowDownToLine className="h-3.5 w-3.5" />
</button>
</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>
</div>
{/* ---------- 右侧:预览 ---------- */}
<section className="flex min-h-0 flex-col overflow-hidden rounded-2xl border border-border bg-card shadow-sm">
<div className="flex flex-wrap 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-semibold text-foreground">
<MonitorSmartphone className="h-4 w-4 text-emerald-600" /> 预览
{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-emerald-600/15 text-emerald-700 dark:text-emerald-400' : '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-emerald-600/15 text-emerald-700 dark:text-emerald-400' : 'text-muted-foreground hover:bg-accent',
)}
>
目标项目
</button>
</div>
</div>
<div className="flex flex-1 flex-wrap items-center gap-2">
<div className="flex min-w-0 flex-1 items-center gap-2 border border-border bg-muted/30 px-3 py-1">
<Globe className="h-4 w-4 shrink-0 text-muted-foreground" />
<button
onClick={() => setScheme((s) => (s === 'http' ? 'https' : 'http'))}
className="flex h-7 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="h-7 w-full border-0 bg-transparent px-0 py-1 text-xs font-medium text-muted-foreground focus-visible:ring-0"
/>
</div>
<div className="flex items-center gap-1">
<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-7 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-7 w-7 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-7 w-7 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"
className="bg-emerald-600 text-white hover:bg-emerald-700"
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="flex h-12 w-12 items-center justify-center rounded-2xl bg-emerald-600/10">
<LayoutDashboard className="h-6 w-6 text-emerald-600" />
</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>
</div>
);
}