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 (
const { input, response, durationSeconds } = await callSandboxTool({
toolName: call.function.name,
rawArgs: call.function.arguments ?? '',
appId: String(workflowProps.runningAppInfo.id),
sourceType: workflowProps.runningAppInfo.sourceType,
sourceId: workflowProps.runningAppInfo.sourceId,
userId: String(workflowProps.uid),
chatId: workflowProps.chatId
});
......@@ -239,7 +240,8 @@ if (toolId === SANDBOX_GET_FILE_URL_TOOL_NAME) {
const result = await dispatchSandboxGetFileUrl({
filePath: toolParams.data.paths[0], // Agent 模式单文件路径
appId: runningAppInfo.id,
sourceType: runningAppInfo.sourceType,
sourceId: runningAppInfo.sourceId,
userId: props.uid,
chatId,
lang: props.lang
......
......@@ -6,12 +6,12 @@
**Redis Key 结构:**
```typescript
// Key 格式: agent_runtime_stopping:{appId}:{chatId}
// Key 格式: agent_runtime_stopping:{sourceType}:{sourceId}:{chatId}
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}`;
**参数类型定义:**
```typescript
type WorkflowStatusParams = {
appId: string;
sourceType: ChatSourceTypeEnum;
sourceId: string;
chatId: string;
};
```
......@@ -45,23 +46,23 @@ type WorkflowStatusParams = {
**1. setAgentRuntimeStop**
- **功能**: 设置停止标志
- **参数**: `{ appId, chatId }`
- **参数**: `{ sourceType, sourceId, chatId }`
- **实现**: 使用 `SETEX` 命令,设置键值为 1,TTL 60 秒
**2. shouldWorkflowStop**
- **功能**: 检查工作流是否应该停止
- **参数**: `{ appId, chatId }`
- **参数**: `{ sourceType, sourceId, chatId }`
- **返回**: `Promise<boolean>` - true=应该停止, false=继续运行
- **实现**: GET 命令获取键值,存在则返回 true
**3. delAgentRuntimeStopSign**
- **功能**: 删除停止标志
- **参数**: `{ appId, chatId }`
- **参数**: `{ sourceType, sourceId, chatId }`
- **实现**: DEL 命令删除键
**4. waitForWorkflowComplete**
- **功能**: 等待工作流完成(停止标志被删除)
- **参数**: `{ appId, chatId, timeout?, pollInterval? }`
- **参数**: `{ sourceType, sourceId, chatId, timeout?, pollInterval? }`
- **实现**: 轮询检查停止标志是否被删除,超时返回
### 1.4 边界情况处理
......@@ -303,7 +304,8 @@ const checkStoppingTimer =
apiVersion === 'v2'
? setInterval(async () => {
stopping = await shouldWorkflowStop({
appId: runningAppInfo.id,
sourceType: runningAppInfo.sourceType,
sourceId: runningAppInfo.sourceId,
chatId
});
}, 100)
......@@ -340,7 +342,8 @@ return runWorkflow({
// 工作流完成后删除 Redis 记录
await delAgentRuntimeStopSign({
appId: runningAppInfo.id,
sourceType: runningAppInfo.sourceType,
sourceId: runningAppInfo.sourceId,
chatId
});
});
......@@ -362,7 +365,8 @@ private async checkNodeCanRun(
// Check queue status
if (data.maxRunTimes <= 0) {
getLogger(LogCategories.MODULE.CHAT).error('Max run times is 0', {
appId: data.runningAppInfo.id
sourceType: data.runningAppInfo.sourceType,
sourceId: data.runningAppInfo.sourceId
});
return;
}
......@@ -370,7 +374,8 @@ private async checkNodeCanRun(
// 停止检测
if (checkIsStopping()) {
getLogger(LogCategories.MODULE.CHAT).warn('Workflow stopped', {
appId: data.runningAppInfo.id,
sourceType: data.runningAppInfo.sourceType,
sourceId: data.runningAppInfo.sourceId,
nodeId: node.nodeId,
nodeName: node.name
});
......@@ -666,4 +671,3 @@ describe('Workflow Status Redis Functions', () => {
test('should handle concurrent stop sign operations')
});
```
......@@ -51,6 +51,10 @@ WORKFLOW_PARALLEL_MAX_CONCURRENCY=10
AGENT_SANDBOX_ARCHIVE_MAX_SIZE=50
# Skill sandbox package size limit, in MB
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.
......
......@@ -38,6 +38,10 @@ WORKFLOW_PARALLEL_MAX_CONCURRENCY=10
AGENT_SANDBOX_ARCHIVE_MAX_SIZE=50
# Skill sandbox 包大小上限,单位 MB
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 服务
......
......@@ -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.
### 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
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.
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 /
风险点:升级前已写入的旧追踪记录没有 `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. 对话标题生成模型改为使用系统默认模型配置管理,便于运行时切换和统一维护。
2. LLM 请求追踪记录按团队隔离查询,唯一索引调整为 `{ teamId, requestId }`,避免 `requestId` 被其他团队复用读取敏感 trace。
3. Skill Edit 对话统一使用标准 Chat 存储和清理链路,历史 Skill Debug 对话可通过初始化接口清理。
4. Agent Sandbox 支持配置 npm 和 PyPI 镜像源,初始化时自动写入常见包管理器配置,减少 sandbox 内依赖安装失败。
......@@ -167,8 +167,8 @@
"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.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.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-26T17:38:34+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/model/intro.en.mdx": "2026-06-04T16:10:15+08:00",
......@@ -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/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/41506.en.mdx": "2026-06-25T14:51:00+08:00",
"content/self-host/upgrading/4-15/41506.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-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.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 {
mcp = 'mcp'
}
/**
* 会话所属资源类型。
*
* `ChatSourceEnum` 表示对话入口来源,例如 test/api/online。
* `ChatSourceTypeEnum` 表示会话归属资源类型,用于在同一套 chat 表中隔离 App 和 Skill Edit。
*/
export enum ChatSourceTypeEnum {
app = 'app',
skillEdit = 'skillEdit'
}
export const ChatSourceMap = {
[ChatSourceEnum.test]: {
name: i18nT('common:core.chat.logs.test'),
......
......@@ -3,7 +3,8 @@ import {
ChatFileTypeEnum,
ChatGenerateStatusEnum,
ChatRoleEnum,
ChatSourceEnum
ChatSourceEnum,
ChatSourceTypeEnum
} from './constants';
import { FlowNodeTypeEnum } from '../workflow/node/constant';
import { DispatchNodeResponseKeyEnum } from '../workflow/runtime/constants';
......@@ -89,8 +90,11 @@ export const ChatSchema = z.object({
userId: ObjectIdSchema,
teamId: ObjectIdSchema,
tmbId: ObjectIdSchema,
sourceType: z.enum(ChatSourceTypeEnum).default(ChatSourceTypeEnum.app).meta({
description: '会话所属资源类型。旧数据可能缺失,业务查询层按 app 兼容。'
}),
appId: ObjectIdSchema.meta({
description: '目前已经变成 sourceId,可能是 app 的,也可能是 skill 的'
description: '历史物理字段名。业务语义为 sourceId,可能是 appId 或 skillId。'
}),
appVersionId: ObjectIdSchema.optional().meta({ description: 'appId 为 app 时候才有' }),
createTime: z.coerce.date(),
......@@ -272,6 +276,7 @@ export const ChatItemDBSchema = ChatItemObjItemSchema.and(
userId: z.string(),
teamId: z.string(),
tmbId: z.string(),
sourceType: z.enum(ChatSourceTypeEnum).default(ChatSourceTypeEnum.app),
appId: z.string(),
time: z.coerce.date(),
deleteTime: z.coerce.date().nullish()
......@@ -289,6 +294,7 @@ export type ErrorTextItemType = z.infer<typeof ErrorTextItemSchema>;
/* --------- chat item response ---------- */
export const ChatItemResponseSchema = z.object({
teamId: z.string(),
sourceType: z.enum(ChatSourceTypeEnum).default(ChatSourceTypeEnum.app),
appId: z.string(),
chatId: z.string(),
chatItemDataId: z.string(),
......
......@@ -28,6 +28,7 @@ import { SearchDataResponseQuoteListItemSchema } from '../../dataset/type';
import type { localeType } from '../../../common/i18n/type';
import { type ChatFileStoreValue, type UserChatItemValueItemType } from '../../chat/type';
import { DatasetSearchModeEnum } from '../../dataset/constants';
import type { ChatSourceTypeEnum } from '../../chat/constants';
import { ChatRoleEnum } from '../../chat/constants';
import z from 'zod';
import type { JSONSchemaInputType } from '../../app/jsonschema';
......@@ -71,13 +72,12 @@ export type ChatDispatchProps = {
externalProvider: ExternalProviderType;
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;
tmbId: string; // App tmbId
name: string;
isChildApp?: boolean;
/** 显式指定本轮工作流使用的 sandbox 资源,避免由 appId/userId/chatId 重新生成。 */
sandboxId?: string;
};
runningUserInfo: {
username: string;
......@@ -127,7 +127,7 @@ export type ModuleDispatchProps<T> = ChatDispatchProps & {
export type SystemVariablesType = {
userId: string;
appId: string;
appId?: string;
chatId?: string;
responseChatItemId?: string;
histories: ChatItemMiniType[];
......
import { ObjectIdSchema } from '../../../common/type/mongo';
import z from 'zod';
import { OutLinkChatAuthSchema } from '../../../support/permission/chat';
import { ChatGenerateStatusSchema } from '../chat/api';
import {
ChatGenerateStatusSchema,
createOutLinkChatTargetInputSchema,
transformChatTargetInput
} from '../chat/api';
// Query Params
export const GetLLMRequestRecordParamsSchema = z.object({
......@@ -63,16 +66,17 @@ export const ChatMessageSchema = z.object({
* 断线续传:GET /api/core/chat/resume(与 v2/chat/completions 配套;支持站内、分享、团队域名鉴权)
* ============================================================================ */
export const ResumeStreamParamsSchema = z.object({
...OutLinkChatAuthSchema.shape,
appId: ObjectIdSchema,
export const ResumeStreamParamsRawSchema = createOutLinkChatTargetInputSchema({
teamId: ObjectIdSchema.optional(),
shareId: z.string().optional(),
outLinkUid: z.string().optional(),
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({
list: z.array(z.any()).meta({
......
......@@ -3,7 +3,7 @@ import { DevApiTagsMap } from '../../tag';
import {
GetLLMRequestRecordParamsSchema,
LLMRequestRecordSchema,
ResumeStreamParamsSchema,
ResumeStreamParamsRawSchema,
StreamNoNeedToBeResumeSchema
} from './api';
import { SandboxPath } from './sandbox';
......@@ -40,10 +40,10 @@ export const AIPath: OpenAPIPath = {
get: {
summary: '恢复流式响应',
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],
requestParams: {
query: ResumeStreamParamsSchema
query: ResumeStreamParamsRawSchema
},
responses: {
200: {
......
import { OutLinkChatAuthSchema } from '../../../../support/permission/chat';
import z from 'zod';
import { createChatTargetInputSchema, transformChatTargetInput } from '../../chat/api';
const SandboxBaseSchema = z.object({
appId: z.string().meta({
example: '68ad85a7463006c963799a05',
description: '应用 ID'
}),
const SandboxBaseShape = {
chatId: z.string().meta({
example: 'bEdzC6PNupZrr1RoVutMF2DL',
description: '对话 ID'
}),
outLinkAuthData: OutLinkChatAuthSchema.optional().describe('外链鉴权数据')
});
};
const withSandboxTarget = <T extends z.ZodRawShape>(shape: T) =>
createChatTargetInputSchema({
...SandboxBaseShape,
...shape
}).transform(transformChatTargetInput);
/**
* 下载文件或目录 - 请求体(响应为文件流或 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('要下载的路径(文件或目录)')
});
export type SandboxDownloadBody = z.input<typeof SandboxDownloadBodySchema>;
export type SandboxDownloadRuntimeBody = z.output<typeof SandboxDownloadBodySchema>;
export const SandboxDownloadResponseSchema = z
.string()
......@@ -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({
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>;
/**
......@@ -41,7 +51,14 @@ export type SandboxCheckExistResponse = z.infer<typeof SandboxCheckExistResponse
export const SandboxChannelSchema = z.enum(['fs', 'terminal']).describe('沙盒 WebSocket 通道');
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,
permission: SandboxTicketPermissionSchema.optional()
.default('read')
......@@ -53,16 +70,24 @@ export const SandboxGetTicketResponseSchema = z.object({
export type SandboxChannel = z.infer<typeof SandboxChannelSchema>;
export type SandboxTicketPermission = z.infer<typeof SandboxTicketPermissionSchema>;
export type SandboxGetTicketBody = z.input<typeof SandboxGetTicketBodySchema>;
export type SandboxGetTicketRuntimeBody = z.output<typeof SandboxGetTicketBodySchema>;
export type SandboxGetTicketResponse = z.infer<typeof SandboxGetTicketResponseSchema>;
/**
* 获取 HTML 预览链接 - 请求/响应
*/
export const SandboxGetHtmlPreviewLinkBodySchema = SandboxBaseSchema.extend({
export const SandboxGetHtmlPreviewLinkBodyRawSchema = createChatTargetInputSchema({
...SandboxBaseShape,
filePath: z.string().describe('文件路径')
});
export const SandboxGetHtmlPreviewLinkBodySchema = withSandboxTarget({
filePath: z.string().describe('文件路径')
});
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<
typeof SandboxGetHtmlPreviewLinkResponseSchema
>;
import type { OpenAPIPath } from '../../../type';
import { DevApiTagsMap } from '../../../tag';
import {
SandboxDownloadBodySchema,
SandboxDownloadBodyRawSchema,
SandboxDownloadResponseSchema,
SandboxCheckExistBodySchema,
SandboxCheckExistBodyRawSchema,
SandboxCheckExistResponseSchema,
SandboxGetTicketBodySchema,
SandboxGetTicketBodyRawSchema,
SandboxGetTicketResponseSchema,
SandboxGetHtmlPreviewLinkBodySchema,
SandboxGetHtmlPreviewLinkBodyRawSchema,
SandboxGetHtmlPreviewLinkResponseSchema
} from './api';
......@@ -20,7 +20,7 @@ export const SandboxPath: OpenAPIPath = {
requestBody: {
content: {
'application/json': {
schema: SandboxDownloadBodySchema
schema: SandboxDownloadBodyRawSchema
}
}
},
......@@ -44,7 +44,7 @@ export const SandboxPath: OpenAPIPath = {
requestBody: {
content: {
'application/json': {
schema: SandboxGetHtmlPreviewLinkBodySchema
schema: SandboxGetHtmlPreviewLinkBodyRawSchema
}
}
},
......@@ -69,7 +69,7 @@ export const SandboxPath: OpenAPIPath = {
requestBody: {
content: {
'application/json': {
schema: SandboxCheckExistBodySchema
schema: SandboxCheckExistBodyRawSchema
}
}
},
......@@ -94,7 +94,7 @@ export const SandboxPath: OpenAPIPath = {
requestBody: {
content: {
'application/json': {
schema: SandboxGetTicketBodySchema
schema: SandboxGetTicketBodyRawSchema
}
}
},
......
......@@ -13,14 +13,13 @@ import {
ZipEntryInfoSchema
} from '../../../../core/ai/skill/type';
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 SandboxInstanceKeySchema = z.string().min(1).describe('FastGPT sandbox instance key');
const NullableParentIdSchema = z.string().nullable().optional().meta({
description: '父级目录 ID'
});
const LooseObjectSchema = z.object({}).catchall(z.any());
export const ListSkillsQuerySchema = z.object({
source: z.enum(['store', 'mine']).optional().describe('技能来源: store=系统技能, mine=我的技能'),
......@@ -218,50 +217,12 @@ export const SkillDebugChatBodySchema = z.object({
skillId: IdSchema,
chatId: z.string().min(1),
responseChatItemId: z.string().optional(),
messages: z.array(LooseObjectSchema),
messages: z.array(ChatCompletionMessageParamSchema),
model: z.string().optional(),
systemPrompt: z.string().optional()
});
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({
skillId: IdSchema
});
......@@ -320,31 +281,6 @@ export const ExportSkillQuerySchema = z.object({
});
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({
skillId: IdSchema,
pageNum: z.number().int().positive().optional().describe('页码,从 1 开始'),
......
......@@ -24,13 +24,6 @@ import {
SaveDeploySkillBodySchema,
SaveDeploySkillResponseSchema,
SkillDebugChatBodySchema,
SkillDebugSessionControlBodySchema,
SkillDebugSessionStopResponseSchema,
SkillDebugRecordsBodySchema,
SkillDebugRecordsResponseSchema,
SkillDebugSessionDeleteBodySchema,
SkillDebugSessionListQuerySchema,
SkillDebugSessionListResponseSchema,
SwitchSkillVersionBodySchema,
UpdateSkillBodySchema,
UpdateSkillVersionBodySchema
......@@ -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': {
post: {
summary: '获取技能版本列表',
......
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';
export const ChatGenerateStatusSchema = z
.enum(ChatGenerateStatusEnum)
.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 */
export const GetRecentlyUsedAppsResponseSchema = z.array(
z.object({
......
......@@ -2,27 +2,30 @@ import { OutLinkChatAuthSchema } from '../../../../support/permission/chat';
import { ObjectIdSchema } from '../../../../common/type/mongo';
import z from 'zod';
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 { OpenAPIAppChatConfigSchema } from '../../app/common/api';
import { ChatGenerateStatusSchema } from '../api';
import {
ChatGenerateStatusSchema,
createChatTargetInputSchema,
transformChatTargetInput
} from '../api';
/* Init */
// Online chat
export const InitChatQuerySchema = z
.object({
appId: ObjectIdSchema.describe('应用ID'),
chatId: z.string().min(1).describe('会话ID'),
loadCustomFeedbacks: z.coerce.boolean().optional().describe('是否加载自定义反馈')
})
.meta({
example: {
appId: '1234567890',
chatId: '1234567890',
loadCustomFeedbacks: true
}
});
export type InitChatQueryType = z.infer<typeof InitChatQuerySchema>;
export const InitChatQueryRawSchema = createChatTargetInputSchema({
chatId: z.string().min(1).describe('会话ID'),
loadCustomFeedbacks: z.coerce.boolean().optional().describe('是否加载自定义反馈')
}).meta({
example: {
appId: '1234567890',
chatId: '1234567890',
loadCustomFeedbacks: true
}
});
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` */
export const InitTeamChatQuerySchema = z.object({
......@@ -35,7 +38,9 @@ export type InitTeamChatQueryType = z.infer<typeof InitTeamChatQuerySchema>;
export const InitChatResponseSchema = z.object({
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('用户头像'),
title: z.string().describe('对话标题'),
variables: z.record(z.string(), z.any()).optional().describe('全局变量值'),
......@@ -58,23 +63,22 @@ export const InitChatResponseSchema = z.object({
export type InitChatResponseType = z.infer<typeof InitChatResponseSchema>;
/* ============ v2/chat/stop ============ */
export const StopV2ChatSchema = z
.object({
appId: ObjectIdSchema.describe('应用ID'),
chatId: z.string().min(1).describe('会话ID'),
outLinkAuthData: OutLinkChatAuthSchema.optional().describe('外链鉴权数据')
})
.meta({
example: {
appId: '1234567890',
chatId: '1234567890',
outLinkAuthData: {
shareId: '1234567890',
outLinkUid: '1234567890'
}
export const StopV2ChatRawSchema = createChatTargetInputSchema({
chatId: z.string().min(1).describe('会话ID'),
outLinkAuthData: OutLinkChatAuthSchema.optional().describe('外链鉴权数据')
}).meta({
example: {
appId: '1234567890',
chatId: '1234567890',
outLinkAuthData: {
shareId: '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
.object({
......
import type { OpenAPIPath } from '../../../type';
import { DevApiTagsMap, SystemOpenApiTagMap } from '../../../tag';
import {
StopV2ChatSchema,
StopV2ChatRawSchema,
StopV2ChatResponseSchema,
InitChatQuerySchema,
InitChatQueryRawSchema,
InitChatResponseSchema
} from './api';
......@@ -14,7 +14,7 @@ export const ChatControllerPath: OpenAPIPath = {
description: '',
tags: [DevApiTagsMap.chatHistory, SystemOpenApiTagMap.chatHistory],
requestParams: {
query: InitChatQuerySchema
query: InitChatQueryRawSchema
},
responses: {
200: {
......@@ -37,7 +37,7 @@ export const ChatControllerPath: OpenAPIPath = {
requestBody: {
content: {
'application/json': {
schema: StopV2ChatSchema
schema: StopV2ChatRawSchema
}
}
},
......
import z from 'zod';
import { createChatTargetInputSchema, transformChatTargetInput } from '../api';
/* =============== updateFeedbackReadStatus =============== */
export const UpdateFeedbackReadStatusBodySchema = z.object({
appId: z.string().min(1).meta({
example: '68ad85a7463006c963799a05',
description: '应用 ID'
}),
const FeedbackTargetSchema = {
chatId: z.string().min(1).meta({
example: 'chat123',
description: '对话 ID'
......@@ -13,13 +9,25 @@ export const UpdateFeedbackReadStatusBodySchema = z.object({
dataId: z.string().min(1).meta({
example: 'data123',
description: '消息数据 ID'
}),
})
};
/* =============== updateFeedbackReadStatus =============== */
export const UpdateFeedbackReadStatusBodyRawSchema = createChatTargetInputSchema({
...FeedbackTargetSchema,
isRead: z.boolean().meta({
example: true,
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({
success: z.boolean().meta({
......@@ -32,19 +40,8 @@ export type UpdateFeedbackReadStatusResponseType = z.infer<
>;
/* =============== adminUpdate =============== */
export const AdminUpdateFeedbackBodySchema = z.object({
appId: z.string().min(1).meta({
example: '68ad85a7463006c963799a05',
description: '应用 ID'
}),
chatId: z.string().min(1).meta({
example: 'chat123',
description: '对话 ID'
}),
dataId: z.string().min(1).meta({
example: 'data123',
description: '消息数据 ID'
}),
export const AdminUpdateFeedbackBodyRawSchema = createChatTargetInputSchema({
...FeedbackTargetSchema,
datasetId: z.string().min(1).meta({
example: 'dataset123',
description: '数据集 ID'
......@@ -62,49 +59,33 @@ export const AdminUpdateFeedbackBodySchema = z.object({
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 type AdminUpdateFeedbackResponseType = z.infer<typeof AdminUpdateFeedbackResponseSchema>;
/* =============== closeCustom =============== */
export const CloseCustomFeedbackBodySchema = z.object({
appId: z.string().min(1).meta({
example: '68ad85a7463006c963799a05',
description: '应用 ID'
}),
chatId: z.string().min(1).meta({
example: 'chat123',
description: '对话 ID'
}),
dataId: z.string().min(1).meta({
example: 'data123',
description: '消息数据 ID'
}),
export const CloseCustomFeedbackBodyRawSchema = createChatTargetInputSchema({
...FeedbackTargetSchema,
index: z.number().int().nonnegative().meta({
example: 0,
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 type CloseCustomFeedbackResponseType = z.infer<typeof CloseCustomFeedbackResponseSchema>;
/* =============== updateUserFeedback =============== */
export const UpdateUserFeedbackBodySchema = z.object({
appId: z.string().min(1).meta({
example: '68ad85a7463006c963799a05',
description: '应用 ID'
}),
chatId: z.string().min(1).meta({
example: 'chat123',
description: '对话 ID'
}),
dataId: z.string().min(1).meta({
example: 'data123',
description: '消息数据 ID'
}),
export const UpdateUserFeedbackBodyRawSchema = createChatTargetInputSchema({
...FeedbackTargetSchema,
userGoodFeedback: z.string().nullish().meta({
example: '回答很好',
description: '用户好评反馈内容'
......@@ -114,17 +95,16 @@ export const UpdateUserFeedbackBodySchema = z.object({
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 type UpdateUserFeedbackResponseType = z.infer<typeof UpdateUserFeedbackResponseSchema>;
/* =============== getFeedbackRecordIds =============== */
export const GetFeedbackRecordIdsBodySchema = z.object({
appId: z.string().meta({
example: '68ad85a7463006c963799a05',
description: '应用 ID'
}),
export const GetFeedbackRecordIdsBodyRawSchema = createChatTargetInputSchema({
chatId: z.string().meta({
example: 'chat123',
description: '对话 ID'
......@@ -138,7 +118,10 @@ export const GetFeedbackRecordIdsBodySchema = z.object({
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({
total: z.number().int().nonnegative().meta({
......
......@@ -2,15 +2,15 @@ import type { OpenAPIPath } from '../../../type';
import { DevApiTagsMap } from '../../../tag';
import { SystemOpenApiTagMap } from '../../../tag';
import {
UpdateFeedbackReadStatusBodySchema,
UpdateFeedbackReadStatusBodyRawSchema,
UpdateFeedbackReadStatusResponseSchema,
AdminUpdateFeedbackBodySchema,
AdminUpdateFeedbackBodyRawSchema,
AdminUpdateFeedbackResponseSchema,
CloseCustomFeedbackBodySchema,
CloseCustomFeedbackBodyRawSchema,
CloseCustomFeedbackResponseSchema,
UpdateUserFeedbackBodySchema,
UpdateUserFeedbackBodyRawSchema,
UpdateUserFeedbackResponseSchema,
GetFeedbackRecordIdsBodySchema,
GetFeedbackRecordIdsBodyRawSchema,
GetFeedbackRecordIdsResponseSchema
} from './api';
......@@ -23,7 +23,7 @@ export const ChatFeedbackPath: OpenAPIPath = {
requestBody: {
content: {
'application/json': {
schema: UpdateUserFeedbackBodySchema
schema: UpdateUserFeedbackBodyRawSchema
}
}
},
......@@ -47,7 +47,7 @@ export const ChatFeedbackPath: OpenAPIPath = {
requestBody: {
content: {
'application/json': {
schema: GetFeedbackRecordIdsBodySchema
schema: GetFeedbackRecordIdsBodyRawSchema
}
}
},
......@@ -65,13 +65,13 @@ export const ChatFeedbackPath: OpenAPIPath = {
},
'/core/chat/feedback/updateFeedbackReadStatus': {
post: {
summary: '应用管理员-更新反馈阅读状态',
summary: '更新反馈阅读状态',
description: '标记指定消息的反馈为已读或未读状态',
tags: [DevApiTagsMap.chatFeedback],
requestBody: {
content: {
'application/json': {
schema: UpdateFeedbackReadStatusBodySchema
schema: UpdateFeedbackReadStatusBodyRawSchema
}
}
},
......@@ -89,13 +89,13 @@ export const ChatFeedbackPath: OpenAPIPath = {
},
'/core/chat/feedback/adminUpdate': {
post: {
summary: '应用管理员-标注反馈',
description: '管理员为指定消息添加或更新标注反馈,包含数据集关联信息',
summary: '标注反馈',
description: '为指定消息添加或更新标注反馈,包含数据集关联信息',
tags: [DevApiTagsMap.chatFeedback],
requestBody: {
content: {
'application/json': {
schema: AdminUpdateFeedbackBodySchema
schema: AdminUpdateFeedbackBodyRawSchema
}
}
},
......@@ -113,13 +113,13 @@ export const ChatFeedbackPath: OpenAPIPath = {
},
'/core/chat/feedback/closeCustom': {
post: {
summary: '应用管理员-关闭自定义反馈',
summary: '关闭自定义反馈',
description: '删除或关闭指定索引位置的自定义反馈条目',
tags: [DevApiTagsMap.chatFeedback],
requestBody: {
content: {
'application/json': {
schema: CloseCustomFeedbackBodySchema
schema: CloseCustomFeedbackBodyRawSchema
}
}
},
......
import { OutLinkChatAuthSchema } from '../../../../support/permission/chat';
import { ObjectIdSchema } from '../../../../common/type/mongo';
import { AppFileSelectConfigTypeSchema } from '../../../../core/app/type/config.schema';
import z from 'zod';
import { createChatTargetInputSchema, transformChatTargetInput } from '../api';
/* ============ chat file ============ */
export const PresignChatFileGetUrlSchema = z
.object({
key: z.string().min(1).describe('文件key'),
appId: ObjectIdSchema.describe('应用ID'),
mode: z.enum(['proxy', 'presigned']).optional().describe('下载方式'),
outLinkAuthData: OutLinkChatAuthSchema.optional().describe('外链鉴权数据')
})
.meta({
example: {
key: '1234567890',
appId: '1234567890',
outLinkAuthData: {
shareId: '1234567890',
outLinkUid: '1234567890'
}
const withChatFileTarget = <T extends z.ZodRawShape>(shape: T) =>
createChatTargetInputSchema(shape).transform(transformChatTargetInput);
export const PresignChatFileGetUrlRawSchema = createChatTargetInputSchema({
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('外链鉴权数据')
}).meta({
example: {
key: '1234567890',
appId: '1234567890',
chatId: '1234567890',
outLinkAuthData: {
shareId: '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
.object({
filename: z.string().min(1).describe('文件名'),
appId: ObjectIdSchema.describe('应用ID'),
chatId: z.string().min(1).describe('对话ID'),
fileSelectConfig: AppFileSelectConfigTypeSchema.describe('本次上传控件的文件选择配置'),
outLinkAuthData: OutLinkChatAuthSchema.optional().describe('外链鉴权数据')
})
.meta({
example: {
filename: '1234567890',
appId: '1234567890',
chatId: '1234567890',
fileSelectConfig: {
canSelectFile: true,
customFileExtensionList: ['.txt']
},
outLinkAuthData: {
shareId: '1234567890',
outLinkUid: '1234567890'
}
export const PresignChatFilePostUrlRawSchema = createChatTargetInputSchema({
filename: z.string().min(1).describe('文件名'),
chatId: z.string().min(1).describe('对话ID'),
fileSelectConfig: AppFileSelectConfigTypeSchema.describe('本次上传控件的文件选择配置'),
outLinkAuthData: OutLinkChatAuthSchema.optional().describe('外链鉴权数据')
}).meta({
example: {
filename: '1234567890',
appId: '1234567890',
chatId: '1234567890',
fileSelectConfig: {
canSelectFile: true,
customFileExtensionList: ['.txt']
},
outLinkAuthData: {
shareId: '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 { DevApiTagsMap } from '../../../tag';
import { PresignChatFilePostUrlSchema, PresignChatFileGetUrlSchema } from './api';
import { PresignChatFilePostUrlRawSchema, PresignChatFileGetUrlRawSchema } from './api';
import { CreatePostPresignedUrlResponseSchema } from '../../../../common/file/s3/type';
import { z } from 'zod';
......@@ -13,7 +13,7 @@ export const ChatFilePath: OpenAPIPath = {
requestBody: {
content: {
'application/json': {
schema: PresignChatFilePostUrlSchema
schema: PresignChatFilePostUrlRawSchema
}
}
},
......@@ -37,7 +37,7 @@ export const ChatFilePath: OpenAPIPath = {
requestBody: {
content: {
'application/json': {
schema: PresignChatFileGetUrlSchema
schema: PresignChatFileGetUrlRawSchema
}
}
},
......
......@@ -4,9 +4,13 @@ import { DevApiTagsMap } from '../../../tag';
import {
HelperBotCompletionsParamsSchema,
DeleteHelperBotChatParamsSchema,
GetHelperBotFilePresignParamsSchema,
GetHelperBotFilePreviewParamsSchema,
GetHelperBotFilePreviewResponseSchema,
GetHelperBotChatRecordsParamsSchema,
GetHelperBotChatRecordsResponseSchema
} from './api';
import { CreatePostPresignedUrlResponseSchema } from '../../../../common/file/s3/type';
export const HelperBotPath: OpenAPIPath = {
'/proApi/core/chat/helperBot/completions': {
......@@ -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 { ObjectIdSchema } from '../../../../common/type/mongo';
import { OutLinkChatAuthSchema } from '../../../../support/permission/chat';
import { ChatSourceEnum } from '../../../../core/chat/constants';
import { PaginationSchema, PaginationResponseSchema } from '../../../api';
import { ChatGenerateStatusSchema } from '../api';
import {
ChatGenerateStatusSchema,
createChatTargetInputSchema,
createOptionalOutLinkChatTargetInputSchema,
createOutLinkChatTargetInputSchema,
refineOptionalChatTargetInput,
transformChatTargetInput,
transformOptionalChatTargetInput
} from '../api';
// Get chat sessions schema
export const GetHistoriesBodySchema = PaginationSchema.extend(OutLinkChatAuthSchema.shape).extend({
appId: z.string().optional().describe('应用ID'),
const GetHistoriesPropsSchema = {
source: z.enum(ChatSourceEnum).optional().describe('对话来源'),
startCreateTime: z.string().optional().describe('创建时间开始'),
endCreateTime: z.string().optional().describe('创建时间结束'),
startUpdateTime: 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(
z.object({
chatId: z.string(),
......@@ -29,11 +42,16 @@ export const GetHistoriesResponseSchema = PaginationResponseSchema(
);
export type GetHistoriesResponseType = z.infer<typeof GetHistoriesResponseSchema>;
export const GetHistoryStatusBodySchema = OutLinkChatAuthSchema.extend({
appId: ObjectIdSchema.optional().describe('应用ID'),
const GetHistoryStatusPropsSchema = {
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({
list: z.array(
......@@ -47,38 +65,49 @@ export const GetHistoryStatusResponseSchema = z.object({
});
export type GetHistoryStatusResponseType = z.infer<typeof GetHistoryStatusResponseSchema>;
export const MarkChatReadBodySchema = OutLinkChatAuthSchema.extend({
appId: ObjectIdSchema.describe('应用ID'),
const MarkChatReadPropsSchema = {
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
export const UpdateHistoryBodySchema = OutLinkChatAuthSchema.extend({
appId: ObjectIdSchema.describe('应用ID'),
const UpdateHistoryPropsSchema = {
chatId: z.string().min(1).describe('会话ID'),
title: z.string().optional().describe('标题'),
customTitle: z.string().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
export const DelChatHistorySchema = OutLinkChatAuthSchema.extend({
appId: ObjectIdSchema.optional().describe('应用ID'),
export const DelChatHistoryRawSchema = createOptionalOutLinkChatTargetInputSchema({
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
export const ClearChatHistoriesSchema = OutLinkChatAuthSchema.extend({
appId: ObjectIdSchema.optional().describe('应用ID')
});
export type ClearChatHistoriesType = z.infer<typeof ClearChatHistoriesSchema>;
export const ClearChatHistoriesRawSchema = createOptionalOutLinkChatTargetInputSchema({});
export const ClearChatHistoriesSchema = ClearChatHistoriesRawSchema.transform(
transformOptionalChatTargetInput
);
export type ClearChatHistoriesType = z.infer<typeof ClearChatHistoriesRawSchema>;
export type ClearChatHistoriesRuntimeType = z.infer<typeof ClearChatHistoriesSchema>;
// Batch delete chat sessions schema (for log manager)
export const ChatBatchDeleteBodySchema = z.object({
appId: ObjectIdSchema,
export const ChatBatchDeleteBodyRawSchema = createChatTargetInputSchema({
chatIds: z
.array(z.string().min(1))
.min(1)
......@@ -87,4 +116,7 @@ export const ChatBatchDeleteBodySchema = z.object({
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 { DevApiTagsMap, SystemOpenApiTagMap } from '../../../tag';
import {
GetHistoriesBodySchema,
GetHistoriesBodyRawSchema,
GetHistoriesResponseSchema,
GetHistoryStatusBodySchema,
GetHistoryStatusBodyRawSchema,
GetHistoryStatusResponseSchema,
MarkChatReadBodySchema,
UpdateHistoryBodySchema,
ChatBatchDeleteBodySchema,
DelChatHistorySchema,
ClearChatHistoriesSchema
MarkChatReadBodyRawSchema,
UpdateHistoryBodyRawSchema,
ChatBatchDeleteBodyRawSchema,
DelChatHistoryRawSchema,
ClearChatHistoriesRawSchema
} from './api';
export const ChatHistoryPath: OpenAPIPath = {
'/core/chat/history/getHistories': {
post: {
summary: '获取会话列表',
description: '分页获取指定应用的会话',
description: '分页获取会话列表',
tags: [DevApiTagsMap.chatHistory, SystemOpenApiTagMap.chatHistory],
requestBody: {
content: {
'application/json': {
schema: GetHistoriesBodySchema
schema: GetHistoriesBodyRawSchema
}
}
},
......@@ -46,7 +46,7 @@ export const ChatHistoryPath: OpenAPIPath = {
requestBody: {
content: {
'application/json': {
schema: GetHistoryStatusBodySchema
schema: GetHistoryStatusBodyRawSchema
}
}
},
......@@ -70,7 +70,7 @@ export const ChatHistoryPath: OpenAPIPath = {
requestBody: {
content: {
'application/json': {
schema: MarkChatReadBodySchema
schema: MarkChatReadBodyRawSchema
}
}
},
......@@ -89,7 +89,7 @@ export const ChatHistoryPath: OpenAPIPath = {
requestBody: {
content: {
'application/json': {
schema: UpdateHistoryBodySchema
schema: UpdateHistoryBodyRawSchema
}
}
},
......@@ -106,7 +106,7 @@ export const ChatHistoryPath: OpenAPIPath = {
description: '软删除指定的单个会话,不会物理删除',
tags: [DevApiTagsMap.chatHistory, SystemOpenApiTagMap.chatHistory],
requestParams: {
query: DelChatHistorySchema
query: DelChatHistoryRawSchema
},
responses: {
200: {
......@@ -117,11 +117,11 @@ export const ChatHistoryPath: OpenAPIPath = {
},
'/core/chat/history/clearHistories': {
delete: {
summary: '清空应用会话',
description: '清空指定应用的所有会话(软删除)',
summary: '清空会话',
description: '清空所有会话(软删除)',
tags: [DevApiTagsMap.chatHistory, SystemOpenApiTagMap.chatHistory],
requestParams: {
query: ClearChatHistoriesSchema
query: ClearChatHistoriesRawSchema
},
responses: {
200: {
......@@ -133,12 +133,12 @@ export const ChatHistoryPath: OpenAPIPath = {
'/core/chat/history/batchDelete': {
post: {
summary: '批量删除会话',
description: '批量删除指定应用的多个会话(真实删除),需应用日志管理权限。',
description: '批量删除多个会话(真实删除),需对应会话目标的管理权限。',
tags: [DevApiTagsMap.chatHistory, SystemOpenApiTagMap.chatHistory],
requestBody: {
content: {
'application/json': {
schema: ChatBatchDeleteBodySchema
schema: ChatBatchDeleteBodyRawSchema
}
}
},
......
......@@ -7,7 +7,7 @@ import { OutLinkChatAuthSchema } from '../../../../support/permission/chat';
* API: 获取对话输入引导列表
* Route: POST /api/core/chat/inputGuide/list
* Method: POST
* Description: 获取指定应用的对话输入引导列表,支持关键词搜索
* Description: 获取对话输入引导列表,支持关键词搜索
* Tags: ['Chat', 'InputGuide', 'Read']
* ============================================================================ */
......@@ -36,7 +36,7 @@ export type ChatInputGuideListResponseType = z.infer<typeof ChatInputGuideListRe
* API: 统计对话输入引导总数
* Route: GET /api/core/chat/inputGuide/countTotal
* Method: GET
* Description: 获取指定应用的对话输入引导总数
* Description: 获取对话输入引导总数
* Tags: ['Chat', 'InputGuide', 'Read']
* ============================================================================ */
......@@ -102,10 +102,10 @@ export const DeleteChatInputGuideResponseSchema = z.undefined().meta({ descripti
export type DeleteChatInputGuideResponseType = z.infer<typeof DeleteChatInputGuideResponseSchema>;
/* ============================================================================
* API: 删除应用所有对话输入引导
* API: 删除所有对话输入引导
* Route: DELETE /api/core/chat/inputGuide/deleteAll
* Method: DELETE
* Description: 删除指定应用的所有对话输入引导
* Description: 删除所有对话输入引导
* Tags: ['Chat', 'InputGuide', 'Delete']
* ============================================================================ */
......
......@@ -20,7 +20,7 @@ export const ChatInputGuidePath: OpenAPIPath = {
'/core/chat/inputGuide/list': {
post: {
summary: '获取对话输入引导列表',
description: '获取指定应用的对话输入引导列表,支持关键词模糊搜索和分页',
description: '获取对话输入引导列表,支持关键词模糊搜索和分页',
tags: [DevApiTagsMap.chatInputGuide],
requestBody: {
content: {
......@@ -44,7 +44,7 @@ export const ChatInputGuidePath: OpenAPIPath = {
'/core/chat/inputGuide/countTotal': {
get: {
summary: '统计对话输入引导总数',
description: '获取指定应用的对话输入引导总数',
description: '获取对话输入引导总数',
tags: [DevApiTagsMap.chatInputGuide],
parameters: [
{
......@@ -116,8 +116,8 @@ export const ChatInputGuidePath: OpenAPIPath = {
},
'/core/chat/inputGuide/deleteAll': {
delete: {
summary: '删除应用所有对话输入引导',
description: '删除指定应用的所有对话输入引导',
summary: '删除所有对话输入引导',
description: '删除所有对话输入引导',
tags: [DevApiTagsMap.chatInputGuide],
requestBody: {
content: {
......
import type { OpenAPIPath } from '../../../type';
import { DevApiTagsMap, SystemOpenApiTagMap } from '../../../tag';
import {
GetResDataQuerySchema,
DeleteChatRecordBodySchema,
GetResDataQueryRawSchema,
DeleteChatRecordBodyRawSchema,
DeleteChatRecordResponseSchema,
GetQuoteBodySchema,
GetQuoteBodyRawSchema,
GetQuoteResponseSchema,
GetCollectionQuoteBodySchema,
GetCollectionQuoteBodyRawSchema,
GetCollectionQuoteResSchema,
GetPaginationRecordsBodySchema,
GetPaginationRecordsBodyRawSchema,
GetPaginationRecordsResponseSchema,
GetRecordsV2BodySchema,
GetRecordsV2BodyRawSchema,
GetRecordsV2ResponseSchema,
GetChatSpeechBodySchema
GetChatSpeechBodySchema,
AudioTranscriptionsFormRawSchema
} from './api';
export const ChatRecordPath: OpenAPIPath = {
'/core/chat/record/getPaginationRecords': {
post: {
summary: '分页获取对话',
description: '分页获取指定应用和会话的对话,支持多种鉴权模式',
description: '分页获取指定会话的对话,支持多种鉴权模式',
tags: [DevApiTagsMap.chatRecord, SystemOpenApiTagMap.chat],
requestBody: {
content: {
'application/json': {
schema: GetPaginationRecordsBodySchema
schema: GetPaginationRecordsBodyRawSchema
}
}
},
......@@ -43,12 +44,12 @@ export const ChatRecordPath: OpenAPIPath = {
'/core/chat/record/getRecords_v2': {
post: {
summary: '根据锚点获取对话',
description: '根据锚点获取指定应用和会话的对话,支持多种鉴权模式',
description: '根据锚点获取指定会话的对话,支持多种鉴权模式',
tags: [DevApiTagsMap.chatRecord, SystemOpenApiTagMap.chat],
requestBody: {
content: {
'application/json': {
schema: GetRecordsV2BodySchema
schema: GetRecordsV2BodyRawSchema
}
}
},
......@@ -71,7 +72,7 @@ export const ChatRecordPath: OpenAPIPath = {
description: '根据 dataId 获取对话中某条 AI 回复的详细响应数据',
tags: [DevApiTagsMap.chatRecord, SystemOpenApiTagMap.chat],
requestParams: {
query: GetResDataQuerySchema
query: GetResDataQueryRawSchema
},
responses: {
200: {
......@@ -89,7 +90,7 @@ export const ChatRecordPath: OpenAPIPath = {
requestBody: {
content: {
'application/json': {
schema: GetQuoteBodySchema
schema: GetQuoteBodyRawSchema
}
}
},
......@@ -113,7 +114,7 @@ export const ChatRecordPath: OpenAPIPath = {
requestBody: {
content: {
'application/json': {
schema: GetCollectionQuoteBodySchema
schema: GetCollectionQuoteBodyRawSchema
}
}
},
......@@ -138,7 +139,7 @@ export const ChatRecordPath: OpenAPIPath = {
requestBody: {
content: {
'application/json': {
schema: DeleteChatRecordBodySchema
schema: DeleteChatRecordBodyRawSchema
}
}
},
......@@ -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 = [
tags: [ApiKeyTagNameMap[SystemOpenApiTagMap.appLog]]
},
{
name: '应用对话',
name: '对话',
tags: [
ApiKeyTagNameMap[SystemOpenApiTagMap.chatHistory],
ApiKeyTagNameMap[SystemOpenApiTagMap.chat],
......
......@@ -12,6 +12,7 @@ export type UsageSchemaType = {
source: `${UsageSourceEnum}`;
appId?: string;
skillId?: string;
datasetId?: string;
/** @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 {
import { differenceInHours } from 'date-fns';
import { S3Buckets } from '../../config/constants';
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 {
constructor() {
......@@ -39,7 +63,7 @@ export class S3ChatSource extends S3PrivateBucket {
extension: extension.replace('.', ''),
imageParsePrefix: `${pathname.replace(`/${S3Buckets.private}/`, '').replace(extension, '')}-parsed`
};
} catch (error) {
} catch {
return {
filename: '',
extension: '',
......@@ -63,9 +87,17 @@ export class S3ChatSource extends S3PrivateBucket {
}
async createUploadChatFileURL(params: CheckChatFileKeys) {
const { appId, chatId, uId, filename, expiredTime, maxFileSize, allowedExtensions } =
ChatFileUploadSchema.parse(params);
const { fileKey } = getFileS3Key.chat({ appId, chatId, uId, filename });
const {
sourceType,
sourceId,
chatId,
uId,
filename,
expiredTime,
maxFileSize,
allowedExtensions
} = ChatFileUploadSchema.parse(params);
const { fileKey } = getChatFileS3Key({ sourceType, sourceId, chatId, uId, filename });
return await this.createPresignedPutUrl(
{ rawKey: fileKey, filename },
{
......@@ -79,14 +111,20 @@ export class S3ChatSource extends S3PrivateBucket {
}
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];
await this.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;
}
......@@ -96,10 +134,11 @@ export class S3ChatSource extends S3PrivateBucket {
}
async uploadChatFile(params: UploadFileParams) {
const { appId, chatId, uId, filename, body, contentType, expiredTime } =
const { sourceType, sourceId, chatId, uId, filename, body, contentType, expiredTime } =
UploadChatFileSchema.parse(params);
const { fileKey } = getFileS3Key.chat({
appId,
const { fileKey } = getChatFileS3Key({
sourceType,
sourceId,
chatId,
uId,
filename
......@@ -114,9 +153,14 @@ export class S3ChatSource extends S3PrivateBucket {
});
}
getToolFilePrefix(params: { appId: string; chatId: string; uId: string }) {
const { appId, chatId, uId } = params;
return [S3Sources.chat, appId, uId, chatId].filter(Boolean).join('/');
getToolFilePrefix(params: {
sourceType: ChatS3SourceType;
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 { 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。
*
* 聊天文件 key 的授权边界由 appId 与 uid 决定。任何签名或读取前都应先解析
* 这些路径段并与已鉴权上下文绑定,避免只校验一个无关 app 后签发任意 object key。
* 新格式为 `chat/${sourceType}/${sourceId}/${uid}/${chatId}/${filename}`。
* legacy App 格式 `chat/${appId}/${uid}/${chatId}/${filename}` 继续按原始 key
* 读取,只在解析结果中归一化为 `sourceType=app` 供鉴权使用。
*/
export function parseChatFileS3Key(key: string): {
appId: string;
uid: string;
chatId: string;
filename: string;
} | null {
export function parseChatFileS3Key(key: string): ParsedChatFileS3Key | null {
if (!isS3ObjectKey(key, 'chat')) return null;
const [, appId, uid, chatId, ...filenameParts] = key.split('/');
const filename = filenameParts.join('/');
const [, firstSegment, secondSegment, thirdSegment, fourthSegment, ...filenameParts] =
key.split('/');
const sourceTypeResult = ChatS3SourceTypeSchema.safeParse(firstSegment);
const isSourceAwareKey = sourceTypeResult.success;
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 (!appId || !uid || !chatId || !filename) return null;
if (!sourceId || !uid || !chatId || !filename) return null;
return {
appId,
sourceType,
sourceId,
uid,
chatId,
filename
filename,
legacyAppKey: !isSourceAwareKey
};
}
/**
* 判断聊天文件 key 是否属于已鉴权的 app 与聊天用户。
* 判断聊天文件 key 是否属于已鉴权的 chat source 与聊天用户。
*/
export function isAuthorizedChatFileS3Key({
key,
appId,
uid
sourceType,
sourceId,
uid,
chatId
}: {
key: string;
appId: string;
sourceType: ChatS3SourceType;
sourceId: string;
uid: string;
chatId?: string;
}) {
const parsedKey = parseChatFileS3Key(key);
return (
!!parsedKey &&
String(parsedKey.appId) === String(appId) &&
String(parsedKey.uid) === String(uid)
parsedKey.sourceType === sourceType &&
String(parsedKey.sourceId) === String(sourceId) &&
String(parsedKey.uid) === String(uid) &&
(chatId === undefined || String(parsedKey.chatId) === String(chatId))
);
}
import z from 'zod';
import { ObjectIdSchema } from '@fastgpt/global/common/type/mongo';
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({
appId: ObjectIdSchema,
sourceType: ChatS3SourceTypeSchema,
sourceId: ObjectIdSchema,
chatId: z.string().nonempty(),
uId: z.string().nonempty(),
filename: z.string().nonempty(),
......@@ -11,17 +16,19 @@ export const ChatFileUploadSchema = z.object({
maxFileSize: z.number().positive().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({
appId: ObjectIdSchema,
sourceType: ChatS3SourceTypeSchema,
sourceId: ObjectIdSchema,
chatId: 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({
appId: ObjectIdSchema,
sourceType: ChatS3SourceTypeSchema,
sourceId: ObjectIdSchema,
chatId: z.string().nonempty(),
uId: z.string().nonempty(),
filename: UploadFileByBodySchema.shape.filename,
......@@ -30,4 +37,4 @@ export const UploadChatFileSchema = z.object({
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;
import type { SandboxInstanceSchemaType } from '../type';
import { SandboxStatusEnum, SandboxTypeEnum } from '@fastgpt/global/core/ai/sandbox/constants';
import { SandboxLimitSchema, SandboxProviderSchema } from '../type';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
/**
* sandbox 实例记录集合。
......@@ -22,8 +23,18 @@ const SandboxInstanceSchema = new Schema({
type: String,
required: true
},
// Chat 模式和 skill sandbox 都会复用这组根字段。
// @deprecated 仅保留给 4.15.0-beta6 一次性迁移脚本识别旧 sandbox 归属。
// 运行时业务必须使用 sourceType/sourceId。
appId: String,
sourceType: {
type: String,
enum: Object.values(ChatSourceTypeEnum),
required: true
},
sourceId: {
type: String,
required: true
},
userId: String,
chatId: String,
type: {
......@@ -58,6 +69,7 @@ const SandboxInstanceSchema = new Schema({
}
});
// @deprecated 旧 appId 维度索引仅用于迁移窗口和历史数据观察,新业务查询必须使用 sourceType/sourceId。
SandboxInstanceSchema.index(
{ provider: 1, appId: 1, userId: 1, chatId: 1 },
{
......@@ -73,6 +85,7 @@ SandboxInstanceSchema.index(
);
SandboxInstanceSchema.index({ status: 1, lastActiveAt: 1, 'metadata.archive.state': 1 });
SandboxInstanceSchema.index({ provider: 1, sandboxId: 1 }, { unique: true });
// @deprecated 旧 appId 维度索引仅用于迁移窗口和历史数据观察,新业务查询必须使用 sourceType/sourceId。
SandboxInstanceSchema.index(
{ appId: 1, chatId: 1 },
{
......@@ -84,8 +97,10 @@ SandboxInstanceSchema.index(
}
}
);
// @deprecated 旧 Skill Edit 归属索引仅用于迁移窗口,新业务不得写入或查询 metadata.skillId。
SandboxInstanceSchema.index({ 'metadata.skillId': 1 });
SandboxInstanceSchema.index({ type: 1, chatId: 1 });
SandboxInstanceSchema.index({ sourceType: 1, sourceId: 1, chatId: 1 });
/**
* 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';
import { createAgentSandboxPermissionDeniedError } from '../error';
import { checkTeamSandboxPermission } from '../../../../support/permission/teamLimit';
import { getSandboxRuntimeProfile } from './profile';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { getRunningSandboxId } from './id';
export type AgentSandboxRuntimeContext = {
sandboxClient: SandboxClient;
......@@ -15,16 +17,16 @@ export type AgentSandboxRuntimeContext = {
* skill 注入、entrypoint 和扫描由 skill runtime 自己处理。
*/
export async function prepareAgentSandboxRuntime({
appId,
sourceType,
sourceId,
userId,
chatId,
sandboxId,
teamId
}: {
appId: string;
sourceType: ChatSourceTypeEnum;
sourceId: string;
userId: string;
chatId: string;
sandboxId?: string;
teamId: string;
}): Promise<AgentSandboxRuntimeContext> {
try {
......@@ -33,9 +35,19 @@ export async function prepareAgentSandboxRuntime({
throw createAgentSandboxPermissionDeniedError();
}
const sandboxClient = await getSandboxClient(
sandboxId ? { sandboxId } : { appId, userId, chatId }
);
const sandboxId = getRunningSandboxId({
sourceType,
sourceId,
userId,
chatId
});
const sandboxClient = await getSandboxClient({
sandboxId,
sourceType,
sourceId,
userId: sourceType === ChatSourceTypeEnum.app ? userId : '',
chatId
});
const runtimeProfile = getSandboxRuntimeProfile();
return {
......
......@@ -2,6 +2,7 @@ import { getErrText } from '@fastgpt/global/common/error/utils';
import { batchRun } from '@fastgpt/global/common/system/utils';
import { subDays } from 'date-fns';
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 { getLogger, LogCategories } from '../../../../common/logger';
import { getS3SandboxSource } from '../../../../common/s3/sources/sandbox';
......@@ -596,7 +597,8 @@ async function createRestoreSandbox(params: {
export async function restoreArchivedSandboxBeforeUse(params: {
provider: SandboxProviderType;
sandboxId: string;
appId?: string;
sourceType: ChatSourceTypeEnum;
sourceId: string;
userId?: string;
chatId?: string;
vmConfig?: VolumeManagerResult | null;
......@@ -658,7 +660,8 @@ export async function restoreArchivedSandboxBeforeUse(params: {
const restoredStorage = params.storage ?? restoreTarget.storage;
const restoredDoc = await markSandboxRestored(restoringDoc, {
appId: params.appId,
sourceType: params.sourceType,
sourceId: params.sourceId,
userId: params.userId,
chatId: params.chatId,
storage: restoredStorage,
......
import { batchRun } from '@fastgpt/global/common/system/utils';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { getLogger, LogCategories } from '../../../../common/logger';
import {
deleteSandboxResourceRecord,
findSandboxResourcesByAppId,
findSandboxResourcesByChatIds,
findSandboxResourcesBySource,
findSandboxResourcesBySourceChatIds,
findSkillRelatedSandboxResources,
markSandboxResourceStopped,
type SandboxResourceRef
} from '../instance/repository';
......@@ -13,6 +15,19 @@ import { getS3SandboxSource } from '../../../../common/s3/sources/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 资源记录。
*
......@@ -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,
chatIds
}: {
appId: string;
chatIds: string[];
}) => {
const instances = await findSandboxResourcesByChatIds({ appId, chatIds });
if (!instances.length) return;
if (chatIds.length === 0) 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);
});
})
);
const instances = await findSandboxResourcesBySourceChatIds({
sourceType: ChatSourceTypeEnum.app,
sourceId: appId,
chatIds
});
await deleteSandboxResources(instances);
};
/**
* 删除某个 app 下的全部 sandbox 资源。
* 删除某个 App 下的全部 sandbox 资源。
*
* app 删除流程可能遇到多个 chat、edit-debug 或历史 provider 资源,因此统一从实例记录查询后逐条清理。
* 这是 App 删除场景的语义化入口;内部仍走 source-aware 查询,避免上层继续拼物理字段。
*/
export const deleteSandboxesByAppId = async (appId: string) => {
const instances = await findSandboxResourcesByAppId(appId);
if (!instances.length) return;
export const deleteAppSandboxes = async (appId: string) => {
const instances = await findSandboxResourcesBySource({
sourceType: ChatSourceTypeEnum.app,
sourceId: appId
});
await deleteSandboxResources(instances);
};
await Promise.allSettled(
instances.map(async (doc) => {
await deleteSandboxResource(doc).catch((err) => {
logger.error('Failed to delete sandbox', { sandboxId: doc.sandboxId, error: err });
});
})
);
/**
* 删除一批 Skill Edit 相关的全部 sandbox 资源。
*
* 只在 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 { getLogger, LogCategories } from '../../../../common/logger';
import {
......@@ -22,19 +22,18 @@ import {
const logger = getLogger(LogCategories.MODULE.AI.SANDBOX);
export type SandboxClientQuery =
| {
sandboxId: string;
}
| {
appId: string;
userId?: string;
chatId: string;
};
export type SandboxClientQuery = {
sandboxId: string;
sourceType: ChatSourceTypeEnum;
sourceId: string;
userId?: string;
chatId?: string;
};
type SandboxClientProps = {
sandboxId: string;
appId?: string;
sourceType: ChatSourceTypeEnum;
sourceId: string;
userId?: string;
chatId?: string;
};
......@@ -54,7 +53,8 @@ type SandboxClientOptions = {
* resource.ts 中的 stopSandboxResource/deleteSandboxResource,避免误触发 create/resume。
*/
export class SandboxClient {
private appId?: string;
private sourceType: ChatSourceTypeEnum;
private sourceId: string;
private userId?: string;
private chatId?: string;
private sandboxId: string;
......@@ -66,7 +66,8 @@ export class SandboxClient {
private readonly opts: SandboxClientOptions = {}
) {
this.sandboxId = props.sandboxId;
this.appId = props.appId;
this.sourceType = props.sourceType;
this.sourceId = props.sourceId;
this.userId = props.userId;
this.chatId = props.chatId;
......@@ -86,7 +87,8 @@ export class SandboxClient {
const instance = await upsertRunningSandboxInstance({
provider: this.providerName,
sandboxId: this.sandboxId,
appId: this.appId,
sourceType: this.sourceType,
sourceId: this.sourceId,
userId: this.userId,
chatId: this.chatId,
storage: this.opts?.vmConfig?.storage,
......@@ -168,23 +170,17 @@ export class SandboxClient {
}
const resolveSandboxClientProps = (props: SandboxClientQuery): SandboxClientProps => {
if ('sandboxId' in props) {
if (!props.sandboxId) {
throw new Error('sandboxId is required');
}
return {
sandboxId: props.sandboxId
};
if (!props.sandboxId) {
throw new Error('sandboxId is required');
}
if (!props.appId || !props.chatId) {
throw new Error('appId and chatId are required when sandboxId is not provided');
if (!props.sourceType || !props.sourceId) {
throw new Error('sourceType and sourceId are required');
}
const sandboxUserId = props.chatId === 'edit-debug' ? '' : (props.userId ?? '');
return {
sandboxId: generateSandboxId(props.appId, sandboxUserId, props.chatId),
appId: props.appId,
sandboxId: props.sandboxId,
sourceType: props.sourceType,
sourceId: props.sourceId,
userId: props.userId,
chatId: props.chatId
};
......@@ -193,7 +189,8 @@ const resolveSandboxClientProps = (props: SandboxClientQuery): SandboxClientProp
/**
* 获取当前业务会话的运行态 sandbox client。
*
* 传入 sandboxId 时直接使用指定实例;传入 app/user/chat 三元组时使用稳定规则生成 sandboxId。
* 调用方必须按 sourceType/sourceId 计算 sandboxId;这里不再接收 appId 等旧业务字段,
* 避免运行态写入或恢复时继续污染 sandbox 实例归属。
* 返回前会准备 volume 配置并确保 sandbox 可用。
*/
export const getSandboxClient = async (
......@@ -201,7 +198,7 @@ export const getSandboxClient = async (
opts: Omit<SandboxClientOptions, 'vmConfig'> = {}
) => {
const sandboxClientProps = resolveSandboxClientProps(props);
const { sandboxId, appId, userId, chatId } = sandboxClientProps;
const { sandboxId, userId, chatId } = sandboxClientProps;
const providerName = opts.providerName ?? getConfiguredSandboxProvider();
let vmConfig: VolumeManagerResult | undefined;
......@@ -215,7 +212,8 @@ export const getSandboxClient = async (
await restoreArchivedSandboxBeforeUse({
provider: providerName,
sandboxId,
appId,
sourceType: sandboxClientProps.sourceType,
sourceId: sandboxClientProps.sourceId,
userId,
chatId,
resourceLimit: opts.resourceLimits
......
......@@ -13,7 +13,7 @@ const SandboxGetFileUrlToolSchema = z.object({
export const sandboxGetFileUrlTool = defineTool({
zodSchema: SandboxGetFileUrlToolSchema,
execute: async ({ appId, userId, chatId, sandboxInstance, params }) => {
execute: async ({ sourceType, sourceId, userId, chatId, sandboxInstance, params }) => {
const result = await Promise.all(
params.paths.map(async (filePath) => {
const filename = path.basename(filePath);
......@@ -23,7 +23,8 @@ export const sandboxGetFileUrlTool = defineTool({
const chatBucket = getS3ChatSource();
const expiredTime = addHours(new Date(), 2);
const { key } = await chatBucket.uploadChatFile({
appId,
sourceType,
sourceId,
chatId,
uId: userId,
filename,
......
......@@ -13,6 +13,8 @@ import { parseJsonArgs } from '../../utils';
import { writeUrlFilesToSandbox } from '../service/file';
import { getSandboxRuntimeProfile } from '../runtime/profile';
import { preparePackageMirrors, prepareSandbox } from '../runtime/prepare';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { getRunningSandboxId } from '../runtime/id';
const ToolMap = {
...editFileToolMap,
......@@ -37,18 +39,18 @@ export type SandboxToolCallResult = {
* 未传入 client 时会按 app/user/chat 获取运行态 sandbox。
*/
export const runSandboxTools = async ({
appId,
sourceType,
sourceId,
userId,
chatId,
sandboxId,
toolName,
args,
sandboxClient
}: {
appId: string;
sourceType: ChatSourceTypeEnum;
sourceId: string;
userId: string;
chatId: string;
sandboxId?: string;
toolName: string;
args: string;
sandboxClient?: SandboxClient;
......@@ -77,11 +79,24 @@ export const runSandboxTools = async ({
};
}
const sandboxId = getRunningSandboxId({
sourceType,
sourceId,
userId,
chatId
});
const instance =
sandboxClient ??
(await getSandboxClient(sandboxId ? { sandboxId } : { appId, userId, chatId }));
(await getSandboxClient({
sandboxId,
sourceType,
sourceId,
userId: sourceType === ChatSourceTypeEnum.app ? userId : '',
chatId
}));
const result = await tool.execute({
appId,
sourceType,
sourceId,
userId,
chatId,
sandboxInstance: instance,
......@@ -103,19 +118,31 @@ export const runSandboxTools = async ({
* 即使没有文件也会返回 sandbox client,供 sandbox entrypoint 和后续工具调用复用。
*/
export const prepareSandboxToolRuntime = async ({
appId,
sourceType,
sourceId,
userId,
chatId,
sandboxId,
files
}: {
appId: string;
sourceType: ChatSourceTypeEnum;
sourceId: string;
userId: string;
chatId: string;
sandboxId?: 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();
await prepareSandbox(
{
......
import type { z } from 'zod';
import type { SandboxClient } from '../service/runtime';
import type { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
type ToolExecuteContext<P> = {
appId: string;
sourceType: ChatSourceTypeEnum;
sourceId: string;
userId: string;
chatId: string;
sandboxInstance: SandboxClient;
......
import z from 'zod';
import { SandboxStatusEnum, SandboxTypeEnum } from '@fastgpt/global/core/ai/sandbox/constants';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
// ---- 沙盒实例 DB 类型 ----
export const SandboxProviderSchema = z.enum(['sealosdevbox', 'opensandbox', 'e2b']);
......@@ -47,6 +48,7 @@ export const SandboxMetadataSchema = z.object({
})
.optional(),
/** @deprecated 旧 Skill Edit 归属字段,仅迁移脚本/历史数据观察使用。 */
skillId: z.string().optional(),
sessionId: z.string().optional(),
skillIds: z.array(z.string()).optional(),
......@@ -60,7 +62,10 @@ export type SandboxMetadataType = z.infer<typeof SandboxMetadataSchema>;
export const SandboxInstanceZodSchema = z.object({
_id: z.string(),
sandboxId: z.string(),
/** @deprecated 旧 sandbox 归属字段,仅迁移脚本/历史数据观察使用。 */
appId: z.string().nullish(),
sourceType: z.enum(ChatSourceTypeEnum),
sourceId: z.string(),
userId: z.string().nullish(),
chatId: z.string().nullish(),
type: z.enum(SandboxTypeEnum).nullish(),
......
......@@ -5,7 +5,6 @@ import {
} from '@fastgpt/global/core/workflow/runtime/constants';
import { UsageSourceEnum } from '@fastgpt/global/support/wallet/usage/constants';
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 { concatHistories, removeEmptyUserInput } from '@fastgpt/global/core/chat/utils';
import { ReadPermissionVal } from '@fastgpt/global/support/permission/constant';
......@@ -16,12 +15,10 @@ import {
import {
ChatGenerateStatusEnum,
ChatRoleEnum,
ChatSourceTypeEnum,
ChatSourceEnum
} from '@fastgpt/global/core/chat/constants';
import {
SkillDebugChatBodySchema,
type SkillDebugChatBody
} from '@fastgpt/global/core/ai/skill/api';
import { SkillDebugChatBodySchema } from '@fastgpt/global/core/ai/skill/api';
import { SandboxTypeEnum } from '@fastgpt/global/core/ai/sandbox/constants';
import { UserError } from '@fastgpt/global/common/error/utils';
import { getNanoid } from '@fastgpt/global/common/string/tools';
......@@ -36,7 +33,7 @@ import { getRunningUserInfoByTmbId } from '../../../../support/user/team/utils';
import { formatModelChars2Points } from '../../../../support/wallet/usage/utils';
import { getDefaultLLMModel } from '../../model';
import { getEditDebugSandboxId } from '../edit/config';
import { findSandboxInstanceBySandboxId } from '../../sandbox/instance/repository';
import { findSandboxInstanceBySandboxIdAndSource } from '../../sandbox/instance/repository';
import { getSandboxProviderConfig } from '../../sandbox/provider/config';
import { dispatchWorkFlow } from '../../../workflow/dispatch';
import { WORKFLOW_MAX_RUN_TIMES } from '../../../workflow/constants';
......@@ -58,10 +55,6 @@ import type { AgentSandboxPrepareAction } from '../../../workflow/dispatch/ai/ag
const logger = getLogger(LogCategories.MODULE.AGENT_SKILLS);
type SkillDebugChatProps = Omit<SkillDebugChatBody, 'messages'> & {
messages: ChatCompletionMessageParam[];
};
/**
* 处理 Skill 调试对话的共享主流程。
*
......@@ -79,7 +72,8 @@ export async function handleSkillDebugChat(
let streamResponseContext: SkillDebugStreamResponseContext | undefined;
const roundState = {
preparedRound: undefined as PreChatRoundResult | undefined,
appId: '',
sourceType: undefined as ChatSourceTypeEnum | undefined,
sourceId: '',
chatId: '',
responseChatItemId: '',
finalized: false
......@@ -96,8 +90,12 @@ export async function handleSkillDebugChat(
} = parseApiInput({
req,
bodySchema: SkillDebugChatBodySchema
}).body as SkillDebugChatProps;
}).body;
skillId = parsedSkillId;
const chatSource = {
sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId
};
if (!Array.isArray(messages) || messages.length === 0) {
throw new UserError('messages is required');
......@@ -120,10 +118,11 @@ export async function handleSkillDebugChat(
const providerConfig = getSandboxProviderConfig();
const editDebugSandboxId = getEditDebugSandboxId(skillId);
const sandboxInstance = await findSandboxInstanceBySandboxId({
const sandboxInstance = await findSandboxInstanceBySandboxIdAndSource({
provider: providerConfig.provider,
sandboxId: editDebugSandboxId,
appId: skillId,
sourceType: chatSource.sourceType,
sourceId: chatSource.sourceId,
type: SandboxTypeEnum.editDebug
});
if (!sandboxInstance) {
......@@ -140,7 +139,7 @@ export async function handleSkillDebugChat(
}
const { histories } = await getChatItems({
appId: skillId,
...chatSource,
chatId,
offset: 0,
limit: 20,
......@@ -150,7 +149,7 @@ export async function handleSkillDebugChat(
const newHistories = concatHistories(histories, chatMessages);
const interactive = getLastInteractiveValue(newHistories);
const preparedRound = await preChatRound({
appId: skillId,
...chatSource,
chatId,
teamId,
tmbId,
......@@ -162,7 +161,8 @@ export async function handleSkillDebugChat(
const runningChatId = preparedRound.chatId;
const finalResponseChatItemId = preparedRound.responseChatItemId;
roundState.preparedRound = preparedRound;
roundState.appId = skillId;
roundState.sourceType = chatSource.sourceType;
roundState.sourceId = chatSource.sourceId;
roundState.chatId = runningChatId;
roundState.responseChatItemId = finalResponseChatItemId;
......@@ -178,7 +178,8 @@ export async function handleSkillDebugChat(
stream: true,
detail: true,
teamId,
appId: skillId,
sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId,
chatId: runningChatId,
responseId: runningChatId,
showNodeStatus: true
......@@ -202,11 +203,11 @@ export async function handleSkillDebugChat(
usageSource: UsageSourceEnum.fastgpt,
uid: tmbId,
runningAppInfo: {
id: skillId,
sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId,
name: skill.name,
teamId,
tmbId,
sandboxId: editDebugSandboxId
tmbId
},
runningUserInfo: await getRunningUserInfoByTmbId(tmbId),
chatId: runningChatId,
......@@ -282,8 +283,8 @@ export async function handleSkillDebugChat(
};
const saveParams: SaveChatProps = {
...chatSource,
chatId: runningChatId,
appId: skillId,
teamId,
tmbId,
nodes: [],
......@@ -310,7 +311,7 @@ export async function handleSkillDebugChat(
if (!preparedRound.shouldFinalizePreparedRound && preparedRound.shouldPersistChatRound) {
await updateChatGenerateStatus({
appId: skillId,
...chatSource,
chatId: runningChatId,
status: ChatGenerateStatusEnum.done
});
......@@ -327,19 +328,22 @@ export async function handleSkillDebugChat(
if (
!roundState.finalized &&
preparedRound?.shouldPersistChatRound &&
roundState.appId &&
roundState.sourceType &&
roundState.sourceId &&
roundState.chatId
) {
if (preparedRound.shouldFinalizePreparedRound) {
await failChatRound({
appId: roundState.appId,
sourceType: roundState.sourceType,
sourceId: roundState.sourceId,
chatId: roundState.chatId,
responseChatItemId: roundState.responseChatItemId,
error: err
});
} else {
await updateChatGenerateStatus({
appId: roundState.appId,
sourceType: roundState.sourceType,
sourceId: roundState.sourceId,
chatId: roundState.chatId,
status: ChatGenerateStatusEnum.error
});
......
......@@ -2,6 +2,7 @@ import type { NextApiRequest, NextApiResponse } from 'next';
import { getSseErrorResponse } from '../../../../common/response';
import { clearCookie } from '../../../../support/permission/auth/common';
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 { getWorkflowResponseWrite } from '../../../workflow/dispatch/utils';
......@@ -11,7 +12,8 @@ type CreateSkillDebugStreamResponseContextParams = {
stream: boolean;
detail: boolean;
teamId: string;
appId: string;
sourceType: ChatSourceTypeEnum;
sourceId: string;
chatId: string;
responseId?: string;
showNodeStatus?: boolean;
......@@ -29,7 +31,8 @@ export const createSkillDebugStreamResponseContext = async ({
stream,
detail,
teamId,
appId,
sourceType,
sourceId,
chatId,
responseId,
showNodeStatus = true
......@@ -38,7 +41,8 @@ export const createSkillDebugStreamResponseContext = async ({
? await getStreamResumeMirror({
resumeRequestHeaderValue: req.headers?.[STREAM_RESUME_REQUEST_HEADER],
teamId,
appId,
sourceType,
sourceId,
chatId
})
: undefined;
......
......@@ -11,8 +11,10 @@ import { mongoSessionRun } from '../../../../common/mongo/sessionRun';
import { deleteSkillAllPackages } from '../package';
import { MongoAgentSkills } from '../model/schema';
import { MongoAgentSkillsVersion } from '../version/schema';
import { deleteSkillRelatedSandboxes } from '../sandbox/controller';
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);
......@@ -37,7 +39,17 @@ const deleteSkillExternalData = async ({
const nonFolderSkillIds = nonFolderSkills.map((skill) => String(skill._id));
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';
import { updateCurrentVersion } from '../manage';
import { removeSkillPackageTTL, uploadSkillPackage } from '../package';
import { packageSkillInSandbox } from './sandbox';
import { EDIT_DEBUG_SANDBOX_CHAT_ID } from './config';
import { getEditDebugSandboxId } from './config';
import { createVersion } from '../version';
import { getSandboxRuntimeProfile } from '../../sandbox/runtime/profile';
import { getSandboxProviderConfig } from '../../sandbox/provider/config';
import {
findSandboxInstanceByAppChatType,
findSandboxInstanceBySandboxId,
updateSandboxInstanceRecordBySandboxId
} from '../../sandbox/instance/repository';
import { MongoAgentSkills } from '../model/schema';
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 { UserError } from '@fastgpt/global/common/error/utils';
import type { SaveDeploySkillResponse } from '@fastgpt/global/core/ai/skill/api';
......@@ -41,10 +42,9 @@ export async function saveDeploySkillFromSandbox({
versionName
}: SaveDeploySkillFromSandboxParams): Promise<SaveDeploySkillResponse> {
const providerConfig = getSandboxProviderConfig();
const sandboxInfo = await findSandboxInstanceByAppChatType({
const sandboxInfo = await findSandboxInstanceBySandboxId({
provider: providerConfig.provider,
appId: skillId,
chatId: EDIT_DEBUG_SANDBOX_CHAT_ID,
sandboxId: getEditDebugSandboxId(skillId),
status: SandboxStatusEnum.running,
type: SandboxTypeEnum.editDebug
});
......@@ -126,6 +126,8 @@ export async function saveDeploySkillFromSandbox({
await updateSandboxInstanceRecordBySandboxId({
provider: providerConfig.provider,
sandboxId: sandboxInfo.sandboxId,
sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId,
metadata: {
...(sandboxInfo.metadata || {}),
versionId
......
......@@ -18,6 +18,7 @@ import {
import { getSandboxRuntimeProfile } from '../../sandbox/runtime/profile';
import type { SandboxImageConfigType } from '@fastgpt/global/core/ai/skill/type';
import { SandboxTypeEnum } from '@fastgpt/global/core/ai/sandbox/constants';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import {
connectReadySandboxByInstance,
connectToSandbox,
......@@ -31,8 +32,8 @@ import { deleteSandboxResource } from '../../sandbox/service/resource';
import {
countRunningSandboxInstancesByType,
deleteSandboxInstanceRecord,
findSandboxInstanceByAppChatType,
findSandboxResourcesByAppChatTypeExcludeProvider,
findSandboxInstanceBySandboxId,
findSandboxResourcesBySourceChatTypeExcludeProvider,
migrateArchivedSandboxInstanceRecord,
updateSandboxInstanceRecordBySandboxId
} from '../../sandbox/instance/repository';
......@@ -156,10 +157,9 @@ export async function createEditDebugSandbox(
* 只有这个旧 wrapper,启动时顺手展开一层,避免每次加载继续制造
* skills/<edit-dir>/<real-skill>/SKILL.md 这种嵌套结构。
*/
const existingInstance = await findSandboxInstanceByAppChatType({
const existingInstance = await findSandboxInstanceBySandboxId({
provider: providerConfig.provider,
appId: skillId,
chatId: EDIT_DEBUG_SANDBOX_CHAT_ID,
sandboxId: sessionId,
type: SandboxTypeEnum.editDebug
});
......@@ -293,7 +293,8 @@ export async function createEditDebugSandbox(
await updateSandboxInstanceRecordBySandboxId({
provider: providerConfig.provider,
sandboxId: instance.sandboxId,
appId: skillId,
sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId,
userId: '',
chatId: EDIT_DEBUG_SANDBOX_CHAT_ID,
metadata: preparedContext.workspaceHasContent
......@@ -375,7 +376,8 @@ export async function createEditDebugSandbox(
await updateSandboxInstanceRecordBySandboxId({
provider: providerConfig.provider,
sandboxId: instance.sandboxId,
appId: skillId,
sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId,
userId: '',
chatId: EDIT_DEBUG_SANDBOX_CHAT_ID,
metadata: newMetadata
......@@ -443,9 +445,10 @@ export async function createEditDebugSandbox(
});
}
const staleProviderInstances = await findSandboxResourcesByAppChatTypeExcludeProvider({
const staleProviderInstances = await findSandboxResourcesBySourceChatTypeExcludeProvider({
provider: providerConfig.provider,
appId: skillId,
sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId,
chatId: EDIT_DEBUG_SANDBOX_CHAT_ID,
type: SandboxTypeEnum.editDebug
});
......@@ -471,7 +474,8 @@ export async function createEditDebugSandbox(
const migratedInstance = await migrateArchivedSandboxInstanceRecord({
source: instance,
provider: providerConfig.provider,
appId: skillId,
sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId,
userId: '',
chatId: EDIT_DEBUG_SANDBOX_CHAT_ID,
type: SandboxTypeEnum.editDebug
......@@ -511,7 +515,9 @@ export async function createEditDebugSandbox(
const createRuntimeSandboxClient = () =>
getSandboxClient(
{
appId: skillId,
sandboxId: sessionId,
sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId,
userId: '',
chatId: EDIT_DEBUG_SANDBOX_CHAT_ID
},
......@@ -601,14 +607,14 @@ export async function createEditDebugSandbox(
const newSandboxDoc = await updateSandboxInstanceRecordBySandboxId({
provider: providerConfig.provider,
sandboxId: sessionId,
appId: skillId,
sourceType: ChatSourceTypeEnum.skillEdit,
sourceId: skillId,
userId: '',
chatId: EDIT_DEBUG_SANDBOX_CHAT_ID,
type: SandboxTypeEnum.editDebug,
metadata: {
teamId,
tmbId,
skillId,
sessionId,
...(sandboxInfo.image ? { image: sandboxInfo.image } : {}),
providerCreatedAt: sandboxInfo.createdAt,
......
......@@ -2,8 +2,7 @@ import type { SandboxInstanceSchemaType } from '@fastgpt/global/core/ai/skill/ty
import { getSandboxProviderConfig } from '../../sandbox/provider/config';
import {
findSandboxInstanceBySandboxIdAndTeam,
findSandboxResourceBySandboxIdAndTeam,
findSkillRelatedSandboxResources
findSandboxResourceBySandboxIdAndTeam
} from '../../sandbox/instance/repository';
import { deleteSandboxResource } from '../../sandbox/service/resource';
import { getLogger, LogCategories } from '../../../../common/logger';
......@@ -67,26 +66,3 @@ export async function deleteSandbox(params: DeleteSandboxParams): Promise<void>
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'
import { SystemToolSecretInputTypeEnum } from '@fastgpt/global/core/app/tool/systemTool/constants';
import { MongoEvaluation } from './evaluation/evalSchema';
import { removeEvaluationJob } from './evaluation/mq';
import { MongoChatItem } from '../chat/chatItemSchema';
import { MongoChat } from '../chat/chatSchema';
import { MongoOutLink } from '../../support/outLink/schema';
import { MongoOpenApi } from '../../support/openapi/schema';
import { MongoAppVersion } from './version/schema';
......@@ -26,15 +24,13 @@ import {
} from '@fastgpt/global/support/permission/constant';
import { removeImageByPath } from '../../common/file/image/controller';
import { MongoAppLogKeys } from './logs/logkeysSchema';
import { MongoChatItemResponse } from '../chat/chatItemResponseSchema';
import { getS3ChatSource } from '../../common/s3/sources/chat';
import { MongoAppChatLog } from './logs/chatLogsSchema';
import { MongoAppRegistration } from '../../support/appRegistration/schema';
import { MongoMcpKey } from '../../support/mcp/schema';
import { MongoAppRecord } from './record/schema';
import { mongoSessionRun } from '../../common/mongo/sessionRun';
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 {
SelectedAgentSkillItemTypeSchema,
......@@ -43,6 +39,8 @@ import {
import z from 'zod';
import { nodeInputIsReference } from '@fastgpt/global/core/workflow/utils';
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);
......@@ -246,23 +244,13 @@ export const deleteAppDataProcessor = async ({
// 1. 删除应用头像
await removeImageByPath(app.avatar);
// 2. 删除聊天记录和S3文件
// 删除沙盒实例
{
// 对话生成的
await deleteSandboxesByAppId(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 });
// 2. 删除聊天记录、S3 文件和 sandbox 资源。App logs 属于应用统计域,单独清理。
await deleteAppSandboxes(appId);
await deleteChatResourcesBySource({
sourceType: ChatSourceTypeEnum.app,
sourceId: appId
});
await MongoAppChatLog.deleteMany({ teamId, appId });
await MongoChatItemResponse.deleteMany({ appId });
await MongoChatItem.deleteMany({ appId });
await MongoChat.deleteMany({ appId });
// 3. 删除应用相关数据(使用事务)
{
......
......@@ -3,10 +3,10 @@
* Used by stream resume, sidebar polling, and stale-generating correction paths.
*/
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 = {
appId: string;
type EnsureGenerateChatParams = ChatSourceParams & {
chatId: string;
teamId: string;
tmbId: string;
......@@ -18,11 +18,18 @@ type EnsureGenerateChatParams = {
const buildGeneratingChatUpdate = (params: EnsureGenerateChatParams) => {
const now = new Date();
const { sourceType, sourceId, ...chatFields } = params;
const chatSource = {
sourceType,
sourceId
};
return {
now,
chatSource,
$set: {
...params,
...chatFields,
...buildChatSourceWriteFields(chatSource),
updateTime: now,
hasBeenRead: false,
chatGenerateStatus: ChatGenerateStatusEnum.generating
......@@ -34,11 +41,11 @@ const buildGeneratingChatUpdate = (params: EnsureGenerateChatParams) => {
};
export const ensureGenerateChat = async (params: EnsureGenerateChatParams) => {
const { $set, $setOnInsert } = buildGeneratingChatUpdate(params);
const { $set, $setOnInsert, chatSource } = buildGeneratingChatUpdate(params);
await MongoChat.updateOne(
{
appId: params.appId,
...buildChatSourceQuery(chatSource),
chatId: params.chatId
},
{
......@@ -54,21 +61,21 @@ export const ensureGenerateChat = async (params: EnsureGenerateChatParams) => {
/**
* 尝试占用一次会话生成槽。
*
* 同一个 `appId/chatId` 只允许一个请求进入生成中状态;已有 generating 记录时返回 false,
* 同一个 `sourceType/sourceId/chatId` 只允许一个请求进入生成中状态;已有 generating 记录时返回 false,
* 由 API 层转换为“当前会话正在运行”的错误。
*
* 这里用“条件匹配 + upsert + 唯一索引”实现无副作用抢占:只有非 generating
* 记录会被更新为 generating;如果已有 generating 记录,查询不会命中,upsert 会因
* `{ appId, chatId }` 唯一索引报 11000,再转换为 false。这样被拒绝的并发请求不会刷新
* chat source 唯一索引报 11000,再转换为 false。这样被拒绝的并发请求不会刷新
* updateTime 或覆盖 source/sourceName。
*/
export const tryStartGenerateChat = async (params: EnsureGenerateChatParams) => {
const { $set, $setOnInsert } = buildGeneratingChatUpdate(params);
const { $set, $setOnInsert, chatSource } = buildGeneratingChatUpdate(params);
try {
await MongoChat.findOneAndUpdate(
{
appId: params.appId,
...buildChatSourceQuery(chatSource),
chatId: params.chatId,
chatGenerateStatus: { $ne: ChatGenerateStatusEnum.generating }
},
......@@ -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;
/** 若传入则覆盖;否则在 done/error 时默认未读(前台看完可再调 markRead) */
hasBeenRead?: boolean;
};
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 $set: Record<string, unknown> = {
chatGenerateStatus: status,
......@@ -108,5 +122,5 @@ export const updateChatGenerateStatus = async (params: UpdateChatGenerateStatusP
} else if (status === ChatGenerateStatusEnum.done || status === ChatGenerateStatusEnum.error) {
$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'
import { TeamCollectionName } from '@fastgpt/global/support/user/team/constant';
import { AppCollectionName } from '../app/schema';
import { ChatItemResponseCollectionName } from './constants';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
const ChatItemResponseSchema = new Schema({
teamId: {
......@@ -11,6 +12,10 @@ const ChatItemResponseSchema = new Schema({
ref: TeamCollectionName,
required: true
},
sourceType: {
type: String,
enum: Object.values(ChatSourceTypeEnum)
},
appId: {
type: Schema.Types.ObjectId,
ref: AppCollectionName,
......@@ -37,6 +42,13 @@ const ChatItemResponseSchema = new Schema({
// 按 chat item 拉取完整 nodeResponse rows;复合索引包含 _id,避免详情读取时额外排序。
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
ChatItemResponseSchema.index({ teamId: 1, time: -1 });
......
import { connectionMongo, getMongoModel } from '../../common/mongo';
const { Schema } = connectionMongo;
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 {
TeamCollectionName,
......@@ -31,6 +31,10 @@ const ChatItemSchema = new Schema({
type: String,
require: true
},
sourceType: {
type: String,
enum: Object.values(ChatSourceTypeEnum)
},
dataId: {
type: String,
require: true,
......@@ -99,12 +103,16 @@ const ChatItemSchema = new Schema({
close custom feedback;
*/
ChatItemSchema.index({ appId: 1, chatId: 1, dataId: 1 });
ChatItemSchema.index({ sourceType: 1, appId: 1, chatId: 1, dataId: 1 });
// Get histories
ChatItemSchema.index({ appId: 1, chatId: 1, deleteTime: 1 });
ChatItemSchema.index({ sourceType: 1, appId: 1, chatId: 1, deleteTime: 1 });
// get chatitem list,Anchor filter
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
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>(
ChatItemCollectionName,
......
......@@ -2,7 +2,11 @@ import { connectionMongo, getMongoModel } from '../../common/mongo';
import { getLogger, LogCategories } from '../../common/logger';
const { Schema } = connectionMongo;
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 {
TeamCollectionName,
TeamMemberCollectionName
......@@ -26,6 +30,11 @@ const ChatSchema = new Schema({
ref: TeamMemberCollectionName,
required: true
},
sourceType: {
type: String,
enum: Object.values(ChatSourceTypeEnum)
},
// 历史物理字段名,业务语义为 sourceId;App 场景才是真实 appId。
appId: {
type: Schema.Types.ObjectId,
ref: AppCollectionName,
......@@ -130,6 +139,10 @@ try {
ChatSchema.index({ chatId: 1 });
// Delete by appid; init chat; update chat; auth chat;
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
ChatSchema.index(
......@@ -143,6 +156,14 @@ try {
// get user history
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
ChatSchema.index(
{ shareId: 1, outLinkUid: 1, updateTime: -1 },
......
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 { MongoChat } from './chatSchema';
import {
......@@ -16,6 +16,7 @@ export const STALE_GENERATING_CHAT_MINUTES = 30;
type GeneratingChat = {
_id: unknown;
teamId: { toString: () => string } | string;
sourceType?: ChatSourceTypeEnum;
appId: { toString: () => string } | string;
chatId: string;
updateTime?: Date;
......@@ -67,6 +68,7 @@ export const cleanStaleGeneratingChats = async (): Promise<CleanStaleGeneratingC
{
_id: 1,
teamId: 1,
sourceType: 1,
appId: 1,
chatId: 1,
updateTime: 1
......@@ -92,7 +94,8 @@ export const cleanStaleGeneratingChats = async (): Promise<CleanStaleGeneratingC
try {
const activeState = await getStreamResumeActiveState({
teamId: chat.teamId.toString(),
appId: chat.appId.toString(),
sourceType: chat.sourceType ?? ChatSourceTypeEnum.app,
sourceId: chat.appId.toString(),
chatId: chat.chatId
});
......
......@@ -4,10 +4,15 @@ import { MongoChat } from './chatSchema';
import { ChatRoleEnum } from '@fastgpt/global/core/chat/constants';
import { MongoChatItemResponse } from './chatItemResponseSchema';
import type { ClientSession } from '../../common/mongo';
import { Types } from '../../common/mongo';
import { UserError } from '@fastgpt/global/common/error/utils';
import { getLogger, LogCategories } from '../../common/logger';
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);
......@@ -35,7 +40,8 @@ const defaultNodeResponsePreviewProjection = {
export async function getChatItems({
includeDeleted = false,
appId,
sourceType,
sourceId,
chatId,
field,
limit,
......@@ -48,7 +54,8 @@ export async function getChatItems({
nextId
}: {
includeDeleted?: boolean;
appId: string;
sourceType: ChatSourceTypeEnum;
sourceId: string;
chatId?: string;
field: string;
limit: number;
......@@ -69,10 +76,13 @@ export async function getChatItems({
return { histories: [], total: 0, hasMorePrev: false, hasMoreNext: false };
}
const chatSource = { sourceType, sourceId };
const shouldReadNodeResponse = nodeResponseMode || 'none';
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 () => {
// Mode 1: offset pagination (original logic)
......@@ -198,7 +208,7 @@ export async function getChatItems({
const isPreview = shouldReadNodeResponse === 'preview';
const rows = await MongoChatItemResponse.find(
{
appId,
...buildChatSourceQuery(chatSource),
chatId,
chatItemDataId: { $in: chatItemDataIds }
},
......@@ -245,26 +255,32 @@ export async function getChatItems({
* Update feedback count statistics for a chat in 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 session - Optional MongoDB session for transaction support
*/
export async function updateChatFeedbackCount({
appId,
sourceType,
sourceId,
chatId,
session
}: {
appId: string;
sourceType: ChatSourceTypeEnum;
sourceId: string;
chatId: string;
session?: ClientSession;
}): Promise<void> {
const chatSource = { sourceType, sourceId };
const sourceQuery = buildChatSourceQuery(chatSource);
const sourceAggregateMatch = buildChatSourceAggregateMatch(chatSource);
try {
// Aggregate feedback statistics from chatItems
const stats = await MongoChatItem.aggregate(
[
{
$match: {
appId: new Types.ObjectId(appId),
...sourceAggregateMatch,
chatId,
obj: ChatRoleEnum.AI
}
......@@ -371,7 +387,7 @@ export async function updateChatFeedbackCount({
// Update Chat table with aggregated statistics and boolean flags
await MongoChat.updateOne(
{
appId,
...sourceQuery,
chatId
},
updateQuery,
......@@ -381,7 +397,8 @@ export async function updateChatFeedbackCount({
);
logger.debug('Chat feedback count updated', {
appId,
sourceType: chatSource.sourceType,
sourceId: chatSource.sourceId,
chatId,
stats: feedbackStats,
hasGoodFeedback,
......@@ -390,7 +407,12 @@ export async function updateChatFeedbackCount({
hasUnreadBadFeedback
});
} 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;
}
}
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'
import type { WorkflowInteractiveResponseType } from '@fastgpt/global/core/workflow/template/system/interactive/type';
import type { UserChatItemType } from '@fastgpt/global/core/chat/type';
import { MongoChatItem } from './chatItemSchema';
import { buildChatSourceQuery, type ChatSourceParams } from './source';
/**
* 解析本轮 workflow 写入 nodeResponse 时应该归属的 AI chat item dataId。
......@@ -29,13 +30,13 @@ export const getInteractiveResponseStatus = ({
};
export const resolveResponseChatItemId = async ({
appId,
sourceType,
sourceId,
chatId,
responseChatItemId,
interactive,
userContent
}: {
appId: string;
}: ChatSourceParams & {
chatId?: string;
responseChatItemId: string;
interactive?: WorkflowInteractiveResponseType;
......@@ -48,7 +49,7 @@ export const resolveResponseChatItemId = async ({
const chatItem = await MongoChatItem.findOne(
{
appId,
...buildChatSourceQuery({ sourceType, sourceId }),
chatId,
obj: ChatRoleEnum.AI
},
......
......@@ -13,6 +13,7 @@ import {
import { MongoChatItemResponse } from './chatItemResponseSchema';
import { getLogger, LogCategories } from '../../common/logger';
import { writePrimary } from '../../common/mongo/utils';
import { buildChatSourceQuery, buildChatSourceWriteFields, type ChatSourceParams } from './source';
const logger = getLogger(LogCategories.MODULE.CHAT.HISTORY);
// 常规写入失败后最多重试 3 次;仍失败再进入瘦身 fallback,避免异常详情阻断主流程。
......@@ -20,17 +21,9 @@ const NODE_RESPONSE_WRITE_RETRY_TIMES = 3;
type ChatItemResponseBase = Pick<
ChatItemResponseSchemaType,
'teamId' | 'appId' | 'chatId' | 'chatItemDataId'
>;
export type ChatItemResponseStorageRow = ChatItemResponseBase & {
/**
* 完整 nodeResponse 数据。身份字段也放在 data 内:
* - data.id: 本次节点响应实例 ID。
* - data.parentId: 父响应实例 ID,用于详情读取时重新拼 childrenResponses。
*/
data: ChatHistoryItemResType;
};
'teamId' | 'chatId' | 'chatItemDataId'
> &
ChatSourceParams;
/**
* saveChat 仍需要同步得到本轮引用、错误数和根节点费用。
......@@ -53,6 +46,21 @@ type CreateRowsParams = ChatItemResponseBase & {
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。
* 这里刻意不暴露 Mongoose Model 全量类型,降低单元测试和业务代码耦合。
......@@ -291,6 +299,13 @@ export const createChatItemResponseRows = ({
nodeResponses = [],
...base
}: 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) => {
const id = getResponseId(response);
const currentParentId = getParentId(response);
......@@ -305,7 +320,8 @@ export const createChatItemResponseRows = ({
});
return {
...base,
...restBase,
...sourceWriteFields,
data
};
});
......@@ -338,18 +354,21 @@ export const composeChatItemResponseData = ({ rows = [] }: { rows?: ChatItemResp
composeNodeResponseDetail(rows);
export const getChatItemResponseData = async ({
appId,
sourceType,
sourceId,
chatId,
chatItemDataId,
fallbackResponseData
}: {
appId: string;
sourceType: ChatSourceParams['sourceType'];
sourceId: string;
chatId: string;
chatItemDataId: string;
fallbackResponseData?: ChatHistoryItemResType[];
}) => {
const rows = await getChatItemResponseRows({
appId,
sourceType,
sourceId,
chatId,
chatItemDataId
});
......@@ -362,23 +381,30 @@ export const getChatItemResponseData = async ({
};
export const getChatItemResponseRows = async ({
appId,
sourceType,
sourceId,
chatId,
chatItemDataId
}: {
appId: string;
sourceType: ChatSourceParams['sourceType'];
sourceId: string;
chatId: string;
chatItemDataId: string;
}) =>
// _id 顺序就是 writer create 顺序;详情拼树后,同级 children 也按运行时写入顺序展示。
MongoChatItemResponse.find(
{ appId, chatId, chatItemDataId },
{
data: 1
}
)
.sort({ _id: 1 })
.lean();
}) => {
const chatSource = { sourceType, sourceId };
return (
// _id 顺序就是 writer create 顺序;详情拼树后,同级 children 也按运行时写入顺序展示。
MongoChatItemResponse.find(
{ ...buildChatSourceQuery(chatSource), chatId, chatItemDataId },
{
data: 1
}
)
.sort({ _id: 1 })
.lean()
);
};
/**
* 请求级 nodeResponse 写入器。
......
......@@ -9,6 +9,8 @@ import {
import { getLogger, LogCategories } from '../../common/logger';
import { serviceEnv } from '../../env';
import { getChatItemResponseData } from './nodeResponseStorage';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { buildChatSourceQuery } from './source';
const logger = getLogger(LogCategories.MODULE.CHAT.RECORD);
......@@ -91,7 +93,10 @@ const pushChatLogInternal = async ({
return;
}
const chat = await MongoChat.findOne({ chatId }).lean();
const chat = await MongoChat.findOne({
...buildChatSourceQuery({ sourceType: ChatSourceTypeEnum.app, sourceId: appId }),
chatId
}).lean();
if (!chat) {
return;
......@@ -157,7 +162,8 @@ ${JSON.stringify(item.interactive, null, 2)}
}
const responseData = await getChatItemResponseData({
appId,
sourceType: ChatSourceTypeEnum.app,
sourceId: appId,
chatId,
chatItemDataId: chatItemAi.dataId
});
......
......@@ -2,6 +2,7 @@ import { serviceEnv } from '../../env';
import { getLogger, LogCategories } from '../../common/logger';
import { FASTGPT_REDIS_PREFIX, getGlobalRedisConnection } from '../../common/redis';
import type { NextApiResponse } from 'next';
import type { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import { StreamResumeUnavailableReasonEnum } from '@fastgpt/global/core/workflow/runtime/constants';
const logger = getLogger(LogCategories.MODULE.CHAT.RESUME);
......@@ -38,18 +39,20 @@ let lastLoggedMemoryPressureState: boolean | undefined;
type StreamResumeRedisKeysParams = {
teamId: string;
appId: string;
sourceType: ChatSourceTypeEnum;
sourceId: string;
chatId: string;
};
export const getStreamResumeRedisKeys = ({
teamId,
appId,
sourceType,
sourceId,
chatId
}: StreamResumeRedisKeysParams) => ({
keyOfStream: `stream:resume:data:${teamId}:${appId}:${chatId}`,
keyOfUnavailable: `stream:resume:unavailable:${teamId}:${appId}:${chatId}`,
keyOfActive: `stream:resume:active:${teamId}:${appId}:${chatId}`
keyOfStream: `stream:resume:data:${teamId}:${sourceType}:${sourceId}:${chatId}`,
keyOfUnavailable: `stream:resume:unavailable:${teamId}:${sourceType}:${sourceId}:${chatId}`,
keyOfActive: `stream:resume:active:${teamId}:${sourceType}:${sourceId}:${chatId}`
});
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';
import { createLLMResponse } from '../ai/llm/request';
import { getDefaultChatTitleModel } from '../ai/model';
import { MongoChat } from './chatSchema';
import { buildChatSourceQuery, type ChatSourceParams } from './source';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
const logger = getLogger(LogCategories.MODULE.CHAT);
......@@ -170,21 +172,23 @@ export type GeneratedChatTitleResult = {
};
export const syncGeneratedChatTitleFromUserContent = async ({
appId,
sourceType,
sourceId,
chatId,
teamId,
userContent,
shouldGenerateTitle = true,
fixedTitle
}: {
appId: string;
chatId: string;
teamId: string;
userContent: UserChatItemType;
shouldGenerateTitle?: boolean;
fixedTitle?: string;
}): Promise<GeneratedChatTitleResult | undefined> => {
} & ChatSourceParams): Promise<GeneratedChatTitleResult | undefined> => {
try {
// Skill Edit 调试会话不需要模型生成标题,也不写入固定标题,避免调试链路产生额外模型调用。
if (sourceType === ChatSourceTypeEnum.skillEdit) return;
if (!shouldGenerateTitle) return;
const questionText = getQuestionText(userContent);
......@@ -208,7 +212,7 @@ export const syncGeneratedChatTitleFromUserContent = async ({
const result = await MongoChat.updateOne(
{
appId,
...buildChatSourceQuery({ sourceType, sourceId }),
chatId,
$and: [customTitleCondition, titleCondition]
},
......@@ -226,7 +230,7 @@ export const syncGeneratedChatTitleFromUserContent = async ({
updated: result.modifiedCount > 0
};
} 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 ({
* 这里故意不 await 标题模型请求,避免 `preChatRound` 阻塞主对话流启动。内部 helper 已经
* 自行捕获错误,因此调度失败不会影响对话保存。
*/
export const scheduleGeneratedChatTitleFromUserContent = (params: {
appId: string;
chatId: string;
teamId: string;
userContent: UserChatItemType;
shouldGenerateTitle?: boolean;
fixedTitle?: string;
}) => {
export const scheduleGeneratedChatTitleFromUserContent = (
params: {
chatId: string;
teamId: string;
userContent: UserChatItemType;
shouldGenerateTitle?: boolean;
fixedTitle?: string;
} & ChatSourceParams
) => {
return syncGeneratedChatTitleFromUserContent(params);
};
......
import type { ChatItemMiniType, UserChatItemType } from '@fastgpt/global/core/chat/type';
import { UserError } from '@fastgpt/global/common/error/utils';
import { MongoChatItem } from '../chatItemSchema';
import type { ChatSourceTypeEnum } 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';
......@@ -11,8 +13,7 @@ export const CHAT_DATA_ID_DUPLICATE_ERROR_MESSAGE = 'Chat dataId already exists'
* 当前运行前唯一性只约束 AI responseChatItemId;Human 消息允许与 AI 消息使用同一个
* dataId 表示同一轮对话。
*/
type ValidateChatRoundDataIdsParams = {
appId: string;
type ValidateChatRoundDataIdsParams = ChatSourceParams & {
chatId: string;
userContent: UserChatItemType & { dataId?: string };
responseChatItemId?: string;
......@@ -56,11 +57,13 @@ export const assertNoDuplicateChatDataIdsInRequest = (dataIds: Array<string | un
* dataId 校验应使用 validateChatRoundDataIds。
*/
export const assertNoExistingChatDataIds = async ({
appId,
sourceType,
sourceId,
chatId,
dataIds
}: {
appId: string;
sourceType: ChatSourceTypeEnum;
sourceId: string;
chatId: string;
dataIds: Array<string | undefined>;
}) => {
......@@ -69,7 +72,7 @@ export const assertNoExistingChatDataIds = async ({
const existingChatItem = await MongoChatItem.findOne(
{
appId,
...buildChatSourceQuery({ sourceType, sourceId }),
chatId,
dataId: { $in: validDataIds }
},
......@@ -90,7 +93,8 @@ export const assertNoExistingChatDataIds = async ({
* AI placeholder 或最终回复覆盖已有 AI 消息。
*/
export const validateChatRoundDataIds = async ({
appId,
sourceType,
sourceId,
chatId,
responseChatItemId
}: ValidateChatRoundDataIdsParams) => {
......@@ -98,7 +102,7 @@ export const validateChatRoundDataIds = async ({
const existingChatItem = await MongoChatItem.findOne(
{
appId,
...buildChatSourceQuery({ sourceType, sourceId }),
chatId,
obj: ChatRoleEnum.AI,
dataId: responseChatItemId
......
import { ChatErrEnum } from '@fastgpt/global/common/error/code/chat';
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 { AIChatItemType, UserChatItemType } from '@fastgpt/global/core/chat/type';
import type { WorkflowInteractiveResponseType } from '@fastgpt/global/core/workflow/template/system/interactive/type';
......@@ -16,6 +20,7 @@ import {
syncGeneratedChatTitleFromUserContent,
type GeneratedChatTitleResult
} from '../title';
import { buildChatSourceQuery, buildChatSourceWriteFields, type ChatSourceParams } from '../source';
export const NO_RECORD_CHAT_ID = 'NO_RECORD_HISTORIES';
......@@ -39,18 +44,16 @@ export const stripUserContentFileUrls = (userContent: UserChatItemType & { dataI
});
};
export type EnsurePendingChatRoundParams = {
export type EnsurePendingChatRoundParams = ChatSourceParams & {
chatId: string;
appId: string;
teamId: string;
tmbId: string;
userContent: UserChatItemType & { dataId?: string };
responseChatItemId: string;
};
export type PrepareChatRoundParams = {
export type PrepareChatRoundParams = ChatSourceParams & {
chatId: string;
appId: string;
teamId: string;
tmbId: string;
source: `${ChatSourceEnum}`;
......@@ -115,17 +118,13 @@ export const getPreparedRoundDataIds = ({
export const prepareChatRound = async (
params: PrepareChatRoundParams
): Promise<PrepareChatRoundResult> => {
const {
chatId,
appId,
teamId,
tmbId,
source,
sourceName,
shareId,
outLinkUid,
responseChatItemId
} = params;
const { chatId, teamId, tmbId, source, sourceName, shareId, outLinkUid, responseChatItemId } =
params;
const chatSource = {
sourceType: params.sourceType,
sourceId: params.sourceId
};
const sourceWriteFields = buildChatSourceWriteFields(chatSource);
if (isSkipSaveChatId(chatId)) {
return {
......@@ -154,14 +153,14 @@ export const prepareChatRound = async (
await mongoSessionRun(async (session) => {
const previousChat = await MongoChat.findOneAndUpdate(
{
appId,
...buildChatSourceQuery(chatSource),
chatId
},
{
$set: {
teamId,
tmbId,
appId,
...sourceWriteFields,
chatId,
source,
sourceName,
......@@ -192,14 +191,14 @@ export const prepareChatRound = async (
teamId,
tmbId,
chatId,
appId,
...sourceWriteFields,
...userPayload
},
{
teamId,
tmbId,
chatId,
appId,
...sourceWriteFields,
...aiPlaceholder
}
],
......@@ -239,7 +238,8 @@ export const preChatRound = async (params: PreChatRoundParams): Promise<PreChatR
}
const canStartGenerate = await tryStartGenerateChat({
appId: params.appId,
sourceType: params.sourceType,
sourceId: params.sourceId,
chatId,
teamId: params.teamId,
tmbId: params.tmbId,
......@@ -257,7 +257,7 @@ export const preChatRound = async (params: PreChatRoundParams): Promise<PreChatR
if (isInteractiveContinue) {
const previousAiItem = await MongoChatItem.findOne(
{
appId: params.appId,
...buildChatSourceQuery({ sourceType: params.sourceType, sourceId: params.sourceId }),
chatId,
obj: ChatRoleEnum.AI
},
......@@ -280,7 +280,8 @@ export const preChatRound = async (params: PreChatRoundParams): Promise<PreChatR
}
await validateChatRoundDataIds({
appId: params.appId,
sourceType: params.sourceType,
sourceId: params.sourceId,
chatId,
userContent: params.userContent,
responseChatItemId
......@@ -293,7 +294,8 @@ export const preChatRound = async (params: PreChatRoundParams): Promise<PreChatR
});
const titleGeneration = syncGeneratedChatTitleFromUserContent({
appId: params.appId,
sourceType: params.sourceType,
sourceId: params.sourceId,
chatId,
teamId: params.teamId,
userContent: params.userContent,
......@@ -310,7 +312,8 @@ export const preChatRound = async (params: PreChatRoundParams): Promise<PreChatR
};
} catch (error) {
await updateChatGenerateStatus({
appId: params.appId,
sourceType: params.sourceType,
sourceId: params.sourceId,
chatId,
status: ChatGenerateStatusEnum.error
});
......
......@@ -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 SelectAppItemType } from '@fastgpt/global/core/workflow/template/system/abandoned/runApp/type';
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 {
getWorkflowEntryNodeIds,
......@@ -62,7 +62,8 @@ export const dispatchAppRequest = async (props: Props): Promise<Response> => {
const chatHistories = getHistories(history, histories);
const { files } = chatValue2RuntimePrompt(query);
const childRunningAppInfo = {
id: String(appData._id),
sourceType: ChatSourceTypeEnum.app,
sourceId: String(appData._id),
name: appData.name,
teamId: String(appData.teamId),
tmbId: String(appData.tmbId),
......
......@@ -209,19 +209,19 @@ export const dispatchRunAgent = async (props: DispatchAgentModuleProps): Promise
if (effectiveUseAgentSandbox) {
streamAgentSandboxInitStatus({
workflowStreamResponse,
appId: runningAppInfo.id,
sourceType: runningAppInfo.sourceType,
sourceId: runningAppInfo.sourceId,
userId: uid,
chatId,
sandboxId: runningAppInfo.sandboxId
chatId
});
}
// 初始化 sandbox:初始化、注入 skills、files
const { sandboxClient, currentWorkingDirectory, skillInfos } = await ensureAgentSandboxRuntime({
appId: runningAppInfo.id,
sourceType: runningAppInfo.sourceType,
sourceId: runningAppInfo.sourceId,
userId: uid,
chatId,
sandboxId: runningAppInfo.sandboxId,
teamId: runningAppInfo.teamId,
tmbId: runningUserInfo.tmbId,
needSandboxRuntime: effectiveUseAgentSandbox,
......
import { getErrText } from '@fastgpt/global/common/error/utils';
import { SANDBOX_SYSTEM_PROMPT } from '@fastgpt/global/core/ai/sandbox/constants';
import { ChatRoleEnum } from '@fastgpt/global/core/chat/constants';
import { ChatRoleEnum, ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
import type {
AIChatItemValueItemType,
ChatHistoryItemResType
......@@ -144,17 +144,17 @@ export const dispatchPiAgent = async (props: DispatchAgentModuleProps): Promise<
if (effectiveUseAgentSandbox) {
streamAgentSandboxInitStatus({
workflowStreamResponse,
appId: runningAppInfo.id,
sourceType: runningAppInfo.sourceType,
sourceId: runningAppInfo.sourceId,
userId: uid,
chatId,
sandboxId: runningAppInfo.sandboxId
chatId
});
}
const { sandboxClient, currentWorkingDirectory, skillInfos } = await ensureAgentSandboxRuntime({
appId: runningAppInfo.id,
sourceType: runningAppInfo.sourceType,
sourceId: runningAppInfo.sourceId,
userId: uid,
chatId,
sandboxId: runningAppInfo.sandboxId,
teamId: runningAppInfo.teamId,
tmbId: runningUserInfo.tmbId,
needSandboxRuntime: effectiveUseAgentSandbox,
......
......@@ -21,6 +21,7 @@ import type { RunWorkflowProps } from '../../../../../../../core/workflow/dispat
import { anyValueDecrypt } from '../../../../../../../common/secret/utils';
import { WorkflowVariableState } from '../../../../utils/variables';
import { getRuntimeNodeResponseSummary } from '../../../../utils';
import { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
type Props = Pick<
RunWorkflowProps,
......@@ -78,7 +79,8 @@ export const dispatchApp = async (props: Props): Promise<DispatchSubAppResponse>
// Rewrite children app variables
const { externalProvider } = await getUserChatInfo(appData.tmbId);
const childRunningAppInfo = {
id: String(appData._id),
sourceType: ChatSourceTypeEnum.app,
sourceId: String(appData._id),
teamId: String(appData.teamId),
tmbId: String(appData.tmbId),
name: appData.name,
......@@ -105,7 +107,8 @@ export const dispatchApp = async (props: Props): Promise<DispatchSubAppResponse>
const { assistantResponses, flowUsages, runtimeNodeResponseSummary } = await runWorkflow({
...data,
runningAppInfo: {
id: String(appData._id),
sourceType: ChatSourceTypeEnum.app,
sourceId: String(appData._id),
name: appData.name,
teamId: String(appData.teamId),
tmbId: String(appData.tmbId),
......@@ -177,7 +180,8 @@ export const dispatchPlugin = async (props: Props): Promise<DispatchSubAppRespon
// Rewrite children app variables
const { externalProvider } = await getUserChatInfo(appData.tmbId);
const childRunningAppInfo = {
id: String(appData._id),
sourceType: ChatSourceTypeEnum.app,
sourceId: String(appData._id),
teamId: String(appData.teamId || runningAppInfo.teamId),
tmbId: String(appData.tmbId || runningAppInfo.tmbId),
name: appData.name,
......@@ -242,7 +246,8 @@ export const dispatchPlugin = async (props: Props): Promise<DispatchSubAppRespon
const { flowUsages, runtimeNodeResponseSummary } = await runWorkflow({
...data,
runningAppInfo: {
id: String(appData._id),
sourceType: ChatSourceTypeEnum.app,
sourceId: String(appData._id),
// 如果系统插件有 teamId 和 tmbId,则使用系统插件的 teamId 和 tmbId(管理员指定了插件作为系统插件)
name: appData.name,
teamId: appData.teamId || runningAppInfo.teamId,
......
......@@ -23,6 +23,7 @@ import {
withAgentSandboxInitLease
} from '../../../../../../ai/sandbox/runtime/entrypoint';
import { resolveSandboxHome } from '../../../../../../ai/sandbox/runtime/home';
import type { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
export type AgentSandboxPrepareContext = SandboxPrepareContext & {
sandboxClient: SandboxClient;
......@@ -36,10 +37,10 @@ export type AgentSandboxPrepareAction = (
) => Promise<AgentSandboxPrepareContext>;
type EnsureAgentSandboxRuntimeParams = {
appId: string;
sourceType: ChatSourceTypeEnum;
sourceId: string;
userId: string;
chatId: string;
sandboxId?: string;
teamId: string;
tmbId: string;
needSandboxRuntime: boolean;
......@@ -62,10 +63,10 @@ type AgentSandboxPrepareStep = SandboxPrepareStep<AgentSandboxPrepareContext>;
* workflow 层显式编排本轮 sandbox 生命周期;runtime 层只暴露具体原子能力。
*/
export async function ensureAgentSandboxRuntime({
appId,
sourceType,
sourceId,
userId,
chatId,
sandboxId,
teamId,
tmbId,
needSandboxRuntime,
......@@ -82,10 +83,10 @@ export async function ensureAgentSandboxRuntime({
}
const sandboxContext = await prepareAgentSandboxRuntime({
appId,
sourceType,
sourceId,
userId,
chatId,
sandboxId,
teamId
});
......
import { generateSandboxId } from '@fastgpt/global/core/ai/sandbox/constants';
import { SseResponseEventEnum } from '@fastgpt/global/core/workflow/runtime/constants';
import { EDIT_DEBUG_SANDBOX_CHAT_ID } from '../../../../../../ai/skill/edit/config';
import type { WorkflowResponseType } from '../../../../type';
import { getRunningSandboxId } from '../../../../../../ai/sandbox/runtime/id';
import type { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
/**
* 发送 Agent 对话中的 sandbox runtime 准备状态。
......@@ -10,20 +10,23 @@ import type { WorkflowResponseType } from '../../../../type';
*/
export const streamAgentSandboxInitStatus = ({
workflowStreamResponse,
appId,
sourceType,
sourceId,
userId,
chatId,
sandboxId
chatId
}: {
workflowStreamResponse?: WorkflowResponseType;
appId: string;
sourceType: ChatSourceTypeEnum;
sourceId: string;
userId: string;
chatId: string;
sandboxId?: string;
}) => {
const effectiveSandboxId =
sandboxId ||
generateSandboxId(appId, chatId === EDIT_DEBUG_SANDBOX_CHAT_ID ? '' : userId, chatId);
const effectiveSandboxId = getRunningSandboxId({
sourceType,
sourceId,
userId,
chatId
});
workflowStreamResponse?.({
event: SseResponseEventEnum.sandboxStatus,
......
......@@ -5,6 +5,7 @@ import type { localeType } from '@fastgpt/global/common/i18n/type';
import { runSandboxTools } from '../../../../../../ai/sandbox/toolCall';
import type { DispatchSubAppResponse } from '../../type';
import type { SandboxClient } from '../../../../../../ai/sandbox/service/runtime';
import type { ChatSourceTypeEnum } from '@fastgpt/global/core/chat/constants';
/**
* Agent 子工具层的 sandbox tool 适配器。
......@@ -15,29 +16,29 @@ import type { SandboxClient } from '../../../../../../ai/sandbox/service/runtime
export const dispatchSandboxTool = async ({
toolName,
rawArgs,
appId,
sourceType,
sourceId,
userId,
chatId,
sandboxId,
lang,
sandboxClient
}: {
toolName: string;
rawArgs: string;
appId: string;
sourceType: ChatSourceTypeEnum;
sourceId: string;
userId: string;
chatId: string;
sandboxId?: string;
lang?: localeType;
sandboxClient?: SandboxClient;
}): Promise<DispatchSubAppResponse> => {
const { input, response } = await runSandboxTools({
toolName,
args: rawArgs,
appId,
sourceType,
sourceId,
userId,
chatId,
sandboxId,
sandboxClient
});
......
......@@ -25,6 +25,7 @@ import { InvokeProcessor } from '../../../../../../../support/invoke/invoke';
import { getLogger, LogCategories } from '../../../../../../../common/logger';
import { authAppByTmbId } from '../../../../../../../support/permission/app/auth';
import { ReadPermissionVal } from '@fastgpt/global/support/permission/constant';
import { getWorkflowAppId } from '../../../../utils/source';
type SystemInputConfigType = {
type: SystemToolSecretInputTypeEnum;
......@@ -122,15 +123,18 @@ export const dispatchTool = async ({
const formatToolId = getToolRawId(tool.id);
let answerText = '';
const appId = getWorkflowAppId(runningAppInfo);
const invokeToken = new InvokeProcessor({
appId: runningAppInfo.id,
chatId,
uId: uid,
permissions: tool.permissions ?? [],
teamId: runningAppInfo.teamId,
tmbId: runningAppInfo.tmbId
}).generateToken();
const invokeToken = appId
? new InvokeProcessor({
appId,
chatId,
uId: uid,
permissions: tool.permissions ?? [],
teamId: runningAppInfo.teamId,
tmbId: runningAppInfo.tmbId
}).generateToken()
: undefined;
const childId = toolConfig.systemTool.toolId.split('/')[1];
......@@ -143,15 +147,15 @@ export const dispatchTool = async ({
secrets: inputConfigParams,
systemVar: {
app: {
id: runningAppInfo.id,
name: runningAppInfo.id
id: appId || '',
name: appId ? runningAppInfo.name : ''
},
chat: {
chatId,
uid
},
time: String(variableState.get('cTime') ?? ''),
invokeToken
invokeToken: invokeToken || ''
},
onMessage: ({ type, content }) => {
if (workflowStreamResponse && content) {
......
......@@ -253,10 +253,10 @@ export const getExecuteTool = ({
const result = await dispatchSandboxTool({
toolName: toolId,
rawArgs: args,
appId: runningAppInfo.id,
sourceType: runningAppInfo.sourceType,
sourceId: runningAppInfo.sourceId,
userId: uid,
chatId,
sandboxId: runningAppInfo.sandboxId,
lang,
sandboxClient
});
......
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