plugin-document-understanding 1.1.14 → 1.1.16

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 (132) hide show
  1. package/README.md +29 -29
  2. package/client-v2.d.ts +2 -2
  3. package/client-v2.js +1 -1
  4. package/dist/client/{345.e6e484fb1974c3d3.js → 345.277fbb2b97424db5.js} +1 -1
  5. package/dist/client/index.js +1 -1
  6. package/dist/client-v2/{345.a8f28526ac21e02a.js → 345.2fa9834b46dd4531.js} +1 -1
  7. package/dist/client-v2/index.js +1 -1
  8. package/dist/externalVersion.js +8 -7
  9. package/dist/locale/en-US.json +3 -1
  10. package/dist/locale/zh-CN.json +3 -1
  11. package/dist/node_modules/form-data/lib/form_data.js +2 -2
  12. package/dist/node_modules/form-data/node_modules/es-define-property/.eslintrc +13 -0
  13. package/dist/node_modules/form-data/node_modules/es-define-property/.github/FUNDING.yml +12 -0
  14. package/dist/node_modules/form-data/node_modules/es-define-property/.nycrc +9 -0
  15. package/dist/node_modules/form-data/node_modules/es-define-property/index.d.ts +3 -0
  16. package/dist/node_modules/form-data/node_modules/es-define-property/index.js +14 -0
  17. package/dist/node_modules/form-data/node_modules/es-define-property/package.json +81 -0
  18. package/dist/node_modules/form-data/node_modules/es-define-property/test/index.js +56 -0
  19. package/dist/node_modules/form-data/node_modules/es-object-atoms/.eslintrc +16 -0
  20. package/dist/node_modules/form-data/node_modules/es-object-atoms/.github/FUNDING.yml +12 -0
  21. package/dist/node_modules/form-data/node_modules/es-object-atoms/RequireObjectCoercible.d.ts +3 -0
  22. package/dist/node_modules/form-data/node_modules/es-object-atoms/RequireObjectCoercible.js +11 -0
  23. package/dist/node_modules/form-data/node_modules/es-object-atoms/ToObject.d.ts +7 -0
  24. package/dist/node_modules/form-data/node_modules/es-object-atoms/ToObject.js +10 -0
  25. package/dist/node_modules/form-data/node_modules/es-object-atoms/index.d.ts +3 -0
  26. package/dist/node_modules/form-data/node_modules/es-object-atoms/index.js +4 -0
  27. package/dist/node_modules/form-data/node_modules/es-object-atoms/isObject.d.ts +3 -0
  28. package/dist/node_modules/form-data/node_modules/es-object-atoms/isObject.js +6 -0
  29. package/dist/node_modules/form-data/node_modules/es-object-atoms/package.json +80 -0
  30. package/dist/node_modules/form-data/node_modules/es-object-atoms/test/index.js +38 -0
  31. package/dist/node_modules/form-data/node_modules/es-set-tostringtag/.eslintrc +13 -0
  32. package/dist/node_modules/form-data/node_modules/es-set-tostringtag/.nycrc +9 -0
  33. package/dist/node_modules/form-data/node_modules/es-set-tostringtag/index.d.ts +10 -0
  34. package/dist/node_modules/form-data/node_modules/es-set-tostringtag/index.js +35 -0
  35. package/dist/node_modules/form-data/node_modules/es-set-tostringtag/node_modules/hasown/.eslintrc +5 -0
  36. package/dist/node_modules/form-data/node_modules/es-set-tostringtag/node_modules/hasown/.github/FUNDING.yml +12 -0
  37. package/dist/node_modules/form-data/node_modules/es-set-tostringtag/node_modules/hasown/.nycrc +13 -0
  38. package/dist/node_modules/form-data/node_modules/es-set-tostringtag/node_modules/hasown/index.d.ts +3 -0
  39. package/dist/node_modules/form-data/node_modules/es-set-tostringtag/node_modules/hasown/index.js +8 -0
  40. package/dist/node_modules/form-data/node_modules/es-set-tostringtag/node_modules/hasown/package.json +92 -0
  41. package/dist/node_modules/form-data/node_modules/es-set-tostringtag/package.json +78 -0
  42. package/dist/node_modules/form-data/node_modules/es-set-tostringtag/test/index.js +85 -0
  43. package/dist/node_modules/form-data/node_modules/get-intrinsic/.eslintrc +42 -0
  44. package/dist/node_modules/form-data/node_modules/get-intrinsic/.github/FUNDING.yml +12 -0
  45. package/dist/node_modules/form-data/node_modules/get-intrinsic/.nycrc +9 -0
  46. package/dist/node_modules/form-data/node_modules/get-intrinsic/index.js +378 -0
  47. package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/.eslintrc +11 -0
  48. package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/.github/FUNDING.yml +12 -0
  49. package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/.nycrc +9 -0
  50. package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/index.d.ts +3 -0
  51. package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/index.js +14 -0
  52. package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/package.json +111 -0
  53. package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/shams.d.ts +3 -0
  54. package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/shams.js +45 -0
  55. package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/test/index.js +22 -0
  56. package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/test/shams/core-js.js +29 -0
  57. package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/test/shams/get-own-property-symbols.js +29 -0
  58. package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/has-symbols/test/tests.js +58 -0
  59. package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/hasown/.eslintrc +5 -0
  60. package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/hasown/.github/FUNDING.yml +12 -0
  61. package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/hasown/.nycrc +13 -0
  62. package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/hasown/index.d.ts +3 -0
  63. package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/hasown/index.js +8 -0
  64. package/dist/node_modules/form-data/node_modules/get-intrinsic/node_modules/hasown/package.json +92 -0
  65. package/dist/node_modules/form-data/node_modules/get-intrinsic/package.json +97 -0
  66. package/dist/node_modules/form-data/node_modules/get-intrinsic/test/GetIntrinsic.js +274 -0
  67. package/dist/node_modules/form-data/node_modules/gopd/.eslintrc +16 -0
  68. package/dist/node_modules/form-data/node_modules/gopd/.github/FUNDING.yml +12 -0
  69. package/dist/node_modules/form-data/node_modules/gopd/gOPD.d.ts +1 -0
  70. package/dist/node_modules/form-data/node_modules/gopd/gOPD.js +4 -0
  71. package/dist/node_modules/form-data/node_modules/gopd/index.d.ts +5 -0
  72. package/dist/node_modules/form-data/node_modules/gopd/index.js +15 -0
  73. package/dist/node_modules/form-data/node_modules/gopd/package.json +77 -0
  74. package/dist/node_modules/form-data/node_modules/gopd/test/index.js +36 -0
  75. package/dist/node_modules/form-data/node_modules/has-tostringtag/.eslintrc +5 -0
  76. package/dist/node_modules/form-data/node_modules/has-tostringtag/.github/FUNDING.yml +12 -0
  77. package/dist/node_modules/form-data/node_modules/has-tostringtag/.nycrc +13 -0
  78. package/dist/node_modules/form-data/node_modules/has-tostringtag/index.d.ts +3 -0
  79. package/dist/node_modules/form-data/node_modules/has-tostringtag/index.js +8 -0
  80. package/dist/node_modules/form-data/node_modules/has-tostringtag/package.json +108 -0
  81. package/dist/node_modules/form-data/node_modules/has-tostringtag/shams.d.ts +3 -0
  82. package/dist/node_modules/form-data/node_modules/has-tostringtag/shams.js +8 -0
  83. package/dist/node_modules/form-data/node_modules/has-tostringtag/test/index.js +21 -0
  84. package/dist/node_modules/form-data/node_modules/has-tostringtag/test/shams/core-js.js +31 -0
  85. package/dist/node_modules/form-data/node_modules/has-tostringtag/test/shams/get-own-property-symbols.js +30 -0
  86. package/dist/node_modules/form-data/node_modules/has-tostringtag/test/tests.js +15 -0
  87. package/dist/node_modules/form-data/node_modules/hasown/.github/FUNDING.yml +12 -0
  88. package/dist/node_modules/form-data/node_modules/hasown/.nycrc +13 -0
  89. package/dist/node_modules/form-data/node_modules/hasown/index.d.ts +3 -0
  90. package/dist/node_modules/form-data/node_modules/hasown/index.js +8 -0
  91. package/dist/node_modules/form-data/node_modules/hasown/package.json +91 -0
  92. package/dist/node_modules/form-data/package.json +1 -1
  93. package/dist/node_modules/mime-types/index.js +3 -3
  94. package/dist/node_modules/mime-types/package.json +1 -1
  95. package/dist/server/actions.js +45 -35
  96. package/package.json +57 -46
  97. package/src/client/index.tsx +15 -15
  98. package/src/client-v2/components/EndpointsTab.tsx +578 -578
  99. package/src/client-v2/components/JobsTab.tsx +294 -294
  100. package/src/client-v2/components/PipelinesTab.tsx +962 -962
  101. package/src/client-v2/components/PluginSettings.tsx +54 -50
  102. package/src/client-v2/components/ServiceConfigTab.tsx +139 -139
  103. package/src/client-v2/components/__tests__/PluginSettings.test.tsx +39 -0
  104. package/src/client-v2/index.tsx +1 -1
  105. package/src/client-v2/locale.ts +21 -21
  106. package/src/client-v2/models/index.ts +12 -12
  107. package/src/client-v2/plugin.tsx +31 -21
  108. package/src/client-v2/types.ts +32 -32
  109. package/src/index.ts +2 -2
  110. package/src/locale/en-US.json +3 -1
  111. package/src/locale/zh-CN.json +3 -1
  112. package/src/server/__tests__/actions.test.ts +121 -98
  113. package/src/server/__tests__/cluster-safety.test.ts +259 -259
  114. package/src/server/__tests__/document-understanding-service.test.ts +82 -82
  115. package/src/server/__tests__/dugate-integration.test.ts +221 -221
  116. package/src/server/__tests__/smoke.test.ts +78 -55
  117. package/src/server/__tests__/upload-security.test.ts +128 -0
  118. package/src/server/actions.ts +53 -51
  119. package/src/server/collections/config.ts +18 -18
  120. package/src/server/collections/endpoints.ts +33 -33
  121. package/src/server/collections/jobs.ts +42 -42
  122. package/src/server/collections/pipeline-steps.ts +27 -27
  123. package/src/server/collections/pipelines.ts +19 -19
  124. package/src/server/dugate-seed.ts +491 -491
  125. package/src/server/index.ts +1 -1
  126. package/src/server/plugin.ts +143 -143
  127. package/src/server/services/AsyncJobManager.ts +238 -238
  128. package/src/server/services/DocumentUnderstandingService.ts +332 -332
  129. package/src/server/services/ExternalApiClient.ts +178 -178
  130. package/src/server/services/PipelineExecutor.ts +593 -593
  131. package/src/server/tools/document-understanding-tool.ts +181 -181
  132. package/src/server/types.ts +90 -90
