feat: 工具配置增强、站点拨测与日志中心多项改进

- 工具配置:新增卸载 API/UI、Go 工具链、流水线构建自动安装依赖
- 修复 ListTools VerifyTool 递归栈溢出导致获取工具配置失败
- Node.js Alpine 安装改用 unofficial-builds musl 预编译包与 index.json 解析 LTS
- 站点拨测:详情页路由、告警自动恢复、并发拨测与默认可观测频率
- 日志中心:RBAC、查询构建器、ES/Loki 增强与审计 request/response 展示
- 发布配置:构建节点、流水线远程执行、Deploy RBAC 导航拆分
This commit is contained in:
Logan committed 2026-07-02 07:47:33 +08:00
1 parent cde7bbe540
commit 7e1c8f583c
84 files changed
+7729 -1507

No files matched your search

@@ -0,0 +1,350 @@
import { useState, useEffect, useCallback } from 'react';
import { Plus, Pencil, Trash2, RefreshCw, Server, Cpu } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel';
import { PageEmpty } from '@/components/layout/PageEmpty';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { toast } from 'sonner';
import { useConfirm } from '@/components/ui/confirm-dialog';
import { buildNodeApi, serverApi, type BuildNode } from '@/api';
interface ServerItem {
id: number;
hostname: string;
ip: string;
}
// 构建节点管理(Jenkins Agent 风格 SSH 节点) // Logan.Li
export default function BuildNodesManager({ embedded = false }: { embedded?: boolean }) {
const confirm = useConfirm();
const [nodes, setNodes] = useState<BuildNode[]>([]);
const [master, setMaster] = useState({ name: 'Master', max_executors: 2, running_count: 0 });
const [servers, setServers] = useState<ServerItem[]>([]);
const [loading, setLoading] = useState(false);
const [dialogOpen, setDialogOpen] = useState(false);
const [editNode, setEditNode] = useState<BuildNode | null>(null);
const [testingId, setTestingId] = useState<number | null>(null);
const [masterMax, setMasterMax] = useState('2');
const [savingMaster, setSavingMaster] = useState(false);
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [serverId, setServerId] = useState('');
const [labels, setLabels] = useState('');
const [maxExecutors, setMaxExecutors] = useState('2');
const [workspacePath, setWorkspacePath] = useState('/data/aiops-workspace');
const [submitting, setSubmitting] = useState(false);
const load = useCallback(async () => {
setLoading(true);
try {
const [nodeRes, srvRes] = await Promise.all([
buildNodeApi.list(),
serverApi.getServers({ page_size: 200 }).catch(() => ({ list: [] })),
]);
const data = nodeRes as { list?: BuildNode[]; master?: typeof master };
setNodes(Array.isArray(data?.list) ? data.list : []);
if (data?.master) {
setMaster(data.master);
setMasterMax(String(data.master.max_executors || 2));
}
const srvList = (srvRes as { list?: ServerItem[] })?.list || [];
setServers(srvList);
} catch {
toast.error('加载构建节点失败');
} finally {
setLoading(false);
}
}, []);
useEffect(() => { load(); }, [load]);
const openCreate = () => {
setEditNode(null);
setName('');
setDescription('');
setServerId('');
setLabels('');
setMaxExecutors('2');
setWorkspacePath('/data/aiops-workspace');
setDialogOpen(true);
};
const openEdit = (node: BuildNode) => {
setEditNode(node);
setName(node.name);
setDescription(node.description || '');
setServerId(String(node.server_id));
setLabels(node.labels || '');
setMaxExecutors(String(node.max_executors || 2));
setWorkspacePath(node.workspace_path || '/data/aiops-workspace');
setDialogOpen(true);
};
const handleSubmit = async () => {
if (!name.trim() || !serverId) {
toast.error('请填写名称并选择服务器');
return;
}
setSubmitting(true);
try {
const payload = {
name: name.trim(),
description,
server_id: Number(serverId),
labels,
max_executors: Number(maxExecutors) || 2,
workspace_path: workspacePath || '/data/aiops-workspace',
};
if (editNode) {
await buildNodeApi.update(editNode.id, payload);
toast.success('已更新');
} else {
await buildNodeApi.create(payload);
toast.success('已创建');
}
setDialogOpen(false);
load();
} catch {
toast.error('操作失败');
} finally {
setSubmitting(false);
}
};
const handleDelete = async (node: BuildNode) => {
const ok = await confirm({ title: '删除节点', description: `确定删除构建节点「${node.name}」?` });
if (!ok) return;
try {
await buildNodeApi.delete(node.id);
toast.success('已删除');
load();
} catch {
toast.error('删除失败,请确认无流水线绑定');
}
};
const handleTest = async (node: BuildNode) => {
setTestingId(node.id);
try {
const res = await buildNodeApi.test(node.id) as { success?: boolean; message?: string };
if (res?.success) {
toast.success(`连通成功: ${res.message || ''}`);
} else {
toast.error(res?.message || '连接失败');
}
} catch {
toast.error('测试失败');
} finally {
setTestingId(null);
}
};
const handleToggle = async (node: BuildNode) => {
try {
await buildNodeApi.update(node.id, { enabled: !node.enabled });
load();
} catch {
toast.error('更新失败');
}
};
const handleSaveMaster = async () => {
const n = Number(masterMax);
if (!n || n < 1) {
toast.error('并发数至少为 1');
return;
}
setSavingMaster(true);
try {
const res = await buildNodeApi.updateMaster({ max_executors: n });
const m = res as { max_executors?: number; running_count?: number };
setMaster((prev) => ({
...prev,
max_executors: m?.max_executors ?? n,
running_count: m?.running_count ?? prev.running_count,
}));
toast.success('Master 并发已更新');
} catch {
toast.error('更新失败');
} finally {
setSavingMaster(false);
}
};
const panel = (
<div className={embedded ? 'space-y-4' : 'mt-4 space-y-4'}>
<ContentPanel
toolbar={(
<div className="flex items-center justify-between w-full">
<span className="text-sm font-medium text-[var(--dg-text-primary)]">构建节点</span>
<div className="flex gap-2">
<Button variant="ghost" size="sm" onClick={load} disabled={loading}>
<RefreshCw className={`h-3.5 w-3.5 mr-1${loading ? ' animate-spin' : ''}`} />刷新
</Button>
<Button size="sm" onClick={openCreate}>
<Plus className="h-3.5 w-3.5 mr-1" />添加
</Button>
</div>
</div>
)}
>
<div className="mb-3 p-3 rounded-lg border border-[var(--dg-border)] bg-[var(--dg-bg-secondary)]">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-2">
<Cpu className="h-4 w-4 text-[var(--dg-text-muted)]" />
<span className="text-sm font-medium text-[var(--dg-text-primary)]">Master(内置)</span>
<Badge variant="outline" className="text-[10px]">默认调度</Badge>
<span className="text-xs text-[var(--dg-text-muted)]">
占用 {master.running_count}/{master.max_executors}
</span>
</div>
<div className="flex items-center gap-2">
<Label className="text-xs text-[var(--dg-text-muted)] shrink-0">最大并发</Label>
<Input
type="number"
min={1}
max={32}
value={masterMax}
onChange={(e) => setMasterMax(e.target.value)}
className="h-7 w-16 text-xs dg-input"
/>
<Button size="sm" className="h-7 text-xs" onClick={handleSaveMaster} disabled={savingMaster}>
{savingMaster ? '保存中' : '保存'}
</Button>
</div>
</div>
<p className="text-[11px] text-[var(--dg-text-muted)] mt-2">
未指定节点时优先在 Master 执行;并发设为 1 时按触发顺序串行排队;满载后自动调度到空闲远程节点
</p>
</div>
{nodes.length === 0 ? (
<PageEmpty
title="暂无远程构建节点"
description="关联服务器资产添加 SSH 节点,将重型构建任务调度到高性能机器"
action={<Button size="sm" onClick={openCreate}><Plus className="h-3.5 w-3.5 mr-1" />添加节点</Button>}
/>
) : (
<div className="space-y-2">
{nodes.map((node) => (
<div
key={node.id}
className="flex items-center justify-between gap-3 p-3 rounded-lg border border-[var(--dg-border)] hover:bg-[var(--dg-bg-secondary)]/50"
>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium text-sm text-[var(--dg-text-primary)]">{node.name}</span>
<Badge variant={node.enabled ? 'default' : 'secondary'} className="text-[10px]">
{node.enabled ? '启用' : '禁用'}
</Badge>
<span className="text-[10px] text-[var(--dg-text-muted)] font-mono">
{node.hostname || node.ip || `server#${node.server_id}`}
</span>
</div>
<div className="flex items-center gap-3 mt-1 text-[11px] text-[var(--dg-text-muted)]">
<span>执行器 {node.running_count || 0}/{node.max_executors}</span>
{node.labels && <span>标签 {node.labels}</span>}
<span className="truncate">{node.workspace_path}</span>
</div>
</div>
<div className="flex items-center gap-1 shrink-0">
<Button variant="ghost" size="sm" className="h-7 text-xs" disabled={testingId === node.id} onClick={() => handleTest(node)}>
{testingId === node.id ? '测试中' : '测试'}
</Button>
<Button variant="ghost" size="sm" className="h-7 text-xs" onClick={() => handleToggle(node)}>
{node.enabled ? '禁用' : '启用'}
</Button>
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => openEdit(node)}>
<Pencil className="h-3.5 w-3.5" />
</Button>
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => handleDelete(node)}>
<Trash2 className="h-3.5 w-3.5 text-[var(--dg-red)]" />
</Button>
</div>
</div>
))}
</div>
)}
</ContentPanel>
</div>
);
const dialog = (
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent className="max-w-md bg-[var(--dg-bg-primary)] border-[var(--dg-border)]">
<DialogHeader>
<DialogTitle>{editNode ? '编辑节点' : '添加节点'}</DialogTitle>
<DialogDescription className="text-[var(--dg-text-muted)]">
基于服务器 SSH 凭据注册构建 Agent,流水线可绑定或自动调度
</DialogDescription>
</DialogHeader>
<div className="space-y-3">
<div className="space-y-1">
<Label className="text-xs">节点名称</Label>
<Input value={name} onChange={(e) => setName(e.target.value)} className="h-8 text-xs dg-input" placeholder="build-node-01" />
</div>
<div className="space-y-1">
<Label className="text-xs">关联服务器</Label>
<Select value={serverId || '__none'} onValueChange={(v) => setServerId(v === '__none' ? '' : v)}>
<SelectTrigger className="h-8 text-xs dg-input"><SelectValue placeholder="选择服务器" /></SelectTrigger>
<SelectContent>
<SelectItem value="__none">请选择</SelectItem>
{servers.map((s) => (
<SelectItem key={s.id} value={String(s.id)}>
{s.hostname} ({s.ip})
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="grid grid-cols-2 gap-2">
<div className="space-y-1">
<Label className="text-xs">最大并发</Label>
<Input value={maxExecutors} onChange={(e) => setMaxExecutors(e.target.value)} type="number" min={1} className="h-8 text-xs dg-input" />
</div>
<div className="space-y-1">
<Label className="text-xs">工作区路径</Label>
<Input value={workspacePath} onChange={(e) => setWorkspacePath(e.target.value)} className="h-8 text-xs font-mono dg-input" />
</div>
</div>
<div className="space-y-1">
<Label className="text-xs">标签 <span className="text-[var(--dg-text-muted)]">(可选)</span></Label>
<Input value={labels} onChange={(e) => setLabels(e.target.value)} className="h-8 text-xs dg-input" placeholder="linux,docker,high-mem" />
</div>
<div className="space-y-1">
<Label className="text-xs">描述</Label>
<Input value={description} onChange={(e) => setDescription(e.target.value)} className="h-8 text-xs dg-input" />
</div>
<div className="flex justify-end gap-2 pt-2">
<Button variant="outline" onClick={() => setDialogOpen(false)}>取消</Button>
<Button onClick={handleSubmit} disabled={submitting}>{submitting ? '保存中' : '保存'}</Button>
</div>
</div>
</DialogContent>
</Dialog>
);
if (embedded) {
return (
<>
{panel}
{dialog}
</>
);
}
return (
<PageShell title="构建节点" subtitle="Master 与远程 SSH 构建节点">
{panel}
{dialog}
</PageShell>
);
}
@@ -6,7 +6,9 @@ import { Badge } from '@/components/ui/badge';
import { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel';
import { PageEmpty } from '@/components/layout/PageEmpty';
import { StatStrip } from '@/components/ui/stat-strip';
import { useSearchParams } from 'react-router-dom';
import BuildNodesManager from './BuildNodesManager';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
@@ -98,8 +100,12 @@ function EnvFormDialog({ open, onClose, onSaved, editData }: { open: boolean; on
);
}
const CONFIG_TABS = ['repos', 'registries', 'environments', 'tools', 'build-nodes'] as const;
export default function DeployCredentials() {
const _confirm = useConfirm();
const [searchParams] = useSearchParams();
const tabFromUrl = searchParams.get('tab');
const [repos, setRepos] = useState<Repo[]>([]);
const [registries, setRegistries] = useState<Registry[]>([]);
const [environments, setEnvironments] = useState<Environment[]>([]);
@@ -109,7 +115,9 @@ export default function DeployCredentials() {
const [editingId, setEditingId] = useState<number | null>(null);
const [envDialogOpen, setEnvDialogOpen] = useState(false);
const [editEnv, setEditEnv] = useState<Environment | null>(null);
const [activeTab, setActiveTab] = useState('repos');
const [activeTab, setActiveTab] = useState(
tabFromUrl && (CONFIG_TABS as readonly string[]).includes(tabFromUrl) ? tabFromUrl : 'repos',
);
const fetchAll = async () => {
setLoading(true);
@@ -142,29 +150,21 @@ export default function DeployCredentials() {
{ id: 'repos', label: 'Git 仓库', badge: repos.length || undefined },
{ id: 'registries', label: '镜像仓库', badge: registries.length || undefined },
{ id: 'environments', label: '环境管理', badge: environments.length || undefined },
{ id: 'build-nodes', label: '构建节点' },
{ id: 'tools', label: '工具配置' },
];
return (
<PageShell
variant="list"
title="发布配置管理"
subtitle="Git 仓库、镜像仓库、环境与工具配置"
title="发布配置"
subtitle="Git 仓库、镜像仓库、环境与工具"
icon={<Settings2 className="h-5 w-5" />}
loading={loading}
tabs={pageTabs}
activeTab={activeTab}
onTabChange={setActiveTab}
metrics={(
<StatStrip
items={[
{ label: 'Git 仓库', value: repos.length, color: 'blue' },
{ label: '镜像仓库', value: registries.length, color: 'cyan' },
{ label: '环境', value: environments.length, color: 'purple' },
]}
/>
)}
actions={(
actions={activeTab === 'build-nodes' ? undefined : (
<>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={fetchAll}>
<RefreshCw className="w-4 h-4 mr-1" />刷新
@@ -177,6 +177,7 @@ export default function DeployCredentials() {
</Button>
</>
)}
contentClassName="space-y-4"
>
{activeTab === 'repos' && (
repos.length === 0 ? (
@@ -325,6 +326,8 @@ export default function DeployCredentials() {
</>
)}
{activeTab === 'build-nodes' && <BuildNodesManager embedded />}
{activeTab === 'tools' && <ToolConfigTab />}
<CredentialFormDialog
@@ -0,0 +1,37 @@
import { NavLink } from 'react-router-dom';
import { GitBranch, Settings2, Shield, Users, Server } from 'lucide-react';
import { cn } from '@/lib/utils';
const NAV_ITEMS = [
{ path: '/pipelines', label: '流水线', icon: GitBranch },
{ path: '/deploy/build-nodes', label: '构建节点', icon: Server },
{ path: '/deploy/configureTools', label: '发布配置', icon: Settings2 },
{ path: '/deploy/rbac', label: 'Job 权限', icon: Shield },
{ path: '/deploy/groups', label: '用户组', icon: Users },
];
// 应用发布模块二级导航 // Logan.Li
export function DeployNav() {
return (
<nav className="flex items-center gap-1 p-1 rounded-lg bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] w-fit flex-wrap">
{NAV_ITEMS.map((item) => {
const Icon = item.icon;
return (
<NavLink
key={item.path}
to={item.path}
className={({ isActive }) => cn(
'flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors',
isActive
? 'bg-[var(--dg-bg-primary)] text-[var(--dg-text-primary)] border border-[var(--dg-border)] shadow-sm'
: 'text-[var(--dg-text-muted)] hover:text-[var(--dg-text-primary)]',
)}
>
<Icon className="h-3.5 w-3.5" />
{item.label}
</NavLink>
);
})}
</nav>
);
}
+250 -271
View File
@@ -1,5 +1,5 @@
import { useState, useEffect, useMemo } from 'react';
import { Shield, Plus, Trash2, Save, Loader2, Users, Regex, Check, X, GitBranch, UserPlus} from 'lucide-react';
import { Shield, Plus, Trash2, Save, Loader2, Users, GitBranch, UserPlus, Check, X } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@@ -11,45 +11,62 @@ import { deployApi, userApi, pipelineApi } from '@/api';
import { useConfirm } from '@/components/ui/confirm-dialog';
import { PageShell } from '@/components/layout/PageShell';
import { PageEmpty } from '@/components/layout/PageEmpty';
import { StatStrip } from '@/components/ui/stat-strip';
import { useSearchParams } from 'react-router-dom';
import UserGroupsManager from './UserGroupsManager';
import { JobRoleCreateDialog } from './deploy-rbac/JobRoleCreateDialog';
import { matchPipelines, pipelineDisplayLabel, type PipelineMatchItem } from './deploy-rbac/matchPipeline';
import type { JsonData } from '@/types/common';
interface ItemRole {
id: number; name: string; code: string; pattern: string; role: string;
description: string; status: number; created_at: string;
id: number;
name: string;
code: string;
pattern: string;
role: string;
description: string;
status: number;
created_at: string;
}
interface AssignedUser {
id: number; user_id: number; item_role_id: number;
user?: { id: number; username: string; real_name: string };
id: number;
user_id: number;
item_role_id: number;
item_role?: ItemRole;
}
const ROLE_LABEL: Record<string, string> = {
owner: '拥有者',
editor: '编辑者',
viewer: '查看者',
};
const RBAC_TABS = ['roles', 'users', 'preview', 'groups'] as const;
// 发布 Job 权限 — 正则匹配 code / job_name,Jenkins Role Strategy 风格 // Logan.Li
export default function DeployRBAC() {
const [searchParams] = useSearchParams();
const tabFromUrl = searchParams.get('tab');
const [roles, setRoles] = useState<ItemRole[]>([]);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
// Pipeline list for live preview
const [pipelines, setPipelines] = useState<JsonData[]>([]);
const [activeTab, setActiveTab] = useState(
tabFromUrl && (RBAC_TABS as readonly string[]).includes(tabFromUrl) ? tabFromUrl : 'roles',
);
const [pipelines, setPipelines] = useState<PipelineMatchItem[]>([]);
const [previewRoleId, setPreviewRoleId] = useState<number | null>(null);
// User assignment
const [users, setUsers] = useState<JsonData[]>([]);
const [assignments, setAssignments] = useState<AssignedUser[]>([]);
const [selectedUserId, setSelectedUserId] = useState<string>('');
const [assignRoleId, setAssignRoleId] = useState<string>('');
const [selectedUserId, setSelectedUserId] = useState('');
const [assignRoleId, setAssignRoleId] = useState('');
const [assignLoading, setAssignLoading] = useState(false);
// Create
const [showCreate, setShowCreate] = useState(false);
const [createOpen, setCreateOpen] = useState(false);
const [newName, setNewName] = useState('');
const [newCode, setNewCode] = useState('');
const [newPattern, setNewPattern] = useState('');
const [newRole, setNewRole] = useState('editor');
const [newDesc, setNewDesc] = useState('');
// Edit
const [editing, setEditing] = useState<number | null>(null);
const [editPattern, setEditPattern] = useState('');
const [editRole, setEditRole] = useState('');
@@ -64,11 +81,10 @@ export default function DeployRBAC() {
pipelineApi.getPipelines({ page_size: 200 }),
userApi.getUsers({ page_size: 500 }),
]);
setRoles(Array.isArray(rolesRes) ? rolesRes : (rolesRes as JsonData)?.list || (rolesRes as JsonData)?.data || []);
setPipelines(Array.isArray(pipesRes) ? pipesRes : (pipesRes as JsonData)?.list || (pipesRes as JsonData)?.data || []);
const uList = Array.isArray(usersRes) ? usersRes : (usersRes as JsonData)?.list || (usersRes as JsonData)?.data || [];
setUsers(uList);
} catch { /* */ }
setRoles(Array.isArray(rolesRes) ? rolesRes : (rolesRes as JsonData)?.list || []);
setPipelines(Array.isArray(pipesRes) ? pipesRes : (pipesRes as JsonData)?.list || []);
setUsers(Array.isArray(usersRes) ? usersRes : (usersRes as JsonData)?.list || []);
} catch { /* silent */ }
finally { setLoading(false); }
};
@@ -78,40 +94,40 @@ export default function DeployRBAC() {
if (!selectedUserId) { setAssignments([]); return; }
try {
const res: JsonData = await deployApi.getUserItemRoles(Number(selectedUserId));
setAssignments(Array.isArray(res) ? res : res?.data || res?.list || []);
setAssignments(Array.isArray(res) ? res : res?.list || []);
} catch { setAssignments([]); }
};
useEffect(() => { loadAssignments(); }, [selectedUserId]);
// Compute matched pipeline codes for each role
const matchCount = useMemo(() => {
const map: Record<number, string[]> = {};
roles.forEach(r => {
try {
const re = new RegExp(r.pattern);
map[r.id] = pipelines.filter(p => re.test(p.code)).map(p => p.code);
} catch { map[r.id] = []; }
});
const map: Record<number, PipelineMatchItem[]> = {};
roles.forEach((r) => { map[r.id] = matchPipelines(r.pattern, pipelines); });
return map;
}, [roles, pipelines]);
const previewRole = previewRoleId ? roles.find(r => r.id === previewRoleId) : null;
const previewMatches = previewRole ? (matchCount[previewRoleId!] || []) : [];
const previewMatches = previewRoleId ? (matchCount[previewRoleId] || []) : pipelines;
const handleCreate = async () => {
if (!newName.trim() || !newCode.trim() || !newPattern.trim()) {
toast.error('名称、代码、正则表达式不能为空'); return;
toast.error('请填写名称、标识与正则'); return;
}
setSaving(true);
try {
await deployApi.createItemRole({ name: newName.trim(), code: newCode.trim(), pattern: newPattern.trim(), role: newRole, description: newDesc });
await deployApi.createItemRole({
name: newName.trim(),
code: newCode.trim(),
pattern: newPattern.trim(),
role: newRole,
description: newDesc,
});
toast.success('已创建');
setShowCreate(false);
setCreateOpen(false);
setNewName(''); setNewCode(''); setNewPattern(''); setNewRole('editor'); setNewDesc('');
loadData();
} catch (e) { toast.error(e?.message || '创建失败'); }
finally { setSaving(false); }
} catch (e: unknown) {
toast.error((e as Error)?.message || '创建失败');
} finally { setSaving(false); }
};
const handleUpdate = async (id: number) => {
@@ -122,12 +138,17 @@ export default function DeployRBAC() {
toast.success('已更新');
setEditing(null);
loadData();
} catch (e) { toast.error(e?.message || '更新失败'); }
finally { setSaving(false); }
} catch (e: unknown) {
toast.error((e as Error)?.message || '更新失败');
} finally { setSaving(false); }
};
const handleDelete = async (role: ItemRole) => {
const ok = await _confirm({ title: '删除角色', description: `确定删除「${role.name}」?匹配 ${matchCount[role.id]?.length || 0} 条流水线`, variant: 'destructive' });
const ok = await _confirm({
title: '删除权限',
description: `确定删除「${role.name}」?将影响 ${matchCount[role.id]?.length || 0} 个发布任务`,
variant: 'destructive',
});
if (!ok) return;
try { await deployApi.deleteItemRole(role.id); toast.success('已删除'); loadData(); }
catch { toast.error('删除失败'); }
@@ -142,15 +163,19 @@ export default function DeployRBAC() {
};
const handleAssign = async () => {
if (!selectedUserId || !assignRoleId) { toast.error('请选择用户和角色'); return; }
if (!selectedUserId || !assignRoleId) { toast.error('请选择用户和权限'); return; }
setAssignLoading(true);
try {
await deployApi.assignItemRole(Number(selectedUserId), { user_id: Number(selectedUserId), item_role_id: Number(assignRoleId) });
await deployApi.assignItemRole(Number(selectedUserId), {
user_id: Number(selectedUserId),
item_role_id: Number(assignRoleId),
});
toast.success('已分配');
setAssignRoleId('');
loadAssignments();
} catch (e) { toast.error(e?.message || '分配失败'); }
finally { setAssignLoading(false); }
} catch (e: unknown) {
toast.error((e as Error)?.message || '分配失败');
} finally { setAssignLoading(false); }
};
const handleRevoke = async (id: number) => {
@@ -161,257 +186,211 @@ export default function DeployRBAC() {
} catch { toast.error('撤销失败'); }
};
const roleBadgeClass = (role: string) =>
role === 'owner' ? 'bg-amber-500/20 dg-text-yellow border-amber-500/30' :
role === 'editor' ? 'bg-blue-500/20 dg-text-blue border-blue-500/30' :
'bg-[var(--dg-bg-active)]/20 dg-text-secondary border-[var(--dg-border)]';
const selectedUser = users.find(u => String(u.id) === selectedUserId);
const activeRoles = roles.filter(r => r.status === 1).length;
const selectedUser = users.find((u) => String(u.id) === selectedUserId);
const pageTabs = [
{ id: 'roles', label: '权限策略', badge: roles.length || undefined },
{ id: 'users', label: '用户授权' },
{ id: 'groups', label: '用户组' },
{ id: 'preview', label: '命中预览' },
];
return (
<PageShell
variant="list"
title="发布权限"
subtitle="Jenkins-style Role Strategy — 按流水线 code 正则匹配分配角色"
title="Job 权限"
subtitle="按流水线 code / Job 名称正则分配发布权限"
icon={<Shield className="h-5 w-5" />}
loading={loading}
metrics={(
<StatStrip
items={[
{ label: 'Item Role', value: roles.length, color: 'purple' },
{ label: '已启用', value: activeRoles, color: 'emerald' },
{ label: '流水线', value: pipelines.length, color: 'blue' },
]}
/>
)}
actions={(
<Button className="dg-btn-primary" onClick={() => setShowCreate(true)} disabled={showCreate}>
<Plus className="w-4 h-4 mr-1" />新建角色
tabs={pageTabs}
activeTab={activeTab}
onTabChange={setActiveTab}
actions={activeTab === 'groups' ? undefined : (
<Button className="dg-btn-primary" onClick={() => setCreateOpen(true)}>
<Plus className="w-4 h-4 mr-1" />新建权限
</Button>
)}
contentClassName="space-y-4"
>
{/* ====== Pipeline Preview ====== */}
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
<CardContent className="p-4">
<div className="flex items-center gap-2 mb-3">
<GitBranch className="w-4 h-4 dg-text-blue" />
<span className="text-sm font-medium text-[var(--dg-text-primary)]">流水线命中预览</span>
<span className="text-xs text-[var(--dg-text-muted)]">— 选择一个角色查看哪些流水线会被匹配</span>
</div>
<div className="flex gap-2 mb-3 flex-wrap">
<Button variant={previewRoleId === null ? 'secondary' : 'ghost'} size="sm" onClick={() => setPreviewRoleId(null)}>全部 ({pipelines.length})</Button>
{roles.map(r => (
<Button key={r.id} variant={previewRoleId === r.id ? 'secondary' : 'ghost'} size="sm" onClick={() => setPreviewRoleId(r.id)}
className={r.status === 0 ? 'opacity-40' : ''}>
{r.name} ({matchCount[r.id]?.length || 0})
</Button>
{activeTab === 'roles' && (
roles.length === 0 ? (
<PageEmpty
icon={<Shield className="h-10 w-10" />}
title="暂无 Job 权限策略"
description="创建策略后,用户将按正则自动获得匹配流水线的访问权限"
action={<Button onClick={() => setCreateOpen(true)}><Plus className="h-4 w-4 mr-1" />新建权限</Button>}
/>
) : (
<div className="space-y-2">
{roles.map((role) => (
<Card key={role.id} className={`dg-card ${role.status === 0 ? 'opacity-50' : ''}`}>
<CardContent className="p-3">
<div className="flex items-center justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 flex-wrap">
<span className="text-sm font-medium text-[var(--dg-text-primary)]">{role.name}</span>
<Badge variant="outline" className="text-[10px] border-[var(--dg-border)]">
{ROLE_LABEL[role.role] || role.role}
</Badge>
{role.status === 0 && <Badge variant="outline" className="text-[10px]">已禁用</Badge>}
<Badge
variant="outline"
className="text-[10px] cursor-pointer border-[var(--dg-border)]"
onClick={() => { setActiveTab('preview'); setPreviewRoleId(role.id); }}
>
{matchCount[role.id]?.length || 0} 个 Job
</Badge>
</div>
<p className="text-xs text-[var(--dg-text-muted)] mt-1 font-mono truncate">
{role.pattern}
{role.description ? ` · ${role.description}` : ''}
</p>
</div>
<div className="flex items-center gap-1 shrink-0">
{editing === role.id ? (
<>
<Input value={editPattern} onChange={(e) => setEditPattern(e.target.value)} className="h-7 w-32 text-xs font-mono dg-input" />
<Select value={editRole} onValueChange={setEditRole}>
<SelectTrigger className="h-7 w-20 text-xs"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="owner">拥有者</SelectItem>
<SelectItem value="editor">编辑者</SelectItem>
<SelectItem value="viewer">查看者</SelectItem>
</SelectContent>
</Select>
<Button size="icon" variant="ghost" className="h-7 w-7" onClick={() => handleUpdate(role.id)}><Check className="w-3.5 h-3.5" /></Button>
<Button size="icon" variant="ghost" className="h-7 w-7" onClick={() => setEditing(null)}><X className="w-3.5 h-3.5" /></Button>
</>
) : (
<>
<Button variant="ghost" size="sm" className="h-7 text-xs" onClick={() => { setEditing(role.id); setEditPattern(role.pattern); setEditRole(role.role); }}>编辑</Button>
<Button variant="ghost" size="sm" className="h-7 text-xs" onClick={() => handleToggleStatus(role)}>{role.status ? '禁用' : '启用'}</Button>
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-red)]" onClick={() => handleDelete(role)}><Trash2 className="w-3.5 h-3.5" /></Button>
</>
)}
</div>
</div>
</CardContent>
</Card>
))}
</div>
<div className="flex flex-wrap gap-1.5 max-h-32 overflow-y-auto">
{previewRoleId === null
? pipelines.map(p => <Badge key={p.id} variant="secondary" className="text-xs"><GitBranch className="w-3 h-3 mr-0.5" />{p.code}</Badge>)
: pipelines.map(p => {
const matched = previewMatches.includes(p.code);
return (
<Badge key={p.id} variant={matched ? 'default' : 'secondary'}
className={`text-xs ${matched ? 'bg-purple-500/20 text-purple-300 border-purple-500/30' : 'opacity-30'}`}>
<GitBranch className="w-3 h-3 mr-0.5" />{p.code}
</Badge>
);
})
}
{previewRoleId !== null && previewMatches.length === 0 && (
<span className="text-xs dg-text-red">无匹配 — 请调整正则表达式</span>
)}
</div>
</CardContent>
</Card>
)
)}
{/* Create form */}
{showCreate && (
<Card className="bg-[var(--dg-bg-secondary)] border-purple-500/20">
<CardContent className="p-4 space-y-3">
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-[var(--dg-text-primary)] flex items-center gap-2"><Plus className="w-4 h-4" />新建 Item Role</span>
<Button variant="ghost" size="sm" onClick={() => setShowCreate(false)}>取消</Button>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1"><Label className="text-xs">名称</Label><Input value={newName} onChange={e => setNewName(e.target.value)} placeholder="如: backend" className="h-8 text-sm" /></div>
<div className="space-y-1"><Label className="text-xs">代码 (唯一标识)</Label><Input value={newCode} onChange={e => setNewCode(e.target.value)} placeholder="如: backend" className="h-8 text-sm font-mono" /></div>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1">
<Label className="text-xs flex items-center gap-1"><Regex className="w-3 h-3" />正则匹配 Pattern</Label>
<Input value={newPattern} onChange={e => { setNewPattern(e.target.value); }} placeholder='如: ^cex-.*' className="h-8 text-sm font-mono" />
{newPattern && (
<p className="text-xs text-[var(--dg-text-muted)]">
实时匹配: {(() => { try { const n = pipelines.filter(p => new RegExp(newPattern).test(p.code)).length; return n > 0 ? `✅ 命中 ${n} 条流水线` : '⚠️ 无匹配'; } catch { return '❌ 正则语法错误'; } })()}
</p>
)}
</div>
<div className="space-y-1">
<Label className="text-xs">角色</Label>
<Select value={newRole} onValueChange={setNewRole}>
<SelectTrigger className="h-8 text-sm"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="owner">拥有者 (owner)</SelectItem>
<SelectItem value="editor">编辑者 (editor)</SelectItem>
<SelectItem value="viewer">查看者 (viewer)</SelectItem>
{activeTab === 'users' && (
<Card className="dg-card">
<CardContent className="p-4 space-y-4">
<div className="flex flex-wrap gap-3 items-end">
<div className="space-y-1 flex-1 min-w-[200px]">
<Label className="text-xs">用户</Label>
<Select value={selectedUserId} onValueChange={setSelectedUserId}>
<SelectTrigger className="h-8 text-sm dg-input"><SelectValue placeholder="选择用户" /></SelectTrigger>
<SelectContent className="max-h-60">
{users.map((u) => (
<SelectItem key={u.id as number} value={String(u.id)}>
{(u.real_name as string) || (u.username as string)} ({u.username as string})
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-1"><Label className="text-xs">描述 (可选)</Label><Input value={newDesc} onChange={e => setNewDesc(e.target.value)} placeholder="简要说明此角色的用途" className="h-8 text-sm" /></div>
<Button onClick={handleCreate} disabled={saving} className="w-full">
{saving ? <Loader2 className="w-4 h-4 mr-1 animate-spin" /> : <Save className="w-4 h-4 mr-1" />}
{saving ? '创建中...' : '创建'}
</Button>
</CardContent>
</Card>
)}
{/* Role list */}
{roles.length === 0 ? (
<PageEmpty icon={<Shield className="h-10 w-10" />} title="暂无 Item Role" description="创建角色后按正则匹配流水线并分配给用户" />
) : (
<div className="space-y-2">
{roles.map(role => (
<Card key={role.id} className={`bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] ${role.status === 0 ? 'opacity-50' : ''}`}>
<CardContent className="p-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3 flex-1 min-w-0">
<div className="w-9 h-9 rounded-lg bg-purple-500/20 flex items-center justify-center shrink-0">
<Regex className="w-4 h-4 dg-text-purple" />
</div>
<div className="min-w-0">
<div className="flex items-center gap-1.5 flex-wrap">
<span className="text-sm font-semibold text-[var(--dg-text-primary)]">{role.name}</span>
<Badge className={`text-xs border ${roleBadgeClass(role.role)}`}>{role.role === 'owner' ? '拥有者' : role.role === 'editor' ? '编辑者' : '查看者'}</Badge>
{role.status === 0 && <Badge variant="secondary" className="text-xs dg-text-red">已禁用</Badge>}
<Badge variant="secondary" className="text-xs cursor-pointer" onClick={() => setPreviewRoleId(previewRoleId === role.id ? null : role.id)}>
<GitBranch className="w-3 h-3 mr-0.5" />{matchCount[role.id]?.length || 0} 条
</Badge>
</div>
<div className="text-xs text-[var(--dg-text-secondary)] mt-0.5 truncate">
<code className="font-mono dg-text-purple bg-purple-500/10 px-1 rounded">{role.code}</code>
<span className="mx-1">→</span>
<code className="font-mono dg-text-blue bg-blue-500/10 px-1 rounded">{role.pattern}</code>
{role.description && <span className="ml-2 opacity-60">{role.description}</span>}
</div>
</div>
</div>
<div className="flex items-center gap-1 shrink-0">
{editing === role.id ? (
<>
<Input value={editPattern} onChange={e => setEditPattern(e.target.value)} className="h-7 w-36 text-xs font-mono" placeholder="正则表达式" />
<Select value={editRole} onValueChange={setEditRole}>
<SelectTrigger className="h-7 w-20 text-xs"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="owner">拥有者</SelectItem>
<SelectItem value="editor">编辑者</SelectItem>
<SelectItem value="viewer">查看者</SelectItem>
</SelectContent>
</Select>
<Button size="icon" variant="ghost" className="h-7 w-7 dg-text-green" onClick={() => handleUpdate(role.id)}><Check className="w-3.5 h-3.5" /></Button>
<Button size="icon" variant="ghost" className="h-7 w-7 dg-text-red" onClick={() => setEditing(null)}><X className="w-3.5 h-3.5" /></Button>
</>
) : (
<>
<Button variant="ghost" size="sm" className="h-7 text-xs" onClick={() => { setEditing(role.id); setEditPattern(role.pattern); setEditRole(role.role); }}><Save className="w-3 h-3 mr-1" />编辑</Button>
<Button variant="ghost" size="sm" className="h-7 text-xs" onClick={() => handleToggleStatus(role)}>{role.status ? '禁用' : '启用'}</Button>
<Button variant="ghost" size="icon" className="h-7 w-7 text-red-500" onClick={() => handleDelete(role)}><Trash2 className="w-3.5 h-3.5" /></Button>
</>
)}
</div>
</div>
</CardContent>
</Card>
))}
</div>
)}
{/* ====== User Assignment ====== */}
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
<CardContent className="p-4">
<div className="flex items-center gap-2 mb-3">
<UserPlus className="w-4 h-4 dg-text-yellow" />
<span className="text-sm font-medium text-[var(--dg-text-primary)]">分配角色给用户</span>
</div>
<div className="flex gap-3 items-end mb-4">
<div className="space-y-1 flex-1">
<Label className="text-xs">选择用户</Label>
<Select value={selectedUserId} onValueChange={setSelectedUserId}>
<SelectTrigger className="h-8 text-sm"><SelectValue placeholder="选择用户..." /></SelectTrigger>
<SelectContent className="max-h-60">
<div className="px-2 py-1.5 sticky top-0 bg-popover z-10"><Input placeholder="搜索用户..." className="h-7 text-xs" /></div>
{users.map(u => (
<SelectItem key={u.id} value={String(u.id)}>
{u.real_name || u.username} ({u.username})
{assignments.some(a => a.user_id === u.id) && <span className="ml-2 text-xs dg-text-purple">已分配</span>}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1 w-48">
<Label className="text-xs">Item Role</Label>
<Select value={assignRoleId} onValueChange={setAssignRoleId}>
<SelectTrigger className="h-8 text-sm"><SelectValue placeholder="选择角色" /></SelectTrigger>
<SelectContent>
{roles.filter(r => r.status === 1).map(r => (
<SelectItem key={r.id} value={String(r.id)}>{r.name} ({r.role})</SelectItem>
))}
</SelectContent>
</Select>
</div>
<Button className="h-8" onClick={handleAssign} disabled={assignLoading || !selectedUserId || !assignRoleId}>
{assignLoading ? <Loader2 className="w-3.5 h-3.5 mr-1 animate-spin" /> : <UserPlus className="w-3.5 h-3.5 mr-1" />}
分配
</Button>
</div>
{/* Assigned roles for selected user */}
{selectedUser && (
<div>
<div className="flex items-center gap-2 mb-2">
<Badge variant="secondary" className="text-xs">
<Users className="w-3 h-3 mr-1" />{selectedUser.real_name || selectedUser.username}
</Badge>
<span className="text-xs text-[var(--dg-text-muted)]">已分配角色:</span>
<div className="space-y-1 w-48">
<Label className="text-xs">权限策略</Label>
<Select value={assignRoleId} onValueChange={setAssignRoleId}>
<SelectTrigger className="h-8 text-sm dg-input"><SelectValue placeholder="选择策略" /></SelectTrigger>
<SelectContent>
{roles.filter((r) => r.status === 1).map((r) => (
<SelectItem key={r.id} value={String(r.id)}>{r.name} ({ROLE_LABEL[r.role]})</SelectItem>
))}
</SelectContent>
</Select>
</div>
{assignments.length === 0 ? (
<p className="text-xs text-[var(--dg-text-muted)] py-2">该用户尚未分配任何 Item Role</p>
<Button className="h-8" onClick={handleAssign} disabled={assignLoading || !selectedUserId || !assignRoleId}>
{assignLoading ? <Loader2 className="w-3.5 h-3.5 mr-1 animate-spin" /> : <UserPlus className="w-3.5 h-3.5 mr-1" />}
分配
</Button>
</div>
{selectedUser ? (
assignments.length === 0 ? (
<p className="text-xs text-[var(--dg-text-muted)]">该用户尚未分配 Job 权限</p>
) : (
<div className="space-y-1">
{assignments.map(a => {
const roleInfo = a.item_role || roles.find(r => r.id === a.item_role_id);
<div className="space-y-1.5">
{assignments.map((a) => {
const roleInfo = a.item_role || roles.find((r) => r.id === a.item_role_id);
return (
<div key={a.id} className="flex items-center justify-between py-1.5 px-2 rounded bg-[var(--dg-bg-tertiary)] text-xs">
<div className="flex items-center gap-2">
<Badge className={`text-xs border ${roleBadgeClass(roleInfo?.role || 'viewer')}`}>
{roleInfo?.role === 'owner' ? '拥有者' : roleInfo?.role === 'editor' ? '编辑者' : '查看者'}
</Badge>
<span className="text-[var(--dg-text-primary)]">{roleInfo?.name || `#${a.item_role_id}`}</span>
{roleInfo && (
<code className="font-mono text-[var(--dg-text-muted)] bg-[var(--dg-bg-primary)] px-1 rounded text-xs">
{roleInfo.pattern}
</code>
)}
<div key={a.id} className="flex items-center justify-between py-2 px-2.5 rounded-md bg-[var(--dg-bg-tertiary)] text-xs">
<div className="flex items-center gap-2 min-w-0">
<Badge variant="outline" className="text-[10px] shrink-0">{ROLE_LABEL[roleInfo?.role || ''] || roleInfo?.role}</Badge>
<span className="text-[var(--dg-text-primary)]">{roleInfo?.name}</span>
<code className="text-[var(--dg-text-muted)] truncate">{roleInfo?.pattern}</code>
</div>
<Button variant="ghost" size="icon" className="h-6 w-6 dg-text-red" onClick={() => handleRevoke(a.id)}>
<Button variant="ghost" size="icon" className="h-6 w-6 shrink-0" onClick={() => handleRevoke(a.id)}>
<X className="w-3 h-3" />
</Button>
</div>
);
})}
</div>
)
) : (
<p className="text-xs text-[var(--dg-text-muted)] flex items-center gap-1"><Users className="w-3.5 h-3.5" />选择用户后查看已分配权限</p>
)}
</CardContent>
</Card>
)}
{activeTab === 'groups' && <UserGroupsManager embedded />}
{activeTab === 'preview' && (
<Card className="dg-card">
<CardContent className="p-4 space-y-3">
<div className="flex flex-wrap gap-1.5">
<Button variant={previewRoleId === null ? 'secondary' : 'ghost'} size="sm" onClick={() => setPreviewRoleId(null)}>
全部 ({pipelines.length})
</Button>
{roles.map((r) => (
<Button
key={r.id}
variant={previewRoleId === r.id ? 'secondary' : 'ghost'}
size="sm"
className={r.status === 0 ? 'opacity-40' : ''}
onClick={() => setPreviewRoleId(r.id)}
>
{r.name} ({matchCount[r.id]?.length || 0})
</Button>
))}
</div>
<div className="flex flex-wrap gap-1.5 max-h-48 overflow-y-auto">
{previewMatches.map((p) => (
<Badge key={p.id as number} variant="outline" className="text-xs font-mono border-[var(--dg-border)]">
<GitBranch className="w-3 h-3 mr-0.5" />
{pipelineDisplayLabel(p)}
</Badge>
))}
{previewRoleId !== null && previewMatches.length === 0 && (
<span className="text-xs text-[var(--dg-text-muted)]">无匹配 — 请调整正则</span>
)}
</div>
)}
</CardContent>
</Card>
</CardContent>
</Card>
)}
<JobRoleCreateDialog
open={createOpen}
onOpenChange={setCreateOpen}
pipelines={pipelines}
saving={saving}
name={newName}
code={newCode}
pattern={newPattern}
role={newRole}
description={newDesc}
onNameChange={setNewName}
onCodeChange={setNewCode}
onPatternChange={setNewPattern}
onRoleChange={setNewRole}
onDescriptionChange={setNewDesc}
onSubmit={handleCreate}
/>
</PageShell>
);
}
}
@@ -42,7 +42,7 @@ import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { toast } from 'sonner';
import { pipelineApi, deployApi } from '@/api';
import { pipelineApi, deployApi, buildNodeApi, type BuildNode } from '@/api';
import { useConfirm } from '@/components/ui/confirm-dialog';
import { PageShell } from '@/components/layout/PageShell';
import { PageEmpty } from '@/components/layout/PageEmpty';
@@ -182,6 +182,8 @@ export default function PipelineEditor() {
const [webhookToken, setWebhookToken] = useState('');
const [variables, setVariables] = useState<[string, string][]>([]);
const [environmentId, setEnvironmentId] = useState<number | string>('');
const [buildNodes, setBuildNodes] = useState<BuildNode[]>([]);
const [buildNodeId, setBuildNodeId] = useState('');
// member add dialog
const [newMemberUser, setNewMemberUser] = useState('');
@@ -230,6 +232,7 @@ export default function PipelineEditor() {
setCronExpr(p.cron_expr || '');
setWebhookToken(p.webhook_token || '');
setEnvironmentId(p.environment_id || '');
setBuildNodeId(p.build_node_id ? String(p.build_node_id) : '');
try {
const parsed = p.variables ? JSON.parse(p.variables) : {};
setVariables(Object.entries(parsed).map(([k, v]) => [k, String(v)]));
@@ -249,6 +252,10 @@ export default function PipelineEditor() {
loadEnvironments();
loadMembers();
loadRuns();
buildNodeApi.list().then((res) => {
const data = res as { list?: BuildNode[] };
setBuildNodes(Array.isArray(data?.list) ? data.list.filter((n) => n.enabled) : []);
}).catch(() => { /* silent */ });
}, [pipelineCode, loadEnvironments, loadMembers, loadRuns]);
const selectedTask = stages.flatMap(s => s.tasks).find(t => t.id === selectedTaskId) || null;
@@ -273,6 +280,7 @@ export default function PipelineEditor() {
webhook_token: webhookToken,
environment_id: environmentId ? Number(environmentId) : null,
variables: JSON.stringify(Object.fromEntries(variables.filter(([k]) => k.trim()))),
build_node_id: buildNodeId ? Number(buildNodeId) : null,
});
toast.success('已保存');
} catch { toast.error('保存失败'); }
@@ -386,7 +394,20 @@ export default function PipelineEditor() {
))}
</SelectContent>
</Select>
<span className="text-xs text-[var(--dg-text-secondary)] opacity-70">选择后流水线执行记录会关联到对应环境</span>
<Server className="w-4 h-4 text-[var(--dg-text-secondary)] ml-2" />
<span className="text-sm text-[var(--dg-text-secondary)]">构建节点:</span>
<Select value={buildNodeId || '__auto'} onValueChange={v => setBuildNodeId(v === '__auto' ? '' : v)}>
<SelectTrigger className="w-48 h-8 text-sm"><SelectValue placeholder="自动调度" /></SelectTrigger>
<SelectContent>
<SelectItem value="__auto">自动调度(Master 优先)</SelectItem>
{buildNodes.map(n => (
<SelectItem key={n.id} value={String(n.id)}>
{n.name} ({n.running_count || 0}/{n.max_executors})
</SelectItem>
))}
</SelectContent>
</Select>
<span className="text-xs text-[var(--dg-text-secondary)] opacity-70">Master 满载时自动调度到空闲远程节点</span>
</CardContent>
</Card>
@@ -491,6 +512,7 @@ export default function PipelineEditor() {
<th className="px-3 py-2 text-left text-[var(--dg-text-secondary)]">状态</th>
<th className="px-3 py-2 text-left text-[var(--dg-text-secondary)]">触发方式</th>
<th className="px-3 py-2 text-left text-[var(--dg-text-secondary)]">触发人</th>
<th className="px-3 py-2 text-left text-[var(--dg-text-secondary)]">节点</th>
<th className="px-3 py-2 text-left text-[var(--dg-text-secondary)]">分支</th>
<th className="px-3 py-2 text-left text-[var(--dg-text-secondary)]">耗时</th>
<th className="px-3 py-2 text-left text-[var(--dg-text-secondary)]">时间</th>
@@ -516,6 +538,7 @@ export default function PipelineEditor() {
{!r.trigger_mode && (r.triggered_by || '手动')}
</td>
<td className="px-3 py-2 text-[var(--dg-text-secondary)] text-xs">{r.triggered_by || 'admin'}</td>
<td className="px-3 py-2 text-[var(--dg-text-secondary)] text-xs">{r.build_node_name || 'Master'}</td>
<td className="px-3 py-2 text-[var(--dg-text-secondary)] font-mono text-xs">{r.branch || '-'}</td>
<td className="px-3 py-2 text-[var(--dg-text-secondary)]">{fmtDuration(r.duration)}</td>
<td className="px-3 py-2 text-[var(--dg-text-secondary)] text-xs">{r.created_at ? new Date(r.created_at).toLocaleString('zh-CN') : '-'}</td>
@@ -5,21 +5,13 @@ import { Input } from '@/components/ui/input';
import {
Plus,
Search,
GitBranch,
Clock,
CheckCircle,
Rocket,
Container,
ArrowRight,
Layers,
ShieldCheck,
Globe,
Code,
Workflow,
Server,
Network,
} from 'lucide-react';
import { pipelineApi } from '@/api';
import { pipelineApi, deployApi } from '@/api';
import { usePipelines, usePipelineMutations } from '@/hooks/api';
import { useConfirm } from '@/components/ui/confirm-dialog';
import { toast } from 'sonner';
@@ -27,7 +19,16 @@ import { PipelineCard } from './pipeline-manager/PipelineCard';
import { PipelineCreateDialog } from './pipeline-manager/PipelineCreateDialog';
import { PageShell } from '@/components/layout/PageShell';
import { PageEmpty } from '@/components/layout/PageEmpty';
import { StatStrip } from '@/components/ui/stat-strip';
import type { JsonData } from '@/types/common';
interface DeployEnvironment {
id: number;
name: string;
display_name: string;
type: string;
color: string;
enabled: boolean;
}
// 流水线列表页编排器 // Logan.Li
export function PipelineManager() {
@@ -39,18 +40,20 @@ export function PipelineManager() {
const [runs, setRuns] = useState<Record<number, Record<string, unknown>[]>>({});
const [loadingRuns, setLoadingRuns] = useState<Record<number, boolean>>({});
const [envFilter, setEnvFilter] = useState<string>('all');
const [environments, setEnvironments] = useState<DeployEnvironment[]>([]);
const [runningRunMap, setRunningRunMap] = useState<Record<number, Record<string, unknown>>>({});
const [newOpen, setNewOpen] = useState(false);
const confirm = useConfirm();
const ENV_TYPES = [
{ key: 'all', label: t('deploy.env.all'), icon: Layers, color: '#6B7280' },
{ key: 'production', label: t('deploy.env.production'), icon: ShieldCheck, color: '#EF4444' },
{ key: 'testing', label: t('deploy.env.testing'), icon: CheckCircle, color: '#F59E0B' },
{ key: 'staging', label: t('deploy.env.staging'), icon: Globe, color: '#8B5CF6' },
{ key: 'development', label: t('deploy.env.development'), icon: Code, color: '#3B82F6' },
];
useEffect(() => {
deployApi.getEnvironments()
.then((res) => {
const list = ((res as JsonData)?.list || []) as DeployEnvironment[];
setEnvironments(list.filter((e) => e.enabled !== false));
})
.catch(() => { /* 环境列表加载失败时仅显示「全部」 */ });
}, []);
// 同步运行中的任务 ID // Logan.Li
useEffect(() => {
@@ -152,12 +155,19 @@ export function PipelineManager() {
const filtered = pipelines.filter((p) => {
const matchSearch = String(p.name || '').toLowerCase().includes(searchQuery.toLowerCase()) ||
String(p.description || '').toLowerCase().includes(searchQuery.toLowerCase());
const env = p.environment as Record<string, unknown> | undefined;
const matchEnv = envFilter === 'all' || (env?.type || '') === envFilter;
const envId = p.environment_id as number | undefined;
const matchEnv = envFilter === 'all' || String(envId || '') === envFilter;
return matchSearch && matchEnv;
});
const runningCount = pipelines.filter(p => p.last_status === 'running').length;
const envTabs = [
{ key: 'all', label: t('deploy.env.all'), color: undefined as string | undefined },
...environments.map((e) => ({
key: String(e.id),
label: e.display_name || e.name,
color: e.color,
})),
];
const toolbar = (
<div className="flex items-center gap-4 flex-wrap">
@@ -170,92 +180,67 @@ export function PipelineManager() {
className="pl-10 dg-input"
/>
</div>
<div className="flex items-center gap-1 bg-[var(--dg-bg-secondary)] rounded-lg p-1 border border-[var(--dg-border)]">
{ENV_TYPES.map((et) => {
const active = envFilter === et.key;
const Icon = et.icon;
return (
<button
key={et.key}
onClick={() => setEnvFilter(et.key)}
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-all ${
active ? 'text-white shadow-sm' : 'text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]'
}`}
style={active ? { backgroundColor: et.color } : {}}
>
<Icon className="h-3.5 w-3.5" />{et.label}
</button>
);
})}
</div>
{envTabs.length > 1 && (
<div className="flex items-center gap-1 bg-[var(--dg-bg-secondary)] rounded-lg p-1 border border-[var(--dg-border)] flex-wrap">
{envTabs.map((et) => {
const active = envFilter === et.key;
return (
<button
key={et.key}
onClick={() => setEnvFilter(et.key)}
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${
active
? 'bg-[var(--dg-bg-primary)] text-[var(--dg-text-primary)] border border-[var(--dg-border)] shadow-sm'
: 'text-[var(--dg-text-muted)] hover:text-[var(--dg-text-primary)]'
}`}
>
{et.key === 'all' ? (
<Layers className="h-3.5 w-3.5" />
) : (
<span
className="w-2 h-2 rounded-full shrink-0"
style={{ backgroundColor: et.color || 'var(--dg-text-muted)' }}
/>
)}
{et.label}
</button>
);
})}
</div>
)}
</div>
);
return (
<PageShell
variant="list"
title={t('deploy.pipeline.title')}
subtitle={t('deploy.pipeline.subtitle')}
title="流水线"
subtitle="CI/CD 构建、镜像打包与双通道部署"
icon={<Workflow className="h-5 w-5" />}
loading={loading}
metrics={(
<StatStrip
items={[
{ label: t('deploy.pipeline.title'), value: pipelines.length, color: 'blue' },
{ label: t('common.running'), value: runningCount, color: 'amber' },
{ label: t('deploy.env.all'), value: filtered.length, color: 'muted' },
]}
/>
)}
toolbar={toolbar}
actions={(
<>
<Button variant="outline" className="dg-btn-secondary" onClick={() => refetchPipelines()} disabled={isFetching}>
<Clock className={`h-4 w-4 mr-2 ${isFetching ? 'animate-spin' : ''}`} />{t('common.refresh')}
<Clock className="h-4 w-4 mr-2" />{t('common.refresh')}
</Button>
<Button className="dg-btn-primary" onClick={() => setNewOpen(true)}>
<Plus className="h-4 w-4 mr-2" />{t('deploy.pipeline.newPipeline')}
</Button>
</>
)}
contentClassName="space-y-4"
>
{/* 全流程可视化横幅 — 双路径 // Logan.Li */}
<div className="flex items-stretch gap-3 px-4 py-3 rounded-lg bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)]">
<div className="flex-1 space-y-1.5">
<div className="flex items-center gap-1.5">
<GitBranch className="h-3 w-3 text-indigo-400" />
<span className="text-[10px] font-semibold text-indigo-400">{t('deploy.banner.build')}</span>
<ArrowRight className="h-2.5 w-2.5 text-[var(--dg-text-secondary)] opacity-30" />
<Rocket className="h-3 w-3 dg-text-red" />
<span className="text-[10px] font-semibold dg-text-red">{t('deploy.banner.deploy')}</span>
<ArrowRight className="h-2.5 w-2.5 text-[var(--dg-text-secondary)] opacity-30" />
<div className="flex items-center gap-1 px-2 py-0.5 rounded bg-blue-400/10 border border-blue-400/20">
<Server className="h-3 w-3 dg-text-blue" />
<span className="text-[10px] font-medium dg-text-blue">{t('deploy.banner.sshHost')}</span>
</div>
</div>
<p className="text-[9px] text-[var(--dg-text-secondary)] opacity-40 pl-1">{t('deploy.banner.sshDesc')}</p>
</div>
<div className="w-px bg-[var(--dg-border)]" />
<div className="flex-1 space-y-1.5">
<div className="flex items-center gap-1.5">
<GitBranch className="h-3 w-3 text-indigo-400" />
<span className="text-[10px] font-semibold text-indigo-400">{t('deploy.banner.build')}</span>
<ArrowRight className="h-2.5 w-2.5 text-[var(--dg-text-secondary)] opacity-30" />
<Container className="h-3 w-3 dg-text-cyan" />
<span className="text-[10px] font-semibold dg-text-cyan">{t('deploy.banner.imageRegistry')}</span>
<ArrowRight className="h-2.5 w-2.5 text-[var(--dg-text-secondary)] opacity-30" />
<Rocket className="h-3 w-3 dg-text-red" />
<span className="text-[10px] font-semibold dg-text-red">{t('deploy.banner.deploy')}</span>
<ArrowRight className="h-2.5 w-2.5 text-[var(--dg-text-secondary)] opacity-30" />
<div className="flex items-center gap-1 px-2 py-0.5 rounded bg-emerald-400/10 border border-emerald-400/20">
<Network className="h-3 w-3 dg-text-green" />
<span className="text-[10px] font-medium dg-text-green">{t('deploy.banner.kubernetes')}</span>
</div>
</div>
<p className="text-[9px] text-[var(--dg-text-secondary)] opacity-40 pl-1">{t('deploy.banner.k8sDesc')}</p>
</div>
<span className="self-center ml-2 text-[10px] text-[var(--dg-text-secondary)] opacity-30 tracking-wide whitespace-nowrap">{t('deploy.banner.fullFlow')}</span>
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 px-4 py-2.5 rounded-lg bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] text-xs text-[var(--dg-text-muted)]">
<span className="flex items-center gap-1.5">
<Server className="h-3.5 w-3.5" />
主机发布:构建 → SSH 关联主机
</span>
<span className="hidden sm:inline text-[var(--dg-border)]">|</span>
<span className="flex items-center gap-1.5">
<Network className="h-3.5 w-3.5" />
Kubernetes 发布:构建 → 镜像 → 关联 Deployment 滚动更新
</span>
</div>
{!loading && filtered.length === 0 ? (
@@ -294,4 +279,4 @@ export function PipelineManager() {
<PipelineCreateDialog open={newOpen} onOpenChange={setNewOpen} onCreated={refetchPipelines} />
</PageShell>
);
}
}
@@ -1,9 +1,10 @@
import { useState, useEffect } from 'react';
import { RefreshCw, Loader2, Download, CheckCircle, XCircle, Clock, Settings2, ChevronDown} from 'lucide-react';
import { RefreshCw, Loader2, Download, CheckCircle, XCircle, Clock, Settings2, ChevronDown, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { useConfirm } from '@/components/ui/confirm-dialog';
import { toast } from 'sonner';
import { deployApi } from '@/api';
import type { JsonData } from '@/types/common';
@@ -29,22 +30,15 @@ const categoryColor: Record<string, string> = {
automation: 'bg-purple-500/20 dg-text-purple border-purple-500/30',
other: 'bg-[var(--dg-bg-active)]/20 dg-text-secondary border-[var(--dg-border)]',
};
const _methodLabel: Record<string, string> = {
preinstall: '预装', lazy: '懒加载', disabled: '禁用',
};
const _methodColor: Record<string, string> = {
preinstall: 'bg-emerald-500/20 dg-text-green border-emerald-500/30',
lazy: 'bg-violet-500/20 dg-text-purple border-violet-500/30',
disabled: 'bg-[var(--dg-bg-active)]/20 dg-text-secondary border-[var(--dg-border)]',
};
// Tools that support version selection
const VERSIONED_TOOLS = ['jdk', 'nodejs', 'maven'];
// 支持版本选择的工具 // Logan.Li
const VERSIONED_TOOLS = ['jdk', 'golang', 'nodejs', 'maven', 'nvm'];
export default function ToolConfigTab() {
const confirm = useConfirm();
const [tools, setTools] = useState<ToolConfig[]>([]);
const [loading, setLoading] = useState(false);
const [installing, setInstalling] = useState<number | null>(null);
const [uninstalling, setUninstalling] = useState<number | null>(null);
// Version dialog state
const [versionDialog, setVersionDialog] = useState<{ tool: ToolConfig; versions: VersionOption[] } | null>(null);
@@ -64,6 +58,14 @@ export default function ToolConfigTab() {
useEffect(() => { fetchTools(); }, []);
// 安装中/失败状态轮询,与磁盘实际状态同步 // Logan.Li
useEffect(() => {
const pending = tools.filter((t) => t.status === 'installing' || t.status === 'failed');
if (pending.length === 0) return undefined;
const timer = setInterval(() => { void fetchTools(); }, 4000);
return () => clearInterval(timer);
}, [tools]);
const openVersionDialog = async (tool: ToolConfig) => {
try {
const res: JsonData = await deployApi.getToolVersions(tool.id);
@@ -74,7 +76,12 @@ export default function ToolConfigTab() {
return;
}
setVersionDialog({ tool, versions });
setSelectedVersion(tool.default_version || versions[0]?.version || '');
const preferred = versions.find((v) => v.version === 'lts')?.version
|| versions.find((v) => v.label.includes('推荐'))?.version
|| tool.default_version
|| versions[0]?.version
|| '';
setSelectedVersion(preferred);
} catch {
// Fallback: install with default version
handleInstall(tool);
@@ -86,18 +93,37 @@ export default function ToolConfigTab() {
try {
const v = version || tool.default_version;
await deployApi.installTool(tool.id, v);
toast.success(`${tool.display_name}${v ? ` (${v})` : ''} 安装已触发`);
toast.success(`${tool.display_name}${v ? ` (${v})` : ''} 安装已触发,可在审计日志查看结果`);
setVersionDialog(null);
setTimeout(async () => {
try { await deployApi.checkTool(tool.id); fetchTools(); } catch { /* ignore */ }
setInstalling(null);
}, 3000);
setInstalling(null);
void fetchTools();
} catch {
toast.error('触发安装失败');
setInstalling(null);
}
};
const handleUninstall = async (tool: ToolConfig) => {
const ok = await confirm({
title: '卸载工具',
description: `确定卸载 ${tool.display_name}?卸载后可重新选择版本安装。`,
confirmText: '卸载',
variant: 'destructive',
});
if (!ok) return;
setUninstalling(tool.id);
try {
await deployApi.uninstallTool(tool.id);
toast.success(`${tool.display_name} 已卸载,可重新安装`);
void fetchTools();
} catch {
toast.error('卸载失败');
} finally {
setUninstalling(null);
}
};
const handleCheckStatus = async (tool: ToolConfig) => {
try {
const res: JsonData = await deployApi.checkTool(tool.id);
@@ -106,30 +132,22 @@ export default function ToolConfigTab() {
} catch { toast.error('检测失败'); }
};
const handleMethodChange = async (tool: ToolConfig, method: 'preinstall' | 'lazy' | 'disabled') => {
try {
await deployApi.updateTool(tool.id, { install_method: method });
toast.success('已更新');
fetchTools();
} catch { toast.error('更新失败'); }
};
// Download speed test
// 检测工具安装状态(磁盘验证)// Logan.Li
const handleTestDownload = async (tool: ToolConfig) => {
setTesting(tool.id);
const start = Date.now();
try {
// Simulate a quick reachability test by fetching the version URL
const res: JsonData = await deployApi.getToolVersions(tool.id);
const res: JsonData = await deployApi.checkTool(tool.id);
const elapsed = ((Date.now() - start) / 1000).toFixed(1);
const available = (res as JsonData)?.versions?.length > 0;
if (available) {
toast.success(`${tool.display_name} 镜像可访问 (${elapsed}s)`);
if (res?.available) {
toast.success(`${tool.display_name} 已就绪${res.version ? ` (${res.version})` : ''} (${elapsed}s)`);
} else {
toast(`${tool.display_name} 无法获取版本列表`, { description: '请检查网络连接' });
const errMsg = (res?.tool as ToolConfig | undefined)?.error_msg;
toast(`${tool.display_name} 未安装或不可用`, { description: errMsg || '可点击「安装」触发懒加载' });
}
fetchTools();
} catch {
toast.error(`${tool.display_name} 网络不可达`);
toast.error(`${tool.display_name} 检测失败`);
}
setTesting(null);
};
@@ -160,7 +178,6 @@ export default function ToolConfigTab() {
<tr>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">工具</th>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)] hidden sm:table-cell">分类</th>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">安装方式</th>
<th className="px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]">状态</th>
<th className="px-3 py-2 text-right font-medium text-[var(--dg-text-secondary)]">操作</th>
</tr>
@@ -188,21 +205,6 @@ export default function ToolConfigTab() {
{categoryLabel[tool.category] || tool.category}
</Badge>
</td>
<td className="px-3 py-2">
<Select
value={tool.install_method}
onValueChange={(v) => handleMethodChange(tool, v as 'preinstall' | 'lazy' | 'disabled')}
>
<SelectTrigger className="h-7 w-[90px] text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="preinstall">预装</SelectItem>
<SelectItem value="lazy">懒加载</SelectItem>
<SelectItem value="disabled">禁用</SelectItem>
</SelectContent>
</Select>
</td>
<td className="px-3 py-2">
{tool.status === 'installed' ? (
<Badge className="bg-emerald-500/20 dg-text-green border-emerald-500/30 text-xs gap-1">
@@ -224,7 +226,21 @@ export default function ToolConfigTab() {
</td>
<td className="px-3 py-2 text-right">
<div className="flex justify-end gap-1">
{tool.install_method === 'lazy' && tool.status !== 'installed' && (
{tool.install_method === 'lazy' && (tool.status === 'installed' || tool.status === 'failed') && (
<Button
variant="outline" size="sm" className="h-7 text-xs text-red-400 border-red-500/30 hover:bg-red-500/10"
onClick={() => handleUninstall(tool)}
disabled={uninstalling === tool.id}
>
{uninstalling === tool.id ? (
<Loader2 className="w-3 h-3 animate-spin mr-1" />
) : (
<Trash2 className="w-3 h-3 mr-1" />
)}
卸载
</Button>
)}
{tool.install_method === 'lazy' && tool.status !== 'installed' && tool.status !== 'installing' && (
hasVersions ? (
<Button
variant="outline" size="sm" className="h-7 text-xs"
@@ -287,6 +303,7 @@ export default function ToolConfigTab() {
<DialogTitle>选择安装版本</DialogTitle>
<DialogDescription>
{versionDialog?.tool.display_name} — 请选择要安装的版本
{versionDialog?.tool.name === 'nodejs' && '(推荐「最新 LTS」由 nvm 自动解析当前 LTS 线)'}
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-2">
@@ -4,6 +4,7 @@ import { Button } from '@/components/ui/button';
import { PageShell } from '@/components/layout/PageShell';
import { PageEmpty } from '@/components/layout/PageEmpty';
import { StatStrip } from '@/components/ui/stat-strip';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
@@ -21,7 +22,7 @@ interface GroupMember {
id: number; group_id: number; username: string; created_at: string;
}
export default function UserGroupsManager() {
export default function UserGroupsManager({ embedded = false }: { embedded?: boolean }) {
const _confirm = useConfirm();
const [groups, setGroups] = useState<Group[]>([]);
const [loading, setLoading] = useState(true);
@@ -83,33 +84,18 @@ export default function UserGroupsManager() {
const memberCount = groups.reduce((sum, g) => sum + (g.members || []).length, 0);
return (
<PageShell
variant="list"
title="用户组管理"
subtitle="创建用户组,将组授权给流水线,组内成员自动获得流水线权限"
icon={<Users className="h-5 w-5" />}
loading={loading}
metrics={(
<StatStrip
items={[
{ label: '用户组', value: groups.length, color: 'blue' },
{ label: '成员总数', value: memberCount, color: 'purple' },
]}
/>
)}
actions={(
<>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={loadGroups}>
<RefreshCw className="w-4 h-4 mr-1" />刷新
</Button>
<Button size="sm" className="dg-btn-primary" onClick={() => { setEditId(null); setFormName(''); setFormDesc(''); setFormOpen(true); }}>
<Plus className="w-4 h-4 mr-1" />新建用户组
</Button>
</>
)}
>
{!loading && groups.length === 0 ? (
const toolbar = embedded ? (
<div className="flex items-center justify-end gap-2 mb-3">
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={loadGroups}>
<RefreshCw className="w-4 h-4 mr-1" />刷新
</Button>
<Button size="sm" className="dg-btn-primary" onClick={() => { setEditId(null); setFormName(''); setFormDesc(''); setFormOpen(true); }}>
<Plus className="w-4 h-4 mr-1" />新建用户组
</Button>
</div>
) : null;
const listBody = !loading && groups.length === 0 ? (
<PageEmpty
icon={<Users className="h-10 w-10" />}
title="暂无用户组"
@@ -171,9 +157,9 @@ export default function UserGroupsManager() {
</div>
))}
</div>
)}
);
{/* Form Dialog */}
const formDialog = (
<Dialog open={formOpen} onOpenChange={setFormOpen}>
<DialogContent>
<DialogHeader><DialogTitle>{editId ? '编辑用户组' : '新建用户组'}</DialogTitle></DialogHeader>
@@ -187,6 +173,47 @@ export default function UserGroupsManager() {
</div>
</DialogContent>
</Dialog>
);
if (embedded) {
return (
<>
{toolbar}
{listBody}
{formDialog}
</>
);
}
return (
<PageShell
variant="list"
title="应用发布"
subtitle="用户组 — 批量授权流水线访问权限"
icon={<Users className="h-5 w-5" />}
loading={loading}
metrics={(
<StatStrip
items={[
{ label: '用户组', value: groups.length, color: 'blue' },
{ label: '成员总数', value: memberCount, color: 'purple' },
]}
/>
)}
actions={(
<>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={loadGroups}>
<RefreshCw className="w-4 h-4 mr-1" />刷新
</Button>
<Button size="sm" className="dg-btn-primary" onClick={() => { setEditId(null); setFormName(''); setFormDesc(''); setFormOpen(true); }}>
<Plus className="w-4 h-4 mr-1" />新建用户组
</Button>
</>
)}
contentClassName="space-y-4"
>
{listBody}
{formDialog}
</PageShell>
);
}
@@ -0,0 +1,121 @@
import { useMemo } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Loader2, Save } from 'lucide-react';
import { matchPipelines, type PipelineMatchItem } from './matchPipeline';
interface JobRoleCreateDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
pipelines: PipelineMatchItem[];
saving: boolean;
name: string;
code: string;
pattern: string;
role: string;
description: string;
onNameChange: (v: string) => void;
onCodeChange: (v: string) => void;
onPatternChange: (v: string) => void;
onRoleChange: (v: string) => void;
onDescriptionChange: (v: string) => void;
onSubmit: () => void;
}
// 新建 Job 权限角色弹窗 // Logan.Li
export function JobRoleCreateDialog({
open,
onOpenChange,
pipelines,
saving,
name,
code,
pattern,
role,
description,
onNameChange,
onCodeChange,
onPatternChange,
onRoleChange,
onDescriptionChange,
onSubmit,
}: JobRoleCreateDialogProps) {
const preview = useMemo(() => matchPipelines(pattern, pipelines), [pattern, pipelines]);
const patternHint = useMemo(() => {
if (!pattern.trim()) return '输入正则,匹配流水线 code 或 Job 名称';
try {
// eslint-disable-next-line no-new
new RegExp(pattern);
return preview.length > 0 ? `命中 ${preview.length} 个发布任务` : '无匹配任务';
} catch {
return '正则语法错误';
}
}, [pattern, preview.length]);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md bg-[var(--dg-bg-primary)] border-[var(--dg-border)]">
<DialogHeader>
<DialogTitle>新建 Job 权限</DialogTitle>
<DialogDescription className="text-[var(--dg-text-muted)]">
按正则匹配流水线 code 或 Job 名称,分配 owner / editor / viewer 权限
</DialogDescription>
</DialogHeader>
<div className="space-y-3">
<div className="grid grid-cols-2 gap-2">
<div className="space-y-1">
<Label className="text-xs">名称</Label>
<Input value={name} onChange={(e) => onNameChange(e.target.value)} placeholder="后端发布" className="h-8 text-sm dg-input" />
</div>
<div className="space-y-1">
<Label className="text-xs">标识</Label>
<Input value={code} onChange={(e) => onCodeChange(e.target.value)} placeholder="backend-jobs" className="h-8 text-sm font-mono dg-input" />
</div>
</div>
<div className="space-y-1">
<Label className="text-xs">匹配正则</Label>
<Input
value={pattern}
onChange={(e) => onPatternChange(e.target.value)}
placeholder="^cex-.* 或 ^api-server$"
className="h-8 text-sm font-mono dg-input"
/>
<p className="text-[10px] text-[var(--dg-text-muted)]">{patternHint}</p>
</div>
<div className="space-y-1">
<Label className="text-xs">权限级别</Label>
<Select value={role} onValueChange={onRoleChange}>
<SelectTrigger className="h-8 text-sm dg-input"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="owner">拥有者 — 配置 + 执行 + 授权</SelectItem>
<SelectItem value="editor">编辑者 — 配置 + 执行</SelectItem>
<SelectItem value="viewer">查看者 — 只读</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label className="text-xs">说明</Label>
<Input value={description} onChange={(e) => onDescriptionChange(e.target.value)} placeholder="可选" className="h-8 text-sm dg-input" />
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>取消</Button>
<Button onClick={onSubmit} disabled={saving}>
{saving ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Save className="h-4 w-4 mr-1" />}
创建
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,29 @@
// 流水线 / Job 正则命中工具(code + job_name) // Logan.Li
export interface PipelineMatchItem {
id: number | string;
code?: string;
job_name?: string;
name?: string;
}
export function pipelineMatchesPattern(pattern: string, pipeline: PipelineMatchItem): boolean {
try {
const re = new RegExp(pattern);
if (pipeline.code && re.test(String(pipeline.code))) return true;
if (pipeline.job_name && re.test(String(pipeline.job_name))) return true;
return false;
} catch {
return false;
}
}
export function matchPipelines(pattern: string, pipelines: PipelineMatchItem[]): PipelineMatchItem[] {
if (!pattern.trim()) return [];
return pipelines.filter((p) => pipelineMatchesPattern(pattern, p));
}
export function pipelineDisplayLabel(p: PipelineMatchItem): string {
if (p.job_name) return `${p.code} · ${p.job_name}`;
return String(p.code || p.name || p.id);
}
@@ -0,0 +1,373 @@
import { useState, useEffect, useCallback, useMemo } from 'react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Search, Server, Network, Loader2, Check } from 'lucide-react';
import { cn } from '@/lib/utils';
import { serverApi, kubernetesApi } from '@/api';
import { getPublicApiBase } from '@/utils/request';
export interface DeployTargetValue {
deployTarget: 'ssh' | 'k8s';
serverIds: number[];
deployRemotePath: string;
deployScript: string;
k8sClusterId: number | '';
k8sNamespace: string;
k8sDeployment: string;
k8sContainerName: string;
}
interface DeployTargetFieldsProps {
value: DeployTargetValue;
onChange: (patch: Partial<DeployTargetValue>) => void;
requireTarget?: boolean;
}
interface ServerItem {
id: number;
hostname: string;
ip?: string;
status?: string;
}
interface ClusterItem {
id: number;
name: string;
code: string;
}
interface DeploymentItem {
namespace: string;
name: string;
image?: string;
ready_replicas?: number;
replicas?: number;
}
// 发布目标选择:SSH 关联主机 / K8s 关联 Deployment // Logan.Li
export function DeployTargetFields({ value, onChange, requireTarget = true }: DeployTargetFieldsProps) {
const [servers, setServers] = useState<ServerItem[]>([]);
const [clusters, setClusters] = useState<ClusterItem[]>([]);
const [deployments, setDeployments] = useState<DeploymentItem[]>([]);
const [serverSearch, setServerSearch] = useState('');
const [depSearch, setDepSearch] = useState('');
const [loadingServers, setLoadingServers] = useState(false);
const [loadingDeps, setLoadingDeps] = useState(false);
const loadServers = useCallback(async () => {
setLoadingServers(true);
try {
const res = await serverApi.getServers({ page_size: 200 });
const list = (res?.list ?? []) as ServerItem[];
setServers(list);
} catch {
setServers([]);
} finally {
setLoadingServers(false);
}
}, []);
const loadClusters = useCallback(async () => {
try {
const res = await kubernetesApi.getClusters();
setClusters((res?.list ?? []) as ClusterItem[]);
} catch {
setClusters([]);
}
}, []);
const loadDeployments = useCallback(async (clusterId: number | '') => {
if (!clusterId) {
setDeployments([]);
return;
}
const cluster = clusters.find((c) => c.id === clusterId);
if (!cluster?.code) {
setDeployments([]);
return;
}
setLoadingDeps(true);
try {
const res = await kubernetesApi.getAllDeployments(cluster.code);
const list = Array.isArray(res) ? res : [];
setDeployments(list as DeploymentItem[]);
} catch {
setDeployments([]);
} finally {
setLoadingDeps(false);
}
}, [clusters]);
useEffect(() => {
loadServers();
loadClusters();
}, [loadServers, loadClusters]);
useEffect(() => {
if (value.deployTarget === 'k8s' && value.k8sClusterId) {
loadDeployments(value.k8sClusterId);
}
}, [value.deployTarget, value.k8sClusterId, loadDeployments]);
const filteredServers = useMemo(() => {
const q = serverSearch.trim().toLowerCase();
if (!q) return servers;
return servers.filter(
(s) => s.hostname?.toLowerCase().includes(q) || s.ip?.toLowerCase().includes(q),
);
}, [servers, serverSearch]);
const filteredDeployments = useMemo(() => {
const q = depSearch.trim().toLowerCase();
if (!q) return deployments;
return deployments.filter(
(d) => d.name.toLowerCase().includes(q) || d.namespace.toLowerCase().includes(q),
);
}, [deployments, depSearch]);
const toggleServer = (id: number) => {
const next = value.serverIds.includes(id)
? value.serverIds.filter((x) => x !== id)
: [...value.serverIds, id];
onChange({ serverIds: next });
};
const selectDeployment = (dep: DeploymentItem) => {
onChange({
k8sNamespace: dep.namespace,
k8sDeployment: dep.name,
});
};
const selectedCluster = clusters.find((c) => c.id === value.k8sClusterId);
return (
<div className="space-y-3">
<div className="flex gap-1 p-1 rounded-lg bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)]">
{([
{ key: 'ssh' as const, label: '主机发布', icon: Server },
{ key: 'k8s' as const, label: 'Kubernetes 发布', icon: Network },
]).map((item) => {
const active = value.deployTarget === item.key;
const Icon = item.icon;
return (
<button
key={item.key}
type="button"
onClick={() => onChange({
deployTarget: item.key,
serverIds: item.key === 'ssh' ? value.serverIds : [],
deployRemotePath: item.key === 'ssh' ? value.deployRemotePath : '',
deployScript: item.key === 'ssh' ? value.deployScript : '',
k8sClusterId: item.key === 'k8s' ? value.k8sClusterId : '',
k8sNamespace: item.key === 'k8s' ? value.k8sNamespace : '',
k8sDeployment: item.key === 'k8s' ? value.k8sDeployment : '',
k8sContainerName: item.key === 'k8s' ? value.k8sContainerName : '',
})}
className={cn(
'flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-md text-xs font-medium transition-colors',
active
? 'bg-[var(--dg-bg-primary)] text-[var(--dg-text-primary)] border border-[var(--dg-border)] shadow-sm'
: 'text-[var(--dg-text-muted)] hover:text-[var(--dg-text-primary)]',
)}
>
<Icon className="h-3.5 w-3.5" />
{item.label}
</button>
);
})}
</div>
{value.deployTarget === 'ssh' ? (
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs">
关联主机
{requireTarget && <span className="text-[var(--dg-red)] ml-0.5">*</span>}
</Label>
{value.serverIds.length > 0 && (
<Badge variant="outline" className="text-[10px] border-[var(--dg-border)]">
已选 {value.serverIds.length} 台
</Badge>
)}
</div>
<div className="relative">
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--dg-text-muted)]" />
<Input
value={serverSearch}
onChange={(e) => setServerSearch(e.target.value)}
placeholder="搜索主机名或 IP"
className="pl-8 h-8 text-xs dg-input"
/>
</div>
<ScrollArea className="h-[140px] rounded-lg border border-[var(--dg-border)] bg-[var(--dg-bg-secondary)]">
{loadingServers ? (
<div className="flex items-center justify-center py-8 text-xs text-[var(--dg-text-muted)]">
<Loader2 className="h-4 w-4 animate-spin mr-1.5" />加载中
</div>
) : filteredServers.length === 0 ? (
<p className="text-xs text-[var(--dg-text-muted)] text-center py-8">暂无可用主机</p>
) : (
<div className="p-1.5 space-y-1">
{filteredServers.map((srv) => {
const selected = value.serverIds.includes(srv.id);
return (
<button
key={srv.id}
type="button"
onClick={() => toggleServer(srv.id)}
className={cn(
'w-full flex items-center gap-2 px-2.5 py-2 rounded-md text-left text-xs transition-colors',
selected
? 'bg-[var(--dg-bg-hover)] border border-[var(--dg-border)]'
: 'hover:bg-[var(--dg-bg-hover)]/60',
)}
>
<span className={cn(
'w-4 h-4 rounded border flex items-center justify-center shrink-0',
selected ? 'bg-[var(--dg-blue)] border-[var(--dg-blue)]' : 'border-[var(--dg-border)]',
)}>
{selected && <Check className="h-2.5 w-2.5 text-white" />}
</span>
<Server className="h-3.5 w-3.5 text-[var(--dg-text-muted)] shrink-0" />
<span className="font-medium text-[var(--dg-text-primary)] truncate">{srv.hostname}</span>
{srv.ip && <span className="text-[var(--dg-text-muted)] ml-auto shrink-0">{srv.ip}</span>}
</button>
);
})}
</div>
)}
</ScrollArea>
<p className="text-[10px] text-[var(--dg-text-muted)]">构建完成后 SCP 上传 jar/tar.gz 到远程目录并执行部署命令</p>
<div className="grid grid-cols-2 gap-2">
<div className="space-y-1">
<Label className="text-xs">远程目录</Label>
<Input
value={value.deployRemotePath}
onChange={(e) => onChange({ deployRemotePath: e.target.value })}
placeholder="/opt/apps/my-app"
className="h-8 text-xs font-mono dg-input"
/>
</div>
<div className="space-y-1">
<Label className="text-xs">部署命令</Label>
<Input
value={value.deployScript}
onChange={(e) => onChange({ deployScript: e.target.value })}
placeholder="./restart.sh"
className="h-8 text-xs font-mono dg-input"
/>
</div>
</div>
</div>
) : (
<div className="space-y-2">
<div className="grid grid-cols-2 gap-2">
<div className="space-y-1">
<Label className="text-xs">
Kubernetes 集群
{requireTarget && <span className="text-[var(--dg-red)] ml-0.5">*</span>}
</Label>
<Select
value={value.k8sClusterId ? String(value.k8sClusterId) : '__none'}
onValueChange={(v) => onChange({
k8sClusterId: v === '__none' ? '' : Number(v),
k8sNamespace: '',
k8sDeployment: '',
})}
>
<SelectTrigger className="h-8 text-xs dg-input">
<SelectValue placeholder="选择集群" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__none">请选择</SelectItem>
{clusters.map((c) => (
<SelectItem key={c.id} value={String(c.id)}>{c.name}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label className="text-xs">已选 Deployment</Label>
<Input
readOnly
value={value.k8sDeployment ? `${value.k8sNamespace}/${value.k8sDeployment}` : ''}
placeholder="从下方列表选择"
className="h-8 text-xs dg-input font-mono"
/>
</div>
</div>
{selectedCluster && (
<>
<div className="relative">
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--dg-text-muted)]" />
<Input
value={depSearch}
onChange={(e) => setDepSearch(e.target.value)}
placeholder="搜索 Deployment 或命名空间"
className="pl-8 h-8 text-xs dg-input"
/>
</div>
<ScrollArea className="h-[140px] rounded-lg border border-[var(--dg-border)] bg-[var(--dg-bg-secondary)]">
{loadingDeps ? (
<div className="flex items-center justify-center py-8 text-xs text-[var(--dg-text-muted)]">
<Loader2 className="h-4 w-4 animate-spin mr-1.5" />加载 Deployment
</div>
) : filteredDeployments.length === 0 ? (
<p className="text-xs text-[var(--dg-text-muted)] text-center py-8">暂无 Deployment</p>
) : (
<div className="p-1.5 space-y-1">
{filteredDeployments.map((dep) => {
const selected = value.k8sDeployment === dep.name && value.k8sNamespace === dep.namespace;
return (
<button
key={`${dep.namespace}/${dep.name}`}
type="button"
onClick={() => selectDeployment(dep)}
className={cn(
'w-full flex items-center gap-2 px-2.5 py-2 rounded-md text-left text-xs transition-colors',
selected
? 'bg-[var(--dg-bg-hover)] border border-[var(--dg-border)]'
: 'hover:bg-[var(--dg-bg-hover)]/60',
)}
>
<Network className="h-3.5 w-3.5 text-[var(--dg-text-muted)] shrink-0" />
<span className="font-mono text-[var(--dg-text-primary)] truncate">
{dep.namespace}/{dep.name}
</span>
<span className="text-[var(--dg-text-muted)] ml-auto shrink-0">
{dep.ready_replicas ?? 0}/{dep.replicas ?? 0}
</span>
</button>
);
})}
</div>
)}
</ScrollArea>
<div className="space-y-1">
<Label className="text-xs">容器名 <span className="text-[var(--dg-text-muted)]">(多容器时填写)</span></Label>
<Input
value={value.k8sContainerName}
onChange={(e) => onChange({ k8sContainerName: e.target.value })}
placeholder="默认首个容器"
className="h-8 text-xs font-mono dg-input"
/>
</div>
{value.k8sDeployment && selectedCluster && (
<p className="text-[10px] text-[var(--dg-text-muted)] leading-relaxed">
流水线部署将调用 CI 接口:
<code className="text-[var(--dg-text-secondary)] break-all">
POST {getPublicApiBase()}/kubernetes/{selectedCluster.code}/namespace/{value.k8sNamespace}/deployments/{value.k8sDeployment}/update-image
</code>
</p>
)}
</>
)}
</div>
)}
</div>
);
}
@@ -56,6 +56,14 @@ export function PipelineCard({
const registry = pipeline.registry as Record<string, unknown> | undefined;
const environment = pipeline.environment as Record<string, unknown> | undefined;
const code = (pipeline.code || pipeline.id) as string;
const deployTarget = String(pipeline.deploy_target || 'ssh');
let serverCount = 0;
try {
const ids = pipeline.server_ids ? JSON.parse(String(pipeline.server_ids)) : [];
serverCount = Array.isArray(ids) ? ids.length : 0;
} catch { /* ignore */ }
const k8sDep = pipeline.k8s_deployment ? String(pipeline.k8s_deployment) : '';
const k8sNs = pipeline.k8s_namespace ? String(pipeline.k8s_namespace) : '';
return (
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] overflow-hidden">
@@ -82,6 +90,11 @@ export function PipelineCard({
{pipeline.job_name && (
<Badge variant="secondary" className="text-xs font-mono opacity-60">{String(pipeline.job_name)}</Badge>
)}
{pipeline.build_node_id && (
<Badge variant="outline" className="text-[10px] gap-1">
<Server className="h-3 w-3" />指定节点
</Badge>
)}
</div>
<p className="text-xs text-[var(--dg-text-secondary)] mt-1 line-clamp-1">
{String(pipeline.description || '暂无描述')}
@@ -124,10 +137,16 @@ export function PipelineCard({
{pipeline.deploy_mode === 'tag' ? 'Tag发版' : String(pipeline.branch || 'main')}
</span>
<span className="flex items-center gap-1">
{(pipeline.deploy_target || 'ssh') === 'k8s' ? (
<><Network className="h-3 w-3" />Kubernetes</>
{deployTarget === 'k8s' ? (
<>
<Network className="h-3 w-3" />
{k8sDep ? `${k8sNs}/${k8sDep}` : 'Kubernetes Deployment'}
</>
) : (
<><Server className="h-3 w-3" />SSH 主机</>
<>
<Server className="h-3 w-3" />
{serverCount > 0 ? `${serverCount} 台主机` : 'SSH 主机'}
</>
)}
</span>
{repo && <span className="flex items-center gap-1"><Globe className="h-3 w-3" />{String(repo.name)}</span>}
@@ -180,8 +199,20 @@ export function PipelineCard({
const isSuccess = runStatus === 'success' || runStatus === 'completed';
const isRunning = runStatus === 'running' || runStatus === 'in_progress';
const isFailed = runStatus === 'failed' || runStatus === 'error';
const color = isFailed ? '#EF4444' : isRunning ? '#3B82F6' : isSuccess ? '#10B981' : '#6B7280';
const bgColor = isFailed ? '#EF444428' : isRunning ? '#3B82F628' : isSuccess ? '#10B98128' : '#6B728018';
const color = isFailed
? 'var(--dg-red)'
: isRunning
? 'var(--dg-blue)'
: isSuccess
? 'var(--dg-green)'
: 'var(--dg-text-muted)';
const bgColor = isFailed
? 'color-mix(in srgb, var(--dg-red) 12%, transparent)'
: isRunning
? 'color-mix(in srgb, var(--dg-blue) 12%, transparent)'
: isSuccess
? 'color-mix(in srgb, var(--dg-green) 12%, transparent)'
: 'var(--dg-bg-tertiary)';
const icon = isFailed ? (
<XCircle className="h-3 w-3" />
) : isRunning ? (
@@ -197,7 +228,7 @@ export function PipelineCard({
className="flex items-center gap-1.5 px-2.5 py-1.5 text-[11px] font-semibold border shadow-sm"
style={{
backgroundColor: bgColor,
borderColor: `${color}70`,
borderColor: 'var(--dg-border)',
color,
borderRadius: i === 0 ? '8px 0 0 8px' : i === stages.length - 1 ? '0 8px 8px 0' : '0',
}}
@@ -1,28 +1,36 @@
import { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import {
Rocket,
Plus,
GitBranch,
Tag,
Server,
Network,
Globe,
Container,
Loader2,
Trash2,
ChevronRight as ChevronRightSmall,
ChevronDown,
Settings2,
} from 'lucide-react';
import { credentialApi, deployApi, pipelineApi } from '@/api';
import { buildNodeApi, credentialApi, deployApi, pipelineApi, type BuildNode } from '@/api';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';
import { nameToCode } from '../pipeline-helpers';
import { STAGE_DEFS } from './constants';
import { DeployTargetFields, type DeployTargetValue } from './DeployTargetFields';
interface PipelineCreateDialogProps {
open: boolean;
@@ -30,45 +38,79 @@ interface PipelineCreateDialogProps {
onCreated: () => void;
}
// 新建流水线对话框(含表单状态) // Logan.Li
const PRESETS = [
{
key: 'ssh',
label: '主机发布',
desc: 'SCP 上传构建产物到关联主机',
stages: ['checkout', 'build', 'deploy'],
deployTarget: 'ssh' as const,
},
{
key: 'k8s',
label: 'Kubernetes 发布',
desc: '镜像打包后 CI 更新 Deployment',
stages: ['checkout', 'build', 'image', 'deploy'],
deployTarget: 'k8s' as const,
},
];
const DEFAULT_TARGET: DeployTargetValue = {
deployTarget: 'ssh',
serverIds: [],
deployRemotePath: '',
deployScript: '',
k8sClusterId: '',
k8sNamespace: '',
k8sDeployment: '',
k8sContainerName: '',
};
// 新建流水线对话框 — 精简分步 + 双发布目标 // Logan.Li
export function PipelineCreateDialog({ open, onOpenChange, onCreated }: PipelineCreateDialogProps) {
const { t } = useTranslation();
const [step, setStep] = useState<1 | 2>(1);
const [preset, setPreset] = useState('ssh');
const [newName, setNewName] = useState('');
const [newJobName, setNewJobName] = useState('');
const [newDesc, setNewDesc] = useState('');
const [newSource, setNewSource] = useState('');
const [newBranch, setNewBranch] = useState('main');
const [newDockerfile, setNewDockerfile] = useState('');
const [selectedStages, setSelectedStages] = useState<string[]>(['checkout', 'build', 'image', 'deploy']);
const [newDeployMode, setNewDeployMode] = useState('branch');
const [newDeployTarget, setNewDeployTarget] = useState('ssh');
const [selectedStages, setSelectedStages] = useState<string[]>(['checkout', 'build', 'deploy']);
const [deployTarget, setDeployTarget] = useState<DeployTargetValue>(DEFAULT_TARGET);
const [newEnvironmentId, setNewEnvironmentId] = useState<number | string>('');
const [saving, setSaving] = useState(false);
const [advancedOpen, setAdvancedOpen] = useState(false);
const [gitCredentials, setGitCredentials] = useState<Record<string, unknown>[]>([]);
const [dockerCredentials, setDockerCredentials] = useState<Record<string, unknown>[]>([]);
const [newGitCredentialId, setNewGitCredentialId] = useState<number | string>('');
const [newRegistryCredentialId, setNewRegistryCredentialId] = useState<number | string>('');
const [newJobName, setNewJobName] = useState('');
const [newTriggerMode, setNewTriggerMode] = useState('manual');
const [newWatchBranches, setNewWatchBranches] = useState('');
const [newExcludeBranch, setNewExcludeBranch] = useState('');
const [newCronExpr, setNewCronExpr] = useState('');
const [newWebhookToken, setNewWebhookToken] = useState('');
const [newEnvVars, setNewEnvVars] = useState<{ key: string; value: string; desc: string }[]>([]);
const [newCachePaths, setNewCachePaths] = useState('');
const [newMaxExecutors, setNewMaxExecutors] = useState(2);
const [newEnvVars, setNewEnvVars] = useState<{ key: string; value: string }[]>([]);
const [environments, setEnvironments] = useState<Record<string, unknown>[]>([]);
const [buildNodes, setBuildNodes] = useState<BuildNode[]>([]);
const [buildNodeId, setBuildNodeId] = useState('');
const loadRefs = useCallback(async () => {
try {
const [rEnv, rCred] = await Promise.all([
const [rEnv, rCred, rNodes] = await Promise.all([
deployApi.getEnvironments().catch(() => ({ list: [] })),
credentialApi.list({ page_size: 100 }).catch(() => ({ list: [] })),
buildNodeApi.list().catch(() => ({ list: [] })),
] as const);
setEnvironments(Array.isArray((rEnv as Record<string, unknown>)?.list) ? (rEnv as Record<string, unknown>).list as Record<string, unknown>[] : []);
setEnvironments(Array.isArray((rEnv as Record<string, unknown>)?.list)
? (rEnv as Record<string, unknown>).list as Record<string, unknown>[]
: []);
const allCreds: Record<string, unknown>[] = (rCred as Record<string, unknown>)?.list as Record<string, unknown>[] || [];
setGitCredentials(allCreds.filter((c) => c.secret_type === 'api'));
setDockerCredentials(allCreds.filter((c) => c.secret_type === 'docker'));
const nodeData = rNodes as { list?: BuildNode[] };
setBuildNodes(Array.isArray(nodeData?.list) ? nodeData.list.filter((n) => n.enabled) : []);
} catch { /* silent */ }
}, []);
@@ -76,33 +118,71 @@ export function PipelineCreateDialog({ open, onOpenChange, onCreated }: Pipeline
if (open) loadRefs();
}, [open, loadRefs]);
const applyPreset = (key: string) => {
const p = PRESETS.find((x) => x.key === key);
if (!p) return;
setPreset(key);
setSelectedStages(p.stages);
setDeployTarget({
...DEFAULT_TARGET,
deployTarget: p.deployTarget,
});
};
const resetForm = () => {
setStep(1);
setPreset('ssh');
setNewName('');
setNewJobName('');
setNewDesc('');
setNewSource('');
setNewBranch('main');
setNewDockerfile('');
setSelectedStages(['checkout', 'build', 'image', 'deploy']);
setNewDeployMode('branch');
setNewDeployTarget('ssh');
setSelectedStages(['checkout', 'build', 'deploy']);
setDeployTarget(DEFAULT_TARGET);
setNewEnvironmentId('');
setNewGitCredentialId('');
setNewRegistryCredentialId('');
setNewJobName('');
setNewTriggerMode('manual');
setNewWatchBranches('');
setNewExcludeBranch('');
setNewCronExpr('');
setNewWebhookToken('');
setNewEnvVars([]);
setNewCachePaths('');
setNewMaxExecutors(2);
setAdvancedOpen(false);
setBuildNodeId('');
};
const validateStep1 = () => {
if (!newName.trim()) {
toast.error('请输入流水线名称');
return false;
}
return true;
};
const validateStep2 = () => {
if (selectedStages.includes('checkout') && !newSource.trim()) {
toast.error(t('deploy.stage.checkoutNeedGit'));
return false;
}
if (selectedStages.includes('image') && !newRegistryCredentialId) {
toast.error(t('deploy.stage.imageNeedDocker'));
return false;
}
if (selectedStages.includes('deploy')) {
if (deployTarget.deployTarget === 'ssh' && deployTarget.serverIds.length === 0) {
toast.error('主机发布需至少关联一台主机');
return false;
}
if (deployTarget.deployTarget === 'k8s' && (!deployTarget.k8sClusterId || !deployTarget.k8sDeployment)) {
toast.error('Kubernetes 发布需选择集群与 Deployment');
return false;
}
}
return true;
};
const handleCreate = async () => {
if (!newName.trim()) { toast.error('请输入流水线名称'); return; }
if (selectedStages.includes('checkout') && !newSource.trim()) { toast.error('代码检出阶段需要填写 Git URL'); return; }
if (selectedStages.includes('image') && !newRegistryCredentialId) { toast.error('镜像打包阶段需要关联 Docker 凭证'); return; }
if (!validateStep1() || !validateStep2()) return;
setSaving(true);
try {
const stageNames = selectedStages.map((k) => STAGE_DEFS.find((s) => s.key === k)?.label || k);
@@ -122,381 +202,358 @@ export function PipelineCreateDialog({ open, onOpenChange, onCreated }: Pipeline
dockerfile: newDockerfile,
type: 'deploy',
stages,
deploy_mode: newDeployMode,
deploy_target: newDeployTarget,
deploy_mode: 'branch',
deploy_target: deployTarget.deployTarget,
server_ids: deployTarget.serverIds.length > 0 ? JSON.stringify(deployTarget.serverIds) : undefined,
deploy_remote_path: deployTarget.deployRemotePath || undefined,
deploy_script: deployTarget.deployScript || undefined,
k8s_cluster_id: deployTarget.k8sClusterId ? Number(deployTarget.k8sClusterId) : null,
k8s_namespace: deployTarget.k8sNamespace || undefined,
k8s_deployment: deployTarget.k8sDeployment || undefined,
k8s_container_name: deployTarget.k8sContainerName || undefined,
environment_id: newEnvironmentId ? Number(newEnvironmentId) : null,
repo_id: null,
registry_id: null,
git_credential_id: newGitCredentialId ? Number(newGitCredentialId) : null,
registry_credential_id: newRegistryCredentialId ? Number(newRegistryCredentialId) : null,
trigger_mode: newTriggerMode,
watch_branches: newWatchBranches || undefined,
exclude_branch: newExcludeBranch || undefined,
cron_expr: newCronExpr || undefined,
webhook_token: newWebhookToken || undefined,
variables: newEnvVars.length > 0 ? JSON.stringify(newEnvVars) : undefined,
cache_paths: newCachePaths || undefined,
max_executors: newMaxExecutors,
build_node_id: buildNodeId ? Number(buildNodeId) : null,
});
toast.success('流水线已创建');
toast.success(t('deploy.pipeline.created'));
onOpenChange(false);
resetForm();
onCreated();
} catch {
toast.error('创建失败');
toast.error(t('deploy.pipeline.createFailed'));
} finally {
setSaving(false);
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto bg-[var(--dg-bg-primary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2"><Rocket className="h-5 w-5" />新建流水线</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1">
<Label>名称 <span className="dg-text-red">*</span></Label>
<Input value={newName} onChange={(e) => setNewName(e.target.value)} placeholder="例如: demo-jar 后端部署" className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] h-9" />
</div>
<div className="space-y-1">
<Label>Job 名称 <span className="text-xs text-[var(--dg-text-secondary)]">(Webhook URL)</span></Label>
<Input value={newJobName} onChange={(e) => setNewJobName(e.target.value)} placeholder="cex-admin-server" className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] h-9 font-mono text-sm" />
{newJobName && <p className="text-[10px] text-[var(--dg-text-secondary)] opacity-60">Webhook: POST .../webhook/job/<b>{newJobName}</b></p>}
</div>
</div>
<div className="space-y-1">
<Label>描述</Label>
<Textarea value={newDesc} onChange={(e) => setNewDesc(e.target.value)} placeholder="流水线描述..." rows={2} className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]" />
</div>
const toggleStage = (key: string) => {
setSelectedStages((prev) => (
prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key]
));
};
<div className="grid grid-cols-3 gap-3">
<div className="space-y-1">
<Label>部署模式</Label>
<div className="flex gap-1 bg-[var(--dg-bg-secondary)] rounded-lg p-1 border border-[var(--dg-border)]">
{[
{ key: 'branch', label: '分支', icon: GitBranch },
{ key: 'tag', label: 'Tag 发版', icon: Tag },
].map((m) => {
const active = newDeployMode === m.key;
return (
<button
key={m.key}
onClick={() => setNewDeployMode(m.key)}
className={`flex-1 flex items-center justify-center gap-1 px-2 py-1.5 rounded-md text-xs font-medium transition-all ${
active ? 'bg-blue-500 text-white' : 'text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]'
}`}
>
<m.icon className="h-3.5 w-3.5" />{m.label}
</button>
);
})}
</div>
return (
<Dialog open={open} onOpenChange={(v) => { if (!v) resetForm(); onOpenChange(v); }}>
<DialogContent className="max-w-lg max-h-[88vh] overflow-y-auto bg-[var(--dg-bg-primary)] border-[var(--dg-border)]">
<DialogHeader>
<DialogTitle className="text-[var(--dg-text-primary)]">新建流水线</DialogTitle>
<DialogDescription className="text-[var(--dg-text-muted)]">
选择发布方式,关联主机或 Kubernetes Deployment,创建后可继续编辑阶段脚本
</DialogDescription>
</DialogHeader>
{/* 步骤指示 */}
<div className="flex items-center gap-2 text-xs">
<button
type="button"
onClick={() => setStep(1)}
className={cn(
'px-2.5 py-1 rounded-md transition-colors',
step === 1 ? 'bg-[var(--dg-bg-hover)] text-[var(--dg-text-primary)]' : 'text-[var(--dg-text-muted)]',
)}
>
1. 基础
</button>
<span className="text-[var(--dg-border)]">/</span>
<button
type="button"
onClick={() => { if (validateStep1()) setStep(2); }}
className={cn(
'px-2.5 py-1 rounded-md transition-colors',
step === 2 ? 'bg-[var(--dg-bg-hover)] text-[var(--dg-text-primary)]' : 'text-[var(--dg-text-muted)]',
)}
>
2. 代码与发布
</button>
</div>
{step === 1 ? (
<div className="space-y-4">
<div className="grid grid-cols-2 gap-2">
{PRESETS.map((p) => (
<button
key={p.key}
type="button"
onClick={() => applyPreset(p.key)}
className={cn(
'p-3 rounded-lg border text-left transition-colors',
preset === p.key
? 'border-[var(--dg-blue)] bg-[color-mix(in_srgb,var(--dg-blue)_8%,transparent)]'
: 'border-[var(--dg-border)] hover:bg-[var(--dg-bg-hover)]',
)}
>
<div className="text-sm font-medium text-[var(--dg-text-primary)]">{p.label}</div>
<div className="text-[11px] text-[var(--dg-text-muted)] mt-0.5">{p.desc}</div>
</button>
))}
</div>
<div className="space-y-1">
<Label>部署目标</Label>
<div className="flex gap-1 bg-[var(--dg-bg-secondary)] rounded-lg p-1 border border-[var(--dg-border)]">
{[
{ key: 'ssh', label: 'SSH 主机', icon: Server },
{ key: 'k8s', label: 'Kubernetes 集群', icon: Network },
].map((t) => {
const active = newDeployTarget === t.key;
return (
<button
key={t.key}
onClick={() => setNewDeployTarget(t.key)}
className={`flex-1 flex items-center justify-center gap-1 px-2 py-1.5 rounded-md text-xs font-medium transition-all ${
active ? 'bg-green-500 text-white' : 'text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]'
}`}
>
<t.icon className="h-3.5 w-3.5" />{t.label}
</button>
);
})}
</div>
<div className="space-y-1.5">
<Label className="text-xs">名称 <span className="text-[var(--dg-red)]">*</span></Label>
<Input
value={newName}
onChange={(e) => setNewName(e.target.value)}
placeholder="例如 demo-api"
className="h-9 dg-input"
/>
</div>
<div className="space-y-1">
<Label>环境分组</Label>
<Select value={String(newEnvironmentId)} onValueChange={(v) => setNewEnvironmentId(v === '__none' ? '' : v)}>
<SelectTrigger className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] h-9"><SelectValue placeholder="选择环境" /></SelectTrigger>
<div className="space-y-1.5">
<Label className="text-xs">描述</Label>
<Textarea
value={newDesc}
onChange={(e) => setNewDesc(e.target.value)}
placeholder="可选"
rows={2}
className="dg-input text-sm"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs">环境分组</Label>
<Select
value={String(newEnvironmentId)}
onValueChange={(v) => setNewEnvironmentId(v === '__none' ? '' : v)}
>
<SelectTrigger className="h-9 dg-input"><SelectValue placeholder="选择环境" /></SelectTrigger>
<SelectContent>
<SelectItem value="__none">不指定</SelectItem>
{environments.map((env) => (
<SelectItem key={env.id as number} value={String(env.id)}>
<span className="flex items-center gap-1.5">
<span className="w-2 h-2 rounded-full inline-block" style={{ backgroundColor: env.color as string }} />
{String(env.display_name)}
</span>
{String(env.display_name)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1">
<Label>Git URL {selectedStages.includes('checkout') && <span className="dg-text-red">*</span>}</Label>
<Input value={newSource} onChange={(e) => setNewSource(e.target.value)} placeholder="https://gitee.com/user/repo.git" className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] h-9 font-mono text-xs" />
</div>
<div className="space-y-1">
<Label>分支 / Tag</Label>
<Input value={newBranch} onChange={(e) => setNewBranch(e.target.value)} placeholder={newDeployMode === 'tag' ? 'v1.0.0' : 'main'} className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] h-9" />
</div>
<div className="space-y-1">
<Label>Git 凭证 <span className="text-xs text-[var(--dg-text-secondary)] opacity-60">(API Token)</span></Label>
<Select value={String(newGitCredentialId)} onValueChange={(v) => setNewGitCredentialId(v === '__none' ? '' : v)}>
<SelectTrigger className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] h-9"><SelectValue placeholder="选择凭证" /></SelectTrigger>
<SelectContent>
<SelectItem value="__none">不关联</SelectItem>
{gitCredentials.map((c) => (
<SelectItem key={c.id as number} value={String(c.id)}>
<span className="flex items-center gap-1.5">
<Globe className="h-3 w-3 opacity-60" />{String(c.name)} {c.summary && <span className="text-[10px] opacity-50">({String(c.summary)})</span>}
</span>
</SelectItem>
))}
</SelectContent>
</Select>
{!newGitCredentialId && selectedStages.includes('checkout') && <p className="text-xs dg-text-yellow">建议关联凭证</p>}
</div>
<div className="space-y-1">
<Label>镜像仓库凭证 {selectedStages.includes('image') && <span className="dg-text-red">*</span>}</Label>
<Select value={String(newRegistryCredentialId)} onValueChange={(v) => setNewRegistryCredentialId(v === '__none' ? '' : v)}>
<SelectTrigger className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] h-9"><SelectValue placeholder="选择 Docker 凭证" /></SelectTrigger>
<SelectContent>
<SelectItem value="__none">不关联</SelectItem>
{dockerCredentials.map((c) => (
<SelectItem key={c.id as number} value={String(c.id)}>
<span className="flex items-center gap-1.5">
<Container className="h-3 w-3 opacity-60" />{String(c.name)} {c.summary && <span className="text-[10px] opacity-50">({String(c.summary)})</span>}
</span>
</SelectItem>
))}
</SelectContent>
</Select>
{!newRegistryCredentialId && selectedStages.includes('image') && <p className="text-xs dg-text-yellow">需要关联 Docker 凭证</p>}
<div className="flex justify-end gap-2 pt-2">
<Button variant="outline" onClick={() => onOpenChange(false)}>取消</Button>
<Button onClick={() => { if (validateStep1()) setStep(2); }}>下一步</Button>
</div>
</div>
) : (
<div className="space-y-4">
<DeployTargetFields
value={deployTarget}
onChange={(patch) => setDeployTarget((prev) => ({ ...prev, ...patch }))}
requireTarget={selectedStages.includes('deploy')}
/>
{newRegistryCredentialId && newJobName && (
<div className="p-2.5 rounded-md bg-blue-500/5 border border-blue-500/20 text-xs text-[var(--dg-text-secondary)]">
<span className="dg-text-blue">镜像命名:</span>
<code className="text-[var(--dg-text-primary)]">{'{registry}'}/{'{namespace}'}/{'{'}{'{JOB_BASE_NAME}'}{'}'}:{'{'}{'{tag}'}{'}'}</code>
<span className="ml-2 opacity-60">例:</span>
<code className="opacity-60">harbor.ast1001.com/test/{newJobName}:latest</code>
<div className="grid grid-cols-2 gap-2">
<div className="space-y-1.5">
<Label className="text-xs">
Git 仓库 {selectedStages.includes('checkout') && <span className="text-[var(--dg-red)]">*</span>}
</Label>
<Input
value={newSource}
onChange={(e) => setNewSource(e.target.value)}
placeholder="https://gitee.com/user/repo.git"
className="h-8 text-xs font-mono dg-input"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs">分支</Label>
<Input value={newBranch} onChange={(e) => setNewBranch(e.target.value)} className="h-8 text-xs dg-input" />
</div>
</div>
)}
<div className="space-y-1">
<Label>Dockerfile 路径</Label>
<Input value={newDockerfile} onChange={(e) => setNewDockerfile(e.target.value)} placeholder="jar/Dockerfile" className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] h-9 font-mono text-xs" />
</div>
<div className="space-y-2">
<Label>发布流程 <span className="text-xs text-[var(--dg-text-secondary)] opacity-70 ml-1">按顺序选择阶段</span></Label>
<div className="flex flex-wrap gap-2">
{STAGE_DEFS.map((def) => {
const active = selectedStages.includes(def.key);
return (
<Badge
key={def.key}
className={`cursor-pointer transition-all text-xs px-3 py-1.5 ${active ? 'border-current' : 'border-[var(--dg-border)] opacity-50 hover:opacity-80'}`}
style={active ? { backgroundColor: `${def.color}20`, color: def.color, borderColor: def.color } : {}}
onClick={() => setSelectedStages(active ? selectedStages.filter((t) => t !== def.key) : [...selectedStages, def.key])}
title={def.desc}
>
<def.icon className="h-3 w-3 mr-1" />{def.label} {def.needs.includes('repo') ? '🔗' : ''}{def.needs.includes('registry') ? '📦' : ''}
</Badge>
);
})}
<div className="grid grid-cols-2 gap-2">
<div className="space-y-1.5">
<Label className="text-xs">Git 凭证</Label>
<Select value={String(newGitCredentialId)} onValueChange={(v) => setNewGitCredentialId(v === '__none' ? '' : v)}>
<SelectTrigger className="h-8 text-xs dg-input"><SelectValue placeholder="选择凭证" /></SelectTrigger>
<SelectContent>
<SelectItem value="__none">不关联</SelectItem>
{gitCredentials.map((c) => (
<SelectItem key={c.id as number} value={String(c.id)}>
<span className="flex items-center gap-1"><Globe className="h-3 w-3" />{String(c.name)}</span>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{selectedStages.includes('image') && (
<div className="space-y-1.5">
<Label className="text-xs">镜像凭证 <span className="text-[var(--dg-red)]">*</span></Label>
<Select value={String(newRegistryCredentialId)} onValueChange={(v) => setNewRegistryCredentialId(v === '__none' ? '' : v)}>
<SelectTrigger className="h-8 text-xs dg-input"><SelectValue placeholder="Docker 凭证" /></SelectTrigger>
<SelectContent>
<SelectItem value="__none">不关联</SelectItem>
{dockerCredentials.map((c) => (
<SelectItem key={c.id as number} value={String(c.id)}>
<span className="flex items-center gap-1"><Container className="h-3 w-3" />{String(c.name)}</span>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
</div>
{selectedStages.length > 0 && (
<div className="flex items-center mt-2">
{selectedStages.map((key, i) => {
const def = STAGE_DEFS.find((t) => t.key === key)!;
{deployTarget.deployTarget === 'k8s' && (
<div className="space-y-1.5">
<Label className="text-xs">Dockerfile 路径</Label>
<Input
value={newDockerfile}
onChange={(e) => setNewDockerfile(e.target.value)}
placeholder="Dockerfile"
className="h-8 text-xs font-mono dg-input"
/>
</div>
)}
<div className="space-y-1.5">
<Label className="text-xs">CI 阶段</Label>
<div className="flex flex-wrap gap-1.5">
{STAGE_DEFS.map((def) => {
const active = selectedStages.includes(def.key);
return (
<div key={i} className="flex items-center">
<div
className="flex items-center gap-1 px-2 py-1 text-[11px] font-medium border"
style={{
backgroundColor: `${def.color}20`,
borderColor: `${def.color}40`,
color: def.color,
borderRadius: i === 0 ? '6px 0 0 6px' : i === selectedStages.length - 1 ? '0 6px 6px 0' : '0',
}}
>
<def.icon className="h-3 w-3" />{def.label}
</div>
{i < selectedStages.length - 1 && (
<div className="flex items-center justify-center w-4 h-5 -mx-px z-10">
<ChevronRightSmall className="h-3 w-3" style={{ color: def.color }} />
</div>
)}
</div>
<Badge
key={def.key}
variant={active ? 'default' : 'outline'}
className={cn('cursor-pointer text-xs', !active && 'opacity-50')}
onClick={() => toggleStage(def.key)}
>
<def.icon className="h-3 w-3 mr-1" />
{def.label}
</Badge>
);
})}
</div>
)}
</div>
<div className="border-t border-[var(--dg-border)] pt-4">
<Label className="mb-2 block">触发方式</Label>
<div className="flex gap-1 bg-[var(--dg-bg-secondary)] rounded-lg p-1 border border-[var(--dg-border)]">
{[
{ key: 'manual', label: '手动', desc: '手动触发执行' },
{ key: 'git_push', label: '代码推送', desc: 'Git Push 自动触发' },
{ key: 'cron', label: '定时', desc: 'Cron 定时执行' },
{ key: 'webhook', label: 'Webhook', desc: '外部 Webhook 调用' },
].map((t) => {
const active = newTriggerMode === t.key;
return (
<button
key={t.key}
onClick={() => setNewTriggerMode(t.key)}
className={`flex-1 flex flex-col items-center gap-0.5 px-2 py-2 rounded-md text-xs font-medium transition-all ${
active ? 'bg-blue-500 text-white' : 'text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]'
}`}
title={t.desc}
>
{t.label}
</button>
);
})}
</div>
{newTriggerMode === 'git_push' && (
<div className="mt-3 space-y-2 p-3 rounded-md bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)]">
<div className="space-y-1">
<Label className="text-xs">监听分支 <span className="text-[var(--dg-text-secondary)] opacity-60">(逗号分隔,支持 * 通配)</span></Label>
<Input value={newWatchBranches} onChange={(e) => setNewWatchBranches(e.target.value)} placeholder="release/*, main" className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] h-8 font-mono text-xs" />
</div>
<div className="space-y-1">
<Label className="text-xs">排除分支 <span className="text-[var(--dg-text-secondary)] opacity-60">(不触发构建)</span></Label>
<Input value={newExcludeBranch} onChange={(e) => setNewExcludeBranch(e.target.value)} placeholder="wip/*, draft/*" className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] h-8 font-mono text-xs" />
</div>
</div>
)}
{newTriggerMode === 'cron' && (
<div className="mt-3 space-y-2 p-3 rounded-md bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)]">
<div className="space-y-1">
<Label className="text-xs">Cron 表达式 <span className="text-[var(--dg-text-secondary)] opacity-60">(标准 5 位)</span></Label>
<Input value={newCronExpr} onChange={(e) => setNewCronExpr(e.target.value)} placeholder="0 2 * * *" className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] h-8 font-mono text-xs" />
</div>
<div className="flex flex-wrap gap-1.5">
{[
{ expr: '*/5 * * * *', label: '每5分钟' },
{ expr: '0 * * * *', label: '每小时' },
{ expr: '0 2 * * *', label: '每天2点' },
{ expr: '0 0 * * 0', label: '每周日' },
].map((c) => (
<Badge key={c.expr} variant="outline" className="cursor-pointer text-[10px] hover:bg-blue-500/10" onClick={() => setNewCronExpr(c.expr)}>
{c.label}
</Badge>
))}
</div>
</div>
)}
{newTriggerMode === 'webhook' && (
<div className="mt-3 space-y-2 p-3 rounded-md bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)]">
<div className="space-y-1">
<Label className="text-xs">Webhook Token <span className="text-[var(--dg-text-secondary)] opacity-60">(签名验证,可选)</span></Label>
<Input value={newWebhookToken} onChange={(e) => setNewWebhookToken(e.target.value)} placeholder="随机字符串" className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] h-8 font-mono text-xs" />
</div>
<p className="text-[10px] text-[var(--dg-text-secondary)] opacity-60">
Webhook URL: <code className="text-[var(--dg-blue)]">POST /api/v1/webhook/pipeline/{'{code}'}</code>
{selectedStages.length > 0 && (
<p className="text-[10px] text-[var(--dg-text-muted)] flex items-center gap-1 flex-wrap">
<GitBranch className="h-3 w-3" />
{selectedStages.map((k) => STAGE_DEFS.find((d) => d.key === k)?.label || k).join(' → ')}
</p>
</div>
)}
</div>
<div className="border-t border-[var(--dg-border)] pt-4">
<div className="flex items-center justify-between mb-2">
<Label>环境变量 <span className="text-xs text-[var(--dg-text-secondary)] opacity-60">(${'{VAR_NAME}'} 引用)</span></Label>
<Button variant="ghost" size="sm" className="h-7 text-xs" onClick={() => setNewEnvVars([...newEnvVars, { key: '', value: '', desc: '' }])}>
<Plus className="h-3 w-3 mr-1" />添加变量
</Button>
)}
</div>
{newEnvVars.length === 0 ? (
<p className="text-xs text-[var(--dg-text-muted)] py-2">暂无变量,点击&quot;添加变量&quot;新增</p>
) : (
<div className="space-y-2">
{newEnvVars.map((v, i) => (
<div key={i} className="grid grid-cols-12 gap-2 items-start p-2 rounded-md bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)]">
<Input
value={v.key}
onChange={(e) => {
const nv = [...newEnvVars];
nv[i] = { ...nv[i], key: e.target.value };
setNewEnvVars(nv);
}}
placeholder="变量名"
className="col-span-3 h-8 text-xs font-mono bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]"
/>
<Input
value={v.value}
onChange={(e) => {
const nv = [...newEnvVars];
nv[i] = { ...nv[i], value: e.target.value };
setNewEnvVars(nv);
}}
placeholder="变量值"
className="col-span-4 h-8 text-xs font-mono bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]"
/>
<Input
value={v.desc}
onChange={(e) => {
const nv = [...newEnvVars];
nv[i] = { ...nv[i], desc: e.target.value };
setNewEnvVars(nv);
}}
placeholder="说明"
className="col-span-4 h-8 text-xs bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]"
/>
<Button variant="ghost" size="icon" className="col-span-1 h-8 w-8 dg-text-red" onClick={() => setNewEnvVars(newEnvVars.filter((_, idx) => idx !== i))}>
<Trash2 className="h-3.5 w-3.5" />
<Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>
<CollapsibleTrigger asChild>
<button
type="button"
className="flex items-center gap-1.5 text-xs text-[var(--dg-text-muted)] hover:text-[var(--dg-text-primary)]"
>
<Settings2 className="h-3.5 w-3.5" />
高级设置
<ChevronDown className={cn('h-3.5 w-3.5 transition-transform', advancedOpen && 'rotate-180')} />
</button>
</CollapsibleTrigger>
<CollapsibleContent className="mt-3 space-y-3 pt-3 border-t border-[var(--dg-border)]">
<div className="space-y-1.5">
<Label className="text-xs">构建节点</Label>
<Select value={buildNodeId || '__auto'} onValueChange={(v) => setBuildNodeId(v === '__auto' ? '' : v)}>
<SelectTrigger className="h-8 text-xs dg-input"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="__auto">自动调度(Master 优先)</SelectItem>
{buildNodes.map((n) => (
<SelectItem key={n.id} value={String(n.id)}>
{n.name} ({n.running_count || 0}/{n.max_executors})
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Job 名称 <span className="text-[var(--dg-text-muted)]">(Webhook)</span></Label>
<Input value={newJobName} onChange={(e) => setNewJobName(e.target.value)} className="h-8 text-xs font-mono dg-input" />
</div>
<div className="space-y-1.5">
<Label className="text-xs">触发方式</Label>
<Select value={newTriggerMode} onValueChange={setNewTriggerMode}>
<SelectTrigger className="h-8 text-xs dg-input"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="manual">手动</SelectItem>
<SelectItem value="git_push">代码推送</SelectItem>
<SelectItem value="cron">定时</SelectItem>
<SelectItem value="webhook">Webhook</SelectItem>
</SelectContent>
</Select>
</div>
{newTriggerMode === 'git_push' && (
<Input
value={newWatchBranches}
onChange={(e) => setNewWatchBranches(e.target.value)}
placeholder="监听分支,如 main, release/*"
className="h-8 text-xs font-mono dg-input"
/>
)}
{newTriggerMode === 'cron' && (
<Input
value={newCronExpr}
onChange={(e) => setNewCronExpr(e.target.value)}
placeholder="0 2 * * *"
className="h-8 text-xs font-mono dg-input"
/>
)}
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<Label className="text-xs">环境变量</Label>
<Button
type="button"
variant="ghost"
size="sm"
className="h-6 text-[10px]"
onClick={() => setNewEnvVars([...newEnvVars, { key: '', value: '' }])}
>
<Plus className="h-3 w-3 mr-0.5" />添加
</Button>
</div>
))}
{newEnvVars.map((v, i) => (
<div key={i} className="flex gap-1.5">
<Input
value={v.key}
onChange={(e) => {
const nv = [...newEnvVars];
nv[i] = { ...nv[i], key: e.target.value };
setNewEnvVars(nv);
}}
placeholder="KEY"
className="h-7 text-xs font-mono dg-input flex-1"
/>
<Input
value={v.value}
onChange={(e) => {
const nv = [...newEnvVars];
nv[i] = { ...nv[i], value: e.target.value };
setNewEnvVars(nv);
}}
placeholder="value"
className="h-7 text-xs font-mono dg-input flex-[2]"
/>
<Button
type="button"
variant="ghost"
size="icon"
className="h-7 w-7 shrink-0"
onClick={() => setNewEnvVars(newEnvVars.filter((_, idx) => idx !== i))}
>
<Trash2 className="h-3.5 w-3.5 text-[var(--dg-red)]" />
</Button>
</div>
))}
</div>
</CollapsibleContent>
</Collapsible>
<div className="flex justify-between gap-2 pt-2 border-t border-[var(--dg-border)]">
<Button variant="ghost" onClick={() => setStep(1)}>上一步</Button>
<div className="flex gap-2">
<Button variant="outline" onClick={() => onOpenChange(false)}>取消</Button>
<Button onClick={handleCreate} disabled={saving}>
{saving ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Rocket className="h-4 w-4 mr-1" />}
{saving ? '创建中' : '创建'}
</Button>
</div>
)}
</div>
<div className="border-t border-[var(--dg-border)] pt-4">
<Label className="mb-2 block">构建缓存 <span className="text-xs text-[var(--dg-text-secondary)] opacity-60">(加速后续构建)</span></Label>
<Input value={newCachePaths} onChange={(e) => setNewCachePaths(e.target.value)} placeholder="node_modules, .m2, target" className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] h-8 text-xs font-mono" />
<p className="text-[10px] text-[var(--dg-text-secondary)] opacity-50 mt-1">多个路径用逗号分隔,相同的 Key 会命中已有缓存</p>
</div>
<div className="border-t border-[var(--dg-border)] pt-4">
<Label className="mb-2 block">并发执行数 <span className="text-xs text-[var(--dg-text-secondary)] opacity-60">(Number of executors)</span></Label>
<div className="flex items-center gap-2">
<Select value={String(newMaxExecutors)} onValueChange={(v) => setNewMaxExecutors(Number(v))}>
<SelectTrigger className="w-32 h-8 text-xs bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="1">1 — 串行</SelectItem>
<SelectItem value="2">2</SelectItem>
<SelectItem value="3">3</SelectItem>
<SelectItem value="4">4</SelectItem>
<SelectItem value="5">5</SelectItem>
</SelectContent>
</Select>
</div>
<p className="text-[10px] text-[var(--dg-text-secondary)] opacity-50 mt-1">设为 1 则按顺序串行执行,默认 2 可并发构建</p>
</div>
</div>
<div className="flex justify-end gap-2 mt-4 pt-4 border-t border-[var(--dg-border)]">
<Button variant="outline" onClick={() => onOpenChange(false)}>取消</Button>
<Button onClick={handleCreate} disabled={saving}>
{saving ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Rocket className="h-4 w-4 mr-1" />}
{saving ? '创建中...' : '创建流水线'}
</Button>
</div>
)}
</DialogContent>
</Dialog>
);