plugin-build-ui-template 1.0.3 → 1.0.6

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.
@@ -1,454 +1,495 @@
1
- import { Context, Next } from '@nocobase/actions';
2
- import { Repository } from '@nocobase/database';
3
- import type { Application } from '@nocobase/server';
4
- // @ts-ignore
5
- import { PluginAIServer } from '@nocobase/plugin-ai';
6
- import { HumanMessage, SystemMessage } from '@langchain/core/messages';
7
- import { uid } from '@nocobase/utils';
8
-
9
- export const WORKER_JOB_BUILD_UI_TEMPLATE_PROCESS = 'build-ui-template:process';
10
- const BUILD_TEMPLATE_QUEUE_CHANNEL = 'plugin-build-ui-template.build';
11
- const BUILD_TEMPLATE_QUEUE_TIMEOUT_MS = 10 * 60 * 1000;
12
- const BUILD_TEMPLATE_QUEUE_POLL_INTERVAL_MS = 5000;
13
- const BUILD_TEMPLATE_QUEUE_WAKE_CHANNEL = 'plugin-build-ui-template.build.wake';
14
-
15
- type BuildQueueMessage = {
16
- spaceId: string;
17
- runId: string;
18
- queuedAt?: string;
19
- };
20
-
21
- type BuildRunContext = {
22
- spaceId: string;
23
- runId: string;
24
- };
25
-
26
- let buildQueueTimer: NodeJS.Timeout | null = null;
27
- let buildQueueKickTimer: NodeJS.Timeout | null = null;
28
- let buildQueueProcessing = false;
29
- let buildQueueWakeHandler: ((message?: any) => Promise<void>) | null = null;
30
-
31
- class StaleBuildRunError extends Error {
32
- constructor(spaceId: string, runId: string) {
33
- super(`Build run ${runId} for space ${spaceId} is no longer active`);
34
- this.name = 'StaleBuildRunError';
35
- }
36
- }
37
-
38
- // 1. Triggers building
39
- export async function build(ctx: Context, next: Next) {
40
- const { filterByTk } = ctx.action.params;
41
- if (!filterByTk) {
42
- return ctx.throw(400, 'spaceId is required');
43
- }
44
-
45
- const spaceRepo = ctx.db.getRepository('aiBuildUiTemplateSpaces');
46
- const space = await spaceRepo.findById(filterByTk);
47
- if (!space) {
48
- return ctx.throw(404, 'Space not found');
49
- }
50
-
51
- const runId = uid();
52
- const now = new Date();
53
-
54
- await spaceRepo.update({
55
- filterByTk,
56
- values: {
57
- status: 'building',
58
- buildPhase: 'queued',
59
- buildRunId: runId,
60
- buildQueuedAt: now,
61
- buildLog: 'Build requested, queuing job...',
62
- },
63
- transaction: ctx.transaction,
64
- });
65
-
66
- ctx.body = {
67
- result: 'ok',
68
- runId,
69
- };
70
-
71
- await next();
72
-
73
- // Push to local event queue & wake worker
74
- const app = ctx.app;
75
- setTimeout(() => {
76
- enqueueLocalBuild(app, { spaceId: String(filterByTk), runId });
77
- }, 100);
78
- }
79
-
80
- // 2. Queue Mechanics
81
- function enqueueLocalBuild(app: Application, message: BuildQueueMessage) {
82
- app.log?.info(`[plugin-build-ui-template] Enqueued build ${message.runId} for space "${message.spaceId}"`);
83
- publishBuildQueueWake(app, message);
84
- }
85
-
86
- async function publishBuildQueueWake(app: Application, message?: BuildQueueMessage) {
87
- try {
88
- await (app as any).pubSubManager?.publish?.(
89
- BUILD_TEMPLATE_QUEUE_WAKE_CHANNEL,
90
- { spaceId: message?.spaceId, runId: message?.runId },
91
- );
92
- } catch (error: any) {
93
- app.log?.debug(`[plugin-build-ui-template] Wake publish skipped: ${error?.message || error}`);
94
- }
95
- }
96
-
97
- export function registerBuildTemplateQueue(app: Application) {
98
- if (buildQueueTimer) return;
99
-
100
- buildQueueWakeHandler = async () => {
101
- scheduleBuildQueueTick(app, 0);
102
- };
103
-
104
- const subscribe = (app as any).pubSubManager?.subscribe?.(BUILD_TEMPLATE_QUEUE_WAKE_CHANNEL, buildQueueWakeHandler);
105
- if (subscribe?.catch) {
106
- subscribe.catch((error: any) => {
107
- app.log?.debug(`[plugin-build-ui-template] Wake subscribe skipped: ${error?.message || error}`);
108
- });
109
- }
110
-
111
- buildQueueTimer = setInterval(() => scheduleBuildQueueTick(app, 0), BUILD_TEMPLATE_QUEUE_POLL_INTERVAL_MS);
112
- (buildQueueTimer as any).unref?.();
113
- scheduleBuildQueueTick(app, 1000);
114
- }
115
-
116
- export function unregisterBuildTemplateQueue(app: Application) {
117
- if (buildQueueTimer) {
118
- clearInterval(buildQueueTimer);
119
- buildQueueTimer = null;
120
- }
121
- if (buildQueueKickTimer) {
122
- clearTimeout(buildQueueKickTimer);
123
- buildQueueKickTimer = null;
124
- }
125
- if (buildQueueWakeHandler) {
126
- (app as any).pubSubManager?.unsubscribe?.(
127
- BUILD_TEMPLATE_QUEUE_WAKE_CHANNEL,
128
- buildQueueWakeHandler,
129
- ).catch(() => undefined);
130
- buildQueueWakeHandler = null;
131
- }
132
- buildQueueProcessing = false;
133
- }
134
-
135
- function scheduleBuildQueueTick(app: Application, delayMs: number) {
136
- if (buildQueueKickTimer) return;
137
- buildQueueKickTimer = setTimeout(() => {
138
- buildQueueKickTimer = null;
139
- runBuildQueueTick(app).catch((error) => {
140
- app.log?.error('[plugin-build-ui-template] Queue tick failed', error);
141
- });
142
- }, delayMs);
143
- (buildQueueKickTimer as any).unref?.();
144
- }
145
-
146
- async function runBuildQueueTick(app: Application) {
147
- if (buildQueueProcessing) return;
148
- buildQueueProcessing = true;
149
-
150
- try {
151
- const spaceRepo = app.db.getRepository('aiBuildUiTemplateSpaces');
152
- const queuedSpaces = await spaceRepo.find({
153
- filter: {
154
- status: 'building',
155
- buildPhase: 'queued',
156
- },
157
- sort: ['buildQueuedAt'],
158
- limit: 1,
159
- });
160
-
161
- if (!queuedSpaces || queuedSpaces.length === 0) {
162
- return;
163
- }
164
-
165
- const space = queuedSpaces[0];
166
- const run: BuildRunContext = {
167
- spaceId: String(space.get('id')),
168
- runId: String(space.get('buildRunId')),
169
- };
170
-
171
- app.log?.info(`[plugin-build-ui-template] Starting async build for space ${run.spaceId}`);
172
-
173
- // Claim run
174
- const [affected] = await spaceRepo.update({
175
- filter: {
176
- id: run.spaceId,
177
- status: 'building',
178
- buildPhase: 'queued',
179
- buildRunId: run.runId,
180
- },
181
- values: {
182
- buildPhase: 'running',
183
- buildStartedAt: new Date(),
184
- buildHeartbeatAt: new Date(),
185
- },
186
- });
187
-
188
- if (affected <= 0) {
189
- app.log?.warn(`[plugin-build-ui-template] Failed to claim build run ${run.runId}`);
190
- return;
191
- }
192
-
193
- // Keep updating heartbeat during the build
194
- const heartbeatTimer = setInterval(() => {
195
- spaceRepo.update({
196
- filter: { id: run.spaceId, buildRunId: run.runId },
197
- values: { buildHeartbeatAt: new Date() },
198
- }).catch(() => undefined);
199
- }, 10000);
200
-
201
- try {
202
- await executeBuild(app, run);
203
- } catch (err: any) {
204
- app.log?.error(`[plugin-build-ui-template] Build ${run.runId} failed`, err);
205
- await spaceRepo.update({
206
- filter: { id: run.spaceId, buildRunId: run.runId },
207
- values: {
208
- status: 'error',
209
- buildPhase: 'error',
210
- buildLog: `Generation failed: ${err.message || String(err)}`,
211
- },
212
- }).catch(() => undefined);
213
- } finally {
214
- clearInterval(heartbeatTimer);
215
- }
216
-
217
- } finally {
218
- buildQueueProcessing = false;
219
- }
220
- }
221
-
222
- export async function recoverInterruptedBuilds(app: Application) {
223
- const spaceRepo = app.db.getRepository('aiBuildUiTemplateSpaces');
224
- const runningSpaces = await spaceRepo.find({
225
- filter: {
226
- status: 'building',
227
- buildPhase: 'running',
228
- },
229
- });
230
-
231
- for (const space of runningSpaces) {
232
- const spaceId = String(space.get('id'));
233
- app.log?.info(`[plugin-build-ui-template] Re-queuing interrupted build for space ${spaceId}`);
234
- await spaceRepo.update({
235
- filterByTk: spaceId,
236
- values: {
237
- buildPhase: 'queued',
238
- buildQueuedAt: new Date(),
239
- buildLog: 'System restarted, re-queuing build job...',
240
- },
241
- });
242
- }
243
- }
244
-
245
- // 3. Generation Logic
246
- async function executeBuild(app: Application, run: BuildRunContext) {
247
- const spaceRepo = app.db.getRepository('aiBuildUiTemplateSpaces');
248
- const space = await spaceRepo.findById(run.spaceId);
249
- if (!space) throw new Error('Space not found');
250
-
251
- const { title, llmService, model, systemPrompt, promptRequirements, type, targetCollection } = space.get();
252
- if (!llmService || !model) throw new Error('LLM Service or model is missing in space settings');
253
-
254
- // Load collection metadata
255
- await updateSpace(app, run, 'preparing', 'Loading target collection metadata...');
256
- let fieldsMeta = '';
257
- if (targetCollection) {
258
- const collection = app.db.getCollection(targetCollection);
259
- if (collection) {
260
- const fields = collection.fields;
261
- fieldsMeta = Array.from(fields.values())
262
- .map((f: any) => `- Name: ${f.name}, Type: ${f.type}, Title: ${f.options?.title || f.name}`)
263
- .join('\n');
264
- }
265
- }
266
-
267
- await updateSpace(app, run, 'generating', 'AI is generating UI flow models...');
268
-
269
- const aiPlugin = app.pm.get('ai') as PluginAIServer;
270
- if (!aiPlugin) throw new Error('Plugin AI is not available');
271
-
272
- const serviceData = await aiPlugin.aiManager.getLLMService({ llmService, model });
273
- const provider = serviceData.provider;
274
-
275
- // Prompts LLM for layout
276
- const messages = [];
277
- if (systemPrompt) {
278
- messages.push(new SystemMessage(systemPrompt));
279
- } else {
280
- messages.push(
281
- new SystemMessage(
282
- `You are a senior UI UX developer specializing in NocoBase V2.
283
- You construct professional block layouts using nested JSON FlowModels.
284
-
285
- Rules:
286
- - Return ONLY a valid JSON structure representing the root FlowModel. No markdown code fences, no explanations.
287
- - The root object must contain "use" representing the block type. Common types: "EditFormModel", "DetailsBlockModel", "TableBlockModel", "GridCardBlockModel".
288
- - The layout is recursive. Sub-models should be defined in a "subModels" object, mapped by subKey.
289
- - Every subModel must have a unique "uid" placeholder (you can output temporary strings like "node_1", "node_2").
290
- - Always include standard grid layouts: a Form or Details block should have a subModel with key "grid" using "ReferenceFormGridModel" or "FormGridModel" containing a grid of fields.
291
- - Ensure correct collection binding by using target fields provided in the prompt context.
292
- `
293
- )
294
- );
295
- }
296
-
297
- let prompt = `Create a beautiful UI ${type === 'popup' ? 'Popup' : 'Block'} template for collection "${targetCollection || 'unknown'}".
298
- Requirements: ${promptRequirements || 'Create a clean, functional dashboard/form layout'}
299
- `;
300
-
301
- if (fieldsMeta) {
302
- prompt += `\nAvailable Database Fields for collection "${targetCollection}":\n${fieldsMeta}`;
303
- }
304
-
305
- messages.push(new HumanMessage(prompt));
306
-
307
- const response = await provider.chatModel.invoke(messages);
308
- const rawText = stripThink(toPlainText(response.content));
309
-
310
- await updateSpace(app, run, 'saving', 'Parsing and storing the new FlowModel...');
311
-
312
- // Parse layout tree - Highly resilient JSON boundary parsing
313
- const cleanJsonText = stripFence(rawText);
314
- const jsonStart = cleanJsonText.indexOf('{');
315
- const jsonEnd = cleanJsonText.lastIndexOf('}');
316
- const jsonText = jsonStart >= 0 && jsonEnd > jsonStart ? cleanJsonText.slice(jsonStart, jsonEnd + 1) : cleanJsonText;
317
-
318
- let parsedModel: any;
319
- try {
320
- parsedModel = JSON.parse(jsonText);
321
- } catch (err) {
322
- throw new Error(`Failed to parse AI output as JSON: ${rawText.slice(0, 300)}`);
323
- }
324
-
325
- // Set randomized UIDs to make them uniquely saveable
326
- const uidMap: Record<string, string> = {};
327
- const assignUids = (node: any) => {
328
- if (!node || typeof node !== 'object') return;
329
- const oldUid = node.uid || node['x-uid'] || uid();
330
- const newUid = uid();
331
- uidMap[oldUid] = newUid;
332
- node.uid = newUid;
333
- node['x-uid'] = newUid;
334
-
335
- if (node.subModels && typeof node.subModels === 'object') {
336
- for (const val of Object.values(node.subModels)) {
337
- const items = Array.isArray(val) ? val : [val];
338
- for (const item of items) {
339
- assignUids(item);
340
- }
341
- }
342
- }
343
- };
344
- assignUids(parsedModel);
345
-
346
- // Highly robust recursive replacement of temporary placeholder UIDs inside nested objects
347
- const replacePlaceholderUids = (val: any): any => {
348
- if (typeof val === 'string') {
349
- return uidMap[val] || val;
350
- }
351
- if (Array.isArray(val)) {
352
- return val.map(replacePlaceholderUids);
353
- }
354
- if (val && typeof val === 'object') {
355
- const next: any = {};
356
- for (const [k, v] of Object.entries(val)) {
357
- next[k] = replacePlaceholderUids(v);
358
- }
359
- return next;
360
- }
361
- return val;
362
- };
363
- parsedModel = replacePlaceholderUids(parsedModel);
364
-
365
- // Set parent relation options
366
- const configureRelations = (node: any, parentUid?: string, subKey?: string, subType?: string) => {
367
- if (!node || typeof node !== 'object') return;
368
- if (parentUid && subKey) {
369
- node.parentId = parentUid;
370
- node.subKey = subKey;
371
- node.subType = subType || 'object';
372
- }
373
- if (node.subModels && typeof node.subModels === 'object') {
374
- for (const [key, val] of Object.entries(node.subModels)) {
375
- const isArray = Array.isArray(val);
376
- const items = isArray ? val : [val];
377
- items.forEach((item: any, idx: number) => {
378
- configureRelations(item, node.uid, key, isArray ? 'array' : 'object');
379
- if (isArray) {
380
- item.sortIndex = idx + 1;
381
- }
382
- });
383
- }
384
- }
385
- };
386
- configureRelations(parsedModel);
387
-
388
- // Save tree to database
389
- const flowRepo = app.db.getRepository('flowModels') as any;
390
- if (!flowRepo || typeof flowRepo.insertModel !== 'function') {
391
- throw new Error('FlowModelRepository or insertModel is not available. Ensure plugin-flow-engine is enabled.');
392
- }
393
-
394
- const savedModel = await flowRepo.insertModel(parsedModel);
395
- const targetUid = savedModel?.uid || parsedModel.uid;
396
-
397
- // Create UI template record
398
- const templateRepo = app.db.getRepository('flowModelTemplates');
399
- const tplUid = uid();
400
- await templateRepo.create({
401
- values: {
402
- uid: tplUid,
403
- name: `${title || 'AI'} Template (${type})`,
404
- description: `AI-generated template: ${promptRequirements?.slice(0, 100) || ''}`,
405
- targetUid,
406
- useModel: parsedModel.use || 'BlockModel',
407
- type: type || 'block',
408
- collectionName: targetCollection || undefined,
409
- },
410
- });
411
-
412
- await spaceRepo.update({
413
- filterByTk: run.spaceId,
414
- values: {
415
- status: 'completed',
416
- buildPhase: 'completed',
417
- templateUid: tplUid,
418
- buildLog: `Template generated successfully! Target root FlowModel UID: ${targetUid}`,
419
- },
420
- });
421
- }
422
-
423
- async function updateSpace(app: Application, run: BuildRunContext, phase: string, log: string) {
424
- const spaceRepo = app.db.getRepository('aiBuildUiTemplateSpaces');
425
- await spaceRepo.update({
426
- filter: { id: run.spaceId, buildRunId: run.runId },
427
- values: {
428
- buildPhase: phase,
429
- buildLog: log,
430
- },
431
- }).catch(() => undefined);
432
- }
433
-
434
- function toPlainText(value: unknown) {
435
- if (typeof value === 'string') return value;
436
- if (Array.isArray(value)) {
437
- return value.map((item: any) => item?.text || item?.content || '').filter(Boolean).join('\n');
438
- }
439
- if (value && typeof value === 'object') {
440
- return (value as any).text || (value as any).content || JSON.stringify(value);
441
- }
442
- return String(value);
443
- }
444
-
445
- function stripThink(text: string) {
446
- return text.replace(/<think>[\s\S]*?(?:<\/think>|$)/gi, '').trim();
447
- }
448
-
449
- function stripFence(text: string) {
450
- return text
451
- .replace(/^```(?:json|markdown|md)?\s*/i, '')
452
- .replace(/```\s*$/i, '')
453
- .trim();
454
- }
1
+ import { Context, Next } from '@nocobase/actions';
2
+ import { Repository } from '@nocobase/database';
3
+ import type { Application } from '@nocobase/server';
4
+ // @ts-ignore
5
+ import { PluginAIServer } from '@nocobase/plugin-ai';
6
+ import { HumanMessage, SystemMessage } from '@langchain/core/messages';
7
+ import { uid } from '@nocobase/utils';
8
+
9
+ export const WORKER_JOB_BUILD_UI_TEMPLATE_PROCESS = 'build-ui-template:process';
10
+ const BUILD_TEMPLATE_QUEUE_CHANNEL = 'plugin-build-ui-template.build';
11
+ const BUILD_TEMPLATE_WORKER_ALIASES = [BUILD_TEMPLATE_QUEUE_CHANNEL];
12
+ const BUILD_TEMPLATE_QUEUE_TIMEOUT_MS = 10 * 60 * 1000;
13
+ const BUILD_TEMPLATE_QUEUE_POLL_INTERVAL_MS = 5000;
14
+ const BUILD_TEMPLATE_QUEUE_WAKE_CHANNEL = 'plugin-build-ui-template.build.wake';
15
+
16
+ type BuildQueueMessage = {
17
+ spaceId: string;
18
+ runId: string;
19
+ queuedAt?: string;
20
+ };
21
+
22
+ type BuildRunContext = {
23
+ spaceId: string;
24
+ runId: string;
25
+ };
26
+
27
+ let buildQueueTimer: NodeJS.Timeout | null = null;
28
+ let buildQueueKickTimer: NodeJS.Timeout | null = null;
29
+ let buildQueueProcessing = false;
30
+ let buildQueueWakeHandler: ((message?: any) => Promise<void>) | null = null;
31
+
32
+ class StaleBuildRunError extends Error {
33
+ constructor(spaceId: string, runId: string) {
34
+ super(`Build run ${runId} for space ${spaceId} is no longer active`);
35
+ this.name = 'StaleBuildRunError';
36
+ }
37
+ }
38
+
39
+ // 1. Triggers building
40
+ export async function build(ctx: Context, next: Next) {
41
+ const { filterByTk } = ctx.action.params;
42
+ if (!filterByTk) {
43
+ return ctx.throw(400, 'spaceId is required');
44
+ }
45
+
46
+ const spaceRepo = ctx.db.getRepository('aiBuildUiTemplateSpaces');
47
+ const space = await spaceRepo.findById(filterByTk);
48
+ if (!space) {
49
+ return ctx.throw(404, 'Space not found');
50
+ }
51
+
52
+ const runId = uid();
53
+ const now = new Date();
54
+
55
+ await spaceRepo.update({
56
+ filterByTk,
57
+ values: {
58
+ status: 'building',
59
+ buildPhase: 'queued',
60
+ buildRunId: runId,
61
+ buildQueuedAt: now,
62
+ buildLog: 'Build requested, queuing job...',
63
+ },
64
+ transaction: ctx.transaction,
65
+ });
66
+
67
+ ctx.body = {
68
+ result: 'ok',
69
+ runId,
70
+ };
71
+
72
+ await next();
73
+
74
+ // Push to local event queue & wake worker
75
+ const app = ctx.app;
76
+ setTimeout(() => {
77
+ enqueueLocalBuild(app, { spaceId: String(filterByTk), runId });
78
+ }, 100);
79
+ }
80
+
81
+ // 2. Queue Mechanics
82
+ function enqueueLocalBuild(app: Application, message: BuildQueueMessage) {
83
+ app.log?.info(`[plugin-build-ui-template] Enqueued build ${message.runId} for space "${message.spaceId}"`);
84
+ publishBuildQueueWake(app, message);
85
+ }
86
+
87
+ function isBuildTemplateWorker(app: Application) {
88
+ return app.serving(WORKER_JOB_BUILD_UI_TEMPLATE_PROCESS) || workerModeServesBuildTemplate();
89
+ }
90
+
91
+ function workerModeServesBuildTemplate() {
92
+ const workerMode = process.env.WORKER_MODE || '';
93
+ const workerModes = workerMode
94
+ .split(',')
95
+ .map((mode) => mode.trim())
96
+ .filter(Boolean);
97
+
98
+ return workerModes.some((mode) => {
99
+ if (mode === '*' || mode === 'worker' || mode === 'task' || mode === WORKER_JOB_BUILD_UI_TEMPLATE_PROCESS) {
100
+ return true;
101
+ }
102
+ return BUILD_TEMPLATE_WORKER_ALIASES.includes(mode);
103
+ });
104
+ }
105
+
106
+ async function publishBuildQueueWake(app: Application, message?: BuildQueueMessage) {
107
+ try {
108
+ await (app as any).pubSubManager?.publish?.(
109
+ BUILD_TEMPLATE_QUEUE_WAKE_CHANNEL,
110
+ { spaceId: message?.spaceId, runId: message?.runId },
111
+ { skipSelf: !isBuildTemplateWorker(app) },
112
+ );
113
+ } catch (error: any) {
114
+ app.log?.debug(`[plugin-build-ui-template] Wake publish skipped: ${error?.message || error}`);
115
+ }
116
+ }
117
+
118
+ export function registerBuildTemplateQueue(app: Application) {
119
+ if (!isBuildTemplateWorker(app)) {
120
+ app.log?.debug?.('[plugin-build-ui-template] Queue processor disabled on non-worker node');
121
+ return;
122
+ }
123
+ if (buildQueueTimer) return;
124
+
125
+ buildQueueWakeHandler = async () => {
126
+ scheduleBuildQueueTick(app, 0);
127
+ };
128
+
129
+ const subscribe = (app as any).pubSubManager?.subscribe?.(BUILD_TEMPLATE_QUEUE_WAKE_CHANNEL, buildQueueWakeHandler);
130
+ if (subscribe?.catch) {
131
+ subscribe.catch((error: any) => {
132
+ app.log?.debug(`[plugin-build-ui-template] Wake subscribe skipped: ${error?.message || error}`);
133
+ });
134
+ }
135
+
136
+ buildQueueTimer = setInterval(() => scheduleBuildQueueTick(app, 0), BUILD_TEMPLATE_QUEUE_POLL_INTERVAL_MS);
137
+ (buildQueueTimer as any).unref?.();
138
+ scheduleBuildQueueTick(app, 1000);
139
+ app.log?.info?.(
140
+ `[plugin-build-ui-template] Queue processor started (interval ${BUILD_TEMPLATE_QUEUE_POLL_INTERVAL_MS}ms)`,
141
+ );
142
+ }
143
+
144
+ export function unregisterBuildTemplateQueue(app: Application) {
145
+ if (buildQueueTimer) {
146
+ clearInterval(buildQueueTimer);
147
+ buildQueueTimer = null;
148
+ }
149
+ if (buildQueueKickTimer) {
150
+ clearTimeout(buildQueueKickTimer);
151
+ buildQueueKickTimer = null;
152
+ }
153
+ if (buildQueueWakeHandler) {
154
+ (app as any).pubSubManager
155
+ ?.unsubscribe?.(BUILD_TEMPLATE_QUEUE_WAKE_CHANNEL, buildQueueWakeHandler)
156
+ .catch(() => undefined);
157
+ buildQueueWakeHandler = null;
158
+ }
159
+ buildQueueProcessing = false;
160
+ }
161
+
162
+ function scheduleBuildQueueTick(app: Application, delayMs: number) {
163
+ if (buildQueueKickTimer) return;
164
+ buildQueueKickTimer = setTimeout(() => {
165
+ buildQueueKickTimer = null;
166
+ runBuildQueueTick(app).catch((error) => {
167
+ app.log?.error('[plugin-build-ui-template] Queue tick failed', error);
168
+ });
169
+ }, delayMs);
170
+ (buildQueueKickTimer as any).unref?.();
171
+ }
172
+
173
+ async function runBuildQueueTick(app: Application) {
174
+ if (buildQueueProcessing) return;
175
+ buildQueueProcessing = true;
176
+
177
+ try {
178
+ const spaceRepo = app.db.getRepository('aiBuildUiTemplateSpaces');
179
+ const queuedSpaces = await spaceRepo.find({
180
+ filter: {
181
+ status: 'building',
182
+ buildPhase: 'queued',
183
+ },
184
+ sort: ['buildQueuedAt'],
185
+ limit: 1,
186
+ });
187
+
188
+ if (!queuedSpaces || queuedSpaces.length === 0) {
189
+ return;
190
+ }
191
+
192
+ const space = queuedSpaces[0];
193
+ const run: BuildRunContext = {
194
+ spaceId: String(space.get('id')),
195
+ runId: String(space.get('buildRunId')),
196
+ };
197
+
198
+ app.log?.info(`[plugin-build-ui-template] Starting async build for space ${run.spaceId}`);
199
+
200
+ // Claim run
201
+ const [affected] = await spaceRepo.update({
202
+ filter: {
203
+ id: run.spaceId,
204
+ status: 'building',
205
+ buildPhase: 'queued',
206
+ buildRunId: run.runId,
207
+ },
208
+ values: {
209
+ buildPhase: 'running',
210
+ buildStartedAt: new Date(),
211
+ buildHeartbeatAt: new Date(),
212
+ },
213
+ });
214
+
215
+ if (affected <= 0) {
216
+ app.log?.warn(`[plugin-build-ui-template] Failed to claim build run ${run.runId}`);
217
+ return;
218
+ }
219
+
220
+ // Keep updating heartbeat during the build
221
+ const heartbeatTimer = setInterval(() => {
222
+ spaceRepo
223
+ .update({
224
+ filter: { id: run.spaceId, buildRunId: run.runId },
225
+ values: { buildHeartbeatAt: new Date() },
226
+ })
227
+ .catch(() => undefined);
228
+ }, 10000);
229
+
230
+ try {
231
+ await executeBuild(app, run);
232
+ } catch (err: any) {
233
+ app.log?.error(`[plugin-build-ui-template] Build ${run.runId} failed`, err);
234
+ await spaceRepo
235
+ .update({
236
+ filter: { id: run.spaceId, buildRunId: run.runId },
237
+ values: {
238
+ status: 'error',
239
+ buildPhase: 'error',
240
+ buildLog: `Generation failed: ${err.message || String(err)}`,
241
+ },
242
+ })
243
+ .catch(() => undefined);
244
+ } finally {
245
+ clearInterval(heartbeatTimer);
246
+ }
247
+ } finally {
248
+ buildQueueProcessing = false;
249
+ }
250
+ }
251
+
252
+ export async function recoverInterruptedBuilds(app: Application) {
253
+ if (!isBuildTemplateWorker(app)) {
254
+ return;
255
+ }
256
+
257
+ const spaceRepo = app.db.getRepository('aiBuildUiTemplateSpaces');
258
+ const runningSpaces = await spaceRepo.find({
259
+ filter: {
260
+ status: 'building',
261
+ buildPhase: 'running',
262
+ },
263
+ });
264
+
265
+ for (const space of runningSpaces) {
266
+ const spaceId = String(space.get('id'));
267
+ app.log?.info(`[plugin-build-ui-template] Re-queuing interrupted build for space ${spaceId}`);
268
+ await spaceRepo.update({
269
+ filterByTk: spaceId,
270
+ values: {
271
+ buildPhase: 'queued',
272
+ buildQueuedAt: new Date(),
273
+ buildLog: 'System restarted, re-queuing build job...',
274
+ },
275
+ });
276
+ }
277
+ }
278
+
279
+ // 3. Generation Logic
280
+ async function executeBuild(app: Application, run: BuildRunContext) {
281
+ const spaceRepo = app.db.getRepository('aiBuildUiTemplateSpaces');
282
+ const space = await spaceRepo.findById(run.spaceId);
283
+ if (!space) throw new Error('Space not found');
284
+
285
+ const { title, llmService, model, systemPrompt, promptRequirements, type, targetCollection } = space.get();
286
+ if (!llmService || !model) throw new Error('LLM Service or model is missing in space settings');
287
+
288
+ // Load collection metadata
289
+ await updateSpace(app, run, 'preparing', 'Loading target collection metadata...');
290
+ let fieldsMeta = '';
291
+ if (targetCollection) {
292
+ const collection = app.db.getCollection(targetCollection);
293
+ if (collection) {
294
+ const fields = collection.fields;
295
+ fieldsMeta = Array.from(fields.values())
296
+ .map((f: any) => `- Name: ${f.name}, Type: ${f.type}, Title: ${f.options?.title || f.name}`)
297
+ .join('\n');
298
+ }
299
+ }
300
+
301
+ await updateSpace(app, run, 'generating', 'AI is generating UI flow models...');
302
+
303
+ const aiPlugin = app.pm.get('ai') as PluginAIServer;
304
+ if (!aiPlugin) throw new Error('Plugin AI is not available');
305
+
306
+ const serviceData = await aiPlugin.aiManager.getLLMService({ llmService, model });
307
+ const provider = serviceData.provider;
308
+
309
+ // Prompts LLM for layout
310
+ const messages = [];
311
+ if (systemPrompt) {
312
+ messages.push(new SystemMessage(systemPrompt));
313
+ } else {
314
+ messages.push(
315
+ new SystemMessage(
316
+ `You are a senior UI UX developer specializing in NocoBase V2.
317
+ You construct professional block layouts using nested JSON FlowModels.
318
+
319
+ Rules:
320
+ - Return ONLY a valid JSON structure representing the root FlowModel. No markdown code fences, no explanations.
321
+ - The root object must contain "use" representing the block type. Common types: "EditFormModel", "DetailsBlockModel", "TableBlockModel", "GridCardBlockModel".
322
+ - The layout is recursive. Sub-models should be defined in a "subModels" object, mapped by subKey.
323
+ - Every subModel must have a unique "uid" placeholder (you can output temporary strings like "node_1", "node_2").
324
+ - Always include standard grid layouts: a Form or Details block should have a subModel with key "grid" using "ReferenceFormGridModel" or "FormGridModel" containing a grid of fields.
325
+ - Ensure correct collection binding by using target fields provided in the prompt context.
326
+ `,
327
+ ),
328
+ );
329
+ }
330
+
331
+ let prompt = `Create a beautiful UI ${type === 'popup' ? 'Popup' : 'Block'} template for collection "${
332
+ targetCollection || 'unknown'
333
+ }".
334
+ Requirements: ${promptRequirements || 'Create a clean, functional dashboard/form layout'}
335
+ `;
336
+
337
+ if (fieldsMeta) {
338
+ prompt += `\nAvailable Database Fields for collection "${targetCollection}":\n${fieldsMeta}`;
339
+ }
340
+
341
+ messages.push(new HumanMessage(prompt));
342
+
343
+ const response = await provider.chatModel.invoke(messages);
344
+ const rawText = stripThink(toPlainText(response.content));
345
+
346
+ await updateSpace(app, run, 'saving', 'Parsing and storing the new FlowModel...');
347
+
348
+ // Parse layout tree - Highly resilient JSON boundary parsing
349
+ const cleanJsonText = stripFence(rawText);
350
+ const jsonStart = cleanJsonText.indexOf('{');
351
+ const jsonEnd = cleanJsonText.lastIndexOf('}');
352
+ const jsonText = jsonStart >= 0 && jsonEnd > jsonStart ? cleanJsonText.slice(jsonStart, jsonEnd + 1) : cleanJsonText;
353
+
354
+ let parsedModel: any;
355
+ try {
356
+ parsedModel = JSON.parse(jsonText);
357
+ } catch (err) {
358
+ throw new Error(`Failed to parse AI output as JSON: ${rawText.slice(0, 300)}`);
359
+ }
360
+
361
+ // Set randomized UIDs to make them uniquely saveable
362
+ const uidMap: Record<string, string> = {};
363
+ const assignUids = (node: any) => {
364
+ if (!node || typeof node !== 'object') return;
365
+ const oldUid = node.uid || node['x-uid'] || uid();
366
+ const newUid = uid();
367
+ uidMap[oldUid] = newUid;
368
+ node.uid = newUid;
369
+ node['x-uid'] = newUid;
370
+
371
+ if (node.subModels && typeof node.subModels === 'object') {
372
+ for (const val of Object.values(node.subModels)) {
373
+ const items = Array.isArray(val) ? val : [val];
374
+ for (const item of items) {
375
+ assignUids(item);
376
+ }
377
+ }
378
+ }
379
+ };
380
+ assignUids(parsedModel);
381
+
382
+ // Highly robust recursive replacement of temporary placeholder UIDs inside nested objects
383
+ const replacePlaceholderUids = (val: any): any => {
384
+ if (typeof val === 'string') {
385
+ return uidMap[val] || val;
386
+ }
387
+ if (Array.isArray(val)) {
388
+ return val.map(replacePlaceholderUids);
389
+ }
390
+ if (val && typeof val === 'object') {
391
+ const next: any = {};
392
+ for (const [k, v] of Object.entries(val)) {
393
+ next[k] = replacePlaceholderUids(v);
394
+ }
395
+ return next;
396
+ }
397
+ return val;
398
+ };
399
+ parsedModel = replacePlaceholderUids(parsedModel);
400
+
401
+ // Set parent relation options
402
+ const configureRelations = (node: any, parentUid?: string, subKey?: string, subType?: string) => {
403
+ if (!node || typeof node !== 'object') return;
404
+ if (parentUid && subKey) {
405
+ node.parentId = parentUid;
406
+ node.subKey = subKey;
407
+ node.subType = subType || 'object';
408
+ }
409
+ if (node.subModels && typeof node.subModels === 'object') {
410
+ for (const [key, val] of Object.entries(node.subModels)) {
411
+ const isArray = Array.isArray(val);
412
+ const items = isArray ? val : [val];
413
+ items.forEach((item: any, idx: number) => {
414
+ configureRelations(item, node.uid, key, isArray ? 'array' : 'object');
415
+ if (isArray) {
416
+ item.sortIndex = idx + 1;
417
+ }
418
+ });
419
+ }
420
+ }
421
+ };
422
+ configureRelations(parsedModel);
423
+
424
+ // Save tree to database
425
+ const flowRepo = app.db.getRepository('flowModels') as any;
426
+ if (!flowRepo || typeof flowRepo.insertModel !== 'function') {
427
+ throw new Error('FlowModelRepository or insertModel is not available. Ensure plugin-flow-engine is enabled.');
428
+ }
429
+
430
+ const savedModel = await flowRepo.insertModel(parsedModel);
431
+ const targetUid = savedModel?.uid || parsedModel.uid;
432
+
433
+ // Create UI template record
434
+ const templateRepo = app.db.getRepository('flowModelTemplates');
435
+ const tplUid = uid();
436
+ await templateRepo.create({
437
+ values: {
438
+ uid: tplUid,
439
+ name: `${title || 'AI'} Template (${type})`,
440
+ description: `AI-generated template: ${promptRequirements?.slice(0, 100) || ''}`,
441
+ targetUid,
442
+ useModel: parsedModel.use || 'BlockModel',
443
+ type: type || 'block',
444
+ collectionName: targetCollection || undefined,
445
+ },
446
+ });
447
+
448
+ await spaceRepo.update({
449
+ filterByTk: run.spaceId,
450
+ values: {
451
+ status: 'completed',
452
+ buildPhase: 'completed',
453
+ templateUid: tplUid,
454
+ buildLog: `Template generated successfully! Target root FlowModel UID: ${targetUid}`,
455
+ },
456
+ });
457
+ }
458
+
459
+ async function updateSpace(app: Application, run: BuildRunContext, phase: string, log: string) {
460
+ const spaceRepo = app.db.getRepository('aiBuildUiTemplateSpaces');
461
+ await spaceRepo
462
+ .update({
463
+ filter: { id: run.spaceId, buildRunId: run.runId },
464
+ values: {
465
+ buildPhase: phase,
466
+ buildLog: log,
467
+ },
468
+ })
469
+ .catch(() => undefined);
470
+ }
471
+
472
+ function toPlainText(value: unknown) {
473
+ if (typeof value === 'string') return value;
474
+ if (Array.isArray(value)) {
475
+ return value
476
+ .map((item: any) => item?.text || item?.content || '')
477
+ .filter(Boolean)
478
+ .join('\n');
479
+ }
480
+ if (value && typeof value === 'object') {
481
+ return (value as any).text || (value as any).content || JSON.stringify(value);
482
+ }
483
+ return String(value);
484
+ }
485
+
486
+ function stripThink(text: string) {
487
+ return text.replace(/<think>[\s\S]*?(?:<\/think>|$)/gi, '').trim();
488
+ }
489
+
490
+ function stripFence(text: string) {
491
+ return text
492
+ .replace(/^```(?:json|markdown|md)?\s*/i, '')
493
+ .replace(/```\s*$/i, '')
494
+ .trim();
495
+ }