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 };
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, watch } from 'vue';
|
||||
import type { AiConversationResult } from '@classhelper/shared';
|
||||
const props = defineProps<{ questions: NonNullable<AiConversationResult['questions']> }>();
|
||||
const visible = defineModel<boolean>({ default: false });
|
||||
const emit = defineEmits<{ answer: [text: string] }>();
|
||||
const answers = reactive<Record<string, string>>({});
|
||||
watch(visible, (value) => {
|
||||
if (value) for (const key of Object.keys(answers)) delete answers[key];
|
||||
});
|
||||
const complete = computed(
|
||||
() => props.questions.length > 0 && props.questions.every((q) => answers[q.id]?.trim()),
|
||||
);
|
||||
function submit() {
|
||||
if (!complete.value) return;
|
||||
const text = props.questions.map((q) => `${q.text}:${answers[q.id]!.trim()}`).join('\n');
|
||||
visible.value = false;
|
||||
emit('answer', text);
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<el-dialog
|
||||
v-model="visible"
|
||||
title="AI 需要你补充信息"
|
||||
width="520px"
|
||||
append-to-body
|
||||
:close-on-click-modal="false"
|
||||
class="assistant-questions-dialog"
|
||||
>
|
||||
<p>回答后会继续生成操作预览;删除等操作仍需核对预览并确认执行。</p>
|
||||
<section v-for="question in questions" :key="question.id" class="question-field">
|
||||
<h3 :id="'ai-question-' + question.id">{{ question.text }}</h3>
|
||||
<div class="question-options" :aria-labelledby="'ai-question-' + question.id">
|
||||
<el-button
|
||||
v-for="option in question.options || []"
|
||||
:key="option"
|
||||
:type="answers[question.id] === option ? 'primary' : 'default'"
|
||||
:aria-pressed="answers[question.id] === option"
|
||||
@click="answers[question.id] = option"
|
||||
>
|
||||
{{ option }}
|
||||
</el-button>
|
||||
</div>
|
||||
<el-input
|
||||
v-model="answers[question.id]"
|
||||
type="textarea"
|
||||
:autosize="{ minRows: 2, maxRows: 5 }"
|
||||
maxlength="1000"
|
||||
placeholder="选择上方答案,或输入自己的回答"
|
||||
:aria-labelledby="'ai-question-' + question.id"
|
||||
/>
|
||||
</section>
|
||||
<template #footer>
|
||||
<el-button @click="visible = false">稍后回答</el-button>
|
||||
<el-button type="primary" :disabled="!complete" @click="submit">发送回答</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
<style scoped>
|
||||
.question-field {
|
||||
margin: 16px 0;
|
||||
}
|
||||
.question-field h3 {
|
||||
font-size: 1em;
|
||||
overflow-wrap: anywhere;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.question-options {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin: 12px 0;
|
||||
}
|
||||
.question-options :deep(.el-button) {
|
||||
height: auto;
|
||||
white-space: normal;
|
||||
line-height: 1.5;
|
||||
text-align: left;
|
||||
max-width: 100%;
|
||||
margin: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -19,6 +19,7 @@ import { useAuthStore } from '@/stores/auth';
|
||||
import { hashAttachment, importFileBase64 } from '@/composables/assistantFiles';
|
||||
import { findClassInSession } from '@/composables/useClassInSession';
|
||||
import AssistantData from '@/components/AssistantData.vue';
|
||||
import AssistantQuestions from '@/components/AssistantQuestions.vue';
|
||||
import UrgentClassWarning from '@/components/UrgentClassWarning.vue';
|
||||
import { observeTask } from '@/composables/assistantStream';
|
||||
interface ChatMessage {
|
||||
@@ -32,22 +33,44 @@ interface ChatMessage {
|
||||
const auth = useAuthStore();
|
||||
let viewEpoch = 0;
|
||||
const replacePlan = ref(false);
|
||||
const deletingConversation = ref(false);
|
||||
const questionsVisible = ref(false),
|
||||
questionSource = ref<ChatMessage>();
|
||||
function showQuestions(message: ChatMessage) {
|
||||
if (busy.value || executing.value || !message.result?.questions?.length) return;
|
||||
questionSource.value = message;
|
||||
questionsVisible.value = true;
|
||||
}
|
||||
async function answerQuestions(answer: string) {
|
||||
if (busy.value || executing.value) return;
|
||||
text.value = answer;
|
||||
await send();
|
||||
}
|
||||
|
||||
const conversationId = ref('');
|
||||
const conversations = ref<{ id: string; title: string }[]>([]);
|
||||
let conversationListRequest = 0;
|
||||
async function loadConversations() {
|
||||
conversations.value = await api.get('/ai/conversations');
|
||||
const request = ++conversationListRequest;
|
||||
const rows = await api.get<{ id: string; title: string }[]>('/ai/conversations');
|
||||
if (request === conversationListRequest && !disposed) conversations.value = rows;
|
||||
}
|
||||
async function openConversation(id: string) {
|
||||
if ((busy.value || executing.value) && !observing) return;
|
||||
viewEpoch++;
|
||||
questionsVisible.value = false;
|
||||
questionSource.value = undefined;
|
||||
const epoch = ++viewEpoch;
|
||||
controller?.abort();
|
||||
busy.value = false;
|
||||
executing.value = false;
|
||||
questionsVisible.value = false;
|
||||
questionSource.value = undefined;
|
||||
conversationId.value = id;
|
||||
attachments.value = [];
|
||||
files.clear();
|
||||
replacePlan.value = false;
|
||||
const turns = await api.get<AiTaskDto[]>(`/ai/conversations/${id}`);
|
||||
if (epoch !== viewEpoch || disposed) return;
|
||||
messages.value = turns.flatMap((t) => [
|
||||
{ role: 'user' as const, content: t.text },
|
||||
{
|
||||
@@ -67,6 +90,48 @@ async function openConversation(id: string) {
|
||||
lastRequest = last ? { text: last.text, conversationId: id } : undefined;
|
||||
clearCredentials();
|
||||
if (last && ['planning', 'executing'].includes(last.state)) await resumeTask(last.id, true);
|
||||
else if (last?.state === 'waiting_input' && messages.value.at(-1)) showQuestions(messages.value.at(-1)!);
|
||||
}
|
||||
async function deleteCurrentConversation() {
|
||||
const id = conversationId.value;
|
||||
if (!id || busy.value || executing.value || hashing.value || deletingConversation.value) return;
|
||||
const title = conversations.value.find((c) => c.id === id)?.title || '新对话';
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`删除“${title}”?对话轮次和暂存附件会清除,未完成计划会取消。已执行的业务操作及审计记录保留。`,
|
||||
'删除对话',
|
||||
{ type: 'warning', confirmButtonText: '删除对话', cancelButtonText: '保留对话' },
|
||||
);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
deletingConversation.value = true;
|
||||
try {
|
||||
await api.delete(`/ai/conversations/${encodeURIComponent(id)}`);
|
||||
viewEpoch++;
|
||||
controller?.abort();
|
||||
questionsVisible.value = false;
|
||||
questionSource.value = undefined;
|
||||
conversationId.value = '';
|
||||
taskId.value = '';
|
||||
messages.value = [];
|
||||
active.value = undefined;
|
||||
lastRequest = undefined;
|
||||
error.value = '';
|
||||
text.value = '';
|
||||
attachments.value = [];
|
||||
files.clear();
|
||||
clearCredentials();
|
||||
classId.value = '';
|
||||
replacePlan.value = false;
|
||||
await loadConversations();
|
||||
if (conversations.value[0]) await openConversation(conversations.value[0].id);
|
||||
ElMessage.success('对话已删除');
|
||||
} catch (e) {
|
||||
error.value = failure(e);
|
||||
} finally {
|
||||
deletingConversation.value = false;
|
||||
}
|
||||
}
|
||||
async function olderConversations() {
|
||||
const older = await api.get<{ id: string; title: string }[]>('/ai/conversations', {
|
||||
@@ -226,7 +291,14 @@ async function retryTask(): Promise<void> {
|
||||
if (lastRequest) await send(true);
|
||||
}
|
||||
async function send(retrying = false): Promise<void> {
|
||||
if ((!retrying && !text.value.trim()) || busy.value || executing.value || hashing.value) return;
|
||||
if (
|
||||
(!retrying && !text.value.trim()) ||
|
||||
busy.value ||
|
||||
executing.value ||
|
||||
hashing.value ||
|
||||
deletingConversation.value
|
||||
)
|
||||
return;
|
||||
const epoch = viewEpoch;
|
||||
const supersedesTaskId = replacePlan.value && pending.value ? taskId.value : undefined;
|
||||
busy.value = true;
|
||||
@@ -310,6 +382,7 @@ async function send(retrying = false): Promise<void> {
|
||||
observing = false;
|
||||
if (message) message.state = controller.signal.aborted || error.value ? 'stopped' : 'done';
|
||||
busy.value = false;
|
||||
if (message?.result?.questions?.length && !disposed) showQuestions(message);
|
||||
if (!disposed) {
|
||||
taskHistory.value = await aiApi.tasks().catch(() => taskHistory.value);
|
||||
await loadConversations();
|
||||
@@ -324,7 +397,9 @@ function composerKey(event: KeyboardEvent): void {
|
||||
}
|
||||
}
|
||||
async function newConversation(): Promise<void> {
|
||||
if (hashing.value || ((busy.value || executing.value) && !observing)) return;
|
||||
if (deletingConversation.value || hashing.value || ((busy.value || executing.value) && !observing)) return;
|
||||
questionsVisible.value = false;
|
||||
questionSource.value = undefined;
|
||||
viewEpoch++;
|
||||
controller?.abort();
|
||||
busy.value = false;
|
||||
@@ -481,6 +556,7 @@ async function resumeTask(id: string, preserveHistory = false): Promise<void> {
|
||||
error.value = '';
|
||||
const epoch = viewEpoch;
|
||||
const saved = await aiApi.task(id);
|
||||
if (disposed || epoch !== viewEpoch) return;
|
||||
taskId.value = id;
|
||||
lastRequest = { text: saved.text };
|
||||
const message = reactive<ChatMessage>({
|
||||
@@ -496,6 +572,7 @@ async function resumeTask(id: string, preserveHistory = false): Promise<void> {
|
||||
clearCredentials();
|
||||
if (saved.error) error.value = saved.error;
|
||||
if (!['planning', 'executing'].includes(saved.state)) {
|
||||
if (saved.state === 'waiting_input') showQuestions(message);
|
||||
await scroll();
|
||||
return;
|
||||
}
|
||||
@@ -530,6 +607,7 @@ async function resumeTask(id: string, preserveHistory = false): Promise<void> {
|
||||
message.state = error.value ? 'stopped' : 'done';
|
||||
busy.value = false;
|
||||
executing.value = false;
|
||||
if (message.result?.questions?.length && !disposed) showQuestions(message);
|
||||
await scroll();
|
||||
}
|
||||
}
|
||||
@@ -574,12 +652,20 @@ onBeforeUnmount(() => {
|
||||
</div>
|
||||
</div>
|
||||
<div class="agent-header-actions">
|
||||
<el-button
|
||||
v-if="conversationId"
|
||||
:disabled="busy || executing || hashing"
|
||||
:loading="deletingConversation"
|
||||
@click="deleteCurrentConversation"
|
||||
>
|
||||
删除对话
|
||||
</el-button>
|
||||
<el-button v-if="conversations.length >= 30" @click="olderConversations">更多对话</el-button>
|
||||
<el-select
|
||||
v-if="conversations.length"
|
||||
:model-value="conversationId"
|
||||
placeholder="对话历史"
|
||||
:disabled="(busy || executing) && !observing"
|
||||
:disabled="deletingConversation || ((busy || executing) && !observing)"
|
||||
@change="openConversation"
|
||||
>
|
||||
<el-option
|
||||
@@ -589,7 +675,10 @@ onBeforeUnmount(() => {
|
||||
:label="item.title || '新对话'"
|
||||
/>
|
||||
</el-select>
|
||||
<el-button :disabled="hashing || ((busy || executing) && !observing)" @click="newConversation">
|
||||
<el-button
|
||||
:disabled="deletingConversation || hashing || ((busy || executing) && !observing)"
|
||||
@click="newConversation"
|
||||
>
|
||||
新对话
|
||||
</el-button>
|
||||
<el-select
|
||||
@@ -681,19 +770,7 @@ onBeforeUnmount(() => {
|
||||
class="assistant-question"
|
||||
>
|
||||
<strong>{{ question.text }}</strong>
|
||||
<div class="question-options">
|
||||
<el-button
|
||||
v-for="option in question.options || []"
|
||||
:key="option"
|
||||
:disabled="busy"
|
||||
@click="
|
||||
text = question.text + ':' + option;
|
||||
send();
|
||||
"
|
||||
>
|
||||
{{ option }}
|
||||
</el-button>
|
||||
</div>
|
||||
<el-button :disabled="busy || executing" @click="showQuestions(message)">回答问题</el-button>
|
||||
<small>也可以在下方输入框自由回答。</small>
|
||||
</el-card>
|
||||
<el-button
|
||||
@@ -813,6 +890,11 @@ onBeforeUnmount(() => {
|
||||
<el-progress v-if="executing && progress > 0" :percentage="progress" />
|
||||
</section>
|
||||
</div>
|
||||
<AssistantQuestions
|
||||
v-model="questionsVisible"
|
||||
:questions="questionSource?.result?.questions || []"
|
||||
@answer="answerQuestions"
|
||||
/>
|
||||
<el-alert v-if="error" :title="error" type="warning" :closable="true" show-icon @close="error = ''" />
|
||||
<el-button v-if="error && !active?.steps.length && !busy && !executing" @click="retryTask">
|
||||
重试上次任务
|
||||
|
||||
Reference in new issue
Block a user