plugin-ai-api 1.0.20 → 1.0.21

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 (72) hide show
  1. package/dist/client/286.01c0e3c5fff3cccb.js +10 -0
  2. package/dist/client/302.fc3a3491b4ec2dfd.js +10 -0
  3. package/dist/client/562.17a0a299d2e5152c.js +10 -0
  4. package/dist/client/{757.71e30f2a1306562d.js → 757.a01403fb7a1bea01.js} +1 -1
  5. package/dist/client/{902.4238b04ac667c30a.js → 902.92e1daaf1ab16ebf.js} +1 -1
  6. package/dist/client/{97.37cda285d7da3a26.js → 97.72979a11a067a7c9.js} +1 -1
  7. package/dist/client/index.js +1 -1
  8. package/dist/client-v2/302.d27fe4ea9b0b3bf5.js +10 -0
  9. package/dist/client-v2/562.fb2948ee6402de95.js +10 -0
  10. package/dist/client-v2/{757.c377e2f2b054d89d.js → 757.a117ce1cf7119cea.js} +1 -1
  11. package/dist/client-v2/{902.d40d7bda106124c8.js → 902.9054d990ddc223ac.js} +1 -1
  12. package/dist/client-v2/952.94100128b7757f56.js +10 -0
  13. package/dist/client-v2/{97.fc922c37ced86831.js → 97.29c663318eebbd57.js} +1 -1
  14. package/dist/client-v2/index.js +1 -1
  15. package/dist/constants.js +36 -0
  16. package/dist/externalVersion.js +9 -10
  17. package/dist/locale/en-US.json +28 -9
  18. package/dist/locale/vi-VN.json +20 -1
  19. package/dist/locale/zh-CN.json +20 -1
  20. package/dist/server/collections/ai-api-config.js +6 -0
  21. package/dist/server/collections/ai-api-model-metadata.js +83 -0
  22. package/dist/server/plugin.js +13 -1
  23. package/dist/server/resource/ai-api-config.js +17 -0
  24. package/dist/server/routes/agent-completions.js +62 -51
  25. package/dist/server/routes/auth.js +11 -1
  26. package/dist/server/routes/chat-completions.js +145 -4
  27. package/dist/server/routes/completions.js +8 -1
  28. package/dist/server/routes/models.js +78 -20
  29. package/dist/server/routes/router.js +94 -22
  30. package/dist/server/usage.js +2 -0
  31. package/dist/server/utils/app-observability.js +110 -0
  32. package/dist/server/utils/streaming.js +15 -1
  33. package/dist/server/validation.js +18 -0
  34. package/dist/swagger.js +32 -1
  35. package/package.json +1 -1
  36. package/src/client/components/AiApiRolePermissions.tsx +11 -169
  37. package/src/client/locale.ts +11 -21
  38. package/src/client/plugin.tsx +17 -8
  39. package/src/client-v2/__tests__/settings-registration.test.tsx +58 -0
  40. package/src/client-v2/components/AiApiRolePermissions.tsx +173 -0
  41. package/src/client-v2/locale.ts +21 -1
  42. package/src/client-v2/pages/GeneralPage.tsx +13 -0
  43. package/src/client-v2/pages/ModelMetadataPage.tsx +280 -0
  44. package/src/client-v2/pages/RolePermissionsTab.tsx +14 -0
  45. package/src/client-v2/plugin.tsx +41 -1
  46. package/src/constants.ts +21 -0
  47. package/src/locale/en-US.json +28 -9
  48. package/src/locale/vi-VN.json +20 -1
  49. package/src/locale/zh-CN.json +20 -1
  50. package/src/server/__tests__/app-observability.test.ts +98 -0
  51. package/src/server/__tests__/models.test.ts +74 -0
  52. package/src/server/__tests__/request-body.test.ts +310 -0
  53. package/src/server/__tests__/streaming-observability.test.ts +51 -0
  54. package/src/server/collections/ai-api-config.ts +6 -0
  55. package/src/server/collections/ai-api-model-metadata.ts +72 -0
  56. package/src/server/plugin.ts +24 -4
  57. package/src/server/resource/ai-api-config.ts +23 -0
  58. package/src/server/routes/agent-completions.ts +77 -62
  59. package/src/server/routes/auth.ts +14 -1
  60. package/src/server/routes/chat-completions.ts +262 -4
  61. package/src/server/routes/completions.ts +14 -2
  62. package/src/server/routes/models.ts +290 -195
  63. package/src/server/routes/router.ts +136 -26
  64. package/src/server/usage.ts +2 -0
  65. package/src/server/utils/app-observability.ts +105 -0
  66. package/src/server/utils/streaming.ts +13 -1
  67. package/src/server/validation.ts +27 -0
  68. package/src/swagger.ts +38 -1
  69. package/dist/client/302.25edd5d75460acbf.js +0 -10
  70. package/dist/client/778.5c452944cb747975.js +0 -10
  71. package/dist/client-v2/302.9b27a263901d54d8.js +0 -10
  72. package/src/client/AiApiConfigPage.tsx +0 -309
