Commit b32c2579 by Finley Ge Committed by GitHub

feat(plugin): support local plugin debug channel (#7176)

* feat(plugin): add local plugin debug session support

Implement local plugin debugging capability by integrating with the
plugin-server to create and manage debug sessions. This includes:
- Adding API endpoints for session lifecycle (create, status,
  disconnect).
- Providing a CLI connection bridge via one-time ticket exchange.
- Adding support for debug tools in the workflow and tool selection.
- Implementing local storage persistence for active debug sessions in
  the
  web UI.

* feat(plugin): refactor plugin debug channel and connection flow

- Replace single-use debug sessions with a persistent debug channel
  (enabled, revoked, refreshed).
- Introduce long-term `connectionKey` for CLI authentication, replacing
  the one-time ticket mechanism.
- Decouple source identification: debug source is now passed explicitly
  rather than being encoded into the plugin ID.
- Add `DebugToolTag` for better visualization in the UI.

* build(global): update @fastgpt-plugin/sdk-client to 0.0.1-alpha.10

* fix(openapi): use dev api tags for plugin debug docs

* refactor(app): remove local storage based plugin debug session

- Remove `useLocalPluginDebugSession` in favor of API-based state
- Update plugin debug modal to fetch state directly from server
- Simplify tool template retrieval by removing unnecessary local debug
  session dependencies
- Standardize active debug source resolution in API handlers

* refactor(core): refactor debug tool id and source handling

- Standardize debug source prefix to `debug:tmbId:`
- Simplify tool ID parsing logic by removing redundant debug-specific
  checks from `splitCombineToolId`
- Update UI to strictly restrict system toolset creation to valid
  contexts
- Improve debug tool detection and path resolution across service
  modules

* feat(common): support localized plugin error messages

- Implement `withPluginClientLocale` context to propagate locale to
  plugin requests.
- Add `localizePluginErrorResponse` to automatically map plugin `reason`
  fields to localized `message`.
- Enhance `getErrText` to parse nested i18n error objects.
- Propagate `source` property in tool configuration to maintain state
  for debug plugins.
- Introduce `ToastHandledError` class for custom error handling.

* fix(service): normalize empty system tool preview version

* feat(app): adjust system tool UI layout

- Adjust button order in the toolkit header
- Add centering to the plugin debug modal

* feat(service): support local debug for system tools

- Implement repository logic for local system tool configuration
  matching
- Internationalize debug tool labels and descriptions
- Add warning for publishing apps containing debug tools
- Update system tool list key generation to support debug modes

* feat(system): add remote debug support for plugins

- Add `pluginRemoteDebug` config to system settings
- Implement capability probe for plugin service features
- Restrict debug channel access based on enabled status
- Update `@fastgpt-plugin/sdk-client` to 0.0.1-alpha.11
- Fix child tool status application in `SystemToolRepo`

* feat(service): ensure debug tools remain visible as normal

Refactor `SystemToolRepo` to force debug tool status to `Normal`
regardless of saved system configuration, preventing
offline/soon-offline statuses from impacting the debugging experience.

* test(service): remove obsolete fastgpt plugin test file

* feat(app): add system tool remote debugging as commercial feature

- Add commercial restriction for remote debugging APIs
- Update docs to include remote debugging in commercial features
- Implement permission check to prevent unauthorized access

* docs(document): add remote debug suite configuration guide

Add documentation for setting up the system plugin remote debugging
suite
in self-hosted environments, including component architecture,
deployment steps, security notes, and FAQs.

* test(app): fix debug channel test cases mock environment

Mock `feConfigs.isPlus` in test setup to ensure plugin debug channel
handlers behave correctly during tests, and restore the original state
after each test to avoid side effects.
parent dcdc0682
...@@ -21,6 +21,7 @@ FastGPT Commercial Edition is an enhanced version built on top of the Community ...@@ -21,6 +21,7 @@ FastGPT Commercial Edition is an enhanced version built on top of the Community
| Run log dashboard | ❌ | ✅ | ✅ | | Run log dashboard | ❌ | ✅ | ✅ |
| App evaluation | ❌ | ✅ | ✅ | | App evaluation | ❌ | ✅ | ✅ |
| Agent and Skill assisted generation | ❌ | ✅ | ✅ | | Agent and Skill assisted generation | ❌ | ✅ | ✅ |
| System tool remote debugging | ❌ | ✅ | ✅ |
| **Knowledge Base** | | | | | **Knowledge Base** | | | |
| Knowledge base | ✅ | ✅ | ✅ | | Knowledge base | ✅ | ✅ | ✅ |
| Third-party knowledge base scheduled sync | ❌ | ✅ | ✅ | | Third-party knowledge base scheduled sync | ❌ | ✅ | ✅ |
......
...@@ -21,6 +21,7 @@ FastGPT 商业版是基于 FastGPT 社区版的增强版本,增加了一些独 ...@@ -21,6 +21,7 @@ FastGPT 商业版是基于 FastGPT 社区版的增强版本,增加了一些独
| 运行日志看板 | ❌ | ✅ | ✅ | | 运行日志看板 | ❌ | ✅ | ✅ |
| 应用评测 | ❌ | ✅ | ✅ | | 应用评测 | ❌ | ✅ | ✅ |
| Agent 与 Skill 辅助生成 | ❌ | ✅ | ✅ | | Agent 与 Skill 辅助生成 | ❌ | ✅ | ✅ |
| 系统工具远程调试 | ❌ | ✅ | ✅ |
| **知识库** | | | | | **知识库** | | | |
| 知识库 | ✅ | ✅ | ✅ | | 知识库 | ✅ | ✅ | ✅ |
| 第三方知识库定时同步 | ❌ | ✅ | ✅ | | 第三方知识库定时同步 | ❌ | ✅ | ✅ |
......
...@@ -27,7 +27,7 @@ System tool plugins run in the runtime provided by the FastGPT Plugin service. T ...@@ -27,7 +27,7 @@ System tool plugins run in the runtime provided by the FastGPT Plugin service. T
Clarify these items before coding: Clarify these items before coding:
| Information | Description | | Information | Description |
| --- | --- | | -------------------------------- | ------------------------------------------------------------------------------------------- |
| Plugin type | `tool` or `tool-suite`. | | Plugin type | `tool` or `tool-suite`. |
| Plugin ID | `pluginId`, globally stable and unique. Keep it unchanged after release. | | Plugin ID | `pluginId`, globally stable and unique. Keep it unchanged after release. |
| Child tool ID | Required for tool suites. `children[].id` stays unchanged after release. | | Child tool ID | Required for tool suites. `children[].id` stays unchanged after release. |
...@@ -116,7 +116,7 @@ pnpx @fastgpt-plugin/cli create ...@@ -116,7 +116,7 @@ pnpx @fastgpt-plugin/cli create
The CLI creates the plugin directory and common files: The CLI creates the plugin directory and common files:
| File | Purpose | | File | Purpose |
| --- | --- | | ------------------ | ------------------------------------------------------------------------- |
| `index.ts` | Plugin entry, default-exporting `defineTool()` or `defineToolSet()`. | | `index.ts` | Plugin entry, default-exporting `defineTool()` or `defineToolSet()`. |
| `package.json` | Plugin dependencies and `build`, `build:dev`, `pack`, and `test` scripts. | | `package.json` | Plugin dependencies and `build`, `build:dev`, `pack`, and `test` scripts. |
| `tsconfig.json` | TypeScript config. | | `tsconfig.json` | TypeScript config. |
...@@ -139,7 +139,10 @@ import { ...@@ -139,7 +139,10 @@ import {
import z from 'zod'; import z from 'zod';
const secretSchema = z.object({ const secretSchema = z.object({
apiKey: z.string().min(1).meta({ apiKey: z
.string()
.min(1)
.meta({
title: 'API Key', title: 'API Key',
isSecret: true isSecret: true
} satisfies SecretSchemaMetaType) } satisfies SecretSchemaMetaType)
...@@ -147,7 +150,10 @@ const secretSchema = z.object({ ...@@ -147,7 +150,10 @@ const secretSchema = z.object({
const handler = createToolHandler({ const handler = createToolHandler({
inputSchema: z.object({ inputSchema: z.object({
query: z.string().min(1).meta({ query: z
.string()
.min(1)
.meta({
title: 'Query', title: 'Query',
description: 'Search keyword' description: 'Search keyword'
} satisfies InputSchemaMetaType) } satisfies InputSchemaMetaType)
...@@ -288,7 +294,7 @@ export default defineToolSet({ ...@@ -288,7 +294,7 @@ export default defineToolSet({
During build, the CLI scans icons in the plugin root and writes them into the built `manifest.json`. During build, the CLI scans icons in the plugin root and writes them into the built `manifest.json`.
| Scenario | File name | | Scenario | File name |
| --- | --- | | --------------------- | --------------------------------------------------------------------------- |
| Main plugin icon | `logo.svg`, `logo.png`, `logo.jpg`, `logo.jpeg`, `logo.webp`, or `logo.gif` | | Main plugin icon | `logo.svg`, `logo.png`, `logo.jpg`, `logo.jpeg`, `logo.webp`, or `logo.gif` |
| Tool-suite child icon | `<childId>.logo.svg`, `<childId>.logo.png`, and similar names | | Tool-suite child icon | `<childId>.logo.svg`, `<childId>.logo.png`, and similar names |
...@@ -340,7 +346,82 @@ Local debug boundaries: ...@@ -340,7 +346,82 @@ Local debug boundaries:
- Local debug does not simulate the production child-process pool, real Node.js IPC, network environment, server timeout, or queue scheduling. - Local debug does not simulate the production child-process pool, real Node.js IPC, network environment, server timeout, or queue scheduling.
- Before listing official plugins, still manually install plugins in a test environment and complete end-to-end testing. - Before listing official plugins, still manually install plugins in a test environment and complete end-to-end testing.
## 7. Build, Check, And Pack ## 7. Remote Debugging
Remote debugging connects a locally developed plugin to a FastGPT test environment. The FastGPT page authenticates the user and generates a debug link, while the CLI uses that link to create a WSS debug channel. Debug plugins are visible only to the current debugger.
Before using it, confirm that the test environment has deployed the FastGPT Plugin service and Connection Gateway, and that your local machine can reach the Gateway WSS endpoint returned by the test environment.
### 7.1 Generate A Debug Link
1. Sign in to the FastGPT test environment.
2. Go to the System Tools page and click Local Debug.
![System Tools local debug entry](/imgs/plugins/system-tool-debug-entry.png)
3. In the modal, click Generate Link and copy the debug link.
4. If a debug session already exists, click Refresh Link to generate a new connection key; the old link becomes invalid.
![Generate local debug link](/imgs/plugins/system-tool-debug-link.png)
The debug link is only for connecting your local CLI to the test environment. Do not commit it to code repositories, documentation examples, or chat logs.
### 7.2 Start A Local Remote-Debug Session
Run this command in a plugin directory or a workspace that contains multiple plugin directories:
```bash
fastgpt-plugin dev
```
After startup, paste the debug link copied from FastGPT into the TUI. The CLI exchanges the connection key from the link for a short-lived WSS connect token, then mounts local plugins to the FastGPT debug channel.
Scripts and Agents can use non-interactive mode:
```bash
fastgpt-plugin dev --no-interactive \
--connect "https://fastgpt.example.com/api/plugin/debug-channel/connection-key:exchange?connectionKey=fpg_dbg_..."
```
When passing only a raw connection key, tell the CLI where the exchange endpoint is:
```bash
FASTGPT_PLUGIN_DEBUG_CONNECT_URL=https://fastgpt.example.com/api/plugin/debug-channel/connection-key:exchange \
fastgpt-plugin dev --no-interactive --connect "fpg_dbg_..."
```
After `--connect` connects successfully, it saves the connection key so later `fastgpt-plugin dev` runs can reuse the local config. In the TUI, press `c` to enter and save a new debug link or connection key.
### 7.3 Specify Plugin Directories And Watch Changes
When no plugin directory is passed, `dev` auto-discovers plugins from the current directory. If the current directory contains `index.ts`, it is used as the plugin entry; otherwise, the CLI scans one level of child directories for `index.ts`.
You can also pass one or more plugin directories explicitly:
```bash
fastgpt-plugin dev ./plugins/getTime ./plugins/dbops --watch
```
`--watch` reloads local plugins and recreates the remote-debug session after local file changes. The CLI reconnects by default when disconnected; use `--no-reconnect` to disable automatic reconnect.
### 7.4 Verify In FastGPT
After the CLI reports that remote debugging is ready, return to the FastGPT test environment:
1. Check the debug plugin on the System Tools page.
2. Select the debug tool in an app, workflow, or Agent.
3. Fill in secrets and input parameters, then start a real invocation.
4. Check local handler logs and errors in the CLI terminal.
The debug tool `source` is bound to the currently signed-in member, so other members do not see that debug plugin by default.
### 7.5 End Debugging
Press `Ctrl+C` in the local terminal to close the current CLI debug session; press `Ctrl+C` again to force exit.
The End Debugging action in FastGPT revokes the current member's debug channel and removes the debug plugin entry from the page. If the debug link is exposed, the signed-in member changes, or authorization needs to be renewed, use Refresh Link to generate a new link.
## 8. Build, Check, And Pack
Inside a plugin directory, usually run: Inside a plugin directory, usually run:
...@@ -369,7 +450,7 @@ Build artifacts should include: ...@@ -369,7 +450,7 @@ Build artifacts should include:
Packaging produces a `.pkg` file. Uploading, installation, and listing should all use that `.pkg` file. Packaging produces a `.pkg` file. Uploading, installation, and listing should all use that `.pkg` file.
## 8. Verification Checklist ## 9. Verification Checklist
Before submitting, confirm: Before submitting, confirm:
...@@ -384,9 +465,10 @@ Before submitting, confirm: ...@@ -384,9 +465,10 @@ Before submitting, confirm:
- `pnpm run test` passes, or the reason it cannot be tested is documented. - `pnpm run test` passes, or the reason it cannot be tested is documented.
- `build`, `check`, and `pack` pass. - `build`, `check`, and `pack` pass.
- Icons and schemas in `dist/manifest.json` are as expected. - Icons and schemas in `dist/manifest.json` are as expected.
- Remote debugging completes a real invocation in the test environment, or the reason remote debugging is not needed for this change is documented.
- `.pkg` can be installed in a test environment and complete a real invocation. - `.pkg` can be installed in a test environment and complete a real invocation.
## 9. Release Flow ## 10. Release Flow
### Community Plugins ### Community Plugins
......
...@@ -27,7 +27,7 @@ description: FastGPT 系统工具开发指南 ...@@ -27,7 +27,7 @@ description: FastGPT 系统工具开发指南
开始编码前先明确这些信息: 开始编码前先明确这些信息:
| 信息 | 说明 | | 信息 | 说明 |
| --- | --- | | ---------- | --------------------------------------------------------- |
| 插件类型 | `tool` 或 `tool-suite`。 | | 插件类型 | `tool` 或 `tool-suite`。 |
| 插件 ID | `pluginId`,全局稳定唯一,发布后保持不变。 | | 插件 ID | `pluginId`,全局稳定唯一,发布后保持不变。 |
| 子工具 ID | 工具集需要,`children[].id` 发布后保持不变。 | | 子工具 ID | 工具集需要,`children[].id` 发布后保持不变。 |
...@@ -116,7 +116,7 @@ pnpx @fastgpt-plugin/cli create ...@@ -116,7 +116,7 @@ pnpx @fastgpt-plugin/cli create
CLI 会创建插件目录,并生成常见文件: CLI 会创建插件目录,并生成常见文件:
| 文件 | 作用 | | 文件 | 作用 |
| --- | --- | | ------------------ | -------------------------------------------------------- |
| `index.ts` | 插件入口,默认导出 `defineTool()` 或 `defineToolSet()`。 | | `index.ts` | 插件入口,默认导出 `defineTool()` 或 `defineToolSet()`。 |
| `package.json` | 插件依赖和 `build`、`build:dev`、`pack`、`test` 脚本。 | | `package.json` | 插件依赖和 `build`、`build:dev`、`pack`、`test` 脚本。 |
| `tsconfig.json` | TypeScript 配置。 | | `tsconfig.json` | TypeScript 配置。 |
...@@ -139,7 +139,10 @@ import { ...@@ -139,7 +139,10 @@ import {
import z from 'zod'; import z from 'zod';
const secretSchema = z.object({ const secretSchema = z.object({
apiKey: z.string().min(1).meta({ apiKey: z
.string()
.min(1)
.meta({
title: 'API Key', title: 'API Key',
isSecret: true isSecret: true
} satisfies SecretSchemaMetaType) } satisfies SecretSchemaMetaType)
...@@ -147,7 +150,10 @@ const secretSchema = z.object({ ...@@ -147,7 +150,10 @@ const secretSchema = z.object({
const handler = createToolHandler({ const handler = createToolHandler({
inputSchema: z.object({ inputSchema: z.object({
query: z.string().min(1).meta({ query: z
.string()
.min(1)
.meta({
title: 'Query', title: 'Query',
description: 'Search keyword' description: 'Search keyword'
} satisfies InputSchemaMetaType) } satisfies InputSchemaMetaType)
...@@ -288,7 +294,7 @@ export default defineToolSet({ ...@@ -288,7 +294,7 @@ export default defineToolSet({
CLI 构建时会扫描插件根目录中的图标并写入构建后的 `manifest.json`。 CLI 构建时会扫描插件根目录中的图标并写入构建后的 `manifest.json`。
| 场景 | 文件名 | | 场景 | 文件名 |
| --- | --- | | ---------------- | -------------------------------------------------------------------------- |
| 主插件图标 | `logo.svg`、`logo.png`、`logo.jpg`、`logo.jpeg`、`logo.webp` 或 `logo.gif` | | 主插件图标 | `logo.svg`、`logo.png`、`logo.jpg`、`logo.jpeg`、`logo.webp` 或 `logo.gif` |
| 工具集子工具图标 | `<childId>.logo.svg`、`<childId>.logo.png` 等 | | 工具集子工具图标 | `<childId>.logo.svg`、`<childId>.logo.png` 等 |
...@@ -340,7 +346,82 @@ pnpx @fastgpt-plugin/cli debug . --run --input-file input.json --secrets-file se ...@@ -340,7 +346,82 @@ pnpx @fastgpt-plugin/cli debug . --run --input-file input.json --secrets-file se
- 本地 debug 不模拟生产子进程池、真实 Node.js IPC、网络环境、服务端超时和队列调度。 - 本地 debug 不模拟生产子进程池、真实 Node.js IPC、网络环境、服务端超时和队列调度。
- 上架官方插件前仍需在测试环境中手动安装插件并完成端到端测试。 - 上架官方插件前仍需在测试环境中手动安装插件并完成端到端测试。
## 7. 构建、检查和打包 ## 7. 远程调试
远程调试用于把本地正在开发的插件接入 FastGPT 测试环境。FastGPT 页面负责鉴权并生成调试链接,CLI 通过该链接建立 WSS 调试通道;调试插件仅对当前调试者本人可见。
使用前确认测试环境已部署 FastGPT Plugin 服务和 Connection Gateway,并且本地开发机可以访问测试环境返回的 Gateway WSS 地址。
### 7.1 生成调试链接
1. 登录 FastGPT 测试环境。
2. 进入「系统工具」页面,点击「本地调试」。
![系统工具本地调试入口](/imgs/plugins/system-tool-debug-entry.png)
3. 在弹窗中点击「生成链接」,复制生成的调试链接。
4. 已有调试会话时,可点击「刷新链接」生成新的 connection key;旧链接会失效。
![生成本地调试链接](/imgs/plugins/system-tool-debug-link.png)
调试链接只用于本地 CLI 连接测试环境,不应提交到代码仓库、文档示例或聊天记录中。
### 7.2 启动本地远程调试会话
在插件目录或包含多个插件目录的工作区中运行:
```bash
fastgpt-plugin dev
```
启动后,将 FastGPT 页面复制的调试链接粘贴到 TUI 中。CLI 会用链接中的 connection key 换取短期 WSS connect token,并把本地插件挂载到 FastGPT 的调试通道。
脚本或 Agent 场景可以使用非交互模式:
```bash
fastgpt-plugin dev --no-interactive \
--connect "https://fastgpt.example.com/api/plugin/debug-channel/connection-key:exchange?connectionKey=fpg_dbg_..."
```
如果只传入裸 connection key,需要让 CLI 知道 exchange 接口地址:
```bash
FASTGPT_PLUGIN_DEBUG_CONNECT_URL=https://fastgpt.example.com/api/plugin/debug-channel/connection-key:exchange \
fastgpt-plugin dev --no-interactive --connect "fpg_dbg_..."
```
`--connect` 成功连接后会保存 connection key,后续可直接运行 `fastgpt-plugin dev` 复用本地配置。TUI 中按 `c` 可重新输入并保存新的调试链接或 connection key。
### 7.3 指定插件目录和监听变化
`dev` 未传插件目录时会自动探测当前目录:当前目录存在 `index.ts` 时使用当前目录;否则扫描下一层子目录中的 `index.ts`。
也可以手动传入一个或多个插件目录:
```bash
fastgpt-plugin dev ./plugins/getTime ./plugins/dbops --watch
```
`--watch` 会在本地文件变化后重新加载插件并重建远程调试会话。CLI 默认开启断线重连;如需关闭自动重连,可加 `--no-reconnect`。
### 7.4 在 FastGPT 中验证
CLI 显示远程调试已就绪后,回到 FastGPT 测试环境:
1. 在「系统工具」页面查看调试插件。
2. 在应用、工作流或 Agent 中选择该调试工具。
3. 填写密钥和输入参数,发起真实调用。
4. 在 CLI 终端查看本地 handler 日志和错误信息。
调试工具的 `source` 会绑定到当前登录成员,其他成员默认看不到该调试插件。
### 7.5 结束调试
本地终端按 `Ctrl+C` 会关闭当前 CLI 调试会话;再次按 `Ctrl+C` 会强制退出。
FastGPT 页面中的「结束调试」会撤销当前成员的 debug channel,并清理页面上的调试插件入口。调试链接泄露、成员切换或需要重新授权时,优先使用「刷新链接」生成新链接。
## 8. 构建、检查和打包
插件目录中通常可以直接运行: 插件目录中通常可以直接运行:
...@@ -369,7 +450,7 @@ pnpx @fastgpt-plugin/cli pack --entry packages/tools/my-tool --dist ./dist --out ...@@ -369,7 +450,7 @@ pnpx @fastgpt-plugin/cli pack --entry packages/tools/my-tool --dist ./dist --out
打包后会生成 `.pkg` 文件。上传、安装和上架都应使用该 `.pkg` 文件。 打包后会生成 `.pkg` 文件。上传、安装和上架都应使用该 `.pkg` 文件。
## 8. 验证清单 ## 9. 验证清单
提交前至少确认: 提交前至少确认:
...@@ -384,9 +465,10 @@ pnpx @fastgpt-plugin/cli pack --entry packages/tools/my-tool --dist ./dist --out ...@@ -384,9 +465,10 @@ pnpx @fastgpt-plugin/cli pack --entry packages/tools/my-tool --dist ./dist --out
- `pnpm run test` 通过,或明确说明无法测试的原因。 - `pnpm run test` 通过,或明确说明无法测试的原因。
- `build`、`check`、`pack` 通过。 - `build`、`check`、`pack` 通过。
- `dist/manifest.json` 中图标和 schema 符合预期。 - `dist/manifest.json` 中图标和 schema 符合预期。
- 使用远程调试完成测试环境真实调用,或明确说明本次无需远程调试的原因。
- `.pkg` 能在测试环境中安装并完成真实调用。 - `.pkg` 能在测试环境中安装并完成真实调用。
## 9. 发布流程 ## 10. 发布流程
### 社区插件 ### 社区插件
......
{ {
"title": "Configuration", "title": "Configuration",
"description": "FastGPT self-hosting configuration", "description": "FastGPT self-hosting configuration",
"pages": ["model", "object-storage", "json", "env", "signoz"] "pages": ["model", "object-storage", "json", "env", "signoz", "remote-debug-suite"]
} }
{ {
"title": "配置说明", "title": "配置说明",
"description": "FastGPT 自部署配置", "description": "FastGPT 自部署配置",
"pages": ["model", "object-storage", "json", "env", "signoz"] "pages": ["model", "object-storage", "json", "env", "signoz", "remote-debug-suite"]
} }
---
title: 系统插件的远程调试功能套件配置
description: FastGPT 接入系统插件的远程调试功能套件
---
import { Alert } from '@/components/docs/Alert';
## 适用场景
系统插件的远程调试功能套件用于把开发者本地运行的 FastGPT 系统插件临时接入 FastGPT 测试环境。它适合系统插件开发、联调和验收,不适合作为生产插件运行时。
<Alert icon="🤖" context="warning">
系统插件的远程调试功能套件仅商业版支持。
优先推荐在 FastGPT 云服务版本中使用远程调试能力。自部署需要额外维护 Plugin Server、Connection Gateway、Redis、反向代理、TLS 和密钥轮换,运维成本更高。
</Alert>
默认的 Docker Compose 部署脚本只包含 FastGPT 主服务和常规 `fastgpt-plugin` 运行环境,不包含 Connection Gateway 的公网 WebSocket 接入配置。自部署环境需要按本文额外部署系统插件的远程调试功能套件。
## 组件关系
远程调试链路包含以下组件:
| 组件 | 作用 |
| -------------------- | --------------------------------------------------------------- |
| FastGPT 主服务 | 提供开启、刷新、关闭调试通道的页面和 API。 |
| Plugin Server | 管理 `connectionKey`、调试 source,并把调试调用转发给 Gateway。 |
| Connection Gateway | 维护 CLI WebSocket 长连接、session、mailbox 和调试调用流转。 |
| Redis | 保存 Gateway session、source owner 和 mailbox 数据。 |
| `fastgpt-plugin dev` | 在开发者本地运行插件,并通过 WebSocket 连接 Gateway。 |
主路径如下:
```mermaid
sequenceDiagram
participant User as Developer
participant FastGPT as FastGPT
participant Plugin as Plugin Server
participant Gateway as Connection Gateway
participant CLI as fastgpt-plugin dev
User->>FastGPT: 开启调试通道
FastGPT->>Plugin: 创建 debug channel
Plugin-->>FastGPT: connectionKey / connectionUrl / source
User->>CLI: fastgpt-plugin dev --connect <connectionUrl>
CLI->>FastGPT: 兑换 connectionKey
FastGPT->>Plugin: 转发 connectionKey exchange
Plugin-->>CLI: gatewayUrl / connectToken / source
CLI->>Gateway: WebSocket bind
FastGPT->>Plugin: 调用 debug source 下的插件
Plugin->>Gateway: 发送 plugin-debug.run
Gateway->>CLI: 转发调试请求
CLI-->>Gateway: 返回执行结果
Gateway-->>Plugin: 流式返回结果
```
## 部署前提
1. FastGPT 主服务已能正常访问 `fastgpt-plugin`,并且两侧的 `PLUGIN_TOKEN` / `AUTH_TOKEN` 一致。
2. `fastgpt-plugin` 版本需要包含远程调试能力;建议与当前 FastGPT 版本要求的 plugin 版本保持一致。
3. Gateway WebSocket 地址需要从开发者本地可访问,生产建议使用 HTTPS 反向代理暴露为 `wss://`。
4. Gateway internal HTTP API 只允许 Plugin Server 所在内网访问。
5. Gateway 使用的 Redis 必须支持 Stream。
6. 所有生产密钥至少 32 位,且不要使用示例值、默认值或弱口令。
## 部署 Connection Gateway
Connection Gateway 由 `fastgpt-plugin` 仓库维护。部署时按网络环境选择国内版或海外版镜像:
```dotenv
# 国内版
CONNECTION_GATEWAY_IMAGE=registry.cn-hangzhou.aliyuncs.com/fastgpt/fastgpt-plugin-connection-gateway:8a52896d1d5b866308778871526cfdff9d22c547
# 海外版
CONNECTION_GATEWAY_IMAGE=ghcr.io/labring/fastgpt-plugin-connection-gateway:8a52896d1d5b866308778871526cfdff9d22c547
```
最小配置形态如下:
```yaml
services:
connection-gateway:
image: ${CONNECTION_GATEWAY_IMAGE}
restart: unless-stopped
environment:
NODE_ENV: production
REDIS_URL: redis://default:mypassword@fastgpt-redis:6379
AUTH_TOKEN: ${CONNECTION_GATEWAY_AUTH_TOKEN}
CONNECTION_GATEWAY_AUTH_TOKEN: ${CONNECTION_GATEWAY_AUTH_TOKEN}
JWT_SECRET: ${CONNECTION_GATEWAY_JWT_SECRET}
CONNECTION_GATEWAY_PORT: 3000
CONNECTION_GATEWAY_WS_PORT: 3001
CONNECTION_GATEWAY_WS_PATH: /connection-gateway/v1
ports:
- '3010:3000'
- '3011:3001'
```
端口说明:
| 端口 | 用途 | 暴露要求 |
| ------ | -------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| `3010` | Gateway HTTP API,对应容器内 `3000`,包含 `/health`、`/internal/*`、`/metrics`。 | 不需要公网暴露,Plugin Server 可通过内网访问即可。 |
| `3011` | Gateway WebSocket,对应容器内 `3001`,默认路径 `/connection-gateway/v1`。 | 需要让开发者本地 CLI 可访问,通常通过反向代理暴露为公网 `wss://` 地址。 |
| Redis | Gateway session、source owner 和 mailbox 存储。 | 不需要公网暴露;Redis 版本必须支持 Stream。 |
## 配置 Plugin Server
在 `fastgpt-plugin` 服务中增加 Gateway 相关环境变量:
```dotenv
# Plugin Server 调用 Gateway internal HTTP API 的内网地址
CONNECTION_GATEWAY_BASE_URL=http://connection-gateway:3000
# 返回给本地 CLI 的 WebSocket 地址,必须能从开发者本地访问
CONNECTION_GATEWAY_PUBLIC_URL=wss://debug-gateway.example.com/connection-gateway/v1
# Plugin Server 调用 Gateway /internal/* 和 /metrics 的 bearer token
CONNECTION_GATEWAY_AUTH_TOKEN=replace-with-a-random-token-at-least-32-chars
# Gateway connect token 的 HMAC secret,必须与 Connection Gateway 完全一致
JWT_SECRET=replace-with-a-random-jwt-secret-at-least-32-chars
```
配置后重启 `fastgpt-plugin`。`CONNECTION_GATEWAY_BASE_URL` 未配置时,Plugin Server 会关闭远程调试能力。
## 配置 FastGPT 主服务
FastGPT 主服务继续使用常规插件配置:
```dotenv
PLUGIN_BASE_URL=http://fastgpt-plugin:3000
PLUGIN_TOKEN=replace-with-the-same-value-as-plugin-auth-token
NEXT_PUBLIC_BASE_URL=https://fastgpt.example.com
```
`NEXT_PUBLIC_BASE_URL` 会影响调试连接链接的生成。公网用户访问 FastGPT 时,应配置为浏览器可访问的 FastGPT 地址。
## 配置反向代理
建议只暴露 Gateway WebSocket 入口,对 Gateway internal HTTP API 保持内网访问。
Nginx 示例:
```nginx
location /connection-gateway/v1 {
proxy_pass http://connection-gateway:3001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_read_timeout 3600s;
}
```
`/internal/*`、`/metrics` 和 Gateway HTTP 端口不要直接暴露到公网。
## 开发者连接
1. 在 FastGPT 插件调试入口开启调试通道,复制页面返回的连接链接。
2. 在本地插件目录运行:
```bash
fastgpt-plugin dev --connect '<connectionUrl>'
```
连接成功后,本地 CLI 会通过 Gateway 上报插件 metadata。FastGPT 工具列表中会出现当前调试 source 下的本地插件。调试 source 的格式为:
```text
debug:tmbId:{tmbId}
```
## 验证
1. 访问 Gateway 健康检查:
```bash
curl http://connection-gateway:3000/health
```
2. 在 FastGPT 页面开启调试通道,确认状态从 `enabled` 变为 `connected`。
3. 运行本地 `fastgpt-plugin dev`,确认 CLI 显示 WebSocket 已连接。
4. 在 FastGPT 中选择调试 source 下的工具并触发一次调用,确认结果由本地插件返回。
## 安全注意事项
- `CONNECTION_GATEWAY_AUTH_TOKEN`、`JWT_SECRET`、`connectionKey` 和 `connectToken` 都属于敏感信息,禁止写入日志、截图或公开文档。
- `CONNECTION_GATEWAY_AUTH_TOKEN` 只给 Plugin Server 使用,本地 CLI 不需要也不应获取。
- `connectionKey` 是长期调试连接密钥,只在开启或刷新调试通道时明文返回;泄露后应立即刷新或关闭调试通道。
- 调试 source 命中后按远程调试路径处理,断连或 session 不存在时会失败,不会回退到生产插件运行时。
- 多副本 Gateway 部署需要保证 session 删除请求能路由到持有 WebSocket 的节点,或接受 Redis session 删除后后续调用失败。
## 常见问题
### 页面可以开启调试,但 CLI 连接失败
检查 `CONNECTION_GATEWAY_PUBLIC_URL` 是否为开发者本地可访问地址。浏览器和 CLI 在开发者电脑上运行,不能使用 Docker 内网域名。
### CLI 已连接,但 FastGPT 显示 disconnected
检查 Plugin Server 是否能访问 `CONNECTION_GATEWAY_BASE_URL`,并确认 `CONNECTION_GATEWAY_AUTH_TOKEN` 与 Gateway 配置一致。
### 连接后调用工具超时
检查 Gateway Redis 是否正常、反向代理是否保留 WebSocket upgrade、`proxy_read_timeout` 是否过短,以及本地 CLI 是否仍在线。
### connect token 校验失败
检查 Plugin Server 和 Connection Gateway 的 `JWT_SECRET` 是否完全一致。
...@@ -92,6 +92,7 @@ description: FastGPT Toc ...@@ -92,6 +92,7 @@ description: FastGPT Toc
- [/en/self-host/config/model/minimax](/en/self-host/config/model/minimax) - [/en/self-host/config/model/minimax](/en/self-host/config/model/minimax)
- [/en/self-host/config/model/siliconCloud](/en/self-host/config/model/siliconCloud) - [/en/self-host/config/model/siliconCloud](/en/self-host/config/model/siliconCloud)
- [/en/self-host/config/object-storage](/en/self-host/config/object-storage) - [/en/self-host/config/object-storage](/en/self-host/config/object-storage)
- [/en/self-host/config/remote-debug-suite](/en/self-host/config/remote-debug-suite)
- [/en/self-host/config/signoz](/en/self-host/config/signoz) - [/en/self-host/config/signoz](/en/self-host/config/signoz)
- [/en/self-host/custom-models/bge-rerank](/en/self-host/custom-models/bge-rerank) - [/en/self-host/custom-models/bge-rerank](/en/self-host/custom-models/bge-rerank)
- [/en/self-host/custom-models/chatglm2](/en/self-host/custom-models/chatglm2) - [/en/self-host/custom-models/chatglm2](/en/self-host/custom-models/chatglm2)
......
...@@ -92,6 +92,7 @@ description: FastGPT 文档目录 ...@@ -92,6 +92,7 @@ description: FastGPT 文档目录
- [/self-host/config/model/minimax](/self-host/config/model/minimax) - [/self-host/config/model/minimax](/self-host/config/model/minimax)
- [/self-host/config/model/siliconCloud](/self-host/config/model/siliconCloud) - [/self-host/config/model/siliconCloud](/self-host/config/model/siliconCloud)
- [/self-host/config/object-storage](/self-host/config/object-storage) - [/self-host/config/object-storage](/self-host/config/object-storage)
- [/self-host/config/remote-debug-suite](/self-host/config/remote-debug-suite)
- [/self-host/config/signoz](/self-host/config/signoz) - [/self-host/config/signoz](/self-host/config/signoz)
- [/self-host/custom-models/bge-rerank](/self-host/custom-models/bge-rerank) - [/self-host/custom-models/bge-rerank](/self-host/custom-models/bge-rerank)
- [/self-host/custom-models/chatglm2](/self-host/custom-models/chatglm2) - [/self-host/custom-models/chatglm2](/self-host/custom-models/chatglm2)
......
...@@ -137,8 +137,8 @@ ...@@ -137,8 +137,8 @@
"content/guide/version/cloud/privacy.mdx": "2026-05-07T15:06:40+08:00", "content/guide/version/cloud/privacy.mdx": "2026-05-07T15:06:40+08:00",
"content/guide/version/cloud/terms.en.mdx": "2026-05-07T15:06:40+08:00", "content/guide/version/cloud/terms.en.mdx": "2026-05-07T15:06:40+08:00",
"content/guide/version/cloud/terms.mdx": "2026-05-28T13:54:38+08:00", "content/guide/version/cloud/terms.mdx": "2026-05-28T13:54:38+08:00",
"content/guide/version/commercial.en.mdx": "2026-06-23T15:18:25+08:00", "content/guide/version/commercial.en.mdx": "2026-06-27T18:52:43+08:00",
"content/guide/version/commercial.mdx": "2026-06-23T15:18:25+08:00", "content/guide/version/commercial.mdx": "2026-06-27T18:52:43+08:00",
"content/guide/version/opensource/intro.en.mdx": "2026-05-07T15:06:40+08:00", "content/guide/version/opensource/intro.en.mdx": "2026-05-07T15:06:40+08:00",
"content/guide/version/opensource/intro.mdx": "2026-05-07T15:06:40+08:00", "content/guide/version/opensource/intro.mdx": "2026-05-07T15:06:40+08:00",
"content/guide/version/opensource/license.en.mdx": "2026-05-07T15:06:40+08:00", "content/guide/version/opensource/license.en.mdx": "2026-05-07T15:06:40+08:00",
...@@ -165,8 +165,8 @@ ...@@ -165,8 +165,8 @@
"content/plugin/intro.mdx": "2026-06-09T16:03:58+08:00", "content/plugin/intro.mdx": "2026-06-09T16:03:58+08:00",
"content/plugin/model-presets.en.mdx": "2026-06-04T16:10:15+08:00", "content/plugin/model-presets.en.mdx": "2026-06-04T16:10:15+08:00",
"content/plugin/model-presets.mdx": "2026-06-04T16:10:15+08:00", "content/plugin/model-presets.mdx": "2026-06-04T16:10:15+08:00",
"content/plugin/system-tool-development.en.mdx": "2026-06-09T16:03:58+08:00", "content/plugin/system-tool-development.en.mdx": "2026-06-27T17:05:53+08:00",
"content/plugin/system-tool-development.mdx": "2026-06-09T16:03:58+08:00", "content/plugin/system-tool-development.mdx": "2026-06-27T17:05:53+08:00",
"content/self-host/config/env.en.mdx": "2026-06-26T17:38:34+08:00", "content/self-host/config/env.en.mdx": "2026-06-26T17:38:34+08:00",
"content/self-host/config/env.mdx": "2026-06-26T17:38:34+08:00", "content/self-host/config/env.mdx": "2026-06-26T17:38:34+08:00",
"content/self-host/config/json.en.mdx": "2026-06-22T11:01:59+08:00", "content/self-host/config/json.en.mdx": "2026-06-22T11:01:59+08:00",
...@@ -444,6 +444,6 @@ ...@@ -444,6 +444,6 @@
"content/self-host/upgrading/outdated/499.mdx": "2026-05-07T15:06:40+08:00", "content/self-host/upgrading/outdated/499.mdx": "2026-05-07T15:06:40+08:00",
"content/self-host/upgrading/upgrade-intruction.en.mdx": "2026-04-26T21:08:47+08:00", "content/self-host/upgrading/upgrade-intruction.en.mdx": "2026-04-26T21:08:47+08:00",
"content/self-host/upgrading/upgrade-intruction.mdx": "2026-04-26T21:08:47+08:00", "content/self-host/upgrading/upgrade-intruction.mdx": "2026-04-26T21:08:47+08:00",
"content/toc.en.mdx": "2026-06-25T14:51:00+08:00", "content/toc.en.mdx": "2026-06-27T18:52:43+08:00",
"content/toc.mdx": "2026-06-25T14:51:00+08:00" "content/toc.mdx": "2026-06-27T18:52:43+08:00"
} }
\ No newline at end of file
...@@ -3,6 +3,7 @@ import { i18nT } from '../../i18n/utils'; ...@@ -3,6 +3,7 @@ import { i18nT } from '../../i18n/utils';
/* dataset: 509000 */ /* dataset: 509000 */
export enum SystemErrEnum { export enum SystemErrEnum {
communityVersionNumLimit = 'communityVersionNumLimit', communityVersionNumLimit = 'communityVersionNumLimit',
commercialFeature = 'commercialFeature',
licenseAppAmountLimit = 'licenseAppAmountLimit', licenseAppAmountLimit = 'licenseAppAmountLimit',
licenseDatasetAmountLimit = 'licenseDatasetAmountLimit', licenseDatasetAmountLimit = 'licenseDatasetAmountLimit',
licenseUserAmountLimit = 'licenseUserAmountLimit' licenseUserAmountLimit = 'licenseUserAmountLimit'
...@@ -14,6 +15,11 @@ const systemErr = [ ...@@ -14,6 +15,11 @@ const systemErr = [
message: i18nT('common:code_error.system_error.community_version_num_limit') message: i18nT('common:code_error.system_error.community_version_num_limit')
}, },
{ {
statusText: SystemErrEnum.commercialFeature,
message: i18nT('common:code_error.system_error.commercial_feature'),
httpStatus: 403
},
{
statusText: SystemErrEnum.licenseAppAmountLimit, statusText: SystemErrEnum.licenseAppAmountLimit,
message: i18nT('common:code_error.system_error.license_app_amount_limit') message: i18nT('common:code_error.system_error.license_app_amount_limit')
}, },
...@@ -34,7 +40,8 @@ export default systemErr.reduce((acc, cur, index) => { ...@@ -34,7 +40,8 @@ export default systemErr.reduce((acc, cur, index) => {
code: 509000 + index, code: 509000 + index,
statusText: cur.statusText, statusText: cur.statusText,
message: cur.message, message: cur.message,
data: null data: null,
httpStatus: cur.httpStatus
} }
}; };
}, {} as ErrType<`${SystemErrEnum}`>); }, {} as ErrType<`${SystemErrEnum}`>);
import { replaceSensitiveText } from '../string/tools'; import { replaceSensitiveText } from '../string/tools';
import { ERROR_RESPONSE } from './errorCode'; import { ERROR_RESPONSE } from './errorCode';
import type { localeType } from '../i18n/type';
import { parseI18nString } from '../i18n/utils';
export const getErrText = (err: any, def = '', lang?: localeType): any => {
const parseI18nError = (value: any): string | undefined => {
if (!lang || !value || typeof value !== 'object') return;
if (typeof value.en === 'string') {
return parseI18nString(value, lang);
}
};
export const getErrText = (err: any, def = ''): any => {
const getRawMsg = (e: any): any => { const getRawMsg = (e: any): any => {
if (typeof e === 'string') return e; if (typeof e === 'string') return e;
if (!e) return ''; if (!e) return '';
return ( return (
e.system_error_text || e.system_error_text ||
e.errorText || e.errorText ||
parseI18nError(e.response?.data?.error?.reason) ||
parseI18nError(e.response?.error?.reason) ||
parseI18nError(e.error?.reason) ||
parseI18nError(e.response?.data?.reason) ||
parseI18nError(e.response?.reason) ||
parseI18nError(e.reason) ||
e.response?.data?.message || e.response?.data?.message ||
e.response?.message || e.response?.message ||
e.response?.data?.msg || e.response?.data?.msg ||
...@@ -45,3 +61,13 @@ export class UserError extends Error { ...@@ -45,3 +61,13 @@ export class UserError extends Error {
this.name = 'UserError'; this.name = 'UserError';
} }
} }
/**
* 表示错误提示已经由业务侧自行展示,通用请求层应跳过重复 toast。
*/
export class ToastHandledError extends Error {
constructor(message: string) {
super(message);
this.name = 'ToastHandledError';
}
}
...@@ -72,6 +72,7 @@ export type FastGPTFeConfigsType = { ...@@ -72,6 +72,7 @@ export type FastGPTFeConfigsType = {
show_publish_offiaccount?: boolean; show_publish_offiaccount?: boolean;
show_publish_wechat?: boolean; show_publish_wechat?: boolean;
show_agent_sandbox?: boolean; show_agent_sandbox?: boolean;
pluginRemoteDebug?: boolean;
show_dataset_enhance?: boolean; show_dataset_enhance?: boolean;
show_batch_eval?: boolean; show_batch_eval?: boolean;
......
import z from 'zod'; import z from 'zod';
import { NodeToolConfigTypeSchema } from '../../workflow/type/node';
import { import {
AgentSkillSourceEnum, AgentSkillSourceEnum,
AgentSkillCategoryEnum, AgentSkillCategoryEnum,
...@@ -163,6 +164,8 @@ export type SandboxInstanceSchemaType = z.infer<typeof SandboxInstanceSchema>; ...@@ -163,6 +164,8 @@ export type SandboxInstanceSchemaType = z.infer<typeof SandboxInstanceSchema>;
export const SkillToolSchema = z.object({ export const SkillToolSchema = z.object({
id: z.string(), id: z.string(),
source: z.string().optional(),
toolConfig: NodeToolConfigTypeSchema.optional(),
config: z.record(z.string(), z.any()) config: z.record(z.string(), z.any())
}); });
export type SkillToolType = z.infer<typeof SkillToolSchema>; export type SkillToolType = z.infer<typeof SkillToolSchema>;
import { AppToolSourceEnum } from '../tool/constants'; import { AppToolSourceEnum } from '../tool/constants';
import { NodeInputKeyEnum } from '../../workflow/constants';
import type { StoreNodeItemType } from '../../workflow/type/node';
import type { SelectedToolItemType } from '../formEdit/type';
/** /**
Tool id rule: Tool id rule:
...@@ -12,7 +15,7 @@ import { AppToolSourceEnum } from '../tool/constants'; ...@@ -12,7 +15,7 @@ import { AppToolSourceEnum } from '../tool/constants';
(deprecated) community: community-id (deprecated) community: community-id
*/ */
export function splitCombineToolId(id: string): { export function splitCombineToolId(id: string): {
source: AppToolSourceEnum; source: AppToolSourceEnum | string;
pluginId: string; pluginId: string;
authAppId?: string; authAppId?: string;
} { } {
...@@ -79,6 +82,51 @@ export function splitCombineToolId(id: string): { ...@@ -79,6 +82,51 @@ export function splitCombineToolId(id: string): {
throw new Error('Invalid tool id'); throw new Error('Invalid tool id');
} }
const DebugToolSourcePrefix = 'debug:tmbId:';
export function isDebugToolSource(source?: string): source is string {
return typeof source === 'string' && source.startsWith(DebugToolSourcePrefix);
}
export function parseDebugToolSource(source?: string): { tmbId: string } | undefined {
if (!isDebugToolSource(source)) return;
const tmbMatch = /^debug:tmbId:([^:]+)$/.exec(source);
if (tmbMatch) {
return {
tmbId: tmbMatch[1]
};
}
}
export function hasDebugToolInSelectedTools(selectedTools?: SelectedToolItemType[] | null) {
return selectedTools?.some((tool) => isDebugToolSource(tool.source)) ?? false;
}
/**
* 检查发布数据中是否包含本地调试工具。
* 需要同时覆盖普通工具节点、工具集配置和 Agent 节点 selectedTools 输入,避免调试 source 被发布到线上版本。
*/
export function hasDebugToolInNodes(nodes?: StoreNodeItemType[] | null) {
return (
nodes?.some((node) => {
if (isDebugToolSource(node.source)) return true;
const toolConfig = node.toolConfig;
if (isDebugToolSource(toolConfig?.systemTool?.source)) return true;
if (isDebugToolSource(toolConfig?.systemToolSet?.source)) return true;
const selectedToolsInput = node.inputs.find(
(input) => input.key === NodeInputKeyEnum.selectedTools
);
const selectedTools = Array.isArray(selectedToolsInput?.value)
? (selectedToolsInput.value as SelectedToolItemType[])
: [];
return hasDebugToolInSelectedTools(selectedTools);
}) ?? false
);
}
export const getToolRawId = (id: string) => { export const getToolRawId = (id: string) => {
const toolId = splitCombineToolId(id).pluginId; const toolId = splitCombineToolId(id).pluginId;
......
...@@ -41,6 +41,9 @@ export const NodeToolConfigTypeSchema = z.object({ ...@@ -41,6 +41,9 @@ export const NodeToolConfigTypeSchema = z.object({
.object({ .object({
toolId: z.string().meta({ toolId: z.string().meta({
description: '节点引用的系统工具 ID' description: '节点引用的系统工具 ID'
}),
source: z.string().optional().meta({
description: '系统工具来源。调试工具会写入 debug source'
}) })
}) })
.optional() .optional()
...@@ -52,6 +55,9 @@ export const NodeToolConfigTypeSchema = z.object({ ...@@ -52,6 +55,9 @@ export const NodeToolConfigTypeSchema = z.object({
toolId: z.string().meta({ toolId: z.string().meta({
description: '系统工具集 ID' description: '系统工具集 ID'
}), }),
source: z.string().optional().meta({
description: '系统工具集来源。调试工具会写入 debug source'
}),
toolList: z toolList: z
.array( .array(
z z
...@@ -164,6 +170,7 @@ export const FlowNodeCommonTypeSchema = z.object({ ...@@ -164,6 +170,7 @@ export const FlowNodeCommonTypeSchema = z.object({
// plugin data // plugin data
pluginId: z.string().optional(), // plugin id pluginId: z.string().optional(), // plugin id
source: z.string().optional(), // plugin source, e.g. debug source
isFolder: BoolSchema.optional(), isFolder: BoolSchema.optional(),
pluginData: ToolDataSchema.optional(), pluginData: ToolDataSchema.optional(),
...@@ -219,6 +226,7 @@ export type FlowNodeTemplateType = z.infer<typeof FlowNodeTemplateTypeSchema>; ...@@ -219,6 +226,7 @@ export type FlowNodeTemplateType = z.infer<typeof FlowNodeTemplateTypeSchema>;
// Api response // Api response
export const NodeTemplateListItemTypeSchema = z.object({ export const NodeTemplateListItemTypeSchema = z.object({
id: z.string(), // 系统节点-系统节点的 id, 系统插件-插件的 id,团队应用的 id id: z.string(), // 系统节点-系统节点的 id, 系统插件-插件的 id,团队应用的 id
source: z.string().optional(), // 系统插件运行来源,例如 debug source
flowNodeType: z.enum(FlowNodeTypeEnum), // render node card flowNodeType: z.enum(FlowNodeTypeEnum), // render node card
parentId: ParentIdSchema.optional(), parentId: ParentIdSchema.optional(),
isFolder: BoolSchema.optional(), isFolder: BoolSchema.optional(),
......
...@@ -44,6 +44,10 @@ export const GetSystemToolTemplatesBodySchema = z.object({ ...@@ -44,6 +44,10 @@ export const GetSystemToolTemplatesBodySchema = z.object({
example: 'systemTool-map', example: 'systemTool-map',
description: '工具集父工具 ID。传入后返回该工具集下的子工具模板' description: '工具集父工具 ID。传入后返回该工具集下的子工具模板'
}), }),
source: z.string().optional().meta({
example: 'debug:tmbId:tmb_xxx',
description: '工具来源。调试状态下由前端显式传入 debug source,不再拼接到工具 ID 中'
}),
tags: z tags: z
.array(z.string()) .array(z.string())
.optional() .optional()
...@@ -73,6 +77,10 @@ export const GetToolPathQuerySchema = z.object({ ...@@ -73,6 +77,10 @@ export const GetToolPathQuerySchema = z.object({
example: 'systemTool-map/geocode', example: 'systemTool-map/geocode',
description: '工具 ID。为空时返回空路径' description: '工具 ID。为空时返回空路径'
}), }),
source: z.string().optional().meta({
example: 'debug:tmbId:tmb_xxx',
description: '工具来源。调试状态下显式传入 debug source,不再拼接到工具 ID 中'
}),
type: z.enum(['current', 'parent']).optional().meta({ type: z.enum(['current', 'parent']).optional().meta({
example: 'current', example: 'current',
description: '路径类型:current 返回当前工具路径,parent 只返回父工具路径' description: '路径类型:current 返回当前工具路径,parent 只返回父工具路径'
...@@ -108,6 +116,10 @@ const GetPreviewNodeBaseQuerySchema = z.object({ ...@@ -108,6 +116,10 @@ const GetPreviewNodeBaseQuerySchema = z.object({
example: 'systemTool-weather', example: 'systemTool-weather',
description: description:
'工具 ID,支持系统工具 systemTool/commercial、我的工具 personal/mcp/http 组合 ID 及工具集子工具 ID' '工具 ID,支持系统工具 systemTool/commercial、我的工具 personal/mcp/http 组合 ID 及工具集子工具 ID'
}),
source: z.string().optional().meta({
example: 'debug:tmbId:tmb_xxx',
description: '工具来源。调试状态下显式传入 debug source,不再拼接到 appId 中'
}) })
}); });
......
import z from 'zod';
export const PluginDebugChannelStatusSchema = z.enum([
'enabled',
'connected',
'disconnected',
'revoked'
]);
export const PluginDebugChannelActionBodySchema = z.object({}).optional().default({});
export type PluginDebugChannelActionBodyType = z.infer<typeof PluginDebugChannelActionBodySchema>;
const PluginDebugChannelBaseSchema = z.object({
tmbId: z.string().min(1).meta({
example: 'tmb_xxx',
description: '当前团队成员 ID'
}),
source: z.string().min(1).optional().meta({
example: 'debug:tmbId:tmb_xxx',
description: 'plugin-server 返回的调试 source,后续查询和运行必须原样透传'
}),
status: PluginDebugChannelStatusSchema.meta({
example: 'enabled',
description: '调试通道状态'
}),
enabled: z.boolean().meta({
example: true,
description: '调试通道是否开启'
}),
keyId: z.string().min(1).optional().meta({
example: 'dbg_key_xxx',
description: 'plugin-server 当前连接密钥 ID'
}),
createdAt: z.number().int().positive().optional().meta({
example: 1781500000000,
description: '调试通道创建时间戳,单位毫秒'
}),
updatedAt: z.number().int().positive().optional().meta({
example: 1781500000000,
description: '调试通道更新时间戳,单位毫秒'
}),
refreshedAt: z.number().int().positive().optional().meta({
example: 1781500000000,
description: '连接密钥最近刷新时间戳,单位毫秒'
}),
revokedAt: z.number().int().positive().optional().meta({
example: 1781500000000,
description: '调试通道关闭时间戳,单位毫秒'
})
});
/* ============================================================================
* API: 开启插件调试通道
* Route: POST /api/plugin/debug-channel/enable
* Method: POST
* Description: 为当前登录团队成员开启插件调试通道,并返回 plugin-server 生成的 source 和长期 connectionKey
* Tags: ['插件调试', 'Write']
* ============================================================================ */
export const EnablePluginDebugChannelBodySchema = PluginDebugChannelActionBodySchema;
export type EnablePluginDebugChannelBodyType = z.infer<typeof EnablePluginDebugChannelBodySchema>;
export const EnablePluginDebugChannelResponseSchema = PluginDebugChannelBaseSchema.extend({
connectionKey: z.string().min(1).optional().meta({
example: 'fgdbg_xxx',
description: '长期连接密钥,仅在开启或刷新时返回,供 CLI 连接使用'
}),
connectionUrl: z.string().url().optional().meta({
example:
'https://fastgpt.example.com/api/plugin/debug-channel/connection-key:exchange?connectionKey=fgdbg_xxx',
description: '本地 CLI 可直接访问的 FastGPT HTTP 调试连接链接'
})
}).required({
source: true
});
export type EnablePluginDebugChannelResponseType = z.infer<
typeof EnablePluginDebugChannelResponseSchema
>;
/* ============================================================================
* API: 刷新插件调试连接密钥
* Route: POST /api/plugin/debug-channel/key:refresh
* Method: POST
* Description: 刷新当前登录团队成员的插件调试 connectionKey,旧连接密钥会失效
* Tags: ['插件调试', 'Write']
* ============================================================================ */
export const RefreshPluginDebugConnectionKeyBodySchema = PluginDebugChannelActionBodySchema;
export type RefreshPluginDebugConnectionKeyBodyType = z.infer<
typeof RefreshPluginDebugConnectionKeyBodySchema
>;
export const RefreshPluginDebugConnectionKeyResponseSchema =
EnablePluginDebugChannelResponseSchema.required({
connectionKey: true
});
export type RefreshPluginDebugConnectionKeyResponseType = z.infer<
typeof RefreshPluginDebugConnectionKeyResponseSchema
>;
export const PluginDebugChannelPluginSchema = z
.object({
pluginId: z.string().min(1).meta({
example: 'getTime',
description: '调试插件 ID'
}),
source: z.string().min(1).meta({
example: 'debug:tmbId:tmb_xxx',
description: '调试插件来源'
}),
version: z.string().min(1).meta({
example: '0.0.1',
description: '调试插件版本'
}),
name: z.unknown().meta({
example: {
en: 'Get Time',
'zh-CN': '获取时间'
},
description: '调试插件名称,保持 plugin-server 原始 i18n 结构'
}),
description: z
.unknown()
.optional()
.meta({
example: {
en: 'Get current time',
'zh-CN': '获取当前时间'
},
description: '调试插件简介,保持 plugin-server 原始 i18n 结构'
}),
icon: z.string().optional().meta({
example: 'https://fastgpt.example.com/icon.png',
description: '调试插件图标'
}),
tags: z
.array(z.string())
.optional()
.meta({
example: ['search'],
description: '调试插件标签'
})
})
.catchall(z.unknown());
/* ============================================================================
* API: 获取插件调试通道状态
* Route: GET /api/plugin/debug-channel
* Method: GET
* Description: 获取当前登录团队成员的插件调试状态、source、keyId 和已挂载调试插件
* Tags: ['插件调试', 'Read']
* ============================================================================ */
export const GetPluginDebugChannelQuerySchema = z.object({}).optional().default({});
export type GetPluginDebugChannelQueryType = z.infer<typeof GetPluginDebugChannelQuerySchema>;
export const GetPluginDebugChannelResponseSchema = PluginDebugChannelBaseSchema.extend({
plugins: z.array(PluginDebugChannelPluginSchema).meta({
description: '当前调试通道已挂载的插件列表'
}),
gateway: z
.object({
sessionId: z.string().min(1).optional().meta({
example: 'gateway-session-id',
description: 'connection-gateway session ID'
}),
ownerAlive: z.boolean().meta({
example: true,
description: 'CLI 连接是否在线'
}),
mailboxLag: z.number().int().nonnegative().meta({
example: 0,
description: 'gateway mailbox 延迟'
})
})
.optional()
.meta({
description: 'gateway 状态'
})
});
export type GetPluginDebugChannelResponseType = z.infer<typeof GetPluginDebugChannelResponseSchema>;
/* ============================================================================
* API: 关闭插件调试通道
* Route: POST /api/plugin/debug-channel/revoke
* Method: POST
* Description: 关闭当前登录团队成员的插件调试通道,并断开对应 gateway session
* Tags: ['插件调试', 'Write']
* ============================================================================ */
export const RevokePluginDebugChannelBodySchema = PluginDebugChannelActionBodySchema;
export type RevokePluginDebugChannelBodyType = z.infer<typeof RevokePluginDebugChannelBodySchema>;
export const RevokePluginDebugChannelResponseSchema = z.object({
revoked: z.boolean().meta({
example: true,
description: 'plugin-server 是否执行了关闭;false 表示目标状态已达成'
})
});
export type RevokePluginDebugChannelResponseType = z.infer<
typeof RevokePluginDebugChannelResponseSchema
>;
/* ============================================================================
* API: 兑换插件调试连接信息
* Route: GET/POST /api/plugin/debug-channel/connection-key:exchange
* Method: GET/POST
* Description: CLI 使用 HTTP 连接链接或 connectionKey 兑换短期 WSS connectToken 和 gateway 连接信息
* Tags: ['插件调试', 'Public', 'Write']
* ============================================================================ */
export const ExchangePluginDebugConnectionKeyBodySchema = z.object({
connectionKey: z.string().min(1).meta({
example: 'fgdbg_xxx',
description: '长期插件调试连接密钥'
})
});
export type ExchangePluginDebugConnectionKeyBodyType = z.infer<
typeof ExchangePluginDebugConnectionKeyBodySchema
>;
export const ExchangePluginDebugConnectionKeyQuerySchema =
ExchangePluginDebugConnectionKeyBodySchema;
export type ExchangePluginDebugConnectionKeyQueryType = z.infer<
typeof ExchangePluginDebugConnectionKeyQuerySchema
>;
export const ExchangePluginDebugConnectionKeyResponseSchema = z.object({
gatewayUrl: z.string().min(1).meta({
example: 'wss://gateway.example.com/debug',
description: 'connection-gateway WebSocket 地址'
}),
transport: z.literal('websocket').meta({
example: 'websocket',
description: '调试连接传输协议'
}),
source: z.string().min(1).meta({
example: 'debug:tmbId:tmb_xxx',
description: 'plugin-server 返回的调试 source'
}),
connectToken: z.string().min(1).meta({
example: 'short_lived_connect_token',
description: '短期 WSS 绑定令牌,仅供 CLI 使用'
}),
expiresAt: z.number().int().positive().meta({
example: 1781500000000,
description: 'connectToken 过期时间戳,单位毫秒'
})
});
export type ExchangePluginDebugConnectionKeyResponseType = z.infer<
typeof ExchangePluginDebugConnectionKeyResponseSchema
>;
import type { OpenAPIPath } from '../../../type';
import { DevApiTagsMap } from '../../../tag';
import {
EnablePluginDebugChannelBodySchema,
EnablePluginDebugChannelResponseSchema,
ExchangePluginDebugConnectionKeyBodySchema,
ExchangePluginDebugConnectionKeyQuerySchema,
ExchangePluginDebugConnectionKeyResponseSchema,
GetPluginDebugChannelResponseSchema,
RefreshPluginDebugConnectionKeyBodySchema,
RefreshPluginDebugConnectionKeyResponseSchema,
RevokePluginDebugChannelBodySchema,
RevokePluginDebugChannelResponseSchema
} from './api';
export const PluginDebugPath: OpenAPIPath = {
'/plugin/debug-channel/enable': {
post: {
summary: '开启插件调试通道',
description:
'为当前登录团队成员开启插件调试通道,并返回 plugin-server 生成的 source 和长期 connectionKey',
tags: [DevApiTagsMap.pluginDebug],
requestBody: {
content: {
'application/json': {
schema: EnablePluginDebugChannelBodySchema
}
}
},
responses: {
200: {
description: '开启插件调试通道成功',
content: {
'application/json': {
schema: EnablePluginDebugChannelResponseSchema
}
}
}
}
}
},
'/plugin/debug-channel/key:refresh': {
post: {
summary: '刷新插件调试连接密钥',
description: '刷新当前登录团队成员的插件调试 connectionKey,旧连接密钥会失效',
tags: [DevApiTagsMap.pluginDebug],
requestBody: {
content: {
'application/json': {
schema: RefreshPluginDebugConnectionKeyBodySchema
}
}
},
responses: {
200: {
description: '刷新插件调试连接密钥成功',
content: {
'application/json': {
schema: RefreshPluginDebugConnectionKeyResponseSchema
}
}
}
}
}
},
'/plugin/debug-channel': {
get: {
summary: '获取插件调试通道状态',
description: '获取当前登录团队成员的插件调试状态、source、keyId 和已挂载调试插件',
tags: [DevApiTagsMap.pluginDebug],
responses: {
200: {
description: '获取插件调试通道状态成功',
content: {
'application/json': {
schema: GetPluginDebugChannelResponseSchema
}
}
}
}
}
},
'/plugin/debug-channel/revoke': {
post: {
summary: '关闭插件调试通道',
description: '关闭当前登录团队成员的插件调试通道,并断开对应 gateway session',
tags: [DevApiTagsMap.pluginDebug],
requestBody: {
content: {
'application/json': {
schema: RevokePluginDebugChannelBodySchema
}
}
},
responses: {
200: {
description: '关闭插件调试通道成功',
content: {
'application/json': {
schema: RevokePluginDebugChannelResponseSchema
}
}
}
}
}
},
'/plugin/debug-channel/connection-key:exchange': {
get: {
summary: '通过连接链接兑换插件调试连接信息',
description:
'CLI 使用包含 connectionKey 的 HTTP 连接链接兑换短期 WSS connectToken 和 gateway 连接信息',
tags: [DevApiTagsMap.pluginDebug],
requestParams: {
query: ExchangePluginDebugConnectionKeyQuerySchema
},
responses: {
200: {
description: '兑换插件调试连接信息成功',
content: {
'application/json': {
schema: ExchangePluginDebugConnectionKeyResponseSchema
}
}
}
}
},
post: {
summary: '兑换插件调试连接信息',
description: 'CLI 使用 connectionKey 兑换短期 WSS connectToken 和 gateway 连接信息',
tags: [DevApiTagsMap.pluginDebug],
requestBody: {
content: {
'application/json': {
schema: ExchangePluginDebugConnectionKeyBodySchema
}
}
},
responses: {
200: {
description: '兑换插件调试连接信息成功',
content: {
'application/json': {
schema: ExchangePluginDebugConnectionKeyResponseSchema
}
}
}
}
}
}
};
...@@ -3,10 +3,12 @@ import { MarketplacePath } from './marketplace'; ...@@ -3,10 +3,12 @@ import { MarketplacePath } from './marketplace';
import { PluginToolTagPath } from './toolTag'; import { PluginToolTagPath } from './toolTag';
import { PluginAdminPath } from './admin'; import { PluginAdminPath } from './admin';
import { PluginTeamPath } from './team'; import { PluginTeamPath } from './team';
import { PluginDebugPath } from './debug';
export const PluginPath: OpenAPIPath = { export const PluginPath: OpenAPIPath = {
...MarketplacePath, ...MarketplacePath,
...PluginToolTagPath, ...PluginToolTagPath,
...PluginAdminPath, ...PluginAdminPath,
...PluginTeamPath ...PluginTeamPath,
...PluginDebugPath
}; };
...@@ -25,7 +25,10 @@ export const TeamSystemPluginListItemSchema = SystemToolListItemSchema.extend({ ...@@ -25,7 +25,10 @@ export const TeamSystemPluginListItemSchema = SystemToolListItemSchema.extend({
export const GetTeamPluginListResponseSchema = z.array(TeamSystemPluginListItemSchema); export const GetTeamPluginListResponseSchema = z.array(TeamSystemPluginListItemSchema);
export type GetTeamPluginListResponseType = z.infer<typeof GetTeamPluginListResponseSchema>; export type GetTeamPluginListResponseType = z.infer<typeof GetTeamPluginListResponseSchema>;
export const GetTeamToolDetailSourceEnum = z.enum(['system', 'team']); export const GetTeamToolDetailSourceSchema = z.union([
z.enum(['system', 'team']),
z.string().regex(/^debug:tmbId:[^:]+$/)
]);
/* ============================================================================ /* ============================================================================
* API: 获取团队工具详情 * API: 获取团队工具详情
...@@ -44,9 +47,10 @@ export const GetTeamToolDetailQuerySchema = z.object({ ...@@ -44,9 +47,10 @@ export const GetTeamToolDetailQuerySchema = z.object({
example: '68ad85a7463006c963799a05', example: '68ad85a7463006c963799a05',
description: '工具版本 ID。为空时返回最新版本详情' description: '工具版本 ID。为空时返回最新版本详情'
}), }),
source: GetTeamToolDetailSourceEnum.optional().meta({ source: GetTeamToolDetailSourceSchema.optional().meta({
example: 'system', example: 'debug:tmbId:tmb_xxx',
description: '工具来源。system 表示系统工具,team 表示当前团队工具' description:
'工具来源。system 表示系统工具,team 表示当前团队工具,debug:tmbId:* 表示当前调试来源'
}) })
}); });
......
...@@ -75,6 +75,9 @@ const OpenAPIToolRefSchema = z ...@@ -75,6 +75,9 @@ const OpenAPIToolRefSchema = z
.object({ .object({
toolId: z.string().meta({ toolId: z.string().meta({
description: '节点引用的工具 ID' description: '节点引用的工具 ID'
}),
source: z.string().optional().meta({
description: '节点引用的工具来源。调试工具会写入 debug source'
}) })
}) })
.meta({ .meta({
......
...@@ -72,7 +72,7 @@ export const openAPITagGroups = [ ...@@ -72,7 +72,7 @@ export const openAPITagGroups = [
}, },
{ {
name: '核心-插件系统', name: '核心-插件系统',
tags: [DevApiTagsMap.pluginToolTag, DevApiTagsMap.pluginTeam] tags: [DevApiTagsMap.pluginToolTag, DevApiTagsMap.pluginTeam, DevApiTagsMap.pluginDebug]
}, },
{ {
name: '辅助-用户体系', name: '辅助-用户体系',
......
...@@ -43,6 +43,7 @@ export const DevApiTagsMap = { ...@@ -43,6 +43,7 @@ export const DevApiTagsMap = {
/* 核心-插件系统 */ /* 核心-插件系统 */
pluginToolTag: '工具标签', pluginToolTag: '工具标签',
pluginTeam: '团队插件管理', pluginTeam: '团队插件管理',
pluginDebug: '插件调试',
/* 辅助-用户体系 */ /* 辅助-用户体系 */
userInform: '用户通知', userInform: '用户通知',
......
...@@ -13,7 +13,7 @@ ...@@ -13,7 +13,7 @@
"dependencies": { "dependencies": {
"@apidevtools/swagger-parser": "^10.1.0", "@apidevtools/swagger-parser": "^10.1.0",
"@bany/curl-to-json": "^1.2.8", "@bany/curl-to-json": "^1.2.8",
"@fastgpt-plugin/sdk-client": "0.0.1-alpha.9", "@fastgpt-plugin/sdk-client": "0.0.1-alpha.11",
"axios": "catalog:", "axios": "catalog:",
"ipaddr.js": "catalog:", "ipaddr.js": "catalog:",
"cron-parser": "^4.9.0", "cron-parser": "^4.9.0",
......
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { getErrText, UserError } from '@fastgpt/global/common/error/utils'; import { getErrText, ToastHandledError, UserError } from '@fastgpt/global/common/error/utils';
import { ERROR_ENUM, ERROR_RESPONSE } from '@fastgpt/global/common/error/errorCode'; import { ERROR_ENUM, ERROR_RESPONSE } from '@fastgpt/global/common/error/errorCode';
describe('getErrText', () => { describe('getErrText', () => {
...@@ -52,6 +52,42 @@ describe('getErrText', () => { ...@@ -52,6 +52,42 @@ describe('getErrText', () => {
}; };
expect(getErrText(err)).toBe('Sandbox is not configured'); expect(getErrText(err)).toBe('Sandbox is not configured');
}); });
it('should use localized reason when locale is provided', () => {
const err = {
response: {
data: {
error: {
message: 'English message',
reason: {
en: 'English reason',
'zh-CN': '中文原因'
}
}
}
}
};
expect(getErrText(err, '', 'zh-CN')).toBe('中文原因');
});
it('should keep existing nested object behavior when locale is not provided', () => {
const err = {
response: {
data: {
error: {
message: 'English message',
reason: {
en: 'English reason',
'zh-CN': '中文原因'
}
}
}
}
};
expect(getErrText(err)).toBe('');
});
}); });
describe('UserError', () => { describe('UserError', () => {
...@@ -63,3 +99,13 @@ describe('UserError', () => { ...@@ -63,3 +99,13 @@ describe('UserError', () => {
expect(err.message).toBe('boom'); expect(err.message).toBe('boom');
}); });
}); });
describe('ToastHandledError', () => {
it('should set name to ToastHandledError', () => {
const err = new ToastHandledError('handled');
expect(err).toBeInstanceOf(Error);
expect(err.name).toBe('ToastHandledError');
expect(err.message).toBe('handled');
});
});
...@@ -7,7 +7,8 @@ describe('GetPreviewNodeQuerySchema', () => { ...@@ -7,7 +7,8 @@ describe('GetPreviewNodeQuerySchema', () => {
expect( expect(
GetPreviewNodeQuerySchema.safeParse({ GetPreviewNodeQuerySchema.safeParse({
appId: 'systemTool-weather', appId: 'systemTool-weather',
versionId: '' versionId: '',
source: 'debug:tmbId:tmb-1'
}).success }).success
).toBe(true); ).toBe(true);
......
...@@ -2,6 +2,9 @@ import { describe, expect, it } from 'vitest'; ...@@ -2,6 +2,9 @@ import { describe, expect, it } from 'vitest';
import { import {
getToolNameCandidates, getToolNameCandidates,
getToolRawId, getToolRawId,
hasDebugToolInNodes,
hasDebugToolInSelectedTools,
parseDebugToolSource,
parseToolsetToolId, parseToolsetToolId,
splitCombineToolId, splitCombineToolId,
splitToolsetToolPluginId splitToolsetToolPluginId
...@@ -117,6 +120,61 @@ describe('splitCombineToolId', () => { ...@@ -117,6 +120,61 @@ describe('splitCombineToolId', () => {
}); });
}); });
describe('parseDebugToolSource', () => {
it('should parse stable tmb debug source', () => {
expect(parseDebugToolSource('debug:tmbId:tmb-1')).toEqual({
tmbId: 'tmb-1'
});
});
it('should ignore invalid debug source', () => {
expect(parseDebugToolSource('debug:invalid')).toBeUndefined();
expect(parseDebugToolSource('debug:tmbId:tmb-1:session:dbg-1')).toBeUndefined();
expect(parseDebugToolSource('system')).toBeUndefined();
});
it('does not parse debug source from combined tool id', () => {
expect(() => splitCombineToolId('debug:tmbId:tmb-1|weather')).toThrow('Invalid tool id');
});
});
describe('debug tool detection', () => {
it('detects explicit debug source in selected tools', () => {
expect(
hasDebugToolInSelectedTools([
{
id: 'node-id',
pluginId: 'systemTool-weather',
source: 'debug:tmbId:tmb-1'
} as any
])
).toBe(true);
});
it('ignores debug-looking ids without explicit debug source', () => {
expect(
hasDebugToolInSelectedTools([
{
id: 'debug:tmbId:tmb-1|node-id',
pluginId: 'debug:tmbId:tmb-1|weather'
} as any
])
).toBe(false);
});
it('detects explicit debug source in workflow nodes', () => {
expect(
hasDebugToolInNodes([
{
pluginId: 'systemTool-weather',
source: 'debug:tmbId:tmb-1',
inputs: []
} as any
])
).toBe(true);
});
});
describe('getToolRawId', () => { describe('getToolRawId', () => {
it('should return pluginId for pure ObjectId', () => { it('should return pluginId for pure ObjectId', () => {
const result = getToolRawId('507f1f77bcf86cd799439011'); const result = getToolRawId('507f1f77bcf86cd799439011');
......
...@@ -133,6 +133,7 @@ export const LogCategories = { ...@@ -133,6 +133,7 @@ export const LogCategories = {
ADMIN_MARKETPLACE: ['plugin', 'admin', 'marketplace'], ADMIN_MARKETPLACE: ['plugin', 'admin', 'marketplace'],
ADMIN_PKG: ['plugin', 'admin', 'pkg'], ADMIN_PKG: ['plugin', 'admin', 'pkg'],
ADMIN_TOOL: ['plugin', 'admin', 'tool'], ADMIN_TOOL: ['plugin', 'admin', 'tool'],
DEBUG: ['plugin', 'debug'],
TEAM: ['plugin', 'team'], TEAM: ['plugin', 'team'],
TOOL_TAG: ['plugin', 'tool-tag'] TOOL_TAG: ['plugin', 'tool-tag']
}), }),
......
...@@ -28,7 +28,7 @@ export const computedAppToolUsage = async ({ ...@@ -28,7 +28,7 @@ export const computedAppToolUsage = async ({
AppToolSourceEnum.community, AppToolSourceEnum.community,
AppToolSourceEnum.systemTool AppToolSourceEnum.systemTool
]); ]);
if (set.has(source)) { if (set.has(source as AppToolSourceEnum)) {
if (error) return 0; if (error) return 0;
const pluginCurrentCost = plugin.currentCost ?? 0; const pluginCurrentCost = plugin.currentCost ?? 0;
......
...@@ -13,6 +13,7 @@ import { getHTTPToolRuntimeNode } from '@fastgpt/global/core/app/tool/httpTool/u ...@@ -13,6 +13,7 @@ import { getHTTPToolRuntimeNode } from '@fastgpt/global/core/app/tool/httpTool/u
import { getMCPToolRuntimeNode } from '@fastgpt/global/core/app/tool/mcpTool/utils'; import { getMCPToolRuntimeNode } from '@fastgpt/global/core/app/tool/mcpTool/utils';
import { import {
getToolNameCandidates, getToolNameCandidates,
isDebugToolSource,
splitCombineToolId, splitCombineToolId,
splitToolsetToolPluginId splitToolsetToolPluginId
} from '@fastgpt/global/core/app/tool/utils'; } from '@fastgpt/global/core/app/tool/utils';
...@@ -161,10 +162,12 @@ export async function getClientSystemToolPreviewNode({ ...@@ -161,10 +162,12 @@ export async function getClientSystemToolPreviewNode({
...schemaInputs ...schemaInputs
]; ];
const isWorkflowTool = !!toolDetail.associatedPluginId; const isWorkflowTool = !!toolDetail.associatedPluginId;
const toolConfigSource = isDebugToolSource(toolSource) ? toolSource : undefined;
return { return {
id: getNanoid(), id: getNanoid(),
pluginId: pluginId, pluginId: pluginId,
source: toolConfigSource,
flowNodeType: isWorkflowTool flowNodeType: isWorkflowTool
? FlowNodeTypeEnum.pluginModule ? FlowNodeTypeEnum.pluginModule
: toolDetail.isToolSet : toolDetail.isToolSet
...@@ -209,6 +212,7 @@ export async function getClientSystemToolPreviewNode({ ...@@ -209,6 +212,7 @@ export async function getClientSystemToolPreviewNode({
? { ? {
systemToolSet: { systemToolSet: {
toolId: pluginId, toolId: pluginId,
...(toolConfigSource ? { source: toolConfigSource } : {}),
toolList: toolList:
toolDetail.children?.map((child) => ({ toolDetail.children?.map((child) => ({
description: child.description ?? '', description: child.description ?? '',
...@@ -219,7 +223,8 @@ export async function getClientSystemToolPreviewNode({ ...@@ -219,7 +223,8 @@ export async function getClientSystemToolPreviewNode({
} }
: { : {
systemTool: { systemTool: {
toolId: pluginId toolId: pluginId,
...(toolConfigSource ? { source: toolConfigSource } : {})
} }
}) })
} }
...@@ -246,23 +251,23 @@ export async function getClientToolPreviewNode({ ...@@ -246,23 +251,23 @@ export async function getClientToolPreviewNode({
lang?: localeType; lang?: localeType;
source?: string; source?: string;
}): Promise<FlowNodeTemplateType> { }): Promise<FlowNodeTemplateType> {
const { source, pluginId } = splitCombineToolId(appId); const { source: idSource, pluginId } = splitCombineToolId(appId);
const data = await (async () => { const data = await (async () => {
if (source === AppToolSourceEnum.systemTool || source === AppToolSourceEnum.commercial) { if (idSource === AppToolSourceEnum.systemTool || idSource === AppToolSourceEnum.commercial) {
return getClientSystemToolPreviewNode({ return getClientSystemToolPreviewNode({
pluginId: appId, pluginId: appId,
versionId, versionId,
getLatestVersion, getLatestVersion,
lang, lang,
source: source === AppToolSourceEnum.commercial ? AppToolSourceEnum.commercial : toolSource source: toolSource
}); });
} }
// 存在 app 里面的插件的情况 // 存在 app 里面的插件的情况
const app: AppToolType = await (async () => { const app: AppToolType = await (async () => {
// App / Mcp toolset / Http toolset // App / Mcp toolset / Http toolset
if (source === AppToolSourceEnum.personal) { if (idSource === AppToolSourceEnum.personal) {
const item = await MongoApp.findById(pluginId).lean(); const item = await MongoApp.findById(pluginId).lean();
if (!item) return Promise.reject(PluginErrEnum.unExist); if (!item) return Promise.reject(PluginErrEnum.unExist);
if (AppFolderTypeList.includes(item.type)) return Promise.reject(PluginErrEnum.unExist); if (AppFolderTypeList.includes(item.type)) return Promise.reject(PluginErrEnum.unExist);
...@@ -320,7 +325,7 @@ export async function getClientToolPreviewNode({ ...@@ -320,7 +325,7 @@ export async function getClientToolPreviewNode({
}; };
} }
// mcp tool // mcp tool
else if (source === AppToolSourceEnum.mcp) { else if (idSource === AppToolSourceEnum.mcp) {
const { parentId, toolName } = splitToolsetToolPluginId(pluginId); const { parentId, toolName } = splitToolsetToolPluginId(pluginId);
// 1. get parentApp // 1. get parentApp
const item = await MongoApp.findById(parentId).lean(); const item = await MongoApp.findById(parentId).lean();
...@@ -372,7 +377,7 @@ export async function getClientToolPreviewNode({ ...@@ -372,7 +377,7 @@ export async function getClientToolPreviewNode({
}; };
} }
// http tool // http tool
else if (source === AppToolSourceEnum.http) { else if (idSource === AppToolSourceEnum.http) {
const { parentId, toolName } = splitToolsetToolPluginId(pluginId); const { parentId, toolName } = splitToolsetToolPluginId(pluginId);
const item = await MongoApp.findById(parentId).lean(); const item = await MongoApp.findById(parentId).lean();
if (!item) return Promise.reject(PluginErrEnum.unExist); if (!item) return Promise.reject(PluginErrEnum.unExist);
...@@ -475,6 +480,7 @@ export async function getClientToolPreviewNode({ ...@@ -475,6 +480,7 @@ export async function getClientToolPreviewNode({
return { return {
id: getNanoid(), id: getNanoid(),
pluginId: app.id, pluginId: app.id,
source: isDebugToolSource(toolSource) ? toolSource : undefined,
flowNodeType, flowNodeType,
avatar: app.avatar, avatar: app.avatar,
name: parseI18nString(app.name, lang), name: parseI18nString(app.name, lang),
......
...@@ -41,7 +41,15 @@ export async function rewriteAppWorkflowToDetail({ ...@@ -41,7 +41,15 @@ export async function rewriteAppWorkflowToDetail({
Partial<SelectedDatasetType>; Partial<SelectedDatasetType>;
const defaultDeletedDatasetAvatar = DatasetTypeMap[DatasetTypeEnum.dataset].avatar; const defaultDeletedDatasetAvatar = DatasetTypeMap[DatasetTypeEnum.dataset].avatar;
const loadToolNode = async ({ id, versionId }: { id: string; versionId?: string }) => { const loadToolNode = async ({
id,
versionId,
source
}: {
id: string;
versionId?: string;
source?: string;
}) => {
const { authAppId } = splitCombineToolId(id); const { authAppId } = splitCombineToolId(id);
try { try {
...@@ -49,7 +57,8 @@ export async function rewriteAppWorkflowToDetail({ ...@@ -49,7 +57,8 @@ export async function rewriteAppWorkflowToDetail({
getClientToolPreviewNode({ getClientToolPreviewNode({
appId: id, appId: id,
versionId, versionId,
lang lang,
source
}), }),
...(authAppId ...(authAppId
? [ ? [
...@@ -70,7 +79,7 @@ export async function rewriteAppWorkflowToDetail({ ...@@ -70,7 +79,7 @@ export async function rewriteAppWorkflowToDetail({
} catch (error) { } catch (error) {
return { return {
success: false, success: false,
error: getErrText(error) error: getErrText(error, '', lang)
}; };
} }
}; };
...@@ -142,10 +151,15 @@ export async function rewriteAppWorkflowToDetail({ ...@@ -142,10 +151,15 @@ export async function rewriteAppWorkflowToDetail({
if (node.pluginId) { if (node.pluginId) {
const result = await loadToolNode({ const result = await loadToolNode({
id: node.pluginId, id: node.pluginId,
versionId: node.version ?? '' versionId: node.version ?? '',
source:
node.source ??
node.toolConfig?.systemTool?.source ??
node.toolConfig?.systemToolSet?.source
}); });
if (result.success) { if (result.success) {
const preview = result.data!; const preview = result.data!;
node.source = preview.source ?? node.source;
node.avatar = preview.avatar ?? node.avatar; node.avatar = preview.avatar ?? node.avatar;
node.isFolder = preview.isFolder; node.isFolder = preview.isFolder;
node.pluginData = { node.pluginData = {
...@@ -216,7 +230,7 @@ export async function rewriteAppWorkflowToDetail({ ...@@ -216,7 +230,7 @@ export async function rewriteAppWorkflowToDetail({
const tools = toolsParse.success ? toolsParse.data : []; const tools = toolsParse.success ? toolsParse.data : [];
const nodes = await Promise.all( const nodes = await Promise.all(
tools.map(async (tool) => { tools.map(async (tool) => {
const result = await loadToolNode({ id: tool.id }); const result = await loadToolNode({ id: tool.id, source: tool.source });
if (result.success) { if (result.success) {
const data = result.data!; const data = result.data!;
// Merge saved config back into inputs // Merge saved config back into inputs
...@@ -230,6 +244,8 @@ export async function rewriteAppWorkflowToDetail({ ...@@ -230,6 +244,8 @@ export async function rewriteAppWorkflowToDetail({
return { return {
...data, ...data,
source: tool.source ?? data.source,
toolConfig: tool.toolConfig ?? data.toolConfig,
inputs: mergedInputs inputs: mergedInputs
}; };
} else { } else {
......
import type { StoreSecretValueType } from '@fastgpt/global/common/secret/type'; import type { StoreSecretValueType } from '@fastgpt/global/common/secret/type';
import { SystemToolSecretInputTypeEnum } from '@fastgpt/global/core/app/tool/systemTool/constants'; import { SystemToolSecretInputTypeEnum } from '@fastgpt/global/core/app/tool/systemTool/constants';
import type { DispatchSubAppResponse } from '../../type'; import type { DispatchSubAppResponse } from '../../type';
import { getToolNameCandidates, getToolRawId } from '@fastgpt/global/core/app/tool/utils'; import {
getToolNameCandidates,
getToolRawId,
isDebugToolSource
} from '@fastgpt/global/core/app/tool/utils';
import { getSecretValue } from '../../../../../../../common/secret/utils'; import { getSecretValue } from '../../../../../../../common/secret/utils';
import type { import type {
ChatDispatchProps, ChatDispatchProps,
...@@ -86,6 +90,12 @@ export const dispatchTool = async ({ ...@@ -86,6 +90,12 @@ export const dispatchTool = async ({
}; };
const logger = getLogger(LogCategories.MODULE.APP.TOOL); const logger = getLogger(LogCategories.MODULE.APP.TOOL);
const getSystemToolSource = () => {
const toolConfigSource = toolConfig?.systemTool?.source;
if (isDebugToolSource(toolConfigSource)) return toolConfigSource;
return 'system';
};
try { try {
/** /**
...@@ -101,10 +111,11 @@ export const dispatchTool = async ({ ...@@ -101,10 +111,11 @@ export const dispatchTool = async ({
}; };
if (toolConfig?.systemTool?.toolId) { if (toolConfig?.systemTool?.toolId) {
const toolSource = getSystemToolSource();
const systemToolRepo = SystemToolRepo.getInstance(); const systemToolRepo = SystemToolRepo.getInstance();
const tool = await systemToolRepo.getSystemToolRuntime({ const tool = await systemToolRepo.getSystemToolRuntime({
pluginId: toolConfig.systemTool.toolId, pluginId: toolConfig.systemTool.toolId,
source: 'system', source: toolSource,
version version
}); });
const inputConfigParams = await (async () => { const inputConfigParams = await (async () => {
...@@ -117,6 +128,7 @@ export const dispatchTool = async ({ ...@@ -117,6 +128,7 @@ export const dispatchTool = async ({
}); });
case SystemToolSecretInputTypeEnum.system: case SystemToolSecretInputTypeEnum.system:
default: default:
if (isDebugToolSource(toolSource)) return {};
return tool.secretsVal ?? {}; return tool.secretsVal ?? {};
} }
})(); })();
...@@ -142,7 +154,7 @@ export const dispatchTool = async ({ ...@@ -142,7 +154,7 @@ export const dispatchTool = async ({
pluginId: formatToolId, pluginId: formatToolId,
...(childId ? { childId } : {}), ...(childId ? { childId } : {}),
version: tool.version ?? version ?? '', version: tool.version ?? version ?? '',
source: 'system', // TODO: 后续 source 需要从节点配置中获取到 source: toolSource,
input: Object.fromEntries(Object.entries(params)), input: Object.fromEntries(Object.entries(params)),
secrets: inputConfigParams, secrets: inputConfigParams,
systemVar: { systemVar: {
......
import type { SkillToolType } from '@fastgpt/global/core/ai/skill/type'; import type { SkillToolType } from '@fastgpt/global/core/ai/skill/type';
import { import {
getToolNameCandidates, getToolNameCandidates,
isDebugToolSource,
splitCombineToolId, splitCombineToolId,
splitToolsetToolPluginId splitToolsetToolPluginId
} from '@fastgpt/global/core/app/tool/utils'; } from '@fastgpt/global/core/app/tool/utils';
...@@ -106,17 +107,20 @@ export const getAgentRuntimeTools = async ({ ...@@ -106,17 +107,20 @@ export const getAgentRuntimeTools = async ({
const formatSystemToolNode = async ({ const formatSystemToolNode = async ({
toolId, toolId,
nodeId, nodeId,
source idSource,
runtimeSource
}: { }: {
toolId: string; toolId: string;
nodeId: string; nodeId: string;
source: AppToolSourceEnum.systemTool | AppToolSourceEnum.commercial; idSource: AppToolSourceEnum.systemTool | AppToolSourceEnum.commercial;
runtimeSource?: string;
}): Promise<AgentRuntimeNode> => { }): Promise<AgentRuntimeNode> => {
const systemToolRepo = SystemToolRepo.getInstance(); const systemToolRepo = SystemToolRepo.getInstance();
const toolConfigSource = isDebugToolSource(runtimeSource) ? runtimeSource : undefined;
const toolDetail = await systemToolRepo.getSystemToolDetail({ const toolDetail = await systemToolRepo.getSystemToolDetail({
pluginId: toolId, pluginId: toolId,
lang, lang,
source: source === AppToolSourceEnum.commercial ? AppToolSourceEnum.commercial : 'system' source: toolConfigSource ?? (idSource === AppToolSourceEnum.commercial ? idSource : 'system')
}); });
const isWorkflowTool = !!toolDetail.associatedPluginId; const isWorkflowTool = !!toolDetail.associatedPluginId;
const secrets = jsonSchema2SecretInput({ jsonSchema: toolDetail.secretSchema }); const secrets = jsonSchema2SecretInput({ jsonSchema: toolDetail.secretSchema });
...@@ -168,6 +172,7 @@ export const getAgentRuntimeTools = async ({ ...@@ -168,6 +172,7 @@ export const getAgentRuntimeTools = async ({
? { ? {
systemToolSet: { systemToolSet: {
toolId, toolId,
...(toolConfigSource ? { source: toolConfigSource } : {}),
toolList: toolList:
toolDetail.children?.map((child) => ({ toolDetail.children?.map((child) => ({
description: child.description ?? '', description: child.description ?? '',
...@@ -178,7 +183,8 @@ export const getAgentRuntimeTools = async ({ ...@@ -178,7 +183,8 @@ export const getAgentRuntimeTools = async ({
} }
: { : {
systemTool: { systemTool: {
toolId toolId,
...(toolConfigSource ? { source: toolConfigSource } : {})
} }
}) })
} }
...@@ -347,29 +353,32 @@ export const getAgentRuntimeTools = async ({ ...@@ -347,29 +353,32 @@ export const getAgentRuntimeTools = async ({
}; };
const getRuntimeToolNode = async ({ const getRuntimeToolNode = async ({
source, idSource,
runtimeSource,
pluginId, pluginId,
toolId, toolId,
app app
}: { }: {
source: AppToolSourceEnum; idSource: AppToolSourceEnum | string;
runtimeSource?: string;
pluginId: string; pluginId: string;
toolId: string; toolId: string;
app?: AppSchemaType; app?: AppSchemaType;
}): Promise<AgentRuntimeNode> => { }): Promise<AgentRuntimeNode> => {
// Agent 运行时只需要节点执行和 schema 信息,不能依赖面向前端展示的 preview controller。 // Agent 运行时只需要节点执行和 schema 信息,不能依赖面向前端展示的 preview controller。
if (source === AppToolSourceEnum.systemTool || source === AppToolSourceEnum.commercial) { if (idSource === AppToolSourceEnum.systemTool || idSource === AppToolSourceEnum.commercial) {
return formatSystemToolNode({ return formatSystemToolNode({
toolId, toolId,
nodeId: pluginId, nodeId: pluginId,
source idSource,
runtimeSource
}); });
} }
if (!app) return Promise.reject(PluginErrEnum.unExist); if (!app) return Promise.reject(PluginErrEnum.unExist);
if (source === AppToolSourceEnum.mcp) { if (idSource === AppToolSourceEnum.mcp) {
return formatMcpToolNode({ app, pluginId }); return formatMcpToolNode({ app, pluginId });
} }
if (source === AppToolSourceEnum.http) { if (idSource === AppToolSourceEnum.http) {
return formatHttpToolNode({ app, pluginId }); return formatHttpToolNode({ app, pluginId });
} }
return formatPersonalAppNode({ app }); return formatPersonalAppNode({ app });
...@@ -438,7 +447,11 @@ export const getAgentRuntimeTools = async ({ ...@@ -438,7 +447,11 @@ export const getAgentRuntimeTools = async ({
return Promise.all( return Promise.all(
tools.map<Promise<SubAppInitType[]>>(async (tool) => { tools.map<Promise<SubAppInitType[]>>(async (tool) => {
try { try {
const { pluginId, authAppId, source } = splitCombineToolId(tool.id); const { pluginId, authAppId, source: idSource } = splitCombineToolId(tool.id);
const runtimeSource =
tool.source ??
tool.toolConfig?.systemTool?.source ??
tool.toolConfig?.systemToolSet?.source;
// 工具间整体并发;单个 App 类工具必须先鉴权拿到 app,才能读取对应版本节点。 // 工具间整体并发;单个 App 类工具必须先鉴权拿到 app,才能读取对应版本节点。
const authAppPromise = authAppId const authAppPromise = authAppId
? authAppByTmbId({ ? authAppByTmbId({
...@@ -452,7 +465,8 @@ export const getAgentRuntimeTools = async ({ ...@@ -452,7 +465,8 @@ export const getAgentRuntimeTools = async ({
authAppPromise, authAppPromise,
authAppPromise.then((authResult) => authAppPromise.then((authResult) =>
getRuntimeToolNode({ getRuntimeToolNode({
source, idSource,
runtimeSource,
pluginId, pluginId,
app: authResult?.app, app: authResult?.app,
toolId: tool.id toolId: tool.id
...@@ -460,6 +474,9 @@ export const getAgentRuntimeTools = async ({ ...@@ -460,6 +474,9 @@ export const getAgentRuntimeTools = async ({
) )
]); ]);
const authApp = authResult?.app; const authApp = authResult?.app;
if (tool.toolConfig) {
toolNode.toolConfig = tool.toolConfig;
}
// 合并用户在 Agent 工具面板里保存的配置;false/0/空字符串也是有效配置值。 // 合并用户在 Agent 工具面板里保存的配置;false/0/空字符串也是有效配置值。
toolNode.inputs.forEach((input) => { toolNode.inputs.forEach((input) => {
...@@ -482,7 +499,7 @@ export const getAgentRuntimeTools = async ({ ...@@ -482,7 +499,7 @@ export const getAgentRuntimeTools = async ({
} }
const toolType = (() => { const toolType = (() => {
if (source === AppToolSourceEnum.commercial) { if (runtimeSource === AppToolSourceEnum.commercial) {
return 'commercialTool'; return 'commercialTool';
} }
if (toolNode.flowNodeType === FlowNodeTypeEnum.appModule) { if (toolNode.flowNodeType === FlowNodeTypeEnum.appModule) {
......
...@@ -19,7 +19,11 @@ import { getNodeErrResponse } from '../utils'; ...@@ -19,7 +19,11 @@ import { getNodeErrResponse } from '../utils';
import { getAppVersionById } from '../../../../core/app/version/controller'; import { getAppVersionById } from '../../../../core/app/version/controller';
import { runHTTPTool } from '../../../app/http'; import { runHTTPTool } from '../../../app/http';
import { getWorkflowContext } from '../../utils/context'; import { getWorkflowContext } from '../../utils/context';
import { getToolNameCandidates, getToolRawId } from '@fastgpt/global/core/app/tool/utils'; import {
getToolNameCandidates,
getToolRawId,
isDebugToolSource
} from '@fastgpt/global/core/app/tool/utils';
import { pluginClient } from '../../../../thirdProvider/fastgptPlugin'; import { pluginClient } from '../../../../thirdProvider/fastgptPlugin';
import { SystemToolRepo } from '../../../app/tool/systemTool/systemTool.repo'; import { SystemToolRepo } from '../../../app/tool/systemTool/systemTool.repo';
import { InvokeProcessor } from '../../../../support/invoke/invoke'; import { InvokeProcessor } from '../../../../support/invoke/invoke';
...@@ -65,6 +69,13 @@ export const dispatchRunTool = async (props: RunToolProps): Promise<RunToolRespo ...@@ -65,6 +69,13 @@ export const dispatchRunTool = async (props: RunToolProps): Promise<RunToolRespo
const systemToolId = toolConfig?.systemTool?.toolId; const systemToolId = toolConfig?.systemTool?.toolId;
let toolInput: Record<string, any> = {}; let toolInput: Record<string, any> = {};
const getSystemToolSource = () => {
const toolConfigSource = toolConfig?.systemTool?.source;
if (isDebugToolSource(toolConfigSource)) return toolConfigSource;
return 'system';
};
try { try {
/** /**
* HTTP/MCP 子工具的 toolId 可由工作流 JSON 持久化,运行时必须用当前工作流执行身份 * HTTP/MCP 子工具的 toolId 可由工作流 JSON 持久化,运行时必须用当前工作流执行身份
...@@ -80,10 +91,11 @@ export const dispatchRunTool = async (props: RunToolProps): Promise<RunToolRespo ...@@ -80,10 +91,11 @@ export const dispatchRunTool = async (props: RunToolProps): Promise<RunToolRespo
// run system tool // run system tool
if (toolConfig?.systemTool?.toolId) { if (toolConfig?.systemTool?.toolId) {
const toolSource = getSystemToolSource();
const systemToolRepo = SystemToolRepo.getInstance(); const systemToolRepo = SystemToolRepo.getInstance();
const tool = await systemToolRepo.getSystemToolRuntime({ const tool = await systemToolRepo.getSystemToolRuntime({
pluginId: toolConfig.systemTool.toolId, pluginId: toolConfig.systemTool.toolId,
source: 'system', // TODO : 后续用户调用时传 teamId source: toolSource,
version version
}); });
...@@ -98,6 +110,7 @@ export const dispatchRunTool = async (props: RunToolProps): Promise<RunToolRespo ...@@ -98,6 +110,7 @@ export const dispatchRunTool = async (props: RunToolProps): Promise<RunToolRespo
}); });
case SystemToolSecretInputTypeEnum.system: case SystemToolSecretInputTypeEnum.system:
default: default:
if (isDebugToolSource(toolSource)) return {};
return tool.secretsVal ?? {}; return tool.secretsVal ?? {};
} }
})(); })();
...@@ -123,7 +136,7 @@ export const dispatchRunTool = async (props: RunToolProps): Promise<RunToolRespo ...@@ -123,7 +136,7 @@ export const dispatchRunTool = async (props: RunToolProps): Promise<RunToolRespo
const res = await pluginClient.runToolStream({ const res = await pluginClient.runToolStream({
pluginId: formatToolId, pluginId: formatToolId,
version: tool.version ?? version ?? '', version: tool.version ?? version ?? '',
source: 'system', // TODO: 后续用户调用时传 teamId source: toolSource,
input: toolInput, input: toolInput,
secrets: inputConfigParams, secrets: inputConfigParams,
...(childId ? { childId } : {}), ...(childId ? { childId } : {}),
......
...@@ -6,6 +6,7 @@ import { NodeInputKeyEnum } from '@fastgpt/global/core/workflow/constants'; ...@@ -6,6 +6,7 @@ import { NodeInputKeyEnum } from '@fastgpt/global/core/workflow/constants';
import type { localeType } from '@fastgpt/global/common/i18n/type'; import type { localeType } from '@fastgpt/global/common/i18n/type';
import { SystemToolRepo } from '../../app/tool/systemTool/systemTool.repo'; import { SystemToolRepo } from '../../app/tool/systemTool/systemTool.repo';
import { jsonSchema2NodeInput, jsonSchema2NodeOutput } from '@fastgpt/global/core/app/jsonschema'; import { jsonSchema2NodeInput, jsonSchema2NodeOutput } from '@fastgpt/global/core/app/jsonschema';
import { isDebugToolSource } from '@fastgpt/global/core/app/tool/utils';
/* filter search result */ /* filter search result */
export const filterSearchResultsByMaxChars = async ( export const filterSearchResultsByMaxChars = async (
...@@ -42,6 +43,12 @@ export async function getSystemToolRunTimeNodeFromSystemToolset({ ...@@ -42,6 +43,12 @@ export async function getSystemToolRunTimeNodeFromSystemToolset({
lang?: localeType; lang?: localeType;
}): Promise<RuntimeNodeItemType[]> { }): Promise<RuntimeNodeItemType[]> {
const systemToolId = toolSetNode.toolConfig?.systemToolSet?.toolId!; const systemToolId = toolSetNode.toolConfig?.systemToolSet?.toolId!;
const systemToolSource = (() => {
const toolConfigSource = toolSetNode.toolConfig?.systemToolSet?.source;
if (isDebugToolSource(toolConfigSource)) return toolConfigSource;
return 'system';
})();
const selectedTools = toolSetNode.toolConfig?.systemToolSet?.toolList ?? []; const selectedTools = toolSetNode.toolConfig?.systemToolSet?.toolList ?? [];
if (!selectedTools.length) return []; if (!selectedTools.length) return [];
...@@ -52,8 +59,7 @@ export async function getSystemToolRunTimeNodeFromSystemToolset({ ...@@ -52,8 +59,7 @@ export async function getSystemToolRunTimeNodeFromSystemToolset({
const tool = await systemToolRepo.getSystemToolDetail({ const tool = await systemToolRepo.getSystemToolDetail({
pluginId: systemToolId, pluginId: systemToolId,
lang, lang,
// source: toolSetNode.toolConfig?.systemToolSet?.source, source: systemToolSource,
source: 'system',
version: toolSetNode.version, version: toolSetNode.version,
fallbackLatestVersion: true fallbackLatestVersion: true
}); });
...@@ -94,7 +100,8 @@ export async function getSystemToolRunTimeNodeFromSystemToolset({ ...@@ -94,7 +100,8 @@ export async function getSystemToolRunTimeNodeFromSystemToolset({
toolDescription, toolDescription,
toolConfig: { toolConfig: {
systemTool: { systemTool: {
toolId: pluginId toolId: pluginId,
...(isDebugToolSource(systemToolSource) ? { source: systemToolSource } : {})
} }
}, },
pluginId pluginId
......
...@@ -5,6 +5,7 @@ import { ...@@ -5,6 +5,7 @@ import {
FlowNodeInputTypeEnum, FlowNodeInputTypeEnum,
FlowNodeTypeEnum FlowNodeTypeEnum
} from '@fastgpt/global/core/workflow/node/constant'; } from '@fastgpt/global/core/workflow/node/constant';
import { PluginStatusEnum, type PluginStatusType } from '@fastgpt/global/core/plugin/type';
const mocks = vi.hoisted(() => ({ const mocks = vi.hoisted(() => ({
listTools: vi.fn(), listTools: vi.fn(),
...@@ -24,7 +25,8 @@ vi.mock('@fastgpt/service/thirdProvider/fastgptPlugin', () => ({ ...@@ -24,7 +25,8 @@ vi.mock('@fastgpt/service/thirdProvider/fastgptPlugin', () => ({
listTools: mocks.listTools, listTools: mocks.listTools,
listPluginVersions: mocks.listPluginVersions, listPluginVersions: mocks.listPluginVersions,
getTool: mocks.getTool getTool: mocks.getTool
} },
withPluginClientLocale: (_lang: string | undefined, fn: () => Promise<unknown>) => fn()
})); }));
vi.mock('@fastgpt/service/core/plugin/tool/systemToolSchema', () => ({ vi.mock('@fastgpt/service/core/plugin/tool/systemToolSchema', () => ({
...@@ -60,14 +62,16 @@ const createPluginTool = ({ ...@@ -60,14 +62,16 @@ const createPluginTool = ({
pluginId, pluginId,
name, name,
tags = [], tags = [],
hasSecret = false hasSecret = false,
source = 'system'
}: { }: {
pluginId: string; pluginId: string;
name: string; name: string;
tags?: string[]; tags?: string[];
hasSecret?: boolean; hasSecret?: boolean;
source?: string;
}) => ({ }) => ({
source: 'system', source,
isToolset: false, isToolset: false,
hasSecret, hasSecret,
type: 'tool', type: 'tool',
...@@ -85,15 +89,18 @@ const createToolConfig = ({ ...@@ -85,15 +89,18 @@ const createToolConfig = ({
pluginId, pluginId,
pluginOrder, pluginOrder,
tags, tags,
secretsVal secretsVal,
status
}: { }: {
pluginId: string; pluginId: string;
pluginOrder: number; pluginOrder: number;
tags: string[]; tags: string[];
secretsVal?: Record<string, unknown>; secretsVal?: Record<string, unknown>;
status?: PluginStatusType;
}) => ({ }) => ({
pluginId: `systemTool-${pluginId}`, pluginId: `systemTool-${pluginId}`,
pluginOrder, pluginOrder,
status,
secretsVal, secretsVal,
customConfig: { customConfig: {
name: pluginId, name: pluginId,
...@@ -201,6 +208,34 @@ describe('SystemToolRepo.getSystemToolList', () => { ...@@ -201,6 +208,34 @@ describe('SystemToolRepo.getSystemToolList', () => {
); );
expect(mocks.getTool).not.toHaveBeenCalled(); expect(mocks.getTool).not.toHaveBeenCalled();
}); });
it('keeps debug tools visible as normal even when system config is soon offline', async () => {
mocks.listTools.mockResolvedValue([
createPluginTool({
pluginId: 'getTime',
name: 'Get Time',
source: 'debug:tmbId:tmb-1'
})
]);
mocks.findSystemTools.mockResolvedValue([
createToolConfig({
pluginId: 'getTime',
pluginOrder: 1,
tags: [],
status: PluginStatusEnum.SoonOffline
})
]);
const tools = await SystemToolRepo.getInstance().getSystemToolList({
sources: ['system', 'debug:tmbId:tmb-1']
});
expect(tools[0]).toMatchObject({
id: 'systemTool-getTime',
source: 'debug:tmbId:tmb-1',
status: PluginStatusEnum.Normal
});
});
}); });
describe('SystemToolRepo.getSystemToolDetail', () => { describe('SystemToolRepo.getSystemToolDetail', () => {
...@@ -554,6 +589,108 @@ describe('SystemToolRepo.getSystemToolDisplayInfo', () => { ...@@ -554,6 +589,108 @@ describe('SystemToolRepo.getSystemToolDisplayInfo', () => {
expect(mocks.getTool).not.toHaveBeenCalled(); expect(mocks.getTool).not.toHaveBeenCalled();
}); });
it('keeps debug tool display status normal when reading by raw plugin id', async () => {
mocks.findSystemTool.mockResolvedValue(undefined);
mocks.findSystemTools
.mockResolvedValueOnce([
{
pluginId: 'systemTool-weather',
status: PluginStatusEnum.Offline,
currentCost: 2,
systemKeyCost: 1,
customConfig: {
name: 'Configured Weather'
}
}
])
.mockResolvedValueOnce([]);
mocks.listTools.mockResolvedValue([
{
source: 'debug:tmbId:tmb-1',
isToolset: false,
name: { en: 'Weather' },
description: { en: 'Weather intro' },
pluginId: 'weather',
version: '1.0.0',
icon: 'weather.svg',
tags: ['life'],
toolDescription: 'Weather tool',
hasSecret: false
}
]);
const tool = await SystemToolRepo.getInstance().getSystemToolDisplayInfo({
pluginId: 'weather',
source: 'debug:tmbId:tmb-1'
});
expect(tool).toMatchObject({
id: 'weather',
source: 'debug:tmbId:tmb-1',
status: PluginStatusEnum.Normal,
currentCost: 2,
systemKeyCost: 1
});
});
it('keeps debug toolset child display status normal when reading by raw plugin id', async () => {
const childConfig = {
pluginId: 'systemTool-weather/forecast',
status: PluginStatusEnum.Offline,
currentCost: 3,
systemKeyCost: 2,
customConfig: {
toolDescription: 'Configured forecast'
}
};
mocks.findSystemTools.mockResolvedValueOnce([childConfig]).mockResolvedValueOnce([
{
pluginId: 'systemTool-weather',
status: PluginStatusEnum.Normal,
customConfig: {}
},
childConfig
]);
mocks.listTools.mockResolvedValue([
{
source: 'debug:tmbId:tmb-1',
isToolset: true,
name: { en: 'Weather' },
description: { en: 'Weather intro' },
pluginId: 'weather',
version: '1.0.0',
icon: 'weather.svg',
tags: ['life'],
toolDescription: 'Weather tool',
hasSecret: false,
children: [
{
id: 'forecast',
name: { en: 'Forecast' },
description: { en: 'Forecast intro' },
toolDescription: 'Forecast tool',
icon: 'forecast.svg'
}
]
}
]);
const tool = await SystemToolRepo.getInstance().getSystemToolDisplayInfo({
pluginId: 'weather/forecast',
source: 'debug:tmbId:tmb-1'
});
expect(tool).toMatchObject({
id: 'weather/forecast',
source: 'debug:tmbId:tmb-1',
status: PluginStatusEnum.Normal,
currentCost: 3,
systemKeyCost: 2,
toolDescription: 'Configured forecast'
});
});
it('keeps parent toolset display lightweight when list omits child icons', async () => { it('keeps parent toolset display lightweight when list omits child icons', async () => {
mocks.findSystemTool.mockResolvedValue(undefined); mocks.findSystemTool.mockResolvedValue(undefined);
mocks.listTools.mockResolvedValue([ mocks.listTools.mockResolvedValue([
...@@ -672,6 +809,58 @@ describe('SystemToolRepo.getSystemToolDisplayInfo', () => { ...@@ -672,6 +809,58 @@ describe('SystemToolRepo.getSystemToolDisplayInfo', () => {
}); });
}); });
describe('SystemToolRepo.getSystemToolRuntime', () => {
it('does not return configured system secrets for debug source', async () => {
mocks.findSystemTool.mockResolvedValue({
pluginId: 'systemTool-weather',
currentCost: 1,
systemKeyCost: 2,
secretsVal: { apiKey: 'prod-secret' },
customConfig: {}
});
mocks.getTool.mockResolvedValue({
pluginId: 'weather',
version: '1.0.0',
permission: []
});
const tool = await SystemToolRepo.getInstance().getSystemToolRuntime({
pluginId: 'systemTool-weather',
source: 'debug:tmbId:tmb-1'
});
expect(mocks.getTool).toHaveBeenCalledWith({
pluginId: 'weather',
version: undefined,
source: 'debug:tmbId:tmb-1',
fallbackLatestVersion: true
});
expect(tool.secretsVal).toBeUndefined();
});
it('keeps configured system secrets for production source', async () => {
mocks.findSystemTool.mockResolvedValue({
pluginId: 'systemTool-weather',
currentCost: 1,
systemKeyCost: 2,
secretsVal: { apiKey: 'prod-secret' },
customConfig: {}
});
mocks.getTool.mockResolvedValue({
pluginId: 'weather',
version: '1.0.0',
permission: []
});
const tool = await SystemToolRepo.getInstance().getSystemToolRuntime({
pluginId: 'systemTool-weather',
source: 'system'
});
expect(tool.secretsVal).toEqual({ apiKey: 'prod-secret' });
});
});
describe('SystemToolRepo.getVersions', () => { describe('SystemToolRepo.getVersions', () => {
it('returns app version ids and names for workflow tools', async () => { it('returns app version ids and names for workflow tools', async () => {
const sortedAppVersions = [ const sortedAppVersions = [
......
...@@ -3,7 +3,8 @@ import { AppTypeEnum } from '@fastgpt/global/core/app/constants'; ...@@ -3,7 +3,8 @@ import { AppTypeEnum } from '@fastgpt/global/core/app/constants';
const mocks = vi.hoisted(() => ({ const mocks = vi.hoisted(() => ({
findById: vi.fn(), findById: vi.fn(),
getAppVersionById: vi.fn() getAppVersionById: vi.fn(),
getSystemToolDetail: vi.fn()
})); }));
vi.mock('@fastgpt/service/core/app/schema', () => ({ vi.mock('@fastgpt/service/core/app/schema', () => ({
...@@ -19,7 +20,9 @@ vi.mock('@fastgpt/service/core/app/version/controller', () => ({ ...@@ -19,7 +20,9 @@ vi.mock('@fastgpt/service/core/app/version/controller', () => ({
vi.mock('@fastgpt/service/core/app/tool/systemTool/systemTool.repo', () => ({ vi.mock('@fastgpt/service/core/app/tool/systemTool/systemTool.repo', () => ({
SystemToolRepo: { SystemToolRepo: {
getInstance: vi.fn() getInstance: vi.fn(() => ({
getSystemToolDetail: mocks.getSystemToolDetail
}))
} }
})); }));
...@@ -30,6 +33,42 @@ describe('getClientToolPreviewNode', () => { ...@@ -30,6 +33,42 @@ describe('getClientToolPreviewNode', () => {
vi.clearAllMocks(); vi.clearAllMocks();
}); });
it('uses explicit debug source for system tool preview without encoding appId', async () => {
mocks.getSystemToolDetail.mockResolvedValueOnce({
id: 'systemTool-weather',
version: '1.0.0',
status: 1,
source: 'debug:tmbId:tmb-1',
isToolSet: false,
avatar: 'weather.svg',
name: 'Weather',
intro: 'Weather query',
author: 'FastGPT',
tags: [],
toolDescription: 'Weather query',
currentCost: 0,
systemKeyCost: 0,
hasTokenFee: false,
hasSystemSecret: false
});
const result = await getClientToolPreviewNode({
appId: 'systemTool-weather',
versionId: '',
lang: 'en',
source: 'debug:tmbId:tmb-1'
});
expect(mocks.getSystemToolDetail).toHaveBeenCalledWith({
pluginId: 'systemTool-weather',
version: undefined,
lang: 'en',
source: 'debug:tmbId:tmb-1'
});
expect(result.pluginId).toBe('systemTool-weather');
expect(result.source).toBe('debug:tmbId:tmb-1');
});
it('omits runtime schema fields from client preview response', async () => { it('omits runtime schema fields from client preview response', async () => {
mocks.findById.mockReturnValueOnce({ mocks.findById.mockReturnValueOnce({
lean: vi.fn().mockResolvedValue({ lean: vi.fn().mockResolvedValue({
......
...@@ -193,6 +193,86 @@ describe('getClientSystemToolPreviewNode', () => { ...@@ -193,6 +193,86 @@ describe('getClientSystemToolPreviewNode', () => {
expect(result.versionLabel).toBeUndefined(); expect(result.versionLabel).toBeUndefined();
}); });
it('passes explicit debug source without encoding it into plugin id', async () => {
mocks.getSystemToolDetail.mockResolvedValueOnce({
id: 'systemTool-weather',
version: '1.0.0',
status: 1,
source: 'debug:tmbId:tmb-1',
isToolSet: false,
avatar: 'weather.svg',
name: 'Weather',
intro: 'Weather query',
author: 'FastGPT',
tags: [],
toolDescription: 'Weather query',
currentCost: 0,
systemKeyCost: 0,
hasTokenFee: false,
hasSystemSecret: false
});
const result = await getClientSystemToolPreviewNode({
pluginId: 'systemTool-weather',
versionId: '',
lang: 'en',
source: 'debug:tmbId:tmb-1'
});
expect(mocks.getSystemToolDetail).toHaveBeenCalledWith({
pluginId: 'systemTool-weather',
version: undefined,
lang: 'en',
source: 'debug:tmbId:tmb-1'
});
expect(result.pluginId).toBe('systemTool-weather');
expect(result.source).toBe('debug:tmbId:tmb-1');
expect(result.toolConfig?.systemTool).toEqual({
toolId: 'systemTool-weather',
source: 'debug:tmbId:tmb-1'
});
});
it('writes explicit debug source into system toolset config', async () => {
mocks.getSystemToolDetail.mockResolvedValueOnce({
id: 'systemTool-search',
version: '1.0.0',
status: 1,
source: 'debug:tmbId:tmb-1',
isToolSet: true,
avatar: 'search.svg',
name: 'Search',
intro: 'Search tools',
author: 'FastGPT',
tags: [],
toolDescription: 'Search tools',
currentCost: 0,
systemKeyCost: 0,
hasTokenFee: false,
hasSystemSecret: false,
children: [
{
id: 'web',
name: 'Web Search',
description: 'Search web'
}
]
});
const result = await getClientSystemToolPreviewNode({
pluginId: 'systemTool-search',
versionId: '',
lang: 'en',
source: 'debug:tmbId:tmb-1'
});
expect(result.source).toBe('debug:tmbId:tmb-1');
expect(result.toolConfig?.systemToolSet).toMatchObject({
toolId: 'systemTool-search',
source: 'debug:tmbId:tmb-1'
});
});
it('returns plugin module preview for commercial workflow tools', async () => { it('returns plugin module preview for commercial workflow tools', async () => {
mocks.getSystemToolDetail.mockResolvedValueOnce({ mocks.getSystemToolDetail.mockResolvedValueOnce({
id: 'commercial-workflow-tool', id: 'commercial-workflow-tool',
......
...@@ -413,6 +413,56 @@ describe('getAgentRuntimeTools schema loading', () => { ...@@ -413,6 +413,56 @@ describe('getAgentRuntimeTools schema loading', () => {
expect(tools[0].requestSchema.function.parameters).toBe(systemToolInputSchema); expect(tools[0].requestSchema.function.parameters).toBe(systemToolInputSchema);
}); });
it('keeps debug source in selected system tool config', async () => {
getSystemToolDetailMock.mockResolvedValue({
id: 'systemTool-gpjj5s',
name: '热榜工具',
avatar: 'hot-list.png',
intro: '获取热榜信息',
toolDescription: '获取热榜信息',
status: 'active',
source: 'debug:tmbId:tmb-1',
isToolSet: false,
hasSystemSecret: false,
systemSecretStatus: 'none',
currentCost: 0,
systemKeyCost: 0,
hasTokenFee: false,
tags: [],
author: '',
version: '1.0.0',
isLatestVersion: true,
inputSchema: systemToolInputSchema
});
const tools = await getAgentRuntimeTools({
tmbId: 'tmb_1',
tools: [
{
id: 'systemTool-gpjj5s',
source: 'debug:tmbId:tmb-1',
toolConfig: {
systemTool: {
toolId: 'systemTool-gpjj5s',
source: 'debug:tmbId:tmb-1'
}
},
config: {}
}
]
});
expect(getSystemToolDetailMock).toHaveBeenCalledWith({
pluginId: 'systemTool-gpjj5s',
lang: undefined,
source: 'debug:tmbId:tmb-1'
});
expect(tools[0].toolConfig?.systemTool).toEqual({
toolId: 'systemTool-gpjj5s',
source: 'debug:tmbId:tmb-1'
});
});
it('does not rebuild system tool params from node inputs when input schema is missing', async () => { it('does not rebuild system tool params from node inputs when input schema is missing', async () => {
getSystemToolDetailMock.mockResolvedValue({ getSystemToolDetailMock.mockResolvedValue({
id: 'systemTool-gpjj5s', id: 'systemTool-gpjj5s',
......
...@@ -159,6 +159,7 @@ describe('getSystemToolRunTimeNodeFromSystemToolset', () => { ...@@ -159,6 +159,7 @@ describe('getSystemToolRunTimeNodeFromSystemToolset', () => {
const makeToolSetNode = ( const makeToolSetNode = (
overrides: Partial<{ overrides: Partial<{
toolId: string; toolId: string;
source: string;
toolList: { toolId: string; name: string; description: string }[]; toolList: { toolId: string; name: string; description: string }[];
inputs: any[]; inputs: any[];
nodeId: string; nodeId: string;
...@@ -168,6 +169,7 @@ describe('getSystemToolRunTimeNodeFromSystemToolset', () => { ...@@ -168,6 +169,7 @@ describe('getSystemToolRunTimeNodeFromSystemToolset', () => {
toolConfig: { toolConfig: {
systemToolSet: { systemToolSet: {
toolId: overrides.toolId ?? 'systemTool-toolset-1', toolId: overrides.toolId ?? 'systemTool-toolset-1',
source: overrides.source,
toolList: overrides.toolList ?? [] toolList: overrides.toolList ?? []
} }
}, },
...@@ -489,4 +491,29 @@ describe('getSystemToolRunTimeNodeFromSystemToolset', () => { ...@@ -489,4 +491,29 @@ describe('getSystemToolRunTimeNodeFromSystemToolset', () => {
expect(result).toHaveLength(1); expect(result).toHaveLength(1);
expect(result[0].pluginId).toBe('systemTool-toolset-1/child-1'); expect(result[0].pluginId).toBe('systemTool-toolset-1/child-1');
}); });
it('should pass debug source from toolset config to child runtime node', async () => {
const toolSetNode = makeToolSetNode({
source: 'debug:tmbId:tmb-1',
toolList: [{ toolId: 'child-1', name: 'Debug Tool', description: 'Debug Desc' }]
});
mockToolDetail();
const result = await getSystemToolRunTimeNodeFromSystemToolset({
toolSetNode,
lang: 'en'
});
expect(mockGetSystemToolDetail).toHaveBeenCalledWith({
pluginId: 'systemTool-toolset-1',
lang: 'en',
source: 'debug:tmbId:tmb-1',
version: undefined,
fallbackLatestVersion: true
});
expect(result[0].toolConfig?.systemTool).toEqual({
toolId: 'systemTool-toolset-1/child-1',
source: 'debug:tmbId:tmb-1'
});
});
}); });
...@@ -4,13 +4,60 @@ import { ...@@ -4,13 +4,60 @@ import {
type ToolAnswerType, type ToolAnswerType,
type ToolHandlerReturnType type ToolHandlerReturnType
} from '@fastgpt/global/sdk/fastgpt-plugin'; } from '@fastgpt/global/sdk/fastgpt-plugin';
import type { localeType } from '@fastgpt/global/common/i18n/type';
import { parseI18nString } from '@fastgpt/global/common/i18n/utils';
import { AsyncLocalStorage } from 'async_hooks';
export const PLUGIN_BASE_URL = serviceEnv.PLUGIN_BASE_URL ?? ''; export const PLUGIN_BASE_URL = serviceEnv.PLUGIN_BASE_URL ?? '';
export const PLUGIN_TOKEN = serviceEnv.PLUGIN_TOKEN; export const PLUGIN_TOKEN = serviceEnv.PLUGIN_TOKEN;
const PluginClientLocaleContext = new AsyncLocalStorage<localeType | undefined>();
export const withPluginClientLocale = <T>(lang: localeType | undefined, fn: () => Promise<T>) => {
return PluginClientLocaleContext.run(lang, fn);
};
const localizePluginErrorResponse = async (response: Response): Promise<Response> => {
const lang = PluginClientLocaleContext.getStore();
if (response.ok || !lang) return response;
const contentType = response.headers.get('Content-Type') ?? '';
if (!contentType.includes('application/json')) return response;
const payload = await response
.clone()
.json()
.catch(() => undefined);
const reason = payload?.error?.reason;
if (!reason || typeof reason !== 'object' || typeof reason.en !== 'string') return response;
const headers = new Headers(response.headers);
headers.delete('Content-Length');
return new Response(
JSON.stringify({
...payload,
error: {
...payload.error,
message: parseI18nString(reason, lang)
}
}),
{
status: response.status,
statusText: response.statusText,
headers
}
);
};
const localizedFetch: typeof globalThis.fetch = async (input, init) => {
const response = await fetch(input, init);
return localizePluginErrorResponse(response);
};
export const pluginClient = new FastGPTPluginClient({ export const pluginClient = new FastGPTPluginClient({
baseUrl: PLUGIN_BASE_URL, baseUrl: PLUGIN_BASE_URL,
token: PLUGIN_TOKEN token: PLUGIN_TOKEN,
fetch: localizedFetch
}); });
type RunPluginToolStreamParams = { type RunPluginToolStreamParams = {
......
import React from 'react';
import { Box, type BoxProps } from '@chakra-ui/react';
import { useTranslation } from 'next-i18next';
const DebugToolTag = React.memo(function DebugToolTag(props: BoxProps) {
const { t } = useTranslation();
return (
<Box
flexShrink={0}
px={2}
py={0.5}
borderRadius={'6px'}
bg={'rgba(255, 245, 204, 1)'}
color={'rgba(227, 72, 49, 1)'}
border={'1px solid rgba(247, 214, 118, 1)'}
fontSize={'11px'}
fontWeight={'500'}
lineHeight={'16px'}
{...props}
>
{t('app:toolkit_debug_tag')}
</Box>
);
});
export default DebugToolTag;
...@@ -6,6 +6,7 @@ import { useTranslation } from 'next-i18next'; ...@@ -6,6 +6,7 @@ import { useTranslation } from 'next-i18next';
import MyIcon from '../../../common/Icon'; import MyIcon from '../../../common/Icon';
import { parseI18nString } from '@fastgpt/global/common/i18n/utils'; import { parseI18nString } from '@fastgpt/global/common/i18n/utils';
import { PluginStatusEnum, type PluginStatusType } from '@fastgpt/global/core/plugin/type'; import { PluginStatusEnum, type PluginStatusType } from '@fastgpt/global/core/plugin/type';
import DebugToolTag from './DebugToolTag';
export type ToolCardItemType = { export type ToolCardItemType = {
id: string; id: string;
...@@ -23,6 +24,7 @@ export type ToolCardItemType = { ...@@ -23,6 +24,7 @@ export type ToolCardItemType = {
downloadCount?: number; downloadCount?: number;
associatedPluginId?: string; associatedPluginId?: string;
source?: string; source?: string;
isDebug?: boolean;
}; };
/** /**
...@@ -172,7 +174,7 @@ const ToolCard = ({ ...@@ -172,7 +174,7 @@ const ToolCard = ({
}} }}
> >
{/* Update badge in top-right corner */} {/* Update badge in top-right corner */}
{item.update && mode === 'admin' && ( {item.update && mode === 'admin' && !item.isDebug && (
<Flex <Flex
alignItems="center" alignItems="center"
position={'absolute'} position={'absolute'}
...@@ -207,13 +209,20 @@ const ToolCard = ({ ...@@ -207,13 +209,20 @@ const ToolCard = ({
</Flex> </Flex>
)} )}
<HStack> <HStack minW={0}>
<Avatar src={item.icon} borderRadius={'sm'} w={'1.5rem'} /> <Avatar src={item.icon} borderRadius={'sm'} w={'1.5rem'} />
<Box color={'myGray.900'} fontWeight={'medium'}> <Box color={'myGray.900'} fontWeight={'medium'} minW={0} className={'textEllipsis'}>
{parseI18nString(item.name, i18n.language)} {parseI18nString(item.name, i18n.language)}
</Box> </Box>
{item.isDebug && <DebugToolTag />}
{statusLabel && ( {statusLabel && (
<Flex fontSize={'12px'} fontWeight={'medium'} color={statusLabel.color} gap={1}> <Flex
flexShrink={0}
fontSize={'12px'}
fontWeight={'medium'}
color={statusLabel.color}
gap={1}
>
{statusLabel.icon && <MyIcon name={statusLabel.icon as any} w={4} />} {statusLabel.icon && <MyIcon name={statusLabel.icon as any} w={4} />}
{statusLabel.label} {statusLabel.label}
</Flex> </Flex>
......
import { NodeGradients, NodeBorderColors } from '@fastgpt/global/core/workflow/node/constant'; import { NodeGradients, NodeBorderColors } from '@fastgpt/global/core/workflow/node/constant';
import { AppToolSourceEnum } from '@fastgpt/global/core/app/tool/constants'; import { AppToolSourceEnum } from '@fastgpt/global/core/app/tool/constants';
import { FlowNodeTypeEnum } from '@fastgpt/global/core/workflow/node/constant'; import { FlowNodeTypeEnum } from '@fastgpt/global/core/workflow/node/constant';
import { isDebugToolSource } from '@fastgpt/global/core/app/tool/utils';
const getColorSchemaBySource = (source: AppToolSourceEnum) => { const getColorSchemaBySource = (source?: AppToolSourceEnum | string) => {
if (source === AppToolSourceEnum.http || source === AppToolSourceEnum.mcp) { if (source === AppToolSourceEnum.http || source === AppToolSourceEnum.mcp) {
return 'salmon'; return 'salmon';
} }
...@@ -13,6 +14,9 @@ const getColorSchemaBySource = (source: AppToolSourceEnum) => { ...@@ -13,6 +14,9 @@ const getColorSchemaBySource = (source: AppToolSourceEnum) => {
) { ) {
return 'gray'; return 'gray';
} }
if (isDebugToolSource(source)) {
return 'gray';
}
return undefined; return undefined;
}; };
...@@ -21,7 +25,7 @@ export const getGradientByColorSchema = ({ ...@@ -21,7 +25,7 @@ export const getGradientByColorSchema = ({
source source
}: { }: {
colorSchema?: keyof typeof NodeGradients; colorSchema?: keyof typeof NodeGradients;
source: AppToolSourceEnum; source?: AppToolSourceEnum | string;
}): string | undefined => { }): string | undefined => {
const sourceColor = getColorSchemaBySource(source); const sourceColor = getColorSchemaBySource(source);
if (sourceColor) { if (sourceColor) {
...@@ -36,7 +40,7 @@ export const getBorderColorByColorSchema = ({ ...@@ -36,7 +40,7 @@ export const getBorderColorByColorSchema = ({
source source
}: { }: {
colorSchema?: keyof typeof NodeBorderColors; colorSchema?: keyof typeof NodeBorderColors;
source: AppToolSourceEnum; source?: AppToolSourceEnum | string;
}): string | undefined => { }): string | undefined => {
const sourceColor = getColorSchemaBySource(source); const sourceColor = getColorSchemaBySource(source);
if (sourceColor) { if (sourceColor) {
......
import { useToast } from './useToast'; import { useToast } from './useToast';
import { useMutation } from '@tanstack/react-query'; import { useMutation } from '@tanstack/react-query';
import type { UseMutationOptions } from '@tanstack/react-query'; import type { UseMutationOptions } from '@tanstack/react-query';
import { getErrText } from '@fastgpt/global/common/error/utils'; import { getErrText, ToastHandledError } from '@fastgpt/global/common/error/utils';
import { useTranslation } from 'next-i18next'; import { useTranslation } from 'next-i18next';
import { useRequest as ahooksUseRequest } from 'ahooks'; import { useRequest as ahooksUseRequest } from 'ahooks';
...@@ -33,6 +33,7 @@ export const useRequest = <TData, TParams extends any[]>( ...@@ -33,6 +33,7 @@ export const useRequest = <TData, TParams extends any[]>(
...rest, ...rest,
onError: (err, params) => { onError: (err, params) => {
rest?.onError?.(err, params); rest?.onError?.(err, params);
if (err instanceof ToastHandledError) return;
if (errorToast !== '') { if (errorToast !== '') {
const errText = t(getErrText(err, errorToast || '') as any); const errText = t(getErrText(err, errorToast || '') as any);
if (errText) { if (errText) {
......
...@@ -310,6 +310,7 @@ ...@@ -310,6 +310,7 @@
"publish.show_whole_response_tip": "When enabled, the chat page can show the detailed response flow for each module.", "publish.show_whole_response_tip": "When enabled, the chat page can show the detailed response flow for each module.",
"publish_channel": "Publish", "publish_channel": "Publish",
"publish_channel.wecom.empty": "Publish to WeCom bot. Please <a>bind a custom domain</a> and complete domain verification first.", "publish_channel.wecom.empty": "Publish to WeCom bot. Please <a>bind a custom domain</a> and complete domain verification first.",
"publish_remove_debug_tool_tip": "Local debug plugins are present. Remove them before publishing.",
"publish_success": "Publish Successful", "publish_success": "Publish Successful",
"question_guide_tip": "After the conversation, 3 guiding questions will be generated for you.", "question_guide_tip": "After the conversation, 3 guiding questions will be generated for you.",
"raw_params": "original parameters", "raw_params": "original parameters",
...@@ -401,6 +402,17 @@ ...@@ -401,6 +402,17 @@
"toolkit_call_points_label": "Call Points", "toolkit_call_points_label": "Call Points",
"toolkit_config_system_key": "Configure System Key", "toolkit_config_system_key": "Configure System Key",
"toolkit_contribute_resource": "Contribute Resource", "toolkit_contribute_resource": "Contribute Resource",
"toolkit_debug_connection_link": "Debug Link",
"toolkit_debug_copy_link": "Copy connection link",
"toolkit_debug_create_link": "Generate Link",
"toolkit_debug_create_link_tip": "Click Generate Link on the right to view it",
"toolkit_debug_local": "Local Debug",
"toolkit_debug_local_desc": "Paste this link into your local development environment to connect a test plugin in the platform. Test plugins are visible only to the debugger.",
"toolkit_debug_refresh_link": "Refresh Link",
"toolkit_debug_refresh_link_before_copy": "Refresh the connection link before copying",
"toolkit_debug_remote_disabled": "Remote debugging is not enabled",
"toolkit_debug_stop": "Stop Debugging",
"toolkit_debug_tag": "Debug",
"toolkit_hide_tags": "Hide Tags", "toolkit_hide_tags": "Hide Tags",
"toolkit_hide_tags_tip": "Users with the following tags will not see this tool at all", "toolkit_hide_tags_tip": "Users with the following tags will not see this tool at all",
"toolkit_id": "ID", "toolkit_id": "ID",
......
...@@ -186,6 +186,7 @@ ...@@ -186,6 +186,7 @@
"code_error.sandbox_error.agent_sandbox_permission_denied": "The current app is not authorized to use the sandbox/VM. Please contact an administrator to configure it.", "code_error.sandbox_error.agent_sandbox_permission_denied": "The current app is not authorized to use the sandbox/VM. Please contact an administrator to configure it.",
"code_error.sandbox_error.runtime_upgrade_failed": "Virtual machine runtime upgrade failed. Please try again.", "code_error.sandbox_error.runtime_upgrade_failed": "Virtual machine runtime upgrade failed. Please try again.",
"code_error.system_error.community_version_num_limit": "Exceeded Open Source Version Limit, Please Upgrade to Commercial Version: https://fastgpt.io", "code_error.system_error.community_version_num_limit": "Exceeded Open Source Version Limit, Please Upgrade to Commercial Version: https://fastgpt.io",
"code_error.system_error.commercial_feature": "Commercial Edition exclusive feature",
"code_error.system_error.license_app_amount_limit": "Exceed the maximum number of applications in the system", "code_error.system_error.license_app_amount_limit": "Exceed the maximum number of applications in the system",
"code_error.system_error.license_dataset_amount_limit": "Exceed the maximum number of knowledge bases in the system", "code_error.system_error.license_dataset_amount_limit": "Exceed the maximum number of knowledge bases in the system",
"code_error.system_error.license_user_amount_limit": "Exceed the maximum number of users in the system", "code_error.system_error.license_user_amount_limit": "Exceed the maximum number of users in the system",
......
...@@ -310,6 +310,7 @@ ...@@ -310,6 +310,7 @@
"publish.show_whole_response_tip": "开启后,聊天页面可查看每个模块的详细响应流程", "publish.show_whole_response_tip": "开启后,聊天页面可查看每个模块的详细响应流程",
"publish_channel": "发布渠道", "publish_channel": "发布渠道",
"publish_channel.wecom.empty": "发布到企业微信机器人,请先 <a>绑定自定义域名</a>,并且通过域名校验。", "publish_channel.wecom.empty": "发布到企业微信机器人,请先 <a>绑定自定义域名</a>,并且通过域名校验。",
"publish_remove_debug_tool_tip": "存在本地调试插件,请移除后再发布",
"publish_success": "发布成功", "publish_success": "发布成功",
"question_guide_tip": "对话结束后,会为你生成 3 个引导性问题。", "question_guide_tip": "对话结束后,会为你生成 3 个引导性问题。",
"raw_params": "原始参数", "raw_params": "原始参数",
...@@ -401,6 +402,17 @@ ...@@ -401,6 +402,17 @@
"toolkit_call_points_label": "调用积分", "toolkit_call_points_label": "调用积分",
"toolkit_config_system_key": "是否配置系统密钥", "toolkit_config_system_key": "是否配置系统密钥",
"toolkit_contribute_resource": "贡献插件", "toolkit_contribute_resource": "贡献插件",
"toolkit_debug_connection_link": "调试链接",
"toolkit_debug_copy_link": "复制连接链接",
"toolkit_debug_create_link": "生成链接",
"toolkit_debug_create_link_tip": "点击右边“生成链接”查看",
"toolkit_debug_local": "本地调试",
"toolkit_debug_local_desc": "将该链接粘贴到本地开发环境,即可在平台内接入测试插件。测试插件仅对调试者本人可见。",
"toolkit_debug_refresh_link": "刷新链接",
"toolkit_debug_refresh_link_before_copy": "请刷新连接链接后复制",
"toolkit_debug_remote_disabled": "远程调试未启用",
"toolkit_debug_stop": "结束调试",
"toolkit_debug_tag": "调试",
"toolkit_hide_tags": "隐藏标签", "toolkit_hide_tags": "隐藏标签",
"toolkit_hide_tags_tip": "拥有以下标签的用户将完全看不到此工具", "toolkit_hide_tags_tip": "拥有以下标签的用户将完全看不到此工具",
"toolkit_id": "ID", "toolkit_id": "ID",
......
...@@ -186,6 +186,7 @@ ...@@ -186,6 +186,7 @@
"code_error.sandbox_error.agent_sandbox_permission_denied": "当前应用无权使用虚拟机,请联系管理员配置。", "code_error.sandbox_error.agent_sandbox_permission_denied": "当前应用无权使用虚拟机,请联系管理员配置。",
"code_error.sandbox_error.runtime_upgrade_failed": "虚拟机运行环境升级失败,请重新尝试。", "code_error.sandbox_error.runtime_upgrade_failed": "虚拟机运行环境升级失败,请重新尝试。",
"code_error.system_error.community_version_num_limit": "超出社区版数量限制,请升级商业版: https://fastgpt.in", "code_error.system_error.community_version_num_limit": "超出社区版数量限制,请升级商业版: https://fastgpt.in",
"code_error.system_error.commercial_feature": "商业版专属功能",
"code_error.system_error.license_app_amount_limit": "超出系统最大应用数量", "code_error.system_error.license_app_amount_limit": "超出系统最大应用数量",
"code_error.system_error.license_dataset_amount_limit": "超出系统最大知识库数量", "code_error.system_error.license_dataset_amount_limit": "超出系统最大知识库数量",
"code_error.system_error.license_user_amount_limit": "超出系统最大用户数量", "code_error.system_error.license_user_amount_limit": "超出系统最大用户数量",
......
...@@ -302,6 +302,7 @@ ...@@ -302,6 +302,7 @@
"publish.show_whole_response_tip": "開啟後,聊天頁面可查看每個模組的詳細回應流程", "publish.show_whole_response_tip": "開啟後,聊天頁面可查看每個模組的詳細回應流程",
"publish_channel": "發布通道", "publish_channel": "發布通道",
"publish_channel.wecom.empty": "發布到企業微信機器人,請先 <a>綁定自定義域名</a>,並且通過域名校驗。", "publish_channel.wecom.empty": "發布到企業微信機器人,請先 <a>綁定自定義域名</a>,並且通過域名校驗。",
"publish_remove_debug_tool_tip": "存在本地調試插件,請移除後再發布",
"publish_success": "發布成功", "publish_success": "發布成功",
"question_guide_tip": "對話結束後,會為你產生 3 個引導性問題。", "question_guide_tip": "對話結束後,會為你產生 3 個引導性問題。",
"raw_params": "原始參數", "raw_params": "原始參數",
...@@ -391,6 +392,17 @@ ...@@ -391,6 +392,17 @@
"toolkit_call_points_label": "調用積分", "toolkit_call_points_label": "調用積分",
"toolkit_config_system_key": "是否配置系統密鑰", "toolkit_config_system_key": "是否配置系統密鑰",
"toolkit_contribute_resource": "貢獻資源", "toolkit_contribute_resource": "貢獻資源",
"toolkit_debug_connection_link": "調試連結",
"toolkit_debug_copy_link": "複製連接連結",
"toolkit_debug_create_link": "生成連結",
"toolkit_debug_create_link_tip": "點擊右邊「生成連結」查看",
"toolkit_debug_local": "本地調試",
"toolkit_debug_local_desc": "將該連結貼到本地開發環境,即可在平台內接入測試插件。測試插件僅對調試者本人可見。",
"toolkit_debug_refresh_link": "刷新連結",
"toolkit_debug_refresh_link_before_copy": "請刷新連接連結後複製",
"toolkit_debug_remote_disabled": "遠程調試未啟用",
"toolkit_debug_stop": "結束調試",
"toolkit_debug_tag": "調試",
"toolkit_hide_tags": "隱藏標籤", "toolkit_hide_tags": "隱藏標籤",
"toolkit_hide_tags_tip": "擁有以下標籤的使用者將完全看不到此工具", "toolkit_hide_tags_tip": "擁有以下標籤的使用者將完全看不到此工具",
"toolkit_id": "ID", "toolkit_id": "ID",
......
...@@ -184,6 +184,7 @@ ...@@ -184,6 +184,7 @@
"code_error.sandbox_error.agent_sandbox_permission_denied": "當前應用無權使用虛擬機,請聯絡管理員配置。", "code_error.sandbox_error.agent_sandbox_permission_denied": "當前應用無權使用虛擬機,請聯絡管理員配置。",
"code_error.sandbox_error.runtime_upgrade_failed": "虛擬機運行環境升級失敗,請重新嘗試。", "code_error.sandbox_error.runtime_upgrade_failed": "虛擬機運行環境升級失敗,請重新嘗試。",
"code_error.system_error.community_version_num_limit": "超出開源版數量限制,請升級商業版:https://fastgpt.io", "code_error.system_error.community_version_num_limit": "超出開源版數量限制,請升級商業版:https://fastgpt.io",
"code_error.system_error.commercial_feature": "商業版專屬功能",
"code_error.system_error.license_app_amount_limit": "超出系統最大應用數量", "code_error.system_error.license_app_amount_limit": "超出系統最大應用數量",
"code_error.system_error.license_dataset_amount_limit": "超出系統最大知識庫數量", "code_error.system_error.license_dataset_amount_limit": "超出系統最大知識庫數量",
"code_error.system_error.license_user_amount_limit": "超出系統最大用戶數量", "code_error.system_error.license_user_amount_limit": "超出系統最大用戶數量",
......
Subproject commit 7eac10c397a78a1aae5bfc860dd5c3d86c33626d Subproject commit 49e4fe24b9a9b5f9b0d4373c7c4c9a867df653d3
...@@ -303,6 +303,8 @@ export function agentForm2AppWorkflow( ...@@ -303,6 +303,8 @@ export function agentForm2AppWorkflow(
value: data.selectedTools.map((tool) => { value: data.selectedTools.map((tool) => {
return { return {
id: tool.pluginId, id: tool.pluginId,
source: tool.source,
toolConfig: tool.toolConfig,
config: tool.inputs.reduce( config: tool.inputs.reduce(
(acc, input) => { (acc, input) => {
......
...@@ -18,6 +18,8 @@ import { PluginStatusEnum, PluginStatusMap } from '@fastgpt/global/core/plugin/t ...@@ -18,6 +18,8 @@ import { PluginStatusEnum, PluginStatusMap } from '@fastgpt/global/core/plugin/t
import MyTag from '@fastgpt/web/components/common/Tag/index'; import MyTag from '@fastgpt/web/components/common/Tag/index';
import MyIconButton from '@fastgpt/web/components/common/Icon/button'; import MyIconButton from '@fastgpt/web/components/common/Icon/button';
import type { LLMModelItemType } from '@fastgpt/global/core/ai/model.schema'; import type { LLMModelItemType } from '@fastgpt/global/core/ai/model.schema';
import { isDebugToolSource } from '@fastgpt/global/core/app/tool/utils';
import DebugToolTag from '@fastgpt/web/components/core/plugin/tool/DebugToolTag';
const ToolSelect = ({ const ToolSelect = ({
topAgentSelectedTools, topAgentSelectedTools,
...@@ -81,6 +83,7 @@ const ToolSelect = ({ ...@@ -81,6 +83,7 @@ const ToolSelect = ({
const hasFormInput = const hasFormInput =
item.configStatus === 'configured' || item.configStatus === 'waitingForConfig'; item.configStatus === 'configured' || item.configStatus === 'waitingForConfig';
const isUnconfigured = item.configStatus === 'waitingForConfig'; const isUnconfigured = item.configStatus === 'waitingForConfig';
const isDebugTool = isDebugToolSource(item.source);
return ( return (
<MyTooltip key={item.id} label={item.intro}> <MyTooltip key={item.id} label={item.intro}>
...@@ -142,6 +145,7 @@ const ToolSelect = ({ ...@@ -142,6 +145,7 @@ const ToolSelect = ({
{t('app:wait_for_config')} {t('app:wait_for_config')}
</MyTag> </MyTag>
)} )}
{isDebugTool && <DebugToolTag className="unHoverStyle" />}
{/* Edit icon */} {/* Edit icon */}
{hasFormInput && !toolError && ( {hasFormInput && !toolError && (
<MyIconButton <MyIconButton
...@@ -152,7 +156,7 @@ const ToolSelect = ({ ...@@ -152,7 +156,7 @@ const ToolSelect = ({
/> />
)} )}
{/* Delete icon */} {/* Delete icon */}
<Box className="hoverStyle" display={['flex', 'none']}> <Box className="hoverStyle" display={['flex', 'none']} ml={0.5}>
<MyIconButton <MyIconButton
icon="delete" icon="delete"
hoverBg="red.50" hoverBg="red.50"
......
...@@ -44,6 +44,8 @@ import { ...@@ -44,6 +44,8 @@ import {
getToolConfigStatus, getToolConfigStatus,
validateToolConfiguration validateToolConfiguration
} from '@fastgpt/global/core/app/formEdit/utils'; } from '@fastgpt/global/core/app/formEdit/utils';
import { isDebugToolSource } from '@fastgpt/global/core/app/tool/utils';
import DebugToolTag from '@fastgpt/web/components/core/plugin/tool/DebugToolTag';
type Props = { type Props = {
topAgentSelectedTools?: SelectedToolItemType[]; topAgentSelectedTools?: SelectedToolItemType[];
...@@ -73,6 +75,7 @@ const ToolSelectModal = ({ onClose, ...props }: Props & { onClose: () => void }) ...@@ -73,6 +75,7 @@ const ToolSelectModal = ({ onClose, ...props }: Props & { onClose: () => void })
const [templateType, setTemplateType] = useState(TemplateTypeEnum.systemTools); const [templateType, setTemplateType] = useState(TemplateTypeEnum.systemTools);
const [parentId, setParentId] = useState<ParentIdType>(''); const [parentId, setParentId] = useState<ParentIdType>('');
const [parentSource, setParentSource] = useState<string>();
const [searchKey, setSearchKey] = useState(''); const [searchKey, setSearchKey] = useState('');
const [selectedTagIds, setSelectedTagIds] = useState<string[]>([]); const [selectedTagIds, setSelectedTagIds] = useState<string[]>([]);
...@@ -84,14 +87,20 @@ const ToolSelectModal = ({ onClose, ...props }: Props & { onClose: () => void }) ...@@ -84,14 +87,20 @@ const ToolSelectModal = ({ onClose, ...props }: Props & { onClose: () => void })
async ({ async ({
type = templateType, type = templateType,
parentId = '', parentId = '',
searchVal = searchKey searchVal = searchKey,
source
}: { }: {
type?: TemplateTypeEnum; type?: TemplateTypeEnum;
parentId?: ParentIdType; parentId?: ParentIdType;
searchVal?: string; searchVal?: string;
source?: string;
}) => { }) => {
if (type === TemplateTypeEnum.systemTools) { if (type === TemplateTypeEnum.systemTools) {
return getAppToolTemplates({ parentId, searchKey: searchVal }); return getAppToolTemplates({
parentId,
searchKey: searchVal,
source: parentId ? source : undefined
});
} else if (type === TemplateTypeEnum.myTools) { } else if (type === TemplateTypeEnum.myTools) {
return getTeamAppTemplates({ return getTeamAppTemplates({
parentId, parentId,
...@@ -112,9 +121,10 @@ const ToolSelectModal = ({ onClose, ...props }: Props & { onClose: () => void }) ...@@ -112,9 +121,10 @@ const ToolSelectModal = ({ onClose, ...props }: Props & { onClose: () => void })
} }
}, },
{ {
onSuccess(_, [{ type = templateType, parentId = '' }]) { onSuccess(_, [{ type = templateType, parentId = '', source }]) {
setTemplateType(type); setTemplateType(type);
setParentId(parentId); setParentId(parentId);
setParentSource(parentId ? (source ?? parentSource) : undefined);
}, },
refreshDeps: [templateType, searchKey, parentId] refreshDeps: [templateType, searchKey, parentId]
} }
...@@ -133,12 +143,12 @@ const ToolSelectModal = ({ onClose, ...props }: Props & { onClose: () => void }) ...@@ -133,12 +143,12 @@ const ToolSelectModal = ({ onClose, ...props }: Props & { onClose: () => void })
const { data: paths = [] } = useRequest( const { data: paths = [] } = useRequest(
() => { () => {
if (templateType === TemplateTypeEnum.systemTools) if (templateType === TemplateTypeEnum.systemTools)
return getAppToolPaths({ sourceId: parentId, type: 'current' }); return getAppToolPaths({ sourceId: parentId, source: parentSource, type: 'current' });
return getAppFolderPath({ sourceId: parentId, type: 'current' }); return getAppFolderPath({ sourceId: parentId, type: 'current' });
}, },
{ {
manual: false, manual: false,
refreshDeps: [parentId] refreshDeps: [parentId, parentSource]
} }
); );
...@@ -147,16 +157,18 @@ const ToolSelectModal = ({ onClose, ...props }: Props & { onClose: () => void }) ...@@ -147,16 +157,18 @@ const ToolSelectModal = ({ onClose, ...props }: Props & { onClose: () => void })
}); });
const onUpdateParentId = useCallback( const onUpdateParentId = useCallback(
(parentId: ParentIdType) => { (parentId: ParentIdType, source?: string) => {
if (document.activeElement instanceof HTMLElement) { if (document.activeElement instanceof HTMLElement) {
document.activeElement.blur(); document.activeElement.blur();
} }
const nextParentSource = parentId ? (source ?? parentSource) : undefined;
loadTemplates({ loadTemplates({
parentId parentId,
source: nextParentSource
}); });
}, },
[loadTemplates] [loadTemplates, parentSource]
); );
useRequest(() => loadTemplates({ searchVal: searchKey }), { useRequest(() => loadTemplates({ searchVal: searchKey }), {
...@@ -276,7 +288,7 @@ const RenderList = React.memo(function RenderList({ ...@@ -276,7 +288,7 @@ const RenderList = React.memo(function RenderList({
parentId: ParentIdType; parentId: ParentIdType;
searchKey: string; searchKey: string;
selectedTagIds: string[]; selectedTagIds: string[];
setParentId: (parentId: ParentIdType) => any; setParentId: (parentId: ParentIdType, source?: string) => any;
}) { }) {
const { i18n } = useTranslation(); const { i18n } = useTranslation();
const { t } = useSafeTranslation(); const { t } = useSafeTranslation();
...@@ -292,7 +304,11 @@ const RenderList = React.memo(function RenderList({ ...@@ -292,7 +304,11 @@ const RenderList = React.memo(function RenderList({
const { runAsync: onClickAdd, loading: isLoading } = useRequest( const { runAsync: onClickAdd, loading: isLoading } = useRequest(
async (template: NodeTemplateListItemType) => { async (template: NodeTemplateListItemType) => {
const res = await getClientToolPreviewNode({ appId: template.id, versionId: '' }); const res = await getClientToolPreviewNode({
appId: template.id,
versionId: '',
source: template.source
});
const isToolSetTemplate = template.flowNodeType === FlowNodeTypeEnum.toolSet; const isToolSetTemplate = template.flowNodeType === FlowNodeTypeEnum.toolSet;
if (!isToolSetTemplate) { if (!isToolSetTemplate) {
...@@ -350,6 +366,7 @@ const RenderList = React.memo(function RenderList({ ...@@ -350,6 +366,7 @@ const RenderList = React.memo(function RenderList({
const intro = const intro =
t(parseI18nString(template.intro || '', i18n.language)) || t(parseI18nString(template.intro || '', i18n.language)) ||
t('common:core.workflow.Not intro'); t('common:core.workflow.Not intro');
const isDebugTool = isDebugToolSource(template.source);
return ( return (
<MyTooltip <MyTooltip
...@@ -373,6 +390,7 @@ const RenderList = React.memo(function RenderList({ ...@@ -373,6 +390,7 @@ const RenderList = React.memo(function RenderList({
> >
{name} {name}
</Box> </Box>
{isDebugTool && <DebugToolTag />}
{isSystemTool && ( {isSystemTool && (
<Box color={'myGray.500'}> <Box color={'myGray.500'}>
By {template.author || feConfigs?.systemTitle} By {template.author || feConfigs?.systemTitle}
...@@ -411,6 +429,7 @@ const RenderList = React.memo(function RenderList({ ...@@ -411,6 +429,7 @@ const RenderList = React.memo(function RenderList({
flexShrink={0} flexShrink={0}
/> />
<Box minW={0}> <Box minW={0}>
<Flex alignItems={'center'} gap={2} minW={0}>
<Box <Box
color={'myGray.900'} color={'myGray.900'}
fontWeight={'500'} fontWeight={'500'}
...@@ -419,6 +438,8 @@ const RenderList = React.memo(function RenderList({ ...@@ -419,6 +438,8 @@ const RenderList = React.memo(function RenderList({
> >
{name} {name}
</Box> </Box>
{isDebugTool && <DebugToolTag />}
</Flex>
</Box> </Box>
<Flex gap={2} minW={0} justifySelf={'end'} alignItems={'center'}> <Flex gap={2} minW={0} justifySelf={'end'} alignItems={'center'}>
{selected ? ( {selected ? (
...@@ -444,7 +465,7 @@ const RenderList = React.memo(function RenderList({ ...@@ -444,7 +465,7 @@ const RenderList = React.memo(function RenderList({
isLoading={isLoading} isLoading={isLoading}
leftIcon={<MyIcon name={'common/arrowRight'} w={'14px'} />} leftIcon={<MyIcon name={'common/arrowRight'} w={'14px'} />}
iconSpacing={1} iconSpacing={1}
onClick={() => setParentId(template.id)} onClick={() => setParentId(template.id, template.source)}
fontSize={'mini'} fontSize={'mini'}
fontWeight={'500'} fontWeight={'500'}
> >
...@@ -472,7 +493,7 @@ const RenderList = React.memo(function RenderList({ ...@@ -472,7 +493,7 @@ const RenderList = React.memo(function RenderList({
isLoading={isLoading} isLoading={isLoading}
leftIcon={<MyIcon name={'common/arrowRight'} w={'14px'} />} leftIcon={<MyIcon name={'common/arrowRight'} w={'14px'} />}
iconSpacing={1} iconSpacing={1}
onClick={() => setParentId(template.id)} onClick={() => setParentId(template.id, template.source)}
fontSize={'mini'} fontSize={'mini'}
fontWeight={'500'} fontWeight={'500'}
> >
......
...@@ -171,6 +171,7 @@ export const appWorkflow2Form = ({ ...@@ -171,6 +171,7 @@ export const appWorkflow2Form = ({
defaultAppForm.selectedTools.push({ defaultAppForm.selectedTools.push({
id: node.nodeId, id: node.nodeId,
pluginId: node.pluginId, pluginId: node.pluginId,
source: node.source,
isFolder: node.isFolder, isFolder: node.isFolder,
name: node.name, name: node.name,
avatar: node.avatar, avatar: node.avatar,
...@@ -616,6 +617,7 @@ export function form2AppWorkflow( ...@@ -616,6 +617,7 @@ export function form2AppWorkflow(
nodeId, nodeId,
id: tool.id, id: tool.id,
pluginId: tool.pluginId, pluginId: tool.pluginId,
source: tool.source,
name: tool.name, name: tool.name,
intro: tool.intro, intro: tool.intro,
toolDescription: tool.toolDescription, toolDescription: tool.toolDescription,
......
...@@ -137,6 +137,7 @@ const ConfigToolModal = ({ ...@@ -137,6 +137,7 @@ const ConfigToolModal = ({
courseUrl={configTool?.courseUrl} courseUrl={configTool?.courseUrl}
readmeUrl={configTool?.readmeUrl} readmeUrl={configTool?.readmeUrl}
parentId={configTool?.pluginId} parentId={configTool?.pluginId}
source={configTool?.source}
onClose={setFalseSecretModal} onClose={setFalseSecretModal}
onSubmit={(data) => { onSubmit={(data) => {
onChange(data); onChange(data);
......
...@@ -24,6 +24,7 @@ const NodeTemplatesModal = ({ isOpen, onClose }: ModuleTemplateListProps) => { ...@@ -24,6 +24,7 @@ const NodeTemplatesModal = ({ isOpen, onClose }: ModuleTemplateListProps) => {
const { const {
templateType, templateType,
parentId, parentId,
parentSource,
searchKey, searchKey,
setSearchKey, setSearchKey,
templatesIsLoading, templatesIsLoading,
...@@ -86,6 +87,7 @@ const NodeTemplatesModal = ({ isOpen, onClose }: ModuleTemplateListProps) => { ...@@ -86,6 +87,7 @@ const NodeTemplatesModal = ({ isOpen, onClose }: ModuleTemplateListProps) => {
templateType={templateType} templateType={templateType}
onUpdateTemplateType={onUpdateTemplateType} onUpdateTemplateType={onUpdateTemplateType}
parentId={parentId} parentId={parentId}
parentSource={parentSource}
searchKey={searchKey} searchKey={searchKey}
setSearchKey={setSearchKey} setSearchKey={setSearchKey}
onUpdateParentId={onUpdateParentId} onUpdateParentId={onUpdateParentId}
......
...@@ -26,6 +26,7 @@ const NodeTemplatesPopover = () => { ...@@ -26,6 +26,7 @@ const NodeTemplatesPopover = () => {
const { const {
templateType, templateType,
parentId, parentId,
parentSource,
searchKey, searchKey,
setSearchKey, setSearchKey,
templatesIsLoading, templatesIsLoading,
...@@ -123,6 +124,7 @@ const NodeTemplatesPopover = () => { ...@@ -123,6 +124,7 @@ const NodeTemplatesPopover = () => {
templateType={templateType} templateType={templateType}
onUpdateTemplateType={onUpdateTemplateType} onUpdateTemplateType={onUpdateTemplateType}
parentId={parentId} parentId={parentId}
parentSource={parentSource}
onUpdateParentId={onUpdateParentId} onUpdateParentId={onUpdateParentId}
searchKey={searchKey} searchKey={searchKey}
setSearchKey={setSearchKey} setSearchKey={setSearchKey}
......
...@@ -26,10 +26,11 @@ export type NodeTemplateListHeaderProps = { ...@@ -26,10 +26,11 @@ export type NodeTemplateListHeaderProps = {
isPopover?: boolean; isPopover?: boolean;
templateType: TemplateTypeEnum; templateType: TemplateTypeEnum;
parentId: ParentIdType; parentId: ParentIdType;
parentSource?: string;
searchKey: string; searchKey: string;
setSearchKey: Dispatch<SetStateAction<string>>; setSearchKey: Dispatch<SetStateAction<string>>;
onUpdateTemplateType: (type: TemplateTypeEnum) => void; onUpdateTemplateType: (type: TemplateTypeEnum) => void;
onUpdateParentId: (parentId: ParentIdType) => void; onUpdateParentId: (parentId: ParentIdType, source?: string) => void;
selectedTagIds: string[]; selectedTagIds: string[];
setSelectedTagIds: (e: string[]) => any; setSelectedTagIds: (e: string[]) => any;
...@@ -41,6 +42,7 @@ const NodeTemplateListHeader = ({ ...@@ -41,6 +42,7 @@ const NodeTemplateListHeader = ({
isPopover = false, isPopover = false,
templateType, templateType,
parentId, parentId,
parentSource,
searchKey, searchKey,
setSearchKey, setSearchKey,
onUpdateTemplateType, onUpdateTemplateType,
...@@ -57,12 +59,12 @@ const NodeTemplateListHeader = ({ ...@@ -57,12 +59,12 @@ const NodeTemplateListHeader = ({
const { data: paths = [] } = useRequest( const { data: paths = [] } = useRequest(
() => { () => {
if (templateType === TemplateTypeEnum.systemTools) if (templateType === TemplateTypeEnum.systemTools)
return getAppToolPaths({ sourceId: parentId, type: 'current' }); return getAppToolPaths({ sourceId: parentId, source: parentSource, type: 'current' });
return getAppFolderPath({ sourceId: parentId, type: 'current' }); return getAppFolderPath({ sourceId: parentId, type: 'current' });
}, },
{ {
manual: false, manual: false,
refreshDeps: [parentId] refreshDeps: [parentId, parentSource]
} }
); );
......
...@@ -48,13 +48,15 @@ import { useToast } from '@fastgpt/web/hooks/useToast'; ...@@ -48,13 +48,15 @@ import { useToast } from '@fastgpt/web/hooks/useToast';
import { parseI18nString } from '@fastgpt/global/common/i18n/utils'; import { parseI18nString } from '@fastgpt/global/common/i18n/utils';
import { useSystemStore } from '@/web/common/system/useSystemStore'; import { useSystemStore } from '@/web/common/system/useSystemStore';
import { WorkflowModalContext } from '../../../context/workflowModalContext'; import { WorkflowModalContext } from '../../../context/workflowModalContext';
import { isDebugToolSource } from '@fastgpt/global/core/app/tool/utils';
import DebugToolTag from '@fastgpt/web/components/core/plugin/tool/DebugToolTag';
export type TemplateListProps = { export type TemplateListProps = {
onAddNode: ({ newNodes }: { newNodes: Node<FlowNodeItemType>[] }) => void; onAddNode: ({ newNodes }: { newNodes: Node<FlowNodeItemType>[] }) => void;
isPopover?: boolean; isPopover?: boolean;
templates: NodeTemplateListItemType[]; templates: NodeTemplateListItemType[];
templateType: TemplateTypeEnum; templateType: TemplateTypeEnum;
onUpdateParentId: (parentId: string) => void; onUpdateParentId: (parentId: string, source?: string) => void;
}; };
const NodeTemplateListItem = ({ const NodeTemplateListItem = ({
...@@ -71,17 +73,24 @@ const NodeTemplateListItem = ({ ...@@ -71,17 +73,24 @@ const NodeTemplateListItem = ({
position: { x: number; y: number }; position: { x: number; y: number };
}) => void; }) => void;
isPopover?: boolean; isPopover?: boolean;
onUpdateParentId: (parentId: string) => void; onUpdateParentId: (parentId: string, source?: string) => void;
}) => { }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const { feConfigs } = useSystemStore(); const { feConfigs } = useSystemStore();
const { screenToFlowPosition } = useReactFlow(); const { screenToFlowPosition } = useReactFlow();
const handleParams = useContextSelector(WorkflowModalContext, (v) => v.handleParams); const handleParams = useContextSelector(WorkflowModalContext, (v) => v.handleParams);
const isToolHandle = handleParams?.handleId === 'selectedTools';
const isSystemTool = templateType === TemplateTypeEnum.systemTools; const isSystemTool = templateType === TemplateTypeEnum.systemTools;
const isSystemToolSet = isSystemTool && template.flowNodeType === FlowNodeTypeEnum.toolSet; const isSystemToolSet = isSystemTool && template.flowNodeType === FlowNodeTypeEnum.toolSet;
const isToolSelector = handleParams?.handleId === NodeOutputKeyEnum.selectedTools;
// 系统工具集只有在工具调用的工具选择器里才允许直接创建节点。
const allowDirectAddSystemToolSet = isSystemToolSet && isToolSelector;
const canDragCreateNode =
!isPopover &&
(!template.isFolder || template.flowNodeType === FlowNodeTypeEnum.toolSet) &&
(!isSystemToolSet || allowDirectAddSystemToolSet);
const showExpandArrow = template.isFolder || isSystemToolSet; const showExpandArrow = template.isFolder || isSystemToolSet;
const isDebugTool = isDebugToolSource(template.source);
return ( return (
<MyTooltip <MyTooltip
...@@ -95,9 +104,12 @@ const NodeTemplateListItem = ({ ...@@ -95,9 +104,12 @@ const NodeTemplateListItem = ({
objectFit={'contain'} objectFit={'contain'}
borderRadius={'sm'} borderRadius={'sm'}
/> />
<Box fontWeight={'bold'} ml={3} color={'myGray.900'} flex={'1'}> <Flex alignItems={'center'} gap={2} ml={3} flex={'1'} minW={0}>
<Box fontWeight={'bold'} color={'myGray.900'} className="textEllipsis">
{template.name} {template.name}
</Box> </Box>
{isDebugTool && <DebugToolTag />}
</Flex>
{isSystemTool && ( {isSystemTool && (
<Box color={'myGray.500'}>By {template.author || feConfigs?.systemTitle}</Box> <Box color={'myGray.500'}>By {template.author || feConfigs?.systemTitle}</Box>
)} )}
...@@ -132,10 +144,9 @@ const NodeTemplateListItem = ({ ...@@ -132,10 +144,9 @@ const NodeTemplateListItem = ({
whiteSpace={'nowrap'} whiteSpace={'nowrap'}
overflow={'hidden'} overflow={'hidden'}
textOverflow={'ellipsis'} textOverflow={'ellipsis'}
draggable={ draggable={canDragCreateNode}
!isPopover && (!template.isFolder || template.flowNodeType === FlowNodeTypeEnum.toolSet)
}
onDragEnd={(e) => { onDragEnd={(e) => {
if (!canDragCreateNode) return;
if (e.clientX < sliderWidth) return; if (e.clientX < sliderWidth) return;
const nodePosition = screenToFlowPosition({ x: e.clientX, y: e.clientY }); const nodePosition = screenToFlowPosition({ x: e.clientX, y: e.clientY });
handleAddNode({ handleAddNode({
...@@ -144,9 +155,8 @@ const NodeTemplateListItem = ({ ...@@ -144,9 +155,8 @@ const NodeTemplateListItem = ({
}); });
}} }}
onClick={() => { onClick={() => {
// Not tool handle, cannot add toolset if (isSystemToolSet && !allowDirectAddSystemToolSet) {
if (!isToolHandle && template.flowNodeType === FlowNodeTypeEnum.toolSet) { onUpdateParentId(template.id, template.source);
onUpdateParentId(template.id);
return; return;
} }
// Team folder // Team folder
...@@ -169,7 +179,8 @@ const NodeTemplateListItem = ({ ...@@ -169,7 +179,8 @@ const NodeTemplateListItem = ({
borderRadius={'sm'} borderRadius={'sm'}
flexShrink={0} flexShrink={0}
/> />
<Box flex={'1 0 0'} ml={3}> <Box flex={'1 0 0'} ml={3} minW={0}>
<Flex alignItems={'center'} gap={2} minW={0}>
<Box <Box
color={'myGray.900'} color={'myGray.900'}
fontWeight={'500'} fontWeight={'500'}
...@@ -178,6 +189,8 @@ const NodeTemplateListItem = ({ ...@@ -178,6 +189,8 @@ const NodeTemplateListItem = ({
> >
{t(template.name as any)} {t(template.name as any)}
</Box> </Box>
{isDebugTool && <DebugToolTag />}
</Flex>
</Box> </Box>
{showExpandArrow && ( {showExpandArrow && (
<Box <Box
...@@ -192,7 +205,7 @@ const NodeTemplateListItem = ({ ...@@ -192,7 +205,7 @@ const NodeTemplateListItem = ({
display="none" display="none"
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
onUpdateParentId(template.id); onUpdateParentId(template.id, template.source);
}} }}
> >
<MyIcon name="common/arrowRight" w={isPopover ? '16px' : '20px'} /> <MyIcon name="common/arrowRight" w={isPopover ? '16px' : '20px'} />
...@@ -247,7 +260,8 @@ const NodeTemplateList = ({ ...@@ -247,7 +260,8 @@ const NodeTemplateList = ({
if (shouldLoadPreviewNode) { if (shouldLoadPreviewNode) {
const node = await getClientToolPreviewNode({ const node = await getClientToolPreviewNode({
appId: template.id, appId: template.id,
getLatestVersion: true getLatestVersion: true,
source: template.source
}); });
return { return {
...node, ...node,
......
import { useState, useMemo, useCallback, useRef } from 'react'; import { useEffect, useState, useMemo, useCallback, useRef } from 'react';
import { useRequest } from '@fastgpt/web/hooks/useRequest'; import { useRequest } from '@fastgpt/web/hooks/useRequest';
import type { NodeTemplateListItemType } from '@fastgpt/global/core/workflow/type/node'; import type { NodeTemplateListItemType } from '@fastgpt/global/core/workflow/type/node';
import { FlowNodeTypeEnum } from '@fastgpt/global/core/workflow/node/constant'; import { FlowNodeTypeEnum } from '@fastgpt/global/core/workflow/node/constant';
...@@ -19,6 +19,7 @@ export const useNodeTemplates = () => { ...@@ -19,6 +19,7 @@ export const useNodeTemplates = () => {
const searchKeyLock = useRef(false); const searchKeyLock = useRef(false);
const [parentId, setParentId] = useState<ParentIdType>(''); const [parentId, setParentId] = useState<ParentIdType>('');
const [parentSource, setParentSource] = useState<string>();
const appId = useContextSelector(AppContext, (v) => v.appDetail._id); const appId = useContextSelector(AppContext, (v) => v.appDetail._id);
const { basicNodeTemplates, hasToolNode, hasLoopRunNode, getNodeList, nodeAmount } = const { basicNodeTemplates, hasToolNode, hasLoopRunNode, getNodeList, nodeAmount } =
...@@ -83,12 +84,14 @@ export const useNodeTemplates = () => { ...@@ -83,12 +84,14 @@ export const useNodeTemplates = () => {
parentId, parentId,
type = templateType, type = templateType,
searchVal, searchVal,
tags tags,
source
}: { }: {
parentId?: ParentIdType; parentId?: ParentIdType;
type?: TemplateTypeEnum; type?: TemplateTypeEnum;
searchVal?: string; searchVal?: string;
tags?: string[]; tags?: string[];
source?: string;
}) => { }) => {
if (type === TemplateTypeEnum.myTools) { if (type === TemplateTypeEnum.myTools) {
// app, workflow-plugin, mcp // app, workflow-plugin, mcp
...@@ -115,6 +118,7 @@ export const useNodeTemplates = () => { ...@@ -115,6 +118,7 @@ export const useNodeTemplates = () => {
return getAppToolTemplates({ return getAppToolTemplates({
searchKey: searchVal, searchKey: searchVal,
parentId, parentId,
source: parentId ? source : undefined,
tags tags
}); });
} }
...@@ -132,28 +136,47 @@ export const useNodeTemplates = () => { ...@@ -132,28 +136,47 @@ export const useNodeTemplates = () => {
return; return;
} }
loadNodeTemplates({ parentId, searchVal: searchKey, tags: selectedTagIds }); loadNodeTemplates({
parentId,
searchVal: searchKey,
tags: selectedTagIds,
source: parentSource
});
}, },
[searchKey], [searchKey, parentSource],
{ {
wait: 300 wait: 300
} }
); );
useEffect(() => {
if (templateType !== TemplateTypeEnum.systemTools) return;
loadNodeTemplates({
parentId,
searchVal: searchKey,
tags: selectedTagIds,
source: parentSource
});
}, [loadNodeTemplates, parentId, parentSource, searchKey, selectedTagIds, templateType]);
const onUpdateParentId = useCallback( const onUpdateParentId = useCallback(
(parentId: ParentIdType) => { (parentId: ParentIdType, source?: string) => {
const nextParentSource = parentId ? (source ?? parentSource) : undefined;
searchKeyLock.current = true; searchKeyLock.current = true;
setSearchKey(''); setSearchKey('');
setParentId(parentId); setParentId(parentId);
loadNodeTemplates({ parentId }); setParentSource(nextParentSource);
loadNodeTemplates({ parentId, source: nextParentSource });
}, },
[loadNodeTemplates] [loadNodeTemplates, parentSource]
); );
const onUpdateTemplateType = useCallback( const onUpdateTemplateType = useCallback(
(type: TemplateTypeEnum) => { (type: TemplateTypeEnum) => {
searchKeyLock.current = true; searchKeyLock.current = true;
setSearchKey(''); setSearchKey('');
setParentId(''); setParentId('');
setParentSource(undefined);
setSelectedTagIds([]); setSelectedTagIds([]);
setTemplateType(type); setTemplateType(type);
loadNodeTemplates({ type }); loadNodeTemplates({ type });
...@@ -163,9 +186,9 @@ export const useNodeTemplates = () => { ...@@ -163,9 +186,9 @@ export const useNodeTemplates = () => {
const onUpdateSelectedTagIds = useCallback( const onUpdateSelectedTagIds = useCallback(
(tags: string[]) => { (tags: string[]) => {
setSelectedTagIds(tags); setSelectedTagIds(tags);
loadNodeTemplates({ parentId, searchVal: searchKey, tags }); loadNodeTemplates({ parentId, searchVal: searchKey, tags, source: parentSource });
}, },
[loadNodeTemplates, parentId, searchKey] [loadNodeTemplates, parentId, parentSource, searchKey]
); );
const templates = useMemo(() => { const templates = useMemo(() => {
...@@ -178,6 +201,7 @@ export const useNodeTemplates = () => { ...@@ -178,6 +201,7 @@ export const useNodeTemplates = () => {
return { return {
templateType, templateType,
parentId, parentId,
parentSource,
templatesIsLoading, templatesIsLoading,
templates, templates,
onUpdateParentId, onUpdateParentId,
......
...@@ -67,6 +67,7 @@ const ToolConfig = ({ nodeId, inputs }: { nodeId?: string; inputs?: FlowNodeInpu ...@@ -67,6 +67,7 @@ const ToolConfig = ({ nodeId, inputs }: { nodeId?: string; inputs?: FlowNodeInpu
courseUrl={node?.courseUrl} courseUrl={node?.courseUrl}
readmeUrl={node?.readmeUrl} readmeUrl={node?.readmeUrl}
parentId={node?.pluginId} parentId={node?.pluginId}
source={node?.source}
onClose={setFalse} onClose={setFalse}
onSubmit={onSubmit} onSubmit={onSubmit}
/> />
......
...@@ -50,6 +50,8 @@ import QuestionTip from '@fastgpt/web/components/common/MyTooltip/QuestionTip'; ...@@ -50,6 +50,8 @@ import QuestionTip from '@fastgpt/web/components/common/MyTooltip/QuestionTip';
import WorkflowSandboxConfig, { import WorkflowSandboxConfig, {
createSandboxEntrypointInput createSandboxEntrypointInput
} from '../components/WorkflowSandboxConfig'; } from '../components/WorkflowSandboxConfig';
import { isDebugToolSource } from '@fastgpt/global/core/app/tool/utils';
import DebugToolTag from '@fastgpt/web/components/core/plugin/tool/DebugToolTag';
const PromptEditor = dynamic(() => import('@fastgpt/web/components/common/Textarea/PromptEditor')); const PromptEditor = dynamic(() => import('@fastgpt/web/components/common/Textarea/PromptEditor'));
const SkillSelectModal = dynamic( const SkillSelectModal = dynamic(
...@@ -804,6 +806,7 @@ const NodeAgent = ({ data, selected }: NodeProps<FlowNodeItemType>) => { ...@@ -804,6 +806,7 @@ const NodeAgent = ({ data, selected }: NodeProps<FlowNodeItemType>) => {
> >
{item.name} {item.name}
</Box> </Box>
{isDebugToolSource(item.source) && <DebugToolTag />}
<Box className="delete-btn" display={'none'}> <Box className="delete-btn" display={'none'}>
<MyIconButton <MyIconButton
icon="delete" icon="delete"
......
...@@ -52,12 +52,17 @@ import { ...@@ -52,12 +52,17 @@ import {
PluginStatusMap, PluginStatusMap,
type PluginStatusType type PluginStatusType
} from '@fastgpt/global/core/plugin/type'; } from '@fastgpt/global/core/plugin/type';
import { splitCombineToolId, getToolRawId } from '@fastgpt/global/core/app/tool/utils'; import {
splitCombineToolId,
getToolRawId,
isDebugToolSource
} from '@fastgpt/global/core/app/tool/utils';
import { AppToolSourceEnum } from '@fastgpt/global/core/app/tool/constants'; import { AppToolSourceEnum } from '@fastgpt/global/core/app/tool/constants';
import { getAppPermission } from '@/web/core/app/api'; import { getAppPermission } from '@/web/core/app/api';
import { ObjectIdSchema } from '@fastgpt/global/common/type/mongo'; import { ObjectIdSchema } from '@fastgpt/global/common/type/mongo';
import { useConfirm } from '@fastgpt/web/hooks/useConfirm'; import { useConfirm } from '@fastgpt/web/hooks/useConfirm';
import type { SystemToolVersionType } from '@fastgpt/global/core/app/tool/systemTool/type/base'; import type { SystemToolVersionType } from '@fastgpt/global/core/app/tool/systemTool/type/base';
import DebugToolTag from '@fastgpt/web/components/core/plugin/tool/DebugToolTag';
type Props = FlowNodeItemType & { type Props = FlowNodeItemType & {
children?: React.ReactNode | React.ReactNode[] | string; children?: React.ReactNode | React.ReactNode[] | string;
...@@ -224,6 +229,7 @@ const NodeCard = (props: Props) => { ...@@ -224,6 +229,7 @@ const NodeCard = (props: Props) => {
const isLoopNode = isNestedParentNodeType(node?.flowNodeType ?? ''); const isLoopNode = isNestedParentNodeType(node?.flowNodeType ?? '');
const showVersion = useMemo(() => { const showVersion = useMemo(() => {
const source = node?.pluginId ? splitCombineToolId(node.pluginId).source : undefined; const source = node?.pluginId ? splitCombineToolId(node.pluginId).source : undefined;
if (isDebugToolSource(node?.source)) return false;
// 1. MCP/HTTP single tools use the latest toolset content and do not expose version selection. // 1. MCP/HTTP single tools use the latest toolset content and do not expose version selection.
if (source === AppToolSourceEnum.mcp || source === AppToolSourceEnum.http) return false; if (source === AppToolSourceEnum.mcp || source === AppToolSourceEnum.http) return false;
...@@ -376,6 +382,8 @@ const NodeCard = (props: Props) => { ...@@ -376,6 +382,8 @@ const NodeCard = (props: Props) => {
<Box mr={1} /> <Box mr={1} />
{isDebugToolSource(node?.source) && <DebugToolTag mr={2} />}
{showVersion && <NodeVersion node={node!} />} {showVersion && <NodeVersion node={node!} />}
<NodeActionButtons <NodeActionButtons
...@@ -410,6 +418,7 @@ const NodeCard = (props: Props) => { ...@@ -410,6 +418,7 @@ const NodeCard = (props: Props) => {
readmeUrl={node?.readmeUrl} readmeUrl={node?.readmeUrl}
hasSystemSecret={node?.hasSystemSecret} hasSystemSecret={node?.hasSystemSecret}
pluginId={node?.pluginId} pluginId={node?.pluginId}
source={node?.source}
systemKeyCost={node?.systemKeyCost} systemKeyCost={node?.systemKeyCost}
inputConfig={inputConfig} inputConfig={inputConfig}
/> />
...@@ -640,10 +649,7 @@ const NodeVersion = React.memo(function NodeVersion({ node }: { node: FlowNodeIt ...@@ -640,10 +649,7 @@ const NodeVersion = React.memo(function NodeVersion({ node }: { node: FlowNodeIt
return getTeamToolVersions({ return getTeamToolVersions({
toolId: node.pluginId, toolId: node.pluginId,
source: source: toolSource === AppToolSourceEnum.personal ? 'team' : 'system'
toolSource === AppToolSourceEnum.systemTool || toolSource === AppToolSourceEnum.commercial
? 'system'
: 'team'
}); });
}, },
{ {
...@@ -658,7 +664,8 @@ const NodeVersion = React.memo(function NodeVersion({ node }: { node: FlowNodeIt ...@@ -658,7 +664,8 @@ const NodeVersion = React.memo(function NodeVersion({ node }: { node: FlowNodeIt
if (node.pluginId) { if (node.pluginId) {
const template = await getClientToolPreviewNode({ const template = await getClientToolPreviewNode({
appId: node.pluginId, appId: node.pluginId,
versionId versionId,
source: node.source
}); });
if (!!template) { if (!!template) {
...@@ -787,6 +794,7 @@ const MenuRender = React.memo(function MenuRender({ ...@@ -787,6 +794,7 @@ const MenuRender = React.memo(function MenuRender({
outputs: node.data.outputs, outputs: node.data.outputs,
pluginId: node.data.pluginId, pluginId: node.data.pluginId,
source: node.data.source,
isFolder: node.data.isFolder, isFolder: node.data.isFolder,
pluginData: node.data.pluginData, pluginData: node.data.pluginData,
...@@ -816,6 +824,7 @@ const MenuRender = React.memo(function MenuRender({ ...@@ -816,6 +824,7 @@ const MenuRender = React.memo(function MenuRender({
position: { x: node.position.x + 200, y: node.position.y + 50 }, position: { x: node.position.x + 200, y: node.position.y + 50 },
showStatus: template.showStatus, showStatus: template.showStatus,
pluginId: template.pluginId, pluginId: template.pluginId,
source: template.source,
inputs: template.inputs, inputs: template.inputs,
outputs: template.outputs, outputs: template.outputs,
version: template.version, version: template.version,
...@@ -1069,6 +1078,7 @@ const NodeSecret = React.memo(function NodeSecret({ ...@@ -1069,6 +1078,7 @@ const NodeSecret = React.memo(function NodeSecret({
readmeUrl, readmeUrl,
hasSystemSecret, hasSystemSecret,
pluginId, pluginId,
source,
systemKeyCost, systemKeyCost,
inputConfig inputConfig
}: { }: {
...@@ -1078,6 +1088,7 @@ const NodeSecret = React.memo(function NodeSecret({ ...@@ -1078,6 +1088,7 @@ const NodeSecret = React.memo(function NodeSecret({
readmeUrl?: string; readmeUrl?: string;
hasSystemSecret?: boolean; hasSystemSecret?: boolean;
pluginId?: string; pluginId?: string;
source?: string;
systemKeyCost?: number; systemKeyCost?: number;
inputConfig: FlowNodeInputItemType | undefined; inputConfig: FlowNodeInputItemType | undefined;
}) { }) {
...@@ -1128,6 +1139,7 @@ const NodeSecret = React.memo(function NodeSecret({ ...@@ -1128,6 +1139,7 @@ const NodeSecret = React.memo(function NodeSecret({
inputConfig={inputConfig} inputConfig={inputConfig}
hasSystemSecret={hasSystemSecret} hasSystemSecret={hasSystemSecret}
parentId={pluginId} parentId={pluginId}
source={source}
secretCost={systemKeyCost} secretCost={systemKeyCost}
/> />
)} )}
......
...@@ -24,6 +24,8 @@ import { AppErrEnum } from '@fastgpt/global/common/error/code/app'; ...@@ -24,6 +24,8 @@ import { AppErrEnum } from '@fastgpt/global/common/error/code/app';
import { useToast } from '@fastgpt/web/hooks/useToast'; import { useToast } from '@fastgpt/web/hooks/useToast';
import { AppTypeList } from '@fastgpt/global/core/app/constants'; import { AppTypeList } from '@fastgpt/global/core/app/constants';
import { useConfirm } from '@fastgpt/web/hooks/useConfirm'; import { useConfirm } from '@fastgpt/web/hooks/useConfirm';
import { hasDebugToolInNodes } from '@fastgpt/global/core/app/tool/utils';
import { ToastHandledError } from '@fastgpt/global/common/error/utils';
const InfoModal = dynamic(() => import('./InfoModal')); const InfoModal = dynamic(() => import('./InfoModal'));
const TagsEditModal = dynamic(() => import('./TagsEditModal')); const TagsEditModal = dynamic(() => import('./TagsEditModal'));
...@@ -166,6 +168,13 @@ const AppContextProvider = ({ children }: { children: ReactNode }) => { ...@@ -166,6 +168,13 @@ const AppContextProvider = ({ children }: { children: ReactNode }) => {
async (data: PostPublishAppProps) => { async (data: PostPublishAppProps) => {
try { try {
if (!appDetail.permission.hasWritePer) return; if (!appDetail.permission.hasWritePer) return;
if (data.isPublish && hasDebugToolInNodes(data.nodes)) {
toast({
title: t('app:publish_remove_debug_tool_tip'),
status: 'warning'
});
return Promise.reject(new ToastHandledError('Debug tool cannot be published'));
}
await postPublishApp(appId, data); await postPublishApp(appId, data);
setAppDetail((state) => ({ setAppDetail((state) => ({
...state, ...state,
......
...@@ -26,6 +26,7 @@ export type ToolParamsFormType = { ...@@ -26,6 +26,7 @@ export type ToolParamsFormType = {
const SecretInputModal = ({ const SecretInputModal = ({
parentId, parentId,
source,
hasSystemSecret, hasSystemSecret,
secretCost = 0, secretCost = 0,
isFolder, isFolder,
...@@ -36,6 +37,7 @@ const SecretInputModal = ({ ...@@ -36,6 +37,7 @@ const SecretInputModal = ({
onSubmit onSubmit
}: { }: {
parentId?: string; parentId?: string;
source?: string;
isFolder?: boolean; isFolder?: boolean;
inputConfig: FlowNodeInputItemType; inputConfig: FlowNodeInputItemType;
hasSystemSecret?: boolean; hasSystemSecret?: boolean;
...@@ -78,11 +80,11 @@ const SecretInputModal = ({ ...@@ -78,11 +80,11 @@ const SecretInputModal = ({
const { data: childTools = [] } = useRequest<NodeTemplateListItemType[], []>( const { data: childTools = [] } = useRequest<NodeTemplateListItemType[], []>(
async () => { async () => {
if (!isFolder) return []; if (!isFolder) return [];
return getAppToolTemplates({ parentId }); return getAppToolTemplates({ parentId, source });
}, },
{ {
manual: false, manual: false,
refreshDeps: [isFolder, parentId] refreshDeps: [isFolder, parentId, source]
} }
); );
......
...@@ -36,6 +36,8 @@ import { useSystemStore } from '@/web/common/system/useSystemStore'; ...@@ -36,6 +36,8 @@ import { useSystemStore } from '@/web/common/system/useSystemStore';
import ToolTagFilterBox from '@fastgpt/web/components/core/plugin/tool/TagFilterBox'; import ToolTagFilterBox from '@fastgpt/web/components/core/plugin/tool/TagFilterBox';
import { getPluginToolTags } from '@/web/core/plugin/toolTag/api'; import { getPluginToolTags } from '@/web/core/plugin/toolTag/api';
import ConfigToolModal from '@/pageComponents/app/detail/Edit/component/ConfigToolModal'; import ConfigToolModal from '@/pageComponents/app/detail/Edit/component/ConfigToolModal';
import { isDebugToolSource } from '@fastgpt/global/core/app/tool/utils';
import DebugToolTag from '@fastgpt/web/components/core/plugin/tool/DebugToolTag';
type Props = { type Props = {
selectedTools: ChatSettingType['selectedTools']; selectedTools: ChatSettingType['selectedTools'];
...@@ -54,6 +56,7 @@ export const childAppSystemKey: string[] = [ ...@@ -54,6 +56,7 @@ export const childAppSystemKey: string[] = [
const ToolSelectModal = ({ onClose, ...props }: Props & { onClose: () => void }) => { const ToolSelectModal = ({ onClose, ...props }: Props & { onClose: () => void }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const [parentId, setParentId] = useState<ParentIdType>(''); const [parentId, setParentId] = useState<ParentIdType>('');
const [parentSource, setParentSource] = useState<string>();
const [searchKey, setSearchKey] = useState(''); const [searchKey, setSearchKey] = useState('');
const [selectedTagIds, setSelectedTagIds] = useState<string[]>([]); const [selectedTagIds, setSelectedTagIds] = useState<string[]>([]);
...@@ -64,16 +67,19 @@ const ToolSelectModal = ({ onClose, ...props }: Props & { onClose: () => void }) ...@@ -64,16 +67,19 @@ const ToolSelectModal = ({ onClose, ...props }: Props & { onClose: () => void })
} = useRequest( } = useRequest(
async ({ async ({
parentId = '', parentId = '',
searchVal = searchKey searchVal = searchKey,
source
}: { }: {
parentId?: ParentIdType; parentId?: ParentIdType;
searchVal?: string; searchVal?: string;
source?: string;
}) => { }) => {
return getAppToolTemplates({ parentId, searchKey: searchVal }); return getAppToolTemplates({ parentId, searchKey: searchVal, source });
}, },
{ {
onSuccess(_, [{ parentId = '' }]) { onSuccess(_, [{ parentId = '', source }]) {
setParentId(parentId); setParentId(parentId);
setParentSource(parentId ? (source ?? parentSource) : undefined);
}, },
refreshDeps: [searchKey, parentId] refreshDeps: [searchKey, parentId]
} }
...@@ -94,25 +100,27 @@ const ToolSelectModal = ({ onClose, ...props }: Props & { onClose: () => void }) ...@@ -94,25 +100,27 @@ const ToolSelectModal = ({ onClose, ...props }: Props & { onClose: () => void })
const { data: paths = [] } = useRequest( const { data: paths = [] } = useRequest(
() => { () => {
return getAppToolPaths({ sourceId: parentId, type: 'current' }); return getAppToolPaths({ sourceId: parentId, source: parentSource, type: 'current' });
}, },
{ {
manual: false, manual: false,
refreshDeps: [parentId] refreshDeps: [parentId, parentSource]
} }
); );
const onUpdateParentId = useCallback( const onUpdateParentId = useCallback(
(parentId: ParentIdType) => { (parentId: ParentIdType, source?: string) => {
if (document.activeElement instanceof HTMLElement) { if (document.activeElement instanceof HTMLElement) {
document.activeElement.blur(); document.activeElement.blur();
} }
const nextParentSource = parentId ? (source ?? parentSource) : undefined;
loadTemplates({ loadTemplates({
parentId parentId,
source: nextParentSource
}); });
}, },
[loadTemplates] [loadTemplates, parentSource]
); );
useRequest(() => loadTemplates({ searchVal: searchKey }), { useRequest(() => loadTemplates({ searchVal: searchKey }), {
...@@ -191,7 +199,7 @@ const RenderList = React.memo(function RenderList({ ...@@ -191,7 +199,7 @@ const RenderList = React.memo(function RenderList({
parentId: ParentIdType; parentId: ParentIdType;
searchKey: string; searchKey: string;
selectedTagIds: string[]; selectedTagIds: string[];
setParentId: (parentId: ParentIdType) => any; setParentId: (parentId: ParentIdType, source?: string) => any;
}) { }) {
const { t, i18n } = useTranslation(); const { t, i18n } = useTranslation();
const { feConfigs } = useSystemStore(); const { feConfigs } = useSystemStore();
...@@ -208,7 +216,11 @@ const RenderList = React.memo(function RenderList({ ...@@ -208,7 +216,11 @@ const RenderList = React.memo(function RenderList({
const { runAsync: onClickAdd, loading: isLoading } = useRequest( const { runAsync: onClickAdd, loading: isLoading } = useRequest(
async (template: NodeTemplateListItemType) => { async (template: NodeTemplateListItemType) => {
const res = await getClientToolPreviewNode({ appId: template.id, versionId: '' }); const res = await getClientToolPreviewNode({
appId: template.id,
versionId: '',
source: template.source
});
const isToolSetTemplate = template.flowNodeType === FlowNodeTypeEnum.toolSet; const isToolSetTemplate = template.flowNodeType === FlowNodeTypeEnum.toolSet;
/* Invalid plugin check /* Invalid plugin check
...@@ -312,6 +324,7 @@ const RenderList = React.memo(function RenderList({ ...@@ -312,6 +324,7 @@ const RenderList = React.memo(function RenderList({
> >
{templates.map((template) => { {templates.map((template) => {
const selected = selectedTools.some((tool) => tool.pluginId === template.id); const selected = selectedTools.some((tool) => tool.pluginId === template.id);
const isDebugTool = isDebugToolSource(template.source);
return ( return (
<MyTooltip <MyTooltip
...@@ -330,6 +343,7 @@ const RenderList = React.memo(function RenderList({ ...@@ -330,6 +343,7 @@ const RenderList = React.memo(function RenderList({
<Box fontWeight={'bold'} color={'myGray.900'} flex={'1'}> <Box fontWeight={'bold'} color={'myGray.900'} flex={'1'}>
{template.name} {template.name}
</Box> </Box>
{isDebugTool && <DebugToolTag />}
<Box color={'myGray.500'}>By {template.author || feConfigs?.systemTitle}</Box> <Box color={'myGray.500'}>By {template.author || feConfigs?.systemTitle}</Box>
</Flex> </Flex>
<Box pt={2} color={'myGray.500'} maxH={'100px'} overflow={'hidden'}> <Box pt={2} color={'myGray.500'} maxH={'100px'} overflow={'hidden'}>
...@@ -355,7 +369,8 @@ const RenderList = React.memo(function RenderList({ ...@@ -355,7 +369,8 @@ const RenderList = React.memo(function RenderList({
borderRadius={'sm'} borderRadius={'sm'}
flexShrink={0} flexShrink={0}
/> />
<Box flex={'1 0 0'}> <Box flex={'1 0 0'} minW={0}>
<Flex alignItems={'center'} gap={2} minW={0}>
<Box <Box
color={'myGray.900'} color={'myGray.900'}
fontWeight={'500'} fontWeight={'500'}
...@@ -364,6 +379,8 @@ const RenderList = React.memo(function RenderList({ ...@@ -364,6 +379,8 @@ const RenderList = React.memo(function RenderList({
> >
{t(parseI18nString(template.name, i18n.language))} {t(parseI18nString(template.name, i18n.language))}
</Box> </Box>
{isDebugTool && <DebugToolTag />}
</Flex>
</Box> </Box>
{selected ? ( {selected ? (
...@@ -384,7 +401,7 @@ const RenderList = React.memo(function RenderList({ ...@@ -384,7 +401,7 @@ const RenderList = React.memo(function RenderList({
variant={'whiteBase'} variant={'whiteBase'}
isLoading={isLoading} isLoading={isLoading}
leftIcon={<MyIcon name={'common/arrowRight'} w={'16px'} mr={-1.5} />} leftIcon={<MyIcon name={'common/arrowRight'} w={'16px'} mr={-1.5} />}
onClick={() => setParentId(template.id)} onClick={() => setParentId(template.id, template.source)}
px={2} px={2}
fontSize={'mini'} fontSize={'mini'}
> >
...@@ -407,7 +424,7 @@ const RenderList = React.memo(function RenderList({ ...@@ -407,7 +424,7 @@ const RenderList = React.memo(function RenderList({
size={'sm'} size={'sm'}
variant={'whiteBase'} variant={'whiteBase'}
leftIcon={<MyIcon name={'common/arrowRight'} w={'16px'} mr={-1.5} />} leftIcon={<MyIcon name={'common/arrowRight'} w={'16px'} mr={-1.5} />}
onClick={() => setParentId(template.id)} onClick={() => setParentId(template.id, template.source)}
px={2} px={2}
fontSize={'mini'} fontSize={'mini'}
> >
......
...@@ -6,7 +6,7 @@ import { type FlowNodeTemplateType } from '@fastgpt/global/core/workflow/type/no ...@@ -6,7 +6,7 @@ import { type FlowNodeTemplateType } from '@fastgpt/global/core/workflow/type/no
import { NextAPI } from '@/service/middleware/entry'; import { NextAPI } from '@/service/middleware/entry';
import { type ApiRequestProps } from '@fastgpt/service/type/next'; import { type ApiRequestProps } from '@fastgpt/service/type/next';
import { getLocale } from '@fastgpt/service/common/middle/i18n'; import { getLocale } from '@fastgpt/service/common/middle/i18n';
import { splitCombineToolId } from '@fastgpt/global/core/app/tool/utils'; import { isDebugToolSource, splitCombineToolId } from '@fastgpt/global/core/app/tool/utils';
import { ReadPermissionVal } from '@fastgpt/global/support/permission/constant'; import { ReadPermissionVal } from '@fastgpt/global/support/permission/constant';
import { authApp } from '@fastgpt/service/support/permission/app/auth'; import { authApp } from '@fastgpt/service/support/permission/app/auth';
import { parseApiInput } from '@fastgpt/service/common/zod/requestParseError'; import { parseApiInput } from '@fastgpt/service/common/zod/requestParseError';
...@@ -20,7 +20,7 @@ async function handler( ...@@ -20,7 +20,7 @@ async function handler(
req: ApiRequestProps<Record<string, never>, GetPreviewNodeQuery> req: ApiRequestProps<Record<string, never>, GetPreviewNodeQuery>
): Promise<FlowNodeTemplateType> { ): Promise<FlowNodeTemplateType> {
const { const {
query: { appId, versionId, getLatestVersion } query: { appId, versionId, getLatestVersion, source }
} = parseApiInput({ } = parseApiInput({
req, req,
querySchema: GetPreviewNodeQuerySchema querySchema: GetPreviewNodeQuerySchema
...@@ -36,7 +36,8 @@ async function handler( ...@@ -36,7 +36,8 @@ async function handler(
appId, appId,
versionId, versionId,
getLatestVersion, getLatestVersion,
lang: getLocale(req) lang: getLocale(req),
source: isDebugToolSource(source) ? source : undefined
}) })
); );
} }
......
...@@ -15,6 +15,8 @@ import { ...@@ -15,6 +15,8 @@ import {
} from '@fastgpt/global/openapi/core/app/tool/api'; } from '@fastgpt/global/openapi/core/app/tool/api';
import { parseApiInput } from '@fastgpt/service/common/zod/requestParseError'; import { parseApiInput } from '@fastgpt/service/common/zod/requestParseError';
import { PluginStatusEnum, type PluginStatusType } from '@fastgpt/global/core/plugin/type'; import { PluginStatusEnum, type PluginStatusType } from '@fastgpt/global/core/plugin/type';
import { pluginClient } from '@fastgpt/service/thirdProvider/fastgptPlugin';
import { isDebugToolSource } from '@fastgpt/global/core/app/tool/utils';
export type GetSystemPluginTemplatesBody = GetSystemToolTemplatesBodyType; export type GetSystemPluginTemplatesBody = GetSystemToolTemplatesBodyType;
...@@ -23,7 +25,7 @@ export async function handler( ...@@ -23,7 +25,7 @@ export async function handler(
): Promise<NodeTemplateListItemType[]> { ): Promise<NodeTemplateListItemType[]> {
const { teamId, tmbId, isRoot } = await authCert({ req, authToken: true }); const { teamId, tmbId, isRoot } = await authCert({ req, authToken: true });
const { const {
body: { tags, parentId, searchKey } body: { tags, parentId, searchKey, source }
} = parseApiInput({ } = parseApiInput({
req, req,
bodySchema: GetSystemToolTemplatesBodySchema bodySchema: GetSystemToolTemplatesBodySchema
...@@ -38,10 +40,16 @@ export async function handler( ...@@ -38,10 +40,16 @@ export async function handler(
// const tools = await getSystemToolsWithInstalled({ teamId, isRoot, userTags }); // const tools = await getSystemToolsWithInstalled({ teamId, isRoot, userTags });
const systemToolRepo = SystemToolRepo.getInstance(); const systemToolRepo = SystemToolRepo.getInstance();
if (parentId) { if (parentId) {
const parentSource = isDebugToolSource(source)
? await getActiveDebugSource({
tmbId,
source
})
: source;
const parent = await systemToolRepo.getSystemToolDisplayInfoWithChildIcons({ const parent = await systemToolRepo.getSystemToolDisplayInfoWithChildIcons({
pluginId: parentId, pluginId: parentId,
lang, lang,
source: 'system' source: parentSource ?? 'system'
}); });
if (!isSelectableToolStatus(parent.status)) { if (!isSelectableToolStatus(parent.status)) {
return GetSystemToolTemplatesResponseSchema.parse([]); return GetSystemToolTemplatesResponseSchema.parse([]);
...@@ -61,6 +69,7 @@ export async function handler( ...@@ -61,6 +69,7 @@ export async function handler(
intro: child.description, intro: child.description,
toolDescription: child.toolDescription, toolDescription: child.toolDescription,
id: `${parentId}/${child.id}`, id: `${parentId}/${child.id}`,
source: parent.source,
avatar: child.icon ?? parent.avatar, avatar: child.icon ?? parent.avatar,
currentCost: child.currentCost, currentCost: child.currentCost,
systemKeyCost: child.systemKeyCost, systemKeyCost: child.systemKeyCost,
...@@ -73,13 +82,17 @@ export async function handler( ...@@ -73,13 +82,17 @@ export async function handler(
); );
} }
// no parentId, get all tools // no parentId, get all tools
const debugSource = await getActiveDebugSource({ tmbId });
const tools = await systemToolRepo.getSystemToolList({ const tools = await systemToolRepo.getSystemToolList({
lang, lang,
sources: ['system', teamId], op: 'or',
// 调试状态下追加 debug source,Agent/Workflow 仍保留生产环境插件可选。
sources: ['system', teamId, ...(debugSource ? [debugSource] : [])],
tags tags
}); });
const templates = tools const templates = tools
.sort((a, b) => Number(isDebugToolSource(b.source)) - Number(isDebugToolSource(a.source)))
.filter((item) => { .filter((item) => {
if (!isSelectableToolStatus(item.status)) return false; if (!isSelectableToolStatus(item.status)) return false;
if (isRoot) return true; if (isRoot) return true;
...@@ -90,6 +103,7 @@ export async function handler( ...@@ -90,6 +103,7 @@ export async function handler(
...tool, ...tool,
templateType: FlowNodeTemplateTypeEnum.tools, templateType: FlowNodeTemplateTypeEnum.tools,
flowNodeType: tool.isToolSet ? FlowNodeTypeEnum.toolSet : FlowNodeTypeEnum.tool, flowNodeType: tool.isToolSet ? FlowNodeTypeEnum.toolSet : FlowNodeTypeEnum.tool,
source: tool.source,
name: tool.name, name: tool.name,
intro: tool.intro, intro: tool.intro,
instructions: tool.userGuide ?? '', instructions: tool.userGuide ?? '',
...@@ -101,6 +115,19 @@ export async function handler( ...@@ -101,6 +115,19 @@ export async function handler(
return GetSystemToolTemplatesResponseSchema.parse(templates); return GetSystemToolTemplatesResponseSchema.parse(templates);
} }
async function getActiveDebugSource({ tmbId, source }: { tmbId: string; source?: string }) {
const status = await pluginClient.getDebugSessionStatus({ tmbId }).catch(() => undefined);
if (
status?.enabled &&
(status.status === 'enabled' || status.status === 'connected') &&
isDebugToolSource(status.source) &&
(!source || status.source === source)
) {
return status.source;
}
}
export default NextAPI(handler); export default NextAPI(handler);
function getSearchRegex(searchKey?: string) { function getSearchRegex(searchKey?: string) {
......
...@@ -2,7 +2,7 @@ import type { ApiRequestProps } from '@fastgpt/service/type/next'; ...@@ -2,7 +2,7 @@ import type { ApiRequestProps } from '@fastgpt/service/type/next';
import { NextAPI } from '@/service/middleware/entry'; import { NextAPI } from '@/service/middleware/entry';
import { getLocale } from '@fastgpt/service/common/middle/i18n'; import { getLocale } from '@fastgpt/service/common/middle/i18n';
import { SystemToolRepo } from '@fastgpt/service/core/app/tool/systemTool/systemTool.repo'; import { SystemToolRepo } from '@fastgpt/service/core/app/tool/systemTool/systemTool.repo';
import { splitCombineToolId } from '@fastgpt/global/core/app/tool/utils'; import { isDebugToolSource, splitCombineToolId } from '@fastgpt/global/core/app/tool/utils';
import { AppToolSourceEnum } from '@fastgpt/global/core/app/tool/constants'; import { AppToolSourceEnum } from '@fastgpt/global/core/app/tool/constants';
import { import {
GetToolPathQuerySchema, GetToolPathQuerySchema,
...@@ -20,7 +20,7 @@ export type pathResponse = Promise<GetToolPathResponseType>; ...@@ -20,7 +20,7 @@ export type pathResponse = Promise<GetToolPathResponseType>;
export async function handler(req: ApiRequestProps<pathBody, pathQuery>): Promise<pathResponse> { export async function handler(req: ApiRequestProps<pathBody, pathQuery>): Promise<pathResponse> {
const { const {
query: { sourceId: pluginId, type = 'current' } query: { sourceId: pluginId, source, type = 'current' }
} = parseApiInput({ } = parseApiInput({
req, req,
querySchema: GetToolPathQuerySchema querySchema: GetToolPathQuerySchema
...@@ -29,7 +29,7 @@ export async function handler(req: ApiRequestProps<pathBody, pathQuery>): Promis ...@@ -29,7 +29,7 @@ export async function handler(req: ApiRequestProps<pathBody, pathQuery>): Promis
if (!pluginId) return GetToolPathResponseSchema.parse([]); if (!pluginId) return GetToolPathResponseSchema.parse([]);
const parentToolId = getParentToolId(pluginId); const parentToolId = getParentToolId({ toolId: pluginId, source });
const pathToolIds = type === 'parent' ? (parentToolId ? [parentToolId] : []) : []; const pathToolIds = type === 'parent' ? (parentToolId ? [parentToolId] : []) : [];
if (type === 'current') { if (type === 'current') {
...@@ -40,38 +40,54 @@ export async function handler(req: ApiRequestProps<pathBody, pathQuery>): Promis ...@@ -40,38 +40,54 @@ export async function handler(req: ApiRequestProps<pathBody, pathQuery>): Promis
} }
return GetToolPathResponseSchema.parse( return GetToolPathResponseSchema.parse(
await Promise.all(pathToolIds.map((toolId) => getToolPathItem({ toolId, lang }))) await Promise.all(pathToolIds.map((toolId) => getToolPathItem({ toolId, source, lang })))
); );
} }
export default NextAPI(handler); export default NextAPI(handler);
function getParentToolId(toolId: string) { function getParentToolId({ toolId, source }: { toolId: string; source?: string }) {
const { source, pluginId } = splitCombineToolId(toolId); if (isDebugToolSource(source)) {
const { pluginId, hasIdPrefix, idSource } = parseToolIdForPath(toolId);
const [parentPluginId, childPluginId] = pluginId.split('/');
if (!parentPluginId || !childPluginId) return;
return hasIdPrefix ? `${idSource}-${parentPluginId}` : parentPluginId;
}
if (![AppToolSourceEnum.systemTool, AppToolSourceEnum.commercial].includes(source)) { const { source: idSource, pluginId } = splitCombineToolId(toolId);
if (![AppToolSourceEnum.systemTool, AppToolSourceEnum.commercial].includes(idSource as any)) {
return; return;
} }
const [parentPluginId, childPluginId] = pluginId.split('/'); const [parentPluginId, childPluginId] = pluginId.split('/');
if (!parentPluginId || !childPluginId) return; if (!parentPluginId || !childPluginId) return;
return `${source}-${parentPluginId}`; return `${idSource}-${parentPluginId}`;
} }
async function getToolPathItem({ async function getToolPathItem({
toolId, toolId,
source,
lang lang
}: { }: {
toolId: string; toolId: string;
source?: string;
lang: ReturnType<typeof getLocale>; lang: ReturnType<typeof getLocale>;
}): Promise<GetToolPathResponseType[number]> { }): Promise<GetToolPathResponseType[number]> {
const systemToolRepo = SystemToolRepo.getInstance(); const systemToolRepo = SystemToolRepo.getInstance();
const { source } = splitCombineToolId(toolId); const idSource = isDebugToolSource(source)
? parseToolIdForPath(toolId).idSource
: splitCombineToolId(toolId).source;
const toolSource = isDebugToolSource(source)
? source
: idSource === AppToolSourceEnum.commercial
? AppToolSourceEnum.commercial
: 'system';
const tool = await systemToolRepo.getSystemToolDisplayInfo({ const tool = await systemToolRepo.getSystemToolDisplayInfo({
pluginId: toolId, pluginId: toolId,
lang, lang,
source: source === AppToolSourceEnum.commercial ? AppToolSourceEnum.commercial : 'system' source: toolSource
}); });
return { return {
...@@ -79,3 +95,22 @@ async function getToolPathItem({ ...@@ -79,3 +95,22 @@ async function getToolPathItem({
parentName: tool.name parentName: tool.name
}; };
} }
function parseToolIdForPath(toolId: string) {
try {
const parsed = splitCombineToolId(toolId);
return {
idSource: parsed.source,
pluginId: parsed.pluginId,
hasIdPrefix: [AppToolSourceEnum.systemTool, AppToolSourceEnum.commercial].includes(
parsed.source as AppToolSourceEnum
)
};
} catch {
return {
idSource: undefined,
pluginId: toolId,
hasIdPrefix: false
};
}
}
...@@ -6,6 +6,7 @@ import { WritePermissionVal } from '@fastgpt/global/support/permission/constant' ...@@ -6,6 +6,7 @@ import { WritePermissionVal } from '@fastgpt/global/support/permission/constant'
import { formatTime2YMDHM } from '@fastgpt/global/common/string/time'; import { formatTime2YMDHM } from '@fastgpt/global/common/string/time';
import { rewriteAppWorkflowToDetail } from '@fastgpt/service/core/app/utils'; import { rewriteAppWorkflowToDetail } from '@fastgpt/service/core/app/utils';
import { parseApiInput } from '@fastgpt/service/common/zod/requestParseError'; import { parseApiInput } from '@fastgpt/service/common/zod/requestParseError';
import { getLocale } from '@fastgpt/service/common/middle/i18n';
import { import {
GetAppVersionDetailQuerySchema, GetAppVersionDetailQuerySchema,
GetAppVersionDetailResponseSchema, GetAppVersionDetailResponseSchema,
...@@ -34,7 +35,8 @@ async function handler(req: NextApiRequest): Promise<GetAppVersionDetailResponse ...@@ -34,7 +35,8 @@ async function handler(req: NextApiRequest): Promise<GetAppVersionDetailResponse
nodes: result.nodes, nodes: result.nodes,
teamId, teamId,
ownerTmbId: app.tmbId, ownerTmbId: app.tmbId,
isRoot isRoot,
lang: getLocale(req)
}); });
return GetAppVersionDetailResponseSchema.parse({ return GetAppVersionDetailResponseSchema.parse({
......
...@@ -5,6 +5,7 @@ import { WritePermissionVal } from '@fastgpt/global/support/permission/constant' ...@@ -5,6 +5,7 @@ import { WritePermissionVal } from '@fastgpt/global/support/permission/constant'
import { getAppLatestVersion } from '@fastgpt/service/core/app/version/controller'; import { getAppLatestVersion } from '@fastgpt/service/core/app/version/controller';
import { rewriteAppWorkflowToDetail } from '@fastgpt/service/core/app/utils'; import { rewriteAppWorkflowToDetail } from '@fastgpt/service/core/app/utils';
import { parseApiInput } from '@fastgpt/service/common/zod/requestParseError'; import { parseApiInput } from '@fastgpt/service/common/zod/requestParseError';
import { getLocale } from '@fastgpt/service/common/middle/i18n';
import { import {
GetLatestAppVersionQuerySchema, GetLatestAppVersionQuerySchema,
GetLatestAppVersionResponseSchema, GetLatestAppVersionResponseSchema,
...@@ -34,7 +35,8 @@ async function handler( ...@@ -34,7 +35,8 @@ async function handler(
nodes: version.nodes, nodes: version.nodes,
teamId, teamId,
isRoot, isRoot,
ownerTmbId: app.tmbId ownerTmbId: app.tmbId,
lang: getLocale(req)
}); });
return GetLatestAppVersionResponseSchema.parse(version); return GetLatestAppVersionResponseSchema.parse(version);
......
...@@ -10,6 +10,7 @@ import { ...@@ -10,6 +10,7 @@ import {
} from '@fastgpt/global/openapi/core/plugin/team/tool/api'; } from '@fastgpt/global/openapi/core/plugin/team/tool/api';
import { SystemToolRepo } from '@fastgpt/service/core/app/tool/systemTool/systemTool.repo'; import { SystemToolRepo } from '@fastgpt/service/core/app/tool/systemTool/systemTool.repo';
import { parseApiInput } from '@fastgpt/service/common/zod/requestParseError'; import { parseApiInput } from '@fastgpt/service/common/zod/requestParseError';
import { isDebugToolSource } from '@fastgpt/global/core/app/tool/utils';
export type detailQuery = GetTeamToolDetailQueryType; export type detailQuery = GetTeamToolDetailQueryType;
...@@ -33,7 +34,7 @@ async function handler(req: ApiRequestProps<detailBody, detailQuery>): Promise<d ...@@ -33,7 +34,7 @@ async function handler(req: ApiRequestProps<detailBody, detailQuery>): Promise<d
const tool = await systemToolRepo.getSystemToolDetail({ const tool = await systemToolRepo.getSystemToolDetail({
pluginId: toolId, pluginId: toolId,
lang, lang,
source: source === 'team' ? teamId : 'system', source: getQuerySource({ source, teamId }),
version version
}); });
...@@ -41,3 +42,9 @@ async function handler(req: ApiRequestProps<detailBody, detailQuery>): Promise<d ...@@ -41,3 +42,9 @@ async function handler(req: ApiRequestProps<detailBody, detailQuery>): Promise<d
} }
export default NextAPI(handler); export default NextAPI(handler);
function getQuerySource({ source, teamId }: { source?: string; teamId: string }) {
if (source === 'team') return teamId;
if (isDebugToolSource(source)) return source;
return 'system';
}
import type { ApiRequestProps } from '@fastgpt/service/type/next'; import type { ApiRequestProps } from '@fastgpt/service/type/next';
import { NextAPI } from '@/service/middleware/entry'; import { NextAPI } from '@/service/middleware/entry';
import { import {
GetTeamSystemPluginListQuerySchema,
type GetTeamSystemPluginListQueryType, type GetTeamSystemPluginListQueryType,
GetTeamPluginListResponseSchema,
type GetTeamPluginListResponseType type GetTeamPluginListResponseType
} from '@fastgpt/global/openapi/core/plugin/team/tool/api'; } from '@fastgpt/global/openapi/core/plugin/team/tool/api';
import { authCert } from '@fastgpt/service/support/permission/auth/common'; import { authCert } from '@fastgpt/service/support/permission/auth/common';
...@@ -9,6 +11,9 @@ import { getLocale } from '@fastgpt/service/common/middle/i18n'; ...@@ -9,6 +11,9 @@ import { getLocale } from '@fastgpt/service/common/middle/i18n';
import { SystemToolRepo } from '@fastgpt/service/core/app/tool/systemTool/systemTool.repo'; import { SystemToolRepo } from '@fastgpt/service/core/app/tool/systemTool/systemTool.repo';
import { getUserDetail } from '@fastgpt/service/support/user/controller'; import { getUserDetail } from '@fastgpt/service/support/user/controller';
import type { UserTagsType } from '@fastgpt/global/support/user/type'; import type { UserTagsType } from '@fastgpt/global/support/user/type';
import { parseApiInput } from '@fastgpt/service/common/zod/requestParseError';
import { pluginClient } from '@fastgpt/service/thirdProvider/fastgptPlugin';
import { isDebugToolSource } from '@fastgpt/global/core/app/tool/utils';
export type listQuery = GetTeamSystemPluginListQueryType; export type listQuery = GetTeamSystemPluginListQueryType;
...@@ -28,21 +33,29 @@ const hasMatchedUserTag = ({ ...@@ -28,21 +33,29 @@ const hasMatchedUserTag = ({
async function handler(req: ApiRequestProps<listBody, listQuery>): Promise<listResponse> { async function handler(req: ApiRequestProps<listBody, listQuery>): Promise<listResponse> {
const lang = getLocale(req); const lang = getLocale(req);
parseApiInput({
req,
querySchema: GetTeamSystemPluginListQuerySchema
});
const { teamId, tmbId } = await authCert({ req, authToken: true }); const { teamId, tmbId } = await authCert({ req, authToken: true });
const debugSource = await getActiveDebugSource(tmbId);
const systemToolRepo = SystemToolRepo.getInstance(); const systemToolRepo = SystemToolRepo.getInstance();
const [tools, userDetail] = await Promise.all([ const [tools, userDetail] = await Promise.all([
systemToolRepo.getSystemToolList({ systemToolRepo.getSystemToolList({
op: 'or', op: 'or',
sources: ['system', teamId], // 调试 source 作为额外来源追加,保留 system/team 的生产插件可见性。
sources: ['system', teamId, ...(debugSource ? [debugSource] : [])],
lang lang
}), }),
getUserDetail({ tmbId }) getUserDetail({ tmbId })
]); ]);
const userTags = userDetail.tags || []; const userTags = userDetail.tags || [];
return tools return GetTeamPluginListResponseSchema.parse(
tools
.sort((a, b) => Number(isDebugToolSource(b.source)) - Number(isDebugToolSource(a.source)))
.filter((tool) => { .filter((tool) => {
if (hasMatchedUserTag({ userTags, targetTags: tool.hideTags })) return false; if (hasMatchedUserTag({ userTags, targetTags: tool.hideTags })) return false;
return true; return true;
...@@ -50,7 +63,20 @@ async function handler(req: ApiRequestProps<listBody, listQuery>): Promise<listR ...@@ -50,7 +63,20 @@ async function handler(req: ApiRequestProps<listBody, listQuery>): Promise<listR
.map((tool) => ({ .map((tool) => ({
...tool, ...tool,
isPromoted: hasMatchedUserTag({ userTags, targetTags: tool.promoteTags }) isPromoted: hasMatchedUserTag({ userTags, targetTags: tool.promoteTags })
})); }))
);
} }
export default NextAPI(handler); export default NextAPI(handler);
async function getActiveDebugSource(tmbId: string) {
const status = await pluginClient.getDebugSessionStatus({ tmbId }).catch(() => undefined);
if (
status?.enabled &&
(status.status === 'enabled' || status.status === 'connected') &&
isDebugToolSource(status.source)
) {
return status.source;
}
}
...@@ -10,6 +10,7 @@ import { ...@@ -10,6 +10,7 @@ import {
type GetTeamToolVersionsResponseType type GetTeamToolVersionsResponseType
} from '@fastgpt/global/openapi/core/plugin/team/tool/api'; } from '@fastgpt/global/openapi/core/plugin/team/tool/api';
import { parseApiInput } from '@fastgpt/service/common/zod/requestParseError'; import { parseApiInput } from '@fastgpt/service/common/zod/requestParseError';
import { isDebugToolSource } from '@fastgpt/global/core/app/tool/utils';
export type getSystemToolVersionsQuery = GetTeamToolVersionsQueryType; export type getSystemToolVersionsQuery = GetTeamToolVersionsQueryType;
...@@ -33,7 +34,7 @@ async function handler( ...@@ -33,7 +34,7 @@ async function handler(
const systemToolRepo = SystemToolRepo.getInstance(); const systemToolRepo = SystemToolRepo.getInstance();
const versions = await systemToolRepo.getVersions({ const versions = await systemToolRepo.getVersions({
pluginId: toolId, pluginId: toolId,
source: source === 'team' ? teamId : 'system', source: getQuerySource({ source, teamId }),
lang lang
}); });
...@@ -41,3 +42,9 @@ async function handler( ...@@ -41,3 +42,9 @@ async function handler(
} }
export default NextAPI(handler); export default NextAPI(handler);
function getQuerySource({ source, teamId }: { source?: string; teamId: string }) {
if (source === 'team') return teamId;
if (isDebugToolSource(source)) return source;
return 'system';
}
import { NextAPI } from '@/service/middleware/entry';
import { useIPFrequencyLimit } from '@fastgpt/service/common/middle/reqFrequencyLimit';
import { parseApiInput } from '@fastgpt/service/common/zod/requestParseError';
import { pluginClient } from '@fastgpt/service/thirdProvider/fastgptPlugin';
import type { ApiRequestProps } from '@fastgpt/service/type/next';
import { assertCommercialPluginDebugEnabled } from '@/service/core/plugin/debug/authCommercialDebug';
import {
ExchangePluginDebugConnectionKeyBodySchema,
ExchangePluginDebugConnectionKeyQuerySchema,
ExchangePluginDebugConnectionKeyResponseSchema,
type ExchangePluginDebugConnectionKeyBodyType,
type ExchangePluginDebugConnectionKeyQueryType,
type ExchangePluginDebugConnectionKeyResponseType
} from '@fastgpt/global/openapi/core/plugin/debug/api';
export type ExchangePluginDebugConnectionKeyBody = ExchangePluginDebugConnectionKeyBodyType;
export type ExchangePluginDebugConnectionKeyQuery = ExchangePluginDebugConnectionKeyQueryType;
export type ExchangePluginDebugConnectionKeyResponse = ExchangePluginDebugConnectionKeyResponseType;
async function handler(
req: ApiRequestProps<ExchangePluginDebugConnectionKeyBody, ExchangePluginDebugConnectionKeyQuery>
): Promise<ExchangePluginDebugConnectionKeyResponse> {
const input =
req.method === 'GET'
? parseApiInput({
req,
querySchema: ExchangePluginDebugConnectionKeyQuerySchema
}).query
: parseApiInput({
req,
bodySchema: ExchangePluginDebugConnectionKeyBodySchema
}).body;
assertCommercialPluginDebugEnabled();
const result = await pluginClient.exchangeDebugSessionConnectionKey({
connectionKey: input.connectionKey
});
return ExchangePluginDebugConnectionKeyResponseSchema.parse(result);
}
export default NextAPI(
useIPFrequencyLimit({
id: 'plugin-debug-channel-connection-key-exchange',
seconds: 60,
limit: 60,
force: true
}),
handler
);
import { NextAPI } from '@/service/middleware/entry';
import { authCert } from '@fastgpt/service/support/permission/auth/common';
import { parseApiInput } from '@fastgpt/service/common/zod/requestParseError';
import { pluginClient } from '@fastgpt/service/thirdProvider/fastgptPlugin';
import type { ApiRequestProps } from '@fastgpt/service/type/next';
import { buildPluginDebugConnectionUrl } from '@/service/core/plugin/debug/connectionUrl';
import { assertCommercialPluginDebugEnabled } from '@/service/core/plugin/debug/authCommercialDebug';
import {
EnablePluginDebugChannelBodySchema,
EnablePluginDebugChannelResponseSchema,
type EnablePluginDebugChannelBodyType,
type EnablePluginDebugChannelResponseType
} from '@fastgpt/global/openapi/core/plugin/debug/api';
export type EnablePluginDebugChannelBody = EnablePluginDebugChannelBodyType;
export type EnablePluginDebugChannelResponse = EnablePluginDebugChannelResponseType;
async function handler(
req: ApiRequestProps<EnablePluginDebugChannelBody>
): Promise<EnablePluginDebugChannelResponse> {
parseApiInput({
req,
bodySchema: EnablePluginDebugChannelBodySchema
});
const { tmbId } = await authCert({ req, authToken: true });
assertCommercialPluginDebugEnabled();
const result = await pluginClient.createDebugSession({ tmbId });
const connectionUrl = buildPluginDebugConnectionUrl({
req,
connectionKey: result.connectionKey
});
return EnablePluginDebugChannelResponseSchema.parse({
...result,
connectionUrl
});
}
export default NextAPI(handler);
import { NextAPI } from '@/service/middleware/entry';
import { authCert } from '@fastgpt/service/support/permission/auth/common';
import { parseApiInput } from '@fastgpt/service/common/zod/requestParseError';
import { pluginClient } from '@fastgpt/service/thirdProvider/fastgptPlugin';
import type { ApiRequestProps } from '@fastgpt/service/type/next';
import { isProVersion } from '@fastgpt/service/common/system/constants';
import {
GetPluginDebugChannelQuerySchema,
GetPluginDebugChannelResponseSchema,
type GetPluginDebugChannelQueryType,
type GetPluginDebugChannelResponseType
} from '@fastgpt/global/openapi/core/plugin/debug/api';
export type GetPluginDebugChannelQuery = GetPluginDebugChannelQueryType;
export type GetPluginDebugChannelResponse = GetPluginDebugChannelResponseType;
function isNotFoundError(error: unknown) {
if (error instanceof Error && /not found|404/i.test(error.message)) return true;
if (!error || typeof error !== 'object') return false;
const status = (error as { status?: unknown; statusCode?: unknown; code?: unknown }).status;
const statusCode = (error as { status?: unknown; statusCode?: unknown; code?: unknown })
.statusCode;
const code = (error as { status?: unknown; statusCode?: unknown; code?: unknown }).code;
return status === 404 || statusCode === 404 || code === 404;
}
async function handler(
req: ApiRequestProps<Record<string, never>, GetPluginDebugChannelQuery>
): Promise<GetPluginDebugChannelResponse> {
parseApiInput({
req,
querySchema: GetPluginDebugChannelQuerySchema
});
const { tmbId } = await authCert({ req, authToken: true });
if (!isProVersion()) {
return GetPluginDebugChannelResponseSchema.parse({
tmbId,
status: 'revoked',
enabled: false,
plugins: []
});
}
const result = await pluginClient.getDebugSessionStatus({ tmbId }).catch((error) => {
if (isNotFoundError(error)) {
return {
tmbId,
status: 'revoked',
enabled: false,
plugins: []
};
}
throw error;
});
return GetPluginDebugChannelResponseSchema.parse(result);
}
export default NextAPI(handler);
import { NextAPI } from '@/service/middleware/entry';
import { authCert } from '@fastgpt/service/support/permission/auth/common';
import { parseApiInput } from '@fastgpt/service/common/zod/requestParseError';
import { pluginClient } from '@fastgpt/service/thirdProvider/fastgptPlugin';
import type { ApiRequestProps } from '@fastgpt/service/type/next';
import { buildPluginDebugConnectionUrl } from '@/service/core/plugin/debug/connectionUrl';
import { assertCommercialPluginDebugEnabled } from '@/service/core/plugin/debug/authCommercialDebug';
import {
RefreshPluginDebugConnectionKeyBodySchema,
RefreshPluginDebugConnectionKeyResponseSchema,
type RefreshPluginDebugConnectionKeyBodyType,
type RefreshPluginDebugConnectionKeyResponseType
} from '@fastgpt/global/openapi/core/plugin/debug/api';
export type RefreshPluginDebugConnectionKeyBody = RefreshPluginDebugConnectionKeyBodyType;
export type RefreshPluginDebugConnectionKeyResponse = RefreshPluginDebugConnectionKeyResponseType;
async function handler(
req: ApiRequestProps<RefreshPluginDebugConnectionKeyBody>
): Promise<RefreshPluginDebugConnectionKeyResponse> {
parseApiInput({
req,
bodySchema: RefreshPluginDebugConnectionKeyBodySchema
});
const { tmbId } = await authCert({ req, authToken: true });
assertCommercialPluginDebugEnabled();
const result = await pluginClient.refreshDebugSessionKey({ tmbId });
const connectionUrl = buildPluginDebugConnectionUrl({
req,
connectionKey: result.connectionKey
});
return RefreshPluginDebugConnectionKeyResponseSchema.parse({
...result,
connectionUrl
});
}
export default NextAPI(handler);
import { NextAPI } from '@/service/middleware/entry';
import { authCert } from '@fastgpt/service/support/permission/auth/common';
import { parseApiInput } from '@fastgpt/service/common/zod/requestParseError';
import { pluginClient } from '@fastgpt/service/thirdProvider/fastgptPlugin';
import type { ApiRequestProps } from '@fastgpt/service/type/next';
import { isProVersion } from '@fastgpt/service/common/system/constants';
import {
RevokePluginDebugChannelBodySchema,
RevokePluginDebugChannelResponseSchema,
type RevokePluginDebugChannelBodyType,
type RevokePluginDebugChannelResponseType
} from '@fastgpt/global/openapi/core/plugin/debug/api';
export type RevokePluginDebugChannelBody = RevokePluginDebugChannelBodyType;
export type RevokePluginDebugChannelResponse = RevokePluginDebugChannelResponseType;
function isNotFoundError(error: unknown) {
if (error instanceof Error && /not found|404/i.test(error.message)) return true;
if (!error || typeof error !== 'object') return false;
const status = (error as { status?: unknown; statusCode?: unknown; code?: unknown }).status;
const statusCode = (error as { status?: unknown; statusCode?: unknown; code?: unknown })
.statusCode;
const code = (error as { status?: unknown; statusCode?: unknown; code?: unknown }).code;
return status === 404 || statusCode === 404 || code === 404;
}
async function handler(
req: ApiRequestProps<RevokePluginDebugChannelBody>
): Promise<RevokePluginDebugChannelResponse> {
parseApiInput({
req,
bodySchema: RevokePluginDebugChannelBodySchema
});
const { tmbId } = await authCert({ req, authToken: true });
if (!isProVersion()) {
return RevokePluginDebugChannelResponseSchema.parse({
revoked: false
});
}
const result = await pluginClient
.revokeDebugSession({
tmbId,
reason: 'user-revoke'
})
.catch((error) => {
// 关闭调试是用户侧清理动作;通道已释放时,也应允许前端清掉本地调试态。
if (isNotFoundError(error)) {
return {
revoked: false
};
}
throw error;
});
return RevokePluginDebugChannelResponseSchema.parse(result);
}
export default NextAPI(handler);
...@@ -25,8 +25,10 @@ import { serviceEnv } from '@fastgpt/service/env'; ...@@ -25,8 +25,10 @@ import { serviceEnv } from '@fastgpt/service/env';
import { hasAIProxyApiEndpoint } from '@fastgpt/service/thirdProvider/aiproxy/config'; import { hasAIProxyApiEndpoint } from '@fastgpt/service/thirdProvider/aiproxy/config';
import { appEnv } from '@/env'; import { appEnv } from '@/env';
import { pluginTagList } from '@fastgpt/global/sdk/fastgpt-plugin'; import { pluginTagList } from '@fastgpt/global/sdk/fastgpt-plugin';
import { pluginClient } from '@fastgpt/service/thirdProvider/fastgptPlugin';
const logger = getLogger(LogCategories.SYSTEM); const logger = getLogger(LogCategories.SYSTEM);
const pluginFeaturesProbeTimeoutMs = 3000;
const defaultOpenSourceLoginGuideDocUrl = const defaultOpenSourceLoginGuideDocUrl =
'https://doc.fastgpt.io/zh-CN/guide/version/cloud/faq#%E8%B4%A6%E5%8F%B7%E7%99%BB%E5%BD%95%E9%97%AE%E9%A2%98'; 'https://doc.fastgpt.io/zh-CN/guide/version/cloud/faq#%E8%B4%A6%E5%8F%B7%E7%99%BB%E5%BD%95%E9%97%AE%E9%A2%98';
...@@ -141,11 +143,24 @@ const defaultFeConfigs: FastGPTFeConfigsType = { ...@@ -141,11 +143,24 @@ const defaultFeConfigs: FastGPTFeConfigsType = {
uploadFileMaxAmount: serviceEnv.UPLOAD_FILE_MAX_AMOUNT uploadFileMaxAmount: serviceEnv.UPLOAD_FILE_MAX_AMOUNT
}; };
async function getPluginRemoteDebugEnabled() {
try {
const features = await pluginClient.getPluginServiceFeatures({
signal: AbortSignal.timeout(pluginFeaturesProbeTimeoutMs)
});
return features.remoteDebug === true;
} catch (error) {
logger.warn('Plugin service features resolve failed', { error });
return false;
}
}
export async function initSystemConfig() { export async function initSystemConfig() {
// load config // load config
const [{ fastgptConfig, licenseData }, fileConfig] = await Promise.all([ const [{ fastgptConfig, licenseData }, fileConfig, pluginRemoteDebug] = await Promise.all([
getFastGPTConfigFromDB(), getFastGPTConfigFromDB(),
readConfigData('config.json') readConfigData('config.json'),
getPluginRemoteDebugEnabled()
]); ]);
global.licenseData = licenseData; global.licenseData = licenseData;
...@@ -169,6 +184,7 @@ export async function initSystemConfig() { ...@@ -169,6 +184,7 @@ export async function initSystemConfig() {
show_discount_coupon: appEnv.SHOW_DISCOUNT_COUPON, show_discount_coupon: appEnv.SHOW_DISCOUNT_COUPON,
show_dataset_enhance: licenseData?.functions?.datasetEnhance, show_dataset_enhance: licenseData?.functions?.datasetEnhance,
show_batch_eval: licenseData?.functions?.batchEval, show_batch_eval: licenseData?.functions?.batchEval,
pluginRemoteDebug,
payFormUrl: appEnv.PAY_FORM_URL || '', payFormUrl: appEnv.PAY_FORM_URL || '',
agentSandboxFree: appEnv.AGENT_SANDBOX_FREE_TIP, agentSandboxFree: appEnv.AGENT_SANDBOX_FREE_TIP,
......
import { SystemErrEnum } from '@fastgpt/global/common/error/code/system';
/**
* 系统工具远程调试依赖商业版能力;API 层统一拦截,避免绕过前端直接创建或使用调试通道。
*/
export function assertCommercialPluginDebugEnabled() {
if (!global.feConfigs?.isPlus) {
throw SystemErrEnum.commercialFeature;
}
}
import { serviceEnv } from '@fastgpt/service/env';
import type { ApiRequestProps } from '@fastgpt/service/type/next';
const getHeaderValue = (value?: string | string[]) => (Array.isArray(value) ? value[0] : value);
const trimSlash = (value: string) => value.replace(/\/+$/, '');
const getRequestOrigin = (req: ApiRequestProps) => {
const forwardedProto = getHeaderValue(req.headers['x-forwarded-proto'])?.split(',')[0]?.trim();
const forwardedHost = getHeaderValue(req.headers['x-forwarded-host'])?.split(',')[0]?.trim();
const host = forwardedHost || getHeaderValue(req.headers.host)?.trim();
if (host) {
const protocol =
forwardedProto ||
(host.startsWith('localhost') || host.startsWith('127.0.0.1') ? 'http' : 'https');
return `${protocol}://${host}`;
}
return serviceEnv.FE_DOMAIN ? trimSlash(serviceEnv.FE_DOMAIN) : '';
};
/**
* 生成给本地 CLI 使用的 FastGPT HTTP 连接入口。
* CLI 会直接 GET 这个地址,再由 FastGPT 代理向 plugin-server 兑换短期 connectToken。
*/
export const buildPluginDebugConnectionUrl = ({
req,
connectionKey
}: {
req: ApiRequestProps;
connectionKey?: string;
}) => {
if (!connectionKey) return;
const origin = getRequestOrigin(req);
if (!origin) return;
const url = new URL(
`${serviceEnv.NEXT_PUBLIC_BASE_URL || ''}/api/plugin/debug-channel/connection-key:exchange`,
origin
);
url.searchParams.set('connectionKey', connectionKey);
return url.toString();
};
import { useToast } from '@fastgpt/web/hooks/useToast'; import { useToast } from '@fastgpt/web/hooks/useToast';
import { useMutation } from '@tanstack/react-query'; import { useMutation } from '@tanstack/react-query';
import type { UseMutationOptions } from '@tanstack/react-query'; import type { UseMutationOptions } from '@tanstack/react-query';
import { getErrText } from '@fastgpt/global/common/error/utils'; import { getErrText, ToastHandledError } from '@fastgpt/global/common/error/utils';
import { useTranslation } from 'next-i18next'; import { useTranslation } from 'next-i18next';
interface Props extends UseMutationOptions<any, any, any, any> { interface Props extends UseMutationOptions<any, any, any, any> {
...@@ -24,6 +24,7 @@ export const useRequest = ({ successToast, errorToast, onSuccess, onError, ...pr ...@@ -24,6 +24,7 @@ export const useRequest = ({ successToast, errorToast, onSuccess, onError, ...pr
}, },
onError(err: any, variables: void, context: unknown) { onError(err: any, variables: void, context: unknown) {
onError?.(err, variables, context); onError?.(err, variables, context);
if (err instanceof ToastHandledError) return;
if (errorToast !== undefined) { if (errorToast !== undefined) {
const errText = t(getErrText(err, errorToast || '') as any); const errText = t(getErrText(err, errorToast || '') as any);
......
...@@ -8,7 +8,6 @@ import { FlowNodeTypeEnum } from '@fastgpt/global/core/workflow/node/constant'; ...@@ -8,7 +8,6 @@ import { FlowNodeTypeEnum } from '@fastgpt/global/core/workflow/node/constant';
import { FlowNodeTemplateTypeEnum } from '@fastgpt/global/core/workflow/constants'; import { FlowNodeTemplateTypeEnum } from '@fastgpt/global/core/workflow/constants';
import { AppTypeEnum } from '@fastgpt/global/core/app/constants'; import { AppTypeEnum } from '@fastgpt/global/core/app/constants';
import type { import type {
GetPathProps,
ParentIdType, ParentIdType,
ParentTreePathItemType ParentTreePathItemType
} from '@fastgpt/global/common/parentFolder/type'; } from '@fastgpt/global/common/parentFolder/type';
...@@ -16,7 +15,8 @@ import { AppToolSourceEnum } from '@fastgpt/global/core/app/tool/constants'; ...@@ -16,7 +15,8 @@ import { AppToolSourceEnum } from '@fastgpt/global/core/app/tool/constants';
import { getMcpChildren } from './mcpTools'; import { getMcpChildren } from './mcpTools';
import type { import type {
GetPreviewNodeQuery, GetPreviewNodeQuery,
GetSystemToolTemplatesBodyType GetSystemToolTemplatesBodyType,
GetToolPathQueryType
} from '@fastgpt/global/openapi/core/app/tool/api'; } from '@fastgpt/global/openapi/core/app/tool/api';
/* ============ team plugin ============== */ /* ============ team plugin ============== */
...@@ -88,7 +88,7 @@ export const getTeamAppTemplates = async (data?: { ...@@ -88,7 +88,7 @@ export const getTeamAppTemplates = async (data?: {
export const getAppToolTemplates = (data: GetSystemToolTemplatesBodyType) => export const getAppToolTemplates = (data: GetSystemToolTemplatesBodyType) =>
POST<NodeTemplateListItemType[]>('/core/app/tool/getSystemToolTemplates', data); POST<NodeTemplateListItemType[]>('/core/app/tool/getSystemToolTemplates', data);
export const getAppToolPaths = (data: GetPathProps) => { export const getAppToolPaths = (data: GetToolPathQueryType) => {
if (!data.sourceId) return Promise.resolve<ParentTreePathItemType[]>([]); if (!data.sourceId) return Promise.resolve<ParentTreePathItemType[]>([]);
return GET<ParentTreePathItemType[]>('/core/app/tool/path', data); return GET<ParentTreePathItemType[]>('/core/app/tool/path', data);
}; };
......
import { GET, POST } from '@/web/common/api/request';
import type {
EnablePluginDebugChannelBodyType,
EnablePluginDebugChannelResponseType,
GetPluginDebugChannelResponseType,
RefreshPluginDebugConnectionKeyBodyType,
RefreshPluginDebugConnectionKeyResponseType,
RevokePluginDebugChannelResponseType
} from '@fastgpt/global/openapi/core/plugin/debug/api';
export const enablePluginDebugChannel = (data: EnablePluginDebugChannelBodyType = {}) =>
POST<EnablePluginDebugChannelResponseType>('/plugin/debug-channel/enable', data);
export const refreshPluginDebugConnectionKey = (
data: RefreshPluginDebugConnectionKeyBodyType = {}
) => POST<RefreshPluginDebugConnectionKeyResponseType>('/plugin/debug-channel/key:refresh', data);
export const getPluginDebugChannel = () =>
GET<GetPluginDebugChannelResponseType>('/plugin/debug-channel', {});
export const revokePluginDebugChannel = () =>
POST<RevokePluginDebugChannelResponseType>('/plugin/debug-channel/revoke', {});
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { Call } from '@test/utils/request';
import { FlowNodeTypeEnum } from '@fastgpt/global/core/workflow/node/constant';
const mocks = vi.hoisted(() => ({
getClientToolPreviewNode: vi.fn(),
getLocale: vi.fn(),
authApp: vi.fn()
}));
vi.mock('@fastgpt/service/core/app/tool/utils/client', () => ({
getClientToolPreviewNode: mocks.getClientToolPreviewNode
}));
vi.mock('@fastgpt/service/common/middle/i18n', () => ({
getLocale: mocks.getLocale
}));
vi.mock('@fastgpt/service/support/permission/app/auth', () => ({
authApp: mocks.authApp
}));
import handler from '@/pages/api/core/app/tool/getPreviewNode';
describe('get preview node handler', () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.getLocale.mockReturnValue('zh');
mocks.getClientToolPreviewNode.mockResolvedValue({
id: 'node-id',
pluginId: 'systemTool-weather',
source: 'debug:tmbId:tmb-1',
flowNodeType: FlowNodeTypeEnum.tool,
name: 'Weather',
inputs: [],
outputs: []
});
});
it('passes debug source explicitly without encoding it into appId', async () => {
const res = await Call(handler, {
query: {
appId: 'systemTool-weather',
versionId: '',
source: 'debug:tmbId:tmb-1'
}
});
expect(res.code).toBe(200);
expect(mocks.getClientToolPreviewNode).toHaveBeenCalledWith({
appId: 'systemTool-weather',
versionId: '',
getLatestVersion: undefined,
lang: 'zh',
source: 'debug:tmbId:tmb-1'
});
expect(res.data).toMatchObject({
pluginId: 'systemTool-weather',
source: 'debug:tmbId:tmb-1'
});
});
});
...@@ -10,7 +10,10 @@ const mocks = vi.hoisted(() => ({ ...@@ -10,7 +10,10 @@ const mocks = vi.hoisted(() => ({
getSystemToolDetail: vi.fn(), getSystemToolDetail: vi.fn(),
getSystemToolDisplayInfo: vi.fn(), getSystemToolDisplayInfo: vi.fn(),
getSystemToolDisplayInfoWithChildIcons: vi.fn(), getSystemToolDisplayInfoWithChildIcons: vi.fn(),
getInstance: vi.fn() getInstance: vi.fn(),
pluginClient: {
getDebugSessionStatus: vi.fn()
}
})); }));
vi.mock('@fastgpt/service/support/permission/auth/common', () => ({ vi.mock('@fastgpt/service/support/permission/auth/common', () => ({
...@@ -31,6 +34,10 @@ vi.mock('@fastgpt/service/core/app/tool/systemTool/systemTool.repo', () => ({ ...@@ -31,6 +34,10 @@ vi.mock('@fastgpt/service/core/app/tool/systemTool/systemTool.repo', () => ({
} }
})); }));
vi.mock('@fastgpt/service/thirdProvider/fastgptPlugin', () => ({
pluginClient: mocks.pluginClient
}));
import { import {
handler, handler,
type GetSystemPluginTemplatesBody type GetSystemPluginTemplatesBody
...@@ -52,6 +59,12 @@ describe('get system tool templates handler', () => { ...@@ -52,6 +59,12 @@ describe('get system tool templates handler', () => {
getSystemToolDisplayInfo: mocks.getSystemToolDisplayInfo, getSystemToolDisplayInfo: mocks.getSystemToolDisplayInfo,
getSystemToolDisplayInfoWithChildIcons: mocks.getSystemToolDisplayInfoWithChildIcons getSystemToolDisplayInfoWithChildIcons: mocks.getSystemToolDisplayInfoWithChildIcons
}); });
mocks.pluginClient.getDebugSessionStatus.mockResolvedValue({
tmbId: 'tmb-1',
status: 'revoked',
enabled: false,
plugins: []
});
}); });
it('filters root system tools by searchKey', async () => { it('filters root system tools by searchKey', async () => {
...@@ -96,11 +109,100 @@ describe('get system tool templates handler', () => { ...@@ -96,11 +109,100 @@ describe('get system tool templates handler', () => {
expect(result.map((item) => item.id)).toEqual(['weather']); expect(result.map((item) => item.id)).toEqual(['weather']);
expect(mocks.getSystemToolList).toHaveBeenCalledWith({ expect(mocks.getSystemToolList).toHaveBeenCalledWith({
lang: 'zh', lang: 'zh',
op: 'or',
sources: ['system', 'team-1'], sources: ['system', 'team-1'],
tags: ['life'] tags: ['life']
}); });
}); });
it('keeps production tools when a debug session is active', async () => {
mocks.pluginClient.getDebugSessionStatus.mockResolvedValueOnce({
tmbId: 'tmb-1',
source: 'debug:tmbId:tmb-1',
status: 'connected',
enabled: true,
plugins: []
});
mocks.getSystemToolList.mockResolvedValue([
{
id: 'debug-tool',
source: 'debug:tmbId:tmb-1',
name: 'Debug Tool',
intro: '',
toolDescription: '',
isToolSet: false,
status: PluginStatusEnum.Normal,
tags: []
},
{
id: 'system-tool',
source: 'system',
name: 'System Tool',
intro: '',
toolDescription: '',
isToolSet: false,
status: PluginStatusEnum.Normal,
tags: []
}
]);
const result = await handler({
body: {}
} as ApiRequestProps<GetSystemPluginTemplatesBody>);
expect(result.map((item) => item.id)).toEqual(['debug-tool', 'system-tool']);
expect(result[0]?.source).toBe('debug:tmbId:tmb-1');
expect(mocks.pluginClient.getDebugSessionStatus).toHaveBeenCalledWith({
tmbId: 'tmb-1'
});
expect(mocks.getSystemToolList).toHaveBeenCalledWith({
lang: 'zh',
op: 'or',
sources: ['system', 'team-1', 'debug:tmbId:tmb-1'],
tags: undefined
});
});
it('keeps production tools when debug channel is not active', async () => {
mocks.getSystemToolList.mockResolvedValue([]);
await handler({
body: {}
} as ApiRequestProps<GetSystemPluginTemplatesBody>);
expect(mocks.getSystemToolList).toHaveBeenCalledWith({
lang: 'zh',
op: 'or',
sources: ['system', 'team-1'],
tags: undefined
});
});
it('automatically appends the active debug source for root templates', async () => {
mocks.pluginClient.getDebugSessionStatus.mockResolvedValueOnce({
tmbId: 'tmb-1',
source: 'debug:tmbId:tmb-1',
status: 'connected',
enabled: true,
plugins: []
});
mocks.getSystemToolList.mockResolvedValue([]);
await handler({
body: {}
} as ApiRequestProps<GetSystemPluginTemplatesBody>);
expect(mocks.pluginClient.getDebugSessionStatus).toHaveBeenCalledWith({
tmbId: 'tmb-1'
});
expect(mocks.getSystemToolList).toHaveBeenCalledWith({
lang: 'zh',
op: 'or',
sources: ['system', 'team-1', 'debug:tmbId:tmb-1'],
tags: undefined
});
});
it('filters toolset children by escaped searchKey', async () => { it('filters toolset children by escaped searchKey', async () => {
mocks.getSystemToolDisplayInfoWithChildIcons.mockResolvedValue({ mocks.getSystemToolDisplayInfoWithChildIcons.mockResolvedValue({
id: 'toolset', id: 'toolset',
...@@ -155,6 +257,50 @@ describe('get system tool templates handler', () => { ...@@ -155,6 +257,50 @@ describe('get system tool templates handler', () => {
expect(mocks.getSystemToolDetail).not.toHaveBeenCalled(); expect(mocks.getSystemToolDetail).not.toHaveBeenCalled();
}); });
it('uses the parent tool source when opening a production toolset during debug', async () => {
mocks.pluginClient.getDebugSessionStatus.mockResolvedValueOnce({
tmbId: 'tmb-1',
source: 'debug:tmbId:tmb-1',
status: 'connected',
enabled: true,
plugins: []
});
mocks.getSystemToolDisplayInfoWithChildIcons.mockResolvedValue({
id: 'systemTool-toolset',
name: 'Production Toolset',
intro: '',
avatar: '',
status: PluginStatusEnum.Normal,
source: 'system',
children: [
{
id: 'child',
name: 'Production Child',
status: PluginStatusEnum.Normal,
description: '',
currentCost: 0,
systemKeyCost: 0
}
],
hasTokenFee: false
});
const result = await handler({
body: {
parentId: 'systemTool-toolset',
source: 'system'
}
} as ApiRequestProps<GetSystemPluginTemplatesBody>);
expect(result.map((item) => item.id)).toEqual(['systemTool-toolset/child']);
expect(mocks.pluginClient.getDebugSessionStatus).not.toHaveBeenCalled();
expect(mocks.getSystemToolDisplayInfoWithChildIcons).toHaveBeenCalledWith({
pluginId: 'systemTool-toolset',
lang: 'zh',
source: 'system'
});
});
it('filters soon offline and offline tools from root system tool candidates', async () => { it('filters soon offline and offline tools from root system tool candidates', async () => {
mocks.getSystemToolList.mockResolvedValue([ mocks.getSystemToolList.mockResolvedValue([
{ {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment