Commit 6724a1e6 by Archer Committed by GitHub

feat: support source typed skill edit chat (#7185)

* feat: support source typed skill edit chat

* fix: align source-aware sandbox tests

* fix: stabilize beta6 migration sandbox updates

* feat: migrate chat sandbox source handling

* fix: type sandbox migration object ids

* docs: add sandbox package mirror config

* test: align sandbox runtime spec with source target
parent bc905bad
...@@ -210,7 +210,8 @@ if ( ...@@ -210,7 +210,8 @@ if (
const { input, response, durationSeconds } = await callSandboxTool({ const { input, response, durationSeconds } = await callSandboxTool({
toolName: call.function.name, toolName: call.function.name,
rawArgs: call.function.arguments ?? '', rawArgs: call.function.arguments ?? '',
appId: String(workflowProps.runningAppInfo.id), sourceType: workflowProps.runningAppInfo.sourceType,
sourceId: workflowProps.runningAppInfo.sourceId,
userId: String(workflowProps.uid), userId: String(workflowProps.uid),
chatId: workflowProps.chatId chatId: workflowProps.chatId
}); });
...@@ -239,7 +240,8 @@ if (toolId === SANDBOX_GET_FILE_URL_TOOL_NAME) { ...@@ -239,7 +240,8 @@ if (toolId === SANDBOX_GET_FILE_URL_TOOL_NAME) {
const result = await dispatchSandboxGetFileUrl({ const result = await dispatchSandboxGetFileUrl({
filePath: toolParams.data.paths[0], // Agent 模式单文件路径 filePath: toolParams.data.paths[0], // Agent 模式单文件路径
appId: runningAppInfo.id, sourceType: runningAppInfo.sourceType,
sourceId: runningAppInfo.sourceId,
userId: props.uid, userId: props.uid,
chatId, chatId,
lang: props.lang lang: props.lang
......
...@@ -6,12 +6,12 @@ ...@@ -6,12 +6,12 @@
**Redis Key 结构:** **Redis Key 结构:**
```typescript ```typescript
// Key 格式: agent_runtime_stopping:{appId}:{chatId} // Key 格式: agent_runtime_stopping:{sourceType}:{sourceId}:{chatId}
const WORKFLOW_STATUS_PREFIX = 'agent_runtime_stopping'; const WORKFLOW_STATUS_PREFIX = 'agent_runtime_stopping';
type WorkflowStatusKey = `${typeof WORKFLOW_STATUS_PREFIX}:${string}:${string}`; type WorkflowStatusKey = `${typeof WORKFLOW_STATUS_PREFIX}:${string}:${string}:${string}`;
// 示例: agent_runtime_stopping:app_123456:chat_789012 // 示例: agent_runtime_stopping:app:app_123456:chat_789012
``` ```
**状态值设计:** **状态值设计:**
...@@ -22,7 +22,8 @@ type WorkflowStatusKey = `${typeof WORKFLOW_STATUS_PREFIX}:${string}:${string}`; ...@@ -22,7 +22,8 @@ type WorkflowStatusKey = `${typeof WORKFLOW_STATUS_PREFIX}:${string}:${string}`;
**参数类型定义:** **参数类型定义:**
```typescript ```typescript
type WorkflowStatusParams = { type WorkflowStatusParams = {
appId: string; sourceType: ChatSourceTypeEnum;
sourceId: string;
chatId: string; chatId: string;
}; };
``` ```
...@@ -45,23 +46,23 @@ type WorkflowStatusParams = { ...@@ -45,23 +46,23 @@ type WorkflowStatusParams = {
**1. setAgentRuntimeStop** **1. setAgentRuntimeStop**
- **功能**: 设置停止标志 - **功能**: 设置停止标志
- **参数**: `{ appId, chatId }` - **参数**: `{ sourceType, sourceId, chatId }`
- **实现**: 使用 `SETEX` 命令,设置键值为 1,TTL 60 秒 - **实现**: 使用 `SETEX` 命令,设置键值为 1,TTL 60 秒
**2. shouldWorkflowStop** **2. shouldWorkflowStop**
- **功能**: 检查工作流是否应该停止 - **功能**: 检查工作流是否应该停止
- **参数**: `{ appId, chatId }` - **参数**: `{ sourceType, sourceId, chatId }`
- **返回**: `Promise<boolean>` - true=应该停止, false=继续运行 - **返回**: `Promise<boolean>` - true=应该停止, false=继续运行
- **实现**: GET 命令获取键值,存在则返回 true - **实现**: GET 命令获取键值,存在则返回 true
**3. delAgentRuntimeStopSign** **3. delAgentRuntimeStopSign**
- **功能**: 删除停止标志 - **功能**: 删除停止标志
- **参数**: `{ appId, chatId }` - **参数**: `{ sourceType, sourceId, chatId }`
- **实现**: DEL 命令删除键 - **实现**: DEL 命令删除键
**4. waitForWorkflowComplete** **4. waitForWorkflowComplete**
- **功能**: 等待工作流完成(停止标志被删除) - **功能**: 等待工作流完成(停止标志被删除)
- **参数**: `{ appId, chatId, timeout?, pollInterval? }` - **参数**: `{ sourceType, sourceId, chatId, timeout?, pollInterval? }`
- **实现**: 轮询检查停止标志是否被删除,超时返回 - **实现**: 轮询检查停止标志是否被删除,超时返回
### 1.4 边界情况处理 ### 1.4 边界情况处理
...@@ -303,7 +304,8 @@ const checkStoppingTimer = ...@@ -303,7 +304,8 @@ const checkStoppingTimer =
apiVersion === 'v2' apiVersion === 'v2'
? setInterval(async () => { ? setInterval(async () => {
stopping = await shouldWorkflowStop({ stopping = await shouldWorkflowStop({
appId: runningAppInfo.id, sourceType: runningAppInfo.sourceType,
sourceId: runningAppInfo.sourceId,
chatId chatId
}); });
}, 100) }, 100)
...@@ -340,7 +342,8 @@ return runWorkflow({ ...@@ -340,7 +342,8 @@ return runWorkflow({
// 工作流完成后删除 Redis 记录 // 工作流完成后删除 Redis 记录
await delAgentRuntimeStopSign({ await delAgentRuntimeStopSign({
appId: runningAppInfo.id, sourceType: runningAppInfo.sourceType,
sourceId: runningAppInfo.sourceId,
chatId chatId
}); });
}); });
...@@ -362,7 +365,8 @@ private async checkNodeCanRun( ...@@ -362,7 +365,8 @@ private async checkNodeCanRun(
// Check queue status // Check queue status
if (data.maxRunTimes <= 0) { if (data.maxRunTimes <= 0) {
getLogger(LogCategories.MODULE.CHAT).error('Max run times is 0', { getLogger(LogCategories.MODULE.CHAT).error('Max run times is 0', {
appId: data.runningAppInfo.id sourceType: data.runningAppInfo.sourceType,
sourceId: data.runningAppInfo.sourceId
}); });
return; return;
} }
...@@ -370,7 +374,8 @@ private async checkNodeCanRun( ...@@ -370,7 +374,8 @@ private async checkNodeCanRun(
// 停止检测 // 停止检测
if (checkIsStopping()) { if (checkIsStopping()) {
getLogger(LogCategories.MODULE.CHAT).warn('Workflow stopped', { getLogger(LogCategories.MODULE.CHAT).warn('Workflow stopped', {
appId: data.runningAppInfo.id, sourceType: data.runningAppInfo.sourceType,
sourceId: data.runningAppInfo.sourceId,
nodeId: node.nodeId, nodeId: node.nodeId,
nodeName: node.name nodeName: node.name
}); });
...@@ -666,4 +671,3 @@ describe('Workflow Status Redis Functions', () => { ...@@ -666,4 +671,3 @@ describe('Workflow Status Redis Functions', () => {
test('should handle concurrent stop sign operations') test('should handle concurrent stop sign operations')
}); });
``` ```
...@@ -51,6 +51,10 @@ WORKFLOW_PARALLEL_MAX_CONCURRENCY=10 ...@@ -51,6 +51,10 @@ WORKFLOW_PARALLEL_MAX_CONCURRENCY=10
AGENT_SANDBOX_ARCHIVE_MAX_SIZE=50 AGENT_SANDBOX_ARCHIVE_MAX_SIZE=50
# Skill sandbox package size limit, in MB # Skill sandbox package size limit, in MB
AGENT_SANDBOX_SKILL_MAX_SIZE=10 AGENT_SANDBOX_SKILL_MAX_SIZE=10
# Registry used by npm/yarn/bun inside Agent Sandbox
AGENT_SANDBOX_NPM_REGISTRY=
# Python package index used by pip/uv inside Agent Sandbox
AGENT_SANDBOX_PYPI_INDEX_URL=
``` ```
This release adds environment variable validation. Check that both `fastgpt-app` and `fastgpt-pro` include `AES256_SECRET_KEY` and `FILE_TOKEN_KEY`, and that the values are the same in both services. This release adds environment variable validation. Check that both `fastgpt-app` and `fastgpt-pro` include `AES256_SECRET_KEY` and `FILE_TOKEN_KEY`, and that the values are the same in both services.
......
...@@ -38,6 +38,10 @@ WORKFLOW_PARALLEL_MAX_CONCURRENCY=10 ...@@ -38,6 +38,10 @@ WORKFLOW_PARALLEL_MAX_CONCURRENCY=10
AGENT_SANDBOX_ARCHIVE_MAX_SIZE=50 AGENT_SANDBOX_ARCHIVE_MAX_SIZE=50
# Skill sandbox 包大小上限,单位 MB # Skill sandbox 包大小上限,单位 MB
AGENT_SANDBOX_SKILL_MAX_SIZE=10 AGENT_SANDBOX_SKILL_MAX_SIZE=10
# Agent Sandbox 内 npm/yarn/bun 使用的 registry
AGENT_SANDBOX_NPM_REGISTRY=
# Agent Sandbox 内 pip/uv 使用的 Python package index
AGENT_SANDBOX_PYPI_INDEX_URL=
``` ```
#### Plugin 服务 #### Plugin 服务
......
...@@ -19,7 +19,63 @@ The unique index on `llm_request_records` has also changed from the single `requ ...@@ -19,7 +19,63 @@ The unique index on `llm_request_records` has also changed from the single `requ
Risk: trace records written before this upgrade do not have `teamId`, so they can no longer be queried by `requestId` after the upgrade. The UI will treat them as expired. These records already have a TTL and are intended only for temporary debugging. Export the relevant logs or keep the original request details before upgrading if you need to investigate historical calls. Risk: trace records written before this upgrade do not have `teamId`, so they can no longer be queried by `requestId` after the upgrade. The UI will treat them as expired. These records already have a TTL and are intended only for temporary debugging. Export the relevant logs or keep the original request details before upgrading if you need to investigate historical calls.
### 3. Clean up legacy Skill Debug chat data
This version migrates Skill Edit chats to the standard Chat storage model. Historical Skill Debug data wrote `skillId` into the physical `appId` field in the three Chat collections and did not include `sourceType`. Historical sandbox instance records also need `sourceType/sourceId` backfilled. After the upgrade, new Skill Edit chats will not read those legacy records, but we recommend running the root-only initialization API once to migrate sandbox instance ownership fields and clean up legacy Skill Debug chats. This endpoint is only for this upgrade migration and is not exposed as an OpenAPI endpoint.
Before running it, make sure the new Chat source indexes have been created. The initialization API defaults to dry-run mode and only reports matched records:
```bash
curl -X POST 'https://your-domain/api/admin/4150/init4150-beta6' \
-H 'Content-Type: application/json' \
-H 'rootkey: YOUR_ROOT_KEY' \
-d '{"dryRun":true}'
```
After confirming the dry-run result, set `dryRun` to `false` to run the migration and cleanup:
```bash
curl -X POST 'https://your-domain/api/admin/4150/init4150-beta6' \
-H 'Content-Type: application/json' \
-H 'rootkey: YOUR_ROOT_KEY' \
-d '{"dryRun":false}'
```
Parameters:
| Parameter | Type | Default | Description |
| --------- | ------- | ------- | -------------------------------------------------------------- |
| `dryRun` | boolean | `true` | Whether to only report matched data without executing changes. |
This endpoint always scans the full `skills` collection and does not support passing a partial Skill list. Sandbox instance migration must identify all Skills first, then treat the remaining records with `appId` as App sandboxes. Scanning only part of the Skill list could incorrectly mark unscanned Skill sandboxes as App sandboxes.
Migration logic:
1. Read all `_id` values from the `skills` collection.
2. For `agent_sandbox_instances` missing `sourceType` or `sourceId`, records matching `appId=skillId` or `metadata.skillId=skillId` are updated with `sourceType=skillEdit` and `sourceId=skillId`, and the legacy `appId` / `metadata.skillId` fields are unset.
3. Remaining sandbox instances that are still missing `sourceType` or `sourceId`, do not match a Skill, and have a non-empty `appId` are updated with `sourceType=app` and `sourceId=appId`, and the legacy `appId` / `metadata.skillId` fields are unset.
4. Sandbox instances that already have `sourceType/sourceId` but still retain legacy `appId` or `metadata.skillId` only have the legacy fields unset. Their existing standard ownership is not overwritten.
5. Orphan sandboxes with no `appId`, `appId=null`, or `appId=""`, and that cannot be associated with a Skill through `metadata.skillId`, are deleted in non-dry-run mode. This removes the remote sandbox, OpenSandbox volume, S3 archive, and Mongo record. Dry-run only reports them through `orphanMatchedCount`.
6. Legacy Skill Debug chat cleanup first removes Skill IDs that also exist in the `apps` collection, then deletes legacy `chats`, `chatitems`, `chat_item_responses`, and legacy-format Chat S3 prefixes for the remaining Skill IDs.
This endpoint does not backfill `sourceType` for existing App Chat records.
### 4. Configure package registry mirrors for Agent Sandbox
Agent Sandbox now supports package registry mirror configuration. When configured, FastGPT writes mirror configuration files for npm, yarn, bun, pip, and uv under the sandbox HOME directory during sandbox initialization. This improves dependency installation stability in private networks or cross-region network environments.
```dotenv
# Registry used by npm/yarn/bun inside Agent Sandbox
AGENT_SANDBOX_NPM_REGISTRY=
# Python package index used by pip/uv inside Agent Sandbox
AGENT_SANDBOX_PYPI_INDEX_URL=
```
The configuration is cached by content hash in the sandbox runtime state, so the same sandbox only rewrites these files when the configuration changes.
## ⚙️ Improvements ## ⚙️ Improvements
1. Chat title generation now uses the system default model configuration, making it easier to switch at runtime and manage consistently. 1. Chat title generation now uses the system default model configuration, making it easier to switch at runtime and manage consistently.
2. LLM request traces are now queried with team isolation, and the unique index is now `{ teamId, requestId }` to prevent request IDs from exposing sensitive traces across teams. 2. LLM request traces are now queried with team isolation, and the unique index is now `{ teamId, requestId }` to prevent request IDs from exposing sensitive traces across teams.
3. Skill Edit chats now use the standard Chat storage and cleanup flow, and legacy Skill Debug chats can be cleaned through the initialization API.
4. Agent Sandbox now supports npm and PyPI mirror configuration. During initialization, it writes common package manager configuration files to reduce dependency installation failures inside the sandbox.
...@@ -19,7 +19,63 @@ LLM 请求追踪记录(`llm_request_records`)新增 `teamId` 字段,`GET / ...@@ -19,7 +19,63 @@ LLM 请求追踪记录(`llm_request_records`)新增 `teamId` 字段,`GET /
风险点:升级前已写入的旧追踪记录没有 `teamId`,升级后将无法再通过 `requestId` 查询,页面会按追踪记录已过期处理。该记录本身有 TTL,仅用于临时排查模型调用详情;如需排查历史问题,请在升级前导出相关日志或保留原始请求信息。 风险点:升级前已写入的旧追踪记录没有 `teamId`,升级后将无法再通过 `requestId` 查询,页面会按追踪记录已过期处理。该记录本身有 TTL,仅用于临时排查模型调用详情;如需排查历史问题,请在升级前导出相关日志或保留原始请求信息。
### 3. 清理旧 Skill Debug 对话数据
本版本将 Skill Edit 对话迁移到标准 Chat 存储模型。历史 Skill Debug 数据曾把 `skillId` 写入 Chat 三表的物理 `appId` 字段,且没有 `sourceType`;历史 sandbox 实例也需要补齐 `sourceType/sourceId`。升级后旧 Skill Debug 对话不会被新 Skill Edit 对话读取,但建议执行一次 root-only 初始化接口完成 sandbox 实例字段迁移并清理旧 Skill Debug 对话。该接口仅用于本次升级迁移,不作为 OpenAPI 对外接口。
执行前请先确认新的 Chat source 索引已经创建完成。该初始化接口默认 dry-run,只统计不删除:
```bash
curl -X POST 'https://你的域名/api/admin/4150/init4150-beta6' \
-H 'Content-Type: application/json' \
-H 'rootkey: 你的ROOT_KEY' \
-d '{"dryRun":true}'
```
返回结果确认无误后,将 `dryRun` 改为 `false` 执行迁移和删除:
```bash
curl -X POST 'https://你的域名/api/admin/4150/init4150-beta6' \
-H 'Content-Type: application/json' \
-H 'rootkey: 你的ROOT_KEY' \
-d '{"dryRun":false}'
```
接口参数:
| 参数 | 类型 | 默认值 | 说明 |
| -------- | ------- | ------ | ------------------ |
| `dryRun` | boolean | `true` | 是否只统计不执行。 |
该接口会全量读取 `skills` 表,不支持只传部分 Skill ID。原因是 sandbox 实例迁移需要先识别所有 Skill,再把剩余未命中 Skill 且带 `appId` 的实例统一视为 App sandbox;如果只扫描部分 Skill,会把未扫描到的 Skill sandbox 误标成 App。
迁移逻辑:
1. 查询 `skills` 表拿到全部 `_id`。
2. 对缺少 `sourceType` 或 `sourceId` 的 `agent_sandbox_instances`,如果匹配 `appId=skillId` 或 `metadata.skillId=skillId`,写入 `sourceType=skillEdit` 和 `sourceId=skillId`,并清理旧 `appId` / `metadata.skillId` 字段。
3. 对剩余缺少 `sourceType` 或 `sourceId`、未命中 Skill 且存在非空 `appId` 的 sandbox 实例,写入 `sourceType=app` 和 `sourceId=appId`,并清理旧 `appId` / `metadata.skillId` 字段。
4. 对已经具备 `sourceType/sourceId` 但残留旧 `appId` 或 `metadata.skillId` 的 sandbox 实例,只清理旧字段,不覆盖现有标准归属。
5. 没有 `appId`、`appId=null` 或 `appId=""` 且无法通过 `metadata.skillId` 归属到 Skill 的 orphan sandbox,会在非 dry-run 模式下删除远端 sandbox、OpenSandbox volume、S3 归档和 Mongo 记录;dry-run 只通过 `orphanMatchedCount` 统计。
6. 清理旧 Skill Debug chat:先用 `apps` 表去掉与 App `_id` 重复的 Skill ID,再删除剩余 Skill ID 下匹配到的旧 `chats`、`chatitems`、`chat_item_responses` 和旧格式 Chat S3 文件前缀。
该接口不会回填几亿条历史 App Chat 的 `sourceType`。
### 4. Agent Sandbox 包管理镜像源配置
Agent Sandbox 新增包管理镜像源配置。配置后,Agent Sandbox 初始化时会在 sandbox HOME 下写入 npm、yarn、bun、pip 和 uv 的镜像配置文件,提升在私有网络或跨境网络环境中安装依赖的稳定性。
```dotenv
# Agent Sandbox 内 npm/yarn/bun 使用的 registry
AGENT_SANDBOX_NPM_REGISTRY=
# Agent Sandbox 内 pip/uv 使用的 Python package index
AGENT_SANDBOX_PYPI_INDEX_URL=
```
该配置会按内容 hash 缓存在 sandbox runtime state 中,同一个 sandbox 仅在配置变化时重新写入。
## ⚙️ 优化 ## ⚙️ 优化
1. 对话标题生成模型改为使用系统默认模型配置管理,便于运行时切换和统一维护。 1. 对话标题生成模型改为使用系统默认模型配置管理,便于运行时切换和统一维护。
2. LLM 请求追踪记录按团队隔离查询,唯一索引调整为 `{ teamId, requestId }`,避免 `requestId` 被其他团队复用读取敏感 trace。 2. LLM 请求追踪记录按团队隔离查询,唯一索引调整为 `{ teamId, requestId }`,避免 `requestId` 被其他团队复用读取敏感 trace。
3. Skill Edit 对话统一使用标准 Chat 存储和清理链路,历史 Skill Debug 对话可通过初始化接口清理。
4. Agent Sandbox 支持配置 npm 和 PyPI 镜像源,初始化时自动写入常见包管理器配置,减少 sandbox 内依赖安装失败。
...@@ -167,8 +167,8 @@ ...@@ -167,8 +167,8 @@
"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-09T16:03:58+08:00",
"content/plugin/system-tool-development.mdx": "2026-06-09T16:03:58+08:00", "content/plugin/system-tool-development.mdx": "2026-06-09T16:03:58+08:00",
"content/self-host/config/env.en.mdx": "2026-06-25T14:51:00+08:00", "content/self-host/config/env.en.mdx": "2026-06-26T17:38:34+08:00",
"content/self-host/config/env.mdx": "2026-06-25T14:51:00+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",
"content/self-host/config/json.mdx": "2026-06-22T11:01:59+08:00", "content/self-host/config/json.mdx": "2026-06-22T11:01:59+08:00",
"content/self-host/config/model/intro.en.mdx": "2026-06-04T16:10:15+08:00", "content/self-host/config/model/intro.en.mdx": "2026-06-04T16:10:15+08:00",
...@@ -302,8 +302,8 @@ ...@@ -302,8 +302,8 @@
"content/self-host/upgrading/4-15/41504.mdx": "2026-06-15T23:34:43+08:00", "content/self-host/upgrading/4-15/41504.mdx": "2026-06-15T23:34:43+08:00",
"content/self-host/upgrading/4-15/41505.en.mdx": "2026-06-23T13:54:06+08:00", "content/self-host/upgrading/4-15/41505.en.mdx": "2026-06-23T13:54:06+08:00",
"content/self-host/upgrading/4-15/41505.mdx": "2026-06-24T13:53:05+08:00", "content/self-host/upgrading/4-15/41505.mdx": "2026-06-24T13:53:05+08:00",
"content/self-host/upgrading/4-15/41506.en.mdx": "2026-06-25T14:51:00+08:00", "content/self-host/upgrading/4-15/41506.en.mdx": "2026-06-26T17:03:31+08:00",
"content/self-host/upgrading/4-15/41506.mdx": "2026-06-25T14:51:00+08:00", "content/self-host/upgrading/4-15/41506.mdx": "2026-06-26T17:03:31+08:00",
"content/self-host/upgrading/outdated/40.en.mdx": "2026-04-26T21:08:47+08:00", "content/self-host/upgrading/outdated/40.en.mdx": "2026-04-26T21:08:47+08:00",
"content/self-host/upgrading/outdated/40.mdx": "2026-04-26T21:08:47+08:00", "content/self-host/upgrading/outdated/40.mdx": "2026-04-26T21:08:47+08:00",
"content/self-host/upgrading/outdated/41.en.mdx": "2026-04-26T21:08:47+08:00", "content/self-host/upgrading/outdated/41.en.mdx": "2026-04-26T21:08:47+08:00",
......
...@@ -38,6 +38,17 @@ export enum ChatSourceEnum { ...@@ -38,6 +38,17 @@ export enum ChatSourceEnum {
mcp = 'mcp' mcp = 'mcp'
} }
/**
* 会话所属资源类型。
*
* `ChatSourceEnum` 表示对话入口来源,例如 test/api/online。
* `ChatSourceTypeEnum` 表示会话归属资源类型,用于在同一套 chat 表中隔离 App 和 Skill Edit。
*/
export enum ChatSourceTypeEnum {
app = 'app',
skillEdit = 'skillEdit'
}
export const ChatSourceMap = { export const ChatSourceMap = {
[ChatSourceEnum.test]: { [ChatSourceEnum.test]: {
name: i18nT('common:core.chat.logs.test'), name: i18nT('common:core.chat.logs.test'),
......
...@@ -3,7 +3,8 @@ import { ...@@ -3,7 +3,8 @@ import {
ChatFileTypeEnum, ChatFileTypeEnum,
ChatGenerateStatusEnum, ChatGenerateStatusEnum,
ChatRoleEnum, ChatRoleEnum,
ChatSourceEnum ChatSourceEnum,
ChatSourceTypeEnum
} from './constants'; } from './constants';
import { FlowNodeTypeEnum } from '../workflow/node/constant'; import { FlowNodeTypeEnum } from '../workflow/node/constant';
import { DispatchNodeResponseKeyEnum } from '../workflow/runtime/constants'; import { DispatchNodeResponseKeyEnum } from '../workflow/runtime/constants';
...@@ -89,8 +90,11 @@ export const ChatSchema = z.object({ ...@@ -89,8 +90,11 @@ export const ChatSchema = z.object({
userId: ObjectIdSchema, userId: ObjectIdSchema,
teamId: ObjectIdSchema, teamId: ObjectIdSchema,
tmbId: ObjectIdSchema, tmbId: ObjectIdSchema,
sourceType: z.enum(ChatSourceTypeEnum).default(ChatSourceTypeEnum.app).meta({
description: '会话所属资源类型。旧数据可能缺失,业务查询层按 app 兼容。'
}),
appId: ObjectIdSchema.meta({ appId: ObjectIdSchema.meta({
description: '目前已经变成 sourceId,可能是 app 的,也可能是 skill 的' description: '历史物理字段名。业务语义为 sourceId,可能是 appId 或 skillId。'
}), }),
appVersionId: ObjectIdSchema.optional().meta({ description: 'appId 为 app 时候才有' }), appVersionId: ObjectIdSchema.optional().meta({ description: 'appId 为 app 时候才有' }),
createTime: z.coerce.date(), createTime: z.coerce.date(),
...@@ -272,6 +276,7 @@ export const ChatItemDBSchema = ChatItemObjItemSchema.and( ...@@ -272,6 +276,7 @@ export const ChatItemDBSchema = ChatItemObjItemSchema.and(
userId: z.string(), userId: z.string(),
teamId: z.string(), teamId: z.string(),
tmbId: z.string(), tmbId: z.string(),
sourceType: z.enum(ChatSourceTypeEnum).default(ChatSourceTypeEnum.app),
appId: z.string(), appId: z.string(),
time: z.coerce.date(), time: z.coerce.date(),
deleteTime: z.coerce.date().nullish() deleteTime: z.coerce.date().nullish()
...@@ -289,6 +294,7 @@ export type ErrorTextItemType = z.infer<typeof ErrorTextItemSchema>; ...@@ -289,6 +294,7 @@ export type ErrorTextItemType = z.infer<typeof ErrorTextItemSchema>;
/* --------- chat item response ---------- */ /* --------- chat item response ---------- */
export const ChatItemResponseSchema = z.object({ export const ChatItemResponseSchema = z.object({
teamId: z.string(), teamId: z.string(),
sourceType: z.enum(ChatSourceTypeEnum).default(ChatSourceTypeEnum.app),
appId: z.string(), appId: z.string(),
chatId: z.string(), chatId: z.string(),
chatItemDataId: z.string(), chatItemDataId: z.string(),
......
...@@ -28,6 +28,7 @@ import { SearchDataResponseQuoteListItemSchema } from '../../dataset/type'; ...@@ -28,6 +28,7 @@ import { SearchDataResponseQuoteListItemSchema } from '../../dataset/type';
import type { localeType } from '../../../common/i18n/type'; import type { localeType } from '../../../common/i18n/type';
import { type ChatFileStoreValue, type UserChatItemValueItemType } from '../../chat/type'; import { type ChatFileStoreValue, type UserChatItemValueItemType } from '../../chat/type';
import { DatasetSearchModeEnum } from '../../dataset/constants'; import { DatasetSearchModeEnum } from '../../dataset/constants';
import type { ChatSourceTypeEnum } from '../../chat/constants';
import { ChatRoleEnum } from '../../chat/constants'; import { ChatRoleEnum } from '../../chat/constants';
import z from 'zod'; import z from 'zod';
import type { JSONSchemaInputType } from '../../app/jsonschema'; import type { JSONSchemaInputType } from '../../app/jsonschema';
...@@ -71,13 +72,12 @@ export type ChatDispatchProps = { ...@@ -71,13 +72,12 @@ export type ChatDispatchProps = {
externalProvider: ExternalProviderType; externalProvider: ExternalProviderType;
runningAppInfo: { runningAppInfo: {
id: string; // May be the id of the system plug-in (cannot be used directly to look up the table) sourceType: ChatSourceTypeEnum;
sourceId: string;
teamId: string; teamId: string;
tmbId: string; // App tmbId tmbId: string; // App tmbId
name: string; name: string;
isChildApp?: boolean; isChildApp?: boolean;
/** 显式指定本轮工作流使用的 sandbox 资源,避免由 appId/userId/chatId 重新生成。 */
sandboxId?: string;
}; };
runningUserInfo: { runningUserInfo: {
username: string; username: string;
...@@ -127,7 +127,7 @@ export type ModuleDispatchProps<T> = ChatDispatchProps & { ...@@ -127,7 +127,7 @@ export type ModuleDispatchProps<T> = ChatDispatchProps & {
export type SystemVariablesType = { export type SystemVariablesType = {
userId: string; userId: string;
appId: string; appId?: string;
chatId?: string; chatId?: string;
responseChatItemId?: string; responseChatItemId?: string;
histories: ChatItemMiniType[]; histories: ChatItemMiniType[];
......
import { ObjectIdSchema } from '../../../common/type/mongo'; import { ObjectIdSchema } from '../../../common/type/mongo';
import z from 'zod'; import z from 'zod';
import { OutLinkChatAuthSchema } from '../../../support/permission/chat'; import {
import { ChatGenerateStatusSchema } from '../chat/api'; ChatGenerateStatusSchema,
createOutLinkChatTargetInputSchema,
transformChatTargetInput
} from '../chat/api';
// Query Params // Query Params
export const GetLLMRequestRecordParamsSchema = z.object({ export const GetLLMRequestRecordParamsSchema = z.object({
...@@ -63,16 +66,17 @@ export const ChatMessageSchema = z.object({ ...@@ -63,16 +66,17 @@ export const ChatMessageSchema = z.object({
* 断线续传:GET /api/core/chat/resume(与 v2/chat/completions 配套;支持站内、分享、团队域名鉴权) * 断线续传:GET /api/core/chat/resume(与 v2/chat/completions 配套;支持站内、分享、团队域名鉴权)
* ============================================================================ */ * ============================================================================ */
export const ResumeStreamParamsSchema = z.object({ export const ResumeStreamParamsRawSchema = createOutLinkChatTargetInputSchema({
...OutLinkChatAuthSchema.shape,
appId: ObjectIdSchema,
teamId: ObjectIdSchema.optional(), teamId: ObjectIdSchema.optional(),
shareId: z.string().optional(), shareId: z.string().optional(),
outLinkUid: z.string().optional(), outLinkUid: z.string().optional(),
chatId: z.string().meta({ example: 'bEdzC6PNupZrr1RoVutMF2DL', description: '聊天 ID' }) chatId: z.string().meta({ example: 'bEdzC6PNupZrr1RoVutMF2DL', description: '聊天 ID' })
}); });
export const ResumeStreamParamsSchema =
ResumeStreamParamsRawSchema.transform(transformChatTargetInput);
export type ResumeStreamParams = z.infer<typeof ResumeStreamParamsSchema>; export type ResumeStreamParams = z.infer<typeof ResumeStreamParamsRawSchema>;
export type ResumeStreamRuntimeParams = z.infer<typeof ResumeStreamParamsSchema>;
export const StreamResumeCompletedRecordsSchema = z.object({ export const StreamResumeCompletedRecordsSchema = z.object({
list: z.array(z.any()).meta({ list: z.array(z.any()).meta({
......
...@@ -3,7 +3,7 @@ import { DevApiTagsMap } from '../../tag'; ...@@ -3,7 +3,7 @@ import { DevApiTagsMap } from '../../tag';
import { import {
GetLLMRequestRecordParamsSchema, GetLLMRequestRecordParamsSchema,
LLMRequestRecordSchema, LLMRequestRecordSchema,
ResumeStreamParamsSchema, ResumeStreamParamsRawSchema,
StreamNoNeedToBeResumeSchema StreamNoNeedToBeResumeSchema
} from './api'; } from './api';
import { SandboxPath } from './sandbox'; import { SandboxPath } from './sandbox';
...@@ -40,10 +40,10 @@ export const AIPath: OpenAPIPath = { ...@@ -40,10 +40,10 @@ export const AIPath: OpenAPIPath = {
get: { get: {
summary: '恢复流式响应', summary: '恢复流式响应',
description: description:
'与 /v2/chat/completions 配套;GET query 传 appId / chatId / teamId。已完成对话可返回 JSON;若对话仍在生成中,则必须请求 SSE,否则返回 406。', '与 /v2/chat/completions 配套;GET query 传 appId 或 skillId(二选一)以及 chatId,团队空间场景可额外传 teamId/teamToken。已完成对话可返回 JSON;若对话仍在生成中,则必须请求 SSE,否则返回 406。',
tags: [DevApiTagsMap.aiCommon], tags: [DevApiTagsMap.aiCommon],
requestParams: { requestParams: {
query: ResumeStreamParamsSchema query: ResumeStreamParamsRawSchema
}, },
responses: { responses: {
200: { 200: {
......
import { OutLinkChatAuthSchema } from '../../../../support/permission/chat'; import { OutLinkChatAuthSchema } from '../../../../support/permission/chat';
import z from 'zod'; import z from 'zod';
import { createChatTargetInputSchema, transformChatTargetInput } from '../../chat/api';
const SandboxBaseSchema = z.object({ const SandboxBaseShape = {
appId: z.string().meta({
example: '68ad85a7463006c963799a05',
description: '应用 ID'
}),
chatId: z.string().meta({ chatId: z.string().meta({
example: 'bEdzC6PNupZrr1RoVutMF2DL', example: 'bEdzC6PNupZrr1RoVutMF2DL',
description: '对话 ID' description: '对话 ID'
}), }),
outLinkAuthData: OutLinkChatAuthSchema.optional().describe('外链鉴权数据') outLinkAuthData: OutLinkChatAuthSchema.optional().describe('外链鉴权数据')
}); };
const withSandboxTarget = <T extends z.ZodRawShape>(shape: T) =>
createChatTargetInputSchema({
...SandboxBaseShape,
...shape
}).transform(transformChatTargetInput);
/** /**
* 下载文件或目录 - 请求体(响应为文件流或 ZIP) * 下载文件或目录 - 请求体(响应为文件流或 ZIP)
*/ */
export const SandboxDownloadBodySchema = SandboxBaseSchema.extend({ export const SandboxDownloadBodyRawSchema = createChatTargetInputSchema({
...SandboxBaseShape,
path: z.string().optional().default('.').describe('要下载的路径(文件或目录)')
});
export const SandboxDownloadBodySchema = withSandboxTarget({
path: z.string().optional().default('.').describe('要下载的路径(文件或目录)') path: z.string().optional().default('.').describe('要下载的路径(文件或目录)')
}); });
export type SandboxDownloadBody = z.input<typeof SandboxDownloadBodySchema>; export type SandboxDownloadBody = z.input<typeof SandboxDownloadBodySchema>;
export type SandboxDownloadRuntimeBody = z.output<typeof SandboxDownloadBodySchema>;
export const SandboxDownloadResponseSchema = z export const SandboxDownloadResponseSchema = z
.string() .string()
...@@ -28,11 +36,13 @@ export const SandboxDownloadResponseSchema = z ...@@ -28,11 +36,13 @@ export const SandboxDownloadResponseSchema = z
/** /**
* 检查沙盒是否存在 * 检查沙盒是否存在
*/ */
export const SandboxCheckExistBodySchema = SandboxBaseSchema; export const SandboxCheckExistBodyRawSchema = createChatTargetInputSchema(SandboxBaseShape);
export const SandboxCheckExistBodySchema = withSandboxTarget({});
export const SandboxCheckExistResponseSchema = z.object({ export const SandboxCheckExistResponseSchema = z.object({
exists: z.boolean().describe('沙盒是否存在') exists: z.boolean().describe('沙盒是否存在')
}); });
export type SandboxCheckExistBody = z.infer<typeof SandboxCheckExistBodySchema>; export type SandboxCheckExistBody = z.input<typeof SandboxCheckExistBodySchema>;
export type SandboxCheckExistRuntimeBody = z.output<typeof SandboxCheckExistBodySchema>;
export type SandboxCheckExistResponse = z.infer<typeof SandboxCheckExistResponseSchema>; export type SandboxCheckExistResponse = z.infer<typeof SandboxCheckExistResponseSchema>;
/** /**
...@@ -41,7 +51,14 @@ export type SandboxCheckExistResponse = z.infer<typeof SandboxCheckExistResponse ...@@ -41,7 +51,14 @@ export type SandboxCheckExistResponse = z.infer<typeof SandboxCheckExistResponse
export const SandboxChannelSchema = z.enum(['fs', 'terminal']).describe('沙盒 WebSocket 通道'); export const SandboxChannelSchema = z.enum(['fs', 'terminal']).describe('沙盒 WebSocket 通道');
export const SandboxTicketPermissionSchema = z.enum(['read', 'write']).describe('沙盒 Ticket 权限'); export const SandboxTicketPermissionSchema = z.enum(['read', 'write']).describe('沙盒 Ticket 权限');
export const SandboxGetTicketBodySchema = SandboxBaseSchema.extend({ export const SandboxGetTicketBodyRawSchema = createChatTargetInputSchema({
...SandboxBaseShape,
channel: SandboxChannelSchema,
permission: SandboxTicketPermissionSchema.optional()
.default('read')
.describe('fs 通道支持 read/write;terminal 通道固定需要 write')
});
export const SandboxGetTicketBodySchema = withSandboxTarget({
channel: SandboxChannelSchema, channel: SandboxChannelSchema,
permission: SandboxTicketPermissionSchema.optional() permission: SandboxTicketPermissionSchema.optional()
.default('read') .default('read')
...@@ -53,16 +70,24 @@ export const SandboxGetTicketResponseSchema = z.object({ ...@@ -53,16 +70,24 @@ export const SandboxGetTicketResponseSchema = z.object({
export type SandboxChannel = z.infer<typeof SandboxChannelSchema>; export type SandboxChannel = z.infer<typeof SandboxChannelSchema>;
export type SandboxTicketPermission = z.infer<typeof SandboxTicketPermissionSchema>; export type SandboxTicketPermission = z.infer<typeof SandboxTicketPermissionSchema>;
export type SandboxGetTicketBody = z.input<typeof SandboxGetTicketBodySchema>; export type SandboxGetTicketBody = z.input<typeof SandboxGetTicketBodySchema>;
export type SandboxGetTicketRuntimeBody = z.output<typeof SandboxGetTicketBodySchema>;
export type SandboxGetTicketResponse = z.infer<typeof SandboxGetTicketResponseSchema>; export type SandboxGetTicketResponse = z.infer<typeof SandboxGetTicketResponseSchema>;
/** /**
* 获取 HTML 预览链接 - 请求/响应 * 获取 HTML 预览链接 - 请求/响应
*/ */
export const SandboxGetHtmlPreviewLinkBodySchema = SandboxBaseSchema.extend({ export const SandboxGetHtmlPreviewLinkBodyRawSchema = createChatTargetInputSchema({
...SandboxBaseShape,
filePath: z.string().describe('文件路径')
});
export const SandboxGetHtmlPreviewLinkBodySchema = withSandboxTarget({
filePath: z.string().describe('文件路径') filePath: z.string().describe('文件路径')
}); });
export const SandboxGetHtmlPreviewLinkResponseSchema = z.string().describe('HTML 预览链接'); export const SandboxGetHtmlPreviewLinkResponseSchema = z.string().describe('HTML 预览链接');
export type SandboxGetHtmlPreviewLinkBody = z.infer<typeof SandboxGetHtmlPreviewLinkBodySchema>; export type SandboxGetHtmlPreviewLinkBody = z.input<typeof SandboxGetHtmlPreviewLinkBodySchema>;
export type SandboxGetHtmlPreviewLinkRuntimeBody = z.output<
typeof SandboxGetHtmlPreviewLinkBodySchema
>;
export type SandboxGetHtmlPreviewLinkResponse = z.infer< export type SandboxGetHtmlPreviewLinkResponse = z.infer<
typeof SandboxGetHtmlPreviewLinkResponseSchema typeof SandboxGetHtmlPreviewLinkResponseSchema
>; >;
import type { OpenAPIPath } from '../../../type'; import type { OpenAPIPath } from '../../../type';
import { DevApiTagsMap } from '../../../tag'; import { DevApiTagsMap } from '../../../tag';
import { import {
SandboxDownloadBodySchema, SandboxDownloadBodyRawSchema,
SandboxDownloadResponseSchema, SandboxDownloadResponseSchema,
SandboxCheckExistBodySchema, SandboxCheckExistBodyRawSchema,
SandboxCheckExistResponseSchema, SandboxCheckExistResponseSchema,
SandboxGetTicketBodySchema, SandboxGetTicketBodyRawSchema,
SandboxGetTicketResponseSchema, SandboxGetTicketResponseSchema,
SandboxGetHtmlPreviewLinkBodySchema, SandboxGetHtmlPreviewLinkBodyRawSchema,
SandboxGetHtmlPreviewLinkResponseSchema SandboxGetHtmlPreviewLinkResponseSchema
} from './api'; } from './api';
...@@ -20,7 +20,7 @@ export const SandboxPath: OpenAPIPath = { ...@@ -20,7 +20,7 @@ export const SandboxPath: OpenAPIPath = {
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: SandboxDownloadBodySchema schema: SandboxDownloadBodyRawSchema
} }
} }
}, },
...@@ -44,7 +44,7 @@ export const SandboxPath: OpenAPIPath = { ...@@ -44,7 +44,7 @@ export const SandboxPath: OpenAPIPath = {
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: SandboxGetHtmlPreviewLinkBodySchema schema: SandboxGetHtmlPreviewLinkBodyRawSchema
} }
} }
}, },
...@@ -69,7 +69,7 @@ export const SandboxPath: OpenAPIPath = { ...@@ -69,7 +69,7 @@ export const SandboxPath: OpenAPIPath = {
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: SandboxCheckExistBodySchema schema: SandboxCheckExistBodyRawSchema
} }
} }
}, },
...@@ -94,7 +94,7 @@ export const SandboxPath: OpenAPIPath = { ...@@ -94,7 +94,7 @@ export const SandboxPath: OpenAPIPath = {
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: SandboxGetTicketBodySchema schema: SandboxGetTicketBodyRawSchema
} }
} }
}, },
......
...@@ -13,14 +13,13 @@ import { ...@@ -13,14 +13,13 @@ import {
ZipEntryInfoSchema ZipEntryInfoSchema
} from '../../../../core/ai/skill/type'; } from '../../../../core/ai/skill/type';
import { SkillPermissionSchema } from '../../../../support/permission/skill/controller.schema'; import { SkillPermissionSchema } from '../../../../support/permission/skill/controller.schema';
import { ChatGenerateStatusSchema } from '../../chat/api'; import { ChatCompletionMessageParamSchema } from '../../../../core/ai/llm/type';
const IdSchema = z.string().min(1).meta({ description: '资源 ID' }); const IdSchema = z.string().min(1).meta({ description: '资源 ID' });
const SandboxInstanceKeySchema = z.string().min(1).describe('FastGPT sandbox instance key'); const SandboxInstanceKeySchema = z.string().min(1).describe('FastGPT sandbox instance key');
const NullableParentIdSchema = z.string().nullable().optional().meta({ const NullableParentIdSchema = z.string().nullable().optional().meta({
description: '父级目录 ID' description: '父级目录 ID'
}); });
const LooseObjectSchema = z.object({}).catchall(z.any());
export const ListSkillsQuerySchema = z.object({ export const ListSkillsQuerySchema = z.object({
source: z.enum(['store', 'mine']).optional().describe('技能来源: store=系统技能, mine=我的技能'), source: z.enum(['store', 'mine']).optional().describe('技能来源: store=系统技能, mine=我的技能'),
...@@ -218,50 +217,12 @@ export const SkillDebugChatBodySchema = z.object({ ...@@ -218,50 +217,12 @@ export const SkillDebugChatBodySchema = z.object({
skillId: IdSchema, skillId: IdSchema,
chatId: z.string().min(1), chatId: z.string().min(1),
responseChatItemId: z.string().optional(), responseChatItemId: z.string().optional(),
messages: z.array(LooseObjectSchema), messages: z.array(ChatCompletionMessageParamSchema),
model: z.string().optional(), model: z.string().optional(),
systemPrompt: z.string().optional() systemPrompt: z.string().optional()
}); });
export type SkillDebugChatBody = z.infer<typeof SkillDebugChatBodySchema>; export type SkillDebugChatBody = z.infer<typeof SkillDebugChatBodySchema>;
export const SkillDebugSessionListQuerySchema = z.object({
skillId: IdSchema,
pageNum: z.coerce.number().int().positive().optional(),
pageSize: z.coerce.number().int().positive().optional()
});
export type SkillDebugSessionListQuery = z.infer<typeof SkillDebugSessionListQuerySchema>;
export const SkillDebugSessionListResponseSchema = z.object({
list: z.array(
z.object({
chatId: z.string(),
title: z.string(),
updateTime: z.string()
})
),
total: z.number()
});
export type SkillDebugSessionListResponse = z.infer<typeof SkillDebugSessionListResponseSchema>;
export const SkillDebugSessionDeleteBodySchema = z.object({
skillId: IdSchema,
chatId: z.string().min(1)
});
export type SkillDebugSessionDeleteBody = z.infer<typeof SkillDebugSessionDeleteBodySchema>;
export const SkillDebugSessionControlBodySchema = z.object({
skillId: IdSchema,
chatId: z.string().min(1)
});
export type SkillDebugSessionControlBody = z.infer<typeof SkillDebugSessionControlBodySchema>;
export const SkillDebugSessionStopResponseSchema = z.object({
success: z.boolean(),
completed: z.boolean().describe('工作流是否已在本次请求等待窗口内完成停止'),
chatGenerateStatus: ChatGenerateStatusSchema
});
export type SkillDebugSessionStopResponse = z.infer<typeof SkillDebugSessionStopResponseSchema>;
export const ListAppsBySkillIdQuerySchema = z.object({ export const ListAppsBySkillIdQuerySchema = z.object({
skillId: IdSchema skillId: IdSchema
}); });
...@@ -320,31 +281,6 @@ export const ExportSkillQuerySchema = z.object({ ...@@ -320,31 +281,6 @@ export const ExportSkillQuerySchema = z.object({
}); });
export type ExportSkillQuery = z.infer<typeof ExportSkillQuerySchema>; export type ExportSkillQuery = z.infer<typeof ExportSkillQuerySchema>;
export const SkillDebugDeleteChatItemBodySchema = z.object({
skillId: IdSchema,
chatId: z.string(),
contentId: z.string()
});
export type SkillDebugDeleteChatItemBody = z.infer<typeof SkillDebugDeleteChatItemBodySchema>;
export const SkillDebugRecordsBodySchema = z.object({
skillId: IdSchema,
chatId: z.string(),
pageSize: z.coerce.number().int().positive().optional(),
initialId: z.string().optional(),
nextId: z.string().optional(),
prevId: z.string().optional()
});
export type SkillDebugRecordsBody = z.infer<typeof SkillDebugRecordsBodySchema>;
export const SkillDebugRecordsResponseSchema = z.object({
list: z.array(z.any()),
total: z.number(),
hasMorePrev: z.boolean(),
hasMoreNext: z.boolean()
});
export type SkillDebugRecordsResponse = z.infer<typeof SkillDebugRecordsResponseSchema>;
export const ListSkillVersionsBodySchema = z.object({ export const ListSkillVersionsBodySchema = z.object({
skillId: IdSchema, skillId: IdSchema,
pageNum: z.number().int().positive().optional().describe('页码,从 1 开始'), pageNum: z.number().int().positive().optional().describe('页码,从 1 开始'),
......
...@@ -24,13 +24,6 @@ import { ...@@ -24,13 +24,6 @@ import {
SaveDeploySkillBodySchema, SaveDeploySkillBodySchema,
SaveDeploySkillResponseSchema, SaveDeploySkillResponseSchema,
SkillDebugChatBodySchema, SkillDebugChatBodySchema,
SkillDebugSessionControlBodySchema,
SkillDebugSessionStopResponseSchema,
SkillDebugRecordsBodySchema,
SkillDebugRecordsResponseSchema,
SkillDebugSessionDeleteBodySchema,
SkillDebugSessionListQuerySchema,
SkillDebugSessionListResponseSchema,
SwitchSkillVersionBodySchema, SwitchSkillVersionBodySchema,
UpdateSkillBodySchema, UpdateSkillBodySchema,
UpdateSkillVersionBodySchema UpdateSkillVersionBodySchema
...@@ -324,93 +317,6 @@ export const SkillPath: OpenAPIPath = { ...@@ -324,93 +317,6 @@ export const SkillPath: OpenAPIPath = {
} }
} }
}, },
'/core/ai/skill/debugSession/list': {
get: {
summary: '获取技能调试会话列表',
description: '分页获取技能的调试会话',
tags: [DevApiTagsMap.aiSkill],
requestParams: {
query: SkillDebugSessionListQuerySchema
},
responses: {
200: {
description: '成功返回调试会话列表',
content: {
'application/json': {
schema: SkillDebugSessionListResponseSchema
}
}
}
}
}
},
'/core/ai/skill/debugSession/delete': {
post: {
summary: '删除技能调试会话',
description: '软删除一个技能调试会话',
tags: [DevApiTagsMap.aiSkill],
requestBody: {
content: {
'application/json': {
schema: SkillDebugSessionDeleteBodySchema
}
}
},
responses: {
200: {
description: '成功删除调试会话'
}
}
}
},
'/core/ai/skill/debugSession/stop': {
post: {
summary: '停止技能调试对话',
description: '停止指定技能调试会话中正在运行的工作流',
tags: [DevApiTagsMap.aiSkill],
requestBody: {
content: {
'application/json': {
schema: SkillDebugSessionControlBodySchema
}
}
},
responses: {
200: {
description: '成功停止调试对话',
content: {
'application/json': {
schema: SkillDebugSessionStopResponseSchema
}
}
}
}
}
},
'/core/ai/skill/debugSession/records': {
post: {
summary: '获取技能调试会话记录',
description: '分页获取技能调试会话的聊天记录',
tags: [DevApiTagsMap.aiSkill],
requestBody: {
content: {
'application/json': {
schema: SkillDebugRecordsBodySchema
}
}
},
responses: {
200: {
description: '成功返回调试记录',
content: {
'application/json': {
schema: SkillDebugRecordsResponseSchema
}
}
}
}
}
},
'/core/ai/skill/version/list': { '/core/ai/skill/version/list': {
post: { post: {
summary: '获取技能版本列表', summary: '获取技能版本列表',
......
import { ObjectIdSchema } from '../../../common/type/mongo'; import { ObjectIdSchema } from '../../../common/type/mongo';
import { ChatGenerateStatusEnum } from '../../../core/chat/constants'; import { ChatGenerateStatusEnum, ChatSourceTypeEnum } from '../../../core/chat/constants';
import { OutLinkChatAuthSchema } from '../../../support/permission/chat';
import z from 'zod'; import z from 'zod';
export const ChatGenerateStatusSchema = z export const ChatGenerateStatusSchema = z
.enum(ChatGenerateStatusEnum) .enum(ChatGenerateStatusEnum)
.describe('对话生成状态:0=generating(生成中),1=done(已完成),2=error(生成异常)'); .describe('对话生成状态:0=generating(生成中),1=done(已完成),2=error(生成异常)');
const ChatTargetInputShape = {
appId: ObjectIdSchema.optional().meta({
example: '68ad85a7463006c963799a05',
description: '应用 ID。appId 和 skillId 必须且只能传一个。'
}),
skillId: ObjectIdSchema.optional().meta({
example: '68ad85a7463006c963799a06',
description: 'Skill Edit 调试 ID。appId 和 skillId 必须且只能传一个。'
})
};
type ChatTargetInput = {
appId?: unknown;
skillId?: unknown;
[key: string]: unknown;
};
export type ChatTargetInputType =
| {
appId: string;
skillId?: never;
}
| {
appId?: never;
skillId: string;
};
export const refineRequiredChatTargetInput = (
data: { appId?: unknown; skillId?: unknown },
ctx: z.RefinementCtx
) => {
if (!!data.appId === !!data.skillId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'appId or skillId must be provided, but not both'
});
}
};
export const refineOptionalChatTargetInput = (
data: { appId?: unknown; skillId?: unknown },
ctx: z.RefinementCtx
) => {
if (data.appId && data.skillId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'appId and skillId cannot be provided at the same time'
});
}
};
/**
* 将对外 API 的 `appId/skillId` 互斥入参转换为内部标准 chat source。
*
* 该函数只用于 runtime schema 的 `.transform(...)`,OpenAPI path 必须继续注册
* raw schema,避免文档暴露内部 `sourceType/sourceId`。
*/
export const transformChatTargetInput = <T extends ChatTargetInput>(data: T) => {
const { appId, skillId, ...rest } = data;
const sourceId = (appId || skillId) as string;
return {
...rest,
sourceType: appId ? ChatSourceTypeEnum.app : ChatSourceTypeEnum.skillEdit,
sourceId
};
};
/**
* 可选 chat target 的转换函数。
*
* 仅用于外链、团队空间等允许从鉴权上下文推导 App 的接口;如果传入了 target,
* 仍会转换为内部 `sourceType/sourceId`。
*/
export const transformOptionalChatTargetInput = <T extends ChatTargetInput>(data: T) => {
const { appId, skillId, ...rest } = data;
const sourceId = (appId || skillId) as string | undefined;
return {
...rest,
...(appId || skillId
? {
sourceType: appId ? ChatSourceTypeEnum.app : ChatSourceTypeEnum.skillEdit,
sourceId: sourceId!
}
: {})
};
};
/**
* 构造对外 API 使用的 chat target 入参 schema。
*
* 该 schema 不包含 transform,专门用于 OpenAPI 文档和前端请求类型。
* 运行时 API route 应使用 `withChatTarget`,在 `parseApiInput` 阶段转换为
* `sourceType/sourceId`,避免 service 层继续感知 `appId/skillId` 原始字段。
*/
export const createChatTargetInputSchema = <T extends z.ZodRawShape>(shape: T) =>
z
.object({
...ChatTargetInputShape,
...shape
})
.superRefine(refineRequiredChatTargetInput);
/**
* 构造允许缺省 chat target 的对外入参 schema。
*
* 仅用于兼容外链/团队空间等可从鉴权上下文反推出 App 的接口;普通标准 chat API
* 应继续使用 `createChatTargetInputSchema`,要求 appId/skillId 必填且互斥。
*/
export const createOptionalChatTargetInputSchema = <T extends z.ZodRawShape>(shape: T) =>
z
.object({
...ChatTargetInputShape,
...shape
})
.superRefine(refineOptionalChatTargetInput);
/**
* 构造包含外链/团队鉴权字段的 chat target 入参 schema。
*
* 不能用 `OutLinkChatAuthSchema.extend(createChatTargetInputSchema(...).shape)` 拼接,
* 否则会丢失 `createChatTargetInputSchema` 上 appId/skillId 互斥校验。
*/
export const createOutLinkChatTargetInputSchema = <T extends z.ZodRawShape>(shape: T) =>
createChatTargetInputSchema({
...OutLinkChatAuthSchema.shape,
...shape
});
/**
* 构造允许缺省 chat target、且包含外链/团队鉴权字段的入参 schema。
*
* 仅用于外链、团队空间等允许从鉴权上下文推导 App 的接口。
*/
export const createOptionalOutLinkChatTargetInputSchema = <T extends z.ZodRawShape>(shape: T) =>
createOptionalChatTargetInputSchema({
...OutLinkChatAuthSchema.shape,
...shape
});
/**
* API route runtime schema helper.
*
* OpenAPI path 不应直接注册该 schema;它会 transform 输出为内部
* `sourceType/sourceId`,用于 API handler 之后的业务层调用。
*/
export const withChatTarget = <T extends z.ZodRawShape>(shape: T) =>
createChatTargetInputSchema(shape).transform(transformChatTargetInput);
/**
* 少数允许缺省 chat target 的接口使用。必填 target 的标准 chat API
* 不能使用该 helper,避免绕过 appId/skillId 互斥校验。
*/
export const withOptionalChatTarget = <T extends z.ZodRawShape>(shape: T) =>
createOptionalChatTargetInputSchema(shape).transform(transformOptionalChatTargetInput);
/** 包含外链/团队鉴权字段的必填 chat target runtime schema helper。 */
export const withOutLinkChatTarget = <T extends z.ZodRawShape>(shape: T) =>
createOutLinkChatTargetInputSchema(shape).transform(transformChatTargetInput);
/** 包含外链/团队鉴权字段的可选 chat target runtime schema helper。 */
export const withOptionalOutLinkChatTarget = <T extends z.ZodRawShape>(shape: T) =>
createOptionalOutLinkChatTargetInputSchema(shape).transform(transformOptionalChatTargetInput);
/* Recently Used Apps */ /* Recently Used Apps */
export const GetRecentlyUsedAppsResponseSchema = z.array( export const GetRecentlyUsedAppsResponseSchema = z.array(
z.object({ z.object({
......
...@@ -2,27 +2,30 @@ import { OutLinkChatAuthSchema } from '../../../../support/permission/chat'; ...@@ -2,27 +2,30 @@ import { OutLinkChatAuthSchema } from '../../../../support/permission/chat';
import { ObjectIdSchema } from '../../../../common/type/mongo'; import { ObjectIdSchema } from '../../../../common/type/mongo';
import z from 'zod'; import z from 'zod';
import { AppTypeEnum } from '../../../../core/app/constants'; import { AppTypeEnum } from '../../../../core/app/constants';
import { ChatGenerateStatusEnum } from '../../../../core/chat/constants'; import { ChatGenerateStatusEnum, ChatSourceTypeEnum } from '../../../../core/chat/constants';
import { OpenAPIFlowNodeInputItemTypeSchema } from '../../workflow/node'; import { OpenAPIFlowNodeInputItemTypeSchema } from '../../workflow/node';
import { OpenAPIAppChatConfigSchema } from '../../app/common/api'; import { OpenAPIAppChatConfigSchema } from '../../app/common/api';
import { ChatGenerateStatusSchema } from '../api'; import {
ChatGenerateStatusSchema,
createChatTargetInputSchema,
transformChatTargetInput
} from '../api';
/* Init */ /* Init */
// Online chat // Online chat
export const InitChatQuerySchema = z export const InitChatQueryRawSchema = createChatTargetInputSchema({
.object({
appId: ObjectIdSchema.describe('应用ID'),
chatId: z.string().min(1).describe('会话ID'), chatId: z.string().min(1).describe('会话ID'),
loadCustomFeedbacks: z.coerce.boolean().optional().describe('是否加载自定义反馈') loadCustomFeedbacks: z.coerce.boolean().optional().describe('是否加载自定义反馈')
}) }).meta({
.meta({
example: { example: {
appId: '1234567890', appId: '1234567890',
chatId: '1234567890', chatId: '1234567890',
loadCustomFeedbacks: true loadCustomFeedbacks: true
} }
}); });
export type InitChatQueryType = z.infer<typeof InitChatQuerySchema>; export const InitChatQuerySchema = InitChatQueryRawSchema.transform(transformChatTargetInput);
export type InitChatQueryType = z.infer<typeof InitChatQueryRawSchema>;
export type InitChatQueryRuntimeType = z.infer<typeof InitChatQuerySchema>;
/** 团队空间 init:`/api/core/chat/team/init` */ /** 团队空间 init:`/api/core/chat/team/init` */
export const InitTeamChatQuerySchema = z.object({ export const InitTeamChatQuerySchema = z.object({
...@@ -35,7 +38,9 @@ export type InitTeamChatQueryType = z.infer<typeof InitTeamChatQuerySchema>; ...@@ -35,7 +38,9 @@ export type InitTeamChatQueryType = z.infer<typeof InitTeamChatQuerySchema>;
export const InitChatResponseSchema = z.object({ export const InitChatResponseSchema = z.object({
chatId: z.string().optional().describe('会话ID'), chatId: z.string().optional().describe('会话ID'),
appId: ObjectIdSchema.describe('应用ID'), sourceType: z.enum(ChatSourceTypeEnum).describe('会话所属资源类型'),
sourceId: ObjectIdSchema.describe('会话所属资源 ID'),
appId: ObjectIdSchema.optional().describe('真实应用 ID,仅 sourceType=app 时返回'),
userAvatar: z.string().optional().describe('用户头像'), userAvatar: z.string().optional().describe('用户头像'),
title: z.string().describe('对话标题'), title: z.string().describe('对话标题'),
variables: z.record(z.string(), z.any()).optional().describe('全局变量值'), variables: z.record(z.string(), z.any()).optional().describe('全局变量值'),
...@@ -58,13 +63,10 @@ export const InitChatResponseSchema = z.object({ ...@@ -58,13 +63,10 @@ export const InitChatResponseSchema = z.object({
export type InitChatResponseType = z.infer<typeof InitChatResponseSchema>; export type InitChatResponseType = z.infer<typeof InitChatResponseSchema>;
/* ============ v2/chat/stop ============ */ /* ============ v2/chat/stop ============ */
export const StopV2ChatSchema = z export const StopV2ChatRawSchema = createChatTargetInputSchema({
.object({
appId: ObjectIdSchema.describe('应用ID'),
chatId: z.string().min(1).describe('会话ID'), chatId: z.string().min(1).describe('会话ID'),
outLinkAuthData: OutLinkChatAuthSchema.optional().describe('外链鉴权数据') outLinkAuthData: OutLinkChatAuthSchema.optional().describe('外链鉴权数据')
}) }).meta({
.meta({
example: { example: {
appId: '1234567890', appId: '1234567890',
chatId: '1234567890', chatId: '1234567890',
...@@ -73,8 +75,10 @@ export const StopV2ChatSchema = z ...@@ -73,8 +75,10 @@ export const StopV2ChatSchema = z
outLinkUid: '1234567890' outLinkUid: '1234567890'
} }
} }
}); });
export type StopV2ChatParams = z.infer<typeof StopV2ChatSchema>; export const StopV2ChatSchema = StopV2ChatRawSchema.transform(transformChatTargetInput);
export type StopV2ChatParams = z.infer<typeof StopV2ChatRawSchema>;
export type StopV2ChatRuntimeParams = z.infer<typeof StopV2ChatSchema>;
export const StopV2ChatResponseSchema = z export const StopV2ChatResponseSchema = z
.object({ .object({
......
import type { OpenAPIPath } from '../../../type'; import type { OpenAPIPath } from '../../../type';
import { DevApiTagsMap, SystemOpenApiTagMap } from '../../../tag'; import { DevApiTagsMap, SystemOpenApiTagMap } from '../../../tag';
import { import {
StopV2ChatSchema, StopV2ChatRawSchema,
StopV2ChatResponseSchema, StopV2ChatResponseSchema,
InitChatQuerySchema, InitChatQueryRawSchema,
InitChatResponseSchema InitChatResponseSchema
} from './api'; } from './api';
...@@ -14,7 +14,7 @@ export const ChatControllerPath: OpenAPIPath = { ...@@ -14,7 +14,7 @@ export const ChatControllerPath: OpenAPIPath = {
description: '', description: '',
tags: [DevApiTagsMap.chatHistory, SystemOpenApiTagMap.chatHistory], tags: [DevApiTagsMap.chatHistory, SystemOpenApiTagMap.chatHistory],
requestParams: { requestParams: {
query: InitChatQuerySchema query: InitChatQueryRawSchema
}, },
responses: { responses: {
200: { 200: {
...@@ -37,7 +37,7 @@ export const ChatControllerPath: OpenAPIPath = { ...@@ -37,7 +37,7 @@ export const ChatControllerPath: OpenAPIPath = {
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: StopV2ChatSchema schema: StopV2ChatRawSchema
} }
} }
}, },
......
import z from 'zod'; import z from 'zod';
import { createChatTargetInputSchema, transformChatTargetInput } from '../api';
/* =============== updateFeedbackReadStatus =============== */ const FeedbackTargetSchema = {
export const UpdateFeedbackReadStatusBodySchema = z.object({
appId: z.string().min(1).meta({
example: '68ad85a7463006c963799a05',
description: '应用 ID'
}),
chatId: z.string().min(1).meta({ chatId: z.string().min(1).meta({
example: 'chat123', example: 'chat123',
description: '对话 ID' description: '对话 ID'
...@@ -13,13 +9,25 @@ export const UpdateFeedbackReadStatusBodySchema = z.object({ ...@@ -13,13 +9,25 @@ export const UpdateFeedbackReadStatusBodySchema = z.object({
dataId: z.string().min(1).meta({ dataId: z.string().min(1).meta({
example: 'data123', example: 'data123',
description: '消息数据 ID' description: '消息数据 ID'
}), })
};
/* =============== updateFeedbackReadStatus =============== */
export const UpdateFeedbackReadStatusBodyRawSchema = createChatTargetInputSchema({
...FeedbackTargetSchema,
isRead: z.boolean().meta({ isRead: z.boolean().meta({
example: true, example: true,
description: '是否已读' description: '是否已读'
}) })
}); });
export type UpdateFeedbackReadStatusBodyType = z.infer<typeof UpdateFeedbackReadStatusBodySchema>; export const UpdateFeedbackReadStatusBodySchema =
UpdateFeedbackReadStatusBodyRawSchema.transform(transformChatTargetInput);
export type UpdateFeedbackReadStatusBodyType = z.infer<
typeof UpdateFeedbackReadStatusBodyRawSchema
>;
export type UpdateFeedbackReadStatusBodyRuntimeType = z.infer<
typeof UpdateFeedbackReadStatusBodySchema
>;
export const UpdateFeedbackReadStatusResponseSchema = z.object({ export const UpdateFeedbackReadStatusResponseSchema = z.object({
success: z.boolean().meta({ success: z.boolean().meta({
...@@ -32,19 +40,8 @@ export type UpdateFeedbackReadStatusResponseType = z.infer< ...@@ -32,19 +40,8 @@ export type UpdateFeedbackReadStatusResponseType = z.infer<
>; >;
/* =============== adminUpdate =============== */ /* =============== adminUpdate =============== */
export const AdminUpdateFeedbackBodySchema = z.object({ export const AdminUpdateFeedbackBodyRawSchema = createChatTargetInputSchema({
appId: z.string().min(1).meta({ ...FeedbackTargetSchema,
example: '68ad85a7463006c963799a05',
description: '应用 ID'
}),
chatId: z.string().min(1).meta({
example: 'chat123',
description: '对话 ID'
}),
dataId: z.string().min(1).meta({
example: 'data123',
description: '消息数据 ID'
}),
datasetId: z.string().min(1).meta({ datasetId: z.string().min(1).meta({
example: 'dataset123', example: 'dataset123',
description: '数据集 ID' description: '数据集 ID'
...@@ -62,49 +59,33 @@ export const AdminUpdateFeedbackBodySchema = z.object({ ...@@ -62,49 +59,33 @@ export const AdminUpdateFeedbackBodySchema = z.object({
description: '答案内容(可选)' description: '答案内容(可选)'
}) })
}); });
export type AdminUpdateFeedbackBodyType = z.infer<typeof AdminUpdateFeedbackBodySchema>; export const AdminUpdateFeedbackBodySchema =
AdminUpdateFeedbackBodyRawSchema.transform(transformChatTargetInput);
export type AdminUpdateFeedbackBodyType = z.infer<typeof AdminUpdateFeedbackBodyRawSchema>;
export type AdminUpdateFeedbackBodyRuntimeType = z.infer<typeof AdminUpdateFeedbackBodySchema>;
export const AdminUpdateFeedbackResponseSchema = z.undefined().meta({ description: '更新成功' }); export const AdminUpdateFeedbackResponseSchema = z.undefined().meta({ description: '更新成功' });
export type AdminUpdateFeedbackResponseType = z.infer<typeof AdminUpdateFeedbackResponseSchema>; export type AdminUpdateFeedbackResponseType = z.infer<typeof AdminUpdateFeedbackResponseSchema>;
/* =============== closeCustom =============== */ /* =============== closeCustom =============== */
export const CloseCustomFeedbackBodySchema = z.object({ export const CloseCustomFeedbackBodyRawSchema = createChatTargetInputSchema({
appId: z.string().min(1).meta({ ...FeedbackTargetSchema,
example: '68ad85a7463006c963799a05',
description: '应用 ID'
}),
chatId: z.string().min(1).meta({
example: 'chat123',
description: '对话 ID'
}),
dataId: z.string().min(1).meta({
example: 'data123',
description: '消息数据 ID'
}),
index: z.number().int().nonnegative().meta({ index: z.number().int().nonnegative().meta({
example: 0, example: 0,
description: '自定义反馈的索引位置' description: '自定义反馈的索引位置'
}) })
}); });
export type CloseCustomFeedbackBodyType = z.infer<typeof CloseCustomFeedbackBodySchema>; export const CloseCustomFeedbackBodySchema =
CloseCustomFeedbackBodyRawSchema.transform(transformChatTargetInput);
export type CloseCustomFeedbackBodyType = z.infer<typeof CloseCustomFeedbackBodyRawSchema>;
export type CloseCustomFeedbackBodyRuntimeType = z.infer<typeof CloseCustomFeedbackBodySchema>;
export const CloseCustomFeedbackResponseSchema = z.undefined().meta({ description: '关闭成功' }); export const CloseCustomFeedbackResponseSchema = z.undefined().meta({ description: '关闭成功' });
export type CloseCustomFeedbackResponseType = z.infer<typeof CloseCustomFeedbackResponseSchema>; export type CloseCustomFeedbackResponseType = z.infer<typeof CloseCustomFeedbackResponseSchema>;
/* =============== updateUserFeedback =============== */ /* =============== updateUserFeedback =============== */
export const UpdateUserFeedbackBodySchema = z.object({ export const UpdateUserFeedbackBodyRawSchema = createChatTargetInputSchema({
appId: z.string().min(1).meta({ ...FeedbackTargetSchema,
example: '68ad85a7463006c963799a05',
description: '应用 ID'
}),
chatId: z.string().min(1).meta({
example: 'chat123',
description: '对话 ID'
}),
dataId: z.string().min(1).meta({
example: 'data123',
description: '消息数据 ID'
}),
userGoodFeedback: z.string().nullish().meta({ userGoodFeedback: z.string().nullish().meta({
example: '回答很好', example: '回答很好',
description: '用户好评反馈内容' description: '用户好评反馈内容'
...@@ -114,17 +95,16 @@ export const UpdateUserFeedbackBodySchema = z.object({ ...@@ -114,17 +95,16 @@ export const UpdateUserFeedbackBodySchema = z.object({
description: '用户差评反馈内容' description: '用户差评反馈内容'
}) })
}); });
export type UpdateUserFeedbackBodyType = z.infer<typeof UpdateUserFeedbackBodySchema>; export const UpdateUserFeedbackBodySchema =
UpdateUserFeedbackBodyRawSchema.transform(transformChatTargetInput);
export type UpdateUserFeedbackBodyType = z.infer<typeof UpdateUserFeedbackBodyRawSchema>;
export type UpdateUserFeedbackBodyRuntimeType = z.infer<typeof UpdateUserFeedbackBodySchema>;
export const UpdateUserFeedbackResponseSchema = z.undefined().meta({ description: '更新成功' }); export const UpdateUserFeedbackResponseSchema = z.undefined().meta({ description: '更新成功' });
export type UpdateUserFeedbackResponseType = z.infer<typeof UpdateUserFeedbackResponseSchema>; export type UpdateUserFeedbackResponseType = z.infer<typeof UpdateUserFeedbackResponseSchema>;
/* =============== getFeedbackRecordIds =============== */ /* =============== getFeedbackRecordIds =============== */
export const GetFeedbackRecordIdsBodySchema = z.object({ export const GetFeedbackRecordIdsBodyRawSchema = createChatTargetInputSchema({
appId: z.string().meta({
example: '68ad85a7463006c963799a05',
description: '应用 ID'
}),
chatId: z.string().meta({ chatId: z.string().meta({
example: 'chat123', example: 'chat123',
description: '对话 ID' description: '对话 ID'
...@@ -138,7 +118,10 @@ export const GetFeedbackRecordIdsBodySchema = z.object({ ...@@ -138,7 +118,10 @@ export const GetFeedbackRecordIdsBodySchema = z.object({
description: '是否只返回未读的反馈' description: '是否只返回未读的反馈'
}) })
}); });
export type GetFeedbackRecordIdsBodyType = z.infer<typeof GetFeedbackRecordIdsBodySchema>; export const GetFeedbackRecordIdsBodySchema =
GetFeedbackRecordIdsBodyRawSchema.transform(transformChatTargetInput);
export type GetFeedbackRecordIdsBodyType = z.infer<typeof GetFeedbackRecordIdsBodyRawSchema>;
export type GetFeedbackRecordIdsBodyRuntimeType = z.infer<typeof GetFeedbackRecordIdsBodySchema>;
export const GetFeedbackRecordIdsResponseSchema = z.object({ export const GetFeedbackRecordIdsResponseSchema = z.object({
total: z.number().int().nonnegative().meta({ total: z.number().int().nonnegative().meta({
......
...@@ -2,15 +2,15 @@ import type { OpenAPIPath } from '../../../type'; ...@@ -2,15 +2,15 @@ import type { OpenAPIPath } from '../../../type';
import { DevApiTagsMap } from '../../../tag'; import { DevApiTagsMap } from '../../../tag';
import { SystemOpenApiTagMap } from '../../../tag'; import { SystemOpenApiTagMap } from '../../../tag';
import { import {
UpdateFeedbackReadStatusBodySchema, UpdateFeedbackReadStatusBodyRawSchema,
UpdateFeedbackReadStatusResponseSchema, UpdateFeedbackReadStatusResponseSchema,
AdminUpdateFeedbackBodySchema, AdminUpdateFeedbackBodyRawSchema,
AdminUpdateFeedbackResponseSchema, AdminUpdateFeedbackResponseSchema,
CloseCustomFeedbackBodySchema, CloseCustomFeedbackBodyRawSchema,
CloseCustomFeedbackResponseSchema, CloseCustomFeedbackResponseSchema,
UpdateUserFeedbackBodySchema, UpdateUserFeedbackBodyRawSchema,
UpdateUserFeedbackResponseSchema, UpdateUserFeedbackResponseSchema,
GetFeedbackRecordIdsBodySchema, GetFeedbackRecordIdsBodyRawSchema,
GetFeedbackRecordIdsResponseSchema GetFeedbackRecordIdsResponseSchema
} from './api'; } from './api';
...@@ -23,7 +23,7 @@ export const ChatFeedbackPath: OpenAPIPath = { ...@@ -23,7 +23,7 @@ export const ChatFeedbackPath: OpenAPIPath = {
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: UpdateUserFeedbackBodySchema schema: UpdateUserFeedbackBodyRawSchema
} }
} }
}, },
...@@ -47,7 +47,7 @@ export const ChatFeedbackPath: OpenAPIPath = { ...@@ -47,7 +47,7 @@ export const ChatFeedbackPath: OpenAPIPath = {
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: GetFeedbackRecordIdsBodySchema schema: GetFeedbackRecordIdsBodyRawSchema
} }
} }
}, },
...@@ -65,13 +65,13 @@ export const ChatFeedbackPath: OpenAPIPath = { ...@@ -65,13 +65,13 @@ export const ChatFeedbackPath: OpenAPIPath = {
}, },
'/core/chat/feedback/updateFeedbackReadStatus': { '/core/chat/feedback/updateFeedbackReadStatus': {
post: { post: {
summary: '应用管理员-更新反馈阅读状态', summary: '更新反馈阅读状态',
description: '标记指定消息的反馈为已读或未读状态', description: '标记指定消息的反馈为已读或未读状态',
tags: [DevApiTagsMap.chatFeedback], tags: [DevApiTagsMap.chatFeedback],
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: UpdateFeedbackReadStatusBodySchema schema: UpdateFeedbackReadStatusBodyRawSchema
} }
} }
}, },
...@@ -89,13 +89,13 @@ export const ChatFeedbackPath: OpenAPIPath = { ...@@ -89,13 +89,13 @@ export const ChatFeedbackPath: OpenAPIPath = {
}, },
'/core/chat/feedback/adminUpdate': { '/core/chat/feedback/adminUpdate': {
post: { post: {
summary: '应用管理员-标注反馈', summary: '标注反馈',
description: '管理员为指定消息添加或更新标注反馈,包含数据集关联信息', description: '为指定消息添加或更新标注反馈,包含数据集关联信息',
tags: [DevApiTagsMap.chatFeedback], tags: [DevApiTagsMap.chatFeedback],
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: AdminUpdateFeedbackBodySchema schema: AdminUpdateFeedbackBodyRawSchema
} }
} }
}, },
...@@ -113,13 +113,13 @@ export const ChatFeedbackPath: OpenAPIPath = { ...@@ -113,13 +113,13 @@ export const ChatFeedbackPath: OpenAPIPath = {
}, },
'/core/chat/feedback/closeCustom': { '/core/chat/feedback/closeCustom': {
post: { post: {
summary: '应用管理员-关闭自定义反馈', summary: '关闭自定义反馈',
description: '删除或关闭指定索引位置的自定义反馈条目', description: '删除或关闭指定索引位置的自定义反馈条目',
tags: [DevApiTagsMap.chatFeedback], tags: [DevApiTagsMap.chatFeedback],
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: CloseCustomFeedbackBodySchema schema: CloseCustomFeedbackBodyRawSchema
} }
} }
}, },
......
import { OutLinkChatAuthSchema } from '../../../../support/permission/chat'; import { OutLinkChatAuthSchema } from '../../../../support/permission/chat';
import { ObjectIdSchema } from '../../../../common/type/mongo';
import { AppFileSelectConfigTypeSchema } from '../../../../core/app/type/config.schema'; import { AppFileSelectConfigTypeSchema } from '../../../../core/app/type/config.schema';
import z from 'zod'; import z from 'zod';
import { createChatTargetInputSchema, transformChatTargetInput } from '../api';
/* ============ chat file ============ */ /* ============ chat file ============ */
export const PresignChatFileGetUrlSchema = z const withChatFileTarget = <T extends z.ZodRawShape>(shape: T) =>
.object({ createChatTargetInputSchema(shape).transform(transformChatTargetInput);
export const PresignChatFileGetUrlRawSchema = createChatTargetInputSchema({
key: z.string().min(1).describe('文件key'), key: z.string().min(1).describe('文件key'),
appId: ObjectIdSchema.describe('应用ID'), chatId: z.string().min(1).describe('对话ID'),
mode: z.enum(['proxy', 'presigned']).optional().describe('下载方式'), mode: z.enum(['proxy', 'presigned']).optional().describe('下载方式'),
outLinkAuthData: OutLinkChatAuthSchema.optional().describe('外链鉴权数据') outLinkAuthData: OutLinkChatAuthSchema.optional().describe('外链鉴权数据')
}) }).meta({
.meta({
example: { example: {
key: '1234567890', key: '1234567890',
appId: '1234567890', appId: '1234567890',
chatId: '1234567890',
outLinkAuthData: { outLinkAuthData: {
shareId: '1234567890', shareId: '1234567890',
outLinkUid: '1234567890' outLinkUid: '1234567890'
} }
} }
}); });
export type PresignChatFileGetUrlParams = z.infer<typeof PresignChatFileGetUrlSchema>; export const PresignChatFileGetUrlSchema = withChatFileTarget({
key: z.string().min(1).describe('文件key'),
chatId: z.string().min(1).describe('对话ID'),
mode: z.enum(['proxy', 'presigned']).optional().describe('下载方式'),
outLinkAuthData: OutLinkChatAuthSchema.optional().describe('外链鉴权数据')
});
export type PresignChatFileGetUrlParams = z.input<typeof PresignChatFileGetUrlSchema>;
export type PresignChatFileGetUrlRuntimeParams = z.output<typeof PresignChatFileGetUrlSchema>;
export const PresignChatFilePostUrlSchema = z export const PresignChatFilePostUrlRawSchema = createChatTargetInputSchema({
.object({
filename: z.string().min(1).describe('文件名'), filename: z.string().min(1).describe('文件名'),
appId: ObjectIdSchema.describe('应用ID'),
chatId: z.string().min(1).describe('对话ID'), chatId: z.string().min(1).describe('对话ID'),
fileSelectConfig: AppFileSelectConfigTypeSchema.describe('本次上传控件的文件选择配置'), fileSelectConfig: AppFileSelectConfigTypeSchema.describe('本次上传控件的文件选择配置'),
outLinkAuthData: OutLinkChatAuthSchema.optional().describe('外链鉴权数据') outLinkAuthData: OutLinkChatAuthSchema.optional().describe('外链鉴权数据')
}) }).meta({
.meta({
example: { example: {
filename: '1234567890', filename: '1234567890',
appId: '1234567890', appId: '1234567890',
...@@ -45,5 +51,12 @@ export const PresignChatFilePostUrlSchema = z ...@@ -45,5 +51,12 @@ export const PresignChatFilePostUrlSchema = z
outLinkUid: '1234567890' outLinkUid: '1234567890'
} }
} }
}); });
export type PresignChatFilePostUrlParams = z.infer<typeof PresignChatFilePostUrlSchema>; export const PresignChatFilePostUrlSchema = withChatFileTarget({
filename: z.string().min(1).describe('文件名'),
chatId: z.string().min(1).describe('对话ID'),
fileSelectConfig: AppFileSelectConfigTypeSchema.describe('本次上传控件的文件选择配置'),
outLinkAuthData: OutLinkChatAuthSchema.optional().describe('外链鉴权数据')
});
export type PresignChatFilePostUrlParams = z.input<typeof PresignChatFilePostUrlSchema>;
export type PresignChatFilePostUrlRuntimeParams = z.output<typeof PresignChatFilePostUrlSchema>;
import type { OpenAPIPath } from '../../../type'; import type { OpenAPIPath } from '../../../type';
import { DevApiTagsMap } from '../../../tag'; import { DevApiTagsMap } from '../../../tag';
import { PresignChatFilePostUrlSchema, PresignChatFileGetUrlSchema } from './api'; import { PresignChatFilePostUrlRawSchema, PresignChatFileGetUrlRawSchema } from './api';
import { CreatePostPresignedUrlResponseSchema } from '../../../../common/file/s3/type'; import { CreatePostPresignedUrlResponseSchema } from '../../../../common/file/s3/type';
import { z } from 'zod'; import { z } from 'zod';
...@@ -13,7 +13,7 @@ export const ChatFilePath: OpenAPIPath = { ...@@ -13,7 +13,7 @@ export const ChatFilePath: OpenAPIPath = {
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: PresignChatFilePostUrlSchema schema: PresignChatFilePostUrlRawSchema
} }
} }
}, },
...@@ -37,7 +37,7 @@ export const ChatFilePath: OpenAPIPath = { ...@@ -37,7 +37,7 @@ export const ChatFilePath: OpenAPIPath = {
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: PresignChatFileGetUrlSchema schema: PresignChatFileGetUrlRawSchema
} }
} }
}, },
......
...@@ -4,9 +4,13 @@ import { DevApiTagsMap } from '../../../tag'; ...@@ -4,9 +4,13 @@ import { DevApiTagsMap } from '../../../tag';
import { import {
HelperBotCompletionsParamsSchema, HelperBotCompletionsParamsSchema,
DeleteHelperBotChatParamsSchema, DeleteHelperBotChatParamsSchema,
GetHelperBotFilePresignParamsSchema,
GetHelperBotFilePreviewParamsSchema,
GetHelperBotFilePreviewResponseSchema,
GetHelperBotChatRecordsParamsSchema, GetHelperBotChatRecordsParamsSchema,
GetHelperBotChatRecordsResponseSchema GetHelperBotChatRecordsResponseSchema
} from './api'; } from './api';
import { CreatePostPresignedUrlResponseSchema } from '../../../../common/file/s3/type';
export const HelperBotPath: OpenAPIPath = { export const HelperBotPath: OpenAPIPath = {
'/proApi/core/chat/helperBot/completions': { '/proApi/core/chat/helperBot/completions': {
...@@ -76,5 +80,53 @@ export const HelperBotPath: OpenAPIPath = { ...@@ -76,5 +80,53 @@ export const HelperBotPath: OpenAPIPath = {
} }
} }
} }
},
'/core/chat/helperBot/getFilePresign': {
post: {
summary: '获取辅助助手文件上传签名',
description: '获取辅助助手文件上传签名',
tags: [DevApiTagsMap.helperBot],
requestBody: {
content: {
'application/json': {
schema: GetHelperBotFilePresignParamsSchema
}
}
},
responses: {
200: {
description: '成功返回文件上传签名',
content: {
'application/json': {
schema: CreatePostPresignedUrlResponseSchema
}
}
}
}
}
},
'/core/chat/helperBot/getFilePreviewUrl': {
post: {
summary: '获取辅助助手文件预览链接',
description: '获取辅助助手文件预览链接',
tags: [DevApiTagsMap.helperBot],
requestBody: {
content: {
'application/json': {
schema: GetHelperBotFilePreviewParamsSchema
}
}
},
responses: {
200: {
description: '成功返回文件预览链接',
content: {
'application/json': {
schema: GetHelperBotFilePreviewResponseSchema
}
}
}
}
}
} }
}; };
import z from 'zod'; import z from 'zod';
import { ObjectIdSchema } from '../../../../common/type/mongo';
import { OutLinkChatAuthSchema } from '../../../../support/permission/chat';
import { ChatSourceEnum } from '../../../../core/chat/constants'; import { ChatSourceEnum } from '../../../../core/chat/constants';
import { PaginationSchema, PaginationResponseSchema } from '../../../api'; import { PaginationSchema, PaginationResponseSchema } from '../../../api';
import { ChatGenerateStatusSchema } from '../api'; import {
ChatGenerateStatusSchema,
createChatTargetInputSchema,
createOptionalOutLinkChatTargetInputSchema,
createOutLinkChatTargetInputSchema,
refineOptionalChatTargetInput,
transformChatTargetInput,
transformOptionalChatTargetInput
} from '../api';
// Get chat sessions schema // Get chat sessions schema
export const GetHistoriesBodySchema = PaginationSchema.extend(OutLinkChatAuthSchema.shape).extend({ const GetHistoriesPropsSchema = {
appId: z.string().optional().describe('应用ID'),
source: z.enum(ChatSourceEnum).optional().describe('对话来源'), source: z.enum(ChatSourceEnum).optional().describe('对话来源'),
startCreateTime: z.string().optional().describe('创建时间开始'), startCreateTime: z.string().optional().describe('创建时间开始'),
endCreateTime: z.string().optional().describe('创建时间结束'), endCreateTime: z.string().optional().describe('创建时间结束'),
startUpdateTime: z.string().optional().describe('更新时间开始'), startUpdateTime: z.string().optional().describe('更新时间开始'),
endUpdateTime: z.string().optional().describe('更新时间结束') endUpdateTime: z.string().optional().describe('更新时间结束')
}); };
export type GetHistoriesBodyType = z.infer<typeof GetHistoriesBodySchema>; export const GetHistoriesBodyRawSchema = PaginationSchema.extend(
createOptionalOutLinkChatTargetInputSchema(GetHistoriesPropsSchema).shape
).superRefine(refineOptionalChatTargetInput);
export const GetHistoriesBodySchema = GetHistoriesBodyRawSchema.transform(
transformOptionalChatTargetInput
);
export type GetHistoriesBodyType = z.infer<typeof GetHistoriesBodyRawSchema>;
export type GetHistoriesBodyRuntimeType = z.infer<typeof GetHistoriesBodySchema>;
export const GetHistoriesResponseSchema = PaginationResponseSchema( export const GetHistoriesResponseSchema = PaginationResponseSchema(
z.object({ z.object({
chatId: z.string(), chatId: z.string(),
...@@ -29,11 +42,16 @@ export const GetHistoriesResponseSchema = PaginationResponseSchema( ...@@ -29,11 +42,16 @@ export const GetHistoriesResponseSchema = PaginationResponseSchema(
); );
export type GetHistoriesResponseType = z.infer<typeof GetHistoriesResponseSchema>; export type GetHistoriesResponseType = z.infer<typeof GetHistoriesResponseSchema>;
export const GetHistoryStatusBodySchema = OutLinkChatAuthSchema.extend({ const GetHistoryStatusPropsSchema = {
appId: ObjectIdSchema.optional().describe('应用ID'),
chatIds: z.array(z.string().min(1)).min(1).max(200).describe('需要刷新状态的会话 ID 列表') chatIds: z.array(z.string().min(1)).min(1).max(200).describe('需要刷新状态的会话 ID 列表')
}); };
export type GetHistoryStatusBodyType = z.infer<typeof GetHistoryStatusBodySchema>; export const GetHistoryStatusBodyRawSchema = createOutLinkChatTargetInputSchema(
GetHistoryStatusPropsSchema
);
export const GetHistoryStatusBodySchema =
GetHistoryStatusBodyRawSchema.transform(transformChatTargetInput);
export type GetHistoryStatusBodyType = z.infer<typeof GetHistoryStatusBodyRawSchema>;
export type GetHistoryStatusBodyRuntimeType = z.infer<typeof GetHistoryStatusBodySchema>;
export const GetHistoryStatusResponseSchema = z.object({ export const GetHistoryStatusResponseSchema = z.object({
list: z.array( list: z.array(
...@@ -47,38 +65,49 @@ export const GetHistoryStatusResponseSchema = z.object({ ...@@ -47,38 +65,49 @@ export const GetHistoryStatusResponseSchema = z.object({
}); });
export type GetHistoryStatusResponseType = z.infer<typeof GetHistoryStatusResponseSchema>; export type GetHistoryStatusResponseType = z.infer<typeof GetHistoryStatusResponseSchema>;
export const MarkChatReadBodySchema = OutLinkChatAuthSchema.extend({ const MarkChatReadPropsSchema = {
appId: ObjectIdSchema.describe('应用ID'),
chatId: z.string().min(1).describe('会话ID') chatId: z.string().min(1).describe('会话ID')
}); };
export type MarkChatReadBodyType = z.infer<typeof MarkChatReadBodySchema>; export const MarkChatReadBodyRawSchema =
createOutLinkChatTargetInputSchema(MarkChatReadPropsSchema);
export const MarkChatReadBodySchema = MarkChatReadBodyRawSchema.transform(transformChatTargetInput);
export type MarkChatReadBodyType = z.infer<typeof MarkChatReadBodyRawSchema>;
export type MarkChatReadBodyRuntimeType = z.infer<typeof MarkChatReadBodySchema>;
// Update chat session schema // Update chat session schema
export const UpdateHistoryBodySchema = OutLinkChatAuthSchema.extend({ const UpdateHistoryPropsSchema = {
appId: ObjectIdSchema.describe('应用ID'),
chatId: z.string().min(1).describe('会话ID'), chatId: z.string().min(1).describe('会话ID'),
title: z.string().optional().describe('标题'), title: z.string().optional().describe('标题'),
customTitle: z.string().optional().describe('自定义标题'), customTitle: z.string().optional().describe('自定义标题'),
top: z.boolean().optional().describe('是否置顶') top: z.boolean().optional().describe('是否置顶')
}); };
export type UpdateHistoryBodyType = z.infer<typeof UpdateHistoryBodySchema>; export const UpdateHistoryBodyRawSchema =
createOutLinkChatTargetInputSchema(UpdateHistoryPropsSchema);
export const UpdateHistoryBodySchema =
UpdateHistoryBodyRawSchema.transform(transformChatTargetInput);
export type UpdateHistoryBodyType = z.infer<typeof UpdateHistoryBodyRawSchema>;
export type UpdateHistoryBodyRuntimeType = z.infer<typeof UpdateHistoryBodySchema>;
// Delete single chat session schema // Delete single chat session schema
export const DelChatHistorySchema = OutLinkChatAuthSchema.extend({ export const DelChatHistoryRawSchema = createOptionalOutLinkChatTargetInputSchema({
appId: ObjectIdSchema.optional().describe('应用ID'),
chatId: z.string().min(1).describe('会话ID') chatId: z.string().min(1).describe('会话ID')
}); });
export type DelChatHistoryType = z.infer<typeof DelChatHistorySchema>; export const DelChatHistorySchema = DelChatHistoryRawSchema.transform(
transformOptionalChatTargetInput
);
export type DelChatHistoryType = z.infer<typeof DelChatHistoryRawSchema>;
export type DelChatHistoryRuntimeType = z.infer<typeof DelChatHistorySchema>;
// Clear all chat sessions schema // Clear all chat sessions schema
export const ClearChatHistoriesSchema = OutLinkChatAuthSchema.extend({ export const ClearChatHistoriesRawSchema = createOptionalOutLinkChatTargetInputSchema({});
appId: ObjectIdSchema.optional().describe('应用ID') export const ClearChatHistoriesSchema = ClearChatHistoriesRawSchema.transform(
}); transformOptionalChatTargetInput
export type ClearChatHistoriesType = z.infer<typeof ClearChatHistoriesSchema>; );
export type ClearChatHistoriesType = z.infer<typeof ClearChatHistoriesRawSchema>;
export type ClearChatHistoriesRuntimeType = z.infer<typeof ClearChatHistoriesSchema>;
// Batch delete chat sessions schema (for log manager) // Batch delete chat sessions schema (for log manager)
export const ChatBatchDeleteBodySchema = z.object({ export const ChatBatchDeleteBodyRawSchema = createChatTargetInputSchema({
appId: ObjectIdSchema,
chatIds: z chatIds: z
.array(z.string().min(1)) .array(z.string().min(1))
.min(1) .min(1)
...@@ -87,4 +116,7 @@ export const ChatBatchDeleteBodySchema = z.object({ ...@@ -87,4 +116,7 @@ export const ChatBatchDeleteBodySchema = z.object({
example: ['chat_123456', 'chat_789012'] example: ['chat_123456', 'chat_789012']
}) })
}); });
export type ChatBatchDeleteBodyType = z.infer<typeof ChatBatchDeleteBodySchema>; export const ChatBatchDeleteBodySchema =
ChatBatchDeleteBodyRawSchema.transform(transformChatTargetInput);
export type ChatBatchDeleteBodyType = z.infer<typeof ChatBatchDeleteBodyRawSchema>;
export type ChatBatchDeleteBodyRuntimeType = z.infer<typeof ChatBatchDeleteBodySchema>;
import type { OpenAPIPath } from '../../../type'; import type { OpenAPIPath } from '../../../type';
import { DevApiTagsMap, SystemOpenApiTagMap } from '../../../tag'; import { DevApiTagsMap, SystemOpenApiTagMap } from '../../../tag';
import { import {
GetHistoriesBodySchema, GetHistoriesBodyRawSchema,
GetHistoriesResponseSchema, GetHistoriesResponseSchema,
GetHistoryStatusBodySchema, GetHistoryStatusBodyRawSchema,
GetHistoryStatusResponseSchema, GetHistoryStatusResponseSchema,
MarkChatReadBodySchema, MarkChatReadBodyRawSchema,
UpdateHistoryBodySchema, UpdateHistoryBodyRawSchema,
ChatBatchDeleteBodySchema, ChatBatchDeleteBodyRawSchema,
DelChatHistorySchema, DelChatHistoryRawSchema,
ClearChatHistoriesSchema ClearChatHistoriesRawSchema
} from './api'; } from './api';
export const ChatHistoryPath: OpenAPIPath = { export const ChatHistoryPath: OpenAPIPath = {
'/core/chat/history/getHistories': { '/core/chat/history/getHistories': {
post: { post: {
summary: '获取会话列表', summary: '获取会话列表',
description: '分页获取指定应用的会话', description: '分页获取会话列表',
tags: [DevApiTagsMap.chatHistory, SystemOpenApiTagMap.chatHistory], tags: [DevApiTagsMap.chatHistory, SystemOpenApiTagMap.chatHistory],
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: GetHistoriesBodySchema schema: GetHistoriesBodyRawSchema
} }
} }
}, },
...@@ -46,7 +46,7 @@ export const ChatHistoryPath: OpenAPIPath = { ...@@ -46,7 +46,7 @@ export const ChatHistoryPath: OpenAPIPath = {
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: GetHistoryStatusBodySchema schema: GetHistoryStatusBodyRawSchema
} }
} }
}, },
...@@ -70,7 +70,7 @@ export const ChatHistoryPath: OpenAPIPath = { ...@@ -70,7 +70,7 @@ export const ChatHistoryPath: OpenAPIPath = {
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: MarkChatReadBodySchema schema: MarkChatReadBodyRawSchema
} }
} }
}, },
...@@ -89,7 +89,7 @@ export const ChatHistoryPath: OpenAPIPath = { ...@@ -89,7 +89,7 @@ export const ChatHistoryPath: OpenAPIPath = {
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: UpdateHistoryBodySchema schema: UpdateHistoryBodyRawSchema
} }
} }
}, },
...@@ -106,7 +106,7 @@ export const ChatHistoryPath: OpenAPIPath = { ...@@ -106,7 +106,7 @@ export const ChatHistoryPath: OpenAPIPath = {
description: '软删除指定的单个会话,不会物理删除', description: '软删除指定的单个会话,不会物理删除',
tags: [DevApiTagsMap.chatHistory, SystemOpenApiTagMap.chatHistory], tags: [DevApiTagsMap.chatHistory, SystemOpenApiTagMap.chatHistory],
requestParams: { requestParams: {
query: DelChatHistorySchema query: DelChatHistoryRawSchema
}, },
responses: { responses: {
200: { 200: {
...@@ -117,11 +117,11 @@ export const ChatHistoryPath: OpenAPIPath = { ...@@ -117,11 +117,11 @@ export const ChatHistoryPath: OpenAPIPath = {
}, },
'/core/chat/history/clearHistories': { '/core/chat/history/clearHistories': {
delete: { delete: {
summary: '清空应用会话', summary: '清空会话',
description: '清空指定应用的所有会话(软删除)', description: '清空所有会话(软删除)',
tags: [DevApiTagsMap.chatHistory, SystemOpenApiTagMap.chatHistory], tags: [DevApiTagsMap.chatHistory, SystemOpenApiTagMap.chatHistory],
requestParams: { requestParams: {
query: ClearChatHistoriesSchema query: ClearChatHistoriesRawSchema
}, },
responses: { responses: {
200: { 200: {
...@@ -133,12 +133,12 @@ export const ChatHistoryPath: OpenAPIPath = { ...@@ -133,12 +133,12 @@ export const ChatHistoryPath: OpenAPIPath = {
'/core/chat/history/batchDelete': { '/core/chat/history/batchDelete': {
post: { post: {
summary: '批量删除会话', summary: '批量删除会话',
description: '批量删除指定应用的多个会话(真实删除),需应用日志管理权限。', description: '批量删除多个会话(真实删除),需对应会话目标的管理权限。',
tags: [DevApiTagsMap.chatHistory, SystemOpenApiTagMap.chatHistory], tags: [DevApiTagsMap.chatHistory, SystemOpenApiTagMap.chatHistory],
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: ChatBatchDeleteBodySchema schema: ChatBatchDeleteBodyRawSchema
} }
} }
}, },
......
...@@ -7,7 +7,7 @@ import { OutLinkChatAuthSchema } from '../../../../support/permission/chat'; ...@@ -7,7 +7,7 @@ import { OutLinkChatAuthSchema } from '../../../../support/permission/chat';
* API: 获取对话输入引导列表 * API: 获取对话输入引导列表
* Route: POST /api/core/chat/inputGuide/list * Route: POST /api/core/chat/inputGuide/list
* Method: POST * Method: POST
* Description: 获取指定应用的对话输入引导列表,支持关键词搜索 * Description: 获取对话输入引导列表,支持关键词搜索
* Tags: ['Chat', 'InputGuide', 'Read'] * Tags: ['Chat', 'InputGuide', 'Read']
* ============================================================================ */ * ============================================================================ */
...@@ -36,7 +36,7 @@ export type ChatInputGuideListResponseType = z.infer<typeof ChatInputGuideListRe ...@@ -36,7 +36,7 @@ export type ChatInputGuideListResponseType = z.infer<typeof ChatInputGuideListRe
* API: 统计对话输入引导总数 * API: 统计对话输入引导总数
* Route: GET /api/core/chat/inputGuide/countTotal * Route: GET /api/core/chat/inputGuide/countTotal
* Method: GET * Method: GET
* Description: 获取指定应用的对话输入引导总数 * Description: 获取对话输入引导总数
* Tags: ['Chat', 'InputGuide', 'Read'] * Tags: ['Chat', 'InputGuide', 'Read']
* ============================================================================ */ * ============================================================================ */
...@@ -102,10 +102,10 @@ export const DeleteChatInputGuideResponseSchema = z.undefined().meta({ descripti ...@@ -102,10 +102,10 @@ export const DeleteChatInputGuideResponseSchema = z.undefined().meta({ descripti
export type DeleteChatInputGuideResponseType = z.infer<typeof DeleteChatInputGuideResponseSchema>; export type DeleteChatInputGuideResponseType = z.infer<typeof DeleteChatInputGuideResponseSchema>;
/* ============================================================================ /* ============================================================================
* API: 删除应用所有对话输入引导 * API: 删除所有对话输入引导
* Route: DELETE /api/core/chat/inputGuide/deleteAll * Route: DELETE /api/core/chat/inputGuide/deleteAll
* Method: DELETE * Method: DELETE
* Description: 删除指定应用的所有对话输入引导 * Description: 删除所有对话输入引导
* Tags: ['Chat', 'InputGuide', 'Delete'] * Tags: ['Chat', 'InputGuide', 'Delete']
* ============================================================================ */ * ============================================================================ */
......
...@@ -20,7 +20,7 @@ export const ChatInputGuidePath: OpenAPIPath = { ...@@ -20,7 +20,7 @@ export const ChatInputGuidePath: OpenAPIPath = {
'/core/chat/inputGuide/list': { '/core/chat/inputGuide/list': {
post: { post: {
summary: '获取对话输入引导列表', summary: '获取对话输入引导列表',
description: '获取指定应用的对话输入引导列表,支持关键词模糊搜索和分页', description: '获取对话输入引导列表,支持关键词模糊搜索和分页',
tags: [DevApiTagsMap.chatInputGuide], tags: [DevApiTagsMap.chatInputGuide],
requestBody: { requestBody: {
content: { content: {
...@@ -44,7 +44,7 @@ export const ChatInputGuidePath: OpenAPIPath = { ...@@ -44,7 +44,7 @@ export const ChatInputGuidePath: OpenAPIPath = {
'/core/chat/inputGuide/countTotal': { '/core/chat/inputGuide/countTotal': {
get: { get: {
summary: '统计对话输入引导总数', summary: '统计对话输入引导总数',
description: '获取指定应用的对话输入引导总数', description: '获取对话输入引导总数',
tags: [DevApiTagsMap.chatInputGuide], tags: [DevApiTagsMap.chatInputGuide],
parameters: [ parameters: [
{ {
...@@ -116,8 +116,8 @@ export const ChatInputGuidePath: OpenAPIPath = { ...@@ -116,8 +116,8 @@ export const ChatInputGuidePath: OpenAPIPath = {
}, },
'/core/chat/inputGuide/deleteAll': { '/core/chat/inputGuide/deleteAll': {
delete: { delete: {
summary: '删除应用所有对话输入引导', summary: '删除所有对话输入引导',
description: '删除指定应用的所有对话输入引导', description: '删除所有对话输入引导',
tags: [DevApiTagsMap.chatInputGuide], tags: [DevApiTagsMap.chatInputGuide],
requestBody: { requestBody: {
content: { content: {
......
import type { OpenAPIPath } from '../../../type'; import type { OpenAPIPath } from '../../../type';
import { DevApiTagsMap, SystemOpenApiTagMap } from '../../../tag'; import { DevApiTagsMap, SystemOpenApiTagMap } from '../../../tag';
import { import {
GetResDataQuerySchema, GetResDataQueryRawSchema,
DeleteChatRecordBodySchema, DeleteChatRecordBodyRawSchema,
DeleteChatRecordResponseSchema, DeleteChatRecordResponseSchema,
GetQuoteBodySchema, GetQuoteBodyRawSchema,
GetQuoteResponseSchema, GetQuoteResponseSchema,
GetCollectionQuoteBodySchema, GetCollectionQuoteBodyRawSchema,
GetCollectionQuoteResSchema, GetCollectionQuoteResSchema,
GetPaginationRecordsBodySchema, GetPaginationRecordsBodyRawSchema,
GetPaginationRecordsResponseSchema, GetPaginationRecordsResponseSchema,
GetRecordsV2BodySchema, GetRecordsV2BodyRawSchema,
GetRecordsV2ResponseSchema, GetRecordsV2ResponseSchema,
GetChatSpeechBodySchema GetChatSpeechBodySchema,
AudioTranscriptionsFormRawSchema
} from './api'; } from './api';
export const ChatRecordPath: OpenAPIPath = { export const ChatRecordPath: OpenAPIPath = {
'/core/chat/record/getPaginationRecords': { '/core/chat/record/getPaginationRecords': {
post: { post: {
summary: '分页获取对话', summary: '分页获取对话',
description: '分页获取指定应用和会话的对话,支持多种鉴权模式', description: '分页获取指定会话的对话,支持多种鉴权模式',
tags: [DevApiTagsMap.chatRecord, SystemOpenApiTagMap.chat], tags: [DevApiTagsMap.chatRecord, SystemOpenApiTagMap.chat],
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: GetPaginationRecordsBodySchema schema: GetPaginationRecordsBodyRawSchema
} }
} }
}, },
...@@ -43,12 +44,12 @@ export const ChatRecordPath: OpenAPIPath = { ...@@ -43,12 +44,12 @@ export const ChatRecordPath: OpenAPIPath = {
'/core/chat/record/getRecords_v2': { '/core/chat/record/getRecords_v2': {
post: { post: {
summary: '根据锚点获取对话', summary: '根据锚点获取对话',
description: '根据锚点获取指定应用和会话的对话,支持多种鉴权模式', description: '根据锚点获取指定会话的对话,支持多种鉴权模式',
tags: [DevApiTagsMap.chatRecord, SystemOpenApiTagMap.chat], tags: [DevApiTagsMap.chatRecord, SystemOpenApiTagMap.chat],
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: GetRecordsV2BodySchema schema: GetRecordsV2BodyRawSchema
} }
} }
}, },
...@@ -71,7 +72,7 @@ export const ChatRecordPath: OpenAPIPath = { ...@@ -71,7 +72,7 @@ export const ChatRecordPath: OpenAPIPath = {
description: '根据 dataId 获取对话中某条 AI 回复的详细响应数据', description: '根据 dataId 获取对话中某条 AI 回复的详细响应数据',
tags: [DevApiTagsMap.chatRecord, SystemOpenApiTagMap.chat], tags: [DevApiTagsMap.chatRecord, SystemOpenApiTagMap.chat],
requestParams: { requestParams: {
query: GetResDataQuerySchema query: GetResDataQueryRawSchema
}, },
responses: { responses: {
200: { 200: {
...@@ -89,7 +90,7 @@ export const ChatRecordPath: OpenAPIPath = { ...@@ -89,7 +90,7 @@ export const ChatRecordPath: OpenAPIPath = {
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: GetQuoteBodySchema schema: GetQuoteBodyRawSchema
} }
} }
}, },
...@@ -113,7 +114,7 @@ export const ChatRecordPath: OpenAPIPath = { ...@@ -113,7 +114,7 @@ export const ChatRecordPath: OpenAPIPath = {
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: GetCollectionQuoteBodySchema schema: GetCollectionQuoteBodyRawSchema
} }
} }
}, },
...@@ -138,7 +139,7 @@ export const ChatRecordPath: OpenAPIPath = { ...@@ -138,7 +139,7 @@ export const ChatRecordPath: OpenAPIPath = {
requestBody: { requestBody: {
content: { content: {
'application/json': { 'application/json': {
schema: DeleteChatRecordBodySchema schema: DeleteChatRecordBodyRawSchema
} }
} }
}, },
...@@ -172,5 +173,28 @@ export const ChatRecordPath: OpenAPIPath = { ...@@ -172,5 +173,28 @@ export const ChatRecordPath: OpenAPIPath = {
} }
} }
} }
},
'/v1/audio/transcriptions': {
post: {
summary: '语音转文字',
description:
'将 multipart/form-data 表单中的音频文件转换为文本。file 为音频文件,data 为 JSON 序列化后的对话鉴权参数。',
tags: [DevApiTagsMap.chatRecord],
requestBody: {
content: {
'multipart/form-data': {
schema: AudioTranscriptionsFormRawSchema,
encoding: {
data: { contentType: 'application/json' }
}
}
}
},
responses: {
200: {
description: '成功返回识别文本'
}
}
}
} }
}; };
...@@ -25,7 +25,7 @@ export const tagGroups = [ ...@@ -25,7 +25,7 @@ export const tagGroups = [
tags: [ApiKeyTagNameMap[SystemOpenApiTagMap.appLog]] tags: [ApiKeyTagNameMap[SystemOpenApiTagMap.appLog]]
}, },
{ {
name: '应用对话', name: '对话',
tags: [ tags: [
ApiKeyTagNameMap[SystemOpenApiTagMap.chatHistory], ApiKeyTagNameMap[SystemOpenApiTagMap.chatHistory],
ApiKeyTagNameMap[SystemOpenApiTagMap.chat], ApiKeyTagNameMap[SystemOpenApiTagMap.chat],
......
...@@ -12,6 +12,7 @@ export type UsageSchemaType = { ...@@ -12,6 +12,7 @@ export type UsageSchemaType = {
source: `${UsageSourceEnum}`; source: `${UsageSourceEnum}`;
appId?: string; appId?: string;
skillId?: string;
datasetId?: string; datasetId?: string;
/** @deprecated */ /** @deprecated */
......
import { describe, expect, it } from 'vitest';
import {
AudioTranscriptionsDataSchema,
AudioTranscriptionsFormRawSchema,
GetPaginationRecordsBodySchema,
GetRecordsV2BodySchema,
GetResDataQuerySchema
} from '../../../../openapi/core/chat/record/api';
import {
GetHistoriesBodySchema,
MarkChatReadBodySchema
} from '../../../../openapi/core/chat/history/api';
import { ResumeStreamParamsSchema } from '../../../../openapi/core/ai/api';
import { ChatSourceTypeEnum } from '../../../../core/chat/constants';
const appId = '68ad85a7463006c963799a05';
const skillId = '68ad85a7463006c963799a06';
describe('openapi/core/chat target schema', () => {
it('transforms raw appId to internal app source', () => {
const result = MarkChatReadBodySchema.parse({
appId,
chatId: 'chat-1'
});
expect(result).toMatchObject({
sourceType: ChatSourceTypeEnum.app,
sourceId: appId,
chatId: 'chat-1'
});
expect('appId' in result).toBe(false);
});
it('transforms raw skillId to internal skillEdit source', () => {
const result = GetResDataQuerySchema.parse({
skillId,
chatId: 'chat-1',
dataId: 'data-1'
});
expect(result).toMatchObject({
sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId,
chatId: 'chat-1',
dataId: 'data-1'
});
expect('skillId' in result).toBe(false);
});
it('rejects required target when appId and skillId are both provided', () => {
const payload = {
appId,
skillId,
chatId: 'chat-1'
};
expect(() => MarkChatReadBodySchema.parse(payload)).toThrow();
expect(() =>
GetPaginationRecordsBodySchema.parse({
...payload,
pageSize: 10,
offset: 0
})
).toThrow();
expect(() =>
GetRecordsV2BodySchema.parse({
...payload,
pageSize: 10
})
).toThrow();
expect(() => ResumeStreamParamsSchema.parse(payload)).toThrow();
});
it('rejects required target when appId and skillId are both missing', () => {
expect(() => MarkChatReadBodySchema.parse({ chatId: 'chat-1' })).toThrow();
});
it('allows optional target to be omitted but rejects ambiguous optional target', () => {
expect(
GetHistoriesBodySchema.parse({
pageSize: 10,
offset: 0
})
).toMatchObject({
pageSize: 10,
offset: 0
});
expect(() =>
GetHistoriesBodySchema.parse({
appId,
skillId,
pageSize: 10,
offset: 0
})
).toThrow();
});
it('keeps audio transcription OpenAPI form raw while runtime data transforms to source', () => {
const form = AudioTranscriptionsFormRawSchema.parse({
file: 'binary-file-placeholder',
data: {
skillId,
chatId: 'chat-1',
duration: 3
}
});
expect(form.data).toMatchObject({
skillId,
chatId: 'chat-1',
duration: 3
});
expect('sourceType' in form.data).toBe(false);
expect('sourceId' in form.data).toBe(false);
const runtimeData = AudioTranscriptionsDataSchema.parse(form.data);
expect(runtimeData).toMatchObject({
sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId,
chatId: 'chat-1',
duration: 3
});
expect('skillId' in runtimeData).toBe(false);
});
});
...@@ -11,7 +11,31 @@ import { ...@@ -11,7 +11,31 @@ import {
import { differenceInHours } from 'date-fns'; import { differenceInHours } from 'date-fns';
import { S3Buckets } from '../../config/constants'; import { S3Buckets } from '../../config/constants';
import path from 'path'; import path from 'path';
import { getFileS3Key } from '../../utils'; import { getFormatedFilename } from '../../utils';
import type { ChatS3SourceType } from './type';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
const getChatFileS3Key = ({
sourceType,
sourceId,
chatId,
uId,
filename
}: {
sourceType: ChatS3SourceType;
sourceId: string;
chatId: string;
uId: string;
filename?: string;
}) => {
const { formatedFilename, extension } = getFormatedFilename(filename);
const basePrefix = [S3Sources.chat, sourceType, sourceId, uId, chatId].filter(Boolean).join('/');
return {
fileKey: [basePrefix, `${formatedFilename}${extension ? `.${extension}` : ''}`].join('/'),
fileParsedPrefix: [basePrefix, `${formatedFilename}-parsed`].join('/')
};
};
export class S3ChatSource extends S3PrivateBucket { export class S3ChatSource extends S3PrivateBucket {
constructor() { constructor() {
...@@ -39,7 +63,7 @@ export class S3ChatSource extends S3PrivateBucket { ...@@ -39,7 +63,7 @@ export class S3ChatSource extends S3PrivateBucket {
extension: extension.replace('.', ''), extension: extension.replace('.', ''),
imageParsePrefix: `${pathname.replace(`/${S3Buckets.private}/`, '').replace(extension, '')}-parsed` imageParsePrefix: `${pathname.replace(`/${S3Buckets.private}/`, '').replace(extension, '')}-parsed`
}; };
} catch (error) { } catch {
return { return {
filename: '', filename: '',
extension: '', extension: '',
...@@ -63,9 +87,17 @@ export class S3ChatSource extends S3PrivateBucket { ...@@ -63,9 +87,17 @@ export class S3ChatSource extends S3PrivateBucket {
} }
async createUploadChatFileURL(params: CheckChatFileKeys) { async createUploadChatFileURL(params: CheckChatFileKeys) {
const { appId, chatId, uId, filename, expiredTime, maxFileSize, allowedExtensions } = const {
ChatFileUploadSchema.parse(params); sourceType,
const { fileKey } = getFileS3Key.chat({ appId, chatId, uId, filename }); sourceId,
chatId,
uId,
filename,
expiredTime,
maxFileSize,
allowedExtensions
} = ChatFileUploadSchema.parse(params);
const { fileKey } = getChatFileS3Key({ sourceType, sourceId, chatId, uId, filename });
return await this.createPresignedPutUrl( return await this.createPresignedPutUrl(
{ rawKey: fileKey, filename }, { rawKey: fileKey, filename },
{ {
...@@ -79,14 +111,20 @@ export class S3ChatSource extends S3PrivateBucket { ...@@ -79,14 +111,20 @@ export class S3ChatSource extends S3PrivateBucket {
} }
async deleteChatFilesByPrefix(params: DelChatFileByPrefixParams) { async deleteChatFilesByPrefix(params: DelChatFileByPrefixParams) {
const { appId, chatId, uId } = DelChatFileByPrefixSchema.parse(params); const { sourceType, sourceId, chatId, uId } = DelChatFileByPrefixSchema.parse(params);
const prefix = [S3Sources.chat, appId, uId, chatId].filter(Boolean).join('/'); const prefix = [S3Sources.chat, sourceType, sourceId, uId, chatId].filter(Boolean).join('/');
const publicBucket = global.s3BucketMap[S3Buckets.public]; const publicBucket = global.s3BucketMap[S3Buckets.public];
await this.addDeleteJob({ prefix }); await this.addDeleteJob({ prefix });
await publicBucket.addDeleteJob({ prefix }); await publicBucket.addDeleteJob({ prefix });
if (sourceType === ChatSourceTypeEnum.app) {
const legacyPrefix = [S3Sources.chat, sourceId, uId, chatId].filter(Boolean).join('/');
await this.addDeleteJob({ prefix: legacyPrefix });
await publicBucket.addDeleteJob({ prefix: legacyPrefix });
}
return prefix; return prefix;
} }
...@@ -96,10 +134,11 @@ export class S3ChatSource extends S3PrivateBucket { ...@@ -96,10 +134,11 @@ export class S3ChatSource extends S3PrivateBucket {
} }
async uploadChatFile(params: UploadFileParams) { async uploadChatFile(params: UploadFileParams) {
const { appId, chatId, uId, filename, body, contentType, expiredTime } = const { sourceType, sourceId, chatId, uId, filename, body, contentType, expiredTime } =
UploadChatFileSchema.parse(params); UploadChatFileSchema.parse(params);
const { fileKey } = getFileS3Key.chat({ const { fileKey } = getChatFileS3Key({
appId, sourceType,
sourceId,
chatId, chatId,
uId, uId,
filename filename
...@@ -114,9 +153,14 @@ export class S3ChatSource extends S3PrivateBucket { ...@@ -114,9 +153,14 @@ export class S3ChatSource extends S3PrivateBucket {
}); });
} }
getToolFilePrefix(params: { appId: string; chatId: string; uId: string }) { getToolFilePrefix(params: {
const { appId, chatId, uId } = params; sourceType: ChatS3SourceType;
return [S3Sources.chat, appId, uId, chatId].filter(Boolean).join('/'); sourceId: string;
chatId: string;
uId: string;
}) {
const { sourceType, sourceId, chatId, uId } = params;
return [S3Sources.chat, sourceType, sourceId, uId, chatId].filter(Boolean).join('/');
} }
} }
......
import { isS3ObjectKey } from '../../utils'; import { isS3ObjectKey } from '../../utils';
import { ChatS3SourceTypeSchema, type ChatS3SourceType } from './type';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
export type ParsedChatFileS3Key = {
sourceType: ChatS3SourceType;
sourceId: string;
uid: string;
chatId: string;
filename: string;
legacyAppKey: boolean;
};
/** /**
* 解析聊天文件的 S3 key。 * 解析聊天文件的 S3 key。
* *
* 聊天文件 key 的授权边界由 appId 与 uid 决定。任何签名或读取前都应先解析 * 新格式为 `chat/${sourceType}/${sourceId}/${uid}/${chatId}/${filename}`。
* 这些路径段并与已鉴权上下文绑定,避免只校验一个无关 app 后签发任意 object key。 * legacy App 格式 `chat/${appId}/${uid}/${chatId}/${filename}` 继续按原始 key
* 读取,只在解析结果中归一化为 `sourceType=app` 供鉴权使用。
*/ */
export function parseChatFileS3Key(key: string): { export function parseChatFileS3Key(key: string): ParsedChatFileS3Key | null {
appId: string;
uid: string;
chatId: string;
filename: string;
} | null {
if (!isS3ObjectKey(key, 'chat')) return null; if (!isS3ObjectKey(key, 'chat')) return null;
const [, appId, uid, chatId, ...filenameParts] = key.split('/'); const [, firstSegment, secondSegment, thirdSegment, fourthSegment, ...filenameParts] =
const filename = filenameParts.join('/'); key.split('/');
const sourceTypeResult = ChatS3SourceTypeSchema.safeParse(firstSegment);
const isSourceAwareKey = sourceTypeResult.success;
if (!appId || !uid || !chatId || !filename) return null; const sourceType = isSourceAwareKey ? sourceTypeResult.data : ChatSourceTypeEnum.app;
const sourceId = isSourceAwareKey ? secondSegment : firstSegment;
const uid = isSourceAwareKey ? thirdSegment : secondSegment;
const chatId = isSourceAwareKey ? fourthSegment : thirdSegment;
const filename = (isSourceAwareKey ? filenameParts : [fourthSegment, ...filenameParts])
.filter(Boolean)
.join('/');
if (!sourceId || !uid || !chatId || !filename) return null;
return { return {
appId, sourceType,
sourceId,
uid, uid,
chatId, chatId,
filename filename,
legacyAppKey: !isSourceAwareKey
}; };
} }
/** /**
* 判断聊天文件 key 是否属于已鉴权的 app 与聊天用户。 * 判断聊天文件 key 是否属于已鉴权的 chat source 与聊天用户。
*/ */
export function isAuthorizedChatFileS3Key({ export function isAuthorizedChatFileS3Key({
key, key,
appId, sourceType,
uid sourceId,
uid,
chatId
}: { }: {
key: string; key: string;
appId: string; sourceType: ChatS3SourceType;
sourceId: string;
uid: string; uid: string;
chatId?: string;
}) { }) {
const parsedKey = parseChatFileS3Key(key); const parsedKey = parseChatFileS3Key(key);
return ( return (
!!parsedKey && !!parsedKey &&
String(parsedKey.appId) === String(appId) && parsedKey.sourceType === sourceType &&
String(parsedKey.uid) === String(uid) String(parsedKey.sourceId) === String(sourceId) &&
String(parsedKey.uid) === String(uid) &&
(chatId === undefined || String(parsedKey.chatId) === String(chatId))
); );
} }
import z from 'zod'; import z from 'zod';
import { ObjectIdSchema } from '@fastgpt/global/common/type/mongo'; import { ObjectIdSchema } from '@fastgpt/global/common/type/mongo';
import { UploadFileByBodySchema } from '../../contracts/type'; import { UploadFileByBodySchema } from '../../contracts/type';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
export const ChatS3SourceTypeSchema = z.enum(ChatSourceTypeEnum);
export type ChatS3SourceType = z.infer<typeof ChatS3SourceTypeSchema>;
export const ChatFileUploadSchema = z.object({ export const ChatFileUploadSchema = z.object({
appId: ObjectIdSchema, sourceType: ChatS3SourceTypeSchema,
sourceId: ObjectIdSchema,
chatId: z.string().nonempty(), chatId: z.string().nonempty(),
uId: z.string().nonempty(), uId: z.string().nonempty(),
filename: z.string().nonempty(), filename: z.string().nonempty(),
...@@ -11,17 +16,19 @@ export const ChatFileUploadSchema = z.object({ ...@@ -11,17 +16,19 @@ export const ChatFileUploadSchema = z.object({
maxFileSize: z.number().positive().optional(), maxFileSize: z.number().positive().optional(),
allowedExtensions: z.array(z.string().nonempty()).optional() allowedExtensions: z.array(z.string().nonempty()).optional()
}); });
export type CheckChatFileKeys = z.infer<typeof ChatFileUploadSchema>; export type CheckChatFileKeys = z.input<typeof ChatFileUploadSchema>;
export const DelChatFileByPrefixSchema = z.object({ export const DelChatFileByPrefixSchema = z.object({
appId: ObjectIdSchema, sourceType: ChatS3SourceTypeSchema,
sourceId: ObjectIdSchema,
chatId: z.string().nonempty().optional(), chatId: z.string().nonempty().optional(),
uId: z.string().nonempty().optional() uId: z.string().nonempty().optional()
}); });
export type DelChatFileByPrefixParams = z.infer<typeof DelChatFileByPrefixSchema>; export type DelChatFileByPrefixParams = z.input<typeof DelChatFileByPrefixSchema>;
export const UploadChatFileSchema = z.object({ export const UploadChatFileSchema = z.object({
appId: ObjectIdSchema, sourceType: ChatS3SourceTypeSchema,
sourceId: ObjectIdSchema,
chatId: z.string().nonempty(), chatId: z.string().nonempty(),
uId: z.string().nonempty(), uId: z.string().nonempty(),
filename: UploadFileByBodySchema.shape.filename, filename: UploadFileByBodySchema.shape.filename,
...@@ -30,4 +37,4 @@ export const UploadChatFileSchema = z.object({ ...@@ -30,4 +37,4 @@ export const UploadChatFileSchema = z.object({
expiredTime: UploadFileByBodySchema.shape.expiredTime expiredTime: UploadFileByBodySchema.shape.expiredTime
}); });
export type UploadFileParams = z.infer<typeof UploadChatFileSchema>; export type UploadFileParams = z.input<typeof UploadChatFileSchema>;
...@@ -3,6 +3,7 @@ const { Schema } = connectionMongo; ...@@ -3,6 +3,7 @@ const { Schema } = connectionMongo;
import type { SandboxInstanceSchemaType } from '../type'; import type { SandboxInstanceSchemaType } from '../type';
import { SandboxStatusEnum, SandboxTypeEnum } from '@fastgpt/global/core/ai/sandbox/constants'; import { SandboxStatusEnum, SandboxTypeEnum } from '@fastgpt/global/core/ai/sandbox/constants';
import { SandboxLimitSchema, SandboxProviderSchema } from '../type'; import { SandboxLimitSchema, SandboxProviderSchema } from '../type';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
/** /**
* sandbox 实例记录集合。 * sandbox 实例记录集合。
...@@ -22,8 +23,18 @@ const SandboxInstanceSchema = new Schema({ ...@@ -22,8 +23,18 @@ const SandboxInstanceSchema = new Schema({
type: String, type: String,
required: true required: true
}, },
// Chat 模式和 skill sandbox 都会复用这组根字段。 // @deprecated 仅保留给 4.15.0-beta6 一次性迁移脚本识别旧 sandbox 归属。
// 运行时业务必须使用 sourceType/sourceId。
appId: String, appId: String,
sourceType: {
type: String,
enum: Object.values(ChatSourceTypeEnum),
required: true
},
sourceId: {
type: String,
required: true
},
userId: String, userId: String,
chatId: String, chatId: String,
type: { type: {
...@@ -58,6 +69,7 @@ const SandboxInstanceSchema = new Schema({ ...@@ -58,6 +69,7 @@ const SandboxInstanceSchema = new Schema({
} }
}); });
// @deprecated 旧 appId 维度索引仅用于迁移窗口和历史数据观察,新业务查询必须使用 sourceType/sourceId。
SandboxInstanceSchema.index( SandboxInstanceSchema.index(
{ provider: 1, appId: 1, userId: 1, chatId: 1 }, { provider: 1, appId: 1, userId: 1, chatId: 1 },
{ {
...@@ -73,6 +85,7 @@ SandboxInstanceSchema.index( ...@@ -73,6 +85,7 @@ SandboxInstanceSchema.index(
); );
SandboxInstanceSchema.index({ status: 1, lastActiveAt: 1, 'metadata.archive.state': 1 }); SandboxInstanceSchema.index({ status: 1, lastActiveAt: 1, 'metadata.archive.state': 1 });
SandboxInstanceSchema.index({ provider: 1, sandboxId: 1 }, { unique: true }); SandboxInstanceSchema.index({ provider: 1, sandboxId: 1 }, { unique: true });
// @deprecated 旧 appId 维度索引仅用于迁移窗口和历史数据观察,新业务查询必须使用 sourceType/sourceId。
SandboxInstanceSchema.index( SandboxInstanceSchema.index(
{ appId: 1, chatId: 1 }, { appId: 1, chatId: 1 },
{ {
...@@ -84,8 +97,10 @@ SandboxInstanceSchema.index( ...@@ -84,8 +97,10 @@ SandboxInstanceSchema.index(
} }
} }
); );
// @deprecated 旧 Skill Edit 归属索引仅用于迁移窗口,新业务不得写入或查询 metadata.skillId。
SandboxInstanceSchema.index({ 'metadata.skillId': 1 }); SandboxInstanceSchema.index({ 'metadata.skillId': 1 });
SandboxInstanceSchema.index({ type: 1, chatId: 1 }); SandboxInstanceSchema.index({ type: 1, chatId: 1 });
SandboxInstanceSchema.index({ sourceType: 1, sourceId: 1, chatId: 1 });
/** /**
* sandbox 实例 Mongo model。 * sandbox 实例 Mongo model。
......
import { generateSandboxId } from '@fastgpt/global/core/ai/sandbox/constants';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { getEditDebugSandboxId } from '../../skill/edit/config';
/** 根据标准 chat source 语义计算本轮 Agent sandboxId。 */
export const getRunningSandboxId = ({
sourceType,
sourceId,
userId,
chatId
}: {
sourceType: ChatSourceTypeEnum;
sourceId: string;
userId: string;
chatId: string;
}) => {
if (sourceType === ChatSourceTypeEnum.app) {
return generateSandboxId(sourceId, userId, chatId);
}
if (sourceType === ChatSourceTypeEnum.skillEdit) {
return getEditDebugSandboxId(sourceId);
}
const exhaustiveCheck: never = sourceType;
throw new Error(`Unsupported chat source type: ${exhaustiveCheck}`);
};
...@@ -2,6 +2,8 @@ import { getSandboxClient, type SandboxClient } from '../service/runtime'; ...@@ -2,6 +2,8 @@ import { getSandboxClient, type SandboxClient } from '../service/runtime';
import { createAgentSandboxPermissionDeniedError } from '../error'; import { createAgentSandboxPermissionDeniedError } from '../error';
import { checkTeamSandboxPermission } from '../../../../support/permission/teamLimit'; import { checkTeamSandboxPermission } from '../../../../support/permission/teamLimit';
import { getSandboxRuntimeProfile } from './profile'; import { getSandboxRuntimeProfile } from './profile';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { getRunningSandboxId } from './id';
export type AgentSandboxRuntimeContext = { export type AgentSandboxRuntimeContext = {
sandboxClient: SandboxClient; sandboxClient: SandboxClient;
...@@ -15,16 +17,16 @@ export type AgentSandboxRuntimeContext = { ...@@ -15,16 +17,16 @@ export type AgentSandboxRuntimeContext = {
* skill 注入、entrypoint 和扫描由 skill runtime 自己处理。 * skill 注入、entrypoint 和扫描由 skill runtime 自己处理。
*/ */
export async function prepareAgentSandboxRuntime({ export async function prepareAgentSandboxRuntime({
appId, sourceType,
sourceId,
userId, userId,
chatId, chatId,
sandboxId,
teamId teamId
}: { }: {
appId: string; sourceType: ChatSourceTypeEnum;
sourceId: string;
userId: string; userId: string;
chatId: string; chatId: string;
sandboxId?: string;
teamId: string; teamId: string;
}): Promise<AgentSandboxRuntimeContext> { }): Promise<AgentSandboxRuntimeContext> {
try { try {
...@@ -33,9 +35,19 @@ export async function prepareAgentSandboxRuntime({ ...@@ -33,9 +35,19 @@ export async function prepareAgentSandboxRuntime({
throw createAgentSandboxPermissionDeniedError(); throw createAgentSandboxPermissionDeniedError();
} }
const sandboxClient = await getSandboxClient( const sandboxId = getRunningSandboxId({
sandboxId ? { sandboxId } : { appId, userId, chatId } sourceType,
); sourceId,
userId,
chatId
});
const sandboxClient = await getSandboxClient({
sandboxId,
sourceType,
sourceId,
userId: sourceType === ChatSourceTypeEnum.app ? userId : '',
chatId
});
const runtimeProfile = getSandboxRuntimeProfile(); const runtimeProfile = getSandboxRuntimeProfile();
return { return {
......
...@@ -2,6 +2,7 @@ import { getErrText } from '@fastgpt/global/common/error/utils'; ...@@ -2,6 +2,7 @@ import { getErrText } from '@fastgpt/global/common/error/utils';
import { batchRun } from '@fastgpt/global/common/system/utils'; import { batchRun } from '@fastgpt/global/common/system/utils';
import { subDays } from 'date-fns'; import { subDays } from 'date-fns';
import { SandboxStatusEnum } from '@fastgpt/global/core/ai/sandbox/constants'; import { SandboxStatusEnum } from '@fastgpt/global/core/ai/sandbox/constants';
import type { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import type { ISandbox, SandboxCreateSpec } from '@fastgpt-sdk/sandbox-adapter'; import type { ISandbox, SandboxCreateSpec } from '@fastgpt-sdk/sandbox-adapter';
import { getLogger, LogCategories } from '../../../../common/logger'; import { getLogger, LogCategories } from '../../../../common/logger';
import { getS3SandboxSource } from '../../../../common/s3/sources/sandbox'; import { getS3SandboxSource } from '../../../../common/s3/sources/sandbox';
...@@ -596,7 +597,8 @@ async function createRestoreSandbox(params: { ...@@ -596,7 +597,8 @@ async function createRestoreSandbox(params: {
export async function restoreArchivedSandboxBeforeUse(params: { export async function restoreArchivedSandboxBeforeUse(params: {
provider: SandboxProviderType; provider: SandboxProviderType;
sandboxId: string; sandboxId: string;
appId?: string; sourceType: ChatSourceTypeEnum;
sourceId: string;
userId?: string; userId?: string;
chatId?: string; chatId?: string;
vmConfig?: VolumeManagerResult | null; vmConfig?: VolumeManagerResult | null;
...@@ -658,7 +660,8 @@ export async function restoreArchivedSandboxBeforeUse(params: { ...@@ -658,7 +660,8 @@ export async function restoreArchivedSandboxBeforeUse(params: {
const restoredStorage = params.storage ?? restoreTarget.storage; const restoredStorage = params.storage ?? restoreTarget.storage;
const restoredDoc = await markSandboxRestored(restoringDoc, { const restoredDoc = await markSandboxRestored(restoringDoc, {
appId: params.appId, sourceType: params.sourceType,
sourceId: params.sourceId,
userId: params.userId, userId: params.userId,
chatId: params.chatId, chatId: params.chatId,
storage: restoredStorage, storage: restoredStorage,
......
import { batchRun } from '@fastgpt/global/common/system/utils'; import { batchRun } from '@fastgpt/global/common/system/utils';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { getLogger, LogCategories } from '../../../../common/logger'; import { getLogger, LogCategories } from '../../../../common/logger';
import { import {
deleteSandboxResourceRecord, deleteSandboxResourceRecord,
findSandboxResourcesByAppId, findSandboxResourcesBySource,
findSandboxResourcesByChatIds, findSandboxResourcesBySourceChatIds,
findSkillRelatedSandboxResources,
markSandboxResourceStopped, markSandboxResourceStopped,
type SandboxResourceRef type SandboxResourceRef
} from '../instance/repository'; } from '../instance/repository';
...@@ -13,6 +15,19 @@ import { getS3SandboxSource } from '../../../../common/s3/sources/sandbox'; ...@@ -13,6 +15,19 @@ import { getS3SandboxSource } from '../../../../common/s3/sources/sandbox';
const logger = getLogger(LogCategories.MODULE.AI.SANDBOX); const logger = getLogger(LogCategories.MODULE.AI.SANDBOX);
const deleteSandboxResources = async (instances: SandboxResourceRef[]) => {
if (!instances.length) return;
await Promise.allSettled(
instances.map(async (doc) => {
await deleteSandboxResource(doc).catch((err) => {
logger.error('Failed to delete sandbox', { sandboxId: doc.sandboxId, error: err });
return Promise.reject(err);
});
})
);
};
/** /**
* 停止一条已存在的 sandbox 资源记录。 * 停止一条已存在的 sandbox 资源记录。
* *
...@@ -64,46 +79,55 @@ export async function deleteSandboxResource( ...@@ -64,46 +79,55 @@ export async function deleteSandboxResource(
} }
/** /**
* 删除某个 app 下指定 chat 会话关联的 sandbox 资源。 * 删除某个 App 下指定 chat 会话绑定的 runtime sandbox。
* *
* 这里用于聊天记录删除等批量清理场景;单个资源清理失败会记录日志并继续处理剩余资源。 * 只服务 App chat 删除、批量历史清理和 Pro 过期 chat 清理;Skill Edit 编辑沙盒不跟 chat
* 生命周期绑定,必须通过 deleteSkillEditSandboxes 处理。
*/ */
export const deleteSandboxesByChatIds = async ({ export const deleteAppChatRuntimeSandboxes = async ({
appId, appId,
chatIds chatIds
}: { }: {
appId: string; appId: string;
chatIds: string[]; chatIds: string[];
}) => { }) => {
const instances = await findSandboxResourcesByChatIds({ appId, chatIds }); if (chatIds.length === 0) return;
if (!instances.length) return;
await Promise.allSettled( const instances = await findSandboxResourcesBySourceChatIds({
instances.map(async (doc) => { sourceType: ChatSourceTypeEnum.app,
await deleteSandboxResource(doc).catch((err) => { sourceId: appId,
logger.error('Failed to delete sandbox', { sandboxId: doc.sandboxId, error: err }); chatIds
return Promise.reject(err);
}); });
}) await deleteSandboxResources(instances);
);
}; };
/** /**
* 删除某个 app 下的全部 sandbox 资源。 * 删除某个 App 下的全部 sandbox 资源。
* *
* app 删除流程可能遇到多个 chat、edit-debug 或历史 provider 资源,因此统一从实例记录查询后逐条清理。 * 这是 App 删除场景的语义化入口;内部仍走 source-aware 查询,避免上层继续拼物理字段。
*/ */
export const deleteSandboxesByAppId = async (appId: string) => { export const deleteAppSandboxes = async (appId: string) => {
const instances = await findSandboxResourcesByAppId(appId); const instances = await findSandboxResourcesBySource({
if (!instances.length) return; sourceType: ChatSourceTypeEnum.app,
sourceId: appId
});
await deleteSandboxResources(instances);
};
await Promise.allSettled( /**
instances.map(async (doc) => { * 删除一批 Skill Edit 相关的全部 sandbox 资源。
await deleteSandboxResource(doc).catch((err) => { *
logger.error('Failed to delete sandbox', { sandboxId: doc.sandboxId, error: err }); * 只在 Skill 删除时调用。Skill Edit 对话删除、过期聊天清理不应调用这里。
*/
export const deleteSkillEditSandboxes = async (skillIds: string[]) => {
if (skillIds.length === 0) return;
const instances = await findSkillRelatedSandboxResources(skillIds);
logger.info('Deleting skill edit sandboxes', {
skillIds,
count: instances.length
}); });
}) await deleteSandboxResources(instances);
);
}; };
/** /**
......
import { generateSandboxId } from '@fastgpt/global/core/ai/sandbox/constants'; import type { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { getErrText } from '@fastgpt/global/common/error/utils'; import { getErrText } from '@fastgpt/global/common/error/utils';
import { getLogger, LogCategories } from '../../../../common/logger'; import { getLogger, LogCategories } from '../../../../common/logger';
import { import {
...@@ -22,19 +22,18 @@ import { ...@@ -22,19 +22,18 @@ import {
const logger = getLogger(LogCategories.MODULE.AI.SANDBOX); const logger = getLogger(LogCategories.MODULE.AI.SANDBOX);
export type SandboxClientQuery = export type SandboxClientQuery = {
| {
sandboxId: string; sandboxId: string;
} sourceType: ChatSourceTypeEnum;
| { sourceId: string;
appId: string;
userId?: string; userId?: string;
chatId: string; chatId?: string;
}; };
type SandboxClientProps = { type SandboxClientProps = {
sandboxId: string; sandboxId: string;
appId?: string; sourceType: ChatSourceTypeEnum;
sourceId: string;
userId?: string; userId?: string;
chatId?: string; chatId?: string;
}; };
...@@ -54,7 +53,8 @@ type SandboxClientOptions = { ...@@ -54,7 +53,8 @@ type SandboxClientOptions = {
* resource.ts 中的 stopSandboxResource/deleteSandboxResource,避免误触发 create/resume。 * resource.ts 中的 stopSandboxResource/deleteSandboxResource,避免误触发 create/resume。
*/ */
export class SandboxClient { export class SandboxClient {
private appId?: string; private sourceType: ChatSourceTypeEnum;
private sourceId: string;
private userId?: string; private userId?: string;
private chatId?: string; private chatId?: string;
private sandboxId: string; private sandboxId: string;
...@@ -66,7 +66,8 @@ export class SandboxClient { ...@@ -66,7 +66,8 @@ export class SandboxClient {
private readonly opts: SandboxClientOptions = {} private readonly opts: SandboxClientOptions = {}
) { ) {
this.sandboxId = props.sandboxId; this.sandboxId = props.sandboxId;
this.appId = props.appId; this.sourceType = props.sourceType;
this.sourceId = props.sourceId;
this.userId = props.userId; this.userId = props.userId;
this.chatId = props.chatId; this.chatId = props.chatId;
...@@ -86,7 +87,8 @@ export class SandboxClient { ...@@ -86,7 +87,8 @@ export class SandboxClient {
const instance = await upsertRunningSandboxInstance({ const instance = await upsertRunningSandboxInstance({
provider: this.providerName, provider: this.providerName,
sandboxId: this.sandboxId, sandboxId: this.sandboxId,
appId: this.appId, sourceType: this.sourceType,
sourceId: this.sourceId,
userId: this.userId, userId: this.userId,
chatId: this.chatId, chatId: this.chatId,
storage: this.opts?.vmConfig?.storage, storage: this.opts?.vmConfig?.storage,
...@@ -168,23 +170,17 @@ export class SandboxClient { ...@@ -168,23 +170,17 @@ export class SandboxClient {
} }
const resolveSandboxClientProps = (props: SandboxClientQuery): SandboxClientProps => { const resolveSandboxClientProps = (props: SandboxClientQuery): SandboxClientProps => {
if ('sandboxId' in props) {
if (!props.sandboxId) { if (!props.sandboxId) {
throw new Error('sandboxId is required'); throw new Error('sandboxId is required');
} }
return { if (!props.sourceType || !props.sourceId) {
sandboxId: props.sandboxId throw new Error('sourceType and sourceId are required');
};
}
if (!props.appId || !props.chatId) {
throw new Error('appId and chatId are required when sandboxId is not provided');
} }
const sandboxUserId = props.chatId === 'edit-debug' ? '' : (props.userId ?? '');
return { return {
sandboxId: generateSandboxId(props.appId, sandboxUserId, props.chatId), sandboxId: props.sandboxId,
appId: props.appId, sourceType: props.sourceType,
sourceId: props.sourceId,
userId: props.userId, userId: props.userId,
chatId: props.chatId chatId: props.chatId
}; };
...@@ -193,7 +189,8 @@ const resolveSandboxClientProps = (props: SandboxClientQuery): SandboxClientProp ...@@ -193,7 +189,8 @@ const resolveSandboxClientProps = (props: SandboxClientQuery): SandboxClientProp
/** /**
* 获取当前业务会话的运行态 sandbox client。 * 获取当前业务会话的运行态 sandbox client。
* *
* 传入 sandboxId 时直接使用指定实例;传入 app/user/chat 三元组时使用稳定规则生成 sandboxId。 * 调用方必须按 sourceType/sourceId 计算 sandboxId;这里不再接收 appId 等旧业务字段,
* 避免运行态写入或恢复时继续污染 sandbox 实例归属。
* 返回前会准备 volume 配置并确保 sandbox 可用。 * 返回前会准备 volume 配置并确保 sandbox 可用。
*/ */
export const getSandboxClient = async ( export const getSandboxClient = async (
...@@ -201,7 +198,7 @@ export const getSandboxClient = async ( ...@@ -201,7 +198,7 @@ export const getSandboxClient = async (
opts: Omit<SandboxClientOptions, 'vmConfig'> = {} opts: Omit<SandboxClientOptions, 'vmConfig'> = {}
) => { ) => {
const sandboxClientProps = resolveSandboxClientProps(props); const sandboxClientProps = resolveSandboxClientProps(props);
const { sandboxId, appId, userId, chatId } = sandboxClientProps; const { sandboxId, userId, chatId } = sandboxClientProps;
const providerName = opts.providerName ?? getConfiguredSandboxProvider(); const providerName = opts.providerName ?? getConfiguredSandboxProvider();
let vmConfig: VolumeManagerResult | undefined; let vmConfig: VolumeManagerResult | undefined;
...@@ -215,7 +212,8 @@ export const getSandboxClient = async ( ...@@ -215,7 +212,8 @@ export const getSandboxClient = async (
await restoreArchivedSandboxBeforeUse({ await restoreArchivedSandboxBeforeUse({
provider: providerName, provider: providerName,
sandboxId, sandboxId,
appId, sourceType: sandboxClientProps.sourceType,
sourceId: sandboxClientProps.sourceId,
userId, userId,
chatId, chatId,
resourceLimit: opts.resourceLimits resourceLimit: opts.resourceLimits
......
...@@ -13,7 +13,7 @@ const SandboxGetFileUrlToolSchema = z.object({ ...@@ -13,7 +13,7 @@ const SandboxGetFileUrlToolSchema = z.object({
export const sandboxGetFileUrlTool = defineTool({ export const sandboxGetFileUrlTool = defineTool({
zodSchema: SandboxGetFileUrlToolSchema, zodSchema: SandboxGetFileUrlToolSchema,
execute: async ({ appId, userId, chatId, sandboxInstance, params }) => { execute: async ({ sourceType, sourceId, userId, chatId, sandboxInstance, params }) => {
const result = await Promise.all( const result = await Promise.all(
params.paths.map(async (filePath) => { params.paths.map(async (filePath) => {
const filename = path.basename(filePath); const filename = path.basename(filePath);
...@@ -23,7 +23,8 @@ export const sandboxGetFileUrlTool = defineTool({ ...@@ -23,7 +23,8 @@ export const sandboxGetFileUrlTool = defineTool({
const chatBucket = getS3ChatSource(); const chatBucket = getS3ChatSource();
const expiredTime = addHours(new Date(), 2); const expiredTime = addHours(new Date(), 2);
const { key } = await chatBucket.uploadChatFile({ const { key } = await chatBucket.uploadChatFile({
appId, sourceType,
sourceId,
chatId, chatId,
uId: userId, uId: userId,
filename, filename,
......
...@@ -13,6 +13,8 @@ import { parseJsonArgs } from '../../utils'; ...@@ -13,6 +13,8 @@ import { parseJsonArgs } from '../../utils';
import { writeUrlFilesToSandbox } from '../service/file'; import { writeUrlFilesToSandbox } from '../service/file';
import { getSandboxRuntimeProfile } from '../runtime/profile'; import { getSandboxRuntimeProfile } from '../runtime/profile';
import { preparePackageMirrors, prepareSandbox } from '../runtime/prepare'; import { preparePackageMirrors, prepareSandbox } from '../runtime/prepare';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { getRunningSandboxId } from '../runtime/id';
const ToolMap = { const ToolMap = {
...editFileToolMap, ...editFileToolMap,
...@@ -37,18 +39,18 @@ export type SandboxToolCallResult = { ...@@ -37,18 +39,18 @@ export type SandboxToolCallResult = {
* 未传入 client 时会按 app/user/chat 获取运行态 sandbox。 * 未传入 client 时会按 app/user/chat 获取运行态 sandbox。
*/ */
export const runSandboxTools = async ({ export const runSandboxTools = async ({
appId, sourceType,
sourceId,
userId, userId,
chatId, chatId,
sandboxId,
toolName, toolName,
args, args,
sandboxClient sandboxClient
}: { }: {
appId: string; sourceType: ChatSourceTypeEnum;
sourceId: string;
userId: string; userId: string;
chatId: string; chatId: string;
sandboxId?: string;
toolName: string; toolName: string;
args: string; args: string;
sandboxClient?: SandboxClient; sandboxClient?: SandboxClient;
...@@ -77,11 +79,24 @@ export const runSandboxTools = async ({ ...@@ -77,11 +79,24 @@ export const runSandboxTools = async ({
}; };
} }
const sandboxId = getRunningSandboxId({
sourceType,
sourceId,
userId,
chatId
});
const instance = const instance =
sandboxClient ?? sandboxClient ??
(await getSandboxClient(sandboxId ? { sandboxId } : { appId, userId, chatId })); (await getSandboxClient({
sandboxId,
sourceType,
sourceId,
userId: sourceType === ChatSourceTypeEnum.app ? userId : '',
chatId
}));
const result = await tool.execute({ const result = await tool.execute({
appId, sourceType,
sourceId,
userId, userId,
chatId, chatId,
sandboxInstance: instance, sandboxInstance: instance,
...@@ -103,19 +118,31 @@ export const runSandboxTools = async ({ ...@@ -103,19 +118,31 @@ export const runSandboxTools = async ({
* 即使没有文件也会返回 sandbox client,供 sandbox entrypoint 和后续工具调用复用。 * 即使没有文件也会返回 sandbox client,供 sandbox entrypoint 和后续工具调用复用。
*/ */
export const prepareSandboxToolRuntime = async ({ export const prepareSandboxToolRuntime = async ({
appId, sourceType,
sourceId,
userId, userId,
chatId, chatId,
sandboxId,
files files
}: { }: {
appId: string; sourceType: ChatSourceTypeEnum;
sourceId: string;
userId: string; userId: string;
chatId: string; chatId: string;
sandboxId?: string;
files: { path: string; url: string }[]; files: { path: string; url: string }[];
}) => { }) => {
const instance = await getSandboxClient(sandboxId ? { sandboxId } : { appId, userId, chatId }); const sandboxId = getRunningSandboxId({
sourceType,
sourceId,
userId,
chatId
});
const instance = await getSandboxClient({
sandboxId,
sourceType,
sourceId,
userId: sourceType === ChatSourceTypeEnum.app ? userId : '',
chatId
});
const runtimeProfile = getSandboxRuntimeProfile(); const runtimeProfile = getSandboxRuntimeProfile();
await prepareSandbox( await prepareSandbox(
{ {
......
import type { z } from 'zod'; import type { z } from 'zod';
import type { SandboxClient } from '../service/runtime'; import type { SandboxClient } from '../service/runtime';
import type { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
type ToolExecuteContext<P> = { type ToolExecuteContext<P> = {
appId: string; sourceType: ChatSourceTypeEnum;
sourceId: string;
userId: string; userId: string;
chatId: string; chatId: string;
sandboxInstance: SandboxClient; sandboxInstance: SandboxClient;
......
import z from 'zod'; import z from 'zod';
import { SandboxStatusEnum, SandboxTypeEnum } from '@fastgpt/global/core/ai/sandbox/constants'; import { SandboxStatusEnum, SandboxTypeEnum } from '@fastgpt/global/core/ai/sandbox/constants';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
// ---- 沙盒实例 DB 类型 ---- // ---- 沙盒实例 DB 类型 ----
export const SandboxProviderSchema = z.enum(['sealosdevbox', 'opensandbox', 'e2b']); export const SandboxProviderSchema = z.enum(['sealosdevbox', 'opensandbox', 'e2b']);
...@@ -47,6 +48,7 @@ export const SandboxMetadataSchema = z.object({ ...@@ -47,6 +48,7 @@ export const SandboxMetadataSchema = z.object({
}) })
.optional(), .optional(),
/** @deprecated 旧 Skill Edit 归属字段,仅迁移脚本/历史数据观察使用。 */
skillId: z.string().optional(), skillId: z.string().optional(),
sessionId: z.string().optional(), sessionId: z.string().optional(),
skillIds: z.array(z.string()).optional(), skillIds: z.array(z.string()).optional(),
...@@ -60,7 +62,10 @@ export type SandboxMetadataType = z.infer<typeof SandboxMetadataSchema>; ...@@ -60,7 +62,10 @@ export type SandboxMetadataType = z.infer<typeof SandboxMetadataSchema>;
export const SandboxInstanceZodSchema = z.object({ export const SandboxInstanceZodSchema = z.object({
_id: z.string(), _id: z.string(),
sandboxId: z.string(), sandboxId: z.string(),
/** @deprecated 旧 sandbox 归属字段,仅迁移脚本/历史数据观察使用。 */
appId: z.string().nullish(), appId: z.string().nullish(),
sourceType: z.enum(ChatSourceTypeEnum),
sourceId: z.string(),
userId: z.string().nullish(), userId: z.string().nullish(),
chatId: z.string().nullish(), chatId: z.string().nullish(),
type: z.enum(SandboxTypeEnum).nullish(), type: z.enum(SandboxTypeEnum).nullish(),
......
...@@ -5,7 +5,6 @@ import { ...@@ -5,7 +5,6 @@ import {
} from '@fastgpt/global/core/workflow/runtime/constants'; } from '@fastgpt/global/core/workflow/runtime/constants';
import { UsageSourceEnum } from '@fastgpt/global/support/wallet/usage/constants'; import { UsageSourceEnum } from '@fastgpt/global/support/wallet/usage/constants';
import type { AIChatItemType, UserChatItemType } from '@fastgpt/global/core/chat/type'; import type { AIChatItemType, UserChatItemType } from '@fastgpt/global/core/chat/type';
import type { ChatCompletionMessageParam } from '@fastgpt/global/core/ai/llm/type';
import { GPTMessages2Chats } from '@fastgpt/global/core/chat/adapt'; import { GPTMessages2Chats } from '@fastgpt/global/core/chat/adapt';
import { concatHistories, removeEmptyUserInput } from '@fastgpt/global/core/chat/utils'; import { concatHistories, removeEmptyUserInput } from '@fastgpt/global/core/chat/utils';
import { ReadPermissionVal } from '@fastgpt/global/support/permission/constant'; import { ReadPermissionVal } from '@fastgpt/global/support/permission/constant';
...@@ -16,12 +15,10 @@ import { ...@@ -16,12 +15,10 @@ import {
import { import {
ChatGenerateStatusEnum, ChatGenerateStatusEnum,
ChatRoleEnum, ChatRoleEnum,
ChatSourceTypeEnum,
ChatSourceEnum ChatSourceEnum
} from '@fastgpt/global/core/chat/constants'; } from '@fastgpt/global/core/chat/constants';
import { import { SkillDebugChatBodySchema } from '@fastgpt/global/core/ai/skill/api';
SkillDebugChatBodySchema,
type SkillDebugChatBody
} from '@fastgpt/global/core/ai/skill/api';
import { SandboxTypeEnum } from '@fastgpt/global/core/ai/sandbox/constants'; import { SandboxTypeEnum } from '@fastgpt/global/core/ai/sandbox/constants';
import { UserError } from '@fastgpt/global/common/error/utils'; import { UserError } from '@fastgpt/global/common/error/utils';
import { getNanoid } from '@fastgpt/global/common/string/tools'; import { getNanoid } from '@fastgpt/global/common/string/tools';
...@@ -36,7 +33,7 @@ import { getRunningUserInfoByTmbId } from '../../../../support/user/team/utils'; ...@@ -36,7 +33,7 @@ import { getRunningUserInfoByTmbId } from '../../../../support/user/team/utils';
import { formatModelChars2Points } from '../../../../support/wallet/usage/utils'; import { formatModelChars2Points } from '../../../../support/wallet/usage/utils';
import { getDefaultLLMModel } from '../../model'; import { getDefaultLLMModel } from '../../model';
import { getEditDebugSandboxId } from '../edit/config'; import { getEditDebugSandboxId } from '../edit/config';
import { findSandboxInstanceBySandboxId } from '../../sandbox/instance/repository'; import { findSandboxInstanceBySandboxIdAndSource } from '../../sandbox/instance/repository';
import { getSandboxProviderConfig } from '../../sandbox/provider/config'; import { getSandboxProviderConfig } from '../../sandbox/provider/config';
import { dispatchWorkFlow } from '../../../workflow/dispatch'; import { dispatchWorkFlow } from '../../../workflow/dispatch';
import { WORKFLOW_MAX_RUN_TIMES } from '../../../workflow/constants'; import { WORKFLOW_MAX_RUN_TIMES } from '../../../workflow/constants';
...@@ -58,10 +55,6 @@ import type { AgentSandboxPrepareAction } from '../../../workflow/dispatch/ai/ag ...@@ -58,10 +55,6 @@ import type { AgentSandboxPrepareAction } from '../../../workflow/dispatch/ai/ag
const logger = getLogger(LogCategories.MODULE.AGENT_SKILLS); const logger = getLogger(LogCategories.MODULE.AGENT_SKILLS);
type SkillDebugChatProps = Omit<SkillDebugChatBody, 'messages'> & {
messages: ChatCompletionMessageParam[];
};
/** /**
* 处理 Skill 调试对话的共享主流程。 * 处理 Skill 调试对话的共享主流程。
* *
...@@ -79,7 +72,8 @@ export async function handleSkillDebugChat( ...@@ -79,7 +72,8 @@ export async function handleSkillDebugChat(
let streamResponseContext: SkillDebugStreamResponseContext | undefined; let streamResponseContext: SkillDebugStreamResponseContext | undefined;
const roundState = { const roundState = {
preparedRound: undefined as PreChatRoundResult | undefined, preparedRound: undefined as PreChatRoundResult | undefined,
appId: '', sourceType: undefined as ChatSourceTypeEnum | undefined,
sourceId: '',
chatId: '', chatId: '',
responseChatItemId: '', responseChatItemId: '',
finalized: false finalized: false
...@@ -96,8 +90,12 @@ export async function handleSkillDebugChat( ...@@ -96,8 +90,12 @@ export async function handleSkillDebugChat(
} = parseApiInput({ } = parseApiInput({
req, req,
bodySchema: SkillDebugChatBodySchema bodySchema: SkillDebugChatBodySchema
}).body as SkillDebugChatProps; }).body;
skillId = parsedSkillId; skillId = parsedSkillId;
const chatSource = {
sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId
};
if (!Array.isArray(messages) || messages.length === 0) { if (!Array.isArray(messages) || messages.length === 0) {
throw new UserError('messages is required'); throw new UserError('messages is required');
...@@ -120,10 +118,11 @@ export async function handleSkillDebugChat( ...@@ -120,10 +118,11 @@ export async function handleSkillDebugChat(
const providerConfig = getSandboxProviderConfig(); const providerConfig = getSandboxProviderConfig();
const editDebugSandboxId = getEditDebugSandboxId(skillId); const editDebugSandboxId = getEditDebugSandboxId(skillId);
const sandboxInstance = await findSandboxInstanceBySandboxId({ const sandboxInstance = await findSandboxInstanceBySandboxIdAndSource({
provider: providerConfig.provider, provider: providerConfig.provider,
sandboxId: editDebugSandboxId, sandboxId: editDebugSandboxId,
appId: skillId, sourceType: chatSource.sourceType,
sourceId: chatSource.sourceId,
type: SandboxTypeEnum.editDebug type: SandboxTypeEnum.editDebug
}); });
if (!sandboxInstance) { if (!sandboxInstance) {
...@@ -140,7 +139,7 @@ export async function handleSkillDebugChat( ...@@ -140,7 +139,7 @@ export async function handleSkillDebugChat(
} }
const { histories } = await getChatItems({ const { histories } = await getChatItems({
appId: skillId, ...chatSource,
chatId, chatId,
offset: 0, offset: 0,
limit: 20, limit: 20,
...@@ -150,7 +149,7 @@ export async function handleSkillDebugChat( ...@@ -150,7 +149,7 @@ export async function handleSkillDebugChat(
const newHistories = concatHistories(histories, chatMessages); const newHistories = concatHistories(histories, chatMessages);
const interactive = getLastInteractiveValue(newHistories); const interactive = getLastInteractiveValue(newHistories);
const preparedRound = await preChatRound({ const preparedRound = await preChatRound({
appId: skillId, ...chatSource,
chatId, chatId,
teamId, teamId,
tmbId, tmbId,
...@@ -162,7 +161,8 @@ export async function handleSkillDebugChat( ...@@ -162,7 +161,8 @@ export async function handleSkillDebugChat(
const runningChatId = preparedRound.chatId; const runningChatId = preparedRound.chatId;
const finalResponseChatItemId = preparedRound.responseChatItemId; const finalResponseChatItemId = preparedRound.responseChatItemId;
roundState.preparedRound = preparedRound; roundState.preparedRound = preparedRound;
roundState.appId = skillId; roundState.sourceType = chatSource.sourceType;
roundState.sourceId = chatSource.sourceId;
roundState.chatId = runningChatId; roundState.chatId = runningChatId;
roundState.responseChatItemId = finalResponseChatItemId; roundState.responseChatItemId = finalResponseChatItemId;
...@@ -178,7 +178,8 @@ export async function handleSkillDebugChat( ...@@ -178,7 +178,8 @@ export async function handleSkillDebugChat(
stream: true, stream: true,
detail: true, detail: true,
teamId, teamId,
appId: skillId, sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId,
chatId: runningChatId, chatId: runningChatId,
responseId: runningChatId, responseId: runningChatId,
showNodeStatus: true showNodeStatus: true
...@@ -202,11 +203,11 @@ export async function handleSkillDebugChat( ...@@ -202,11 +203,11 @@ export async function handleSkillDebugChat(
usageSource: UsageSourceEnum.fastgpt, usageSource: UsageSourceEnum.fastgpt,
uid: tmbId, uid: tmbId,
runningAppInfo: { runningAppInfo: {
id: skillId, sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId,
name: skill.name, name: skill.name,
teamId, teamId,
tmbId, tmbId
sandboxId: editDebugSandboxId
}, },
runningUserInfo: await getRunningUserInfoByTmbId(tmbId), runningUserInfo: await getRunningUserInfoByTmbId(tmbId),
chatId: runningChatId, chatId: runningChatId,
...@@ -282,8 +283,8 @@ export async function handleSkillDebugChat( ...@@ -282,8 +283,8 @@ export async function handleSkillDebugChat(
}; };
const saveParams: SaveChatProps = { const saveParams: SaveChatProps = {
...chatSource,
chatId: runningChatId, chatId: runningChatId,
appId: skillId,
teamId, teamId,
tmbId, tmbId,
nodes: [], nodes: [],
...@@ -310,7 +311,7 @@ export async function handleSkillDebugChat( ...@@ -310,7 +311,7 @@ export async function handleSkillDebugChat(
if (!preparedRound.shouldFinalizePreparedRound && preparedRound.shouldPersistChatRound) { if (!preparedRound.shouldFinalizePreparedRound && preparedRound.shouldPersistChatRound) {
await updateChatGenerateStatus({ await updateChatGenerateStatus({
appId: skillId, ...chatSource,
chatId: runningChatId, chatId: runningChatId,
status: ChatGenerateStatusEnum.done status: ChatGenerateStatusEnum.done
}); });
...@@ -327,19 +328,22 @@ export async function handleSkillDebugChat( ...@@ -327,19 +328,22 @@ export async function handleSkillDebugChat(
if ( if (
!roundState.finalized && !roundState.finalized &&
preparedRound?.shouldPersistChatRound && preparedRound?.shouldPersistChatRound &&
roundState.appId && roundState.sourceType &&
roundState.sourceId &&
roundState.chatId roundState.chatId
) { ) {
if (preparedRound.shouldFinalizePreparedRound) { if (preparedRound.shouldFinalizePreparedRound) {
await failChatRound({ await failChatRound({
appId: roundState.appId, sourceType: roundState.sourceType,
sourceId: roundState.sourceId,
chatId: roundState.chatId, chatId: roundState.chatId,
responseChatItemId: roundState.responseChatItemId, responseChatItemId: roundState.responseChatItemId,
error: err error: err
}); });
} else { } else {
await updateChatGenerateStatus({ await updateChatGenerateStatus({
appId: roundState.appId, sourceType: roundState.sourceType,
sourceId: roundState.sourceId,
chatId: roundState.chatId, chatId: roundState.chatId,
status: ChatGenerateStatusEnum.error status: ChatGenerateStatusEnum.error
}); });
......
...@@ -2,6 +2,7 @@ import type { NextApiRequest, NextApiResponse } from 'next'; ...@@ -2,6 +2,7 @@ import type { NextApiRequest, NextApiResponse } from 'next';
import { getSseErrorResponse } from '../../../../common/response'; import { getSseErrorResponse } from '../../../../common/response';
import { clearCookie } from '../../../../support/permission/auth/common'; import { clearCookie } from '../../../../support/permission/auth/common';
import { STREAM_RESUME_REQUEST_HEADER } from '@fastgpt/global/core/chat/constants'; import { STREAM_RESUME_REQUEST_HEADER } from '@fastgpt/global/core/chat/constants';
import type { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { getStreamResumeMirror } from '../../../chat/resume'; import { getStreamResumeMirror } from '../../../chat/resume';
import { getWorkflowResponseWrite } from '../../../workflow/dispatch/utils'; import { getWorkflowResponseWrite } from '../../../workflow/dispatch/utils';
...@@ -11,7 +12,8 @@ type CreateSkillDebugStreamResponseContextParams = { ...@@ -11,7 +12,8 @@ type CreateSkillDebugStreamResponseContextParams = {
stream: boolean; stream: boolean;
detail: boolean; detail: boolean;
teamId: string; teamId: string;
appId: string; sourceType: ChatSourceTypeEnum;
sourceId: string;
chatId: string; chatId: string;
responseId?: string; responseId?: string;
showNodeStatus?: boolean; showNodeStatus?: boolean;
...@@ -29,7 +31,8 @@ export const createSkillDebugStreamResponseContext = async ({ ...@@ -29,7 +31,8 @@ export const createSkillDebugStreamResponseContext = async ({
stream, stream,
detail, detail,
teamId, teamId,
appId, sourceType,
sourceId,
chatId, chatId,
responseId, responseId,
showNodeStatus = true showNodeStatus = true
...@@ -38,7 +41,8 @@ export const createSkillDebugStreamResponseContext = async ({ ...@@ -38,7 +41,8 @@ export const createSkillDebugStreamResponseContext = async ({
? await getStreamResumeMirror({ ? await getStreamResumeMirror({
resumeRequestHeaderValue: req.headers?.[STREAM_RESUME_REQUEST_HEADER], resumeRequestHeaderValue: req.headers?.[STREAM_RESUME_REQUEST_HEADER],
teamId, teamId,
appId, sourceType,
sourceId,
chatId chatId
}) })
: undefined; : undefined;
......
...@@ -11,8 +11,10 @@ import { mongoSessionRun } from '../../../../common/mongo/sessionRun'; ...@@ -11,8 +11,10 @@ import { mongoSessionRun } from '../../../../common/mongo/sessionRun';
import { deleteSkillAllPackages } from '../package'; import { deleteSkillAllPackages } from '../package';
import { MongoAgentSkills } from '../model/schema'; import { MongoAgentSkills } from '../model/schema';
import { MongoAgentSkillsVersion } from '../version/schema'; import { MongoAgentSkillsVersion } from '../version/schema';
import { deleteSkillRelatedSandboxes } from '../sandbox/controller';
import { findSkillAndAllChildren } from '../manage/folder'; import { findSkillAndAllChildren } from '../manage/folder';
import { deleteChatResourcesBySource } from '../../../chat/delete';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { deleteSkillEditSandboxes } from '../../sandbox/service/resource';
const logger = getLogger(LogCategories.MODULE.AGENT_SKILLS.CREATION); const logger = getLogger(LogCategories.MODULE.AGENT_SKILLS.CREATION);
...@@ -37,7 +39,17 @@ const deleteSkillExternalData = async ({ ...@@ -37,7 +39,17 @@ const deleteSkillExternalData = async ({
const nonFolderSkillIds = nonFolderSkills.map((skill) => String(skill._id)); const nonFolderSkillIds = nonFolderSkills.map((skill) => String(skill._id));
if (nonFolderSkillIds.length > 0) { if (nonFolderSkillIds.length > 0) {
await deleteSkillRelatedSandboxes(nonFolderSkillIds); await deleteSkillEditSandboxes(nonFolderSkillIds);
await batchRun(
nonFolderSkillIds,
async (skillId) => {
await deleteChatResourcesBySource({
sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId
});
},
3
);
} }
}; };
......
...@@ -4,16 +4,17 @@ import { getLogger, LogCategories } from '../../../../common/logger'; ...@@ -4,16 +4,17 @@ import { getLogger, LogCategories } from '../../../../common/logger';
import { updateCurrentVersion } from '../manage'; import { updateCurrentVersion } from '../manage';
import { removeSkillPackageTTL, uploadSkillPackage } from '../package'; import { removeSkillPackageTTL, uploadSkillPackage } from '../package';
import { packageSkillInSandbox } from './sandbox'; import { packageSkillInSandbox } from './sandbox';
import { EDIT_DEBUG_SANDBOX_CHAT_ID } from './config'; import { getEditDebugSandboxId } from './config';
import { createVersion } from '../version'; import { createVersion } from '../version';
import { getSandboxRuntimeProfile } from '../../sandbox/runtime/profile'; import { getSandboxRuntimeProfile } from '../../sandbox/runtime/profile';
import { getSandboxProviderConfig } from '../../sandbox/provider/config'; import { getSandboxProviderConfig } from '../../sandbox/provider/config';
import { import {
findSandboxInstanceByAppChatType, findSandboxInstanceBySandboxId,
updateSandboxInstanceRecordBySandboxId updateSandboxInstanceRecordBySandboxId
} from '../../sandbox/instance/repository'; } from '../../sandbox/instance/repository';
import { MongoAgentSkills } from '../model/schema'; import { MongoAgentSkills } from '../model/schema';
import { SandboxStatusEnum, SandboxTypeEnum } from '@fastgpt/global/core/ai/sandbox/constants'; import { SandboxStatusEnum, SandboxTypeEnum } from '@fastgpt/global/core/ai/sandbox/constants';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { SkillErrEnum } from '@fastgpt/global/common/error/code/skill'; import { SkillErrEnum } from '@fastgpt/global/common/error/code/skill';
import { UserError } from '@fastgpt/global/common/error/utils'; import { UserError } from '@fastgpt/global/common/error/utils';
import type { SaveDeploySkillResponse } from '@fastgpt/global/core/ai/skill/api'; import type { SaveDeploySkillResponse } from '@fastgpt/global/core/ai/skill/api';
...@@ -41,10 +42,9 @@ export async function saveDeploySkillFromSandbox({ ...@@ -41,10 +42,9 @@ export async function saveDeploySkillFromSandbox({
versionName versionName
}: SaveDeploySkillFromSandboxParams): Promise<SaveDeploySkillResponse> { }: SaveDeploySkillFromSandboxParams): Promise<SaveDeploySkillResponse> {
const providerConfig = getSandboxProviderConfig(); const providerConfig = getSandboxProviderConfig();
const sandboxInfo = await findSandboxInstanceByAppChatType({ const sandboxInfo = await findSandboxInstanceBySandboxId({
provider: providerConfig.provider, provider: providerConfig.provider,
appId: skillId, sandboxId: getEditDebugSandboxId(skillId),
chatId: EDIT_DEBUG_SANDBOX_CHAT_ID,
status: SandboxStatusEnum.running, status: SandboxStatusEnum.running,
type: SandboxTypeEnum.editDebug type: SandboxTypeEnum.editDebug
}); });
...@@ -126,6 +126,8 @@ export async function saveDeploySkillFromSandbox({ ...@@ -126,6 +126,8 @@ export async function saveDeploySkillFromSandbox({
await updateSandboxInstanceRecordBySandboxId({ await updateSandboxInstanceRecordBySandboxId({
provider: providerConfig.provider, provider: providerConfig.provider,
sandboxId: sandboxInfo.sandboxId, sandboxId: sandboxInfo.sandboxId,
sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId,
metadata: { metadata: {
...(sandboxInfo.metadata || {}), ...(sandboxInfo.metadata || {}),
versionId versionId
......
...@@ -18,6 +18,7 @@ import { ...@@ -18,6 +18,7 @@ import {
import { getSandboxRuntimeProfile } from '../../sandbox/runtime/profile'; import { getSandboxRuntimeProfile } from '../../sandbox/runtime/profile';
import type { SandboxImageConfigType } from '@fastgpt/global/core/ai/skill/type'; import type { SandboxImageConfigType } from '@fastgpt/global/core/ai/skill/type';
import { SandboxTypeEnum } from '@fastgpt/global/core/ai/sandbox/constants'; import { SandboxTypeEnum } from '@fastgpt/global/core/ai/sandbox/constants';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { import {
connectReadySandboxByInstance, connectReadySandboxByInstance,
connectToSandbox, connectToSandbox,
...@@ -31,8 +32,8 @@ import { deleteSandboxResource } from '../../sandbox/service/resource'; ...@@ -31,8 +32,8 @@ import { deleteSandboxResource } from '../../sandbox/service/resource';
import { import {
countRunningSandboxInstancesByType, countRunningSandboxInstancesByType,
deleteSandboxInstanceRecord, deleteSandboxInstanceRecord,
findSandboxInstanceByAppChatType, findSandboxInstanceBySandboxId,
findSandboxResourcesByAppChatTypeExcludeProvider, findSandboxResourcesBySourceChatTypeExcludeProvider,
migrateArchivedSandboxInstanceRecord, migrateArchivedSandboxInstanceRecord,
updateSandboxInstanceRecordBySandboxId updateSandboxInstanceRecordBySandboxId
} from '../../sandbox/instance/repository'; } from '../../sandbox/instance/repository';
...@@ -156,10 +157,9 @@ export async function createEditDebugSandbox( ...@@ -156,10 +157,9 @@ export async function createEditDebugSandbox(
* 只有这个旧 wrapper,启动时顺手展开一层,避免每次加载继续制造 * 只有这个旧 wrapper,启动时顺手展开一层,避免每次加载继续制造
* skills/<edit-dir>/<real-skill>/SKILL.md 这种嵌套结构。 * skills/<edit-dir>/<real-skill>/SKILL.md 这种嵌套结构。
*/ */
const existingInstance = await findSandboxInstanceByAppChatType({ const existingInstance = await findSandboxInstanceBySandboxId({
provider: providerConfig.provider, provider: providerConfig.provider,
appId: skillId, sandboxId: sessionId,
chatId: EDIT_DEBUG_SANDBOX_CHAT_ID,
type: SandboxTypeEnum.editDebug type: SandboxTypeEnum.editDebug
}); });
...@@ -293,7 +293,8 @@ export async function createEditDebugSandbox( ...@@ -293,7 +293,8 @@ export async function createEditDebugSandbox(
await updateSandboxInstanceRecordBySandboxId({ await updateSandboxInstanceRecordBySandboxId({
provider: providerConfig.provider, provider: providerConfig.provider,
sandboxId: instance.sandboxId, sandboxId: instance.sandboxId,
appId: skillId, sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId,
userId: '', userId: '',
chatId: EDIT_DEBUG_SANDBOX_CHAT_ID, chatId: EDIT_DEBUG_SANDBOX_CHAT_ID,
metadata: preparedContext.workspaceHasContent metadata: preparedContext.workspaceHasContent
...@@ -375,7 +376,8 @@ export async function createEditDebugSandbox( ...@@ -375,7 +376,8 @@ export async function createEditDebugSandbox(
await updateSandboxInstanceRecordBySandboxId({ await updateSandboxInstanceRecordBySandboxId({
provider: providerConfig.provider, provider: providerConfig.provider,
sandboxId: instance.sandboxId, sandboxId: instance.sandboxId,
appId: skillId, sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId,
userId: '', userId: '',
chatId: EDIT_DEBUG_SANDBOX_CHAT_ID, chatId: EDIT_DEBUG_SANDBOX_CHAT_ID,
metadata: newMetadata metadata: newMetadata
...@@ -443,9 +445,10 @@ export async function createEditDebugSandbox( ...@@ -443,9 +445,10 @@ export async function createEditDebugSandbox(
}); });
} }
const staleProviderInstances = await findSandboxResourcesByAppChatTypeExcludeProvider({ const staleProviderInstances = await findSandboxResourcesBySourceChatTypeExcludeProvider({
provider: providerConfig.provider, provider: providerConfig.provider,
appId: skillId, sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId,
chatId: EDIT_DEBUG_SANDBOX_CHAT_ID, chatId: EDIT_DEBUG_SANDBOX_CHAT_ID,
type: SandboxTypeEnum.editDebug type: SandboxTypeEnum.editDebug
}); });
...@@ -471,7 +474,8 @@ export async function createEditDebugSandbox( ...@@ -471,7 +474,8 @@ export async function createEditDebugSandbox(
const migratedInstance = await migrateArchivedSandboxInstanceRecord({ const migratedInstance = await migrateArchivedSandboxInstanceRecord({
source: instance, source: instance,
provider: providerConfig.provider, provider: providerConfig.provider,
appId: skillId, sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId,
userId: '', userId: '',
chatId: EDIT_DEBUG_SANDBOX_CHAT_ID, chatId: EDIT_DEBUG_SANDBOX_CHAT_ID,
type: SandboxTypeEnum.editDebug type: SandboxTypeEnum.editDebug
...@@ -511,7 +515,9 @@ export async function createEditDebugSandbox( ...@@ -511,7 +515,9 @@ export async function createEditDebugSandbox(
const createRuntimeSandboxClient = () => const createRuntimeSandboxClient = () =>
getSandboxClient( getSandboxClient(
{ {
appId: skillId, sandboxId: sessionId,
sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId,
userId: '', userId: '',
chatId: EDIT_DEBUG_SANDBOX_CHAT_ID chatId: EDIT_DEBUG_SANDBOX_CHAT_ID
}, },
...@@ -601,14 +607,14 @@ export async function createEditDebugSandbox( ...@@ -601,14 +607,14 @@ export async function createEditDebugSandbox(
const newSandboxDoc = await updateSandboxInstanceRecordBySandboxId({ const newSandboxDoc = await updateSandboxInstanceRecordBySandboxId({
provider: providerConfig.provider, provider: providerConfig.provider,
sandboxId: sessionId, sandboxId: sessionId,
appId: skillId, sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId,
userId: '', userId: '',
chatId: EDIT_DEBUG_SANDBOX_CHAT_ID, chatId: EDIT_DEBUG_SANDBOX_CHAT_ID,
type: SandboxTypeEnum.editDebug, type: SandboxTypeEnum.editDebug,
metadata: { metadata: {
teamId, teamId,
tmbId, tmbId,
skillId,
sessionId, sessionId,
...(sandboxInfo.image ? { image: sandboxInfo.image } : {}), ...(sandboxInfo.image ? { image: sandboxInfo.image } : {}),
providerCreatedAt: sandboxInfo.createdAt, providerCreatedAt: sandboxInfo.createdAt,
......
...@@ -2,8 +2,7 @@ import type { SandboxInstanceSchemaType } from '@fastgpt/global/core/ai/skill/ty ...@@ -2,8 +2,7 @@ import type { SandboxInstanceSchemaType } from '@fastgpt/global/core/ai/skill/ty
import { getSandboxProviderConfig } from '../../sandbox/provider/config'; import { getSandboxProviderConfig } from '../../sandbox/provider/config';
import { import {
findSandboxInstanceBySandboxIdAndTeam, findSandboxInstanceBySandboxIdAndTeam,
findSandboxResourceBySandboxIdAndTeam, findSandboxResourceBySandboxIdAndTeam
findSkillRelatedSandboxResources
} from '../../sandbox/instance/repository'; } from '../../sandbox/instance/repository';
import { deleteSandboxResource } from '../../sandbox/service/resource'; import { deleteSandboxResource } from '../../sandbox/service/resource';
import { getLogger, LogCategories } from '../../../../common/logger'; import { getLogger, LogCategories } from '../../../../common/logger';
...@@ -67,26 +66,3 @@ export async function deleteSandbox(params: DeleteSandboxParams): Promise<void> ...@@ -67,26 +66,3 @@ export async function deleteSandbox(params: DeleteSandboxParams): Promise<void>
await deleteSandboxResource(instanceDoc); await deleteSandboxResource(instanceDoc);
} }
/**
* Force delete all sandbox instances related to the given skill IDs
* Called when a skill is deleted to clean up provider resources
*/
export async function deleteSkillRelatedSandboxes(skillIds: string[]): Promise<void> {
if (skillIds.length === 0) return;
const instances = await findSkillRelatedSandboxResources(skillIds);
if (instances.length === 0) return;
addLog.info('[Sandbox] Force deleting skill-related sandboxes', {
skillIds,
count: instances.length
});
await Promise.allSettled(
instances.map(async (doc) => {
await deleteSandboxResource(doc);
})
);
}
...@@ -11,8 +11,6 @@ import { encryptSecretValue, storeSecretValue } from '../../common/secret/utils' ...@@ -11,8 +11,6 @@ import { encryptSecretValue, storeSecretValue } from '../../common/secret/utils'
import { SystemToolSecretInputTypeEnum } from '@fastgpt/global/core/app/tool/systemTool/constants'; import { SystemToolSecretInputTypeEnum } from '@fastgpt/global/core/app/tool/systemTool/constants';
import { MongoEvaluation } from './evaluation/evalSchema'; import { MongoEvaluation } from './evaluation/evalSchema';
import { removeEvaluationJob } from './evaluation/mq'; import { removeEvaluationJob } from './evaluation/mq';
import { MongoChatItem } from '../chat/chatItemSchema';
import { MongoChat } from '../chat/chatSchema';
import { MongoOutLink } from '../../support/outLink/schema'; import { MongoOutLink } from '../../support/outLink/schema';
import { MongoOpenApi } from '../../support/openapi/schema'; import { MongoOpenApi } from '../../support/openapi/schema';
import { MongoAppVersion } from './version/schema'; import { MongoAppVersion } from './version/schema';
...@@ -26,15 +24,13 @@ import { ...@@ -26,15 +24,13 @@ import {
} from '@fastgpt/global/support/permission/constant'; } from '@fastgpt/global/support/permission/constant';
import { removeImageByPath } from '../../common/file/image/controller'; import { removeImageByPath } from '../../common/file/image/controller';
import { MongoAppLogKeys } from './logs/logkeysSchema'; import { MongoAppLogKeys } from './logs/logkeysSchema';
import { MongoChatItemResponse } from '../chat/chatItemResponseSchema';
import { getS3ChatSource } from '../../common/s3/sources/chat';
import { MongoAppChatLog } from './logs/chatLogsSchema'; import { MongoAppChatLog } from './logs/chatLogsSchema';
import { MongoAppRegistration } from '../../support/appRegistration/schema'; import { MongoAppRegistration } from '../../support/appRegistration/schema';
import { MongoMcpKey } from '../../support/mcp/schema'; import { MongoMcpKey } from '../../support/mcp/schema';
import { MongoAppRecord } from './record/schema'; import { MongoAppRecord } from './record/schema';
import { mongoSessionRun } from '../../common/mongo/sessionRun'; import { mongoSessionRun } from '../../common/mongo/sessionRun';
import { getLogger, LogCategories } from '../../common/logger'; import { getLogger, LogCategories } from '../../common/logger';
import { deleteSandboxesByAppId, deleteSandboxesByChatIds } from '../ai/sandbox/service/resource'; import { deleteAppSandboxes } from '../ai/sandbox/service/resource';
import { MongoSystemTool } from '../plugin/tool/systemToolSchema'; import { MongoSystemTool } from '../plugin/tool/systemToolSchema';
import { import {
SelectedAgentSkillItemTypeSchema, SelectedAgentSkillItemTypeSchema,
...@@ -43,6 +39,8 @@ import { ...@@ -43,6 +39,8 @@ import {
import z from 'zod'; import z from 'zod';
import { nodeInputIsReference } from '@fastgpt/global/core/workflow/utils'; import { nodeInputIsReference } from '@fastgpt/global/core/workflow/utils';
import { authSkillByTmbId } from '../../support/permission/skill/auth'; import { authSkillByTmbId } from '../../support/permission/skill/auth';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { deleteChatResourcesBySource } from '../chat/delete';
const logger = getLogger(LogCategories.MODULE.APP.FOLDER); const logger = getLogger(LogCategories.MODULE.APP.FOLDER);
...@@ -246,23 +244,13 @@ export const deleteAppDataProcessor = async ({ ...@@ -246,23 +244,13 @@ export const deleteAppDataProcessor = async ({
// 1. 删除应用头像 // 1. 删除应用头像
await removeImageByPath(app.avatar); await removeImageByPath(app.avatar);
// 2. 删除聊天记录和S3文件 // 2. 删除聊天记录、S3 文件和 sandbox 资源。App logs 属于应用统计域,单独清理。
// 删除沙盒实例 await deleteAppSandboxes(appId);
{ await deleteChatResourcesBySource({
// 对话生成的 sourceType: ChatSourceTypeEnum.app,
await deleteSandboxesByAppId(appId); sourceId: appId
// 编辑 skill 生成的 });
const appChatIds = (await MongoChat.find({ appId }, { _id: 1 }).lean()).map((c) =>
String(c._id)
);
await deleteSandboxesByChatIds({ appId, chatIds: appChatIds });
}
await getS3ChatSource().deleteChatFilesByPrefix({ appId });
await MongoAppChatLog.deleteMany({ teamId, appId }); await MongoAppChatLog.deleteMany({ teamId, appId });
await MongoChatItemResponse.deleteMany({ appId });
await MongoChatItem.deleteMany({ appId });
await MongoChat.deleteMany({ appId });
// 3. 删除应用相关数据(使用事务) // 3. 删除应用相关数据(使用事务)
{ {
......
...@@ -3,10 +3,10 @@ ...@@ -3,10 +3,10 @@
* Used by stream resume, sidebar polling, and stale-generating correction paths. * Used by stream resume, sidebar polling, and stale-generating correction paths.
*/ */
import { MongoChat } from './chatSchema'; import { MongoChat } from './chatSchema';
import { ChatGenerateStatusEnum } from '@fastgpt/global/core/chat/constants'; import { ChatGenerateStatusEnum, ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { buildChatSourceQuery, buildChatSourceWriteFields, type ChatSourceParams } from './source';
type EnsureGenerateChatParams = { type EnsureGenerateChatParams = ChatSourceParams & {
appId: string;
chatId: string; chatId: string;
teamId: string; teamId: string;
tmbId: string; tmbId: string;
...@@ -18,11 +18,18 @@ type EnsureGenerateChatParams = { ...@@ -18,11 +18,18 @@ type EnsureGenerateChatParams = {
const buildGeneratingChatUpdate = (params: EnsureGenerateChatParams) => { const buildGeneratingChatUpdate = (params: EnsureGenerateChatParams) => {
const now = new Date(); const now = new Date();
const { sourceType, sourceId, ...chatFields } = params;
const chatSource = {
sourceType,
sourceId
};
return { return {
now, now,
chatSource,
$set: { $set: {
...params, ...chatFields,
...buildChatSourceWriteFields(chatSource),
updateTime: now, updateTime: now,
hasBeenRead: false, hasBeenRead: false,
chatGenerateStatus: ChatGenerateStatusEnum.generating chatGenerateStatus: ChatGenerateStatusEnum.generating
...@@ -34,11 +41,11 @@ const buildGeneratingChatUpdate = (params: EnsureGenerateChatParams) => { ...@@ -34,11 +41,11 @@ const buildGeneratingChatUpdate = (params: EnsureGenerateChatParams) => {
}; };
export const ensureGenerateChat = async (params: EnsureGenerateChatParams) => { export const ensureGenerateChat = async (params: EnsureGenerateChatParams) => {
const { $set, $setOnInsert } = buildGeneratingChatUpdate(params); const { $set, $setOnInsert, chatSource } = buildGeneratingChatUpdate(params);
await MongoChat.updateOne( await MongoChat.updateOne(
{ {
appId: params.appId, ...buildChatSourceQuery(chatSource),
chatId: params.chatId chatId: params.chatId
}, },
{ {
...@@ -54,21 +61,21 @@ export const ensureGenerateChat = async (params: EnsureGenerateChatParams) => { ...@@ -54,21 +61,21 @@ export const ensureGenerateChat = async (params: EnsureGenerateChatParams) => {
/** /**
* 尝试占用一次会话生成槽。 * 尝试占用一次会话生成槽。
* *
* 同一个 `appId/chatId` 只允许一个请求进入生成中状态;已有 generating 记录时返回 false, * 同一个 `sourceType/sourceId/chatId` 只允许一个请求进入生成中状态;已有 generating 记录时返回 false,
* 由 API 层转换为“当前会话正在运行”的错误。 * 由 API 层转换为“当前会话正在运行”的错误。
* *
* 这里用“条件匹配 + upsert + 唯一索引”实现无副作用抢占:只有非 generating * 这里用“条件匹配 + upsert + 唯一索引”实现无副作用抢占:只有非 generating
* 记录会被更新为 generating;如果已有 generating 记录,查询不会命中,upsert 会因 * 记录会被更新为 generating;如果已有 generating 记录,查询不会命中,upsert 会因
* `{ appId, chatId }` 唯一索引报 11000,再转换为 false。这样被拒绝的并发请求不会刷新 * chat source 唯一索引报 11000,再转换为 false。这样被拒绝的并发请求不会刷新
* updateTime 或覆盖 source/sourceName。 * updateTime 或覆盖 source/sourceName。
*/ */
export const tryStartGenerateChat = async (params: EnsureGenerateChatParams) => { export const tryStartGenerateChat = async (params: EnsureGenerateChatParams) => {
const { $set, $setOnInsert } = buildGeneratingChatUpdate(params); const { $set, $setOnInsert, chatSource } = buildGeneratingChatUpdate(params);
try { try {
await MongoChat.findOneAndUpdate( await MongoChat.findOneAndUpdate(
{ {
appId: params.appId, ...buildChatSourceQuery(chatSource),
chatId: params.chatId, chatId: params.chatId,
chatGenerateStatus: { $ne: ChatGenerateStatusEnum.generating } chatGenerateStatus: { $ne: ChatGenerateStatusEnum.generating }
}, },
...@@ -91,13 +98,20 @@ export const tryStartGenerateChat = async (params: EnsureGenerateChatParams) => ...@@ -91,13 +98,20 @@ export const tryStartGenerateChat = async (params: EnsureGenerateChatParams) =>
} }
}; };
type UpdateChatGenerateStatusParams = Pick<EnsureGenerateChatParams, 'appId' | 'chatId'> & { type UpdateChatGenerateStatusParams = Pick<
EnsureGenerateChatParams,
'sourceType' | 'sourceId' | 'chatId'
> & {
status: ChatGenerateStatusEnum; status: ChatGenerateStatusEnum;
/** 若传入则覆盖;否则在 done/error 时默认未读(前台看完可再调 markRead) */ /** 若传入则覆盖;否则在 done/error 时默认未读(前台看完可再调 markRead) */
hasBeenRead?: boolean; hasBeenRead?: boolean;
}; };
export const updateChatGenerateStatus = async (params: UpdateChatGenerateStatusParams) => { export const updateChatGenerateStatus = async (params: UpdateChatGenerateStatusParams) => {
const { appId, chatId, status, hasBeenRead } = params; const { chatId, status, hasBeenRead } = params;
const chatSource = {
sourceType: params.sourceType,
sourceId: params.sourceId
};
const now = new Date(); const now = new Date();
const $set: Record<string, unknown> = { const $set: Record<string, unknown> = {
chatGenerateStatus: status, chatGenerateStatus: status,
...@@ -108,5 +122,5 @@ export const updateChatGenerateStatus = async (params: UpdateChatGenerateStatusP ...@@ -108,5 +122,5 @@ export const updateChatGenerateStatus = async (params: UpdateChatGenerateStatusP
} else if (status === ChatGenerateStatusEnum.done || status === ChatGenerateStatusEnum.error) { } else if (status === ChatGenerateStatusEnum.done || status === ChatGenerateStatusEnum.error) {
$set.hasBeenRead = false; $set.hasBeenRead = false;
} }
await MongoChat.updateOne({ appId, chatId }, { $set }); await MongoChat.updateOne({ ...buildChatSourceQuery(chatSource), chatId }, { $set });
}; };
...@@ -4,6 +4,7 @@ import type { ChatItemResponseSchemaType } from '@fastgpt/global/core/chat/type' ...@@ -4,6 +4,7 @@ import type { ChatItemResponseSchemaType } from '@fastgpt/global/core/chat/type'
import { TeamCollectionName } from '@fastgpt/global/support/user/team/constant'; import { TeamCollectionName } from '@fastgpt/global/support/user/team/constant';
import { AppCollectionName } from '../app/schema'; import { AppCollectionName } from '../app/schema';
import { ChatItemResponseCollectionName } from './constants'; import { ChatItemResponseCollectionName } from './constants';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
const ChatItemResponseSchema = new Schema({ const ChatItemResponseSchema = new Schema({
teamId: { teamId: {
...@@ -11,6 +12,10 @@ const ChatItemResponseSchema = new Schema({ ...@@ -11,6 +12,10 @@ const ChatItemResponseSchema = new Schema({
ref: TeamCollectionName, ref: TeamCollectionName,
required: true required: true
}, },
sourceType: {
type: String,
enum: Object.values(ChatSourceTypeEnum)
},
appId: { appId: {
type: Schema.Types.ObjectId, type: Schema.Types.ObjectId,
ref: AppCollectionName, ref: AppCollectionName,
...@@ -37,6 +42,13 @@ const ChatItemResponseSchema = new Schema({ ...@@ -37,6 +42,13 @@ const ChatItemResponseSchema = new Schema({
// 按 chat item 拉取完整 nodeResponse rows;复合索引包含 _id,避免详情读取时额外排序。 // 按 chat item 拉取完整 nodeResponse rows;复合索引包含 _id,避免详情读取时额外排序。
ChatItemResponseSchema.index({ appId: 1, chatId: 1, chatItemDataId: 1, _id: 1 }); ChatItemResponseSchema.index({ appId: 1, chatId: 1, chatItemDataId: 1, _id: 1 });
ChatItemResponseSchema.index({
sourceType: 1,
appId: 1,
chatId: 1,
chatItemDataId: 1,
_id: 1
});
// Clear expired response // Clear expired response
ChatItemResponseSchema.index({ teamId: 1, time: -1 }); ChatItemResponseSchema.index({ teamId: 1, time: -1 });
......
import { connectionMongo, getMongoModel } from '../../common/mongo'; import { connectionMongo, getMongoModel } from '../../common/mongo';
const { Schema } = connectionMongo; const { Schema } = connectionMongo;
import { type ChatItemDBSchemaType } from '@fastgpt/global/core/chat/type'; import { type ChatItemDBSchemaType } from '@fastgpt/global/core/chat/type';
import { ChatRoleMap } from '@fastgpt/global/core/chat/constants'; import { ChatRoleMap, ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { getNanoid } from '@fastgpt/global/common/string/tools'; import { getNanoid } from '@fastgpt/global/common/string/tools';
import { import {
TeamCollectionName, TeamCollectionName,
...@@ -31,6 +31,10 @@ const ChatItemSchema = new Schema({ ...@@ -31,6 +31,10 @@ const ChatItemSchema = new Schema({
type: String, type: String,
require: true require: true
}, },
sourceType: {
type: String,
enum: Object.values(ChatSourceTypeEnum)
},
dataId: { dataId: {
type: String, type: String,
require: true, require: true,
...@@ -99,12 +103,16 @@ const ChatItemSchema = new Schema({ ...@@ -99,12 +103,16 @@ const ChatItemSchema = new Schema({
close custom feedback; close custom feedback;
*/ */
ChatItemSchema.index({ appId: 1, chatId: 1, dataId: 1 }); ChatItemSchema.index({ appId: 1, chatId: 1, dataId: 1 });
ChatItemSchema.index({ sourceType: 1, appId: 1, chatId: 1, dataId: 1 });
// Get histories // Get histories
ChatItemSchema.index({ appId: 1, chatId: 1, deleteTime: 1 }); ChatItemSchema.index({ appId: 1, chatId: 1, deleteTime: 1 });
ChatItemSchema.index({ sourceType: 1, appId: 1, chatId: 1, deleteTime: 1 });
// get chatitem list,Anchor filter // get chatitem list,Anchor filter
ChatItemSchema.index({ appId: 1, chatId: 1, _id: -1 }); ChatItemSchema.index({ appId: 1, chatId: 1, _id: -1 });
ChatItemSchema.index({ sourceType: 1, appId: 1, chatId: 1, _id: -1 });
// Query by role (AI/Human), get latest chat item, permission check // Query by role (AI/Human), get latest chat item, permission check
ChatItemSchema.index({ appId: 1, chatId: 1, obj: 1, _id: -1 }); ChatItemSchema.index({ appId: 1, chatId: 1, obj: 1, _id: -1 });
ChatItemSchema.index({ sourceType: 1, appId: 1, chatId: 1, obj: 1, _id: -1 });
export const MongoChatItem = getMongoModel<ChatItemDBSchemaType>( export const MongoChatItem = getMongoModel<ChatItemDBSchemaType>(
ChatItemCollectionName, ChatItemCollectionName,
......
...@@ -2,7 +2,11 @@ import { connectionMongo, getMongoModel } from '../../common/mongo'; ...@@ -2,7 +2,11 @@ import { connectionMongo, getMongoModel } from '../../common/mongo';
import { getLogger, LogCategories } from '../../common/logger'; import { getLogger, LogCategories } from '../../common/logger';
const { Schema } = connectionMongo; const { Schema } = connectionMongo;
import { type ChatSchemaType } from '@fastgpt/global/core/chat/type'; import { type ChatSchemaType } from '@fastgpt/global/core/chat/type';
import { ChatGenerateStatusEnum, ChatSourceEnum } from '@fastgpt/global/core/chat/constants'; import {
ChatGenerateStatusEnum,
ChatSourceEnum,
ChatSourceTypeEnum
} from '@fastgpt/global/core/chat/constants';
import { import {
TeamCollectionName, TeamCollectionName,
TeamMemberCollectionName TeamMemberCollectionName
...@@ -26,6 +30,11 @@ const ChatSchema = new Schema({ ...@@ -26,6 +30,11 @@ const ChatSchema = new Schema({
ref: TeamMemberCollectionName, ref: TeamMemberCollectionName,
required: true required: true
}, },
sourceType: {
type: String,
enum: Object.values(ChatSourceTypeEnum)
},
// 历史物理字段名,业务语义为 sourceId;App 场景才是真实 appId。
appId: { appId: {
type: Schema.Types.ObjectId, type: Schema.Types.ObjectId,
ref: AppCollectionName, ref: AppCollectionName,
...@@ -130,6 +139,10 @@ try { ...@@ -130,6 +139,10 @@ try {
ChatSchema.index({ chatId: 1 }); ChatSchema.index({ chatId: 1 });
// Delete by appid; init chat; update chat; auth chat; // Delete by appid; init chat; update chat; auth chat;
ChatSchema.index({ appId: 1, chatId: 1 }, { unique: true }); ChatSchema.index({ appId: 1, chatId: 1 }, { unique: true });
ChatSchema.index(
{ sourceType: 1, appId: 1, chatId: 1 },
{ unique: true, name: 'sourceType_1_appId_1_chatId_1' }
);
// Clear history(share),Init 4121 // Clear history(share),Init 4121
ChatSchema.index( ChatSchema.index(
...@@ -143,6 +156,14 @@ try { ...@@ -143,6 +156,14 @@ try {
// get user history // get user history
ChatSchema.index({ tmbId: 1, appId: 1, deleteTime: 1, top: -1, updateTime: -1 }); ChatSchema.index({ tmbId: 1, appId: 1, deleteTime: 1, top: -1, updateTime: -1 });
ChatSchema.index({
sourceType: 1,
tmbId: 1,
appId: 1,
deleteTime: 1,
top: -1,
updateTime: -1
});
// get share chat history // get share chat history
ChatSchema.index( ChatSchema.index(
{ shareId: 1, outLinkUid: 1, updateTime: -1 }, { shareId: 1, outLinkUid: 1, updateTime: -1 },
......
import { subMilliseconds, subMinutes } from 'date-fns'; import { subMilliseconds, subMinutes } from 'date-fns';
import { ChatGenerateStatusEnum } from '@fastgpt/global/core/chat/constants'; import { ChatGenerateStatusEnum, ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { getLogger, LogCategories } from '../../common/logger'; import { getLogger, LogCategories } from '../../common/logger';
import { MongoChat } from './chatSchema'; import { MongoChat } from './chatSchema';
import { import {
...@@ -16,6 +16,7 @@ export const STALE_GENERATING_CHAT_MINUTES = 30; ...@@ -16,6 +16,7 @@ export const STALE_GENERATING_CHAT_MINUTES = 30;
type GeneratingChat = { type GeneratingChat = {
_id: unknown; _id: unknown;
teamId: { toString: () => string } | string; teamId: { toString: () => string } | string;
sourceType?: ChatSourceTypeEnum;
appId: { toString: () => string } | string; appId: { toString: () => string } | string;
chatId: string; chatId: string;
updateTime?: Date; updateTime?: Date;
...@@ -67,6 +68,7 @@ export const cleanStaleGeneratingChats = async (): Promise<CleanStaleGeneratingC ...@@ -67,6 +68,7 @@ export const cleanStaleGeneratingChats = async (): Promise<CleanStaleGeneratingC
{ {
_id: 1, _id: 1,
teamId: 1, teamId: 1,
sourceType: 1,
appId: 1, appId: 1,
chatId: 1, chatId: 1,
updateTime: 1 updateTime: 1
...@@ -92,7 +94,8 @@ export const cleanStaleGeneratingChats = async (): Promise<CleanStaleGeneratingC ...@@ -92,7 +94,8 @@ export const cleanStaleGeneratingChats = async (): Promise<CleanStaleGeneratingC
try { try {
const activeState = await getStreamResumeActiveState({ const activeState = await getStreamResumeActiveState({
teamId: chat.teamId.toString(), teamId: chat.teamId.toString(),
appId: chat.appId.toString(), sourceType: chat.sourceType ?? ChatSourceTypeEnum.app,
sourceId: chat.appId.toString(),
chatId: chat.chatId chatId: chat.chatId
}); });
......
...@@ -4,10 +4,15 @@ import { MongoChat } from './chatSchema'; ...@@ -4,10 +4,15 @@ import { MongoChat } from './chatSchema';
import { ChatRoleEnum } from '@fastgpt/global/core/chat/constants'; import { ChatRoleEnum } from '@fastgpt/global/core/chat/constants';
import { MongoChatItemResponse } from './chatItemResponseSchema'; import { MongoChatItemResponse } from './chatItemResponseSchema';
import type { ClientSession } from '../../common/mongo'; import type { ClientSession } from '../../common/mongo';
import { Types } from '../../common/mongo';
import { UserError } from '@fastgpt/global/common/error/utils'; import { UserError } from '@fastgpt/global/common/error/utils';
import { getLogger, LogCategories } from '../../common/logger'; import { getLogger, LogCategories } from '../../common/logger';
import { composeChatItemResponseData } from './nodeResponseStorage'; import { composeChatItemResponseData } from './nodeResponseStorage';
import type { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import {
buildChatSourceAggregateMatch,
buildChatSourceQuery,
type ChatSourceParams
} from './source';
const logger = getLogger(LogCategories.MODULE.CHAT.HISTORY); const logger = getLogger(LogCategories.MODULE.CHAT.HISTORY);
...@@ -35,7 +40,8 @@ const defaultNodeResponsePreviewProjection = { ...@@ -35,7 +40,8 @@ const defaultNodeResponsePreviewProjection = {
export async function getChatItems({ export async function getChatItems({
includeDeleted = false, includeDeleted = false,
appId, sourceType,
sourceId,
chatId, chatId,
field, field,
limit, limit,
...@@ -48,7 +54,8 @@ export async function getChatItems({ ...@@ -48,7 +54,8 @@ export async function getChatItems({
nextId nextId
}: { }: {
includeDeleted?: boolean; includeDeleted?: boolean;
appId: string; sourceType: ChatSourceTypeEnum;
sourceId: string;
chatId?: string; chatId?: string;
field: string; field: string;
limit: number; limit: number;
...@@ -69,10 +76,13 @@ export async function getChatItems({ ...@@ -69,10 +76,13 @@ export async function getChatItems({
return { histories: [], total: 0, hasMorePrev: false, hasMoreNext: false }; return { histories: [], total: 0, hasMorePrev: false, hasMoreNext: false };
} }
const chatSource = { sourceType, sourceId };
const shouldReadNodeResponse = nodeResponseMode || 'none'; const shouldReadNodeResponse = nodeResponseMode || 'none';
field = `dataId ${field}`; field = `dataId ${field}`;
const baseCondition = includeDeleted ? { appId, chatId } : { appId, chatId, deleteTime: null }; const baseCondition = includeDeleted
? { ...buildChatSourceQuery(chatSource), chatId }
: { ...buildChatSourceQuery(chatSource), chatId, deleteTime: null };
const { histories, total, hasMorePrev, hasMoreNext } = await (async () => { const { histories, total, hasMorePrev, hasMoreNext } = await (async () => {
// Mode 1: offset pagination (original logic) // Mode 1: offset pagination (original logic)
...@@ -198,7 +208,7 @@ export async function getChatItems({ ...@@ -198,7 +208,7 @@ export async function getChatItems({
const isPreview = shouldReadNodeResponse === 'preview'; const isPreview = shouldReadNodeResponse === 'preview';
const rows = await MongoChatItemResponse.find( const rows = await MongoChatItemResponse.find(
{ {
appId, ...buildChatSourceQuery(chatSource),
chatId, chatId,
chatItemDataId: { $in: chatItemDataIds } chatItemDataId: { $in: chatItemDataIds }
}, },
...@@ -245,26 +255,32 @@ export async function getChatItems({ ...@@ -245,26 +255,32 @@ export async function getChatItems({
* Update feedback count statistics for a chat in Chat table * Update feedback count statistics for a chat in Chat table
* This method aggregates feedback data from chatItems and updates the Chat table * This method aggregates feedback data from chatItems and updates the Chat table
* *
* @param appId - Application ID * @param sourceType - Chat source type
* @param sourceId - Chat source ID
* @param chatId - Chat ID * @param chatId - Chat ID
* @param session - Optional MongoDB session for transaction support * @param session - Optional MongoDB session for transaction support
*/ */
export async function updateChatFeedbackCount({ export async function updateChatFeedbackCount({
appId, sourceType,
sourceId,
chatId, chatId,
session session
}: { }: {
appId: string; sourceType: ChatSourceTypeEnum;
sourceId: string;
chatId: string; chatId: string;
session?: ClientSession; session?: ClientSession;
}): Promise<void> { }): Promise<void> {
const chatSource = { sourceType, sourceId };
const sourceQuery = buildChatSourceQuery(chatSource);
const sourceAggregateMatch = buildChatSourceAggregateMatch(chatSource);
try { try {
// Aggregate feedback statistics from chatItems // Aggregate feedback statistics from chatItems
const stats = await MongoChatItem.aggregate( const stats = await MongoChatItem.aggregate(
[ [
{ {
$match: { $match: {
appId: new Types.ObjectId(appId), ...sourceAggregateMatch,
chatId, chatId,
obj: ChatRoleEnum.AI obj: ChatRoleEnum.AI
} }
...@@ -371,7 +387,7 @@ export async function updateChatFeedbackCount({ ...@@ -371,7 +387,7 @@ export async function updateChatFeedbackCount({
// Update Chat table with aggregated statistics and boolean flags // Update Chat table with aggregated statistics and boolean flags
await MongoChat.updateOne( await MongoChat.updateOne(
{ {
appId, ...sourceQuery,
chatId chatId
}, },
updateQuery, updateQuery,
...@@ -381,7 +397,8 @@ export async function updateChatFeedbackCount({ ...@@ -381,7 +397,8 @@ export async function updateChatFeedbackCount({
); );
logger.debug('Chat feedback count updated', { logger.debug('Chat feedback count updated', {
appId, sourceType: chatSource.sourceType,
sourceId: chatSource.sourceId,
chatId, chatId,
stats: feedbackStats, stats: feedbackStats,
hasGoodFeedback, hasGoodFeedback,
...@@ -390,7 +407,12 @@ export async function updateChatFeedbackCount({ ...@@ -390,7 +407,12 @@ export async function updateChatFeedbackCount({
hasUnreadBadFeedback hasUnreadBadFeedback
}); });
} catch (error) { } catch (error) {
logger.error('Failed to update chat feedback count', { appId, chatId, error }); logger.error('Failed to update chat feedback count', {
sourceType: chatSource.sourceType,
sourceId: chatSource.sourceId,
chatId,
error
});
throw error; throw error;
} }
} }
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { getS3ChatSource } from '../../common/s3/sources/chat';
import { deleteAppChatRuntimeSandboxes } from '../ai/sandbox/service/resource';
import { MongoChatItemResponse } from './chatItemResponseSchema';
import { MongoChatItem } from './chatItemSchema';
import { MongoChat } from './chatSchema';
import { buildChatSourceQuery, type ChatSourceParams } from './source';
export type DeleteChatResourcesBySourceParams = ChatSourceParams & {
chatIds?: string[];
};
type ChatResourceRecord = {
chatId: string;
tmbId?: unknown;
outLinkUid?: unknown;
};
const getChatResourceUid = (chat: ChatResourceRecord) => {
const uid = chat.outLinkUid || chat.tmbId;
return uid ? String(uid) : undefined;
};
const deleteChatFilesBySourcePrefix = async ({
sourceType,
sourceId,
chatId,
uId
}: Pick<DeleteChatResourcesBySourceParams, 'sourceType' | 'sourceId'> & {
chatId?: string;
uId?: string;
}) => {
await getS3ChatSource().deleteChatFilesByPrefix({
sourceType,
sourceId,
chatId,
uId
});
};
/**
* 按统一 chat source 硬删除标准 chat 资源。
*
* 只处理 `chats`、`chatitems`、`chat_item_responses`、chat S3 文件,以及 App chat
* 绑定的 sandbox 资源;App logs、usage、inputGuide、Skill Edit 编辑沙盒都不属于本函数。
*/
export async function deleteChatResourcesBySource({
sourceType,
sourceId,
chatIds
}: DeleteChatResourcesBySourceParams) {
if (chatIds && chatIds.length === 0) {
// 显式传空数组表示没有目标 chat,不能退化为整 source 删除。
return;
}
const sourceQuery = buildChatSourceQuery({
sourceType,
sourceId
});
const chatIdQuery = chatIds?.length ? { chatId: { $in: chatIds } } : {};
const chatQuery = {
...sourceQuery,
...chatIdQuery
};
const rawChatList = (await MongoChat.find(chatQuery, 'chatId tmbId outLinkUid').lean()) as
| ChatResourceRecord[]
| null;
const chatList = (() => {
if (!chatIds?.length) return rawChatList || [];
const chatMap = new Map((rawChatList || []).map((chat) => [chat.chatId, chat]));
const seenChatIds = new Set<string>();
return chatIds.flatMap((chatId) => {
if (seenChatIds.has(chatId)) return [];
seenChatIds.add(chatId);
const chat = chatMap.get(chatId);
return chat ? [chat] : [];
});
})();
const existingChatIds = chatList.map((chat) => chat.chatId).filter(Boolean);
await Promise.all([
MongoChatItemResponse.deleteMany(chatQuery),
sourceType === ChatSourceTypeEnum.app && existingChatIds.length
? deleteAppChatRuntimeSandboxes({ appId: sourceId, chatIds: existingChatIds })
: Promise.resolve()
]);
await MongoChatItem.deleteMany(chatQuery);
await MongoChat.deleteMany(chatQuery);
if (!chatIds?.length) {
await deleteChatFilesBySourcePrefix({
sourceType,
sourceId
});
return;
}
await Promise.all(
chatList.map((chat) => {
const uId = getChatResourceUid(chat);
if (!uId) return Promise.resolve();
return deleteChatFilesBySourcePrefix({
sourceType,
sourceId,
chatId: chat.chatId,
uId
});
})
);
}
...@@ -4,6 +4,7 @@ import { checkInteractiveResponseStatus } from '@fastgpt/global/core/chat/utils' ...@@ -4,6 +4,7 @@ import { checkInteractiveResponseStatus } from '@fastgpt/global/core/chat/utils'
import type { WorkflowInteractiveResponseType } from '@fastgpt/global/core/workflow/template/system/interactive/type'; import type { WorkflowInteractiveResponseType } from '@fastgpt/global/core/workflow/template/system/interactive/type';
import type { UserChatItemType } from '@fastgpt/global/core/chat/type'; import type { UserChatItemType } from '@fastgpt/global/core/chat/type';
import { MongoChatItem } from './chatItemSchema'; import { MongoChatItem } from './chatItemSchema';
import { buildChatSourceQuery, type ChatSourceParams } from './source';
/** /**
* 解析本轮 workflow 写入 nodeResponse 时应该归属的 AI chat item dataId。 * 解析本轮 workflow 写入 nodeResponse 时应该归属的 AI chat item dataId。
...@@ -29,13 +30,13 @@ export const getInteractiveResponseStatus = ({ ...@@ -29,13 +30,13 @@ export const getInteractiveResponseStatus = ({
}; };
export const resolveResponseChatItemId = async ({ export const resolveResponseChatItemId = async ({
appId, sourceType,
sourceId,
chatId, chatId,
responseChatItemId, responseChatItemId,
interactive, interactive,
userContent userContent
}: { }: ChatSourceParams & {
appId: string;
chatId?: string; chatId?: string;
responseChatItemId: string; responseChatItemId: string;
interactive?: WorkflowInteractiveResponseType; interactive?: WorkflowInteractiveResponseType;
...@@ -48,7 +49,7 @@ export const resolveResponseChatItemId = async ({ ...@@ -48,7 +49,7 @@ export const resolveResponseChatItemId = async ({
const chatItem = await MongoChatItem.findOne( const chatItem = await MongoChatItem.findOne(
{ {
appId, ...buildChatSourceQuery({ sourceType, sourceId }),
chatId, chatId,
obj: ChatRoleEnum.AI obj: ChatRoleEnum.AI
}, },
......
...@@ -13,6 +13,7 @@ import { ...@@ -13,6 +13,7 @@ import {
import { MongoChatItemResponse } from './chatItemResponseSchema'; import { MongoChatItemResponse } from './chatItemResponseSchema';
import { getLogger, LogCategories } from '../../common/logger'; import { getLogger, LogCategories } from '../../common/logger';
import { writePrimary } from '../../common/mongo/utils'; import { writePrimary } from '../../common/mongo/utils';
import { buildChatSourceQuery, buildChatSourceWriteFields, type ChatSourceParams } from './source';
const logger = getLogger(LogCategories.MODULE.CHAT.HISTORY); const logger = getLogger(LogCategories.MODULE.CHAT.HISTORY);
// 常规写入失败后最多重试 3 次;仍失败再进入瘦身 fallback,避免异常详情阻断主流程。 // 常规写入失败后最多重试 3 次;仍失败再进入瘦身 fallback,避免异常详情阻断主流程。
...@@ -20,17 +21,9 @@ const NODE_RESPONSE_WRITE_RETRY_TIMES = 3; ...@@ -20,17 +21,9 @@ const NODE_RESPONSE_WRITE_RETRY_TIMES = 3;
type ChatItemResponseBase = Pick< type ChatItemResponseBase = Pick<
ChatItemResponseSchemaType, ChatItemResponseSchemaType,
'teamId' | 'appId' | 'chatId' | 'chatItemDataId' 'teamId' | 'chatId' | 'chatItemDataId'
>; > &
ChatSourceParams;
export type ChatItemResponseStorageRow = ChatItemResponseBase & {
/**
* 完整 nodeResponse 数据。身份字段也放在 data 内:
* - data.id: 本次节点响应实例 ID。
* - data.parentId: 父响应实例 ID,用于详情读取时重新拼 childrenResponses。
*/
data: ChatHistoryItemResType;
};
/** /**
* saveChat 仍需要同步得到本轮引用、错误数和根节点费用。 * saveChat 仍需要同步得到本轮引用、错误数和根节点费用。
...@@ -53,6 +46,21 @@ type CreateRowsParams = ChatItemResponseBase & { ...@@ -53,6 +46,21 @@ type CreateRowsParams = ChatItemResponseBase & {
nodeResponses?: ChatHistoryItemResType[]; nodeResponses?: ChatHistoryItemResType[];
}; };
type ChatItemResponseStorageBase = Pick<
ChatItemResponseSchemaType,
'teamId' | 'chatId' | 'chatItemDataId'
> &
ReturnType<typeof buildChatSourceWriteFields>;
export type ChatItemResponseStorageRow = ChatItemResponseStorageBase & {
/**
* 完整 nodeResponse 数据。身份字段也放在 data 内:
* - data.id: 本次节点响应实例 ID。
* - data.parentId: 父响应实例 ID,用于详情读取时重新拼 childrenResponses。
*/
data: ChatHistoryItemResType;
};
/** /**
* writer 只依赖 create,测试里可以传入轻量 mock model。 * writer 只依赖 create,测试里可以传入轻量 mock model。
* 这里刻意不暴露 Mongoose Model 全量类型,降低单元测试和业务代码耦合。 * 这里刻意不暴露 Mongoose Model 全量类型,降低单元测试和业务代码耦合。
...@@ -291,6 +299,13 @@ export const createChatItemResponseRows = ({ ...@@ -291,6 +299,13 @@ export const createChatItemResponseRows = ({
nodeResponses = [], nodeResponses = [],
...base ...base
}: CreateRowsParams): ChatItemResponseStorageRow[] => { }: CreateRowsParams): ChatItemResponseStorageRow[] => {
const chatSource = {
sourceType: base.sourceType,
sourceId: base.sourceId
};
const sourceWriteFields = buildChatSourceWriteFields(chatSource);
const { sourceType: _sourceType, sourceId: _sourceId, ...restBase } = base;
return nodeResponses.map((response) => { return nodeResponses.map((response) => {
const id = getResponseId(response); const id = getResponseId(response);
const currentParentId = getParentId(response); const currentParentId = getParentId(response);
...@@ -305,7 +320,8 @@ export const createChatItemResponseRows = ({ ...@@ -305,7 +320,8 @@ export const createChatItemResponseRows = ({
}); });
return { return {
...base, ...restBase,
...sourceWriteFields,
data data
}; };
}); });
...@@ -338,18 +354,21 @@ export const composeChatItemResponseData = ({ rows = [] }: { rows?: ChatItemResp ...@@ -338,18 +354,21 @@ export const composeChatItemResponseData = ({ rows = [] }: { rows?: ChatItemResp
composeNodeResponseDetail(rows); composeNodeResponseDetail(rows);
export const getChatItemResponseData = async ({ export const getChatItemResponseData = async ({
appId, sourceType,
sourceId,
chatId, chatId,
chatItemDataId, chatItemDataId,
fallbackResponseData fallbackResponseData
}: { }: {
appId: string; sourceType: ChatSourceParams['sourceType'];
sourceId: string;
chatId: string; chatId: string;
chatItemDataId: string; chatItemDataId: string;
fallbackResponseData?: ChatHistoryItemResType[]; fallbackResponseData?: ChatHistoryItemResType[];
}) => { }) => {
const rows = await getChatItemResponseRows({ const rows = await getChatItemResponseRows({
appId, sourceType,
sourceId,
chatId, chatId,
chatItemDataId chatItemDataId
}); });
...@@ -362,23 +381,30 @@ export const getChatItemResponseData = async ({ ...@@ -362,23 +381,30 @@ export const getChatItemResponseData = async ({
}; };
export const getChatItemResponseRows = async ({ export const getChatItemResponseRows = async ({
appId, sourceType,
sourceId,
chatId, chatId,
chatItemDataId chatItemDataId
}: { }: {
appId: string; sourceType: ChatSourceParams['sourceType'];
sourceId: string;
chatId: string; chatId: string;
chatItemDataId: string; chatItemDataId: string;
}) => }) => {
const chatSource = { sourceType, sourceId };
return (
// _id 顺序就是 writer create 顺序;详情拼树后,同级 children 也按运行时写入顺序展示。 // _id 顺序就是 writer create 顺序;详情拼树后,同级 children 也按运行时写入顺序展示。
MongoChatItemResponse.find( MongoChatItemResponse.find(
{ appId, chatId, chatItemDataId }, { ...buildChatSourceQuery(chatSource), chatId, chatItemDataId },
{ {
data: 1 data: 1
} }
) )
.sort({ _id: 1 }) .sort({ _id: 1 })
.lean(); .lean()
);
};
/** /**
* 请求级 nodeResponse 写入器。 * 请求级 nodeResponse 写入器。
......
...@@ -9,6 +9,8 @@ import { ...@@ -9,6 +9,8 @@ import {
import { getLogger, LogCategories } from '../../common/logger'; import { getLogger, LogCategories } from '../../common/logger';
import { serviceEnv } from '../../env'; import { serviceEnv } from '../../env';
import { getChatItemResponseData } from './nodeResponseStorage'; import { getChatItemResponseData } from './nodeResponseStorage';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { buildChatSourceQuery } from './source';
const logger = getLogger(LogCategories.MODULE.CHAT.RECORD); const logger = getLogger(LogCategories.MODULE.CHAT.RECORD);
...@@ -91,7 +93,10 @@ const pushChatLogInternal = async ({ ...@@ -91,7 +93,10 @@ const pushChatLogInternal = async ({
return; return;
} }
const chat = await MongoChat.findOne({ chatId }).lean(); const chat = await MongoChat.findOne({
...buildChatSourceQuery({ sourceType: ChatSourceTypeEnum.app, sourceId: appId }),
chatId
}).lean();
if (!chat) { if (!chat) {
return; return;
...@@ -157,7 +162,8 @@ ${JSON.stringify(item.interactive, null, 2)} ...@@ -157,7 +162,8 @@ ${JSON.stringify(item.interactive, null, 2)}
} }
const responseData = await getChatItemResponseData({ const responseData = await getChatItemResponseData({
appId, sourceType: ChatSourceTypeEnum.app,
sourceId: appId,
chatId, chatId,
chatItemDataId: chatItemAi.dataId chatItemDataId: chatItemAi.dataId
}); });
......
...@@ -2,6 +2,7 @@ import { serviceEnv } from '../../env'; ...@@ -2,6 +2,7 @@ import { serviceEnv } from '../../env';
import { getLogger, LogCategories } from '../../common/logger'; import { getLogger, LogCategories } from '../../common/logger';
import { FASTGPT_REDIS_PREFIX, getGlobalRedisConnection } from '../../common/redis'; import { FASTGPT_REDIS_PREFIX, getGlobalRedisConnection } from '../../common/redis';
import type { NextApiResponse } from 'next'; import type { NextApiResponse } from 'next';
import type { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { StreamResumeUnavailableReasonEnum } from '@fastgpt/global/core/workflow/runtime/constants'; import { StreamResumeUnavailableReasonEnum } from '@fastgpt/global/core/workflow/runtime/constants';
const logger = getLogger(LogCategories.MODULE.CHAT.RESUME); const logger = getLogger(LogCategories.MODULE.CHAT.RESUME);
...@@ -38,18 +39,20 @@ let lastLoggedMemoryPressureState: boolean | undefined; ...@@ -38,18 +39,20 @@ let lastLoggedMemoryPressureState: boolean | undefined;
type StreamResumeRedisKeysParams = { type StreamResumeRedisKeysParams = {
teamId: string; teamId: string;
appId: string; sourceType: ChatSourceTypeEnum;
sourceId: string;
chatId: string; chatId: string;
}; };
export const getStreamResumeRedisKeys = ({ export const getStreamResumeRedisKeys = ({
teamId, teamId,
appId, sourceType,
sourceId,
chatId chatId
}: StreamResumeRedisKeysParams) => ({ }: StreamResumeRedisKeysParams) => ({
keyOfStream: `stream:resume:data:${teamId}:${appId}:${chatId}`, keyOfStream: `stream:resume:data:${teamId}:${sourceType}:${sourceId}:${chatId}`,
keyOfUnavailable: `stream:resume:unavailable:${teamId}:${appId}:${chatId}`, keyOfUnavailable: `stream:resume:unavailable:${teamId}:${sourceType}:${sourceId}:${chatId}`,
keyOfActive: `stream:resume:active:${teamId}:${appId}:${chatId}` keyOfActive: `stream:resume:active:${teamId}:${sourceType}:${sourceId}:${chatId}`
}); });
type StreamResumeKeys = ReturnType<typeof getStreamResumeRedisKeys>; type StreamResumeKeys = ReturnType<typeof getStreamResumeRedisKeys>;
......
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { Types } from '../../common/mongo';
export type ChatSourceParams = {
sourceType: ChatSourceTypeEnum;
sourceId: string;
};
/**
* 将业务层 source 语义映射到 chat 三表的历史物理字段。
*
* 第一版不重命名 Mongo 字段,所有新写入仍写入 `appId`,但业务含义为
* `sourceId`。调用方必须通过该 helper 写入,避免再次把 skillId 伪装成 appId。
*/
export function buildChatSourceWriteFields({ sourceType, sourceId }: ChatSourceParams) {
return {
sourceType,
appId: sourceId
};
}
/**
* 构造 chat 三表 source-aware 查询条件。
*
* App 查询默认兼容缺失 `sourceType` 的历史数据;Skill Edit 必须精确匹配
* `sourceType=skillEdit`。
*/
export function buildChatSourceQuery({ sourceType, sourceId }: ChatSourceParams) {
if (sourceType === ChatSourceTypeEnum.app) {
return {
appId: sourceId,
$or: [{ sourceType: ChatSourceTypeEnum.app }, { sourceType: { $exists: false } }]
};
}
if (sourceType === ChatSourceTypeEnum.skillEdit) {
return {
appId: sourceId,
sourceType: ChatSourceTypeEnum.skillEdit
};
}
const exhaustiveCheck: never = sourceType;
throw new Error(`Unsupported chat source type: ${exhaustiveCheck}`);
}
const buildPhysicalSourceIdAggregateMatch = (sourceId: string) => {
if (!Types.ObjectId.isValid(sourceId)) {
return sourceId;
}
// Mongoose 不会自动 cast aggregate.$match,显式兼容 ObjectId 存量数据。
return new Types.ObjectId(sourceId);
};
/**
* 构造 aggregate.$match 使用的 chat source 条件。
*
* 与普通 query helper 语义一致,但会显式把 ObjectId 字符串转换成 ObjectId,
* 避免聚合管线里无法命中历史 `appId` 物理字段。
*/
export function buildChatSourceAggregateMatch(params: ChatSourceParams) {
return {
...buildChatSourceQuery(params),
appId: buildPhysicalSourceIdAggregateMatch(params.sourceId)
};
}
...@@ -6,6 +6,8 @@ import { getLogger, LogCategories } from '../../common/logger'; ...@@ -6,6 +6,8 @@ import { getLogger, LogCategories } from '../../common/logger';
import { createLLMResponse } from '../ai/llm/request'; import { createLLMResponse } from '../ai/llm/request';
import { getDefaultChatTitleModel } from '../ai/model'; import { getDefaultChatTitleModel } from '../ai/model';
import { MongoChat } from './chatSchema'; import { MongoChat } from './chatSchema';
import { buildChatSourceQuery, type ChatSourceParams } from './source';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
const logger = getLogger(LogCategories.MODULE.CHAT); const logger = getLogger(LogCategories.MODULE.CHAT);
...@@ -170,21 +172,23 @@ export type GeneratedChatTitleResult = { ...@@ -170,21 +172,23 @@ export type GeneratedChatTitleResult = {
}; };
export const syncGeneratedChatTitleFromUserContent = async ({ export const syncGeneratedChatTitleFromUserContent = async ({
appId, sourceType,
sourceId,
chatId, chatId,
teamId, teamId,
userContent, userContent,
shouldGenerateTitle = true, shouldGenerateTitle = true,
fixedTitle fixedTitle
}: { }: {
appId: string;
chatId: string; chatId: string;
teamId: string; teamId: string;
userContent: UserChatItemType; userContent: UserChatItemType;
shouldGenerateTitle?: boolean; shouldGenerateTitle?: boolean;
fixedTitle?: string; fixedTitle?: string;
}): Promise<GeneratedChatTitleResult | undefined> => { } & ChatSourceParams): Promise<GeneratedChatTitleResult | undefined> => {
try { try {
// Skill Edit 调试会话不需要模型生成标题,也不写入固定标题,避免调试链路产生额外模型调用。
if (sourceType === ChatSourceTypeEnum.skillEdit) return;
if (!shouldGenerateTitle) return; if (!shouldGenerateTitle) return;
const questionText = getQuestionText(userContent); const questionText = getQuestionText(userContent);
...@@ -208,7 +212,7 @@ export const syncGeneratedChatTitleFromUserContent = async ({ ...@@ -208,7 +212,7 @@ export const syncGeneratedChatTitleFromUserContent = async ({
const result = await MongoChat.updateOne( const result = await MongoChat.updateOne(
{ {
appId, ...buildChatSourceQuery({ sourceType, sourceId }),
chatId, chatId,
$and: [customTitleCondition, titleCondition] $and: [customTitleCondition, titleCondition]
}, },
...@@ -226,7 +230,7 @@ export const syncGeneratedChatTitleFromUserContent = async ({ ...@@ -226,7 +230,7 @@ export const syncGeneratedChatTitleFromUserContent = async ({
updated: result.modifiedCount > 0 updated: result.modifiedCount > 0
}; };
} catch (error) { } catch (error) {
logger.warn('Failed to generate chat title', { appId, chatId, error }); logger.warn('Failed to generate chat title', { sourceType, sourceId, chatId, error });
} }
}; };
...@@ -236,14 +240,15 @@ export const syncGeneratedChatTitleFromUserContent = async ({ ...@@ -236,14 +240,15 @@ export const syncGeneratedChatTitleFromUserContent = async ({
* 这里故意不 await 标题模型请求,避免 `preChatRound` 阻塞主对话流启动。内部 helper 已经 * 这里故意不 await 标题模型请求,避免 `preChatRound` 阻塞主对话流启动。内部 helper 已经
* 自行捕获错误,因此调度失败不会影响对话保存。 * 自行捕获错误,因此调度失败不会影响对话保存。
*/ */
export const scheduleGeneratedChatTitleFromUserContent = (params: { export const scheduleGeneratedChatTitleFromUserContent = (
appId: string; params: {
chatId: string; chatId: string;
teamId: string; teamId: string;
userContent: UserChatItemType; userContent: UserChatItemType;
shouldGenerateTitle?: boolean; shouldGenerateTitle?: boolean;
fixedTitle?: string; fixedTitle?: string;
}) => { } & ChatSourceParams
) => {
return syncGeneratedChatTitleFromUserContent(params); return syncGeneratedChatTitleFromUserContent(params);
}; };
......
import type { ChatItemMiniType, UserChatItemType } from '@fastgpt/global/core/chat/type'; import type { ChatItemMiniType, UserChatItemType } from '@fastgpt/global/core/chat/type';
import { UserError } from '@fastgpt/global/common/error/utils'; import { UserError } from '@fastgpt/global/common/error/utils';
import { MongoChatItem } from '../chatItemSchema'; import { MongoChatItem } from '../chatItemSchema';
import type { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { ChatRoleEnum } from '@fastgpt/global/core/chat/constants'; import { ChatRoleEnum } from '@fastgpt/global/core/chat/constants';
import { buildChatSourceQuery, type ChatSourceParams } from '../source';
export const CHAT_DATA_ID_DUPLICATE_ERROR_MESSAGE = 'Chat dataId already exists'; export const CHAT_DATA_ID_DUPLICATE_ERROR_MESSAGE = 'Chat dataId already exists';
...@@ -11,8 +13,7 @@ export const CHAT_DATA_ID_DUPLICATE_ERROR_MESSAGE = 'Chat dataId already exists' ...@@ -11,8 +13,7 @@ export const CHAT_DATA_ID_DUPLICATE_ERROR_MESSAGE = 'Chat dataId already exists'
* 当前运行前唯一性只约束 AI responseChatItemId;Human 消息允许与 AI 消息使用同一个 * 当前运行前唯一性只约束 AI responseChatItemId;Human 消息允许与 AI 消息使用同一个
* dataId 表示同一轮对话。 * dataId 表示同一轮对话。
*/ */
type ValidateChatRoundDataIdsParams = { type ValidateChatRoundDataIdsParams = ChatSourceParams & {
appId: string;
chatId: string; chatId: string;
userContent: UserChatItemType & { dataId?: string }; userContent: UserChatItemType & { dataId?: string };
responseChatItemId?: string; responseChatItemId?: string;
...@@ -56,11 +57,13 @@ export const assertNoDuplicateChatDataIdsInRequest = (dataIds: Array<string | un ...@@ -56,11 +57,13 @@ export const assertNoDuplicateChatDataIdsInRequest = (dataIds: Array<string | un
* dataId 校验应使用 validateChatRoundDataIds。 * dataId 校验应使用 validateChatRoundDataIds。
*/ */
export const assertNoExistingChatDataIds = async ({ export const assertNoExistingChatDataIds = async ({
appId, sourceType,
sourceId,
chatId, chatId,
dataIds dataIds
}: { }: {
appId: string; sourceType: ChatSourceTypeEnum;
sourceId: string;
chatId: string; chatId: string;
dataIds: Array<string | undefined>; dataIds: Array<string | undefined>;
}) => { }) => {
...@@ -69,7 +72,7 @@ export const assertNoExistingChatDataIds = async ({ ...@@ -69,7 +72,7 @@ export const assertNoExistingChatDataIds = async ({
const existingChatItem = await MongoChatItem.findOne( const existingChatItem = await MongoChatItem.findOne(
{ {
appId, ...buildChatSourceQuery({ sourceType, sourceId }),
chatId, chatId,
dataId: { $in: validDataIds } dataId: { $in: validDataIds }
}, },
...@@ -90,7 +93,8 @@ export const assertNoExistingChatDataIds = async ({ ...@@ -90,7 +93,8 @@ export const assertNoExistingChatDataIds = async ({
* AI placeholder 或最终回复覆盖已有 AI 消息。 * AI placeholder 或最终回复覆盖已有 AI 消息。
*/ */
export const validateChatRoundDataIds = async ({ export const validateChatRoundDataIds = async ({
appId, sourceType,
sourceId,
chatId, chatId,
responseChatItemId responseChatItemId
}: ValidateChatRoundDataIdsParams) => { }: ValidateChatRoundDataIdsParams) => {
...@@ -98,7 +102,7 @@ export const validateChatRoundDataIds = async ({ ...@@ -98,7 +102,7 @@ export const validateChatRoundDataIds = async ({
const existingChatItem = await MongoChatItem.findOne( const existingChatItem = await MongoChatItem.findOne(
{ {
appId, ...buildChatSourceQuery({ sourceType, sourceId }),
chatId, chatId,
obj: ChatRoleEnum.AI, obj: ChatRoleEnum.AI,
dataId: responseChatItemId dataId: responseChatItemId
......
import { ChatErrEnum } from '@fastgpt/global/common/error/code/chat'; import { ChatErrEnum } from '@fastgpt/global/common/error/code/chat';
import { getNanoid } from '@fastgpt/global/common/string/tools'; import { getNanoid } from '@fastgpt/global/common/string/tools';
import { ChatGenerateStatusEnum, ChatRoleEnum } from '@fastgpt/global/core/chat/constants'; import {
ChatGenerateStatusEnum,
ChatRoleEnum,
ChatSourceTypeEnum
} from '@fastgpt/global/core/chat/constants';
import type { ChatSourceEnum } from '@fastgpt/global/core/chat/constants'; import type { ChatSourceEnum } from '@fastgpt/global/core/chat/constants';
import type { AIChatItemType, UserChatItemType } from '@fastgpt/global/core/chat/type'; import type { AIChatItemType, UserChatItemType } from '@fastgpt/global/core/chat/type';
import type { WorkflowInteractiveResponseType } from '@fastgpt/global/core/workflow/template/system/interactive/type'; import type { WorkflowInteractiveResponseType } from '@fastgpt/global/core/workflow/template/system/interactive/type';
...@@ -16,6 +20,7 @@ import { ...@@ -16,6 +20,7 @@ import {
syncGeneratedChatTitleFromUserContent, syncGeneratedChatTitleFromUserContent,
type GeneratedChatTitleResult type GeneratedChatTitleResult
} from '../title'; } from '../title';
import { buildChatSourceQuery, buildChatSourceWriteFields, type ChatSourceParams } from '../source';
export const NO_RECORD_CHAT_ID = 'NO_RECORD_HISTORIES'; export const NO_RECORD_CHAT_ID = 'NO_RECORD_HISTORIES';
...@@ -39,18 +44,16 @@ export const stripUserContentFileUrls = (userContent: UserChatItemType & { dataI ...@@ -39,18 +44,16 @@ export const stripUserContentFileUrls = (userContent: UserChatItemType & { dataI
}); });
}; };
export type EnsurePendingChatRoundParams = { export type EnsurePendingChatRoundParams = ChatSourceParams & {
chatId: string; chatId: string;
appId: string;
teamId: string; teamId: string;
tmbId: string; tmbId: string;
userContent: UserChatItemType & { dataId?: string }; userContent: UserChatItemType & { dataId?: string };
responseChatItemId: string; responseChatItemId: string;
}; };
export type PrepareChatRoundParams = { export type PrepareChatRoundParams = ChatSourceParams & {
chatId: string; chatId: string;
appId: string;
teamId: string; teamId: string;
tmbId: string; tmbId: string;
source: `${ChatSourceEnum}`; source: `${ChatSourceEnum}`;
...@@ -115,17 +118,13 @@ export const getPreparedRoundDataIds = ({ ...@@ -115,17 +118,13 @@ export const getPreparedRoundDataIds = ({
export const prepareChatRound = async ( export const prepareChatRound = async (
params: PrepareChatRoundParams params: PrepareChatRoundParams
): Promise<PrepareChatRoundResult> => { ): Promise<PrepareChatRoundResult> => {
const { const { chatId, teamId, tmbId, source, sourceName, shareId, outLinkUid, responseChatItemId } =
chatId, params;
appId, const chatSource = {
teamId, sourceType: params.sourceType,
tmbId, sourceId: params.sourceId
source, };
sourceName, const sourceWriteFields = buildChatSourceWriteFields(chatSource);
shareId,
outLinkUid,
responseChatItemId
} = params;
if (isSkipSaveChatId(chatId)) { if (isSkipSaveChatId(chatId)) {
return { return {
...@@ -154,14 +153,14 @@ export const prepareChatRound = async ( ...@@ -154,14 +153,14 @@ export const prepareChatRound = async (
await mongoSessionRun(async (session) => { await mongoSessionRun(async (session) => {
const previousChat = await MongoChat.findOneAndUpdate( const previousChat = await MongoChat.findOneAndUpdate(
{ {
appId, ...buildChatSourceQuery(chatSource),
chatId chatId
}, },
{ {
$set: { $set: {
teamId, teamId,
tmbId, tmbId,
appId, ...sourceWriteFields,
chatId, chatId,
source, source,
sourceName, sourceName,
...@@ -192,14 +191,14 @@ export const prepareChatRound = async ( ...@@ -192,14 +191,14 @@ export const prepareChatRound = async (
teamId, teamId,
tmbId, tmbId,
chatId, chatId,
appId, ...sourceWriteFields,
...userPayload ...userPayload
}, },
{ {
teamId, teamId,
tmbId, tmbId,
chatId, chatId,
appId, ...sourceWriteFields,
...aiPlaceholder ...aiPlaceholder
} }
], ],
...@@ -239,7 +238,8 @@ export const preChatRound = async (params: PreChatRoundParams): Promise<PreChatR ...@@ -239,7 +238,8 @@ export const preChatRound = async (params: PreChatRoundParams): Promise<PreChatR
} }
const canStartGenerate = await tryStartGenerateChat({ const canStartGenerate = await tryStartGenerateChat({
appId: params.appId, sourceType: params.sourceType,
sourceId: params.sourceId,
chatId, chatId,
teamId: params.teamId, teamId: params.teamId,
tmbId: params.tmbId, tmbId: params.tmbId,
...@@ -257,7 +257,7 @@ export const preChatRound = async (params: PreChatRoundParams): Promise<PreChatR ...@@ -257,7 +257,7 @@ export const preChatRound = async (params: PreChatRoundParams): Promise<PreChatR
if (isInteractiveContinue) { if (isInteractiveContinue) {
const previousAiItem = await MongoChatItem.findOne( const previousAiItem = await MongoChatItem.findOne(
{ {
appId: params.appId, ...buildChatSourceQuery({ sourceType: params.sourceType, sourceId: params.sourceId }),
chatId, chatId,
obj: ChatRoleEnum.AI obj: ChatRoleEnum.AI
}, },
...@@ -280,7 +280,8 @@ export const preChatRound = async (params: PreChatRoundParams): Promise<PreChatR ...@@ -280,7 +280,8 @@ export const preChatRound = async (params: PreChatRoundParams): Promise<PreChatR
} }
await validateChatRoundDataIds({ await validateChatRoundDataIds({
appId: params.appId, sourceType: params.sourceType,
sourceId: params.sourceId,
chatId, chatId,
userContent: params.userContent, userContent: params.userContent,
responseChatItemId responseChatItemId
...@@ -293,7 +294,8 @@ export const preChatRound = async (params: PreChatRoundParams): Promise<PreChatR ...@@ -293,7 +294,8 @@ export const preChatRound = async (params: PreChatRoundParams): Promise<PreChatR
}); });
const titleGeneration = syncGeneratedChatTitleFromUserContent({ const titleGeneration = syncGeneratedChatTitleFromUserContent({
appId: params.appId, sourceType: params.sourceType,
sourceId: params.sourceId,
chatId, chatId,
teamId: params.teamId, teamId: params.teamId,
userContent: params.userContent, userContent: params.userContent,
...@@ -310,7 +312,8 @@ export const preChatRound = async (params: PreChatRoundParams): Promise<PreChatR ...@@ -310,7 +312,8 @@ export const preChatRound = async (params: PreChatRoundParams): Promise<PreChatR
}; };
} catch (error) { } catch (error) {
await updateChatGenerateStatus({ await updateChatGenerateStatus({
appId: params.appId, sourceType: params.sourceType,
sourceId: params.sourceId,
chatId, chatId,
status: ChatGenerateStatusEnum.error status: ChatGenerateStatusEnum.error
}); });
......
...@@ -3,7 +3,7 @@ import type { ChatItemMiniType } from '@fastgpt/global/core/chat/type'; ...@@ -3,7 +3,7 @@ import type { ChatItemMiniType } from '@fastgpt/global/core/chat/type';
import type { ModuleDispatchProps } from '@fastgpt/global/core/workflow/runtime/type'; import type { ModuleDispatchProps } from '@fastgpt/global/core/workflow/runtime/type';
import { type SelectAppItemType } from '@fastgpt/global/core/workflow/template/system/abandoned/runApp/type'; import { type SelectAppItemType } from '@fastgpt/global/core/workflow/template/system/abandoned/runApp/type';
import { runWorkflow } from '../index'; import { runWorkflow } from '../index';
import { ChatRoleEnum } from '@fastgpt/global/core/chat/constants'; import { ChatRoleEnum, ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { SseResponseEventEnum } from '@fastgpt/global/core/workflow/runtime/constants'; import { SseResponseEventEnum } from '@fastgpt/global/core/workflow/runtime/constants';
import { import {
getWorkflowEntryNodeIds, getWorkflowEntryNodeIds,
...@@ -62,7 +62,8 @@ export const dispatchAppRequest = async (props: Props): Promise<Response> => { ...@@ -62,7 +62,8 @@ export const dispatchAppRequest = async (props: Props): Promise<Response> => {
const chatHistories = getHistories(history, histories); const chatHistories = getHistories(history, histories);
const { files } = chatValue2RuntimePrompt(query); const { files } = chatValue2RuntimePrompt(query);
const childRunningAppInfo = { const childRunningAppInfo = {
id: String(appData._id), sourceType: ChatSourceTypeEnum.app,
sourceId: String(appData._id),
name: appData.name, name: appData.name,
teamId: String(appData.teamId), teamId: String(appData.teamId),
tmbId: String(appData.tmbId), tmbId: String(appData.tmbId),
......
This diff is collapsed. Click to expand it.
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