@@ -0,0 +1,110 @@
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
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var app_observability_exports = {};
28
+ __export(app_observability_exports, {
29
+ addAiApiUsage: () => addAiApiUsage,
30
+ finishAiApiObservation: () => finishAiApiObservation,
31
+ markAiApiFirstProviderOutput: () => markAiApiFirstProviderOutput,
32
+ setAiApiObservationOutcome: () => setAiApiObservationOutcome,
33
+ startAiApiObservation: () => startAiApiObservation
34
+ });
35
+ module.exports = __toCommonJS(app_observability_exports);
36
+ const CONTRACT_SYMBOL = Symbol.for("nocobase.app-observability.contract");
37
+ const NOOP_HANDLE = {
38
+ markFirstByte() {
39
+ },
40
+ addInputTokens() {
41
+ },
42
+ addOutputTokens() {
43
+ },
44
+ finish() {
45
+ }
46
+ };
47
+ function state(ctx) {
48
+ return ctx.state;
49
+ }
50
+ function safely(ctx, callback) {
51
+ var _a, _b, _c;
52
+ try {
53
+ callback();
54
+ } catch (error) {
55
+ (_c = (_b = (_a = ctx.app) == null ? void 0 : _a.logger) == null ? void 0 : _b.warn) == null ? void 0 : _c.call(_b, "[ai-api] App observability callback failed", { error });
56
+ }
57
+ }
58
+ function startAiApiObservation(ctx, input) {
59
+ let handle = NOOP_HANDLE;
60
+ safely(ctx, () => {
61
+ const contract = ctx.app[CONTRACT_SYMBOL];
62
+ if (!contract || typeof contract.start !== "function") return;
63
+ const candidate = contract.start({
64
+ service: input.service,
65
+ operation: input.operation,
66
+ streaming: input.streaming,
67
+ attributes: {
68
+ mode: input.mode,
69
+ endpoint: input.operation,
70
+ ...input.model ? { model: input.model } : {}
71
+ }
72
+ });
73
+ if (candidate && typeof candidate.finish === "function") handle = candidate;
74
+ });
75
+ state(ctx).aiApiObservabilityHandle = handle;
76
+ }
77
+ function markAiApiFirstProviderOutput(ctx) {
78
+ safely(ctx, () => {
79
+ var _a;
80
+ return (_a = state(ctx).aiApiObservabilityHandle) == null ? void 0 : _a.markFirstByte();
81
+ });
82
+ }
83
+ function addAiApiUsage(ctx, usage) {
84
+ if (!usage) return;
85
+ safely(ctx, () => {
86
+ const handle = state(ctx).aiApiObservabilityHandle;
87
+ if (usage.prompt_tokens !== null) handle == null ? void 0 : handle.addInputTokens(usage.prompt_tokens);
88
+ if (usage.completion_tokens !== null) handle == null ? void 0 : handle.addOutputTokens(usage.completion_tokens);
89
+ });
90
+ }
91
+ function setAiApiObservationOutcome(ctx, outcome) {
92
+ state(ctx).aiApiObservabilityOutcome = outcome;
93
+ }
94
+ function finishAiApiObservation(ctx, fallback) {
95
+ const current = state(ctx);
96
+ const handle = current.aiApiObservabilityHandle;
97
+ if (!handle) return;
98
+ current.aiApiObservabilityHandle = void 0;
99
+ const outcome = current.aiApiObservabilityOutcome ?? fallback;
100
+ current.aiApiObservabilityOutcome = void 0;
101
+ safely(ctx, () => handle.finish(outcome));
102
+ }
103
+ // Annotate the CommonJS export names for ESM import in node:
104
+ 0 && (module.exports = {
105
+ addAiApiUsage,
106
+ finishAiApiObservation,
107
+ markAiApiFirstProviderOutput,
108
+ setAiApiObservationOutcome,
109
+ startAiApiObservation
110
+ });
@@ -26,18 +26,30 @@ var __copyProps = (to, from, except, desc) => {
26
26
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
27
  var streaming_exports = {};
28
28
  __export(streaming_exports, {
29
+ AiApiClientDisconnectedError: () => AiApiClientDisconnectedError,
29
30
  createRequestAbortController: () => createRequestAbortController,
31
+ isClientDisconnected: () => isClientDisconnected,
30
32
  isStreamingRequested: () => isStreamingRequested,
31
33
  writeResponse: () => writeResponse
32
34
  });
33
35
  module.exports = __toCommonJS(streaming_exports);
36
+ class AiApiClientDisconnectedError extends Error {
37
+ code = "client_disconnected";
38
+ constructor() {
39
+ super("Client disconnected");
40
+ this.name = "AiApiClientDisconnectedError";
41
+ }
42
+ }
43
+ function isClientDisconnected(ctx, error) {
44
+ return ctx.req.aborted === true || error instanceof AiApiClientDisconnectedError;
45
+ }
34
46
  function isStreamingRequested(value) {
35
47
  return value !== false;
36
48
  }
37
49
  function createRequestAbortController(ctx) {
38
50
  const controller = new AbortController();
39
51
  const abort = () => {
40
- if (!ctx.res.writableEnded) controller.abort(new Error("Client disconnected"));
52
+ if (!ctx.res.writableEnded) controller.abort(new AiApiClientDisconnectedError());
41
53
  };
42
54
  ctx.req.once("aborted", abort);
43
55
  ctx.res.once("close", abort);
@@ -74,7 +86,9 @@ function waitForDrain(ctx) {
74
86
  }
75
87
  // Annotate the CommonJS export names for ESM import in node:
76
88
  0 && (module.exports = {
89
+ AiApiClientDisconnectedError,
77
90
  createRequestAbortController,
91
+ isClientDisconnected,
78
92
  isStreamingRequested,
79
93
  writeResponse
80
94
  });
@@ -36,6 +36,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
36
36
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
37
  var validation_exports = {};
38
38
  __export(validation_exports, {
39
+ validateModelMetadata: () => validateModelMetadata,
39
40
  validateModelPrice: () => validateModelPrice,
40
41
  validateQuotaPolicy: () => validateQuotaPolicy
41
42
  });
@@ -77,6 +78,22 @@ async function validateModelPrice(db, model) {
77
78
  });
78
79
  if (overlap) throw new Error("An enabled price already overlaps this effective period.");
79
80
  }
