fix(ai): 修复追问与删除确认并支持删除对话
This commit is contained in:
1 parent
0b57e926bd
commit
195ee3b90a
24 files changed
+627
-113
No files matched your search
@@ -813,6 +813,21 @@ try {
|
||||
assert.equal(incompleteBody.code, 'AI_TASK_INCOMPLETE');
|
||||
assert(!incompleteBody.message.includes('换一种说法'));
|
||||
check('持续异常保持明确未完成状态和重试入口,不伪报执行成功');
|
||||
const questionSamples = [
|
||||
'请确认是否删除“周一课表”?确认后我会继续。',
|
||||
{ message: '请确认是否删除“周一课表”?', queries: [], operations: [] },
|
||||
{ questions: [{ question: '要删除哪张课表?', options: ['周一', '周五'] }], queries: [], operations: [] },
|
||||
];
|
||||
for (const sample of questionSamples) {
|
||||
const before = modelBodies.length;
|
||||
modelReplies.push(sample);
|
||||
const reply = await api('/ai/interpret', teacher, 'POST', { text: '删除课表' });
|
||||
assert.equal(modelBodies.length, before + 1, '自然语言追问不应进入格式校正循环');
|
||||
assert.equal(reply.planId, null);
|
||||
assert.equal(reply.steps.length, 0);
|
||||
assert(reply.questions?.length);
|
||||
}
|
||||
check('普通中文确认、message追问和question别名均转为可交互问题,不触发校正或写入');
|
||||
modelReplies.push({ questions: [{ id: 'subject', text: '请选择科目', options: ['数学', '语文'] }] });
|
||||
const clarification = await api('/ai/interpret', teacher, 'POST', { text: '给这个班布置作业' });
|
||||
assert.equal(clarification.planId, null);
|
||||
@@ -870,6 +885,10 @@ try {
|
||||
});
|
||||
const reader = connection.body!.getReader();
|
||||
assert((await reader.read()).value!.length > 0);
|
||||
const runningConversation = (await prisma.aiTask.findUniqueOrThrow({ where: { id: background.id } }))
|
||||
.conversationId!;
|
||||
await api(`/ai/conversations/${runningConversation}`, teacher, 'DELETE', undefined, 409);
|
||||
assert.equal(await prisma.aiTask.count({ where: { id: background.id } }), 1);
|
||||
await reader.cancel();
|
||||
releaseModel();
|
||||
modelHold = undefined;
|
||||
@@ -1184,6 +1203,63 @@ try {
|
||||
assert.notEqual(tf.find((f) => f.path === path)!.id, af.find((f) => f.path === path)!.id);
|
||||
}
|
||||
check('三层目录自动补建父目录,同名目录按教师身份独立保存');
|
||||
const deletable = await api('/ai/conversations', teacher, 'POST', {});
|
||||
const deletingTask = await api('/ai/tasks', teacher, 'POST', {
|
||||
conversationId: deletable.id,
|
||||
text: '对话删除验收',
|
||||
});
|
||||
const pendingPlan = await interpret([
|
||||
{
|
||||
action: 'notifications.create',
|
||||
params: { classId: A.id, title: '删除对话不发布', content: '只生成预览' },
|
||||
},
|
||||
]);
|
||||
await prisma.aiTask.update({
|
||||
where: { id: deletingTask.id },
|
||||
data: {
|
||||
state: 'ready',
|
||||
result: (await import('../src/lib/secrets.js')).encryptSecret(JSON.stringify(pendingPlan)),
|
||||
},
|
||||
});
|
||||
const auditCount = await prisma.aiAudit.count();
|
||||
const actualNotificationCount = await prisma.notification.count();
|
||||
await api(`/ai/conversations/${deletable.id}`, admin, 'DELETE', undefined, 403);
|
||||
await api(`/ai/conversations/${deletable.id}`, teacher, 'DELETE');
|
||||
assert.equal(await prisma.aiConversation.count({ where: { id: deletable.id } }), 0);
|
||||
assert.equal(await prisma.aiTask.count({ where: { conversationId: deletable.id } }), 0);
|
||||
assert.equal(await prisma.aiAudit.count(), auditCount);
|
||||
assert.equal(await prisma.notification.count(), actualNotificationCount);
|
||||
assert(
|
||||
(await prisma.aiPlanStep.findMany({ where: { auditId: pendingPlan.planId! } })).every(
|
||||
(s) => s.state === 'blocked',
|
||||
),
|
||||
);
|
||||
await api('/ai/tasks', teacher, 'POST', { conversationId: deletable.id, text: '不能继续已删除对话' }, 403);
|
||||
const attachmentChat = await api('/ai/conversations', teacher, 'POST', {});
|
||||
const attachmentTask = await api('/ai/tasks', teacher, 'POST', {
|
||||
conversationId: attachmentChat.id,
|
||||
text: '暂存附件',
|
||||
attachments: [attachment],
|
||||
});
|
||||
await api(`/ai/tasks/${attachmentTask.id}/files/${attachment.id}`, teacher, 'PUT', bytes, 200, {
|
||||
'content-type': 'application/octet-stream',
|
||||
});
|
||||
const stagedPath = path.join(
|
||||
process.env.COURSEWARE_DIR!,
|
||||
'.ai-tasks',
|
||||
createHash('sha256').update(attachmentTask.id).digest('hex'),
|
||||
createHash('sha256').update(attachment.id).digest('hex'),
|
||||
);
|
||||
assert(fs.existsSync(stagedPath));
|
||||
await api(`/ai/conversations/${attachmentChat.id}`, teacher, 'DELETE');
|
||||
assert(!fs.existsSync(stagedPath));
|
||||
const executedConversation = (await prisma.aiTask.findUniqueOrThrow({ where: { id: staged.id } }))
|
||||
.conversationId!;
|
||||
const homeworkCount = await prisma.homework.count();
|
||||
await api(`/ai/conversations/${executedConversation}`, teacher, 'DELETE');
|
||||
assert.equal(await prisma.homework.count(), homeworkCount);
|
||||
check('删除对话仅限本人,轮次清除、待确认计划失效且业务数据与审计保留');
|
||||
|
||||
console.log(`AI 隔离验收通过:${checks} 项`);
|
||||
} finally {
|
||||
globalThis.fetch = realFetch;
|
||||
|
||||
@@ -27,6 +27,14 @@ import { setTimeout as delay } from 'node:timers/promises';
|
||||
|
||||
const router = Router();
|
||||
router.use(authenticate());
|
||||
router.delete(
|
||||
'/conversations/:id',
|
||||
requirePermission('ai:use'),
|
||||
validate({ params: planIdSchema }),
|
||||
async (req, res) => {
|
||||
sendOk(res, await tasks.deleteConversation(getAuthUser(req), String(req.params.id)));
|
||||
},
|
||||
);
|
||||
router.post('/conversations', requirePermission('ai:use'), async (req, res) => {
|
||||
sendOk(res, await tasks.createConversation(getAuthUser(req)));
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { z } from 'zod';
|
||||
import { modelReplySchema as replySchema, normalizeModelReply, type ModelReply } from './model-reply.js';
|
||||
import {
|
||||
dayKeyLocal,
|
||||
type AiInterpretResult,
|
||||
@@ -17,30 +17,6 @@ import { planWithModel, sanitizePrompt, type AgentRun } from './model-planner.js
|
||||
import { getAiSettings } from './ai.service.js';
|
||||
import type { AiInterpretInput } from './ai.schemas.js';
|
||||
|
||||
const operationSchema = z
|
||||
.object({
|
||||
action: z.string().min(1).max(80),
|
||||
target: z.record(z.string(), z.string().max(100)).optional(),
|
||||
params: z.record(z.string(), z.unknown()).optional(),
|
||||
query: z.record(z.string(), z.unknown()).optional(),
|
||||
attachmentId: z.string().max(100).optional(),
|
||||
})
|
||||
.strict();
|
||||
const replySchema = z.object({
|
||||
questions: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string().min(1).max(100),
|
||||
text: z.string().min(1).max(1000),
|
||||
options: z.array(z.string().max(200)).max(10).optional(),
|
||||
}),
|
||||
)
|
||||
.max(3)
|
||||
.optional(),
|
||||
message: z.string().max(4000).optional(),
|
||||
queries: z.array(operationSchema).max(8).default([]),
|
||||
operations: z.array(operationSchema).max(16).default([]),
|
||||
});
|
||||
const aliases: Record<string, string> = {
|
||||
create_homework: 'homeworks.create',
|
||||
create_notification: 'notifications.create',
|
||||
@@ -48,10 +24,7 @@ const aliases: Record<string, string> = {
|
||||
};
|
||||
|
||||
/** 本地确定性解析只用于 mock 和原有模型之外的文件、查询入口,不新增任何模型出站数据。 */
|
||||
function localReply(
|
||||
input: AiInterpretInput,
|
||||
classes: { id: string; name: string }[],
|
||||
): z.infer<typeof replySchema> | null {
|
||||
function localReply(input: AiInterpretInput, classes: { id: string; name: string }[]): ModelReply | null {
|
||||
const classId =
|
||||
input.classId ||
|
||||
classes.find((item) => input.text.includes(item.name))?.id ||
|
||||
@@ -139,10 +112,10 @@ export async function interpretConversation(
|
||||
const classes = tools.some((item) => item.action === 'classes.list')
|
||||
? ((await runRead(user, { action: 'classes.list' })) as { id: string; name: string }[])
|
||||
: [];
|
||||
let reply: z.infer<typeof replySchema> | null = null;
|
||||
let reply: ModelReply | null = null;
|
||||
if (settings.provider === 'mock') {
|
||||
try {
|
||||
reply = replySchema.parse(JSON.parse(input.text));
|
||||
reply = normalizeModelReply(JSON.parse(input.text));
|
||||
} catch {
|
||||
/* 自然语言示例继续走本地解析。 */
|
||||
}
|
||||
@@ -186,6 +159,7 @@ export async function interpretConversation(
|
||||
});
|
||||
else reply = replySchema.parse({ message: '离线示例未识别此任务,请配置模型或补充具体操作。' });
|
||||
}
|
||||
reply = normalizeModelReply(reply);
|
||||
if (reply.questions?.length)
|
||||
return {
|
||||
planId: null,
|
||||
@@ -252,7 +226,7 @@ export async function interpretConversation(
|
||||
{ role: 'assistant' as const, content: JSON.stringify(reply).slice(0, 8000) },
|
||||
{
|
||||
role: 'user' as const,
|
||||
content: `预览校验未通过:${sanitizePrompt(error.message)}。请查询真实数据后修正参数,不能省略用户要求。信息不足时提出具体问题。`,
|
||||
content: `预览校验未通过:${sanitizePrompt(error.message)}。请查询真实数据后修正参数,不能省略用户要求。信息不足时通过 questions:[{id,text,options?}] 提出具体问题,并清空 operations 和 queries。`,
|
||||
},
|
||||
].slice(-20),
|
||||
},
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { z } from 'zod';
|
||||
import { parseModelReply, type ModelReply } from './model-reply.js';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import {
|
||||
dayKeyLocal,
|
||||
@@ -18,50 +18,7 @@ import { redact } from './business-read.js';
|
||||
import type { AiInterpretInput } from './ai.schemas.js';
|
||||
import { modelEndpoint, readCompletion } from './model-transport.js';
|
||||
|
||||
const operationSchema = z
|
||||
.object({
|
||||
action: z.string().min(1).max(80),
|
||||
target: z.record(z.string(), z.string().max(100)).optional(),
|
||||
params: z.record(z.string(), z.unknown()).optional(),
|
||||
query: z.record(z.string(), z.unknown()).optional(),
|
||||
attachmentId: z.string().max(100).optional(),
|
||||
})
|
||||
.strict();
|
||||
const replySchema = z
|
||||
.object({
|
||||
questions: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string().min(1).max(100),
|
||||
text: z.string().min(1).max(1000),
|
||||
options: z.array(z.string().max(200)).max(10).optional(),
|
||||
}),
|
||||
)
|
||||
.max(3)
|
||||
.optional(),
|
||||
message: z.string().max(4000).optional(),
|
||||
queries: z.array(operationSchema).max(8).default([]),
|
||||
operations: z.array(operationSchema).max(16).default([]),
|
||||
})
|
||||
.refine(
|
||||
(value) =>
|
||||
!!value.message?.trim() ||
|
||||
!!value.questions?.length ||
|
||||
value.queries.length > 0 ||
|
||||
value.operations.length > 0,
|
||||
'回复不能是空对象',
|
||||
);
|
||||
|
||||
export function parseModelReply(content: string) {
|
||||
const trimmed = content
|
||||
.trim()
|
||||
.replace(/^```(?:json)?\s*/i, '')
|
||||
.replace(/\s*```$/, '');
|
||||
// 只修正展示包装,不猜测 ID、不补写业务参数,不执行任意文本。
|
||||
const start = trimmed.indexOf('{'),
|
||||
end = trimmed.lastIndexOf('}');
|
||||
return replySchema.parse(JSON.parse(start >= 0 && end >= start ? trimmed.slice(start, end + 1) : trimmed));
|
||||
}
|
||||
export { parseModelReply } from './model-reply.js';
|
||||
|
||||
function visibleMessage(content: string): string | undefined {
|
||||
const match = content.match(/"message"\s*:\s*"((?:[^"\\]|\\.)*)/);
|
||||
@@ -107,9 +64,11 @@ export async function planWithModel(
|
||||
{
|
||||
role: 'system',
|
||||
content: [
|
||||
'你是 ClassHelper 助手。只输出严格 JSON:{message,queries:[{action,target?,query?}],operations:[{action,target?,params?,attachmentId?}]}。',
|
||||
'你是 ClassHelper 助手。只输出严格 JSON:{message,questions?:[{id,text,options?}],queries:[{action,target?,query?}],operations:[{action,target?,params?,attachmentId?}]}。',
|
||||
'例如普通回复:{"message":"你好,需要处理什么?","queries":[],"operations":[]};查询:{"message":"正在查询班级","queries":[{"action":"classes.list"}],"operations":[]}。禁止 Markdown 围栏,message 只写简短进度或给用户的回复。',
|
||||
'缺少用户才能提供的必要信息时,返回 questions:[{id,text,options?}],operations 和 queries 必须为空,等待用户回答。',
|
||||
'提问示例:{"message":"请选择要删除的课表","questions":[{"id":"plan","text":"要删除哪张课表?","options":["周一","周五"]}],"queries":[],"operations":[]}。',
|
||||
'删除等危险操作的最终确认由客户端操作预览和确认窗口完成,不需要反复在聊天里索取口头确认。目标明确且已查询真实 id 时直接返回待确认 operations,例如 plans.delete 的 target:{id:真实课表id};目标不明时才通过 questions 追问,不得声称已经删除。',
|
||||
'queries 只能查询,operations 是待确认写操作,不能声称已执行。先查询真实 id 和现状,再规划修改;不猜测班级、账号、学生、课程和时间点 id。信息不足时追问。',
|
||||
'仅可选择工具目录中的 action。工具 schema.target 列出路径参数,schema.params 是 params 的 JSON Schema。查询条件放 query。所有数据和动作遵循操作者的实时权限。',
|
||||
'数据库备份/恢复/清空/切换/SQL、服务器配置/启停/升级和密钥维护禁止执行。密码字段留空,由用户在专门表单输入。',
|
||||
@@ -178,7 +137,7 @@ export async function planWithModel(
|
||||
'AI_PROVIDER_ERROR',
|
||||
`模型服务暂不可用(HTTP ${response.status}),请检查服务地址、模型与密钥。任务尚未执行。`,
|
||||
);
|
||||
let reply: z.infer<typeof replySchema>;
|
||||
let reply: ModelReply;
|
||||
try {
|
||||
let published = '';
|
||||
let lastReasoningUpdate = 0;
|
||||
@@ -212,7 +171,7 @@ export async function planWithModel(
|
||||
messages.push({
|
||||
role: 'user',
|
||||
content:
|
||||
'上一轮输出未通过校验或被截断。请重新输出完整 JSON 对象,包含 message 字符串、queries 数组和 operations 数组;不使用 Markdown,不添加解释。不确定的业务参数请在 message 中追问,不猜测。',
|
||||
'上一轮输出未通过校验或被截断。请重新输出完整 JSON 对象,包含 message 字符串、queries 数组和 operations 数组;不使用 Markdown,不添加解释。缺少用户信息时返回 questions:[{id,text,options?}],并令 queries 和 operations 为空;不要在 message 中反复询问确认,不猜测业务参数。',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const operationSchema = z
|
||||
.object({
|
||||
action: z.string().min(1).max(80),
|
||||
target: z.record(z.string(), z.string().max(100)).optional(),
|
||||
params: z.record(z.string(), z.unknown()).optional(),
|
||||
query: z.record(z.string(), z.unknown()).optional(),
|
||||
attachmentId: z.string().max(100).optional(),
|
||||
})
|
||||
.strict();
|
||||
export const modelReplySchema = z
|
||||
.object({
|
||||
message: z.string().max(4000).optional(),
|
||||
questions: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string().min(1).max(100),
|
||||
text: z.string().min(1).max(1000),
|
||||
options: z.array(z.string().min(1).max(200)).max(10).optional(),
|
||||
}),
|
||||
)
|
||||
.max(3)
|
||||
.optional(),
|
||||
queries: z.array(operationSchema).max(8).default([]),
|
||||
operations: z.array(operationSchema).max(16).default([]),
|
||||
})
|
||||
.refine(
|
||||
(v) => !!v.message?.trim() || !!v.questions?.length || v.queries.length > 0 || v.operations.length > 0,
|
||||
'回复不能是空对象',
|
||||
);
|
||||
export type ModelReply = z.infer<typeof modelReplySchema>;
|
||||
|
||||
function isQuestion(text: string) {
|
||||
return /[??]|是否|能否|可否|请(?:问|确认|选择|提供|补充|说明|指定)|which\b|would you\b|could you\b/i.test(
|
||||
text,
|
||||
);
|
||||
}
|
||||
function questionFromText(text: string) {
|
||||
return {
|
||||
id: 'question-1',
|
||||
text: text.slice(0, 1000),
|
||||
...(/请确认|是否确认|确定(?:要|删除)|are you sure/i.test(text)
|
||||
? { options: ['继续生成操作预览', '取消本次请求'] }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
/** 仅兼容展示与追问字段,不从自然语言推断任何业务动作、对象 id 或执行许可。 */
|
||||
export function normalizeModelReply(value: unknown): ModelReply {
|
||||
if (typeof value === 'string') {
|
||||
const text = value.trim();
|
||||
if (!text || !isQuestion(text)) throw new Error('模型回复不是有效的操作协议或追问');
|
||||
return modelReplySchema.parse({
|
||||
message: text,
|
||||
questions: [questionFromText(text)],
|
||||
});
|
||||
}
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return modelReplySchema.parse(value);
|
||||
const raw = value as Record<string, unknown>;
|
||||
const requested = raw.questions ?? (raw.question === undefined ? undefined : [raw.question]);
|
||||
let questions: unknown = requested;
|
||||
if (requested !== undefined) {
|
||||
const list = Array.isArray(requested) ? requested : [requested];
|
||||
questions = list.map((item, index) => {
|
||||
if (typeof item === 'string') return { id: `question-${index + 1}`, text: item.trim() };
|
||||
if (!item || typeof item !== 'object' || Array.isArray(item)) return item;
|
||||
const question = item as Record<string, unknown>;
|
||||
return {
|
||||
id: question.id || `question-${index + 1}`,
|
||||
text: question.text ?? question.question,
|
||||
options: Array.isArray(question.options)
|
||||
? question.options.map((option) =>
|
||||
typeof option === 'object' && option !== null && !Array.isArray(option)
|
||||
? (option as Record<string, unknown>).label
|
||||
: option,
|
||||
)
|
||||
: question.options,
|
||||
};
|
||||
});
|
||||
}
|
||||
// 文字追问只能在没有业务动作/查询时转成问题;已有删除预览保留原有确认链。
|
||||
if (
|
||||
(questions === undefined || (Array.isArray(questions) && questions.length === 0)) &&
|
||||
typeof raw.message === 'string' &&
|
||||
isQuestion(raw.message) &&
|
||||
(raw.operations === undefined || (Array.isArray(raw.operations) && raw.operations.length === 0)) &&
|
||||
(raw.queries === undefined || (Array.isArray(raw.queries) && raw.queries.length === 0))
|
||||
) {
|
||||
questions = [questionFromText(raw.message.trim())];
|
||||
}
|
||||
if (Array.isArray(questions) && questions.length) {
|
||||
return modelReplySchema.parse({ ...raw, questions, queries: [], operations: [] });
|
||||
}
|
||||
return modelReplySchema.parse({ ...raw, questions });
|
||||
}
|
||||
export function parseModelReply(content: string): ModelReply {
|
||||
const trimmed = content
|
||||
.trim()
|
||||
.replace(/^```(?:json)?\s*/i, '')
|
||||
.replace(/\s*```$/, '');
|
||||
const start = trimmed.indexOf('{'),
|
||||
end = trimmed.lastIndexOf('}');
|
||||
if (start >= 0 && end >= start) return normalizeModelReply(JSON.parse(trimmed.slice(start, end + 1)));
|
||||
// 不把截断的 JSON 或损坏的动作协议当普通提问吞掉。
|
||||
if (/^[{[\"]|^```/.test(trimmed)) return normalizeModelReply(JSON.parse(trimmed));
|
||||
return normalizeModelReply(trimmed);
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import type { Request } from 'express';
|
||||
import type { AiAgentEvent, AiConversationResult, AiTaskDto } from '@classhelper/shared';
|
||||
import { prisma } from '../../lib/db.js';
|
||||
import { ApiError } from '../../lib/http.js';
|
||||
import { logger } from '../../lib/logger.js';
|
||||
import { assertPermission, loadAuthPrincipal } from '../../lib/authz/index.js';
|
||||
import { loadSessionUser } from '../../lib/authz/session.js';
|
||||
import { encryptSecret, decryptSecret } from '../../lib/secrets.js';
|
||||
@@ -141,13 +142,27 @@ export async function createTask(user: TokenPayload, input: AiInterpretInput) {
|
||||
messages: context.map((item) => ({ ...item, content: sanitizePrompt(item.content).slice(0, 8000) })),
|
||||
};
|
||||
Object.assign(safe, { accessStamp: await accessStamp(user) });
|
||||
const row = await prisma.aiTask.create({
|
||||
data: {
|
||||
userId: user.sub,
|
||||
conversationId: conversation.id,
|
||||
turnNumber: (previous.at(-1)?.turnNumber ?? 0) + 1,
|
||||
input: encryptSecret(JSON.stringify(safe)),
|
||||
},
|
||||
const row = await prisma.$transaction(async (tx) => {
|
||||
// 与删除对话共用同一行锁,避免新轮次写入已删除的对话。
|
||||
const locked = await tx.aiConversation.updateMany({
|
||||
where: { id: conversation.id, userId: user.sub },
|
||||
data: { updatedAt: new Date(), title: conversation.title || sanitizePrompt(input.text).slice(0, 80) },
|
||||
});
|
||||
if (!locked.count) throw ApiError.forbidden('此对话已删除或无法访问');
|
||||
const latest = await tx.aiTask.findFirst({
|
||||
where: { conversationId: conversation.id, userId: user.sub },
|
||||
orderBy: { turnNumber: 'desc' },
|
||||
});
|
||||
if ((latest?.turnNumber ?? 0) !== (previous.at(-1)?.turnNumber ?? 0))
|
||||
throw ApiError.conflict('对话已有新轮次,请重新发送');
|
||||
return tx.aiTask.create({
|
||||
data: {
|
||||
userId: user.sub,
|
||||
conversationId: conversation.id,
|
||||
turnNumber: (latest?.turnNumber ?? 0) + 1,
|
||||
input: encryptSecret(JSON.stringify(safe)),
|
||||
},
|
||||
});
|
||||
});
|
||||
if (last && inherited?.length) {
|
||||
for (const attachment of inherited) {
|
||||
@@ -158,10 +173,6 @@ export async function createTask(user: TokenPayload, input: AiInterpretInput) {
|
||||
await fsp.copyFile(source, target);
|
||||
}
|
||||
}
|
||||
await prisma.aiConversation.update({
|
||||
where: { id: conversation.id },
|
||||
data: { title: conversation.title || sanitizePrompt(input.text).slice(0, 80), updatedAt: new Date() },
|
||||
});
|
||||
return { id: row.id, conversationId: conversation.id };
|
||||
}
|
||||
export async function stageAttachment(
|
||||
@@ -505,3 +516,41 @@ export async function conversationTurns(user: TokenPayload, id: string, before?:
|
||||
});
|
||||
return Promise.all(rows.reverse().map((row) => task(user, row.id)));
|
||||
}
|
||||
|
||||
/** 删除自己的对话,不回滚已执行业务,也不删除业务审计。 */
|
||||
export async function deleteConversation(user: TokenPayload, id: string) {
|
||||
await ownedConversation(user, id);
|
||||
const rows = await prisma.$transaction(async (tx) => {
|
||||
const locked = await tx.aiConversation.updateMany({
|
||||
where: { id, userId: user.sub },
|
||||
data: { updatedAt: new Date() },
|
||||
});
|
||||
if (!locked.count) throw ApiError.forbidden('无法访问此对话');
|
||||
const tasks = await tx.aiTask.findMany({ where: { conversationId: id, userId: user.sub } });
|
||||
if (tasks.some((t) => active.has(t.id) || ['planning', 'executing'].includes(t.state)))
|
||||
throw ApiError.conflict('对话仍有后台任务,请先停止或等待完成后再删除');
|
||||
const planIds = tasks.flatMap((t) =>
|
||||
t.result ? [decode<AiConversationResult>(t.result).planId].filter((p): p is string => Boolean(p)) : [],
|
||||
);
|
||||
if (
|
||||
await tx.aiPlanStep.count({ where: { auditId: { in: planIds }, userId: user.sub, state: 'running' } })
|
||||
)
|
||||
throw ApiError.conflict('业务操作正在执行,请等待完成后再删除');
|
||||
await tx.aiPlanStep.updateMany({
|
||||
where: {
|
||||
auditId: { in: planIds },
|
||||
userId: user.sub,
|
||||
state: { in: ['draft', 'prepared', 'confirmed', 'failed'] },
|
||||
},
|
||||
data: { state: 'blocked', result: JSON.stringify({ message: '对话已删除,未完成计划已取消' }) },
|
||||
});
|
||||
await tx.aiTask.deleteMany({ where: { conversationId: id, userId: user.sub } });
|
||||
await tx.aiConversation.delete({ where: { id } });
|
||||
return tasks;
|
||||
});
|
||||
for (const row of rows)
|
||||
await cleanup(row.id, decode<AiInterpretInput>(row.input)).catch(() =>
|
||||
logger.warn('AI 对话已删除,暂存附件清理未完成'),
|
||||
);
|
||||
return { id };
|
||||
}
|
||||
Reference in new issue
Block a user