plugin-document-understanding 1.1.9 → 1.1.12
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.
- package/dist/client/345.17f88ffb846ec69b.js +10 -0
- package/dist/client/index.js +1 -1
- package/dist/client-v2/345.1e0c321d30702aa1.js +10 -0
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +7 -7
- package/dist/locale/en-US.json +171 -121
- package/dist/locale/vi-VN.json +171 -121
- package/dist/locale/zh-CN.json +171 -1
- package/dist/node_modules/form-data/lib/form_data.js +3 -3
- package/dist/node_modules/form-data/package.json +1 -1
- package/dist/server/collections/jobs.js +13 -0
- package/dist/server/services/AsyncJobManager.js +87 -31
- package/dist/server/services/DocumentUnderstandingService.js +48 -5
- package/dist/server/services/PipelineExecutor.js +66 -29
- package/package.json +46 -49
- package/src/client/index.tsx +7 -1
- package/src/client-v2/components/EndpointsTab.tsx +177 -108
- package/src/client-v2/components/JobsTab.tsx +94 -59
- package/src/client-v2/components/PipelinesTab.tsx +244 -154
- package/src/client-v2/components/PluginSettings.tsx +2 -0
- package/src/client-v2/components/ServiceConfigTab.tsx +56 -39
- package/src/client-v2/types.ts +32 -0
- package/src/locale/en-US.json +171 -121
- package/src/locale/vi-VN.json +171 -121
- package/src/locale/zh-CN.json +171 -1
- package/src/server/__tests__/cluster-safety.test.ts +259 -0
- package/src/server/__tests__/document-understanding-service.test.ts +13 -2
- package/src/server/__tests__/pipeline-executor.test.ts +55 -55
- package/src/server/actions.ts +176 -176
- package/src/server/collections/jobs.ts +13 -0
- package/src/server/plugin.ts +134 -134
- package/src/server/services/AsyncJobManager.ts +98 -32
- package/src/server/services/DocumentUnderstandingService.ts +52 -4
- package/src/server/services/PipelineExecutor.ts +79 -32
- package/src/server/types.ts +2 -0
- package/dist/client-v2/794.9b984a25b2fc7c14.js +0 -10
|
@@ -1,11 +1,24 @@
|
|
|
1
1
|
import { Database } from '@nocobase/database';
|
|
2
2
|
import { ExternalApiClient } from './ExternalApiClient';
|
|
3
|
-
import { EndpointDef
|
|
3
|
+
import { EndpointDef } from '../types';
|
|
4
4
|
|
|
5
5
|
interface LoggerLike {
|
|
6
6
|
warn: (...args: unknown[]) => void;
|
|
7
7
|
}
|
|
8
8
|
|
|
9
|
+
// Lease for inline (pending/running) execution. Refreshed at the start of every
|
|
10
|
+
// pipeline step; must outlive the slowest step (endpoint timeout x retries).
|
|
11
|
+
export const JOB_RUN_LEASE_MS = 10 * 60 * 1000;
|
|
12
|
+
// Lease for polling jobs. Refreshed on every poll tick, so it only needs to
|
|
13
|
+
// outlive a few missed ticks before another node may adopt the job.
|
|
14
|
+
const JOB_POLL_LEASE_MIN_MS = 60 * 1000;
|
|
15
|
+
|
|
16
|
+
export function pollLeaseMs(pollInterval?: number): number {
|
|
17
|
+
return Math.max((pollInterval || 5000) * 3, JOB_POLL_LEASE_MIN_MS);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const JOBS_COLLECTION = 'doc_understanding_jobs';
|
|
21
|
+
|
|
9
22
|
export class AsyncJobManager {
|
|
10
23
|
private db: Database;
|
|
11
24
|
private apiClient: ExternalApiClient;
|
|
@@ -13,6 +26,7 @@ export class AsyncJobManager {
|
|
|
13
26
|
private onJobComplete: (jobId: number, result: any) => Promise<void>;
|
|
14
27
|
private onJobError: (jobId: number, error: string) => Promise<void>;
|
|
15
28
|
private logger: LoggerLike;
|
|
29
|
+
private nodeId: string;
|
|
16
30
|
|
|
17
31
|
constructor(
|
|
18
32
|
db: Database,
|
|
@@ -22,12 +36,14 @@ export class AsyncJobManager {
|
|
|
22
36
|
onJobError: (jobId: number, error: string) => Promise<void>;
|
|
23
37
|
},
|
|
24
38
|
logger: LoggerLike,
|
|
39
|
+
nodeId: string,
|
|
25
40
|
) {
|
|
26
41
|
this.db = db;
|
|
27
42
|
this.apiClient = apiClient;
|
|
28
43
|
this.onJobComplete = callbacks.onJobComplete;
|
|
29
44
|
this.onJobError = callbacks.onJobError;
|
|
30
45
|
this.logger = logger;
|
|
46
|
+
this.nodeId = nodeId;
|
|
31
47
|
}
|
|
32
48
|
|
|
33
49
|
async startPolling(
|
|
@@ -52,8 +68,16 @@ export class AsyncJobManager {
|
|
|
52
68
|
return;
|
|
53
69
|
}
|
|
54
70
|
|
|
71
|
+
// Renew our lease; if the row no longer matches (job finished, or another
|
|
72
|
+
// node adopted it after our lease expired) stop polling immediately.
|
|
73
|
+
if (!(await this.refreshLease(jobId, endpoint))) {
|
|
74
|
+
this.stopPolling(jobId);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
|
|
55
78
|
const pollResultSubpath = endpoint.pollResultSubpath;
|
|
56
79
|
if (!pollResultSubpath) {
|
|
80
|
+
this.stopPolling(jobId);
|
|
57
81
|
await this.onJobError(jobId, 'Polling result subpath is not configured');
|
|
58
82
|
return;
|
|
59
83
|
}
|
|
@@ -95,61 +119,103 @@ export class AsyncJobManager {
|
|
|
95
119
|
this.intervals.set(jobId, timer);
|
|
96
120
|
}
|
|
97
121
|
|
|
122
|
+
private async refreshLease(jobId: number, endpoint: EndpointDef): Promise<boolean> {
|
|
123
|
+
const jobsRepo = this.db.getRepository<any>(JOBS_COLLECTION);
|
|
124
|
+
const updated = await jobsRepo.update({
|
|
125
|
+
filter: { id: jobId, status: 'polling', ownedBy: this.nodeId },
|
|
126
|
+
values: { leaseExpiresAt: new Date(Date.now() + pollLeaseMs(endpoint.pollInterval)) },
|
|
127
|
+
});
|
|
128
|
+
return Array.isArray(updated) ? updated.length > 0 : Boolean(updated);
|
|
129
|
+
}
|
|
130
|
+
|
|
98
131
|
/**
|
|
99
|
-
*
|
|
132
|
+
* Fail pending/running jobs that can no longer be executing. First the jobs
|
|
133
|
+
* this node owned (in-memory execution state is lost across a restart), then
|
|
134
|
+
* any remaining job whose owner lease expired. Rows without a lease predate
|
|
135
|
+
* ownership tracking and are treated as orphaned too.
|
|
100
136
|
*/
|
|
101
|
-
async
|
|
102
|
-
const jobsRepo = this.db.getRepository<any>(
|
|
103
|
-
const
|
|
137
|
+
async failOrphanedActiveJobs(): Promise<void> {
|
|
138
|
+
const jobsRepo = this.db.getRepository<any>(JOBS_COLLECTION);
|
|
139
|
+
const now = new Date();
|
|
140
|
+
|
|
141
|
+
await jobsRepo.update({
|
|
142
|
+
filter: { status: { $in: ['pending', 'running'] }, ownedBy: this.nodeId },
|
|
143
|
+
values: { status: 'failed', error: 'Server restarted during execution', completedAt: now },
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
await jobsRepo.update({
|
|
104
147
|
filter: {
|
|
105
|
-
status: ['pending', 'running'],
|
|
148
|
+
status: { $in: ['pending', 'running'] },
|
|
149
|
+
$or: [{ leaseExpiresAt: { $lt: now } }, { leaseExpiresAt: null }],
|
|
106
150
|
},
|
|
151
|
+
values: { status: 'failed', error: 'Job lease expired before completion', completedAt: now },
|
|
107
152
|
});
|
|
108
|
-
|
|
109
|
-
for (const job of stuckJobs) {
|
|
110
|
-
await jobsRepo.update({
|
|
111
|
-
filterByTk: job.id,
|
|
112
|
-
values: {
|
|
113
|
-
status: 'failed',
|
|
114
|
-
error: 'Server restarted during execution',
|
|
115
|
-
completedAt: new Date(),
|
|
116
|
-
},
|
|
117
|
-
});
|
|
118
|
-
}
|
|
119
153
|
}
|
|
120
154
|
|
|
121
155
|
/**
|
|
122
|
-
*
|
|
123
|
-
*
|
|
156
|
+
* Re-adopt 'polling' jobs whose owner can no longer be polling them: jobs this
|
|
157
|
+
* node owned before a restart, jobs whose lease expired, and legacy rows without
|
|
158
|
+
* ownership. Webhook-mode jobs are skipped — nothing polls them, and any node
|
|
159
|
+
* can process the webhook when it arrives.
|
|
124
160
|
*/
|
|
125
|
-
async
|
|
126
|
-
const jobsRepo = this.db.getRepository<any>(
|
|
127
|
-
const
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
161
|
+
async adoptOrphanedPollingJobs(): Promise<void> {
|
|
162
|
+
const jobsRepo = this.db.getRepository<any>(JOBS_COLLECTION);
|
|
163
|
+
const now = new Date();
|
|
164
|
+
const candidates = await jobsRepo.find({
|
|
165
|
+
filter: {
|
|
166
|
+
status: 'polling',
|
|
167
|
+
$or: [{ ownedBy: this.nodeId }, { leaseExpiresAt: { $lt: now } }, { ownedBy: null }],
|
|
168
|
+
},
|
|
169
|
+
});
|
|
131
170
|
|
|
132
|
-
|
|
133
|
-
const
|
|
134
|
-
const
|
|
171
|
+
for (const job of candidates) {
|
|
172
|
+
const externalTaskIds = (job.externalTaskIds || {}) as Record<string, string>;
|
|
173
|
+
const stepKey = String(job.currentStep);
|
|
174
|
+
const taskId = externalTaskIds[stepKey];
|
|
135
175
|
if (!taskId) continue;
|
|
136
176
|
|
|
137
|
-
// We need the endpoint definition for this step
|
|
138
177
|
const pipelineRepo = this.db.getRepository('doc_understanding_pipelines');
|
|
139
178
|
const pipeline = await pipelineRepo.findOne({
|
|
140
179
|
filter: { id: job.pipelineId },
|
|
141
180
|
appends: ['steps', 'steps.endpoint'],
|
|
142
181
|
});
|
|
143
|
-
|
|
144
182
|
if (!pipeline) continue;
|
|
145
183
|
|
|
146
|
-
const
|
|
184
|
+
const steps = ((pipeline as any).steps || []) as Array<{ stepOrder: number; endpoint?: EndpointDef }>;
|
|
185
|
+
const step = steps.find((s) => s.stepOrder === job.currentStep);
|
|
147
186
|
if (!step?.endpoint || step.endpoint.executionMode !== 'polling') continue;
|
|
148
187
|
|
|
149
|
-
await this.
|
|
188
|
+
if (await this.claimJobForPolling(job.id, step.endpoint)) {
|
|
189
|
+
await this.startPolling(job.id, step.endpoint, taskId);
|
|
190
|
+
}
|
|
150
191
|
}
|
|
151
192
|
}
|
|
152
193
|
|
|
194
|
+
private async claimJobForPolling(jobId: number, endpoint: EndpointDef): Promise<boolean> {
|
|
195
|
+
return this.db.sequelize.transaction(async (transaction: { LOCK: { UPDATE: string } }): Promise<boolean> => {
|
|
196
|
+
const jobsRepo = this.db.getRepository<any>(JOBS_COLLECTION);
|
|
197
|
+
const row = await jobsRepo.findOne({ filterByTk: jobId, transaction, lock: transaction.LOCK.UPDATE });
|
|
198
|
+
if (!row) return false;
|
|
199
|
+
if (String(row.get('status')) !== 'polling') return false;
|
|
200
|
+
|
|
201
|
+
const owner = row.get('ownedBy') as string | null;
|
|
202
|
+
const lease = row.get('leaseExpiresAt') as Date | string | null;
|
|
203
|
+
const leaseValid = lease != null && new Date(lease).getTime() > Date.now();
|
|
204
|
+
// A different node still owns the job with a valid lease: leave it alone.
|
|
205
|
+
if (owner !== this.nodeId && leaseValid) return false;
|
|
206
|
+
|
|
207
|
+
await jobsRepo.update({
|
|
208
|
+
filterByTk: jobId,
|
|
209
|
+
values: {
|
|
210
|
+
ownedBy: this.nodeId,
|
|
211
|
+
leaseExpiresAt: new Date(Date.now() + pollLeaseMs(endpoint.pollInterval)),
|
|
212
|
+
},
|
|
213
|
+
transaction,
|
|
214
|
+
});
|
|
215
|
+
return true;
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
|
|
153
219
|
stopPolling(jobId: number) {
|
|
154
220
|
const timer = this.intervals.get(jobId);
|
|
155
221
|
if (timer) {
|
|
@@ -15,11 +15,17 @@ export class DocumentUnderstandingService {
|
|
|
15
15
|
private initialized = false;
|
|
16
16
|
private startupRecoveryCompleted = false;
|
|
17
17
|
private initializationPromise?: Promise<void>;
|
|
18
|
+
private maintenanceTimer?: NodeJS.Timeout;
|
|
19
|
+
// Unique per process; used as the job owner so other nodes can tell orphaned
|
|
20
|
+
// jobs apart from jobs that are still being processed.
|
|
21
|
+
private readonly nodeId: string;
|
|
18
22
|
private static readonly HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
23
|
+
private static readonly MAINTENANCE_INTERVAL_MS = 30_000;
|
|
19
24
|
|
|
20
25
|
constructor(app: Application, db: Database) {
|
|
21
26
|
this.app = app;
|
|
22
27
|
this.db = db;
|
|
28
|
+
this.nodeId = `${app?.name || 'app'}:${process.pid}:${crypto.randomUUID()}`;
|
|
23
29
|
}
|
|
24
30
|
|
|
25
31
|
async initialize(options: { recoverJobs?: boolean } = {}): Promise<void> {
|
|
@@ -43,6 +49,7 @@ export class DocumentUnderstandingService {
|
|
|
43
49
|
const config = await this.ensureConfig();
|
|
44
50
|
|
|
45
51
|
this.jobManager?.destroy();
|
|
52
|
+
this.stopMaintenance();
|
|
46
53
|
this.apiClient = new ExternalApiClient(config);
|
|
47
54
|
this.jobManager = new AsyncJobManager(
|
|
48
55
|
this.db,
|
|
@@ -60,19 +67,57 @@ export class DocumentUnderstandingService {
|
|
|
60
67
|
},
|
|
61
68
|
},
|
|
62
69
|
this.app.logger,
|
|
70
|
+
this.nodeId,
|
|
63
71
|
);
|
|
64
72
|
|
|
65
|
-
this.pipelineExecutor = new PipelineExecutor(
|
|
73
|
+
this.pipelineExecutor = new PipelineExecutor(
|
|
74
|
+
this.db,
|
|
75
|
+
this.apiClient,
|
|
76
|
+
this.jobManager,
|
|
77
|
+
this.app.logger,
|
|
78
|
+
this.nodeId,
|
|
79
|
+
);
|
|
66
80
|
|
|
67
81
|
if (recoverJobs && !this.startupRecoveryCompleted) {
|
|
68
|
-
await this.
|
|
69
|
-
await this.jobManager.recoverPollingJobs();
|
|
82
|
+
await this.maintainJobs();
|
|
70
83
|
this.startupRecoveryCompleted = true;
|
|
71
84
|
}
|
|
85
|
+
this.startMaintenance();
|
|
72
86
|
|
|
73
87
|
this.initialized = true;
|
|
74
88
|
}
|
|
75
89
|
|
|
90
|
+
/**
|
|
91
|
+
* Cluster maintenance sweep: fails active jobs whose owner is gone and
|
|
92
|
+
* re-adopts orphaned polling jobs. Safe to run on every node — all state
|
|
93
|
+
* transitions are guarded by ownership checks and row-level claims.
|
|
94
|
+
*/
|
|
95
|
+
async maintainJobs(): Promise<void> {
|
|
96
|
+
if (!this.jobManager) return;
|
|
97
|
+
try {
|
|
98
|
+
await this.jobManager.failOrphanedActiveJobs();
|
|
99
|
+
await this.jobManager.adoptOrphanedPollingJobs();
|
|
100
|
+
} catch (err) {
|
|
101
|
+
this.app.logger.warn('Document Understanding: job maintenance sweep failed.', err);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
private startMaintenance(): void {
|
|
106
|
+
this.stopMaintenance();
|
|
107
|
+
this.maintenanceTimer = setInterval(() => {
|
|
108
|
+
this.maintainJobs();
|
|
109
|
+
}, DocumentUnderstandingService.MAINTENANCE_INTERVAL_MS);
|
|
110
|
+
// The sweep must never keep the process alive on shutdown.
|
|
111
|
+
this.maintenanceTimer.unref?.();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
private stopMaintenance(): void {
|
|
115
|
+
if (this.maintenanceTimer) {
|
|
116
|
+
clearInterval(this.maintenanceTimer);
|
|
117
|
+
this.maintenanceTimer = undefined;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
76
121
|
private async ensureConfig(): Promise<ServiceConfig> {
|
|
77
122
|
const configRepo = this.db.getRepository<any>('doc_understanding_config');
|
|
78
123
|
let config = await configRepo.findOne();
|
|
@@ -90,7 +135,9 @@ export class DocumentUnderstandingService {
|
|
|
90
135
|
});
|
|
91
136
|
}
|
|
92
137
|
|
|
93
|
-
|
|
138
|
+
// Attributes live on the Sequelize model prototype, so callers that spread the
|
|
139
|
+
// result would otherwise get an object with none of the config fields.
|
|
140
|
+
return config.toJSON();
|
|
94
141
|
}
|
|
95
142
|
|
|
96
143
|
isReady(): boolean {
|
|
@@ -124,6 +171,7 @@ export class DocumentUnderstandingService {
|
|
|
124
171
|
}
|
|
125
172
|
|
|
126
173
|
destroy(): void {
|
|
174
|
+
this.stopMaintenance();
|
|
127
175
|
this.jobManager?.destroy();
|
|
128
176
|
this.initialized = false;
|
|
129
177
|
this.startupRecoveryCompleted = false;
|
|
@@ -3,7 +3,7 @@ import { basename, resolve, sep } from 'path';
|
|
|
3
3
|
import { Database } from '@nocobase/database';
|
|
4
4
|
import mime from 'mime-types';
|
|
5
5
|
import { ExternalApiClient, FileInput } from './ExternalApiClient';
|
|
6
|
-
import { AsyncJobManager } from './AsyncJobManager';
|
|
6
|
+
import { AsyncJobManager, JOB_RUN_LEASE_MS, pollLeaseMs } from './AsyncJobManager';
|
|
7
7
|
import { PipelineDef, PipelineStepDef, JobState, EndpointDef } from '../types';
|
|
8
8
|
|
|
9
9
|
interface LoggerLike {
|
|
@@ -74,12 +74,20 @@ export class PipelineExecutor {
|
|
|
74
74
|
private apiClient: ExternalApiClient;
|
|
75
75
|
private jobManager: AsyncJobManager;
|
|
76
76
|
private logger: LoggerLike;
|
|
77
|
-
|
|
78
|
-
|
|
77
|
+
private nodeId: string;
|
|
78
|
+
|
|
79
|
+
constructor(
|
|
80
|
+
db: Database,
|
|
81
|
+
apiClient: ExternalApiClient,
|
|
82
|
+
jobManager: AsyncJobManager,
|
|
83
|
+
logger: LoggerLike,
|
|
84
|
+
nodeId = '',
|
|
85
|
+
) {
|
|
79
86
|
this.db = db;
|
|
80
87
|
this.apiClient = apiClient;
|
|
81
88
|
this.jobManager = jobManager;
|
|
82
89
|
this.logger = logger;
|
|
90
|
+
this.nodeId = nodeId;
|
|
83
91
|
}
|
|
84
92
|
|
|
85
93
|
private async resolveFile(urlOrPath: string, fieldName = 'file'): Promise<FileInput | null> {
|
|
@@ -140,6 +148,8 @@ export class PipelineExecutor {
|
|
|
140
148
|
externalTaskIds: {},
|
|
141
149
|
startedAt: new Date(),
|
|
142
150
|
createdById: userId,
|
|
151
|
+
ownedBy: this.nodeId,
|
|
152
|
+
leaseExpiresAt: new Date(Date.now() + JOB_RUN_LEASE_MS),
|
|
143
153
|
},
|
|
144
154
|
});
|
|
145
155
|
|
|
@@ -239,7 +249,10 @@ export class PipelineExecutor {
|
|
|
239
249
|
let currentOrder = startFromOrder;
|
|
240
250
|
|
|
241
251
|
try {
|
|
242
|
-
await jobsRepo.update({
|
|
252
|
+
await jobsRepo.update({
|
|
253
|
+
filterByTk: job.id,
|
|
254
|
+
values: { status: 'running', ownedBy: this.nodeId, leaseExpiresAt: new Date(Date.now() + JOB_RUN_LEASE_MS) },
|
|
255
|
+
});
|
|
243
256
|
|
|
244
257
|
for (const step of steps) {
|
|
245
258
|
if (step.stepOrder < startFromOrder) continue;
|
|
@@ -247,7 +260,10 @@ export class PipelineExecutor {
|
|
|
247
260
|
context.jobId = job.id;
|
|
248
261
|
currentOrder = step.stepOrder;
|
|
249
262
|
|
|
250
|
-
await jobsRepo.update({
|
|
263
|
+
await jobsRepo.update({
|
|
264
|
+
filterByTk: job.id,
|
|
265
|
+
values: { currentStep: currentOrder, leaseExpiresAt: new Date(Date.now() + JOB_RUN_LEASE_MS) },
|
|
266
|
+
});
|
|
251
267
|
|
|
252
268
|
if (!this.evaluateCondition(step.condition, context)) {
|
|
253
269
|
continue; // Skip step
|
|
@@ -293,7 +309,12 @@ export class PipelineExecutor {
|
|
|
293
309
|
|
|
294
310
|
await jobsRepo.update({
|
|
295
311
|
filterByTk: job.id,
|
|
296
|
-
values: {
|
|
312
|
+
values: {
|
|
313
|
+
status: 'polling',
|
|
314
|
+
externalTaskIds,
|
|
315
|
+
// This node keeps polling and refreshes the lease on every tick.
|
|
316
|
+
leaseExpiresAt: new Date(Date.now() + pollLeaseMs(step.endpoint.pollInterval)),
|
|
317
|
+
},
|
|
297
318
|
});
|
|
298
319
|
|
|
299
320
|
await this.jobManager.startPolling(job.id, step.endpoint, taskId);
|
|
@@ -309,7 +330,13 @@ export class PipelineExecutor {
|
|
|
309
330
|
|
|
310
331
|
await jobsRepo.update({
|
|
311
332
|
filterByTk: job.id,
|
|
312
|
-
values: {
|
|
333
|
+
values: {
|
|
334
|
+
status: 'polling',
|
|
335
|
+
externalTaskIds,
|
|
336
|
+
// No process actively owns a webhook wait: the callback may arrive
|
|
337
|
+
// at any node, so there is no lease to renew.
|
|
338
|
+
leaseExpiresAt: null,
|
|
339
|
+
},
|
|
313
340
|
});
|
|
314
341
|
|
|
315
342
|
// End execution. Webhook will resume.
|
|
@@ -343,39 +370,59 @@ export class PipelineExecutor {
|
|
|
343
370
|
const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
|
|
344
371
|
const pipelineRepo = this.db.getRepository<any>('doc_understanding_pipelines');
|
|
345
372
|
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
373
|
+
// Atomic claim: webhooks can be delivered more than once and a polling tick can
|
|
374
|
+
// race with a webhook, so only the first caller that still finds the job in
|
|
375
|
+
// 'polling' may resume it. The row lock plus status re-check makes the claim
|
|
376
|
+
// safe across nodes.
|
|
377
|
+
type ResumeClaim = { job: any; steps: PipelineStepDef[]; stepResults: Record<string, any>; currentStep: number };
|
|
378
|
+
const resume: ResumeClaim | undefined = await this.db.sequelize.transaction(
|
|
379
|
+
async (transaction: { LOCK: { UPDATE: string } }): Promise<ResumeClaim | undefined> => {
|
|
380
|
+
const locked = await jobsRepo.findOne({ filterByTk: jobId, transaction, lock: transaction.LOCK.UPDATE });
|
|
381
|
+
if (!locked || String(locked.get('status')) !== 'polling') return undefined;
|
|
382
|
+
|
|
383
|
+
const pipeline = await pipelineRepo.findOne({
|
|
384
|
+
filter: { id: locked.get('pipelineId') },
|
|
385
|
+
appends: ['steps', 'steps.endpoint'],
|
|
386
|
+
transaction,
|
|
387
|
+
});
|
|
388
|
+
if (!pipeline) return undefined;
|
|
389
|
+
|
|
390
|
+
const steps = [...((pipeline as any).steps || [])].sort(
|
|
391
|
+
(a: PipelineStepDef, b: PipelineStepDef) => a.stepOrder - b.stepOrder,
|
|
392
|
+
);
|
|
393
|
+
const currentStep = Number(locked.get('currentStep'));
|
|
394
|
+
const step = steps.find((s) => s.stepOrder === currentStep);
|
|
395
|
+
const stepResults = { ...((locked.get('stepResults') as Record<string, any>) || {}) };
|
|
396
|
+
if (step) {
|
|
397
|
+
stepResults[step.outputAlias || step.stepOrder.toString()] = asyncResult;
|
|
398
|
+
}
|
|
355
399
|
|
|
356
|
-
|
|
357
|
-
|
|
400
|
+
await jobsRepo.update({
|
|
401
|
+
filterByTk: jobId,
|
|
402
|
+
values: {
|
|
403
|
+
status: 'running',
|
|
404
|
+
ownedBy: this.nodeId,
|
|
405
|
+
leaseExpiresAt: new Date(Date.now() + JOB_RUN_LEASE_MS),
|
|
406
|
+
stepResults,
|
|
407
|
+
},
|
|
408
|
+
transaction,
|
|
409
|
+
});
|
|
410
|
+
return { job: locked, steps, stepResults, currentStep };
|
|
411
|
+
},
|
|
412
|
+
);
|
|
358
413
|
|
|
359
|
-
if (
|
|
360
|
-
job.stepResults = job.stepResults || {};
|
|
361
|
-
job.stepResults[step.outputAlias || step.stepOrder.toString()] = asyncResult;
|
|
362
|
-
|
|
363
|
-
await jobsRepo.update({
|
|
364
|
-
filterByTk: jobId,
|
|
365
|
-
values: { stepResults: job.stepResults }, // updating stepResults json
|
|
366
|
-
});
|
|
367
|
-
}
|
|
414
|
+
if (!resume) return;
|
|
368
415
|
|
|
369
416
|
const context: ExecutionContext = {
|
|
370
|
-
input: job.input,
|
|
417
|
+
input: resume.job.get('input'),
|
|
371
418
|
files: [], // Files cannot easily persist across webhook unless stored in bucket. For now assume next steps use only json.
|
|
372
|
-
stepResults:
|
|
373
|
-
jobId: job.id,
|
|
419
|
+
stepResults: resume.stepResults,
|
|
420
|
+
jobId: resume.job.id,
|
|
374
421
|
};
|
|
375
422
|
|
|
376
423
|
// resume from next step
|
|
377
|
-
this.runSteps(job, steps, context,
|
|
378
|
-
this.logger.error(`Failed executing step ${
|
|
424
|
+
this.runSteps(resume.job, resume.steps, context, resume.currentStep + 1).catch((err) => {
|
|
425
|
+
this.logger.error(`Failed executing step ${resume.currentStep + 1} for job ${resume.job.id}`, err);
|
|
379
426
|
});
|
|
380
427
|
}
|
|
381
428
|
|
package/src/server/types.ts
CHANGED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* This file is part of the NocoBase (R) project.
|
|
3
|
-
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
|
|
4
|
-
* Authors: NocoBase Team.
|
|
5
|
-
*
|
|
6
|
-
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
|
|
7
|
-
* For more information, please refer to: https://www.nocobase.com/agreement.
|
|
8
|
-
*/
|
|
9
|
-
|
|
10
|
-
"use strict";(self.webpackChunkplugin_document_understanding_client_v2=self.webpackChunkplugin_document_understanding_client_v2||[]).push([["794"],{441:function(e,t,n){n.r(t),n.d(t,{PluginSettings:function(){return Z}});var r=n(155),l=n.n(r),a=n(59),o=n(694),i=JSON.parse('{"UU":"plugin-document-understanding"}'),u=n(375),c=n(485);function s(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function d(e,t,n,r,l,a,o){try{var i=e[a](o),u=i.value}catch(e){n(e);return}i.done?t(u):Promise.resolve(u).then(r,l)}function m(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,l=null==e?null:"u">typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=l){var a=[],o=!0,i=!1;try{for(l=l.call(e);!(o=(n=l.next()).done)&&(a.push(n.value),!t||a.length!==t);o=!0);}catch(e){i=!0,r=e}finally{try{o||null==l.return||l.return()}finally{if(i)throw r}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return s(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if("Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return s(e,t)}}(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var p=function(){var e=m(a.Form.useForm(),1)[0],t=(0,c.useApp)().apiClient,n=m((0,r.useState)(!0),2),o=n[0],i=n[1],s=m((0,r.useState)(!1),2),p=s[0],f=s[1];return((0,r.useEffect)(function(){t.request({url:"docUnderstanding:getConfig"}).then(function(t){var n=t.data;e.setFieldsValue((null==n?void 0:n.data)||{}),i(!1)}).catch(function(){return i(!1)})},[t,e]),o)?l().createElement(a.Spin,{style:{marginTop:40}}):l().createElement(a.Form,{form:e,layout:"vertical",onFinish:function(e){var n;return(n=function(){return function(e,t){var n,r,l,a={label:0,sent:function(){if(1&l[0])throw l[1];return l[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),i=Object.defineProperty;return i(o,"next",{value:u(0)}),i(o,"throw",{value:u(1)}),i(o,"return",{value:u(2)}),"function"==typeof Symbol&&i(o,Symbol.iterator,{value:function(){return this}}),o;function u(i){return function(u){var c=[i,u];if(n)throw TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(a=0)),a;)try{if(n=1,r&&(l=2&c[0]?r.return:c[0]?r.throw||((l=r.return)&&l.call(r),0):r.next)&&!(l=l.call(r,c[1])).done)return l;switch(r=0,l&&(c=[2&c[0],l.value]),c[0]){case 0:case 1:l=c;break;case 4:return a.label++,{value:c[1],done:!1};case 5:a.label++,r=c[1],c=[0];continue;case 7:c=a.ops.pop(),a.trys.pop();continue;default:if(!(l=(l=a.trys).length>0&&l[l.length-1])&&(6===c[0]||2===c[0])){a=0;continue}if(3===c[0]&&(!l||c[1]>l[0]&&c[1]<l[3])){a.label=c[1];break}if(6===c[0]&&a.label<l[1]){a.label=l[1],l=c;break}if(l&&a.label<l[2]){a.label=l[2],a.ops.push(c);break}l[2]&&a.ops.pop(),a.trys.pop();continue}c=t.call(e,a)}catch(e){c=[6,e],r=0}finally{n=l=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}}(this,function(n){switch(n.label){case 0:f(!0),n.label=1;case 1:return n.trys.push([1,3,4,5]),[4,t.request({url:"docUnderstanding:updateConfig",method:"POST",data:e})];case 2:return n.sent(),a.message.success("Configuration saved successfully"),[3,5];case 3:return n.sent(),a.message.error("Failed to save config"),[3,5];case 4:return f(!1),[7];case 5:return[2]}})},function(){var e=this,t=arguments;return new Promise(function(r,l){var a=n.apply(e,t);function o(e){d(a,r,l,o,i,"next",e)}function i(e){d(a,r,l,o,i,"throw",e)}o(void 0)})})()},style:{maxWidth:600}},l().createElement(a.Alert,{message:"Service Connection",description:"Configure the connection to your external document processing service. All endpoints will use this base URL and authentication.",type:"info",showIcon:!0,style:{marginBottom:24}}),l().createElement(a.Form.Item,{name:"baseUrl",label:"Base URL",rules:[{required:!0,message:"Base URL is required"}],help:"The root URL of your document processing API"},l().createElement(a.Input,{prefix:l().createElement(u.LinkOutlined,null),placeholder:"http://my-ocr-service:8000"})),l().createElement(a.Form.Item,{name:"authType",label:"Authentication Type",initialValue:"none"},l().createElement(a.Select,null,l().createElement(a.Select.Option,{value:"none"},"None"),l().createElement(a.Select.Option,{value:"api_key"},"API Key"),l().createElement(a.Select.Option,{value:"bearer"},"Bearer Token"),l().createElement(a.Select.Option,{value:"custom_header"},"Custom Header"))),l().createElement(a.Form.Item,{noStyle:!0,dependencies:["authType"]},function(){var t=e.getFieldValue("authType");return"none"===t?null:l().createElement(l().Fragment,null,"custom_header"===t&&l().createElement(a.Form.Item,{name:"authHeaderName",label:"Custom Header Name",rules:[{required:!0}]},l().createElement(a.Input,{placeholder:"X-Api-Key"})),l().createElement(a.Form.Item,{name:"authKey",label:"bearer"===t?"Bearer Token":"API Key",rules:[{required:!0}]},l().createElement(a.Input.Password,{placeholder:"Enter key or token"})))}),l().createElement("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"0 16px"}},l().createElement(a.Form.Item,{name:"defaultTimeout",label:"Request Timeout (ms)",initialValue:3e4},l().createElement(a.InputNumber,{style:{width:"100%"},min:1e3,step:1e3})),l().createElement(a.Form.Item,{name:"defaultRetries",label:"Default Retries",initialValue:2},l().createElement(a.InputNumber,{style:{width:"100%"},min:0,max:10})),l().createElement(a.Form.Item,{name:"pollInterval",label:"Poll Interval (ms)",initialValue:5e3},l().createElement(a.InputNumber,{style:{width:"100%"},min:1e3,step:1e3})),l().createElement(a.Form.Item,{name:"pollTimeout",label:"Poll Timeout (ms)",initialValue:3e5},l().createElement(a.InputNumber,{style:{width:"100%"},min:5e3,step:5e3}))),l().createElement(a.Form.Item,{name:"webhookSecret",label:"Webhook Secret",help:"Used to verify HMAC-SHA256 signatures on incoming webhook callbacks"},l().createElement(a.Input.Password,{placeholder:"Optional: secret for webhook signature verification"})),l().createElement(a.Form.Item,null,l().createElement(a.Button,{type:"primary",htmlType:"submit",icon:l().createElement(u.SaveOutlined,null),loading:p},"Save Configuration")))};function f(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function y(e,t,n,r,l,a,o){try{var i=e[a](o),u=i.value}catch(e){n(e);return}i.done?t(u):Promise.resolve(u).then(r,l)}function h(e){return function(){var t=this,n=arguments;return new Promise(function(r,l){var a=e.apply(t,n);function o(e){y(a,r,l,o,i,"next",e)}function i(e){y(a,r,l,o,i,"throw",e)}o(void 0)})}}function b(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,l=null==e?null:"u">typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=l){var a=[],o=!0,i=!1;try{for(l=l.call(e);!(o=(n=l.next()).done)&&(a.push(n.value),!t||a.length!==t);o=!0);}catch(e){i=!0,r=e}finally{try{o||null==l.return||l.return()}finally{if(i)throw r}}return a}}(e,t)||E(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function g(e){return function(e){if(Array.isArray(e))return f(e)}(e)||function(e){if("u">typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||E(e)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function E(e,t){if(e){if("string"==typeof e)return f(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if("Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return f(e,t)}}function v(e,t){var n,r,l,a={label:0,sent:function(){if(1&l[0])throw l[1];return l[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),i=Object.defineProperty;return i(o,"next",{value:u(0)}),i(o,"throw",{value:u(1)}),i(o,"return",{value:u(2)}),"function"==typeof Symbol&&i(o,Symbol.iterator,{value:function(){return this}}),o;function u(i){return function(u){var c=[i,u];if(n)throw TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(a=0)),a;)try{if(n=1,r&&(l=2&c[0]?r.return:c[0]?r.throw||((l=r.return)&&l.call(r),0):r.next)&&!(l=l.call(r,c[1])).done)return l;switch(r=0,l&&(c=[2&c[0],l.value]),c[0]){case 0:case 1:l=c;break;case 4:return a.label++,{value:c[1],done:!1};case 5:a.label++,r=c[1],c=[0];continue;case 7:c=a.ops.pop(),a.trys.pop();continue;default:if(!(l=(l=a.trys).length>0&&l[l.length-1])&&(6===c[0]||2===c[0])){a=0;continue}if(3===c[0]&&(!l||c[1]>l[0]&&c[1]<l[3])){a.label=c[1];break}if(6===c[0]&&a.label<l[1]){a.label=l[1],l=c;break}if(l&&a.label<l[2]){a.label=l[2],a.ops.push(c);break}l[2]&&a.ops.pop(),a.trys.pop();continue}c=t.call(e,a)}catch(e){c=[6,e],r=0}finally{n=l=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}}var S=a.Input.TextArea,O=function(e){var t=e.value,n=void 0===t?{}:t,o=e.onChange,i=b((0,r.useState)([]),2),c=i[0],s=i[1],d=(0,r.useRef)(!1);(0,r.useEffect)(function(){if(d.current){d.current=!1;return}s(Object.entries(n||{}).map(function(e,t){var n=b(e,2),r=n[0],l=n[1];return{id:"".concat(r,"_").concat(t),key:r,value:String(null!=l?l:"")}}))},[n]);var m=function(e){s(e);var t=e.reduce(function(e,t){var n=t.key.trim();return n&&(e[n]=t.value),e},{});d.current=!0,null==o||o(t)},p=function(e,t,n){var r,l,a=g(c);a[e]=(r=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){var r;r=n[t],t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r})}return e}({},a[e]),l=l={key:t,value:n},Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(l)):(function(e){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t.push.apply(t,n)}return t})(Object(l)).forEach(function(e){Object.defineProperty(r,e,Object.getOwnPropertyDescriptor(l,e))}),r),m(a)},f=function(e){m(c.filter(function(t,n){return n!==e}))};return l().createElement("div",null,c.map(function(e,t){return l().createElement(a.Space,{key:e.id,style:{display:"flex",marginBottom:4}},l().createElement(a.Input,{placeholder:"Header name",value:e.key,onChange:function(n){return p(t,n.target.value,e.value)},style:{width:180}}),l().createElement(a.Input,{placeholder:"Value",value:e.value,onChange:function(n){return p(t,e.key,n.target.value)},style:{width:220}}),l().createElement(a.Button,{size:"small",danger:!0,icon:l().createElement(u.DeleteOutlined,null),onClick:function(){return f(t)}}))}),l().createElement(a.Button,{size:"small",type:"dashed",icon:l().createElement(u.PlusOutlined,null),onClick:function(){return s(g(c).concat([{id:"new_".concat(Date.now(),"_").concat(Math.random()),key:"",value:""}]))}},"Add Header"))},w=function(e){var t=e.value,n=e.onChange,a=e.placeholder,o=b((0,r.useState)(""),2),i=o[0],u=o[1],c=b((0,r.useState)(""),2),s=c[0],d=c[1];return(0,r.useEffect)(function(){if(!t)return void u("");try{u("string"==typeof t?JSON.stringify(JSON.parse(t),null,2):JSON.stringify(t,null,2))}catch(e){u("string"==typeof t?t:"")}},[t]),l().createElement("div",null,l().createElement(S,{rows:6,value:i,onChange:function(e){return u(e.target.value)},onBlur:function(){if(!i.trim()){d(""),null==n||n(null);return}try{var e=JSON.parse(i);d(""),null==n||n(e)}catch(e){d("Invalid JSON")}},placeholder:a||"{}",style:{fontFamily:"monospace",fontSize:12}}),s&&l().createElement("div",{style:{color:"#ff4d4f",fontSize:12}},s))},I=function(){var e=(0,c.useApp)().apiClient,t=b((0,r.useState)([]),2),n=t[0],o=t[1],i=b((0,r.useState)(!1),2),s=i[0],d=i[1],m=b((0,r.useState)(!1),2),p=m[0],f=m[1],y=b(a.Form.useForm(),1)[0],g=b((0,r.useState)(null),2),E=g[0],I=g[1],k=(0,r.useCallback)(function(){return h(function(){var t;return v(this,function(n){switch(n.label){case 0:d(!0),n.label=1;case 1:return n.trys.push([1,,3,4]),[4,e.request({url:"docUnderstanding:listEndpoints"})];case 2:return o((null==(t=n.sent().data)?void 0:t.data)||[]),[3,4];case 3:return d(!1),[7];case 4:return[2]}})})()},[e]);(0,r.useEffect)(function(){k()},[k]);var T=function(e){I(e.id),y.setFieldsValue(e),f(!0)},C=[{title:"Name",dataIndex:"name",width:150},{title:"Subpath",dataIndex:"subpath",width:200},{title:"Method",dataIndex:"method",width:80,render:function(e){return l().createElement(a.Tag,null,e)}},{title:"Execution",dataIndex:"executionMode",width:100,render:function(e){return l().createElement(a.Tag,{color:{sync:"green",polling:"blue",webhook:"purple"}[e]},e)}},{title:"File",dataIndex:"fileInputMode",width:90,render:function(e){return"none"===e?"-":e}},{title:"Enabled",dataIndex:"enabled",width:70,render:function(e){return e?l().createElement(a.Tag,{color:"success"},"Yes"):l().createElement(a.Tag,null,"No")}},{title:"Action",width:120,render:function(t,n){return l().createElement(a.Space,null,l().createElement(a.Button,{type:"link",size:"small",icon:l().createElement(u.EditOutlined,null),onClick:function(){return T(n)}},"Edit"),l().createElement(a.Popconfirm,{title:"Delete this endpoint?",onConfirm:function(){var t;return t=n.id,h(function(){return v(this,function(n){switch(n.label){case 0:return[4,e.request({url:"docUnderstanding:deleteEndpoint",method:"POST",params:{filterByTk:t}})];case 1:return n.sent(),a.message.success("Deleted"),k(),[2]}})})()}},l().createElement(a.Button,{type:"link",size:"small",danger:!0,icon:l().createElement(u.DeleteOutlined,null)},"Delete")))}}];return l().createElement("div",null,l().createElement("div",{style:{marginBottom:16}},l().createElement(a.Button,{type:"primary",icon:l().createElement(u.PlusOutlined,null),onClick:function(){I(null),y.resetFields(),f(!0)}},"Add Endpoint")),l().createElement(a.Table,{rowKey:"id",columns:C,dataSource:n,loading:s,size:"small"}),l().createElement(a.Modal,{title:E?"Edit Endpoint":"Add Endpoint",open:p,onOk:function(){return h(function(){var t;return v(this,function(n){switch(n.label){case 0:return n.trys.push([0,6,,7]),[4,y.validateFields()];case 1:if((t=n.sent()).customHeaders=Object.entries(t.customHeaders||{}).reduce(function(e,t){var n=b(t,2),r=n[0],l=n[1],a=r.trim();return a&&(e[a]=l),e},{}),!E)return[3,3];return[4,e.request({url:"docUnderstanding:updateEndpoint",method:"POST",params:{filterByTk:E},data:t})];case 2:return n.sent(),[3,5];case 3:return[4,e.request({url:"docUnderstanding:createEndpoint",method:"POST",data:t})];case 4:n.sent(),n.label=5;case 5:return a.message.success("Saved"),f(!1),k(),[3,7];case 6:return n.sent(),[3,7];case 7:return[2]}})})()},onCancel:function(){return f(!1)},width:680,destroyOnClose:!0},l().createElement(a.Form,{form:y,layout:"vertical",preserve:!1},l().createElement(a.Tabs,{size:"small",items:[{key:"basic",label:"Basic",children:l().createElement(l().Fragment,null,l().createElement(a.Form.Item,{name:"name",label:"Unique Name",rules:[{required:!0}]},l().createElement(a.Input,{placeholder:"ocr, classify, extract..."})),l().createElement(a.Form.Item,{name:"subpath",label:"Subpath",rules:[{required:!0}]},l().createElement(a.Input,{placeholder:"/api/v1/ocr"})),l().createElement(a.Form.Item,{name:"description",label:"Description"},l().createElement(S,{rows:2,placeholder:"What this endpoint does"})),l().createElement(a.Space,{size:"large"},l().createElement(a.Form.Item,{name:"method",label:"HTTP Method",initialValue:"POST"},l().createElement(a.Select,{style:{width:120}},l().createElement(a.Select.Option,{value:"GET"},"GET"),l().createElement(a.Select.Option,{value:"POST"},"POST"),l().createElement(a.Select.Option,{value:"PUT"},"PUT"))),l().createElement(a.Form.Item,{name:"enabled",label:"Enabled",valuePropName:"checked",initialValue:!0},l().createElement(a.Switch,null))))},{key:"file",label:"File Input",children:l().createElement(l().Fragment,null,l().createElement(a.Form.Item,{name:"fileInputMode",label:"File Input Mode",initialValue:"none"},l().createElement(a.Select,{style:{width:200}},l().createElement(a.Select.Option,{value:"none"},"None"),l().createElement(a.Select.Option,{value:"multipart"},"Multipart Upload"),l().createElement(a.Select.Option,{value:"base64"},"Base64 in JSON"))),l().createElement(a.Form.Item,{noStyle:!0,dependencies:["fileInputMode"]},function(){return"none"!==y.getFieldValue("fileInputMode")?l().createElement(l().Fragment,null,l().createElement(a.Form.Item,{name:"fileFieldName",label:"File Field Name",initialValue:"file"},l().createElement(a.Input,{placeholder:"file",style:{width:200}})),l().createElement(a.Form.Item,{name:"maxFiles",label:"Max Files",initialValue:1},l().createElement(a.InputNumber,{min:1,max:20,style:{width:120}}))):null}))},{key:"async",label:"Async Config",children:l().createElement(l().Fragment,null,l().createElement(a.Form.Item,{name:"executionMode",label:"Execution Mode",initialValue:"sync"},l().createElement(a.Select,{style:{width:200}},l().createElement(a.Select.Option,{value:"sync"},"Synchronous"),l().createElement(a.Select.Option,{value:"polling"},"Polling"),l().createElement(a.Select.Option,{value:"webhook"},"Webhook"))),l().createElement(a.Form.Item,{noStyle:!0,dependencies:["executionMode"]},function(){var e=y.getFieldValue("executionMode");return"sync"===e?null:l().createElement(l().Fragment,null,l().createElement(a.Form.Item,{name:"pollTaskIdField",label:"Task ID Field",help:"Field in response containing the async task ID",initialValue:"task_id"},l().createElement(a.Input,{placeholder:"task_id"})),"polling"===e&&l().createElement(l().Fragment,null,l().createElement(a.Form.Item,{name:"pollResultSubpath",label:"Poll Result Subpath",help:"URL to poll for result. Use {taskId} as placeholder.",rules:[{required:!0,message:"Required for polling mode"}]},l().createElement(a.Input,{placeholder:"/api/v1/tasks/{taskId}/result"})),l().createElement(a.Form.Item,{name:"pollResultField",label:"Result Field",help:"Field in poll response containing the actual result"},l().createElement(a.Input,{placeholder:"result"})),l().createElement(a.Form.Item,{name:"pollStatusField",label:"Status Field (optional)",help:"Field to check completion status. If empty, any non-null result = complete."},l().createElement(a.Input,{placeholder:"status"})),l().createElement(a.Form.Item,{name:"pollCompletedValue",label:"Completed Value",help:"Value of status field that means 'done'",initialValue:"completed"},l().createElement(a.Input,{placeholder:"completed"})),l().createElement(a.Space,{size:"large"},l().createElement(a.Form.Item,{name:"pollInterval",label:"Poll Interval (ms)",help:"Override default"},l().createElement(a.InputNumber,{min:1e3,step:1e3,placeholder:"5000",style:{width:150}})),l().createElement(a.Form.Item,{name:"pollTimeout",label:"Poll Timeout (ms)",help:"Override default"},l().createElement(a.InputNumber,{min:5e3,step:5e3,placeholder:"300000",style:{width:150}})))))}))},{key:"schema",label:"Schema",children:l().createElement(l().Fragment,null,l().createElement(a.Form.Item,{name:"requestBodySchema",label:"Request Body Schema (JSON Schema)"},l().createElement(w,{placeholder:'{ "type": "object", "properties": { ... } }'})),l().createElement(a.Form.Item,{name:"responseSchema",label:"Response Schema (JSON Schema)"},l().createElement(w,{placeholder:'{ "type": "object", "properties": { ... } }'})))},{key:"headers",label:"Custom Headers",children:l().createElement(a.Form.Item,{name:"customHeaders",label:"Additional Headers"},l().createElement(O,null))}]}))))};function k(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function T(e,t,n,r,l,a,o){try{var i=e[a](o),u=i.value}catch(e){n(e);return}i.done?t(u):Promise.resolve(u).then(r,l)}function C(e){return function(){var t=this,n=arguments;return new Promise(function(r,l){var a=e.apply(t,n);function o(e){T(a,r,l,o,i,"next",e)}function i(e){T(a,r,l,o,i,"throw",e)}o(void 0)})}}function F(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function P(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){F(e,t,n[t])})}return e}function x(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):(function(e){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t.push.apply(t,n)}return t})(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}function A(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,l=null==e?null:"u">typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=l){var a=[],o=!0,i=!1;try{for(l=l.call(e);!(o=(n=l.next()).done)&&(a.push(n.value),!t||a.length!==t);o=!0);}catch(e){i=!0,r=e}finally{try{o||null==l.return||l.return()}finally{if(i)throw r}}return a}}(e,t)||N(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function j(e){return function(e){if(Array.isArray(e))return k(e)}(e)||function(e){if("u">typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||N(e)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function B(e){return e&&"u">typeof Symbol&&e.constructor===Symbol?"symbol":typeof e}function N(e,t){if(e){if("string"==typeof e)return k(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if("Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return k(e,t)}}function R(e,t){var n,r,l,a={label:0,sent:function(){if(1&l[0])throw l[1];return l[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),i=Object.defineProperty;return i(o,"next",{value:u(0)}),i(o,"throw",{value:u(1)}),i(o,"return",{value:u(2)}),"function"==typeof Symbol&&i(o,Symbol.iterator,{value:function(){return this}}),o;function u(i){return function(u){var c=[i,u];if(n)throw TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(a=0)),a;)try{if(n=1,r&&(l=2&c[0]?r.return:c[0]?r.throw||((l=r.return)&&l.call(r),0):r.next)&&!(l=l.call(r,c[1])).done)return l;switch(r=0,l&&(c=[2&c[0],l.value]),c[0]){case 0:case 1:l=c;break;case 4:return a.label++,{value:c[1],done:!1};case 5:a.label++,r=c[1],c=[0];continue;case 7:c=a.ops.pop(),a.trys.pop();continue;default:if(!(l=(l=a.trys).length>0&&l[l.length-1])&&(6===c[0]||2===c[0])){a=0;continue}if(3===c[0]&&(!l||c[1]>l[0]&&c[1]<l[3])){a.label=c[1];break}if(6===c[0]&&a.label<l[1]){a.label=l[1],l=c;break}if(l&&a.label<l[2]){a.label=l[2],a.ops.push(c);break}l[2]&&a.ops.pop(),a.trys.pop();continue}c=t.call(e,a)}catch(e){c=[6,e],r=0}finally{n=l=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}}var U=a.Input.TextArea,z=a.Collapse.Panel,M={pending:{color:"default",label:"Pending"},running:{color:"processing",label:"Running"},polling:{color:"processing",label:"Polling"},completed:{color:"success",label:"Completed"},failed:{color:"error",label:"Failed"},timeout:{color:"error",label:"Timeout"}},D=function(e){var t,n,r;return null!=(t=null!=(n=null==e||null==(r=e.data)?void 0:r.data)?n:null==e?void 0:e.data)?t:e},_=function(e){return JSON.stringify(null!=e?e:{},null,2)},q=function(e){return e&&(void 0===e?"undefined":B(e))==="object"?Object.prototype.hasOwnProperty.call(e,"default")?e.default:"object"===e.type||e.properties?Object.entries(e.properties||{}).reduce(function(e,t){var n=A(t,2),r=n[0],l=q(n[1]);return void 0!==l&&(e[r]=l),e},{}):"array"===e.type?[]:void 0:{}},J=function(e,t){return e&&t&&(void 0===e?"undefined":B(e))==="object"&&(void 0===t?"undefined":B(t))==="object"&&!Array.isArray(e)&&!Array.isArray(t)?Object.entries(e).reduce(function(e,t){var n=A(t,2),r=n[0],l=n[1];return x(P({},e),F({},r,J(l,e[r])))},P({},t)):void 0===t?e:t},V=function(e){var t=e.value,n=e.onChange,a=e.placeholder,o=e.rows,i=A((0,r.useState)(""),2),u=i[0],c=i[1],s=A((0,r.useState)(""),2),d=s[0],m=s[1];return(0,r.useEffect)(function(){if(!t)return void c("");try{c("string"==typeof t?JSON.stringify(JSON.parse(t),null,2):JSON.stringify(t,null,2))}catch(e){c("string"==typeof t?t:"")}},[t]),l().createElement("div",null,l().createElement(U,{rows:void 0===o?5:o,value:u,onChange:function(e){return c(e.target.value)},onBlur:function(){if(!u.trim()){m(""),null==n||n(null);return}try{var e=JSON.parse(u);m(""),null==n||n(e)}catch(e){m("Invalid JSON")}},placeholder:a||"{}",style:{fontFamily:"monospace",fontSize:12}}),d&&l().createElement("div",{style:{color:"#ff4d4f",fontSize:12}},d))},H=function(e){var t=e.steps,n=e.endpoints,r=e.onChange,o=function(e,n){var l,a=j(t),o=e+n;o<0||o>=a.length||(l=[a[o],a[e]],a[e]=l[0],a[o]=l[1],a.forEach(function(e,t){return e.stepOrder=t+1}),r(a))},i=function(e,n,l){var a=j(t);a[e][n]=l,r(a)},c=function(e){var n=t.filter(function(t,n){return n!==e});n.forEach(function(e,t){return e.stepOrder=t+1}),r(n)},s=function(){var e;r(j(t).concat([(e=t.length+1,{_key:"new_".concat(Date.now(),"_").concat(Math.random()),stepOrder:e,name:"",endpointId:null,inputMapping:null,outputAlias:"",condition:null,onError:"fail",retryCount:0})]))};return 0===t.length?l().createElement("div",{style:{textAlign:"center",padding:"20px 0"}},l().createElement(a.Empty,{description:"No steps yet",imageStyle:{height:40}}),l().createElement(a.Button,{type:"dashed",icon:l().createElement(u.PlusOutlined,null),onClick:s,style:{marginTop:8}},"Add First Step")):l().createElement("div",null,l().createElement(a.Collapse,{size:"small",defaultActiveKey:t.map(function(e){return e._key})},t.map(function(e,r){var s=n.find(function(t){return t.id===e.endpointId}),d=l().createElement(a.Space,{size:4,onClick:function(e){return e.stopPropagation()}},l().createElement(a.Button,{size:"small",disabled:0===r,icon:l().createElement(u.ArrowUpOutlined,null),onClick:function(){return o(r,-1)}}),l().createElement(a.Button,{size:"small",disabled:r===t.length-1,icon:l().createElement(u.ArrowDownOutlined,null),onClick:function(){return o(r,1)}}),l().createElement(a.Popconfirm,{title:"Remove step?",onConfirm:function(){return c(r)}},l().createElement(a.Button,{size:"small",danger:!0,icon:l().createElement(u.DeleteOutlined,null)}))),m=l().createElement(a.Space,null,l().createElement(a.Badge,{count:e.stepOrder,style:{backgroundColor:"#1677ff"}}),l().createElement("span",null,e.name||"(unnamed)"),s&&l().createElement(a.Tag,null,s.name),"skip"===e.onError&&l().createElement(a.Tooltip,{title:"Step can be skipped on error"},l().createElement(a.Tag,{color:"orange"},"skip on error")),e.condition&&l().createElement(a.Tooltip,{title:"Has condition"},l().createElement(a.Tag,{color:"purple"},"conditional")));return l().createElement(z,{key:e._key,header:m,extra:d},l().createElement("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"0 16px"}},l().createElement("div",null,l().createElement("label",{style:{fontWeight:500,display:"block",marginBottom:4}},"Step Name *"),l().createElement(a.Input,{value:e.name,onChange:function(e){return i(r,"name",e.target.value)},placeholder:"OCR, Classify, Extract..."})),l().createElement("div",null,l().createElement("label",{style:{fontWeight:500,display:"block",marginBottom:4}},"Endpoint *"),l().createElement(a.Select,{value:e.endpointId,onChange:function(e){return i(r,"endpointId",e)},placeholder:"Select endpoint",style:{width:"100%"},options:n.map(function(e){return{value:e.id,label:"".concat(e.name," (").concat(e.method," ").concat(e.subpath,")")}})})),l().createElement("div",null,l().createElement("label",{style:{fontWeight:500,display:"block",marginBottom:4,marginTop:12}},"Output Alias"),l().createElement(a.Input,{value:e.outputAlias,onChange:function(e){return i(r,"outputAlias",e.target.value)},placeholder:"ocr_result"}),l().createElement("div",{style:{color:"#888",fontSize:11}},"Other steps reference this as: $step[",e.outputAlias||e.stepOrder,"].response.field")),l().createElement("div",null,l().createElement("label",{style:{fontWeight:500,display:"block",marginBottom:4,marginTop:12}},"On Error"),l().createElement(a.Space,null,l().createElement(a.Select,{value:e.onError,onChange:function(e){return i(r,"onError",e)},style:{width:120}},l().createElement(a.Select.Option,{value:"fail"},"Fail"),l().createElement(a.Select.Option,{value:"skip"},"Skip"),l().createElement(a.Select.Option,{value:"retry"},"Retry")),"retry"===e.onError&&l().createElement(a.InputNumber,{value:e.retryCount,onChange:function(e){return i(r,"retryCount",e||0)},min:1,max:10,addonBefore:"x",style:{width:100}})))),l().createElement("div",{style:{marginTop:12}},l().createElement("label",{style:{fontWeight:500,display:"block",marginBottom:4}},"Input Mapping (JSON)",l().createElement(a.Tooltip,{title:"Map endpoint input fields. Use $input.field, $step[alias].response.field, $files, or literal values."},l().createElement("span",{style:{fontWeight:"normal",color:"#888",marginLeft:6,cursor:"help"}},"?"))),l().createElement(V,{value:e.inputMapping,onChange:function(e){return i(r,"inputMapping",e)},placeholder:'{ "text": "$step[ocr_result].response.text", "lang": "vi" }',rows:3})),l().createElement("div",{style:{marginTop:12}},l().createElement("label",{style:{fontWeight:500,display:"block",marginBottom:4}},"Condition (optional JSON)",l().createElement(a.Tooltip,{title:'Only run this step if condition matches. Format: { "field": "$step[x].response.y", "op": "eq", "value": "..." }'},l().createElement("span",{style:{fontWeight:"normal",color:"#888",marginLeft:6,cursor:"help"}},"?"))),l().createElement(V,{value:e.condition,onChange:function(e){return i(r,"condition",e)},placeholder:'{ "field": "$step[classify].response.type", "op": "eq", "value": "invoice" }',rows:2})))})),l().createElement(a.Button,{type:"dashed",icon:l().createElement(u.PlusOutlined,null),onClick:s,style:{marginTop:8,width:"100%"}},"Add Step"))},W=function(){var e,t,n=(0,c.useApp)().apiClient,o=A((0,r.useState)([]),2),i=o[0],s=o[1],d=A((0,r.useState)([]),2),m=d[0],p=d[1],f=A((0,r.useState)(!1),2),y=f[0],h=f[1],b=A((0,r.useState)(!1),2),g=b[0],E=b[1],v=A(a.Form.useForm(),1)[0],S=A((0,r.useState)(null),2),O=S[0],w=S[1],I=A((0,r.useState)([]),2),k=I[0],T=I[1],F=A((0,r.useState)(!1),2),B=F[0],N=F[1],W=A((0,r.useState)(null),2),L=W[0],$=W[1],K=A((0,r.useState)("{}"),2),G=K[0],Y=K[1],X=A((0,r.useState)(""),2),Q=X[0],Z=X[1],ee=A((0,r.useState)(null),2),et=ee[0],en=ee[1],er=A((0,r.useState)(!1),2),el=er[0],ea=er[1],eo=(0,r.useRef)(null),ei=(0,r.useCallback)(function(){return C(function(){var e,t,r,l,a;return R(this,function(o){switch(o.label){case 0:h(!0),o.label=1;case 1:return o.trys.push([1,,3,4]),[4,Promise.all([n.request({url:"docUnderstanding:listPipelines"}),n.request({url:"docUnderstanding:listEndpoints"})])];case 2:return l=(r=A.apply(void 0,[o.sent(),2]))[0],a=r[1],s((null==(e=l.data)?void 0:e.data)||[]),p((null==(t=a.data)?void 0:t.data)||[]),[3,4];case 3:return h(!1),[7];case 4:return[2]}})})()},[n]);(0,r.useEffect)(function(){ei()},[ei]),(0,r.useEffect)(function(){return function(){eo.current&&clearInterval(eo.current)}},[]);var eu=function(e){w(e.id),v.setFieldsValue({name:e.name,description:e.description,enabled:e.enabled,inputSchema:e.inputSchema,outputMapping:e.outputMapping}),T(j(e.steps||[]).sort(function(e,t){return e.stepOrder-t.stepOrder}).map(function(e){return{_key:"srv_".concat(e.id),id:e.id,stepOrder:e.stepOrder,name:e.name,endpointId:e.endpointId,inputMapping:e.inputMapping,outputAlias:e.outputAlias||"",condition:e.condition,onError:e.onError||"fail",retryCount:e.retryCount||0}})),E(!0)},ec=(0,r.useCallback)(function(){eo.current&&(clearInterval(eo.current),eo.current=null)},[]),es=(0,r.useCallback)(function(e){return C(function(){var t;return R(this,function(r){switch(r.label){case 0:return[4,n.request({url:"docUnderstanding:getJobStatus",params:{filterByTk:e}})];case 1:return en(t=D(r.sent())),["completed","failed","timeout"].includes(null==t?void 0:t.status)&&(ec(),ea(!1)),[2,t]}})})()},[n,ec]),ed=(0,r.useCallback)(function(e){ec(),eo.current=setInterval(function(){es(e).catch(function(e){ec(),ea(!1),a.message.error((null==e?void 0:e.message)||"Failed to refresh test job")})},1500)},[es,ec]),em=function(e){ec(),$(e),en(null),ea(!1),Z(""),Y(_(q(e.inputSchema))),N(!0)},ep=function(){ec(),N(!1),$(null),en(null),ea(!1)},ef=[{title:"Name",dataIndex:"name",width:200},{title:"Steps",dataIndex:"steps",width:300,render:function(e){if(!e||0===e.length)return l().createElement(a.Tag,null,"0 steps");var t=j(e).sort(function(e,t){return e.stepOrder-t.stepOrder});return l().createElement(a.Space,{size:2,wrap:!0},t.map(function(e,t){return l().createElement(l().Fragment,{key:e.id},t>0&&l().createElement("span",{style:{color:"#ccc"}},"→"),l().createElement(a.Tag,null,e.name||"Step ".concat(e.stepOrder)))}))}},{title:"Enabled",dataIndex:"enabled",width:80,render:function(e){return e?l().createElement(a.Tag,{color:"success"},"Yes"):l().createElement(a.Tag,null,"No")}},{title:"AI Tool",width:100,render:function(e,t){var n;return t.enabled?l().createElement(a.Tooltip,{title:"Registered as: doc_understanding.".concat(null==(n=t.name)?void 0:n.toLowerCase().replace(/[^a-z0-9_]/g,"_"))},l().createElement(a.Tag,{color:"blue",icon:l().createElement(u.ThunderboltOutlined,null)},"Active")):l().createElement(a.Tag,null,"Inactive")}},{title:"Action",width:190,render:function(e,t){return l().createElement(a.Space,null,l().createElement(a.Button,{type:"link",size:"small",icon:l().createElement(u.PlayCircleOutlined,null),disabled:!t.enabled,onClick:function(){return em(t)}},"Test"),l().createElement(a.Button,{type:"link",size:"small",icon:l().createElement(u.EditOutlined,null),onClick:function(){return eu(t)}},"Edit"),l().createElement(a.Popconfirm,{title:"Delete this pipeline?",onConfirm:function(){var e;return e=t.id,C(function(){return R(this,function(t){switch(t.label){case 0:return[4,n.request({url:"docUnderstanding:deletePipeline",method:"POST",params:{filterByTk:e}})];case 1:return t.sent(),a.message.success("Deleted"),ei(),[2]}})})()}},l().createElement(a.Button,{type:"link",size:"small",danger:!0,icon:l().createElement(u.DeleteOutlined,null)},"Delete")))}}];return l().createElement("div",null,l().createElement("div",{style:{marginBottom:16}},l().createElement(a.Button,{type:"primary",icon:l().createElement(u.PlusOutlined,null),onClick:function(){w(null),v.resetFields(),T([]),E(!0)}},"Add Pipeline")),l().createElement(a.Table,{rowKey:"id",columns:ef,dataSource:i,loading:y,size:"small"}),l().createElement(a.Modal,{title:O?"Edit Pipeline":"New Pipeline",open:g,onOk:function(){return C(function(){var e,t,r,l,o,i,u,c,s;return R(this,function(d){switch(d.label){case 0:return d.trys.push([0,6,,7]),[4,v.validateFields()];case 1:e=d.sent(),t=!0,r=!1,l=void 0;try{for(o=k[Symbol.iterator]();!(t=(i=o.next()).done);t=!0){if(!(u=i.value).name)return a.message.error("All steps must have a name"),[2];if(!u.endpointId)return a.message.error('Step "'.concat(u.name||u.stepOrder,'" must have an endpoint')),[2]}}catch(e){r=!0,l=e}finally{try{t||null==o.return||o.return()}finally{if(r)throw l}}if(new Set(c=k.map(function(e){return e.outputAlias}).filter(Boolean)).size!==c.length)return a.message.error("Step output aliases must be unique"),[2];if(s=x(P({},e),{steps:k.map(function(e){return x(P({},e.id?{id:e.id}:{}),{stepOrder:e.stepOrder,name:e.name,endpointId:e.endpointId,inputMapping:e.inputMapping,outputAlias:e.outputAlias||void 0,condition:e.condition,onError:e.onError,retryCount:"retry"===e.onError?e.retryCount:0})})}),!O)return[3,3];return[4,n.request({url:"docUnderstanding:updatePipeline",method:"POST",params:{filterByTk:O},data:s})];case 2:return d.sent(),[3,5];case 3:return[4,n.request({url:"docUnderstanding:createPipeline",method:"POST",data:s})];case 4:d.sent(),d.label=5;case 5:return a.message.success("Saved"),E(!1),ei(),[3,7];case 6:return d.sent(),[3,7];case 7:return[2]}})})()},onCancel:function(){return E(!1)},width:800,destroyOnClose:!0},l().createElement(a.Form,{form:v,layout:"vertical",preserve:!1},l().createElement("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"0 16px"}},l().createElement(a.Form.Item,{name:"name",label:"Pipeline Name",rules:[{required:!0}]},l().createElement(a.Input,{placeholder:"full_document_processing"})),l().createElement(a.Form.Item,{name:"enabled",label:"Enabled",valuePropName:"checked",initialValue:!0},l().createElement(a.Switch,null))),l().createElement(a.Form.Item,{name:"description",label:"Description"},l().createElement(U,{rows:2,placeholder:"What this pipeline does"})),l().createElement(a.Card,{title:"Pipeline Steps",size:"small",style:{marginBottom:16},extra:l().createElement(a.Tag,{color:"blue"},k.length," step(s)")},l().createElement(H,{steps:k,endpoints:m,onChange:T})),l().createElement(a.Collapse,{size:"small",ghost:!0},l().createElement(z,{header:"Advanced: Input Schema & Output Mapping",key:"advanced"},l().createElement(a.Form.Item,{name:"inputSchema",label:"Input Schema (JSON Schema)",help:"Defines what input this pipeline accepts. Used by AI tool schema."},l().createElement(V,{placeholder:'{ "type": "object", "properties": { "document_url": { "type": "string" } }, "required": ["document_url"] }'})),l().createElement(a.Form.Item,{name:"outputMapping",label:"Output Mapping (JSON)",help:"Map final step results to pipeline output. If empty, all step results are returned."},l().createElement(V,{placeholder:'{ "text": "$step[ocr_result].response.text", "category": "$step[classify].response.category" }'})))))),l().createElement(a.Modal,{title:L?"Test Playground: ".concat(L.name):"Test Playground",open:B,onCancel:ep,width:860,destroyOnClose:!0,footer:[l().createElement(a.Button,{key:"close",onClick:ep},"Close"),(null==et?void 0:et.id)&&l().createElement(a.Button,{key:"refresh",icon:l().createElement(u.ReloadOutlined,null),disabled:el,onClick:function(){return es(et.id)}},"Refresh"),l().createElement(a.Button,{key:"run",type:"primary",icon:l().createElement(u.PlayCircleOutlined,null),loading:el,onClick:function(){return C(function(){var e,t,r,l,o,i;return R(this,function(u){switch(u.label){case 0:if(!L)return[2];try{t=G.trim()?JSON.parse(G):{},e=J(q(L.inputSchema),t),Z("")}catch(e){return Z("Invalid JSON input"),[2]}ec(),ea(!0),en(null),u.label=1;case 1:return u.trys.push([1,4,,5]),[4,n.request({url:"docUnderstanding:executePipeline",method:"POST",data:{pipelineId:L.id,input:e}})];case 2:if(!(l=null==(r=D(u.sent()))?void 0:r.jobId))throw Error("Pipeline did not return a job ID");return[4,es(l)];case 3:return["completed","failed","timeout"].includes(null==(o=u.sent())?void 0:o.status)||ed(l),a.message.success("Test job #".concat(l," started")),[3,5];case 4:return i=u.sent(),ea(!1),a.message.error((null==i?void 0:i.message)||"Failed to run pipeline test"),[3,5];case 5:return[2]}})})()}},"Run test")].filter(Boolean)},l().createElement("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",gap:16}},l().createElement("div",null,l().createElement("div",{style:{fontWeight:500,marginBottom:6}},"Input JSON"),l().createElement(U,{rows:16,value:G,onChange:function(e){Y(e.target.value),Q&&Z("")},placeholder:'{ "document_url": "https://..." }',style:{fontFamily:"monospace",fontSize:12}}),Q&&l().createElement(a.Alert,{type:"error",showIcon:!0,message:Q,style:{marginTop:8}}),l().createElement(a.Collapse,{size:"small",ghost:!0,style:{marginTop:12}},l().createElement(z,{header:"Input Schema",key:"schema"},l().createElement("pre",{style:{background:"#f5f5f5",padding:12,borderRadius:6,fontSize:12,maxHeight:220,overflow:"auto"}},_(null==L?void 0:L.inputSchema))))),l().createElement("div",null,l().createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:6}},l().createElement("span",{style:{fontWeight:500}},"Result"),(null==et?void 0:et.status)&&l().createElement(a.Tag,{color:(null==(e=M[et.status])?void 0:e.color)||"default"},(null==(t=M[et.status])?void 0:t.label)||et.status)),et?l().createElement("div",null,l().createElement(a.Space,{style:{marginBottom:8},wrap:!0},l().createElement(a.Tag,null,"Job #",et.id),et.currentStep&&l().createElement(a.Tag,null,"Step ",et.currentStep)),et.error&&l().createElement(a.Alert,{type:"error",showIcon:!0,message:"Pipeline error",description:l().createElement("pre",{style:{margin:0,whiteSpace:"pre-wrap"}},et.error),style:{marginBottom:12}}),l().createElement("div",{style:{fontWeight:500,marginBottom:4}},"Final Result"),l().createElement("pre",{style:{background:"#f0f5ff",padding:12,borderRadius:6,fontSize:12,maxHeight:220,overflow:"auto"}},void 0!==et.finalResult&&null!==et.finalResult?_(et.finalResult):"(not yet available)"),l().createElement("div",{style:{fontWeight:500,margin:"12px 0 4px"}},"Step Results"),l().createElement("pre",{style:{background:"#f5f5f5",padding:12,borderRadius:6,fontSize:12,maxHeight:260,overflow:"auto"}},et.stepResults?_(et.stepResults):"{}")):l().createElement(a.Empty,{description:"Run a test to see job output",imageStyle:{height:48}})))))};function L(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function $(e,t,n,r,l,a,o){try{var i=e[a](o),u=i.value}catch(e){n(e);return}i.done?t(u):Promise.resolve(u).then(r,l)}function K(e){return function(){var t=this,n=arguments;return new Promise(function(r,l){var a=e.apply(t,n);function o(e){$(a,r,l,o,i,"next",e)}function i(e){$(a,r,l,o,i,"throw",e)}o(void 0)})}}function G(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,l=null==e?null:"u">typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=l){var a=[],o=!0,i=!1;try{for(l=l.call(e);!(o=(n=l.next()).done)&&(a.push(n.value),!t||a.length!==t);o=!0);}catch(e){i=!0,r=e}finally{try{o||null==l.return||l.return()}finally{if(i)throw r}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return L(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if("Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return L(e,t)}}(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Y(e,t){var n,r,l,a={label:0,sent:function(){if(1&l[0])throw l[1];return l[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),i=Object.defineProperty;return i(o,"next",{value:u(0)}),i(o,"throw",{value:u(1)}),i(o,"return",{value:u(2)}),"function"==typeof Symbol&&i(o,Symbol.iterator,{value:function(){return this}}),o;function u(i){return function(u){var c=[i,u];if(n)throw TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(a=0)),a;)try{if(n=1,r&&(l=2&c[0]?r.return:c[0]?r.throw||((l=r.return)&&l.call(r),0):r.next)&&!(l=l.call(r,c[1])).done)return l;switch(r=0,l&&(c=[2&c[0],l.value]),c[0]){case 0:case 1:l=c;break;case 4:return a.label++,{value:c[1],done:!1};case 5:a.label++,r=c[1],c=[0];continue;case 7:c=a.ops.pop(),a.trys.pop();continue;default:if(!(l=(l=a.trys).length>0&&l[l.length-1])&&(6===c[0]||2===c[0])){a=0;continue}if(3===c[0]&&(!l||c[1]>l[0]&&c[1]<l[3])){a.label=c[1];break}if(6===c[0]&&a.label<l[1]){a.label=l[1],l=c;break}if(l&&a.label<l[2]){a.label=l[2],a.ops.push(c);break}l[2]&&a.ops.pop(),a.trys.pop();continue}c=t.call(e,a)}catch(e){c=[6,e],r=0}finally{n=l=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}}var X={pending:{color:"default",label:"Pending"},running:{color:"processing",label:"Running"},polling:{color:"processing",label:"Polling"},completed:{color:"success",label:"Completed"},failed:{color:"error",label:"Failed"},timeout:{color:"error",label:"Timeout"}},Q=function(){var e,t=(0,c.useApp)().apiClient,n=G((0,r.useState)([]),2),o=n[0],i=n[1],s=G((0,r.useState)([]),2),d=s[0],m=s[1],p=G((0,r.useState)(!1),2),f=p[0],y=p[1],h=G((0,r.useState)(!1),2),b=h[0],g=h[1],E=G((0,r.useState)(null),2),v=E[0],S=E[1],O=G((0,r.useState)(void 0),2),w=O[0],I=O[1],k=G((0,r.useState)(void 0),2),T=k[0],C=k[1],F=(0,r.useCallback)(function(){return K(function(){var e,n;return Y(this,function(r){switch(r.label){case 0:y(!0),r.label=1;case 1:return r.trys.push([1,,3,4]),n={},w&&(n.status=w),T&&(n.pipelineId=T),[4,t.request({url:"docUnderstanding:listJobs",params:{filter:Object.keys(n).length>0?n:void 0}})];case 2:return i((null==(e=r.sent().data)?void 0:e.data)||[]),[3,4];case 3:return y(!1),[7];case 4:return[2]}})})()},[t,w,T]),P=(0,r.useCallback)(function(){return K(function(){var e;return Y(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,t.request({url:"docUnderstanding:listPipelines"})];case 1:return m((null==(e=n.sent().data)?void 0:e.data)||[]),[3,3];case 2:return n.sent(),[3,3];case 3:return[2]}})})()},[t]);(0,r.useEffect)(function(){P()},[P]),(0,r.useEffect)(function(){F();var e=setInterval(F,1e4);return function(){return clearInterval(e)}},[F]);var x=new Map(d.map(function(e){return[e.id,e.name]})),A=[{title:"ID",dataIndex:"id",width:60},{title:"Pipeline",dataIndex:"pipelineId",width:180,render:function(e){return x.get(e)||"#".concat(e)}},{title:"Status",dataIndex:"status",width:100,render:function(e){var t=X[e]||{color:"default",label:e};return l().createElement(a.Tag,{color:t.color},t.label)}},{title:"Current Step",dataIndex:"currentStep",width:90,render:function(e,t){return"completed"===t.status?l().createElement(a.Tag,{color:"success"},"Done"):"failed"===t.status?l().createElement(a.Tag,{color:"error"},"Step ",e):l().createElement(a.Badge,{status:"processing",text:"Step ".concat(e)})}},{title:"Started",dataIndex:"startedAt",width:160,render:function(e){return e?new Date(e).toLocaleString():"-"}},{title:"Completed",dataIndex:"completedAt",width:160,render:function(e){return e?new Date(e).toLocaleString():"-"}},{title:"Action",width:80,render:function(e,n){return l().createElement(a.Button,{size:"small",icon:l().createElement(u.EyeOutlined,null),onClick:function(){return K(function(){var e;return Y(this,function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,t.request({url:"docUnderstanding:getJobStatus",params:{filterByTk:n.id}})];case 1:return S((null==(e=r.sent().data)?void 0:e.data)||n),[3,3];case 2:return r.sent(),S(n),[3,3];case 3:return g(!0),[2]}})})()}},"View")}}];return l().createElement("div",null,l().createElement(a.Space,{style:{marginBottom:16},wrap:!0},l().createElement(a.Select,{allowClear:!0,placeholder:"Filter by status",value:w,onChange:I,style:{width:160},options:Object.entries(X).map(function(e){var t=G(e,2);return{value:t[0],label:t[1].label}})}),l().createElement(a.Select,{allowClear:!0,placeholder:"Filter by pipeline",value:T,onChange:C,style:{width:200},options:d.map(function(e){return{value:e.id,label:e.name}})}),l().createElement(a.Button,{icon:l().createElement(u.ReloadOutlined,null),onClick:F},"Refresh")),l().createElement(a.Table,{rowKey:"id",columns:A,dataSource:o,loading:f,size:"small",pagination:{pageSize:20}}),l().createElement(a.Drawer,{title:v?"Job #".concat(v.id," — ").concat(x.get(v.pipelineId)||"Unknown"):"Job Details",width:640,open:b,onClose:function(){return g(!1)}},v&&l().createElement("div",null,l().createElement("div",{style:{marginBottom:16}},l().createElement(a.Space,null,l().createElement(a.Tag,{color:null==(e=X[v.status])?void 0:e.color},v.status),v.startedAt&&l().createElement("span",null,"Started: ",new Date(v.startedAt).toLocaleString()),v.completedAt&&l().createElement("span",null,"Completed: ",new Date(v.completedAt).toLocaleString()))),v.error&&l().createElement("div",{style:{background:"#fff2f0",border:"1px solid #ffccc7",borderRadius:6,padding:12,marginBottom:16}},l().createElement("strong",{style:{color:"#cf1322"}},"Error:"),l().createElement("pre",{style:{margin:"4px 0 0",whiteSpace:"pre-wrap",color:"#cf1322"}},v.error)),l().createElement("h4",null,"Input"),l().createElement("pre",{style:{background:"#f5f5f5",padding:12,borderRadius:6,fontSize:12,maxHeight:200,overflow:"auto"}},JSON.stringify(v.input,null,2)),l().createElement("h4",{style:{marginTop:16}},"Step Results"),v.stepResults&&Object.keys(v.stepResults).length>0?Object.entries(v.stepResults).map(function(e){var t=G(e,2),n=t[0],r=t[1];return l().createElement("div",{key:n,style:{marginBottom:8}},l().createElement(a.Tag,{color:"blue"},n),l().createElement("pre",{style:{background:"#f5f5f5",padding:8,borderRadius:4,fontSize:11,maxHeight:150,overflow:"auto",marginTop:4}},JSON.stringify(r,null,2)))}):l().createElement("div",{style:{color:"#999"}},"No step results yet"),l().createElement("h4",{style:{marginTop:16}},"Final Result"),l().createElement("pre",{style:{background:"#f0f5ff",padding:12,borderRadius:6,fontSize:12,maxHeight:300,overflow:"auto"}},v.finalResult?JSON.stringify(v.finalResult,null,2):"(not yet available)"),v.externalTaskIds&&Object.keys(v.externalTaskIds).length>0&&l().createElement(l().Fragment,null,l().createElement("h4",{style:{marginTop:16}},"External Task IDs"),l().createElement("pre",{style:{background:"#f5f5f5",padding:8,borderRadius:4,fontSize:11}},JSON.stringify(v.externalTaskIds,null,2))))))},Z=function(){var e,t=(e=(0,o.useFlowEngine)(),function(t){return e.context.t(t,{ns:[i.UU,"client"]})});return l().createElement("div",{style:{backgroundColor:"var(--nb-box-bg)",minHeight:"100vh"}},l().createElement("div",{style:{padding:"16px 24px",backgroundColor:"#fff",borderBottom:"1px solid #f0f0f0"}},l().createElement("h2",{style:{margin:0,fontSize:20,fontWeight:500}},t("Document Understanding - Pipeline Orchestrator"))),l().createElement("div",{style:{padding:"0 24px 24px"}},l().createElement(a.Tabs,{defaultActiveKey:"config",items:[{key:"config",label:t("Service Config"),children:l().createElement(p,null)},{key:"endpoints",label:t("Endpoints"),children:l().createElement(I,null)},{key:"pipelines",label:t("Pipelines"),children:l().createElement(W,null)},{key:"jobs",label:t("Jobs history"),children:l().createElement(Q,null)}]})))}}}]);
|