81
+ function requirePositiveIntegerOrNull(value, field) {
82
+ if (value === null || value === void 0 || value === "") return;
83
+ const parsed = Number(value);
84
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) throw new Error(`${field} must be a positive integer.`);
85
+ }
86
+ function validateModelMetadata(model) {
87
+ if (!String(model.get("llmService") ?? "").trim()) throw new Error("llmService is required.");
88
+ if (!String(model.get("model") ?? "").trim()) throw new Error("model is required.");
89
+ requirePositiveIntegerOrNull(model.get("contextWindow"), "contextWindow");
90
+ requirePositiveIntegerOrNull(model.get("maxCompletionTokens"), "maxCompletionTokens");
91
+ const contextWindow = model.get("contextWindow");
92
+ const maxCompletionTokens = model.get("maxCompletionTokens");
93
+ if (contextWindow !== null && contextWindow !== void 0 && contextWindow !== "" && maxCompletionTokens !== null && maxCompletionTokens !== void 0 && maxCompletionTokens !== "" && Number(maxCompletionTokens) > Number(contextWindow)) {
94
+ throw new Error("maxCompletionTokens cannot exceed contextWindow.");
95
+ }
96
+ }
80
97
  function validateQuotaPolicy(model) {
81
98
  if (!["daily", "monthly"].includes(String(model.get("periodType")))) {
82
99
  throw new Error("periodType must be daily or monthly.");
@@ -97,6 +114,7 @@ function validateQuotaPolicy(model) {
97
114
  }
98
115
  // Annotate the CommonJS export names for ESM import in node:
99
116
  0 && (module.exports = {
117
+ validateModelMetadata,
100
118
  validateModelPrice,
101
119
  validateQuotaPolicy
102
120
  });
package/dist/swagger.js CHANGED
@@ -277,6 +277,13 @@ var swagger_default = {
277
277
  rateLimitPerMinute: {
278
278
  type: "integer",
279
279
  description: "Max requests per minute per user (0 = unlimited)"
280
+ },
281
+ maxRequestBodyMb: {
282
+ type: "integer",
283
+ minimum: 1,
284
+ maximum: 100,
285
+ default: 10,
286
+ description: "Max request body size in megabytes. Requests above this return 413. The gateway buffers each body in memory, so values above 100 are rejected."
280
287
  }
281
288
  }
282
289
  },
@@ -289,11 +296,35 @@ var swagger_default = {
289
296
  owned_by: { type: "string" }
290
297
  }
291
298
  },
