plugin-workflow-ci 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/client-v2.js +1 -0
  2. package/client.js +1 -0
  3. package/dist/client/index.js +10 -0
  4. package/dist/client-v2/index.js +10 -0
  5. package/dist/externalVersion.js +21 -0
  6. package/dist/index.js +48 -0
  7. package/dist/locale/en-US.json +105 -0
  8. package/dist/locale/vi-VN.json +105 -0
  9. package/dist/locale/zh-CN.json +105 -0
  10. package/dist/server/actions/ci-manager.js +307 -0
  11. package/dist/server/collections/ci-gate-runs.js +85 -0
  12. package/dist/server/collections/ci-git-feedback-outbox.js +51 -0
  13. package/dist/server/collections/ci-pipelines.js +88 -0
  14. package/dist/server/index.js +62 -0
  15. package/dist/server/instructions/CiInstructions.js +180 -0
  16. package/dist/server/migrations/20261206000001-harden-workflow-ci-v020.js +91 -0
  17. package/dist/server/plugin.js +255 -0
  18. package/dist/server/services/AiTriageService.js +215 -0
  19. package/dist/server/services/CiGateWorkflowService.js +1776 -0
  20. package/dist/server/services/EphemeralContainerService.js +891 -0
  21. package/dist/server/services/GitFeedbackService.js +995 -0
  22. package/dist/server/services/constants-internal.js +65 -0
  23. package/dist/shared/collection-schemas.js +125 -0
  24. package/dist/shared/constants.js +120 -0
  25. package/dist/shared/runtime-context.js +67 -0
  26. package/dist/shared/types.js +24 -0
  27. package/dist/shared/ui/CiPipelinesSettingsView.js +700 -0
  28. package/package.json +58 -4
  29. package/server.js +1 -0
  30. package/src/client/index.tsx +10 -0
  31. package/src/client/locale.ts +31 -0
  32. package/src/client/plugin.tsx +62 -0
  33. package/src/client/workflow.tsx +119 -0
  34. package/src/client-v2/index.tsx +10 -0
  35. package/src/client-v2/locale.ts +32 -0
  36. package/src/client-v2/plugin.tsx +77 -0
  37. package/src/client-v2/workflow.tsx +124 -0
  38. package/src/index.ts +11 -0
  39. package/src/locale/en-US.json +105 -0
  40. package/src/locale/vi-VN.json +105 -0
  41. package/src/locale/zh-CN.json +105 -0
  42. package/src/server/actions/ci-manager.ts +377 -0
  43. package/src/server/collections/ci-gate-runs.ts +65 -0
  44. package/src/server/collections/ci-git-feedback-outbox.ts +31 -0
  45. package/src/server/collections/ci-pipelines.ts +68 -0
  46. package/src/server/index.ts +17 -0
  47. package/src/server/instructions/CiInstructions.ts +180 -0
  48. package/src/server/migrations/20261206000001-harden-workflow-ci-v020.ts +78 -0
  49. package/src/server/plugin.ts +274 -0
  50. package/src/server/services/AiTriageService.ts +254 -0
  51. package/src/server/services/CiGateWorkflowService.ts +2310 -0
  52. package/src/server/services/EphemeralContainerService.ts +1170 -0
  53. package/src/server/services/GitFeedbackService.ts +1224 -0
  54. package/src/server/services/constants-internal.ts +27 -0
  55. package/src/shared/collection-schemas.ts +98 -0
  56. package/src/shared/constants.ts +50 -0
  57. package/src/shared/runtime-context.tsx +55 -0
  58. package/src/shared/types.ts +203 -0
  59. package/src/shared/ui/CiPipelinesSettingsView.tsx +1035 -0
  60. package/README.md +0 -3
