plugin-document-understanding 1.1.2 → 1.1.4

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