plugin-build-visualization-block 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +21 -0
  3. package/client.d.ts +2 -2
  4. package/client.js +1 -1
  5. package/dist/client/59.6bac6ada1dacea82.js +10 -0
  6. package/dist/client/index.js +1 -1
  7. package/dist/client-v2/385.1e235c5081822f07.js +10 -0
  8. package/dist/client-v2/59.cdb723e410dac32b.js +10 -0
  9. package/dist/client-v2/index.js +37 -1
  10. package/dist/externalVersion.js +12 -7
  11. package/dist/locale/en-US.json +77 -37
  12. package/dist/locale/vi-VN.json +58 -40
  13. package/dist/locale/zh-CN.json +79 -40
  14. package/dist/node_modules/zod/index.cjs +1 -1
  15. package/dist/node_modules/zod/package.json +1 -1
  16. package/dist/server/actions/build.js +8 -720
  17. package/dist/server/collections/workflow-runs.js +51 -0
  18. package/dist/server/pipeline/analyzer.js +18 -4
  19. package/dist/server/plugin.js +17 -20
  20. package/dist/server/tools/build-visualization-block.js +9 -26
  21. package/dist/server/workflow-domain.js +209 -0
  22. package/dist/server/workflow.js +466 -0
  23. package/dist/shared/blockSpec.js +1 -1
  24. package/dist/shared/workflow.js +58 -0
  25. package/package.json +14 -3
  26. package/server.d.ts +2 -2
  27. package/server.js +1 -1
  28. package/src/client/locale.ts +18 -18
  29. package/src/client/plugin.tsx +11 -0
  30. package/src/client/workflow.ts +28 -0
  31. package/src/client-v2/__tests__/buildApi.test.ts +68 -0
  32. package/src/client-v2/__tests__/modelOptions.test.ts +190 -0
  33. package/src/client-v2/__tests__/nativeModels.test.ts +77 -0
  34. package/src/client-v2/buildApi.ts +93 -0
  35. package/src/client-v2/components/AISelectors.tsx +85 -0
  36. package/src/client-v2/components/BuildForm.tsx +186 -0
  37. package/src/client-v2/components/CollectionMultiSelect.tsx +63 -0
  38. package/src/client-v2/components/NativePreview.tsx +53 -0
  39. package/src/client-v2/locale.ts +5 -0
  40. package/src/client-v2/modelOptions.ts +201 -0
  41. package/src/client-v2/models/BuildVisualizationBlockModel.tsx +95 -0
  42. package/src/client-v2/nativeBlock.ts +28 -0
  43. package/src/client-v2/pages/SettingsPage.tsx +77 -0
  44. package/src/client-v2/plugin.tsx +17 -4
  45. package/src/client-v2/workflow-fields.tsx +23 -0
  46. package/src/client-v2/workflow.ts +28 -0
  47. package/src/locale/en-US.json +77 -37
  48. package/src/locale/namespace.ts +6 -6
  49. package/src/locale/vi-VN.json +58 -40
  50. package/src/locale/zh-CN.json +79 -40
  51. package/src/server/__tests__/build-action.test.ts +121 -117
  52. package/src/server/__tests__/plugin.test.ts +19 -34
  53. package/src/server/actions/build.ts +268 -1318
  54. package/src/server/collections/workflow-runs.ts +30 -0
  55. package/src/server/pipeline/analyzer.ts +395 -368
  56. package/src/server/plugin.ts +26 -35
  57. package/src/server/tools/build-visualization-block.ts +18 -28
  58. package/src/server/workflow-domain.ts +235 -0
  59. package/src/server/workflow.ts +519 -0
  60. package/src/shared/blockSpec.ts +10 -1
  61. package/src/shared/workflow.ts +26 -0
  62. package/dist/client-v2/812.6b4f5e757b898c82.js +0 -10