@@ -0,0 +1,1035 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import {
11
+ BranchesOutlined,
12
+ CheckCircleOutlined,
13
+ CloseCircleOutlined,
14
+ CloudUploadOutlined,
15
+ DeleteOutlined,
16
+ EditOutlined,
17
+ ExclamationCircleOutlined,
18
+ FileTextOutlined,
19
+ PlayCircleOutlined,
20
+ PlusOutlined,
21
+ ReloadOutlined,
22
+ RobotOutlined,
23
+ RollbackOutlined,
24
+ SafetyCertificateOutlined,
25
+ StopOutlined,
26
+ SyncOutlined,
27
+ } from '@ant-design/icons';
28
+ import {
29
+ Alert,
30
+ Button,
31
+ Card,
32
+ Descriptions,
33
+ Drawer,
34
+ Empty,
35
+ Flex,
36
+ Form,
37
+ Input,
38
+ InputNumber,
39
+ Modal,
40
+ Popconfirm,
41
+ Select,
42
+ Space,
43
+ Switch,
44
+ Table,
45
+ Tabs,
46
+ Tag,
47
+ Typography,
48
+ message,
49
+ } from 'antd';
50
+ import type { ColumnsType } from 'antd/es/table';
51
+ import React, { useCallback, useEffect, useMemo, useState } from 'react';
52
+ import { CI_MANAGER_RESOURCE, CI_PIPELINES_COLLECTION } from '../constants';
53
+ import { useWorkflowCiRuntime } from '../runtime-context';
54
+ import type { CiApprovalState, CiDeployOutcome, CiGateRunRecord, CiGateRunState, CiPipelineRecord } from '../types';
55
+
56
+ interface CiMetaPayload {
57
+ tenants: Array<{ id: number; key: string; name: string }>;
58
+ gitRepos: Array<{ id: number; name: string }>;
59
+ portainerInstances: Array<{ id: number; name: string }>;
60
+ portainerPipelines: Array<{ id: number; name: string; deployEnabled?: boolean }>;
61
+ agentLoopPatterns: Array<{ id: number; key: string; name: string }>;
62
+ users: Array<{ id: number; username: string; nickname: string }>;
63
+ }
64
+
65
+ function unwrapBody<T>(resp: { data: { data?: T } | T }): T {
66
+ const outer = resp.data;
67
+ if (outer && typeof outer === 'object' && 'data' in outer && outer.data !== undefined) {
68
+ return outer.data as T;
69
+ }
70
+ return outer as T;
71
+ }
72
+
73
+ function renderGateStateTag(state: CiGateRunState | string): React.ReactNode {
74
+ switch (state) {
75
+ case 'succeeded':
76
+ return (
77
+ <Tag color="success" icon={<CheckCircleOutlined />}>
78
+ SUCCEEDED
79
+ </Tag>
80
+ );
81
+ case 'waiting_approval':
82
+ return <Tag color="warning">WAITING BASELINE APPROVAL</Tag>;
83
+ case 'failed':
84
+ return (
85
+ <Tag color="error" icon={<CloseCircleOutlined />}>
86
+ FAILED / BLOCKED
87
+ </Tag>
88
+ );
89
+ case 'canceled':
90
+ return <Tag>CANCELED</Tag>;
91
+ case 'queued':
92
+ return <Tag>QUEUED</Tag>;
93
+ default:
94
+ return (
95
+ <Tag color="processing" icon={<SyncOutlined spin />}>
96
+ {String(state).toUpperCase()}
97
+ </Tag>
98
+ );
99
+ }
100
+ }
101
+
102
+ function renderVerdictAxisTag(verdict?: string | null, reasonCode?: string | null): React.ReactNode {
103
+ if (!verdict) return <Tag>—</Tag>;
104
+ const color =
105
+ verdict === 'passed'
106
+ ? 'success'
107
+ : verdict === 'diff_mismatch'
108
+ ? 'warning'
109
+ : verdict === 'canceled'
110
+ ? 'default'
111
+ : 'error';
112
+ return (
113
+ <Space size={4} wrap>
114
+ <Tag color={color}>{verdict.toUpperCase()}</Tag>
115
+ {reasonCode && reasonCode !== 'ALL_REQUIRED_PASSED' ? <Tag>{reasonCode}</Tag> : null}
116
+ </Space>
117
+ );
118
+ }
119
+
120
+ function renderApprovalAxisTag(state?: CiApprovalState | string | null): React.ReactNode {
121
+ const s = state || 'not_required';
122
+ switch (s) {
123
+ case 'approved':
124
+ return <Tag color="success">QA APPROVED</Tag>;
125
+ case 'pending':
126
+ return <Tag color="warning">PENDING QA</Tag>;
127
+ case 'invalidated':
128
+ return <Tag color="volcano">INVALIDATED</Tag>;
129
+ case 'rejected':
130
+ return <Tag color="error">REJECTED</Tag>;
131
+ default:
132
+ return <Tag>NOT REQUIRED</Tag>;
133
+ }
134
+ }
135
+
136
+ function renderDeployAxisTag(outcome?: CiDeployOutcome | string | null): React.ReactNode {
137
+ const o = outcome || 'not_applicable';
138
+ switch (o) {
139
+ case 'deployed':
140
+ return (
141
+ <Tag color="success" icon={<CheckCircleOutlined />}>
142
+ DEPLOYED
143
+ </Tag>
144
+ );
145
+ case 'rolled_back':
146
+ return (
147
+ <Tag color="orange" icon={<RollbackOutlined />}>
148
+ ROLLED BACK
149
+ </Tag>
150
+ );
151
+ case 'ops_intervention_required':
152
+ return (
153
+ <Tag color="red" icon={<StopOutlined />}>
154
+ OPS INTERVENTION
155
+ </Tag>
156
+ );
157
+ case 'blocked':
158
+ return <Tag color="error">BLOCKED</Tag>;
159
+ case 'failed':
160
+ return <Tag color="error">DEPLOY FAILED</Tag>;
161
+ case 'pending':
162
+ return (
163
+ <Tag color="processing" icon={<SyncOutlined spin />}>
164
+ PENDING
165
+ </Tag>
166
+ );
167
+ default:
168
+ return <Tag>N/A</Tag>;
169
+ }
170
+ }
171
+
172
+ export interface CiPipelinesSettingsViewProps {
173
+ section?: 'all' | 'pipelines' | 'runs';
174
+ }
175
+
176
+ export const CiPipelinesSettingsView: React.FC<CiPipelinesSettingsViewProps> = ({ section = 'all' }) => {
177
+ const { api, t } = useWorkflowCiRuntime();
178
+ const [pipelines, setPipelines] = useState<CiPipelineRecord[]>([]);
179
+ const [gateRuns, setGateRuns] = useState<CiGateRunRecord[]>([]);
180
+ const [meta, setMeta] = useState<CiMetaPayload>({
181
+ tenants: [],
182
+ gitRepos: [],
183
+ portainerInstances: [],
184
+ portainerPipelines: [],
185
+ agentLoopPatterns: [],
186
+ users: [],
187
+ });
188
+ const [loading, setLoading] = useState(false);
189
+ const [busyKey, setBusyKey] = useState<string | null>(null);
190
+
191
+ const [modalOpen, setModalOpen] = useState(false);
192
+ const [editingPipeline, setEditingPipeline] = useState<CiPipelineRecord | null>(null);
193
+ const [pipelineForm] = Form.useForm();
194
+
195
+ const [selectedRun, setSelectedRun] = useState<CiGateRunRecord | null>(null);
196
+
197
+ const loadAll = useCallback(async () => {
198
+ setLoading(true);
199
+ try {
200
+ const [pipeResp, runsResp, metaResp] = await Promise.all([
201
+ api.request<{ data?: CiPipelineRecord[] }>({
202
+ url: `${CI_PIPELINES_COLLECTION}:list`,
203
+ method: 'get',
204
+ params: { sort: ['id'], pageSize: 100 },
205
+ }),
206
+ api.request<{ data?: CiGateRunRecord[] }>({
207
+ url: `${CI_MANAGER_RESOURCE}:listGateRuns`,
208
+ method: 'get',
209
+ params: { limit: 30 },
210
+ }),
211
+ api
212
+ .request<{ data?: CiMetaPayload }>({
213
+ url: `${CI_MANAGER_RESOURCE}:listMeta`,
214
+ method: 'get',
215
+ })
216
+ .catch(() => ({
217
+ data: {
218
+ data: {
219
+ tenants: [],
220
+ gitRepos: [],
221
+ portainerInstances: [],
222
+ portainerPipelines: [],
223
+ agentLoopPatterns: [],
224
+ users: [],
225
+ },
226
+ },
227
+ })),
228
+ ]);
229
+ const parsedPipes = unwrapBody<CiPipelineRecord[]>(pipeResp);
230
+ const parsedRuns = unwrapBody<CiGateRunRecord[]>(runsResp);
231
+ setPipelines(Array.isArray(parsedPipes) ? parsedPipes : []);
232
+ setGateRuns(Array.isArray(parsedRuns) ? parsedRuns : []);
233
+ const parsedMeta = unwrapBody<Partial<CiMetaPayload>>(metaResp);
234
+ if (parsedMeta && typeof parsedMeta === 'object') {
235
+ setMeta({
236
+ tenants: Array.isArray(parsedMeta.tenants) ? parsedMeta.tenants : [],
237
+ gitRepos: Array.isArray(parsedMeta.gitRepos) ? parsedMeta.gitRepos : [],
238
+ portainerInstances: Array.isArray(parsedMeta.portainerInstances) ? parsedMeta.portainerInstances : [],
239
+ portainerPipelines: Array.isArray(parsedMeta.portainerPipelines) ? parsedMeta.portainerPipelines : [],
240
+ agentLoopPatterns: Array.isArray(parsedMeta.agentLoopPatterns) ? parsedMeta.agentLoopPatterns : [],
241
+ users: Array.isArray(parsedMeta.users) ? parsedMeta.users : [],
242
+ });
243
+ }
244
+ } catch (error) {
245
+ message.error(error instanceof Error ? error.message : String(error));
246
+ } finally {
247
+ setLoading(false);
248
+ }
249
+ }, [api]);
250
+
251
+ useEffect(() => {
252
+ loadAll().catch(() => undefined);
253
+ }, [loadAll]);
254
+
255
+ const opsSummary = useMemo(() => {
256
+ const haltedPipelines = pipelines.filter((p) => Boolean(p.promotionHalted));
257
+ const pendingApprovals = gateRuns.filter((r) => r.state === 'waiting_approval' || r.approvalState === 'pending');
258
+ const retryingGit = gateRuns.filter((r) => r.gitFeedbackSyncState === 'retrying');
259
+ const pendingCleanups = gateRuns.filter(
260
+ (r) =>
261
+ Boolean(r.ephemeralContainerId) &&
262
+ (r.state === 'succeeded' || r.state === 'failed' || r.state === 'canceled' || r.state === 'waiting_approval'),
263
+ );
264
+ return {
265
+ haltedPipelines,
266
+ pendingApprovalsCount: pendingApprovals.length,
267
+ retryingGitCount: retryingGit.length,
268
+ pendingCleanupsCount: pendingCleanups.length,
269
+ };
270
+ }, [gateRuns, pipelines]);
271
+
272
+ const openCreateModal = () => {
273
+ setEditingPipeline(null);
274
+ pipelineForm.resetFields();
275
+ pipelineForm.setFieldsValue({
276
+ enabled: true,
277
+ branchPattern: '*',
278
+ protectedBranchesText: 'main, master, release/*',
279
+ triggerOnPush: true,
280
+ triggerOnMergeRequest: true,
281
+ pollMergeRequests: false,
282
+ runnerBackend: 'external_ci',
283
+ runnerTimeoutMs: 300000,
284
+ publishCommitStatus: true,
285
+ statusContext: 'nocobase/ci-test-manager',
286
+ publishPrComment: true,
287
+ enrichGitReview: true,
288
+ deployGateMode: 'none',
289
+ dbBackwardCompatible: true,
290
+ enableAiTriage: true,
291
+ smokeOnClusterHotReload: false,
292
+ });
293
+ setModalOpen(true);
294
+ };
295
+
296
+ const openEditModal = (record: CiPipelineRecord) => {
297
+ setEditingPipeline(record);
298
+ pipelineForm.setFieldsValue({
299
+ ...record,
300
+ protectedBranchesText: Array.isArray(record.protectedBranches) ? record.protectedBranches.join(', ') : '',
301
+ qaAppServicesText: Array.isArray(record.qaAppServices) ? record.qaAppServices.join(', ') : '',
302
+ runnerEnvJson: record.runnerEnv ? JSON.stringify(record.runnerEnv, null, 2) : '',
303
+ });
304
+ setModalOpen(true);
305
+ };
306
+
307
+ const handleSavePipeline = async () => {
308
+ try {
309
+ const raw = (await pipelineForm.validateFields()) as Record<string, unknown>;
310
+ const envJson = String(raw.runnerEnvJson ?? '').trim();
311
+ let runnerEnv: Record<string, string> | null = null;
312
+ if (envJson) {
313
+ runnerEnv = JSON.parse(envJson) as Record<string, string>;
314
+ }
315
+ const protectedBranchesText = String(raw.protectedBranchesText ?? '').trim();
316
+ const protectedBranches = protectedBranchesText
317
+ ? protectedBranchesText
318
+ .split(',')
319
+ .map((s) => s.trim())
320
+ .filter(Boolean)
321
+ : null;
322
+ const qaAppServicesText = String(raw.qaAppServicesText ?? '').trim();
323
+ const qaAppServices = qaAppServicesText
324
+ ? qaAppServicesText
325
+ .split(',')
326
+ .map((s) => s.trim())
327
+ .filter(Boolean)
328
+ : null;
329
+
330
+ const payload: Record<string, unknown> = {
331
+ ...raw,
332
+ runnerEnv,
333
+ protectedBranches,
334
+ qaAppServices,
335
+ };
336
+ delete payload.runnerEnvJson;
337
+ delete payload.protectedBranchesText;
338
+ delete payload.qaAppServicesText;
339
+
340
+ if (editingPipeline) {
341
+ await api.request({
342
+ url: `${CI_PIPELINES_COLLECTION}:update`,
343
+ method: 'post',
344
+ params: { filterByTk: editingPipeline.id },
345
+ data: payload,
346
+ });
347
+ } else {
348
+ await api.request({
349
+ url: `${CI_PIPELINES_COLLECTION}:create`,
350
+ method: 'post',
351
+ data: payload,
352
+ });
353
+ }
354
+ message.success(t('CI Pipeline saved successfully'));
355
+ setModalOpen(false);
356
+ await loadAll();
357
+ } catch (error) {
358
+ message.error(error instanceof Error ? error.message : String(error));
359
+ }
360
+ };
361
+
362
+ const handleDeletePipeline = async (id: number) => {
363
+ try {
364
+ await api.request({
365
+ url: `${CI_PIPELINES_COLLECTION}:destroy`,
366
+ method: 'post',
367
+ params: { filterByTk: id },
368
+ });
369
+ await loadAll();
370
+ } catch (error) {
371
+ message.error(error instanceof Error ? error.message : String(error));
372
+ }
373
+ };
374
+
375
+ const handleClearPromotionHalt = async (pipelineId: number) => {
376
+ setBusyKey(`halt-${pipelineId}`);
377
+ try {
378
+ await api.request({
379
+ url: `${CI_MANAGER_RESOURCE}:clearPromotionHalt`,
380
+ method: 'post',
381
+ data: { pipelineId },
382
+ });
383
+ message.success(t('Cleared promotion halt on pipeline'));
384
+ await loadAll();
385
+ } catch (error) {
386
+ message.error(error instanceof Error ? error.message : String(error));
387
+ } finally {
388
+ setBusyKey(null);
389
+ }
390
+ };
391
+
392
+ const handleTriggerManual = async (pipeline: CiPipelineRecord) => {
393
+ setBusyKey(`run-${pipeline.id}`);
394
+ try {
395
+ await api.request({
396
+ url: `${CI_MANAGER_RESOURCE}:triggerGate`,
397
+ method: 'post',
398
+ data: { pipelineId: pipeline.id, eventType: 'manual', branch: 'main' },
399
+ });
400
+ message.success(t('CI Gate run queued via workflow'));
401
+ await loadAll();
402
+ } catch (error) {
403
+ message.error(error instanceof Error ? error.message : String(error));
404
+ } finally {
405
+ setBusyKey(null);
406
+ }
407
+ };
408
+
409
+ const handlePollMrsNow = async () => {
410
+ setBusyKey('poll-mr');
411
+ try {
412
+ await api.request({
413
+ url: `${CI_MANAGER_RESOURCE}:pollNow`,
414
+ method: 'post',
415
+ });
416
+ message.success(t('Polled open Merge Requests for CI changes'));
417
+ await loadAll();
418
+ } catch (error) {
419
+ message.error(error instanceof Error ? error.message : String(error));
420
+ } finally {
421
+ setBusyKey(null);
422
+ }
423
+ };
424
+
425
+ const handleApproveAndPromote = async (gateRunId: number) => {
426
+ setBusyKey(`approve-${gateRunId}`);
427
+ try {
428
+ await api.request({
429
+ url: `${CI_MANAGER_RESOURCE}:approveDiffAndPromote`,
430
+ method: 'post',
431
+ data: { gateRunId },
432
+ });
433
+ message.success(t('Approved dataset baselines and promoted deployment'));
434
+ await loadAll();
435
+ } catch (error) {
436
+ message.error(error instanceof Error ? error.message : String(error));
437
+ } finally {
438
+ setBusyKey(null);
439
+ }
440
+ };
441
+
442
+ const handleRefreshClick = () => {
443
+ loadAll().catch(() => undefined);
444
+ };
445
+
446
+ const pipelineColumns: ColumnsType<CiPipelineRecord> = [
447
+ {
448
+ title: t('Pipeline'),
449
+ key: 'name',
450
+ render: (_, row) => (
451
+ <Space direction="vertical" size={2}>
452
+ <Space size={6} wrap>
453
+ <Typography.Text strong>{row.name}</Typography.Text>
454
+ <Tag color={row.enabled ? 'blue' : 'default'}>{row.key}</Tag>
455
+ {row.promotionHalted ? (
456
+ <Tag color="red" icon={<StopOutlined />}>
457
+ {t('PROMOTION HALTED')}
458
+ </Tag>
459
+ ) : null}
460
+ </Space>
461
+ <Typography.Text
462
+ type="secondary"
463
+ copyable={{ text: `/api/${CI_MANAGER_RESOURCE}:webhook?pipelineKey=${row.key}` }}
464
+ >
465
+ {`/api/${CI_MANAGER_RESOURCE}:webhook?pipelineKey=${row.key}`}
466
+ </Typography.Text>
467
+ </Space>
468
+ ),
469
+ },
470
+ {
471
+ title: t('Runner Backend'),
472
+ dataIndex: 'runnerBackend',
473
+ width: 190,
474
+ render: (val: string, row) => (
475
+ <Space direction="vertical" size={2}>
476
+ <Tag color="geekblue">{val}</Tag>
477
+ {row.qaStackId ? <Tag color="cyan">{`QA Stack #${row.qaStackId}`}</Tag> : null}
478
+ </Space>
479
+ ),
480
+ },
481
+ {
482
+ title: t('Deploy Gate'),
483
+ dataIndex: 'deployGateMode',
484
+ width: 200,
485
+ render: (mode: string, row) => (
486
+ <Space direction="vertical" size={2}>
487
+ <Tag color={mode === 'none' ? 'default' : 'purple'} icon={<SafetyCertificateOutlined />}>
488
+ {mode}
489
+ </Tag>
490
+ {Array.isArray(row.gateApproverIds) && row.gateApproverIds.length > 0 ? (
491
+ <Typography.Text type="secondary" style={{ fontSize: 12 }}>
492
+ {`${t('Approvers')}: ${row.gateApproverIds.length}`}
493
+ </Typography.Text>
494
+ ) : null}
495
+ </Space>
496
+ ),
497
+ },
498
+ {
499
+ title: t('AI & Git Features'),
500
+ key: 'features',
501
+ render: (_, row) => (
502
+ <Space size={4} wrap>
503
+ {row.publishCommitStatus ? <Tag color="cyan">Commit Status</Tag> : null}
504
+ {row.publishPrComment ? <Tag color="cyan">Sticky PR Comment</Tag> : null}
505
+ {row.enableAiTriage ? (
506
+ <Tag color="gold" icon={<RobotOutlined />}>
507
+ AI Triage
508
+ </Tag>
509
+ ) : null}
510
+ {row.smokeOnClusterHotReload ? <Tag color="green">Hot-Reload Smoke</Tag> : null}
511
+ </Space>
512
+ ),
513
+ },
514
+ {
515
+ title: t('Actions'),
516
+ key: 'actions',
517
+ width: 280,
518
+ render: (_, row) => (
519
+ <Space size={6} wrap>
520
+ {row.promotionHalted ? (
521
+ <Button
522
+ size="small"
523
+ danger
524
+ loading={busyKey === `halt-${row.id}`}
525
+ onClick={() => {
526
+ handleClearPromotionHalt(row.id).catch(() => undefined);
527
+ }}
528
+ >
529
+ {t('Clear Halt')}
530
+ </Button>
531
+ ) : null}
532
+ <Button
533
+ size="small"
534
+ type="primary"
535
+ icon={<PlayCircleOutlined />}
536
+ loading={busyKey === `run-${row.id}`}
537
+ onClick={() => {
538
+ handleTriggerManual(row).catch(() => undefined);
539
+ }}
540
+ >
541
+ {t('Run CI')}
542
+ </Button>
543
+ <Button size="small" icon={<EditOutlined />} aria-label={t('Edit')} onClick={() => openEditModal(row)} />
544
+ <Popconfirm
545
+ title={t('Delete this CI pipeline?')}
546
+ onConfirm={() => {
547
+ handleDeletePipeline(row.id).catch(() => undefined);
548
+ }}
549
+ >
550
+ <Button size="small" danger icon={<DeleteOutlined />} aria-label={t('Delete')} />
551
+ </Popconfirm>
552
+ </Space>
553
+ ),
554
+ },
555
+ ];
556
+
557
+ const runColumns: ColumnsType<CiGateRunRecord> = [
558
+ {
559
+ title: '#',
560
+ dataIndex: 'id',
561
+ width: 65,
562
+ render: (id: number) => `#${id}`,
563
+ },
564
+ {
565
+ title: t('Event & Branch'),
566
+ key: 'branch',
567
+ render: (_, row) => (
568
+ <Space size={4} wrap>
569
+ <Tag>{row.eventType}</Tag>
570
+ <BranchesOutlined />
571
+ <Typography.Text code>{row.branch}</Typography.Text>
572
+ {row.mrIid ? <Tag color="purple">!{row.mrIid}</Tag> : null}
573
+ <Typography.Text type="secondary">{row.commitSha.slice(0, 8)}</Typography.Text>
574
+ {row.buildRunId ? <Tag color="blue">{`Build #${row.buildRunId}`}</Tag> : null}
575
+ </Space>
576
+ ),
577
+ },
578
+ {
579
+ title: t('Test Verdict'),
580
+ key: 'testVerdict',
581
+ width: 190,
582
+ render: (_, row) => (
583
+ <Space size={4} wrap>
584
+ {row.testRunId ? <Typography.Text code>#{row.testRunId}</Typography.Text> : null}
585
+ {renderVerdictAxisTag(row.testVerdict, row.verdictReasonCode)}
586
+ </Space>
587
+ ),
588
+ },
589
+ {
590
+ title: t('Approval Decision'),
591
+ dataIndex: 'approvalState',
592
+ width: 145,
593
+ render: (st: CiApprovalState | undefined) => renderApprovalAxisTag(st),
594
+ },
595
+ {
596
+ title: t('Deploy Outcome'),
597
+ dataIndex: 'deployOutcome',
598
+ width: 165,
599
+ render: (outcome: CiDeployOutcome | undefined) => renderDeployAxisTag(outcome),
600
+ },
601
+ {
602
+ title: t('Gate State'),
603
+ dataIndex: 'state',
604
+ width: 185,
605
+ render: (st: CiGateRunState) => renderGateStateTag(st),
606
+ },
607
+ {
608
+ title: t('Actions'),
609
+ key: 'actions',
610
+ width: 240,
611
+ render: (_, row) => (
612
+ <Space size={6} wrap>
613
+ {row.state === 'waiting_approval' && row.approvalState === 'pending' ? (
614
+ <Button
615
+ size="small"
616
+ type="primary"
617
+ icon={<CloudUploadOutlined />}
618
+ loading={busyKey === `approve-${row.id}`}
619
+ onClick={() => {
620
+ handleApproveAndPromote(row.id).catch(() => undefined);
621
+ }}
622
+ >
623
+ {t('Approve & Promote')}
624
+ </Button>
625
+ ) : null}
626
+ <Button size="small" icon={<FileTextOutlined />} onClick={() => setSelectedRun(row)}>
627
+ {t('Logs & Triage')}
628
+ </Button>
629
+ </Space>
630
+ ),
631
+ },
632
+ ];
633
+
634
+ const renderOperationalAlerts = () => (
635
+ <Space direction="vertical" size={8} style={{ width: '100%', marginBottom: 12 }}>
636
+ {opsSummary.haltedPipelines.map((hp) => (
637
+ <Alert
638
+ key={hp.id}
639
+ type="error"
640
+ showIcon
641
+ icon={<ExclamationCircleOutlined />}
642
+ message={`${t('Promotion Halted')}: ${hp.name} (${hp.key})`}
643
+ description={hp.promotionHaltReason || t('Ops intervention required before resuming production deployments.')}
644
+ action={
645
+ <Button
646
+ size="small"
647
+ danger
648
+ loading={busyKey === `halt-${hp.id}`}
649
+ onClick={() => {
650
+ handleClearPromotionHalt(hp.id).catch(() => undefined);
651
+ }}
652
+ >
653
+ {t('Clear Halt')}
654
+ </Button>
655
+ }
656
+ />
657
+ ))}
658
+ {opsSummary.pendingApprovalsCount > 0 ||
659
+ opsSummary.retryingGitCount > 0 ||
660
+ opsSummary.pendingCleanupsCount > 0 ? (
661
+ <Flex gap={8} wrap="wrap">
662
+ {opsSummary.pendingApprovalsCount > 0 ? (
663
+ <Tag color="warning">{`${t('Pending QA Approvals')}: ${opsSummary.pendingApprovalsCount}`}</Tag>
664
+ ) : null}
665
+ {opsSummary.retryingGitCount > 0 ? (
666
+ <Tag color="processing">{`${t('Git Feedback Retrying')}: ${opsSummary.retryingGitCount}`}</Tag>
667
+ ) : null}
668
+ {opsSummary.pendingCleanupsCount > 0 ? (
669
+ <Tag color="orange">{`${t('Pending Container Cleanups')}: ${opsSummary.pendingCleanupsCount}`}</Tag>
670
+ ) : null}
671
+ </Flex>
672
+ ) : null}
673
+ </Space>
674
+ );
675
+
676
+ const renderPipelinesTab = () => (
677
+ <Card
678
+ aria-label={t('CI Pipelines & Webhooks')}
679
+ title={t('CI Pipelines & Webhooks')}
680
+ extra={
681
+ <Space>
682
+ <Button
683
+ icon={<SyncOutlined />}
684
+ loading={busyKey === 'poll-mr'}
685
+ onClick={() => {
686
+ handlePollMrsNow().catch(() => undefined);
687
+ }}
688
+ >
689
+ {t('Poll Open MRs')}
690
+ </Button>
691
+ <Button type="primary" icon={<PlusOutlined />} onClick={openCreateModal}>
692
+ {t('Create CI Pipeline')}
693
+ </Button>
694
+ <Button aria-label={t('Refresh')} icon={<ReloadOutlined spin={loading} />} onClick={handleRefreshClick} />
695
+ </Space>
696
+ }
697
+ >
698
+ {renderOperationalAlerts()}
699
+ <Table<CiPipelineRecord>
700
+ rowKey="id"
701
+ size="middle"
702
+ loading={loading}
703
+ columns={pipelineColumns}
704
+ dataSource={pipelines}
705
+ locale={{ emptyText: <Empty description={t('No CI pipelines configured yet.')} /> }}
706
+ />
707
+ </Card>
708
+ );
709
+
710
+ const renderRunsTab = () => (
711
+ <Card
712
+ aria-label={t('CI Gate Runs & Approvals')}
713
+ title={t('CI Gate Runs & Approvals')}
714
+ extra={<Button aria-label={t('Refresh')} icon={<ReloadOutlined spin={loading} />} onClick={handleRefreshClick} />}
715
+ >
716
+ {renderOperationalAlerts()}
717
+ <Table<CiGateRunRecord>
718
+ rowKey="id"
719
+ size="small"
720
+ loading={loading}
721
+ columns={runColumns}
722
+ dataSource={gateRuns}
723
+ locale={{ emptyText: <Empty description={t('No CI Gate runs executed yet.')} /> }}
724
+ />
725
+ </Card>
726
+ );
727
+
728
+ return (
729
+ <section aria-label={t('CI Testing & Quality Gate Workflows')}>
730
+ {section === 'pipelines' ? renderPipelinesTab() : null}
731
+ {section === 'runs' ? renderRunsTab() : null}
732
+ {section === 'all' ? (
733
+ <Tabs
734
+ items={[
735
+ {
736
+ key: 'pipelines',
737
+ label: t('CI Pipelines & Webhooks'),
738
+ children: renderPipelinesTab(),
739
+ },
740
+ {
741
+ key: 'runs',
742
+ label: t('CI Gate Runs & Approvals'),
743
+ children: renderRunsTab(),
744
+ },
745
+ ]}
746
+ />
747
+ ) : null}
748
+
749
+ <Modal
750
+ open={modalOpen}
751
+ width={800}
752
+ title={editingPipeline ? t('Edit CI Pipeline') : t('Create CI Pipeline')}
753
+ onCancel={() => setModalOpen(false)}
754
+ onOk={() => {
755
+ handleSavePipeline().catch(() => undefined);
756
+ }}
757
+ >
758
+ <Form form={pipelineForm} layout="vertical">
759
+ <Flex gap={12}>
760
+ <Form.Item style={{ flex: 1 }} name="key" label={t('Pipeline Key')} rules={[{ required: true }]}>
761
+ <Input placeholder="orders-pr-ci" disabled={Boolean(editingPipeline)} />
762
+ </Form.Item>
763
+ <Form.Item style={{ flex: 2 }} name="name" label={t('Pipeline Name')} rules={[{ required: true }]}>
764
+ <Input placeholder="Orders Service PR & Pre-Deploy CI Gate" />
765
+ </Form.Item>
766
+ <Form.Item name="enabled" label={t('Enabled')} valuePropName="checked">
767
+ <Switch />
768
+ </Form.Item>
769
+ </Flex>
770
+
771
+ <Flex gap={12}>
772
+ <Form.Item style={{ flex: 1 }} name="tenantId" label={t('Target Test Tenant')} rules={[{ required: true }]}>
773
+ <Select
774
+ options={meta.tenants.map((item) => ({
775
+ label: `${item.name} (${item.key})`,
776
+ value: item.id,
777
+ }))}
778
+ />
779
+ </Form.Item>
780
+ <Form.Item style={{ flex: 1 }} name="gitRepositoryId" label={t('Git Repository')}>
781
+ <Select
782
+ allowClear
783
+ options={meta.gitRepos.map((repo) => ({
784
+ label: repo.name,
785
+ value: repo.id,
786
+ }))}
787
+ />
788
+ </Form.Item>
789
+ <Form.Item style={{ flex: 1 }} name="branchPattern" label={t('Branch Pattern')}>
790
+ <Input placeholder="main, develop, feature/*" />
791
+ </Form.Item>
792
+ </Flex>
793
+
794
+ <Flex gap={12} wrap="wrap">
795
+ <Form.Item name="triggerOnPush" label={t('Trigger on Push')} valuePropName="checked">
796
+ <Switch />
797
+ </Form.Item>
798
+ <Form.Item name="triggerOnMergeRequest" label={t('Trigger on PR / MR')} valuePropName="checked">
799
+ <Switch />
800
+ </Form.Item>
801
+ <Form.Item name="pollMergeRequests" label={t('Poll MRs (NAT Fallback)')} valuePropName="checked">
802
+ <Switch />
803
+ </Form.Item>
804
+ <Form.Item
805
+ style={{ flex: 1, minWidth: 220 }}
806
+ name="webhookSecret"
807
+ label={t('Git Webhook HMAC / Token Secret')}
808
+ >
809
+ <Input.Password placeholder="GitHub X-Hub-Signature-256 or GitLab Token secret" />
810
+ </Form.Item>
811
+ </Flex>
812
+
813
+ <Flex gap={12}>
814
+ <Form.Item style={{ flex: 1 }} name="runnerBackend" label={t('Runner Backend')}>
815
+ <Select
816
+ options={[
817
+ { label: t('External CI (GitHub Actions / GitLab CI Ingest)'), value: 'external_ci' },
818
+ { label: t('Portainer One-shot Ephemeral Container'), value: 'portainer_ephemeral' },
819
+ { label: t('Cluster Manager Ephemeral Container / K8s'), value: 'cluster_ephemeral' },
820
+ { label: t('Test Manager Default Connectors'), value: 'test_manager_default' },
821
+ ]}
822
+ />
823
+ </Form.Item>
824
+ <Form.Item style={{ flex: 1 }} name="portainerInstanceId" label={t('Portainer Instance')}>
825
+ <Select
826
+ allowClear
827
+ options={meta.portainerInstances.map((inst) => ({ label: inst.name, value: inst.id }))}
828
+ />
829
+ </Form.Item>
830
+ <Form.Item style={{ width: 150 }} name="portainerEndpointId" label={t('Endpoint ID')}>
831
+ <InputNumber style={{ width: '100%' }} min={1} />
832
+ </Form.Item>
833
+ </Flex>
834
+
835
+ <Flex gap={12}>
836
+ <Form.Item style={{ width: 150 }} name="qaEndpointId" label={t('QA Endpoint ID')}>
837
+ <InputNumber style={{ width: '100%' }} min={1} />
838
+ </Form.Item>
839
+ <Form.Item style={{ width: 150 }} name="qaStackId" label={t('QA Stack ID (Lease)')}>
840
+ <InputNumber style={{ width: '100%' }} min={1} />
841
+ </Form.Item>
842
+ <Form.Item style={{ flex: 1 }} name="qaAppServicesText" label={t('QA App Services (comma-separated)')}>
843
+ <Input placeholder="app, worker" />
844
+ </Form.Item>
845
+ </Flex>
846
+
847
+ <Flex gap={12}>
848
+ <Form.Item style={{ flex: 1 }} name="runnerImage" label={t('Ephemeral Runner Docker Image')}>
849
+ <Input placeholder="mcr.microsoft.com/playwright:v1.50.0-noble" />
850
+ </Form.Item>
851
+ <Form.Item style={{ width: 180 }} name="runnerNetwork" label={t('Docker Network')}>
852
+ <Input placeholder="nocobase-net" />
853
+ </Form.Item>
854
+ <Form.Item style={{ width: 160 }} name="runnerTimeoutMs" label={t('Timeout (ms)')}>
855
+ <InputNumber style={{ width: '100%' }} min={10000} step={10000} />
856
+ </Form.Item>
857
+ </Flex>
858
+
859
+ <Form.Item name="runnerCommand" label={t('Ephemeral Container Command (optional)')}>
860
+ <Input.TextArea
861
+ rows={2}
862
+ placeholder='npx vitest run --reporter=junit --outputFile=/tmp/junit.xml && curl -X POST "$NOCOBASE_REPORT_URL" -H "x-test-callback-token: $NOCOBASE_REPORT_TOKEN" -F "runId=$TEST_RUN_ID"'
863
+ />
864
+ </Form.Item>
865
+
866
+ <Form.Item name="runnerEnvJson" label={t('Extra Runner Env JSON')}>
867
+ <Input.TextArea rows={2} placeholder='{"NODE_ENV":"test"}' />
868
+ </Form.Item>
869
+
870
+ <Flex gap={12}>
871
+ <Form.Item style={{ flex: 1 }} name="deployGateMode" label={t('Pre-Deploy Quality Gate Mode')}>
872
+ <Select
873
+ options={[
874
+ { label: t('No Runtime Promotion (CI Feedback Only)'), value: 'none' },
875
+ { label: t('Auto-Promote Runtime Stack when Passed'), value: 'gate_deploy' },
876
+ { label: t('Require Baseline Approval on Diff Mismatch'), value: 'manual_on_diff_mismatch' },
877
+ ]}
878
+ />
879
+ </Form.Item>
880
+ <Form.Item style={{ flex: 1 }} name="portainerPipelineId" label={t('Linked Portainer Build Pipeline')}>
881
+ <Select
882
+ allowClear
883
+ options={meta.portainerPipelines.map((p) => ({
884
+ label: p.deployEnabled ? `${p.name} (deployEnabled=true)` : `${p.name} (Build-Only)`,
885
+ value: p.id,
886
+ }))}
887
+ />
888
+ </Form.Item>
889
+ <Form.Item style={{ width: 150 }} name="deployEndpointId" label={t('Prod Endpoint ID')}>
890
+ <InputNumber style={{ width: '100%' }} min={1} />
891
+ </Form.Item>
892
+ <Form.Item style={{ width: 150 }} name="deployStackId" label={t('Runtime Stack ID')}>
893
+ <InputNumber style={{ width: '100%' }} min={1} />
894
+ </Form.Item>
895
+ </Flex>
896
+
897
+ <Flex gap={12}>
898
+ <Form.Item style={{ flex: 1 }} name="gateApproverIds" label={t('Authorized QA Gate Approvers')}>
899
+ <Select
900
+ mode="multiple"
901
+ allowClear
902
+ placeholder={t('Select dedicated QA approvers (no bypass)')}
903
+ options={meta.users.map((u) => ({
904
+ label: `${u.nickname} (@${u.username || u.id})`,
905
+ value: u.id,
906
+ }))}
907
+ />
908
+ </Form.Item>
909
+ <Form.Item style={{ flex: 1 }} name="protectedBranchesText" label={t('Protected Release Branches')}>
910
+ <Input placeholder="main, master, release/*" />
911
+ </Form.Item>
912
+ <Form.Item name="dbBackwardCompatible" label={t('Auto-Rollback Safe (DB Compat)')} valuePropName="checked">
913
+ <Switch />
914
+ </Form.Item>
915
+ </Flex>
916
+
917
+ <Flex gap={12} wrap="wrap">
918
+ <Form.Item name="publishCommitStatus" label={t('Publish Commit Status')} valuePropName="checked">
919
+ <Switch />
920
+ </Form.Item>
921
+ <Form.Item name="publishPrComment" label={t('Sticky PR Comment')} valuePropName="checked">
922
+ <Switch />
923
+ </Form.Item>
924
+ <Form.Item name="enrichGitReview" label={t('Enrich AI Git Review')} valuePropName="checked">
925
+ <Switch />
926
+ </Form.Item>
927
+ <Form.Item name="enableAiTriage" label={t('Enable AI Triage')} valuePropName="checked">
928
+ <Switch />
929
+ </Form.Item>
930
+ <Form.Item name="smokeOnClusterHotReload" label={t('Cluster Hot-Reload Smoke')} valuePropName="checked">
931
+ <Switch />
932
+ </Form.Item>
933
+ </Flex>
934
+
935
+ <Flex gap={12}>
936
+ <Form.Item style={{ flex: 1 }} name="statusContext" label={t('Commit Status Context')}>
937
+ <Input placeholder="nocobase/ci-test-manager" />
938
+ </Form.Item>
939
+ <Form.Item style={{ flex: 1 }} name="agentLoopPatternKey" label={t('Agent Orchestrator Loop Pattern')}>
940
+ <Select
941
+ allowClear
942
+ options={meta.agentLoopPatterns.map((pat) => ({
943
+ label: `${pat.name} (${pat.key})`,
944
+ value: pat.key,
945
+ }))}
946
+ />
947
+ </Form.Item>
948
+ </Flex>
949
+ </Form>
950
+ </Modal>
951
+
952
+ <Drawer
953
+ open={Boolean(selectedRun)}
954
+ width={720}
955
+ title={selectedRun ? `${t('CI Gate Run')} #${selectedRun.id} (${selectedRun.commitSha.slice(0, 8)})` : ''}
956
+ onClose={() => setSelectedRun(null)}
957
+ >
958
+ {selectedRun ? (
959
+ <Space direction="vertical" size="middle" style={{ width: '100%' }}>
960
+ <Descriptions bordered size="small" column={2}>
961
+ <Descriptions.Item label={t('Commit SHA')}>
962
+ <Typography.Text code>{selectedRun.commitSha}</Typography.Text>
963
+ </Descriptions.Item>
964
+ <Descriptions.Item label={t('Build Provenance')}>
965
+ {selectedRun.buildRunId ? <Tag color="blue">{`Build #${selectedRun.buildRunId}`}</Tag> : '—'}
966
+ </Descriptions.Item>
967
+ <Descriptions.Item label={t('Test Verdict')}>
968
+ {renderVerdictAxisTag(selectedRun.testVerdict, selectedRun.verdictReasonCode)}
969
+ </Descriptions.Item>
970
+ <Descriptions.Item label={t('Approval Decision')}>
971
+ {renderApprovalAxisTag(selectedRun.approvalState)}
972
+ </Descriptions.Item>
973
+ <Descriptions.Item label={t('Deploy Outcome')}>
974
+ {renderDeployAxisTag(selectedRun.deployOutcome)}
975
+ </Descriptions.Item>
976
+ <Descriptions.Item label={t('Git Feedback Sync')}>
977
+ <Tag>{selectedRun.gitFeedbackSyncState || 'not_applicable'}</Tag>
978
+ </Descriptions.Item>
979
+ </Descriptions>
980
+
981
+ {selectedRun.approvalRecord?.approvedBy ? (
982
+ <Alert
983
+ type="success"
984
+ showIcon
985
+ message={`${t('Approved by')} ${selectedRun.approvalRecord.approvedBy} (${
986
+ selectedRun.approvalRecord.approvedAt || ''
987
+ })`}
988
+ />
989
+ ) : null}
990
+
991
+ {selectedRun.rollbackRecord ? (
992
+ <Alert
993
+ type={selectedRun.rollbackRecord.rollbackSucceeded ? 'warning' : 'error'}
994
+ showIcon
995
+ message={
996
+ selectedRun.rollbackRecord.rollbackSucceeded
997
+ ? t('Automatic Production Rollback Verified')
998
+ : t('Production Rollback Skipped / Failed — Ops Intervention Required')
999
+ }
1000
+ description={selectedRun.rollbackRecord.detail}
1001
+ />
1002
+ ) : null}
1003
+
1004
+ {selectedRun.errorMessage ? <Alert type="error" showIcon message={selectedRun.errorMessage} /> : null}
1005
+ {selectedRun.triageResult ? (
1006
+ <Alert
1007
+ type={selectedRun.triageResult.classification === 'baseline_change' ? 'warning' : 'info'}
1008
+ showIcon
1009
+ message={`${t('AI Failure Triage')}: ${selectedRun.triageResult.classification} (${Math.round(
1010
+ selectedRun.triageResult.confidence * 100,
1011
+ )}%)`}
1012
+ description={
1013
+ <Space direction="vertical" size={4}>
1014
+ <Typography.Text>{selectedRun.triageResult.rootCause}</Typography.Text>
1015
+ <Typography.Text type="secondary">{selectedRun.triageResult.suggestedAction}</Typography.Text>
1016
+ {selectedRun.triageResult.triageError ? (
1017
+ <Typography.Text type="warning">{selectedRun.triageResult.triageError}</Typography.Text>
1018
+ ) : null}
1019
+ </Space>
1020
+ }
1021
+ />
1022
+ ) : null}
1023
+ <Card size="small" title={t('Execution Logs')}>
1024
+ <pre style={{ margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-word', fontSize: 12 }}>
1025
+ {selectedRun.logs || t('No logs recorded.')}
1026
+ </pre>
1027
+ </Card>
1028
+ </Space>
1029
+ ) : null}
1030
+ </Drawer>
1031
+ </section>
1032
+ );
1033
+ };
1034
+
1035
+ export default CiPipelinesSettingsView;