@@ -1,962 +1,962 @@
1
- import React, { useEffect, useState, useCallback, useRef } from 'react';
2
- import {
3
- Table,
4
- Button,
5
- Modal,
6
- Form,
7
- Input,
8
- Switch,
9
- message,
10
- Select,
11
- InputNumber,
12
- Card,
13
- Space,
14
- Tag,
15
- Popconfirm,
16
- Collapse,
17
- Tooltip,
18
- Empty,
19
- Badge,
20
- Alert,
21
- } from 'antd';
22
- import type { ColumnsType } from 'antd/es/table';
23
- import {
24
- PlusOutlined,
25
- DeleteOutlined,
26
- EditOutlined,
27
- ArrowUpOutlined,
28
- ArrowDownOutlined,
29
- ThunderboltOutlined,
30
- PlayCircleOutlined,
31
- ReloadOutlined,
32
- } from '@ant-design/icons';
33
- import { useFlowContext } from '@nocobase/flow-engine';
34
- import { useT } from '../locale';
35
- import { EndpointDef, JobState, PipelineDef, PipelineStepDef, errorMessage, unwrapData } from '../types';
36
-
37
- const { TextArea } = Input;
38
- const { Panel } = Collapse;
39
-
40
- const STATUS_COLORS: Record<string, string> = {
41
- pending: 'default',
42
- running: 'processing',
43
- polling: 'processing',
44
- completed: 'success',
45
- failed: 'error',
46
- timeout: 'error',
47
- };
48
-
49
- const TERMINAL_STATUSES = ['completed', 'failed', 'timeout'];
50
-
51
- interface JsonSchemaNode {
52
- type?: string;
53
- properties?: Record<string, JsonSchemaNode>;
54
- default?: unknown;
55
- }
56
-
57
- const isPlainObject = (value: unknown): value is Record<string, unknown> =>
58
- !!value && typeof value === 'object' && !Array.isArray(value);
59
-
60
- const stringifyJson = (value: unknown) => JSON.stringify(value ?? {}, null, 2);
61
-
62
- const buildDefaultInputFromSchema = (schema: unknown): unknown => {
63
- if (!isPlainObject(schema)) {
64
- return {};
65
- }
66
-
67
- if (Object.prototype.hasOwnProperty.call(schema, 'default')) {
68
- return schema.default;
69
- }
70
-
71
- const node = schema as JsonSchemaNode;
72
-
73
- if (node.type === 'object' || node.properties) {
74
- return Object.entries(node.properties || {}).reduce<Record<string, unknown>>((acc, [key, propertySchema]) => {
75
- const value = buildDefaultInputFromSchema(propertySchema);
76
- if (value !== undefined) {
77
- acc[key] = value;
78
- }
79
- return acc;
80
- }, {});
81
- }
82
-
83
- if (node.type === 'array') {
84
- return [];
85
- }
86
-
87
- return undefined;
88
- };
89
-
90
- const mergeDefaults = (defaults: unknown, value: unknown): unknown => {
91
- if (isPlainObject(defaults) && isPlainObject(value)) {
92
- return Object.entries(defaults).reduce<Record<string, unknown>>(
93
- (acc, [key, defaultValue]) => ({
94
- ...acc,
95
- [key]: mergeDefaults(defaultValue, acc[key]),
96
- }),
97
- { ...value },
98
- );
99
- }
100
-
101
- return value === undefined ? defaults : value;
102
- };
103
-
104
- /* ─── JSON Editor ───────────────────────────────────────────────── */
105
- const JsonEditor: React.FC<{
106
- value?: unknown;
107
- onChange?: (v: unknown) => void;
108
- placeholder?: string;
109
- rows?: number;
110
- }> = ({ value, onChange, placeholder, rows = 5 }) => {
111
- const t = useT();
112
- const [text, setText] = useState('');
113
- const [error, setError] = useState('');
114
-
115
- useEffect(() => {
116
- if (!value) {
117
- setText('');
118
- return;
119
- }
120
- try {
121
- setText(typeof value === 'string' ? JSON.stringify(JSON.parse(value), null, 2) : JSON.stringify(value, null, 2));
122
- } catch {
123
- setText(typeof value === 'string' ? value : '');
124
- }
125
- }, [value]);
126
-
127
- const handleBlur = () => {
128
- if (!text.trim()) {
129
- setError('');
130
- onChange?.(null);
131
- return;
132
- }
133
- try {
134
- const parsed = JSON.parse(text);
135
- setError('');
136
- onChange?.(parsed);
137
- } catch {
138
- setError(t('Invalid JSON'));
139
- }
140
- };
141
-
142
- return (
143
- <div>
144
- <TextArea
145
- rows={rows}
146
- value={text}
147
- onChange={(e) => setText(e.target.value)}
148
- onBlur={handleBlur}
149
- placeholder={placeholder || '{}'}
150
- status={error ? 'error' : undefined}
151
- style={{ fontFamily: 'monospace', fontSize: 12 }}
152
- />
153
- {error && (
154
- <div role="alert" style={{ color: '#ff4d4f', fontSize: 12 }}>
155
- {error}
156
- </div>
157
- )}
158
- </div>
159
- );
160
- };
161
-
162
- /* ─── Step Editor ───────────────────────────────────────────────── */
163
- type StepErrorMode = 'fail' | 'skip' | 'retry';
164
-
165
- interface StepData {
166
- _key: string; // client-side key for React
167
- id?: number;
168
- stepOrder: number;
169
- name: string;
170
- endpointId: number | null;
171
- inputMapping: Record<string, unknown> | null;
172
- outputAlias: string;
173
- condition: unknown;
174
- onError: StepErrorMode;
175
- retryCount: number;
176
- }
177
-
178
- const emptyStep = (order: number): StepData => ({
179
- _key: `new_${Date.now()}_${Math.random()}`,
180
- stepOrder: order,
181
- name: '',
182
- endpointId: null,
183
- inputMapping: null,
184
- outputAlias: '',
185
- condition: null,
186
- onError: 'fail',
187
- retryCount: 0,
188
- });
189
-
190
- const StepEditor: React.FC<{
191
- steps: StepData[];
192
- endpoints: EndpointDef[];
193
- onChange: (steps: StepData[]) => void;
194
- }> = ({ steps, endpoints, onChange }) => {
195
- const t = useT();
196
-
197
- const moveStep = (index: number, direction: -1 | 1) => {
198
- const newSteps = [...steps];
199
- const target = index + direction;
200
- if (target < 0 || target >= newSteps.length) return;
201
- [newSteps[index], newSteps[target]] = [newSteps[target], newSteps[index]];
202
- // Recompute stepOrder
203
- newSteps.forEach((s, i) => (s.stepOrder = i + 1));
204
- onChange(newSteps);
205
- };
206
-
207
- const updateStep = <K extends keyof StepData>(index: number, field: K, value: StepData[K]) => {
208
- const newSteps = [...steps];
209
- newSteps[index] = { ...newSteps[index], [field]: value };
210
- onChange(newSteps);
211
- };
212
-
213
- const removeStep = (index: number) => {
214
- const newSteps = steps.filter((_, i) => i !== index);
215
- newSteps.forEach((s, i) => (s.stepOrder = i + 1));
216
- onChange(newSteps);
217
- };
218
-
219
- const addStep = () => {
220
- onChange([...steps, emptyStep(steps.length + 1)]);
221
- };
222
-
223
- if (steps.length === 0) {
224
- return (
225
- <div style={{ textAlign: 'center', padding: '20px 0' }}>
226
- <Empty description={t('No steps yet')} imageStyle={{ height: 40 }} />
227
- <Button type="dashed" icon={<PlusOutlined />} onClick={addStep} style={{ marginTop: 8 }}>
228
- {t('Add First Step')}
229
- </Button>
230
- </div>
231
- );
232
- }
233
-
234
- return (
235
- <div>
236
- <Collapse size="small" defaultActiveKey={steps.map((s) => s._key)}>
237
- {steps.map((step, index) => {
238
- const ep = endpoints.find((e) => e.id === step.endpointId);
239
- const headerExtra = (
240
- <Space size={4} onClick={(e) => e.stopPropagation()}>
241
- <Button
242
- size="small"
243
- disabled={index === 0}
244
- icon={<ArrowUpOutlined />}
245
- onClick={() => moveStep(index, -1)}
246
- aria-label={t('Move step up')}
247
- />
248
- <Button
249
- size="small"
250
- disabled={index === steps.length - 1}
251
- icon={<ArrowDownOutlined />}
252
- onClick={() => moveStep(index, 1)}
253
- aria-label={t('Move step down')}
254
- />
255
- <Popconfirm title={t('Remove step?')} okText={t('Delete')} onConfirm={() => removeStep(index)}>
256
- <Button size="small" danger icon={<DeleteOutlined />} aria-label={t('Remove step?')} />
257
- </Popconfirm>
258
- </Space>
259
- );
260
-
261
- const label = (
262
- <Space>
263
- <Badge count={step.stepOrder} style={{ backgroundColor: '#1677ff' }} />
264
- <span>{step.name || t('(unnamed)')}</span>
265
- {ep && <Tag>{ep.name}</Tag>}
266
- {step.onError === 'skip' && (
267
- <Tooltip title={t('Step can be skipped on error')}>
268
- <Tag color="orange">{t('skip on error')}</Tag>
269
- </Tooltip>
270
- )}
271
- {step.condition && (
272
- <Tooltip title={t('Has condition')}>
273
- <Tag color="purple">{t('conditional')}</Tag>
274
- </Tooltip>
275
- )}
276
- </Space>
277
- );
278
-
279
- const nameId = `step-name-${step._key}`;
280
- const endpointId = `step-endpoint-${step._key}`;
281
- const aliasId = `step-alias-${step._key}`;
282
-
283
- return (
284
- <Panel key={step._key} header={label} extra={headerExtra}>
285
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 16px' }}>
286
- <div>
287
- <label htmlFor={nameId} style={{ fontWeight: 500, display: 'block', marginBottom: 4 }}>
288
- {t('Step Name')} *
289
- </label>
290
- <Input
291
- id={nameId}
292
- value={step.name}
293
- onChange={(e) => updateStep(index, 'name', e.target.value)}
294
- placeholder="OCR, Classify, Extract..."
295
- />
296
- </div>
297
- <div>
298
- <label htmlFor={endpointId} style={{ fontWeight: 500, display: 'block', marginBottom: 4 }}>
299
- {t('Endpoint')} *
300
- </label>
301
- <Select
302
- id={endpointId}
303
- value={step.endpointId}
304
- onChange={(v) => updateStep(index, 'endpointId', v)}
305
- placeholder={t('Select endpoint')}
306
- style={{ width: '100%' }}
307
- options={endpoints.map((endpoint) => ({
308
- value: endpoint.id,
309
- label: `${endpoint.name} (${endpoint.method} ${endpoint.subpath})`,
310
- }))}
311
- />
312
- </div>
313
- <div>
314
- <label
315
- htmlFor={aliasId}
316
- style={{ fontWeight: 500, display: 'block', marginBottom: 4, marginTop: 12 }}
317
- >
318
- {t('Output Alias')}
319
- </label>
320
- <Input
321
- id={aliasId}
322
- value={step.outputAlias}
323
- onChange={(e) => updateStep(index, 'outputAlias', e.target.value)}
324
- placeholder="ocr_result"
325
- />
326
- <div style={{ color: '#888', fontSize: 11 }}>
327
- {t('Other steps reference this as')}: $step[{step.outputAlias || step.stepOrder}].response.field
328
- </div>
329
- </div>
330
- <div>
331
- <label style={{ fontWeight: 500, display: 'block', marginBottom: 4, marginTop: 12 }}>
332
- {t('On Error')}
333
- </label>
334
- <Space>
335
- <Select
336
- value={step.onError}
337
- onChange={(v: StepErrorMode) => updateStep(index, 'onError', v)}
338
- style={{ width: 120 }}
339
- aria-label={t('On Error')}
340
- options={[
341
- { value: 'fail', label: t('Fail') },
342
- { value: 'skip', label: t('Skip') },
343
- { value: 'retry', label: t('Retry') },
344
- ]}
345
- />
346
- {step.onError === 'retry' && (
347
- <InputNumber
348
- value={step.retryCount}
349
- onChange={(v) => updateStep(index, 'retryCount', v || 0)}
350
- min={1}
351
- max={10}
352
- addonBefore="x"
353
- style={{ width: 100 }}
354
- aria-label={t('Retry')}
355
- />
356
- )}
357
- </Space>
358
- </div>
359
- </div>
360
-
361
- <div style={{ marginTop: 12 }}>
362
- <label style={{ fontWeight: 500, display: 'block', marginBottom: 4 }}>
363
- {t('Input Mapping (JSON)')}
364
- <Tooltip
365
- title={t(
366
- 'Map endpoint input fields. Use $input.field, $step[alias].response.field, $files, or literal values.',
367
- )}
368
- >
369
- <span style={{ fontWeight: 'normal', color: '#888', marginLeft: 6, cursor: 'help' }}>?</span>
370
- </Tooltip>
371
- </label>
372
- <JsonEditor
373
- value={step.inputMapping}
374
- onChange={(v) => updateStep(index, 'inputMapping', v as Record<string, unknown> | null)}
375
- placeholder='{ "text": "$step[ocr_result].response.text", "lang": "vi" }'
376
- rows={3}
377
- />
378
- </div>
379
-
380
- <div style={{ marginTop: 12 }}>
381
- <label style={{ fontWeight: 500, display: 'block', marginBottom: 4 }}>
382
- {t('Condition (optional JSON)')}
383
- <Tooltip title={t('Only run this step if the condition matches.')}>
384
- <span style={{ fontWeight: 'normal', color: '#888', marginLeft: 6, cursor: 'help' }}>?</span>
385
- </Tooltip>
386
- </label>
387
- <JsonEditor
388
- value={step.condition}
389
- onChange={(v) => updateStep(index, 'condition', v)}
390
- placeholder='{ "field": "$step[classify].response.type", "op": "eq", "value": "invoice" }'
391
- rows={2}
392
- />
393
- </div>
394
- </Panel>
395
- );
396
- })}
397
- </Collapse>
398
- <Button type="dashed" icon={<PlusOutlined />} onClick={addStep} style={{ marginTop: 8, width: '100%' }}>
399
- {t('Add Step')}
400
- </Button>
401
- </div>
402
- );
403
- };
404
-
405
- /* ─── Pipelines Tab ─────────────────────────────────────────────── */
406
- interface PipelineFormValues {
407
- name: string;
408
- description?: string;
409
- enabled: boolean;
410
- inputSchema?: unknown;
411
- outputMapping?: Record<string, unknown> | null;
412
- }
413
-
414
- export const PipelinesTab = () => {
415
- const ctx = useFlowContext();
416
- const api = ctx.api;
417
- const t = useT();
418
- const [pipelines, setPipelines] = useState<PipelineDef[]>([]);
419
- const [endpoints, setEndpoints] = useState<EndpointDef[]>([]);
420
- const [loading, setLoading] = useState(false);
421
- const [visible, setVisible] = useState(false);
422
- const [form] = Form.useForm<PipelineFormValues>();
423
- const [editingId, setEditingId] = useState<number | null>(null);
424
- const [steps, setSteps] = useState<StepData[]>([]);
425
- const [playgroundVisible, setPlaygroundVisible] = useState(false);
426
- const [playgroundPipeline, setPlaygroundPipeline] = useState<PipelineDef | null>(null);
427
- const [playgroundInput, setPlaygroundInput] = useState('{}');
428
- const [playgroundInputError, setPlaygroundInputError] = useState('');
429
- const [playgroundJob, setPlaygroundJob] = useState<JobState | null>(null);
430
- const [playgroundRunning, setPlaygroundRunning] = useState(false);
431
- const playgroundTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
432
-
433
- const statusLabels: Record<string, string> = {
434
- pending: t('Pending'),
435
- running: t('Running'),
436
- polling: t('Polling'),
437
- completed: t('Completed'),
438
- failed: t('Failed'),
439
- timeout: t('Timeout'),
440
- };
441
-
442
- const fetchData = useCallback(async () => {
443
- setLoading(true);
444
- try {
445
- const [pRes, eRes] = await Promise.all([
446
- api.request({ url: 'docUnderstanding:listPipelines' }),
447
- api.request({ url: 'docUnderstanding:listEndpoints' }),
448
- ]);
449
- setPipelines(unwrapData<PipelineDef[]>(pRes, []));
450
- setEndpoints(unwrapData<EndpointDef[]>(eRes, []));
451
- } finally {
452
- setLoading(false);
453
- }
454
- }, [api]);
455
-
456
- useEffect(() => {
457
- fetchData();
458
- }, [fetchData]);
459
-
460
- useEffect(() => {
461
- return () => {
462
- if (playgroundTimerRef.current) {
463
- clearInterval(playgroundTimerRef.current);
464
- }
465
- };
466
- }, []);
467
-
468
- const openAdd = () => {
469
- setEditingId(null);
470
- form.resetFields();
471
- setSteps([]);
472
- setVisible(true);
473
- };
474
-
475
- const openEdit = (record: PipelineDef) => {
476
- setEditingId(record.id);
477
- form.setFieldsValue({
478
- name: record.name,
479
- description: record.description,
480
- enabled: record.enabled,
481
- inputSchema: record.inputSchema,
482
- outputMapping: record.outputMapping,
483
- });
484
- // Convert steps from server format
485
- const serverSteps = [...(record.steps || [])].sort((a, b) => a.stepOrder - b.stepOrder);
486
- setSteps(
487
- serverSteps.map((s) => ({
488
- _key: `srv_${s.id}`,
489
- id: s.id,
490
- stepOrder: s.stepOrder,
491
- name: s.name,
492
- endpointId: s.endpointId,
493
- inputMapping: s.inputMapping ?? null,
494
- outputAlias: s.outputAlias || '',
495
- condition: s.condition,
496
- onError: s.onError || 'fail',
497
- retryCount: s.retryCount || 0,
498
- })),
499
- );
500
- setVisible(true);
501
- };
502
-
503
- const handleDelete = async (id: number) => {
504
- await api.request({
505
- url: 'docUnderstanding:deletePipeline',
506
- method: 'POST',
507
- params: { filterByTk: id },
508
- });
509
- message.success(t('Deleted'));
510
- fetchData();
511
- };
512
-
513
- const stopPlaygroundPolling = useCallback(() => {
514
- if (playgroundTimerRef.current) {
515
- clearInterval(playgroundTimerRef.current);
516
- playgroundTimerRef.current = null;
517
- }
518
- }, []);
519
-
520
- const fetchPlaygroundJob = useCallback(
521
- async (jobId: number) => {
522
- const res = await api.request({
523
- url: 'docUnderstanding:getJobStatus',
524
- params: { filterByTk: jobId },
525
- });
526
- const job = unwrapData<JobState | null>(res, null);
527
- setPlaygroundJob(job);
528
-
529
- if (job && TERMINAL_STATUSES.includes(job.status)) {
530
- stopPlaygroundPolling();
531
- setPlaygroundRunning(false);
532
- }
533
- return job;
534
- },
535
- [api, stopPlaygroundPolling],
536
- );
537
-
538
- const startPlaygroundPolling = useCallback(
539
- (jobId: number) => {
540
- stopPlaygroundPolling();
541
- playgroundTimerRef.current = setInterval(() => {
542
- fetchPlaygroundJob(jobId).catch((err: unknown) => {
543
- stopPlaygroundPolling();
544
- setPlaygroundRunning(false);
545
- message.error(errorMessage(err) || t('Failed to refresh test job'));
546
- });
547
- }, 1500);
548
- },
549
- [fetchPlaygroundJob, stopPlaygroundPolling, t],
550
- );
551
-
552
- const openPlayground = (record: PipelineDef) => {
553
- stopPlaygroundPolling();
554
- setPlaygroundPipeline(record);
555
- setPlaygroundJob(null);
556
- setPlaygroundRunning(false);
557
- setPlaygroundInputError('');
558
- setPlaygroundInput(stringifyJson(buildDefaultInputFromSchema(record.inputSchema)));
559
- setPlaygroundVisible(true);
560
- };
561
-
562
- const closePlayground = () => {
563
- stopPlaygroundPolling();
564
- setPlaygroundVisible(false);
565
- setPlaygroundPipeline(null);
566
- setPlaygroundJob(null);
567
- setPlaygroundRunning(false);
568
- };
569
-
570
- const runPlayground = async () => {
571
- if (!playgroundPipeline) return;
572
-
573
- let input: unknown;
574
- try {
575
- const parsedInput = playgroundInput.trim() ? JSON.parse(playgroundInput) : {};
576
- input = mergeDefaults(buildDefaultInputFromSchema(playgroundPipeline.inputSchema), parsedInput);
577
- setPlaygroundInputError('');
578
- } catch {
579
- setPlaygroundInputError(t('Invalid JSON input'));
580
- return;
581
- }
582
-
583
- stopPlaygroundPolling();
584
- setPlaygroundRunning(true);
585
- setPlaygroundJob(null);
586
-
587
- try {
588
- const res = await api.request({
589
- url: 'docUnderstanding:executePipeline',
590
- method: 'POST',
591
- data: {
592
- pipelineId: playgroundPipeline.id,
593
- input,
594
- },
595
- });
596
- const jobId = unwrapData<{ jobId?: number }>(res, {}).jobId;
597
- if (!jobId) {
598
- throw new Error(t('Pipeline did not return a job ID'));
599
- }
600
-
601
- const job = await fetchPlaygroundJob(jobId);
602
- if (!job || !TERMINAL_STATUSES.includes(job.status)) {
603
- startPlaygroundPolling(jobId);
604
- }
605
- message.success(`${t('Test job started')}: #${jobId}`);
606
- } catch (err: unknown) {
607
- setPlaygroundRunning(false);
608
- message.error(errorMessage(err) || t('Failed to run pipeline test'));
609
- }
610
- };
611
-
612
- const handleSave = async () => {
613
- try {
614
- const values = await form.validateFields();
615
-
616
- // Validate steps
617
- for (const step of steps) {
618
- if (!step.name) {
619
- message.error(t('All steps must have a name'));
620
- return;
621
- }
622
- if (!step.endpointId) {
623
- message.error(`${t('Step')} "${step.name || step.stepOrder}" ${t('must have an endpoint')}`);
624
- return;
625
- }
626
- }
627
-
628
- // Check alias uniqueness
629
- const aliases = steps.map((s) => s.outputAlias).filter(Boolean);
630
- if (new Set(aliases).size !== aliases.length) {
631
- message.error(t('Step output aliases must be unique'));
632
- return;
633
- }
634
-
635
- const payload = {
636
- ...values,
637
- steps: steps.map((s) => ({
638
- ...(s.id ? { id: s.id } : {}),
639
- stepOrder: s.stepOrder,
640
- name: s.name,
641
- endpointId: s.endpointId,
642
- inputMapping: s.inputMapping,
643
- outputAlias: s.outputAlias || undefined,
644
- condition: s.condition,
645
- onError: s.onError,
646
- retryCount: s.onError === 'retry' ? s.retryCount : 0,
647
- })),
648
- };
649
-
650
- if (editingId) {
651
- await api.request({
652
- url: 'docUnderstanding:updatePipeline',
653
- method: 'POST',
654
- params: { filterByTk: editingId },
655
- data: payload,
656
- });
657
- } else {
658
- await api.request({
659
- url: 'docUnderstanding:createPipeline',
660
- method: 'POST',
661
- data: payload,
662
- });
663
- }
664
- message.success(t('Saved'));
665
- setVisible(false);
666
- fetchData();
667
- } catch {
668
- // Form validation errors are already surfaced inline by antd.
669
- }
670
- };
671
-
672
- const columns: ColumnsType<PipelineDef> = [
673
- { title: t('Name'), dataIndex: 'name', width: 200 },
674
- {
675
- title: t('Steps'),
676
- dataIndex: 'steps',
677
- width: 300,
678
- render: (stepsArr: PipelineStepDef[]) => {
679
- if (!stepsArr || stepsArr.length === 0) return <Tag>0 {t('steps')}</Tag>;
680
- const sorted = [...stepsArr].sort((a, b) => a.stepOrder - b.stepOrder);
681
- return (
682
- <Space size={2} wrap>
683
- {sorted.map((s, i) => (
684
- <React.Fragment key={s.id}>
685
- {i > 0 && <span style={{ color: '#ccc' }}>&rarr;</span>}
686
- <Tag>{s.name || `${t('Step')} ${s.stepOrder}`}</Tag>
687
- </React.Fragment>
688
- ))}
689
- </Space>
690
- );
691
- },
692
- },
693
- {
694
- title: t('Enabled'),
695
- dataIndex: 'enabled',
696
- width: 80,
697
- render: (v: boolean) => (v ? <Tag color="success">{t('Yes')}</Tag> : <Tag>{t('No')}</Tag>),
698
- },
699
- {
700
- title: t('AI Tool'),
701
- width: 100,
702
- render: (_: unknown, record) =>
703
- record.enabled ? (
704
- <Tooltip
705
- title={`${t('Registered as')}: doc_understanding.${record.name?.toLowerCase().replace(/[^a-z0-9_]/g, '_')}`}
706
- >
707
- <Tag color="blue" icon={<ThunderboltOutlined />}>
708
- {t('Active')}
709
- </Tag>
710
- </Tooltip>
711
- ) : (
712
- <Tag>{t('Inactive')}</Tag>
713
- ),
714
- },
715
- {
716
- title: t('Action'),
717
- width: 190,
718
- render: (_: unknown, record) => (
719
- <Space>
720
- <Button
721
- type="link"
722
- size="small"
723
- icon={<PlayCircleOutlined />}
724
- disabled={!record.enabled}
725
- onClick={() => openPlayground(record)}
726
- aria-label={`${t('Test')} ${record.name}`}
727
- >
728
- {t('Test')}
729
- </Button>
730
- <Button
731
- type="link"
732
- size="small"
733
- icon={<EditOutlined />}
734
- onClick={() => openEdit(record)}
735
- aria-label={`${t('Edit')} ${record.name}`}
736
- >
737
- {t('Edit')}
738
- </Button>
739
- <Popconfirm title={t('Delete this pipeline?')} okText={t('Delete')} onConfirm={() => handleDelete(record.id)}>
740
- <Button
741
- type="link"
742
- size="small"
743
- danger
744
- icon={<DeleteOutlined />}
745
- aria-label={`${t('Delete')} ${record.name}`}
746
- >
747
- {t('Delete')}
748
- </Button>
749
- </Popconfirm>
750
- </Space>
751
- ),
752
- },
753
- ];
754
-
755
- return (
756
- <div>
757
- <div style={{ marginBottom: 16 }}>
758
- <Button type="primary" icon={<PlusOutlined />} onClick={openAdd}>
759
- {t('Add Pipeline')}
760
- </Button>
761
- </div>
762
- <Table rowKey="id" columns={columns} dataSource={pipelines} loading={loading} size="small" />
763
-
764
- <Modal
765
- title={editingId ? t('Edit Pipeline') : t('New Pipeline')}
766
- open={visible}
767
- onOk={handleSave}
768
- onCancel={() => setVisible(false)}
769
- okText={t('Save')}
770
- cancelText={t('Cancel')}
771
- width={800}
772
- destroyOnClose
773
- >
774
- <Form form={form} layout="vertical" preserve={false}>
775
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 16px' }}>
776
- <Form.Item name="name" label={t('Pipeline Name')} rules={[{ required: true }]}>
777
- <Input placeholder="full_document_processing" />
778
- </Form.Item>
779
- <Form.Item name="enabled" label={t('Enabled')} valuePropName="checked" initialValue={true}>
780
- <Switch />
781
- </Form.Item>
782
- </div>
783
- <Form.Item name="description" label={t('Description')}>
784
- <TextArea rows={2} placeholder={t('What this pipeline does')} />
785
- </Form.Item>
786
-
787
- <Card
788
- title={t('Pipeline Steps')}
789
- size="small"
790
- style={{ marginBottom: 16 }}
791
- extra={
792
- <Tag color="blue">
793
- {steps.length} {t('step(s)')}
794
- </Tag>
795
- }
796
- >
797
- <StepEditor steps={steps} endpoints={endpoints} onChange={setSteps} />
798
- </Card>
799
-
800
- <Collapse size="small" ghost>
801
- <Panel header={t('Advanced: Input Schema & Output Mapping')} key="advanced">
802
- <Form.Item
803
- name="inputSchema"
804
- label={t('Input Schema (JSON Schema)')}
805
- help={t('Defines what input this pipeline accepts. Used by AI tool schema.')}
806
- >
807
- <JsonEditor placeholder='{ "type": "object", "properties": { "document_url": { "type": "string" } }, "required": ["document_url"] }' />
808
- </Form.Item>
809
- <Form.Item
810
- name="outputMapping"
811
- label={t('Output Mapping (JSON)')}
812
- help={t('Map final step results to pipeline output. If empty, all step results are returned.')}
813
- >
814
- <JsonEditor placeholder='{ "text": "$step[ocr_result].response.text", "category": "$step[classify].response.category" }' />
815
- </Form.Item>
816
- </Panel>
817
- </Collapse>
818
- </Form>
819
- </Modal>
820
-
821
- <Modal
822
- title={playgroundPipeline ? `${t('Test Playground')}: ${playgroundPipeline.name}` : t('Test Playground')}
823
- open={playgroundVisible}
824
- onCancel={closePlayground}
825
- width={860}
826
- destroyOnClose
827
- footer={[
828
- <Button key="close" onClick={closePlayground}>
829
- {t('Close')}
830
- </Button>,
831
- playgroundJob?.id && (
832
- <Button
833
- key="refresh"
834
- icon={<ReloadOutlined />}
835
- disabled={playgroundRunning}
836
- onClick={() => fetchPlaygroundJob(playgroundJob.id)}
837
- >
838
- {t('Refresh')}
839
- </Button>
840
- ),
841
- <Button
842
- key="run"
843
- type="primary"
844
- icon={<PlayCircleOutlined />}
845
- loading={playgroundRunning}
846
- onClick={runPlayground}
847
- >
848
- {t('Run test')}
849
- </Button>,
850
- ].filter(Boolean)}
851
- >
852
- <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1fr)', gap: 16 }}>
853
- <div>
854
- <label htmlFor="playground-input" style={{ fontWeight: 500, marginBottom: 6, display: 'block' }}>
855
- {t('Input JSON')}
856
- </label>
857
- <TextArea
858
- id="playground-input"
859
- rows={16}
860
- value={playgroundInput}
861
- onChange={(e) => {
862
- setPlaygroundInput(e.target.value);
863
- if (playgroundInputError) setPlaygroundInputError('');
864
- }}
865
- placeholder='{ "document_url": "https://..." }'
866
- status={playgroundInputError ? 'error' : undefined}
867
- style={{ fontFamily: 'monospace', fontSize: 12 }}
868
- />
869
- {playgroundInputError && (
870
- <Alert type="error" showIcon message={playgroundInputError} style={{ marginTop: 8 }} />
871
- )}
872
-
873
- <Collapse size="small" ghost style={{ marginTop: 12 }}>
874
- <Panel header={t('Input Schema')} key="schema">
875
- <pre
876
- style={{
877
- background: '#f5f5f5',
878
- padding: 12,
879
- borderRadius: 6,
880
- fontSize: 12,
881
- maxHeight: 220,
882
- overflow: 'auto',
883
- }}
884
- >
885
- {stringifyJson(playgroundPipeline?.inputSchema)}
886
- </pre>
887
- </Panel>
888
- </Collapse>
889
- </div>
890
-
891
- <div>
892
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
893
- <span style={{ fontWeight: 500 }}>{t('Result')}</span>
894
- {playgroundJob?.status && (
895
- <Tag color={STATUS_COLORS[playgroundJob.status] || 'default'}>
896
- {statusLabels[playgroundJob.status] || playgroundJob.status}
897
- </Tag>
898
- )}
899
- </div>
900
-
901
- {!playgroundJob ? (
902
- <Empty description={t('Run a test to see job output')} imageStyle={{ height: 48 }} />
903
- ) : (
904
- <div>
905
- <Space style={{ marginBottom: 8 }} wrap>
906
- <Tag>
907
- {t('Job')} #{playgroundJob.id}
908
- </Tag>
909
- {playgroundJob.currentStep && (
910
- <Tag>
911
- {t('Step')} {playgroundJob.currentStep}
912
- </Tag>
913
- )}
914
- </Space>
915
-
916
- {playgroundJob.error && (
917
- <Alert
918
- type="error"
919
- showIcon
920
- message={t('Pipeline error')}
921
- description={<pre style={{ margin: 0, whiteSpace: 'pre-wrap' }}>{playgroundJob.error}</pre>}
922
- style={{ marginBottom: 12 }}
923
- />
924
- )}
925
-
926
- <div style={{ fontWeight: 500, marginBottom: 4 }}>{t('Final Result')}</div>
927
- <pre
928
- style={{
929
- background: '#f0f5ff',
930
- padding: 12,
931
- borderRadius: 6,
932
- fontSize: 12,
933
- maxHeight: 220,
934
- overflow: 'auto',
935
- }}
936
- >
937
- {playgroundJob.finalResult !== undefined && playgroundJob.finalResult !== null
938
- ? stringifyJson(playgroundJob.finalResult)
939
- : t('(not yet available)')}
940
- </pre>
941
-
942
- <div style={{ fontWeight: 500, margin: '12px 0 4px' }}>{t('Step Results')}</div>
943
- <pre
944
- style={{
945
- background: '#f5f5f5',
946
- padding: 12,
947
- borderRadius: 6,
948
- fontSize: 12,
949
- maxHeight: 260,
950
- overflow: 'auto',
951
- }}
952
- >
953
- {playgroundJob.stepResults ? stringifyJson(playgroundJob.stepResults) : '{}'}
954
- </pre>
955
- </div>
956
- )}
957
- </div>
958
- </div>
959
- </Modal>
960
- </div>
961
- );
962
- };
1
+ import React, { useEffect, useState, useCallback, useRef } from 'react';
2
+ import {
3
+ Table,
4
+ Button,
5
+ Modal,
6
+ Form,
7
+ Input,
8
+ Switch,
9
+ message,
10
+ Select,
11
+ InputNumber,
12
+ Card,
13
+ Space,
14
+ Tag,
15
+ Popconfirm,
16
+ Collapse,
17
+ Tooltip,
18
+ Empty,
19
+ Badge,
20
+ Alert,
21
+ } from 'antd';
22
+ import type { ColumnsType } from 'antd/es/table';
23
+ import {
24
+ PlusOutlined,
25
+ DeleteOutlined,
26
+ EditOutlined,
27
+ ArrowUpOutlined,
28
+ ArrowDownOutlined,
29
+ ThunderboltOutlined,
30
+ PlayCircleOutlined,
31
+ ReloadOutlined,
32
+ } from '@ant-design/icons';
33
+ import { useFlowContext } from '@nocobase/flow-engine';
34
+ import { useT } from '../locale';
35
+ import { EndpointDef, JobState, PipelineDef, PipelineStepDef, errorMessage, unwrapData } from '../types';
36
+
37
+ const { TextArea } = Input;
38
+ const { Panel } = Collapse;
39
+
40
+ const STATUS_COLORS: Record<string, string> = {
41
+ pending: 'default',
42
+ running: 'processing',
43
+ polling: 'processing',
44
+ completed: 'success',
45
+ failed: 'error',
46
+ timeout: 'error',
47
+ };
48
+
49
+ const TERMINAL_STATUSES = ['completed', 'failed', 'timeout'];
50
+
51
+ interface JsonSchemaNode {
52
+ type?: string;
53
+ properties?: Record<string, JsonSchemaNode>;
54
+ default?: unknown;
55
+ }
56
+
57
+ const isPlainObject = (value: unknown): value is Record<string, unknown> =>
58
+ !!value && typeof value === 'object' && !Array.isArray(value);
59
+
60
+ const stringifyJson = (value: unknown) => JSON.stringify(value ?? {}, null, 2);
61
+
62
+ const buildDefaultInputFromSchema = (schema: unknown): unknown => {
63
+ if (!isPlainObject(schema)) {
64
+ return {};
65
+ }
66
+
67
+ if (Object.prototype.hasOwnProperty.call(schema, 'default')) {
68
+ return schema.default;
69
+ }
70
+
71
+ const node = schema as JsonSchemaNode;
72
+
73
+ if (node.type === 'object' || node.properties) {
74
+ return Object.entries(node.properties || {}).reduce<Record<string, unknown>>((acc, [key, propertySchema]) => {
75
+ const value = buildDefaultInputFromSchema(propertySchema);
76
+ if (value !== undefined) {
77
+ acc[key] = value;
78
+ }
79
+ return acc;
80
+ }, {});
81
+ }
82
+
83
+ if (node.type === 'array') {
84
+ return [];
85
+ }
86
+
87
+ return undefined;
88
+ };
89
+
90
+ const mergeDefaults = (defaults: unknown, value: unknown): unknown => {
91
+ if (isPlainObject(defaults) && isPlainObject(value)) {
92
+ return Object.entries(defaults).reduce<Record<string, unknown>>(
93
+ (acc, [key, defaultValue]) => ({
94
+ ...acc,
95
+ [key]: mergeDefaults(defaultValue, acc[key]),
96
+ }),
97
+ { ...value },
98
+ );
99
+ }
100
+
101
+ return value === undefined ? defaults : value;
102
+ };
103
+
104
+ /* ─── JSON Editor ───────────────────────────────────────────────── */
105
+ const JsonEditor: React.FC<{
106
+ value?: unknown;
107
+ onChange?: (v: unknown) => void;
108
+ placeholder?: string;
109
+ rows?: number;
110
+ }> = ({ value, onChange, placeholder, rows = 5 }) => {
111
+ const t = useT();
112
+ const [text, setText] = useState('');
113
+ const [error, setError] = useState('');
114
+
115
+ useEffect(() => {
116
+ if (!value) {
117
+ setText('');
118
+ return;
119
+ }
120
+ try {
121
+ setText(typeof value === 'string' ? JSON.stringify(JSON.parse(value), null, 2) : JSON.stringify(value, null, 2));
122
+ } catch {
123
+ setText(typeof value === 'string' ? value : '');
124
+ }
125
+ }, [value]);
126
+
127
+ const handleBlur = () => {
128
+ if (!text.trim()) {
129
+ setError('');
130
+ onChange?.(null);
131
+ return;
132
+ }
133
+ try {
134
+ const parsed = JSON.parse(text);
135
+ setError('');
136
+ onChange?.(parsed);
137
+ } catch {
138
+ setError(t('Invalid JSON'));
139
+ }
140
+ };
141
+
142
+ return (
143
+ <div>
144
+ <TextArea
145
+ rows={rows}
146
+ value={text}
147
+ onChange={(e) => setText(e.target.value)}
148
+ onBlur={handleBlur}
149
+ placeholder={placeholder || '{}'}
150
+ status={error ? 'error' : undefined}
151
+ style={{ fontFamily: 'monospace', fontSize: 12 }}
152
+ />
153
+ {error && (
154
+ <div role="alert" style={{ color: '#ff4d4f', fontSize: 12 }}>
155
+ {error}
156
+ </div>
157
+ )}
158
+ </div>
159
+ );
160
+ };
161
+
162
+ /* ─── Step Editor ───────────────────────────────────────────────── */
163
+ type StepErrorMode = 'fail' | 'skip' | 'retry';
164
+
165
+ interface StepData {
166
+ _key: string; // client-side key for React
167
+ id?: number;
168
+ stepOrder: number;
169
+ name: string;
170
+ endpointId: number | null;
171
+ inputMapping: Record<string, unknown> | null;
172
+ outputAlias: string;
173
+ condition: unknown;
174
+ onError: StepErrorMode;
175
+ retryCount: number;
176
+ }
177
+
178
+ const emptyStep = (order: number): StepData => ({
179
+ _key: `new_${Date.now()}_${Math.random()}`,
180
+ stepOrder: order,
181
+ name: '',
182
+ endpointId: null,
183
+ inputMapping: null,
184
+ outputAlias: '',
185
+ condition: null,
186
+ onError: 'fail',
187
+ retryCount: 0,
188
+ });
189
+
190
+ const StepEditor: React.FC<{
191
+ steps: StepData[];
192
+ endpoints: EndpointDef[];
193
+ onChange: (steps: StepData[]) => void;
194
+ }> = ({ steps, endpoints, onChange }) => {
195
+ const t = useT();
196
+
197
+ const moveStep = (index: number, direction: -1 | 1) => {
198
+ const newSteps = [...steps];
199
+ const target = index + direction;
200
+ if (target < 0 || target >= newSteps.length) return;
201
+ [newSteps[index], newSteps[target]] = [newSteps[target], newSteps[index]];
202
+ // Recompute stepOrder
203
+ newSteps.forEach((s, i) => (s.stepOrder = i + 1));
204
+ onChange(newSteps);
205
+ };
206
+
207
+ const updateStep = <K extends keyof StepData>(index: number, field: K, value: StepData[K]) => {
208
+ const newSteps = [...steps];
209
+ newSteps[index] = { ...newSteps[index], [field]: value };
210
+ onChange(newSteps);
211
+ };
212
+
213
+ const removeStep = (index: number) => {
214
+ const newSteps = steps.filter((_, i) => i !== index);
215
+ newSteps.forEach((s, i) => (s.stepOrder = i + 1));
216
+ onChange(newSteps);
217
+ };
218
+
219
+ const addStep = () => {
220
+ onChange([...steps, emptyStep(steps.length + 1)]);
221
+ };
222
+
223
+ if (steps.length === 0) {
224
+ return (
225
+ <div style={{ textAlign: 'center', padding: '20px 0' }}>
226
+ <Empty description={t('No steps yet')} imageStyle={{ height: 40 }} />
227
+ <Button type="dashed" icon={<PlusOutlined />} onClick={addStep} style={{ marginTop: 8 }}>
228
+ {t('Add First Step')}
229
+ </Button>
230
+ </div>
231
+ );
232
+ }
233
+
234
+ return (
235
+ <div>
236
+ <Collapse size="small" defaultActiveKey={steps.map((s) => s._key)}>
237
+ {steps.map((step, index) => {
238
+ const ep = endpoints.find((e) => e.id === step.endpointId);
239
+ const headerExtra = (
240
+ <Space size={4} onClick={(e) => e.stopPropagation()}>
241
+ <Button
242
+ size="small"
243
+ disabled={index === 0}
244
+ icon={<ArrowUpOutlined />}
245
+ onClick={() => moveStep(index, -1)}
246
+ aria-label={t('Move step up')}
247
+ />
248
+ <Button
249
+ size="small"
250
+ disabled={index === steps.length - 1}
251
+ icon={<ArrowDownOutlined />}
252
+ onClick={() => moveStep(index, 1)}
253
+ aria-label={t('Move step down')}
254
+ />
255
+ <Popconfirm title={t('Remove step?')} okText={t('Delete')} onConfirm={() => removeStep(index)}>
256
+ <Button size="small" danger icon={<DeleteOutlined />} aria-label={t('Remove step?')} />
257
+ </Popconfirm>
258
+ </Space>
259
+ );
260
+
261
+ const label = (
262
+ <Space>
263
+ <Badge count={step.stepOrder} style={{ backgroundColor: '#1677ff' }} />
264
+ <span>{step.name || t('(unnamed)')}</span>
265
+ {ep && <Tag>{ep.name}</Tag>}
266
+ {step.onError === 'skip' && (
267
+ <Tooltip title={t('Step can be skipped on error')}>
268
+ <Tag color="orange">{t('skip on error')}</Tag>
269
+ </Tooltip>
270
+ )}
271
+ {step.condition && (
272
+ <Tooltip title={t('Has condition')}>
273
+ <Tag color="purple">{t('conditional')}</Tag>
274
+ </Tooltip>
275
+ )}
276
+ </Space>
277
+ );
278
+
279
+ const nameId = `step-name-${step._key}`;
280
+ const endpointId = `step-endpoint-${step._key}`;
281
+ const aliasId = `step-alias-${step._key}`;
282
+
283
+ return (
284
+ <Panel key={step._key} header={label} extra={headerExtra}>
285
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 16px' }}>
286
+ <div>
287
+ <label htmlFor={nameId} style={{ fontWeight: 500, display: 'block', marginBottom: 4 }}>
288
+ {t('Step Name')} *
289
+ </label>
290
+ <Input
291
+ id={nameId}
292
+ value={step.name}
293
+ onChange={(e) => updateStep(index, 'name', e.target.value)}
294
+ placeholder="OCR, Classify, Extract..."
295
+ />
296
+ </div>
297
+ <div>
298
+ <label htmlFor={endpointId} style={{ fontWeight: 500, display: 'block', marginBottom: 4 }}>
299
+ {t('Endpoint')} *
300
+ </label>
301
+ <Select
302
+ id={endpointId}
303
+ value={step.endpointId}
304
+ onChange={(v) => updateStep(index, 'endpointId', v)}
305
+ placeholder={t('Select endpoint')}
306
+ style={{ width: '100%' }}
307
+ options={endpoints.map((endpoint) => ({
308
+ value: endpoint.id,
309
+ label: `${endpoint.name} (${endpoint.method} ${endpoint.subpath})`,
310
+ }))}
311
+ />
312
+ </div>
313
+ <div>
314
+ <label
315
+ htmlFor={aliasId}
316
+ style={{ fontWeight: 500, display: 'block', marginBottom: 4, marginTop: 12 }}
317
+ >
318
+ {t('Output Alias')}
319
+ </label>
320
+ <Input
321
+ id={aliasId}
322
+ value={step.outputAlias}
323
+ onChange={(e) => updateStep(index, 'outputAlias', e.target.value)}
324
+ placeholder="ocr_result"
325
+ />
326
+ <div style={{ color: '#888', fontSize: 11 }}>
327
+ {t('Other steps reference this as')}: $step[{step.outputAlias || step.stepOrder}].response.field
328
+ </div>
329
+ </div>
330
+ <div>
331
+ <label style={{ fontWeight: 500, display: 'block', marginBottom: 4, marginTop: 12 }}>
332
+ {t('On Error')}
333
+ </label>
334
+ <Space>
335
+ <Select
336
+ value={step.onError}
337
+ onChange={(v: StepErrorMode) => updateStep(index, 'onError', v)}
338
+ style={{ width: 120 }}
339
+ aria-label={t('On Error')}
340
+ options={[
341
+ { value: 'fail', label: t('Fail') },
342
+ { value: 'skip', label: t('Skip') },
343
+ { value: 'retry', label: t('Retry') },
344
+ ]}
345
+ />
346
+ {step.onError === 'retry' && (
347
+ <InputNumber
348
+ value={step.retryCount}
349
+ onChange={(v) => updateStep(index, 'retryCount', v || 0)}
350
+ min={1}
351
+ max={10}
352
+ addonBefore="x"
353
+ style={{ width: 100 }}
354
+ aria-label={t('Retry')}
355
+ />
356
+ )}
357
+ </Space>
358
+ </div>
359
+ </div>
360
+
361
+ <div style={{ marginTop: 12 }}>
362
+ <label style={{ fontWeight: 500, display: 'block', marginBottom: 4 }}>
363
+ {t('Input Mapping (JSON)')}
364
+ <Tooltip
365
+ title={t(
366
+ 'Map endpoint input fields. Use $input.field, $step[alias].response.field, $files, or literal values.',
367
+ )}
368
+ >
369
+ <span style={{ fontWeight: 'normal', color: '#888', marginLeft: 6, cursor: 'help' }}>?</span>
370
+ </Tooltip>
371
+ </label>
372
+ <JsonEditor
373
+ value={step.inputMapping}
374
+ onChange={(v) => updateStep(index, 'inputMapping', v as Record<string, unknown> | null)}
375
+ placeholder='{ "text": "$step[ocr_result].response.text", "lang": "vi" }'
376
+ rows={3}
377
+ />
378
+ </div>
379
+
380
+ <div style={{ marginTop: 12 }}>
381
+ <label style={{ fontWeight: 500, display: 'block', marginBottom: 4 }}>
382
+ {t('Condition (optional JSON)')}
383
+ <Tooltip title={t('Only run this step if the condition matches.')}>
384
+ <span style={{ fontWeight: 'normal', color: '#888', marginLeft: 6, cursor: 'help' }}>?</span>
385
+ </Tooltip>
386
+ </label>
387
+ <JsonEditor
388
+ value={step.condition}
389
+ onChange={(v) => updateStep(index, 'condition', v)}
390
+ placeholder='{ "field": "$step[classify].response.type", "op": "eq", "value": "invoice" }'
391
+ rows={2}
392
+ />
393
+ </div>
394
+ </Panel>
395
+ );
396
+ })}
397
+ </Collapse>
398
+ <Button type="dashed" icon={<PlusOutlined />} onClick={addStep} style={{ marginTop: 8, width: '100%' }}>
399
+ {t('Add Step')}
400
+ </Button>
401
+ </div>
402
+ );
403
+ };
404
+
405
+ /* ─── Pipelines Tab ─────────────────────────────────────────────── */
406
+ interface PipelineFormValues {
407
+ name: string;
408
+ description?: string;
409
+ enabled: boolean;
410
+ inputSchema?: unknown;
411
+ outputMapping?: Record<string, unknown> | null;
412
+ }
413
+
414
+ export const PipelinesTab = () => {
415
+ const ctx = useFlowContext();
416
+ const api = ctx.api;
417
+ const t = useT();
418
+ const [pipelines, setPipelines] = useState<PipelineDef[]>([]);
419
+ const [endpoints, setEndpoints] = useState<EndpointDef[]>([]);
420
+ const [loading, setLoading] = useState(false);
421
+ const [visible, setVisible] = useState(false);
422
+ const [form] = Form.useForm<PipelineFormValues>();
423
+ const [editingId, setEditingId] = useState<number | null>(null);
424
+ const [steps, setSteps] = useState<StepData[]>([]);
425
+ const [playgroundVisible, setPlaygroundVisible] = useState(false);
426
+ const [playgroundPipeline, setPlaygroundPipeline] = useState<PipelineDef | null>(null);
427
+ const [playgroundInput, setPlaygroundInput] = useState('{}');
428
+ const [playgroundInputError, setPlaygroundInputError] = useState('');
429
+ const [playgroundJob, setPlaygroundJob] = useState<JobState | null>(null);
430
+ const [playgroundRunning, setPlaygroundRunning] = useState(false);
431
+ const playgroundTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
432
+
433
+ const statusLabels: Record<string, string> = {
434
+ pending: t('Pending'),
435
+ running: t('Running'),
436
+ polling: t('Polling'),
437
+ completed: t('Completed'),
438
+ failed: t('Failed'),
439
+ timeout: t('Timeout'),
440
+ };
441
+
442
+ const fetchData = useCallback(async () => {
443
+ setLoading(true);
444
+ try {
445
+ const [pRes, eRes] = await Promise.all([
446
+ api.request({ url: 'docUnderstanding:listPipelines' }),
447
+ api.request({ url: 'docUnderstanding:listEndpoints' }),
448
+ ]);
449
+ setPipelines(unwrapData<PipelineDef[]>(pRes, []));
450
+ setEndpoints(unwrapData<EndpointDef[]>(eRes, []));
451
+ } finally {
452
+ setLoading(false);
453
+ }
454
+ }, [api]);
455
+
456
+ useEffect(() => {
457
+ fetchData();
458
+ }, [fetchData]);
459
+
460
+ useEffect(() => {
461
+ return () => {
462
+ if (playgroundTimerRef.current) {
463
+ clearInterval(playgroundTimerRef.current);
464
+ }
465
+ };
466
+ }, []);
467
+
468
+ const openAdd = () => {
469
+ setEditingId(null);
470
+ form.resetFields();
471
+ setSteps([]);
472
+ setVisible(true);
473
+ };
474
+
475
+ const openEdit = (record: PipelineDef) => {
476
+ setEditingId(record.id);
477
+ form.setFieldsValue({
478
+ name: record.name,
479
+ description: record.description,
480
+ enabled: record.enabled,
481
+ inputSchema: record.inputSchema,
482
+ outputMapping: record.outputMapping,
483
+ });
484
+ // Convert steps from server format
485
+ const serverSteps = [...(record.steps || [])].sort((a, b) => a.stepOrder - b.stepOrder);
486
+ setSteps(
487
+ serverSteps.map((s) => ({
488
+ _key: `srv_${s.id}`,
489
+ id: s.id,
490
+ stepOrder: s.stepOrder,
491
+ name: s.name,
492
+ endpointId: s.endpointId,
493
+ inputMapping: s.inputMapping ?? null,
494
+ outputAlias: s.outputAlias || '',
495
+ condition: s.condition,
496
+ onError: s.onError || 'fail',
497
+ retryCount: s.retryCount || 0,
498
+ })),
499
+ );
500
+ setVisible(true);
501
+ };
502
+
503
+ const handleDelete = async (id: number) => {
504
+ await api.request({
505
+ url: 'docUnderstanding:deletePipeline',
506
+ method: 'POST',
507
+ params: { filterByTk: id },
508
+ });
509
+ message.success(t('Deleted'));
510
+ fetchData();
511
+ };
512
+
513
+ const stopPlaygroundPolling = useCallback(() => {
514
+ if (playgroundTimerRef.current) {
515
+ clearInterval(playgroundTimerRef.current);
516
+ playgroundTimerRef.current = null;
517
+ }
518
+ }, []);
519
+
520
+ const fetchPlaygroundJob = useCallback(
521
+ async (jobId: number) => {
522
+ const res = await api.request({
523
+ url: 'docUnderstanding:getJobStatus',
524
+ params: { filterByTk: jobId },
525
+ });
526
+ const job = unwrapData<JobState | null>(res, null);
527
+ setPlaygroundJob(job);
528
+
529
+ if (job && TERMINAL_STATUSES.includes(job.status)) {
530
+ stopPlaygroundPolling();
531
+ setPlaygroundRunning(false);
532
+ }
533
+ return job;
534
+ },
535
+ [api, stopPlaygroundPolling],
536
+ );
537
+
538
+ const startPlaygroundPolling = useCallback(
539
+ (jobId: number) => {
540
+ stopPlaygroundPolling();
541
+ playgroundTimerRef.current = setInterval(() => {
542
+ fetchPlaygroundJob(jobId).catch((err: unknown) => {
543
+ stopPlaygroundPolling();
544
+ setPlaygroundRunning(false);
545
+ message.error(errorMessage(err) || t('Failed to refresh test job'));
546
+ });
547
+ }, 1500);
548
+ },
549
+ [fetchPlaygroundJob, stopPlaygroundPolling, t],
550
+ );
551
+
552
+ const openPlayground = (record: PipelineDef) => {
553
+ stopPlaygroundPolling();
554
+ setPlaygroundPipeline(record);
555
+ setPlaygroundJob(null);
556
+ setPlaygroundRunning(false);
557
+ setPlaygroundInputError('');
558
+ setPlaygroundInput(stringifyJson(buildDefaultInputFromSchema(record.inputSchema)));
559
+ setPlaygroundVisible(true);
560
+ };
561
+
562
+ const closePlayground = () => {
563
+ stopPlaygroundPolling();
564
+ setPlaygroundVisible(false);
565
+ setPlaygroundPipeline(null);
566
+ setPlaygroundJob(null);
567
+ setPlaygroundRunning(false);
568
+ };
569
+
570
+ const runPlayground = async () => {
571
+ if (!playgroundPipeline) return;
572
+
573
+ let input: unknown;
574
+ try {
575
+ const parsedInput = playgroundInput.trim() ? JSON.parse(playgroundInput) : {};
576
+ input = mergeDefaults(buildDefaultInputFromSchema(playgroundPipeline.inputSchema), parsedInput);
577
+ setPlaygroundInputError('');
578
+ } catch {
579
+ setPlaygroundInputError(t('Invalid JSON input'));
580
+ return;
581
+ }
582
+
583
+ stopPlaygroundPolling();
584
+ setPlaygroundRunning(true);
585
+ setPlaygroundJob(null);
586
+
587
+ try {
588
+ const res = await api.request({
589
+ url: 'docUnderstanding:executePipeline',
590
+ method: 'POST',
591
+ data: {
592
+ pipelineId: playgroundPipeline.id,
593
+ input,
594
+ },
595
+ });
596
+ const jobId = unwrapData<{ jobId?: number }>(res, {}).jobId;
597
+ if (!jobId) {
598
+ throw new Error(t('Pipeline did not return a job ID'));
599
+ }
600
+
601
+ const job = await fetchPlaygroundJob(jobId);
602
+ if (!job || !TERMINAL_STATUSES.includes(job.status)) {
603
+ startPlaygroundPolling(jobId);
604
+ }
605
+ message.success(`${t('Test job started')}: #${jobId}`);
606
+ } catch (err: unknown) {
607
+ setPlaygroundRunning(false);
608
+ message.error(errorMessage(err) || t('Failed to run pipeline test'));
609
+ }
610
+ };
611
+
612
+ const handleSave = async () => {
613
+ try {
614
+ const values = await form.validateFields();
615
+
616
+ // Validate steps
617
+ for (const step of steps) {
618
+ if (!step.name) {
619
+ message.error(t('All steps must have a name'));
620
+ return;
621
+ }
622
+ if (!step.endpointId) {
623
+ message.error(`${t('Step')} "${step.name || step.stepOrder}" ${t('must have an endpoint')}`);
624
+ return;
625
+ }
626
+ }
627
+
628
+ // Check alias uniqueness
629
+ const aliases = steps.map((s) => s.outputAlias).filter(Boolean);
630
+ if (new Set(aliases).size !== aliases.length) {
631
+ message.error(t('Step output aliases must be unique'));
632
+ return;
633
+ }
634
+
635
+ const payload = {
636
+ ...values,
637
+ steps: steps.map((s) => ({
638
+ ...(s.id ? { id: s.id } : {}),
639
+ stepOrder: s.stepOrder,
640
+ name: s.name,
641
+ endpointId: s.endpointId,
642
+ inputMapping: s.inputMapping,
643
+ outputAlias: s.outputAlias || undefined,
644
+ condition: s.condition,
645
+ onError: s.onError,
646
+ retryCount: s.onError === 'retry' ? s.retryCount : 0,
647
+ })),
648
+ };
649
+
650
+ if (editingId) {
651
+ await api.request({
652
+ url: 'docUnderstanding:updatePipeline',
653
+ method: 'POST',
654
+ params: { filterByTk: editingId },
655
+ data: payload,
656
+ });
657
+ } else {
658
+ await api.request({
659
+ url: 'docUnderstanding:createPipeline',
660
+ method: 'POST',
661
+ data: payload,
662
+ });
663
+ }
664
+ message.success(t('Saved'));
665
+ setVisible(false);
666
+ fetchData();
667
+ } catch {
668
+ // Form validation errors are already surfaced inline by antd.
669
+ }
670
+ };
671
+
672
+ const columns: ColumnsType<PipelineDef> = [
673
+ { title: t('Name'), dataIndex: 'name', width: 200 },
674
+ {
675
+ title: t('Steps'),
676
+ dataIndex: 'steps',
677
+ width: 300,
678
+ render: (stepsArr: PipelineStepDef[]) => {
679
+ if (!stepsArr || stepsArr.length === 0) return <Tag>0 {t('steps')}</Tag>;
680
+ const sorted = [...stepsArr].sort((a, b) => a.stepOrder - b.stepOrder);
681
+ return (
682
+ <Space size={2} wrap>
683
+ {sorted.map((s, i) => (
684
+ <React.Fragment key={s.id}>
685
+ {i > 0 && <span style={{ color: '#ccc' }}>&rarr;</span>}
686
+ <Tag>{s.name || `${t('Step')} ${s.stepOrder}`}</Tag>
687
+ </React.Fragment>
688
+ ))}
689
+ </Space>
690
+ );
691
+ },
692
+ },
693
+ {
694
+ title: t('Enabled'),
695
+ dataIndex: 'enabled',
696
+ width: 80,
697
+ render: (v: boolean) => (v ? <Tag color="success">{t('Yes')}</Tag> : <Tag>{t('No')}</Tag>),
698
+ },
699
+ {
700
+ title: t('AI Tool'),
701
+ width: 100,
702
+ render: (_: unknown, record) =>
703
+ record.enabled ? (
704
+ <Tooltip
705
+ title={`${t('Registered as')}: doc_understanding.${record.name?.toLowerCase().replace(/[^a-z0-9_]/g, '_')}`}
706
+ >
707
+ <Tag color="blue" icon={<ThunderboltOutlined />}>
708
+ {t('Active')}
709
+ </Tag>
710
+ </Tooltip>
711
+ ) : (
712
+ <Tag>{t('Inactive')}</Tag>
713
+ ),
714
+ },
715
+ {
716
+ title: t('Action'),
717
+ width: 190,
718
+ render: (_: unknown, record) => (
719
+ <Space>
720
+ <Button
721
+ type="link"
722
+ size="small"
723
+ icon={<PlayCircleOutlined />}
724
+ disabled={!record.enabled}
725
+ onClick={() => openPlayground(record)}
726
+ aria-label={`${t('Test')} ${record.name}`}
727
+ >
728
+ {t('Test')}
729
+ </Button>
730
+ <Button
731
+ type="link"
732
+ size="small"
733
+ icon={<EditOutlined />}
734
+ onClick={() => openEdit(record)}
735
+ aria-label={`${t('Edit')} ${record.name}`}
736
+ >
737
+ {t('Edit')}
738
+ </Button>
739
+ <Popconfirm title={t('Delete this pipeline?')} okText={t('Delete')} onConfirm={() => handleDelete(record.id)}>
740
+ <Button
741
+ type="link"
742
+ size="small"
743
+ danger
744
+ icon={<DeleteOutlined />}
745
+ aria-label={`${t('Delete')} ${record.name}`}
746
+ >
747
+ {t('Delete')}
748
+ </Button>
749
+ </Popconfirm>
750
+ </Space>
751
+ ),
752
+ },
753
+ ];
754
+
755
+ return (
756
+ <div>
757
+ <div style={{ marginBottom: 16 }}>
758
+ <Button type="primary" icon={<PlusOutlined />} onClick={openAdd}>
759
+ {t('Add Pipeline')}
760
+ </Button>
761
+ </div>
762
+ <Table rowKey="id" columns={columns} dataSource={pipelines} loading={loading} size="small" />
763
+
764
+ <Modal
765
+ title={editingId ? t('Edit Pipeline') : t('New Pipeline')}
766
+ open={visible}
767
+ onOk={handleSave}
768
+ onCancel={() => setVisible(false)}
769
+ okText={t('Save')}
770
+ cancelText={t('Cancel')}
771
+ width={800}
772
+ destroyOnClose
773
+ >
774
+ <Form form={form} layout="vertical" preserve={false}>
775
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 16px' }}>
776
+ <Form.Item name="name" label={t('Pipeline Name')} rules={[{ required: true }]}>
777
+ <Input placeholder="full_document_processing" />
778
+ </Form.Item>
779
+ <Form.Item name="enabled" label={t('Enabled')} valuePropName="checked" initialValue={true}>
780
+ <Switch />
781
+ </Form.Item>
782
+ </div>
783
+ <Form.Item name="description" label={t('Description')}>
784
+ <TextArea rows={2} placeholder={t('What this pipeline does')} />
785
+ </Form.Item>
786
+
787
+ <Card
788
+ title={t('Pipeline Steps')}
789
+ size="small"
790
+ style={{ marginBottom: 16 }}
791
+ extra={
792
+ <Tag color="blue">
793
+ {steps.length} {t('step(s)')}
794
+ </Tag>
795
+ }
796
+ >
797
+ <StepEditor steps={steps} endpoints={endpoints} onChange={setSteps} />
798
+ </Card>
799
+
800
+ <Collapse size="small" ghost>
801
+ <Panel header={t('Advanced: Input Schema & Output Mapping')} key="advanced">
802
+ <Form.Item
803
+ name="inputSchema"
804
+ label={t('Input Schema (JSON Schema)')}
805
+ help={t('Defines what input this pipeline accepts. Used by AI tool schema.')}
806
+ >
807
+ <JsonEditor placeholder='{ "type": "object", "properties": { "document_url": { "type": "string" } }, "required": ["document_url"] }' />
808
+ </Form.Item>
809
+ <Form.Item
810
+ name="outputMapping"
811
+ label={t('Output Mapping (JSON)')}
812
+ help={t('Map final step results to pipeline output. If empty, all step results are returned.')}
813
+ >
814
+ <JsonEditor placeholder='{ "text": "$step[ocr_result].response.text", "category": "$step[classify].response.category" }' />
815
+ </Form.Item>
816
+ </Panel>
817
+ </Collapse>
818
+ </Form>
819
+ </Modal>
820
+
821
+ <Modal
822
+ title={playgroundPipeline ? `${t('Test Playground')}: ${playgroundPipeline.name}` : t('Test Playground')}
823
+ open={playgroundVisible}
824
+ onCancel={closePlayground}
825
+ width={860}
826
+ destroyOnClose
827
+ footer={[
828
+ <Button key="close" onClick={closePlayground}>
829
+ {t('Close')}
830
+ </Button>,
831
+ playgroundJob?.id && (
832
+ <Button
833
+ key="refresh"
834
+ icon={<ReloadOutlined />}
835
+ disabled={playgroundRunning}
836
+ onClick={() => fetchPlaygroundJob(playgroundJob.id)}
837
+ >
838
+ {t('Refresh')}
839
+ </Button>
840
+ ),
841
+ <Button
842
+ key="run"
843
+ type="primary"
844
+ icon={<PlayCircleOutlined />}
845
+ loading={playgroundRunning}
846
+ onClick={runPlayground}
847
+ >
848
+ {t('Run test')}
849
+ </Button>,
850
+ ].filter(Boolean)}
851
+ >
852
+ <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1fr)', gap: 16 }}>
853
+ <div>
854
+ <label htmlFor="playground-input" style={{ fontWeight: 500, marginBottom: 6, display: 'block' }}>
855
+ {t('Input JSON')}
856
+ </label>
857
+ <TextArea
858
+ id="playground-input"
859
+ rows={16}
860
+ value={playgroundInput}
861
+ onChange={(e) => {
862
+ setPlaygroundInput(e.target.value);
863
+ if (playgroundInputError) setPlaygroundInputError('');
864
+ }}
865
+ placeholder='{ "document_url": "https://..." }'
866
+ status={playgroundInputError ? 'error' : undefined}
867
+ style={{ fontFamily: 'monospace', fontSize: 12 }}
868
+ />
869
+ {playgroundInputError && (
870
+ <Alert type="error" showIcon message={playgroundInputError} style={{ marginTop: 8 }} />
871
+ )}
872
+
873
+ <Collapse size="small" ghost style={{ marginTop: 12 }}>
874
+ <Panel header={t('Input Schema')} key="schema">
875
+ <pre
876
+ style={{
877
+ background: '#f5f5f5',
878
+ padding: 12,
879
+ borderRadius: 6,
880
+ fontSize: 12,
881
+ maxHeight: 220,
882
+ overflow: 'auto',
883
+ }}
884
+ >
885
+ {stringifyJson(playgroundPipeline?.inputSchema)}
886
+ </pre>
887
+ </Panel>
888
+ </Collapse>
889
+ </div>
890
+
891
+ <div>
892
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
893
+ <span style={{ fontWeight: 500 }}>{t('Result')}</span>
894
+ {playgroundJob?.status && (
895
+ <Tag color={STATUS_COLORS[playgroundJob.status] || 'default'}>
896
+ {statusLabels[playgroundJob.status] || playgroundJob.status}
897
+ </Tag>
898
+ )}
899
+ </div>
900
+
901
+ {!playgroundJob ? (
902
+ <Empty description={t('Run a test to see job output')} imageStyle={{ height: 48 }} />
903
+ ) : (
904
+ <div>
905
+ <Space style={{ marginBottom: 8 }} wrap>
906
+ <Tag>
907
+ {t('Job')} #{playgroundJob.id}
908
+ </Tag>
909
+ {playgroundJob.currentStep && (
910
+ <Tag>
911
+ {t('Step')} {playgroundJob.currentStep}
912
+ </Tag>
913
+ )}
914
+ </Space>
915
+
916
+ {playgroundJob.error && (
917
+ <Alert
918
+ type="error"
919
+ showIcon
920
+ message={t('Pipeline error')}
921
+ description={<pre style={{ margin: 0, whiteSpace: 'pre-wrap' }}>{playgroundJob.error}</pre>}
922
+ style={{ marginBottom: 12 }}
923
+ />
924
+ )}
925
+
926
+ <div style={{ fontWeight: 500, marginBottom: 4 }}>{t('Final Result')}</div>
927
+ <pre
928
+ style={{
929
+ background: '#f0f5ff',
930
+ padding: 12,
931
+ borderRadius: 6,
932
+ fontSize: 12,
933
+ maxHeight: 220,
934
+ overflow: 'auto',
935
+ }}
936
+ >
937
+ {playgroundJob.finalResult !== undefined && playgroundJob.finalResult !== null
938
+ ? stringifyJson(playgroundJob.finalResult)
939
+ : t('(not yet available)')}
940
+ </pre>
941
+
942
+ <div style={{ fontWeight: 500, margin: '12px 0 4px' }}>{t('Step Results')}</div>
943
+ <pre
944
+ style={{
945
+ background: '#f5f5f5',
946
+ padding: 12,
947
+ borderRadius: 6,
948
+ fontSize: 12,
949
+ maxHeight: 260,
950
+ overflow: 'auto',
951
+ }}
952
+ >
953
+ {playgroundJob.stepResults ? stringifyJson(playgroundJob.stepResults) : '{}'}
954
+ </pre>
955
+ </div>
956
+ )}
957
+ </div>
958
+ </div>
959
+ </Modal>
960
+ </div>
961
+ );
962
+ };