Settings.tsx
27.4 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
import { useCallback, useEffect, useState } from 'react';
import { toast } from 'sonner';
import {
KeyRound,
ShieldCheck,
ShieldAlert,
Cpu,
Server,
Network,
Gauge,
CheckCircle2,
XCircle,
Settings as SettingsIcon,
ServerCog,
Globe,
Rocket,
Boxes,
RotateCw,
Power,
Play,
Square,
Eye,
Activity,
HardDrive,
Timer,
AlertTriangle,
ExternalLink,
type LucideIcon,
} from 'lucide-react';
import { api, markBackendRestarting, setBackendKnownDown, isBackendDownError } from '@/lib/api';
import type { ServerConfigView, SystemStatus, OrchestratorStatus, PreviewState } from '@/lib/types';
import { Badge } from '@/components/ui/badge';
import { PageHeader } from '@/components/layout/PageHeader';
import { ProjectAccessPanel } from '@/components/project/ProjectAccessPanel';
import { LocalModelPanel } from '@/components/ollama/LocalModelPanel';
import { useConnection } from '@/lib/connection';
import { cn } from '@/lib/utils';
function fmtUptime(sec: number): string {
const d = Math.floor(sec / 86400);
const h = Math.floor((sec % 86400) / 3600);
const m = Math.floor((sec % 3600) / 60);
const s = Math.floor(sec % 60);
const parts: string[] = [];
if (d) parts.push(`${d}天`);
if (h) parts.push(`${h}时`);
if (m) parts.push(`${m}分`);
parts.push(`${s}秒`);
return parts.join(' ');
}
function InfoRow({
icon: Icon,
label,
value,
mono,
}: {
icon: LucideIcon;
label: string;
value: React.ReactNode;
mono?: boolean;
}) {
return (
<div className="flex items-center gap-3 py-1.5">
<Icon className="h-4 w-4 shrink-0 text-muted-foreground" />
<span className="w-20 shrink-0 text-xs text-muted-foreground">{label}</span>
<span className={cn('min-w-0 flex-1 truncate text-sm', mono && 'font-mono text-[12px]')}>
{value ?? '—'}
</span>
</div>
);
}
function ServiceCard({
icon: Icon,
title,
running,
statusLabel,
error,
children,
actions,
}: {
icon: LucideIcon;
title: string;
running: boolean;
statusLabel: string;
error?: string | null;
children: React.ReactNode;
actions?: React.ReactNode;
}) {
return (
<div className="flex flex-col rounded-2xl border border-border bg-card">
<div className="flex flex-1 flex-col p-5">
<div className="mb-3 flex items-center justify-between">
<div className="flex items-center gap-3">
<div
className={cn(
'flex h-10 w-10 items-center justify-center rounded-xl',
running
? 'bg-emerald-500/15 text-emerald-500'
: 'bg-slate-500/15 text-slate-500',
)}
>
<Icon className="h-5 w-5" />
</div>
<div>
<div className="text-sm font-semibold">{title}</div>
<div className="text-xs text-muted-foreground">CodeRio 运行时</div>
</div>
</div>
<Badge variant={running ? 'success' : 'neutral'}>{statusLabel}</Badge>
</div>
<div className="divide-y divide-border/60">{children}</div>
{error ? (
<div className="mt-3 flex items-start gap-2 rounded-lg border border-amber-500/25 bg-amber-500/5 p-2.5 text-xs text-amber-600 dark:text-amber-400">
<AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
<span className="break-all">{error}</span>
</div>
) : null}
{actions ? <div className="mt-4 flex flex-wrap gap-2">{actions}</div> : null}
</div>
</div>
);
}
function SecretTile({ label, set }: { label: string; set: boolean }) {
return (
<div
className={cn(
'flex items-center gap-3 rounded-xl border p-4 transition-colors',
set ? 'border-emerald-500/25 bg-emerald-500/5' : 'border-amber-500/25 bg-amber-500/5',
)}
>
<div
className={cn(
'flex h-10 w-10 items-center justify-center rounded-xl',
set ? 'bg-emerald-500/15 text-emerald-500' : 'bg-amber-500/15 text-amber-500',
)}
>
{set ? <ShieldCheck className="h-5 w-5" /> : <ShieldAlert className="h-5 w-5" />}
</div>
<div className="min-w-0 flex-1">
<div className="text-sm font-medium">{label}</div>
<div
className={cn(
'text-xs',
set ? 'text-emerald-600 dark:text-emerald-400' : 'text-amber-600 dark:text-amber-400',
)}
>
{set ? '已配置并加密存储' : '尚未配置'}
</div>
</div>
{set ? (
<CheckCircle2 className="h-5 w-5 text-emerald-500" />
) : (
<XCircle className="h-5 w-5 text-amber-500" />
)}
</div>
);
}
export default function Settings() {
const [cfg, setCfg] = useState<ServerConfigView | null>(null);
const [loading, setLoading] = useState(true);
const [status, setStatus] = useState<SystemStatus | null>(null);
const [pending, setPending] = useState<string | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [sup, setSup] = useState<{ available: boolean; running: boolean }>({ available: true, running: true });
const { connected } = useConnection();
// supervisor / 后端在线状态:由 SSE 连接(connected)实时反映,不再轮询。
// 仅在「后端离线」时按需探测一次 supervisor 是否可达,决定显示「启动后端」还是「单进程模式」。
useEffect(() => {
if (connected) {
setSup({ available: true, running: true });
setBackendKnownDown(false);
return;
}
let alive = true;
api
.backendStatus()
.then((r) => {
if (!alive) return;
setSup({ available: true, running: r.running });
setBackendKnownDown(!r.running);
})
.catch(() => {
if (!alive) return;
setSup({ available: false, running: false });
});
return () => {
alive = false;
};
}, [connected]);
useEffect(() => {
api.getConfig().then(setCfg).catch(() => {}).finally(() => setLoading(false));
}, []);
// 拉取系统状态快照:初次进入拉一次,后端(重)连接后(connected false→true)再拉一次。
// 完全事件驱动,不再 setInterval 轮询;单一 effect 同时覆盖「挂载」与「(重)连接」两种时机。
const refresh = useCallback(async () => {
try {
const s = await api.getStatus();
setStatus(s);
setLoadError(null);
} catch {
setLoadError('无法获取服务状态,服务可能正在重启或已停止');
}
}, []);
useEffect(() => {
void refresh();
}, [refresh, connected]);
const runAction = useCallback(
async (key: string, fn: () => Promise<unknown>, okMsg: string) => {
setPending(key);
try {
await fn();
toast.success(okMsg);
} catch (e) {
if (isBackendDownError(e)) {
toast.error('后端未运行,请先在「设置」中启动后端');
} else {
toast.error(e instanceof Error ? e.message : '操作失败');
}
return;
} finally {
setPending(null);
}
try {
await refresh();
} catch {
/* polling recovers */
}
},
[refresh],
);
const configRows = [
{ icon: Cpu, label: 'Provider', value: cfg?.provider ?? '-' },
{ icon: Cpu, label: 'Model', value: cfg?.model ?? '-' },
{ icon: Network, label: 'Base URL', value: cfg?.baseUrl || '(默认)' },
{ icon: Gauge, label: '并发上限', value: String(cfg?.maxConcurrent ?? '-') },
];
const o = status?.orchestrator;
const pv: PreviewState | undefined = status?.preview;
const env = status?.env;
const jobs = status?.jobs;
const jobStats: { label: string; value: number; tone: string }[] = jobs
? [
{ label: '总任务', value: jobs.total, tone: 'text-foreground' },
{ label: '排队中', value: jobs.queued, tone: 'text-slate-500' },
{ label: '生成中', value: jobs.running, tone: 'text-primary' },
{ label: '已完成', value: jobs.done, tone: 'text-emerald-500' },
{ label: '失败', value: jobs.error, tone: 'text-rose-500' },
{ label: '已取消', value: jobs.cancelled, tone: 'text-slate-500' },
]
: [];
const envRows: { icon: LucideIcon; label: string; value: string }[] = env
? [
{ icon: Cpu, label: 'Node', value: env.node },
{ icon: Boxes, label: '平台', value: `${env.platform} ${env.arch}` },
{ icon: Gauge, label: 'CPU 核心', value: String(env.cpus) },
{ icon: HardDrive, label: '内存', value: `${env.totalMemoryGB} GB` },
{ icon: Network, label: '工作目录', value: env.cwd },
]
: [];
return (
<div className="mx-auto max-w-5xl p-6">
<PageHeader
icon={SettingsIcon}
description="凭据、模型与服务信息统一管理:以下仅展示配置状态,密钥由服务端保管,前端不接触任何凭证。"
/>
<div className="mt-5 space-y-5">
{/* Credentials */}
<section className="rounded-2xl border border-border bg-card p-5">
<div className="mb-4 flex items-center gap-2">
<KeyRound className="h-4 w-4 text-primary" />
<h3 className="text-sm font-semibold">凭据状态</h3>
</div>
{loading || !cfg ? (
<div className="grid gap-3 sm:grid-cols-2">
<div className="h-20 animate-pulse rounded-xl bg-muted/60" />
<div className="h-20 animate-pulse rounded-xl bg-muted/60" />
</div>
) : (
<div className="grid gap-3 sm:grid-cols-2">
<SecretTile label="模型 API Key" set={cfg.apiKeySet} />
<SecretTile label="Figma Token" set={cfg.figmaTokenSet} />
</div>
)}
<p className="mt-3 text-xs text-muted-foreground">
API Key 与 Figma Token 通过服务端环境变量或{' '}
<code className="rounded bg-muted px-1">~/.coderio/config.yaml</code> 注入,无需在此填写。
</p>
</section>
{/* Project access / 画像 */}
<ProjectAccessPanel />
{/* Model config */}
<section className="rounded-2xl border border-border bg-card p-5">
<div className="mb-4 flex items-center gap-2">
<Cpu className="h-4 w-4 text-primary" />
<h3 className="text-sm font-semibold">模型配置(只读)</h3>
</div>
<div className="grid gap-px overflow-hidden rounded-xl border border-border bg-border sm:grid-cols-2">
{configRows.map((r) => {
const Icon = r.icon;
return (
<div key={r.label} className="flex items-center gap-3 bg-card p-4">
<Icon className="h-4 w-4 shrink-0 text-muted-foreground" />
<div className="min-w-0 flex-1">
<div className="text-xs text-muted-foreground">{r.label}</div>
<div className="truncate break-all text-sm font-medium">{r.value}</div>
</div>
</div>
);
})}
</div>
</section>
{/* 本地模型 (Ollama) 管理 */}
<LocalModelPanel />
{/* Service & runtime */}
<section className="rounded-2xl border border-border bg-card p-5">
<div className="mb-4 flex items-center gap-2">
<ServerCog className="h-4 w-4 text-primary" />
<h3 className="text-sm font-semibold">服务与运行时</h3>
<Badge variant={connected ? 'success' : 'danger'} className="px-2 py-0.5">
{connected ? '已连接' : '断开'}
</Badge>
{loadError ? <span className="ml-1 text-xs text-amber-500">{loadError}</span> : null}
</div>
<LaunchOverview orchestrator={o} preview={pv} sup={sup} connected={connected} />
<div className="grid gap-4 lg:grid-cols-3">
<ServiceCard
icon={ServerCog}
title="编排服务"
running={o?.running ?? true}
statusLabel={o ? '运行中' : '—'}
>
<InfoRow icon={Boxes} label="版本" value={o?.version ?? '—'} mono />
<InfoRow icon={Cpu} label="进程" value={o?.pid ?? '—'} mono />
<InfoRow icon={Network} label="端口" value={o?.port ?? '—'} mono />
<InfoRow icon={Timer} label="运行时长" value={o ? fmtUptime(o.uptimeSec) : '—'} />
<InfoRow icon={Gauge} label="并发上限" value={o?.maxConcurrent ?? '—'} mono />
<InfoRow icon={HardDrive} label="数据目录" value={o?.dataDir ?? '—'} mono />
<InfoRow icon={HardDrive} label="产物目录" value={o?.outputDir ?? '—'} mono />
<OrchestratorActions pending={pending} setPending={setPending} sup={sup} />
</ServiceCard>
<ServiceCard
icon={Eye}
title="预览服务"
running={pv?.running ?? false}
statusLabel={pv?.running ? '运行中' : '未运行'}
error={pv?.error}
>
<InfoRow
icon={Network}
label="访问地址"
value={
pv?.running && pv.url ? (
<a
href={pv.url}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 text-primary hover:underline"
>
{pv.url}
<ExternalLink className="h-3 w-3" />
</a>
) : (
'未启动'
)
}
/>
<InfoRow icon={Network} label="本地" value={pv?.localUrl ?? '—'} mono />
<InfoRow icon={Gauge} label="端口" value={pv?.port ?? '—'} mono />
<InfoRow icon={Cpu} label="进程" value={pv?.pid ?? '—'} mono />
<InfoRow icon={HardDrive} label="应用路径" value={pv?.appPath ?? '—'} mono />
<PreviewActions pv={pv} pending={pending} runAction={runAction} />
</ServiceCard>
<ServiceCard
icon={Boxes}
title="Coderio 引擎"
running={status?.engine.status === 'ready'}
statusLabel={status?.engine.status === 'ready' ? '就绪' : '异常'}
>
<InfoRow icon={Boxes} label="名称" value={status?.engine.name ?? '—'} />
<InfoRow icon={Boxes} label="版本" value={status?.engine.version ?? '—'} mono />
<InfoRow icon={Activity} label="状态" value={status?.engine.status ?? '—'} />
</ServiceCard>
</div>
{/* Job metrics */}
<div className="mt-4 rounded-xl border border-border bg-muted/40 p-4">
<div className="mb-3 flex items-center gap-2">
<Activity className="h-4 w-4 text-primary" />
<h4 className="text-sm font-semibold">运行指标</h4>
</div>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
{jobStats.map((s) => (
<div
key={s.label}
className="rounded-xl border border-border bg-card p-3 text-center"
>
<div className={cn('text-2xl font-semibold tabular-nums', s.tone)}>{s.value}</div>
<div className="mt-1 text-xs text-muted-foreground">{s.label}</div>
</div>
))}
</div>
</div>
{/* Environment */}
<div className="mt-4 rounded-xl border border-border bg-muted/40 p-4">
<div className="mb-3 flex items-center gap-2">
<Cpu className="h-4 w-4 text-primary" />
<h4 className="text-sm font-semibold">环境信息</h4>
</div>
<div className="grid gap-px overflow-hidden rounded-xl border border-border bg-border sm:grid-cols-2 lg:grid-cols-3">
{envRows.map((r) => {
const Icon = r.icon;
return (
<div key={r.label} className="flex items-center gap-3 bg-card p-4">
<Icon className="h-4 w-4 shrink-0 text-muted-foreground" />
<div className="min-w-0 flex-1">
<div className="text-xs text-muted-foreground">{r.label}</div>
<div className="truncate font-mono text-[12px]">{r.value}</div>
</div>
</div>
);
})}
</div>
</div>
</section>
</div>
</div>
);
}
function LaunchOverview({
orchestrator,
preview,
sup,
connected,
}: {
orchestrator: OrchestratorStatus | undefined;
preview: PreviewState | undefined;
sup: { available: boolean; running: boolean };
connected: boolean;
}) {
const webAddr = 'http://localhost:5173';
const backendPort = orchestrator?.port ?? 4173;
const backendAddr = `http://localhost:${backendPort}`;
const supPort = 4174;
const items = [
{
icon: Globe,
label: '前端界面',
addr: webAddr,
running: true,
hint: '当前页面(你正在看)',
},
{
icon: ServerCog,
label: '后端 API',
addr: backendAddr,
running: connected,
hint: `端口 ${backendPort}`,
},
{
icon: Rocket,
label: 'supervisor',
addr: `http://localhost:${supPort}`,
running: sup.available,
hint: sup.available ? `控制端口 ${supPort}` : '单进程模式(无 supervisor)',
},
{
icon: Eye,
label: '预览服务',
addr: preview?.url ?? null,
running: preview?.running ?? false,
hint: preview?.running ? `端口 ${preview.port}` : '未启动',
},
];
return (
<div className="rounded-xl border border-border bg-muted/40 p-4">
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
<div className="flex items-center gap-2">
<Rocket className="h-4 w-4 text-primary" />
<h4 className="text-sm font-semibold">启动与访问入口</h4>
</div>
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span>启动命令</span>
<code className="rounded bg-emerald-500/10 px-2 py-0.5 font-mono text-[12px] text-emerald-500">
npm run dev
</code>
<span>(仓库根目录执行)</span>
</div>
</div>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
{items.map((it) => {
const Icon = it.icon;
return (
<div key={it.label} className="rounded-xl border border-border bg-card p-3">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-1.5">
<Icon className="h-4 w-4 text-muted-foreground" />
<span className="text-sm font-medium">{it.label}</span>
</div>
<Badge variant={it.running ? 'success' : 'neutral'}>
{it.running ? '运行中' : '已停止'}
</Badge>
</div>
<div className="mt-2">
{it.addr ? (
<a
href={it.addr}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 truncate font-mono text-[12px] text-primary hover:underline"
>
{it.addr}
<ExternalLink className="h-3 w-3 shrink-0" />
</a>
) : (
<span className="font-mono text-[12px] text-muted-foreground">—</span>
)}
</div>
<div className="mt-1 text-xs text-muted-foreground">{it.hint}</div>
</div>
);
})}
</div>
<p className="mt-3 text-xs text-muted-foreground">
开发模式只需一次 <code className="rounded bg-muted px-1">npm run dev</code>
;其后端启停、重启、停止全部均在本页「编排服务」卡片操作。改后端或引擎代码后请点「重启」或重跑该命令。
</p>
</div>
);
}
function OrchestratorActions({
pending,
setPending,
sup,
}: {
pending: string | null;
setPending: (v: string | null) => void;
sup: { available: boolean; running: boolean };
}) {
// 生产单进程模式:没有 supervisor,停止即需手动重启。
if (!sup.available) {
return (
<div className="mt-4 flex flex-wrap items-center gap-2">
<button
type="button"
disabled={pending !== null}
onClick={() => {
if (!window.confirm('确定停止服务吗?停止后需手动重新启动后端进程。')) return;
setPending('shutdown');
api
.shutdownServer()
.then(() => toast.message('服务已停止,请手动重新启动'))
.catch((e: unknown) => toast.error(e instanceof Error ? e.message : '停止失败'))
.finally(() => setPending(null));
}}
className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border px-3 text-xs font-medium text-muted-foreground transition-colors hover:border-rose-500/40 hover:bg-rose-500/10 hover:text-rose-400 disabled:opacity-50"
>
<Power className="h-3.5 w-3.5" />
停止服务
</button>
<span className="text-xs text-muted-foreground">
当前为单进程模式(无 supervisor),停止后需手动重启后端进程。
</span>
</div>
);
}
const doStart = () => {
setPending('start');
api
.startBackend()
.then(() => {
setBackendKnownDown(false);
markBackendRestarting();
toast.success('后端正在启动,请稍候…');
})
.catch((e: unknown) => toast.error(e instanceof Error ? e.message : '启动失败'))
.finally(() => setPending(null));
};
const doRestart = () => {
if (!window.confirm('确定重启编排服务吗?进行中的任务会中断,页面会短暂重连。')) return;
setPending('restart');
api
.restartBackend()
.then(() => {
setBackendKnownDown(false);
markBackendRestarting();
toast.success('服务正在重启,请稍候…');
})
.catch((e: unknown) => toast.error(e instanceof Error ? e.message : '重启失败'))
.finally(() => setPending(null));
};
const doStop = () => {
if (!window.confirm('确定停止后端吗?停止后可通过「启动后端」恢复,预览/生成将不可用。')) return;
setPending('stop');
api
.stopBackend()
.then(() => {
setBackendKnownDown(true);
toast.message('后端已停止,可随时点「启动后端」恢复');
})
.catch((e: unknown) => toast.error(e instanceof Error ? e.message : '停止失败'))
.finally(() => setPending(null));
};
const doShutdown = () => {
if (
!window.confirm(
'确定停止全部吗?将关闭前端、后端与开发服务(supervisor)。之后需重新运行 npm run dev 启动。',
)
)
return;
setPending('shutdown-dev');
api
.shutdownDev()
.then(() => toast.message('正在停止全部服务…'))
.catch((e: unknown) => toast.error(e instanceof Error ? e.message : '操作失败'))
.finally(() => setPending(null));
};
return (
<div className="mt-4 flex flex-wrap items-center gap-2">
{!sup.running ? (
<button
type="button"
disabled={pending !== null}
onClick={doStart}
className="inline-flex h-8 items-center gap-1.5 rounded-lg bg-emerald-500 px-3 text-xs font-medium text-white transition-colors hover:bg-emerald-600 disabled:opacity-50"
>
<Play className={cn('h-3.5 w-3.5', pending === 'start' && 'animate-pulse')} />
启动后端
</button>
) : (
<>
<button
type="button"
disabled={pending !== null}
onClick={doRestart}
className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border px-3 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50"
>
<RotateCw className={cn('h-3.5 w-3.5', pending === 'restart' && 'animate-spin')} />
重启
</button>
<button
type="button"
disabled={pending !== null}
onClick={doStop}
className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border px-3 text-xs font-medium text-muted-foreground transition-colors hover:border-rose-500/40 hover:bg-rose-500/10 hover:text-rose-400 disabled:opacity-50"
>
<Power className="h-3.5 w-3.5" />
停止后端
</button>
</>
)}
<button
type="button"
disabled={pending !== null}
onClick={doShutdown}
className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border px-3 text-xs font-medium text-muted-foreground transition-colors hover:border-rose-500/40 hover:bg-rose-500/10 hover:text-rose-400 disabled:opacity-50"
>
<Power className={cn('h-3.5 w-3.5', pending === 'shutdown-dev' && 'animate-pulse')} />
停止全部
</button>
{!sup.running && (
<span className="inline-flex items-center gap-1.5 rounded-full bg-amber-500/10 px-2.5 py-1 text-xs font-medium text-amber-500">
<AlertTriangle className="h-3.5 w-3.5" />
后端已停止
</span>
)}
</div>
);
}
function PreviewActions({
pv,
pending,
runAction,
}: {
pv: PreviewState | undefined;
pending: string | null;
runAction: (key: string, fn: () => Promise<unknown>, okMsg: string) => Promise<void>;
}) {
const running = pv?.running ?? false;
return (
<div className="mt-4 flex flex-wrap gap-2">
{!running ? (
<button
type="button"
disabled={pending !== null}
onClick={() => void runAction('start', () => api.startPreview(), '预览服务已启动')}
className="inline-flex h-8 items-center gap-1.5 rounded-lg bg-primary px-3 text-xs font-medium text-primary-foreground transition-colors hover:opacity-90 disabled:opacity-50"
>
<Play className="h-3.5 w-3.5" /> 启动
</button>
) : null}
<button
type="button"
disabled={pending !== null || !running}
onClick={() => void runAction('prestart', () => api.restartPreview(), '预览服务已重启')}
className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border px-3 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50"
>
<RotateCw className={cn('h-3.5 w-3.5', pending === 'prestart' && 'animate-spin')} />
重启
</button>
<button
type="button"
disabled={pending !== null || !running}
onClick={() => void runAction('stop', () => api.stopPreview(), '预览服务已停止')}
className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border px-3 text-xs font-medium text-muted-foreground transition-colors hover:border-rose-500/40 hover:bg-rose-500/10 hover:text-rose-400 disabled:opacity-50"
>
<Square className="h-3.5 w-3.5" /> 停止
</button>
</div>
);
}