@@ -0,0 +1,68 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { describe, expect, it, vi } from 'vitest';
4
+ import { loadSettings, parseBuildResult, readBuild, retryBuild, saveSettings, startBuild } from '../buildApi';
5
+
6
+ const spec = {
7
+ version: 1,
8
+ blockType: 'table',
9
+ title: 'Orders',
10
+ primaryCollection: 'orders',
11
+ dataSource: 'warehouse',
12
+ table: { fields: ['name'] },
13
+ };
14
+ describe('V2 visualization build API', () => {
15
+ it('starts a build using the server contract and preserves bigint IDs as strings', async () => {
16
+ const request = vi.fn().mockResolvedValue({ data: { data: { id: '9007199254740993' } } });
17
+ const input = {
18
+ requirement: 'sales',
19
+ dataSource: 'warehouse',
20
+ collections: ['orders', 'customers'],
21
+ llmService: 'service',
22
+ model: 'model',
23
+ };
24
+ expect(await startBuild({ request }, input)).toBe('9007199254740993');
25
+ expect(request).toHaveBeenCalledWith({
26
+ url: 'aiVisualizationBuilds:build',
27
+ method: 'post',
28
+ data: { ...input, primaryCollection: 'orders' },
29
+ });
30
+ });
31
+
32
+ it('reads and retries the exact build ID with the existing action envelope', async () => {
33
+ const request = vi.fn().mockResolvedValue({
34
+ data: { data: { id: '9007199254740993', buildPhase: 'completed', blockSpec: spec, usedFallback: true } },
35
+ });
36
+ const result = await readBuild({ request }, '9007199254740993');
37
+ expect(result.blockSpec).toEqual(spec);
38
+ expect(result.usedFallback).toBe(true);
39
+ await retryBuild({ request }, result.id);
40
+ expect(request).toHaveBeenLastCalledWith({
41
+ url: 'aiVisualizationBuilds:retry',
42
+ method: 'post',
43
+ params: { filterByTk: '9007199254740993' },
44
+ });
45
+ await expect(readBuild({ request }, 'other-id')).rejects.toThrow('Invalid build response');
46
+ });
47
+
48
+ it('rejects completed V1-only or malformed results and accepts pending results without output', () => {
49
+ expect(() =>
50
+ parseBuildResult({ id: 1, buildPhase: 'completed', blockSchema: { 'x-component': 'TableV2' } }),
51
+ ).toThrow('Invalid generated block specification');
52
+ expect(() => parseBuildResult({ id: 1, buildPhase: 'unknown' })).toThrow('Invalid build response');
53
+ expect(parseBuildResult({ id: 1, buildPhase: 'queued' }).blockSpec).toBeUndefined();
54
+ });
55
+
56
+ it('loads and saves settings using the existing singleton resource', async () => {
57
+ const settings = { defaultCollections: ['orders'], defaultDataSource: 'warehouse', enableAITool: false };
58
+ const request = vi.fn().mockResolvedValue({ data: { data: settings } });
59
+ expect(await loadSettings({ request })).toEqual(settings);
60
+ await saveSettings({ request }, settings);
61
+ expect(request).toHaveBeenLastCalledWith({
62
+ url: 'aiVisualizationBuildSettings:update',
63
+ method: 'post',
64
+ params: { filterByTk: 1 },
65
+ data: settings,
66
+ });
67
+ });
68
+ });
@@ -0,0 +1,190 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { describe, expect, it } from 'vitest';
4
+ import type { CreateModelOptions } from '@nocobase/flow-engine';
5
+ import type { BlockSpec } from '../../shared/blockSpec';
6
+ import { createNativeBlockOptions } from '../modelOptions';
7
+
8
+ const base: BlockSpec = {
9
+ version: 1,
10
+ blockType: 'table',
11
+ title: 'Orders',
12
+ dataSource: 'warehouse',
13
+ primaryCollection: 'orders',
14
+ };
15
+ const render = (name: string, mode: 'display' | 'edit') => ({
16
+ use: mode === 'edit' ? 'InputFieldModel' : 'DisplayTextFieldModel',
17
+ props: { name },
18
+ });
19
+ const items = (model: CreateModelOptions, key: string) => model.subModels?.[key] as CreateModelOptions[];
20
+ const child = (model: CreateModelOptions, key: string) => model.subModels?.[key] as CreateModelOptions;
21
+
22
+ describe('V2 native visualization model generation', () => {
23
+ it('creates native table/field models with datasource-aware bindings and sorting without changing the specification', () => {
24
+ const spec: BlockSpec = { ...base, table: { fields: ['name', 'total', 'name'], sortable: ['total'] } };
25
+ const before = JSON.stringify(spec);
26
+ const table = items(
27
+ createNativeBlockOptions(spec, render, () => false),
28
+ 'items',
29
+ )[0];
30
+ expect(table.use).toBe('TableBlockModel');
31
+ expect(table.stepParams?.resourceSettings.init).toEqual({ dataSourceKey: 'warehouse', collectionName: 'orders' });
32
+ const columns = items(table, 'columns');
33
+ expect(columns).toHaveLength(2);
34
+ expect(columns[1].stepParams?.fieldSettings.init.fieldPath).toBe('total');
35
+ expect(columns[1].stepParams?.tableColumnSettings.sorter.sorter).toBe(true);
36
+ expect(child(columns[0], 'field').use).toBe('DisplayTextFieldModel');
37
+ expect(JSON.stringify(spec)).toBe(before);
38
+ expect(JSON.stringify(table)).not.toContain('x-component');
39
+ });
40
+
41
+ it('restores requested native table actions and binds record popups to the clicked record key', () => {
42
+ const table = items(
43
+ createNativeBlockOptions(
44
+ { ...base, table: { fields: ['name'], actions: ['view', 'edit', 'delete', 'add'] } },
45
+ render,
46
+ () => false,
47
+ ),
48
+ 'items',
49
+ )[0];
50
+ expect(items(table, 'actions')[0].use).toBe('AddNewActionModel');
51
+ const actions = items(items(table, 'columns')[1], 'actions');
52
+ expect(actions.map((action) => action.use)).toEqual(['ViewActionModel', 'EditActionModel', 'DeleteActionModel']);
53
+ const tab = items(child(actions[1], 'page'), 'tabs')[0];
54
+ const form = items(child(tab, 'grid'), 'items')[0];
55
+ expect(form.stepParams?.resourceSettings.init.filterByTk).toBe('{{ctx.view.inputArgs.filterByTk}}');
56
+ expect(items(form, 'actions')[0].use).toBe('FormSubmitActionModel');
57
+ });
58
+
59
+ it('keeps standalone edit forms paginated and create forms free of another record key', () => {
60
+ const edit = items(
61
+ createNativeBlockOptions(
62
+ { ...base, blockType: 'form', form: { fields: ['name'], mode: 'edit' } },
63
+ render,
64
+ () => false,
65
+ ),
66
+ 'items',
67
+ )[0];
68
+ expect(edit.use).toBe('EditFormModel');
69
+ expect(edit.stepParams?.resourceSettings.init).not.toHaveProperty('filterByTk');
70
+ const create = items(
71
+ createNativeBlockOptions(
72
+ { ...base, blockType: 'form', form: { fields: ['name'], mode: 'create' } },
73
+ render,
74
+ () => false,
75
+ ),
76
+ 'items',
77
+ )[0];
78
+ expect(create.use).toBe('CreateFormModel');
79
+ expect(child(items(child(create, 'grid'), 'items')[0], 'field').use).toBe('InputFieldModel');
80
+ });
81
+
82
+ it('uses a popup record key only when the datasource and collection match the generated edit form', () => {
83
+ const spec: BlockSpec = { ...base, blockType: 'form', form: { fields: ['name'], mode: 'edit' } };
84
+ const context = { dataSourceKey: 'warehouse', collectionName: 'orders', filterByTk: '9007199254740993' };
85
+ const options = createNativeBlockOptions(spec, render, () => false, true, context);
86
+ expect(items(options, 'items')[0].stepParams?.resourceSettings.init.filterByTk).toBe(
87
+ '{{ctx.view.inputArgs.filterByTk}}',
88
+ );
89
+ for (const mismatch of [
90
+ { ...context, collectionName: 'customers' },
91
+ { ...context, dataSourceKey: 'main' },
92
+ ]) {
93
+ expect(
94
+ items(
95
+ createNativeBlockOptions(spec, render, () => false, true, mismatch),
96
+ 'items',
97
+ )[0].stepParams?.resourceSettings.init,
98
+ ).not.toHaveProperty('filterByTk');
99
+ }
100
+ });
101
+
102
+ it('omits mutation and popup actions from previews', () => {
103
+ const table = items(
104
+ createNativeBlockOptions(
105
+ { ...base, table: { fields: ['name'], actions: ['add', 'delete', 'edit', 'view'] } },
106
+ render,
107
+ () => false,
108
+ false,
109
+ ),
110
+ 'items',
111
+ )[0];
112
+ expect(items(table, 'actions')).toEqual([]);
113
+ expect(items(table, 'columns')).toHaveLength(1);
114
+ const form = items(
115
+ createNativeBlockOptions({ ...base, blockType: 'form', form: { fields: ['name'] } }, render, () => false, false),
116
+ 'items',
117
+ )[0];
118
+ expect(items(form, 'actions')).toEqual([]);
119
+ });
120
+
121
+ it('maps legacy chart types to native V2 configuration and uses query result aliases for axes', () => {
122
+ const root = createNativeBlockOptions(
123
+ {
124
+ ...base,
125
+ blockType: 'chart',
126
+ charts: [
127
+ {
128
+ key: 'sales',
129
+ title: 'Sales',
130
+ chartType: 'ant-design-charts.column',
131
+ measures: [{ field: 'total', aggregation: 'sum', alias: 'sales' }],
132
+ dimensions: [{ field: 'createdAt', alias: 'month', format: 'YYYY-MM' }],
133
+ config: { xField: 'createdAt', yField: 'total' },
134
+ },
135
+ ],
136
+ },
137
+ render,
138
+ () => false,
139
+ );
140
+ const chart = items(root, 'items')[0];
141
+ expect(chart.use).toBe('ChartBlockModel');
142
+ const config = chart.stepParams?.chartSettings.configure;
143
+ expect(config.query.collectionPath).toEqual(['warehouse', 'orders']);
144
+ expect(config.query.dimensions[0].format).toBe('YYYY-MM');
145
+ expect(config.chart.option.builder).toMatchObject({ type: 'bar', xField: 'month', yField: 'sales' });
146
+ });
147
+
148
+ it('uses registered chart plugins and safely renders a statistic without treating generated text as executable code', () => {
149
+ const spec: BlockSpec = {
150
+ ...base,
151
+ blockType: 'chart',
152
+ charts: [
153
+ {
154
+ key: 'total',
155
+ title: 'Total',
156
+ chartType: 'antd.statistic',
157
+ measures: [{ field: 'id', alias: 'a"; dangerous() //', aggregation: 'count' }],
158
+ },
159
+ ],
160
+ };
161
+ const statistic = items(
162
+ createNativeBlockOptions(spec, render, () => false),
163
+ 'items',
164
+ )[0];
165
+ const raw = statistic.stepParams?.chartSettings.configure.chart.option.raw;
166
+ expect(raw).toContain('["a\\"; dangerous() //"]');
167
+ const registered = items(
168
+ createNativeBlockOptions(spec, render, () => true),
169
+ 'items',
170
+ )[0];
171
+ expect(registered.stepParams?.chartSettings.configure.chart.option.builder.type).toBe('antd.statistic');
172
+ });
173
+
174
+ it('refuses unsupported or empty output instead of inserting a legacy schema or an unrelated chart', () => {
175
+ expect(() => createNativeBlockOptions({ ...base, table: { fields: [] } }, render, () => false)).toThrow(
176
+ 'No compatible field renderer',
177
+ );
178
+ expect(() =>
179
+ createNativeBlockOptions(
180
+ {
181
+ ...base,
182
+ blockType: 'chart',
183
+ charts: [{ key: 'x', title: 'x', chartType: 'unknown', measures: [{ field: 'id', alias: 'count' }] }],
184
+ },
185
+ render,
186
+ () => false,
187
+ ),
188
+ ).toThrow('No compatible chart configuration');
189
+ });
190
+ });
@@ -0,0 +1,77 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { describe, expect, it, vi } from 'vitest';
4
+ import * as client from '@nocobase/client-v2';
5
+ import { FlowEngine, FlowModel, type CreateModelOptions } from '@nocobase/flow-engine';
6
+ import type { BlockSpec } from '../../shared/blockSpec';
7
+ import { BuildVisualizationBlockModel } from '../models/BuildVisualizationBlockModel';
8
+ import { buildNativeOptions } from '../nativeBlock';
9
+
10
+ function createEngine() {
11
+ const engine = new FlowEngine();
12
+ const models: Record<string, typeof FlowModel> = {};
13
+ for (const [name, value] of Object.entries(client)) {
14
+ if (typeof value === 'function' && value.prototype instanceof FlowModel) models[name] = value as typeof FlowModel;
15
+ }
16
+ engine.registerModels({ ...models, BuildVisualizationBlockModel });
17
+ engine.context.defineProperty('app', { value: { pm: { get: () => undefined } } });
18
+ engine.context.defineProperty('api', { value: new client.APIClient({ baseURL: 'http://example.test/api/' }) });
19
+ engine.context.dataSourceManager.getDataSource('main').addCollection({
20
+ name: 'orders',
21
+ filterTargetKey: 'id',
22
+ fields: [
23
+ { name: 'id', type: 'integer', interface: 'integer' },
24
+ { name: 'name', type: 'string', interface: 'input' },
25
+ ],
26
+ });
27
+ return engine;
28
+ }
29
+
30
+ const spec: BlockSpec = {
31
+ version: 1,
32
+ title: 'Orders',
33
+ dataSource: 'main',
34
+ primaryCollection: 'orders',
35
+ blockType: 'table',
36
+ table: { fields: ['name'] },
37
+ };
38
+
39
+ describe('V2 native model tree integration', () => {
40
+ it('instantiates real table/field models and restores their datasource/field bindings after serialization', async () => {
41
+ const engine = createEngine();
42
+ const host = engine.createModel<BuildVisualizationBlockModel>({ use: 'BuildVisualizationBlockModel' });
43
+ const grid = await engine.createModelAsync<client.BlockGridModel>(buildNativeOptions(host.context, spec));
44
+ const table = grid.subModels.items[0] as client.TableBlockModel;
45
+ expect(table).toBeInstanceOf(client.TableBlockModel);
46
+ expect(table.collection.name).toBe('orders');
47
+ expect(table.resource.getDataSourceKey()).toBe('main');
48
+ expect(table.subModels.columns[0].collectionField.name).toBe('name');
49
+ const restoredEngine = createEngine();
50
+ const restored = await restoredEngine.createModelAsync<client.BlockGridModel>(
51
+ grid.serialize() as CreateModelOptions,
52
+ );
53
+ const restoredTable = restored.subModels.items[0] as client.TableBlockModel;
54
+ expect(restoredTable.subModels.columns[0].collectionField.name).toBe('name');
55
+ expect(restoredTable.subModels.columns[0].subModels.field).toBeInstanceOf(client.DisplayTextFieldModel);
56
+ });
57
+
58
+ it('creates real editable form fields and restores the existing tree when persistence fails', async () => {
59
+ const engine = createEngine();
60
+ const host = engine.createModel<BuildVisualizationBlockModel>({ use: 'BuildVisualizationBlockModel' });
61
+ const formSpec: BlockSpec = { ...spec, blockType: 'form', form: { mode: 'create', fields: ['name'] } };
62
+ host.pendingOptions = buildNativeOptions(host.context, formSpec);
63
+ const save = vi.spyOn(host, 'save').mockResolvedValue(undefined);
64
+ const selection = { buildId: '9007199254740993', spec: formSpec };
65
+ await host.installGenerated(selection);
66
+ const previous = host.subModels.content;
67
+ const form = (previous as client.BlockGridModel).subModels.items[0] as client.CreateFormModel;
68
+ expect(form).toBeInstanceOf(client.CreateFormModel);
69
+ expect(form.subModels.grid.subModels.items[0].subModels.field).toBeInstanceOf(client.InputFieldModel);
70
+ expect(form.subModels.actions[0]).toBeInstanceOf(client.FormSubmitActionModel);
71
+ host.pendingOptions = buildNativeOptions(host.context, spec);
72
+ save.mockRejectedValue(new Error('save failed'));
73
+ await expect(host.installGenerated({ buildId: 'new', spec })).rejects.toThrow('save failed');
74
+ expect(host.subModels.content).toBe(previous);
75
+ expect(host.props.generationFingerprint).toBe(JSON.stringify(selection));
76
+ });
77
+ });
@@ -0,0 +1,93 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import type { APIClient } from '@nocobase/client-v2';
4
+ import { blockSpecSchema, type BlockSpec } from '../shared/blockSpec';
5
+ import { ACTIONS, BUILD_PHASES, type BuildPhase, SETTINGS_COLLECTION_NAME } from '../shared/constants';
6
+
7
+ type BuildApi = Pick<APIClient, 'request'>;
8
+ export interface BuildSettings {
9
+ defaultDataSource?: string;
10
+ defaultCollections?: string[];
11
+ defaultLLMService?: string;
12
+ defaultModel?: string;
13
+ enableAITool?: boolean;
14
+ }
15
+ export interface BuildInput {
16
+ requirement: string;
17
+ dataSource: string;
18
+ collections: string[];
19
+ llmService: string;
20
+ model: string;
21
+ }
22
+ export interface BuildSelection {
23
+ buildId: string;
24
+ spec: BlockSpec;
25
+ }
26
+ export interface BuildResult {
27
+ id: string;
28
+ buildPhase: BuildPhase;
29
+ blockSpec?: BlockSpec;
30
+ usedFallback: boolean;
31
+ adjustments: unknown;
32
+ errorMessage?: string;
33
+ }
34
+
35
+ export function parseBuildResult(value: unknown): BuildResult {
36
+ if (!value || typeof value !== 'object') throw new Error('Invalid build response');
37
+ const record = value as Record<string, unknown>;
38
+ if (typeof record.id !== 'string' && typeof record.id !== 'number') throw new Error('Invalid build response');
39
+ if (!BUILD_PHASES.includes(record.buildPhase as BuildPhase)) throw new Error('Invalid build response');
40
+ const parsed = blockSpecSchema.safeParse(record.blockSpec);
41
+ if (record.buildPhase === 'completed' && !parsed.success) throw new Error('Invalid generated block specification');
42
+ return {
43
+ id: String(record.id),
44
+ buildPhase: record.buildPhase as BuildPhase,
45
+ blockSpec: parsed.success ? parsed.data : undefined,
46
+ usedFallback: record.usedFallback === true,
47
+ adjustments: record.adjustments,
48
+ errorMessage: typeof record.errorMessage === 'string' ? record.errorMessage : undefined,
49
+ };
50
+ }
51
+
52
+ export async function loadSettings(api: BuildApi) {
53
+ const response = await api.request<{ data: BuildSettings }>({
54
+ url: `${SETTINGS_COLLECTION_NAME}:publicGet`,
55
+ method: 'post',
56
+ });
57
+ return response.data.data;
58
+ }
59
+
60
+ export async function saveSettings(api: BuildApi, values: BuildSettings) {
61
+ await api.request({
62
+ url: `${SETTINGS_COLLECTION_NAME}:update`,
63
+ method: 'post',
64
+ params: { filterByTk: 1 },
65
+ data: values,
66
+ });
67
+ }
68
+
69
+ export async function startBuild(api: BuildApi, input: BuildInput): Promise<string> {
70
+ const response = await api.request<{ data: { id?: string | number } }>({
71
+ url: ACTIONS.build,
72
+ method: 'post',
73
+ data: { ...input, primaryCollection: input.collections[0] },
74
+ });
75
+ const id = response.data.data.id;
76
+ if (id == null || id === '') throw new Error('Invalid build response');
77
+ return String(id);
78
+ }
79
+
80
+ export async function readBuild(api: BuildApi, id: string): Promise<BuildResult> {
81
+ const response = await api.request<{ data: unknown }>({
82
+ url: ACTIONS.getResult,
83
+ method: 'post',
84
+ params: { filterByTk: id },
85
+ });
86
+ const result = parseBuildResult(response.data.data);
87
+ if (result.id !== id) throw new Error('Invalid build response');
88
+ return result;
89
+ }
90
+
91
+ export async function retryBuild(api: BuildApi, id: string) {
92
+ await api.request({ url: ACTIONS.retry, method: 'post', params: { filterByTk: id } });
93
+ }
@@ -0,0 +1,85 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { useApp } from '@nocobase/client-v2';
4
+ import { useRequest } from 'ahooks';
5
+ import { Select } from 'antd';
6
+ import React from 'react';
7
+ import { useT } from '../locale';
8
+
9
+ export function ServiceSelect({
10
+ value,
11
+ onChange,
12
+ disabled,
13
+ }: {
14
+ value?: string;
15
+ onChange?: (value?: string) => void;
16
+ disabled?: boolean;
17
+ }) {
18
+ const api = useApp().apiClient;
19
+ const t = useT();
20
+ const list = useRequest(async () => {
21
+ const response = await api.resource('ai').listLLMServices();
22
+ return response.data.data as Array<{ name: string; title?: string }>;
23
+ });
24
+ return (
25
+ <Select
26
+ value={value}
27
+ onChange={onChange}
28
+ disabled={disabled}
29
+ loading={list.loading}
30
+ allowClear
31
+ showSearch
32
+ aria-label={t('AI service')}
33
+ style={{ width: '100%' }}
34
+ optionFilterProp="label"
35
+ status={list.error ? 'error' : undefined}
36
+ notFoundContent={list.error ? t('Failed to load the list') : undefined}
37
+ options={list.data?.map((service) => ({ label: service.title || service.name, value: service.name }))}
38
+ />
39
+ );
40
+ }
41
+
42
+ export function ModelSelect({
43
+ service,
44
+ value,
45
+ onChange,
46
+ disabled,
47
+ }: {
48
+ service?: string;
49
+ value?: string;
50
+ onChange?: (value?: string) => void;
51
+ disabled?: boolean;
52
+ }) {
53
+ const api = useApp().apiClient;
54
+ const t = useT();
55
+ const list = useRequest(
56
+ async () => {
57
+ const response = await api.resource('ai').listModels({ llmService: service });
58
+ return response.data.data as Array<{ id?: string; name?: string }>;
59
+ },
60
+ { ready: !!service, refreshDeps: [service] },
61
+ );
62
+ return (
63
+ <Select
64
+ value={value}
65
+ onChange={onChange}
66
+ disabled={disabled || !service}
67
+ loading={!!service && list.loading}
68
+ aria-label={t('Model')}
69
+ style={{ width: '100%' }}
70
+ allowClear
71
+ showSearch
72
+ optionFilterProp="label"
73
+ status={list.error ? 'error' : undefined}
74
+ notFoundContent={list.error ? t('Failed to load the list') : undefined}
75
+ options={
76
+ service
77
+ ? list.data?.flatMap((model) => {
78
+ const name = model.id || model.name;
79
+ return name ? [{ label: name, value: name }] : [];
80
+ })
81
+ : []
82
+ }
83
+ />
84
+ );
85
+ }