299
+ ContentBlock: {
300
+ type: "object",
301
+ description: "A multimodal content block. Only text and image_url blocks are forwarded to the provider; any other type is rejected with 400 unsupported_content_block.",
302
+ properties: {
303
+ type: { type: "string", enum: ["text", "image_url"] },
304
+ text: { type: "string" },
305
+ image_url: {
306
+ type: "object",
307
+ properties: {
308
+ url: {
309
+ type: "string",
310
+ description: "An https URL or a base64 data URL, e.g. data:image/png;base64,iVBORw0KGgo...",
311
+ example: "data:image/png;base64,iVBORw0KGgo..."
312
+ },
313
+ detail: { type: "string", enum: ["auto", "low", "high"] }
314
+ },
315
+ required: ["url"]
316
+ }
317
+ },
318
+ required: ["type"]
319
+ },
292
320
  ChatMessage: {
293
321
  type: "object",
294
322
  properties: {
295
323
  role: { type: "string", enum: ["system", "user", "assistant", "tool"] },
296
- content: { type: "string" },
324
+ content: {
325
+ description: 'Plain text, or an array of content blocks for multimodal requests. Inline base64 images inflate the payload by about 33%; see "Max request body size" in the gateway settings.',
326
+ oneOf: [{ type: "string" }, { type: "array", items: { $ref: "#/components/schemas/ContentBlock" } }]
327
+ },
297
328
  name: { type: "string" },
298
329
  tool_call_id: { type: "string" },
299
330
  tool_calls: { type: "array", items: { $ref: "#/components/schemas/ToolCall" } }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "plugin-ai-api",
3
- "version": "1.0.20",
3
+ "version": "1.0.21",
4
4
  "main": "dist/server/index.js",
5
5
  "dependencies": {},
6
6
  "peerDependencies": {
@@ -1,169 +1,11 @@
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
- import React, { useEffect, useState } from 'react';
11
- import { useApp } from '@nocobase/client-v2';
12
- import { Card, Switch, Select, Space, Typography, Spin, Divider } from 'antd';
13
-
14
- const { Text } = Typography;
15
-
16
- interface AiEmployee {
17
- username: string;
18
- nickname: string;
19
- }
20
-
21
- interface RolePermRecord {
22
- id?: number;
23
- roleName: string;
24
- enabled: boolean;
25
- allowAllEmployees: boolean;
26
- allowedEmployees: string[];
27
- }
28
-
29
- /**
30
- * Permission tab shown in Settings → Users & Permissions → [Role] → "AI API" tab.
31
- * Lets admins control whether a role can use the AI API and which AI Employees it may access.
32
- */
33
- export function AiApiRolePermissions({ role }: { role: any }) {
34
- const api = useApp().apiClient;
35
- const [loading, setLoading] = useState(true);
36
- const [saving, setSaving] = useState(false);
37
- const [employees, setEmployees] = useState<AiEmployee[]>([]);
38
- const [record, setRecord] = useState<RolePermRecord | null>(null);
39
-
40
- const roleName = role?.name;
41
-
42
- useEffect(() => {
43
- if (!roleName) return;
44
- loadData();
45
- // eslint-disable-next-line react-hooks/exhaustive-deps
46
- }, [roleName]);
47
-
48
- const loadData = async () => {
49
- setLoading(true);
50
- try {
51
- const [permRes, empRes] = await Promise.all([
52
- api.request({
53
- url: 'aiApiRolePermissions',
54
- params: { filter: { roleName }, paginate: false },
55
- }),
56
- api.request({ url: 'aiEmployees:list', params: { paginate: false } }),
57
- ]);
58
-
59
- const existing = permRes?.data?.data?.[0];
60
- setRecord(
61
- existing
62
- ? {
63
- id: existing.id,
64
- roleName: existing.roleName,
65
- enabled: !!existing.enabled,
66
- allowAllEmployees: existing.allowAllEmployees !== false,
67
- allowedEmployees: existing.allowedEmployees || [],
68
- }
69
- : {
70
- roleName,
71
- enabled: false,
72
- allowAllEmployees: true,
73
- allowedEmployees: [],
74
- },
75
- );
76
-
77
- setEmployees(
78
- (empRes?.data?.data || []).map((e: any) => ({
79
- username: e.username,
80
- nickname: e.nickname || e.username,
81
- })),
82
- );
83
- } catch (err) {
84
- console.error('Failed to load AI API role permissions:', err);
85
- } finally {
86
- setLoading(false);
87
- }
88
- };
89
-
90
- const save = async (patch: Partial<RolePermRecord>) => {
91
- if (!record) return;
92
- const next = { ...record, ...patch };
93
- setRecord(next);
94
- setSaving(true);
95
- try {
96
- if (next.id) {
97
- await api.request({
98
- url: `aiApiRolePermissions/${next.id}`,
99
- method: 'PUT',
100
- data: next,
101
- });
102
- } else {
103
- const res = await api.request({
104
- url: 'aiApiRolePermissions',
105
- method: 'POST',
106
- data: next,
107
- });
108
- const created = res?.data?.data;
109
- if (created?.id) {
110
- setRecord({ ...next, id: created.id });
111
- }
112
- }
113
- } catch (err) {
114
- console.error('Failed to save AI API role permissions:', err);
115
- // Revert on error
116
- setRecord(record);
117
- } finally {
118
- setSaving(false);
119
- }
120
- };
121
-
122
- if (loading) return <Spin />;
123
-
124
- return (
125
- <Card bordered={false}>
126
- <Space direction="vertical" style={{ width: '100%' }} size="middle">
127
- <Space>
128
- <Switch checked={!!record?.enabled} loading={saving} onChange={(checked) => save({ enabled: checked })} />
129
- <Text strong>Allow this role to use the AI API</Text>
130
- </Space>
131
-
132
- {record?.enabled && (
133
- <>
134
- <Divider style={{ margin: '8px 0' }} />
135
- <Space>
136
- <Switch
137
- checked={!!record?.allowAllEmployees}
138
- loading={saving}
139
- onChange={(checked) => save({ allowAllEmployees: checked })}
140
- />
141
- <Text>Allow all AI Employees</Text>
142
- </Space>
143
-
144
- {!record?.allowAllEmployees && (
145
- <div>
146
- <Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>
147
- Select which AI Employees this role may use:
148
- </Text>
149
- <Select
150
- mode="multiple"
151
- allowClear
152
- style={{ width: '100%', maxWidth: 480 }}
153
- placeholder="Select allowed AI Employees"
154
- value={record?.allowedEmployees || []}
155
- options={employees.map((e) => ({
156
- label: `${e.nickname} (${e.username})`,
157
- value: e.username,
158
- }))}
159
- onChange={(vals) => save({ allowedEmployees: vals })}
160
- disabled={saving}
161
- />
162
- </div>
163
- )}
164
- </>
165
- )}
166
- </Space>
167
- </Card>
168
- );
169
- }
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
+ // Implementation lives in client-v2; imports may only flow v1 -> v2, never back.
11
+ export { AiApiRolePermissions } from '../../client-v2/components/AiApiRolePermissions';
@@ -1,21 +1,11 @@
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
- import { tExpr as _tExpr, useFlowEngine } from '@nocobase/flow-engine';
11
- // @ts-ignore
12
- import pkg from './../../package.json';
13
-
14
- export function useT() {
15
- const engine = useFlowEngine();
16
- return (str: string) => engine.context.t(str, { ns: [pkg.name, 'client'] });
17
- }
18
-
19
- export function tExpr(key: string) {
20
- return _tExpr(key, { ns: [pkg.name, 'client'] });
21
- }
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
+ // Implementation lives in client-v2; imports may only flow v1 -> v2, never back.
11
+ export { tExpr, useT } from '../client-v2/locale';
@@ -9,10 +9,12 @@
9
9
 
10
10
  import { Plugin, lazy } from '@nocobase/client';
11
11
  import PluginACLClient from '@nocobase/plugin-acl/client';
12
+ import { AI_API_ACL_SNIPPET } from '../constants';
12
13
  import React from 'react';
13
14
 
14
15
  const AiApiConfigPage = React.lazy(() => import('../client-v2/pages/GeneralPage'));
15
16
  const AiApiModelPricingPage = React.lazy(() => import('../client-v2/pages/ModelPricingPage'));
17
+ const AiApiModelMetadataPage = React.lazy(() => import('../client-v2/pages/ModelMetadataPage'));
16
18
  const AiApiUserQuotasPage = React.lazy(() => import('../client-v2/pages/UserQuotasPage'));
17
19
  const AiApiUsagePage = React.lazy(() => import('../client-v2/pages/UsagePage'));
18
20
  const { AiApiRolePermissions } = lazy(() => import('./components/AiApiRolePermissions'), 'AiApiRolePermissions');
@@ -22,35 +24,42 @@ export class PluginAiApiClient extends Plugin {
22
24
  this.app.pluginSettingsManager.add('ai-api', {
23
25
  icon: 'ApiOutlined',
24
26
  title: this.t('AI API Gateway'),
25
- aclSnippet: 'pm.ai-api.configuration',
27
+ aclSnippet: AI_API_ACL_SNIPPET,
26
28
  });
27
29
 
28
30
  this.app.pluginSettingsManager.add('ai-api.config', {
29
31
  title: this.t('Configuration'),
30
32
  Component: AiApiConfigPage,
31
- aclSnippet: 'pm.ai-api.configuration',
33
+ aclSnippet: AI_API_ACL_SNIPPET,
32
34
  sort: 1,
33
35
  });
34
36
 
35
37
  this.app.pluginSettingsManager.add('ai-api.model-pricing', {
36
38
  title: this.t('Model pricing'),
37
39
  Component: AiApiModelPricingPage,
38
- aclSnippet: 'pm.ai-api.configuration',
40
+ aclSnippet: AI_API_ACL_SNIPPET,
39
41
  sort: 2,
40
42
  });
41
43
 
44
+ this.app.pluginSettingsManager.add('ai-api.model-metadata', {
45
+ title: this.t('Model metadata'),
46
+ Component: AiApiModelMetadataPage,
47
+ aclSnippet: AI_API_ACL_SNIPPET,
48
+ sort: 3,
49
+ });
50
+
42
51
  this.app.pluginSettingsManager.add('ai-api.user-quotas', {
43
52
  title: this.t('User quotas'),
44
53
  Component: AiApiUserQuotasPage,
45
- aclSnippet: 'pm.ai-api.configuration',
46
- sort: 3,
54
+ aclSnippet: AI_API_ACL_SNIPPET,
55
+ sort: 4,
47
56
  });
48
57
 
49
58
  this.app.pluginSettingsManager.add('ai-api.usage', {
50
59
  title: this.t('Usage'),
51
60
  Component: AiApiUsagePage,
52
- aclSnippet: 'pm.ai-api.configuration',
53
- sort: 4,
61
+ aclSnippet: AI_API_ACL_SNIPPET,
62
+ sort: 5,
54
63
  });
55
64
 
56
65
  // Add "AI API" tab in Settings → Users & Permissions → [Role]
@@ -58,7 +67,7 @@ export class PluginAiApiClient extends Plugin {
58
67
  if (aclPlugin?.settingsUI) {
59
68
  aclPlugin.settingsUI.addPermissionsTab(({ t, TabLayout, activeRole }) => ({
60
69
  key: 'aiApi',
61
- label: 'AI API',
70
+ label: t('AI API', { ns: ['plugin-ai-api', 'client'] }),
62
71
  sort: 25,
63
72
  children: (
64
73
  <TabLayout>
@@ -0,0 +1,58 @@
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
+ import { createMockClient } from '@nocobase/client-v2';
11
+ import { AI_API_ACL_SNIPPET } from '../../constants';
12
+ import { PluginAiApiClient } from '../plugin';
13
+
14
+ /**
15
+ * Guards the settings registration itself rather than any page's contents.
16
+ *
17
+ * Two regressions are cheap to reintroduce and invisible until a non-admin logs in:
18
+ * omitting `aclSnippet` makes addPageTabItem default to `pm.ai-api.<key>`, a snippet the
19
+ * server never registers, and omitting `sort` silently reorders the tabs alphabetically.
20
+ */
21
+ describe('AI API v2 settings registration', () => {
22
+ async function loadPlugin() {
23
+ const app = createMockClient();
24
+ await new PluginAiApiClient({}, app).load();
25
+ return app;
26
+ }
27
+
28
+ it('registers every page under the one snippet the server exposes', async () => {
29
+ const app = await loadPlugin();
30
+ const menu = app.pluginSettingsManager.get('ai-api', false);
31
+
32
+ expect(menu?.aclSnippet).toBe(AI_API_ACL_SNIPPET);
33
+ for (const child of menu?.children ?? []) {
34
+ expect(app.pluginSettingsManager.getAclSnippet(child.name), child.name).toBe(AI_API_ACL_SNIPPET);
35
+ }
36
+ });
37
+
38
+ it('hides the menu and every tab when the role denies that snippet', async () => {
39
+ const app = await loadPlugin();
40
+ app.pluginSettingsManager.setAclSnippets([`!${AI_API_ACL_SNIPPET}`]);
41
+
42
+ expect(app.pluginSettingsManager.get('ai-api')).toBeNull();
43
+ expect(app.pluginSettingsManager.getList().map((item) => item.name)).not.toContain('ai-api');
44
+ });
45
+
46
+ it('keeps registration order instead of sorting tabs by name', async () => {
47
+ const app = await loadPlugin();
48
+ app.pluginSettingsManager.setAclSnippets([]);
49
+
50
+ expect(app.pluginSettingsManager.get('ai-api')?.children?.map((item) => item.name)).toEqual([
51
+ 'ai-api.index',
52
+ 'ai-api.model-pricing',
53
+ 'ai-api.model-metadata',
54
+ 'ai-api.user-quotas',
55
+ 'ai-api.usage',
56
+ ]);
57
+ });
58
+ });