diff --git a/docs/app/assistant.md b/docs/app/assistant.md index 234f529..93e6453 100644 --- a/docs/app/assistant.md +++ b/docs/app/assistant.md @@ -45,6 +45,10 @@ description: 多轮对话、文件处理与操作计划,核对后通过现有 ## 对话与轮次 -对话历史按账号保存在服务器。每次发送是一轮,右侧横条可跳转轮次,新对话独立保存。助手缺少必要信息时会显示问题卡片,可选答案或在输入框自由回答;追问阶段不执行写入。格式自动修正每轮至多一次,失败后保留明确的重试入口。 +对话历史按账号保存在服务器。每次发送是一轮,右侧横条可跳转轮次,新对话独立保存。助手缺少必要信息时会弹出提问窗口,可选答案或自由回答。关闭窗口后可通过历史消息中的“回答问题”再次打开,刷新页面也能恢复待回答的问题;追问阶段不执行写入。格式自动修正每轮至多一次,失败后保留明确的重试入口。 勾选“本轮明确替换当前待确认计划”后,新计划形成时只使选中的旧计划失效,历史记录保留。不勾选时保留旧计划;新建对话不影响其他对话的计划。 + +删除课表等危险操作时,目标明确后会先生成变更预览,点击“确认执行”才弹出危险操作确认窗口。聊天中的“确认”回答只用于继续生成预览,不代替最终执行确认。 + +在对话历史中选择对话后,可点击“删除对话”。确认后清除该对话的轮次和暂存附件,未完成计划失效;已执行的业务操作及审计记录保留。仍有后台任务时,请先停止或等待完成再删除。 diff --git a/docs/screenshots/assistant-agent-mobile-dark.png b/docs/screenshots/assistant-agent-mobile-dark.png index ceab970..aea6027 100644 Binary files a/docs/screenshots/assistant-agent-mobile-dark.png and b/docs/screenshots/assistant-agent-mobile-dark.png differ diff --git a/docs/screenshots/assistant-client-cache.png b/docs/screenshots/assistant-client-cache.png index 23e9d12..ce8813d 100644 Binary files a/docs/screenshots/assistant-client-cache.png and b/docs/screenshots/assistant-client-cache.png differ diff --git a/docs/screenshots/assistant-delete-confirm.png b/docs/screenshots/assistant-delete-confirm.png new file mode 100644 index 0000000..03563d3 Binary files /dev/null and b/docs/screenshots/assistant-delete-confirm.png differ diff --git a/docs/screenshots/assistant-plan.png b/docs/screenshots/assistant-plan.png index e67b54f..f12a1ad 100644 Binary files a/docs/screenshots/assistant-plan.png and b/docs/screenshots/assistant-plan.png differ diff --git a/docs/screenshots/assistant-question-dialog.png b/docs/screenshots/assistant-question-dialog.png new file mode 100644 index 0000000..73ae239 Binary files /dev/null and b/docs/screenshots/assistant-question-dialog.png differ diff --git a/docs/screenshots/plan-editor-list.png b/docs/screenshots/plan-editor-list.png index c7ec0f4..71b056f 100644 Binary files a/docs/screenshots/plan-editor-list.png and b/docs/screenshots/plan-editor-list.png differ diff --git a/docs/screenshots/plan-editor-live-api.png b/docs/screenshots/plan-editor-live-api.png index 216aa0b..a395433 100644 Binary files a/docs/screenshots/plan-editor-live-api.png and b/docs/screenshots/plan-editor-live-api.png differ diff --git a/docs/screenshots/plan-editor-shell.png b/docs/screenshots/plan-editor-shell.png index 81c0c1d..64ecae1 100644 Binary files a/docs/screenshots/plan-editor-shell.png and b/docs/screenshots/plan-editor-shell.png differ diff --git a/docs/screenshots/plan-editor-timeline.png b/docs/screenshots/plan-editor-timeline.png index 2f82ce7..4c3b0b3 100644 Binary files a/docs/screenshots/plan-editor-timeline.png and b/docs/screenshots/plan-editor-timeline.png differ diff --git a/docs/screenshots/plan-editor-yaml.png b/docs/screenshots/plan-editor-yaml.png index 77f1330..2d8f5f9 100644 Binary files a/docs/screenshots/plan-editor-yaml.png and b/docs/screenshots/plan-editor-yaml.png differ diff --git a/docs/screenshots/shared-calendar-dark-care.png b/docs/screenshots/shared-calendar-dark-care.png index 041a202..ea2cc28 100644 Binary files a/docs/screenshots/shared-calendar-dark-care.png and b/docs/screenshots/shared-calendar-dark-care.png differ diff --git a/docs/screenshots/shared-calendar.png b/docs/screenshots/shared-calendar.png index 03578e9..181aede 100644 Binary files a/docs/screenshots/shared-calendar.png and b/docs/screenshots/shared-calendar.png differ diff --git a/packages/server/scripts/verify-ai.ts b/packages/server/scripts/verify-ai.ts index 458a0f5..8e21fdc 100644 --- a/packages/server/scripts/verify-ai.ts +++ b/packages/server/scripts/verify-ai.ts @@ -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; diff --git a/packages/server/src/modules/ai/ai.module.ts b/packages/server/src/modules/ai/ai.module.ts index 4178b6c..5ff0549 100644 --- a/packages/server/src/modules/ai/ai.module.ts +++ b/packages/server/src/modules/ai/ai.module.ts @@ -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))); }); diff --git a/packages/server/src/modules/ai/conversation.ts b/packages/server/src/modules/ai/conversation.ts index ddde74c..d20b494 100644 --- a/packages/server/src/modules/ai/conversation.ts +++ b/packages/server/src/modules/ai/conversation.ts @@ -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 = { create_homework: 'homeworks.create', create_notification: 'notifications.create', @@ -48,10 +24,7 @@ const aliases: Record = { }; /** 本地确定性解析只用于 mock 和原有模型之外的文件、查询入口,不新增任何模型出站数据。 */ -function localReply( - input: AiInterpretInput, - classes: { id: string; name: string }[], -): z.infer | 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 | 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), }, diff --git a/packages/server/src/modules/ai/model-planner.ts b/packages/server/src/modules/ai/model-planner.ts index be2cc5c..fa804ee 100644 --- a/packages/server/src/modules/ai/model-planner.ts +++ b/packages/server/src/modules/ai/model-planner.ts @@ -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; + 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; } diff --git a/packages/server/src/modules/ai/model-reply.ts b/packages/server/src/modules/ai/model-reply.ts new file mode 100644 index 0000000..0c5f59f --- /dev/null +++ b/packages/server/src/modules/ai/model-reply.ts @@ -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; + +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; + 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; + 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).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); +} diff --git a/packages/server/src/modules/ai/tasks.ts b/packages/server/src/modules/ai/tasks.ts index 764db9c..54e0140 100644 --- a/packages/server/src/modules/ai/tasks.ts +++ b/packages/server/src/modules/ai/tasks.ts @@ -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(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(row.input)).catch(() => + logger.warn('AI 对话已删除,暂存附件清理未完成'), + ); + return { id }; +} diff --git a/packages/web-admin/src/components/AssistantQuestions.vue b/packages/web-admin/src/components/AssistantQuestions.vue new file mode 100644 index 0000000..9b20325 --- /dev/null +++ b/packages/web-admin/src/components/AssistantQuestions.vue @@ -0,0 +1,82 @@ + + + diff --git a/packages/web-admin/src/views/AssistantView.vue b/packages/web-admin/src/views/AssistantView.vue index 88bd5af..6fdac56 100644 --- a/packages/web-admin/src/views/AssistantView.vue +++ b/packages/web-admin/src/views/AssistantView.vue @@ -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(); +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(`/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 { if (lastRequest) await send(true); } async function send(retrying = false): Promise { - 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 { 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 { - 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 { 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({ @@ -496,6 +572,7 @@ async function resumeTask(id: string, preserveHistory = false): Promise { 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 { 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(() => {
+ + 删除对话 + 更多对话 { :label="item.title || '新对话'" /> - + 新对话 { class="assistant-question" > {{ question.text }} -
- - {{ option }} - -
+ 回答问题 也可以在下方输入框自由回答。 {
+ 重试上次任务 diff --git a/scripts/ui-smoke/assistant.cjs b/scripts/ui-smoke/assistant.cjs index c984f4d..809f524 100644 --- a/scripts/ui-smoke/assistant.cjs +++ b/scripts/ui-smoke/assistant.cjs @@ -108,6 +108,124 @@ module.exports = async function runAssistantChecks({ win, target, record, waitFo ); assert.equal((await request('/homeworks?keyword=' + encodeURIComponent(title))).length, 1); record('AI 界面确认后通过原业务端点执行并显示结果', true); + const sendChat = async (content) => { + await win.webContents.executeJavaScript( + `(() => {const input=document.querySelector('.assistant-composer textarea');Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,'value').set.call(input,${JSON.stringify(content)});input.dispatchEvent(new Event('input',{bubbles:true}));})()`, + ); + assert( + await waitFor( + win, + `Array.from(document.querySelectorAll('.assistant-composer button')).some(b=>b.textContent.trim()==='发送'&&!b.disabled)`, + ), + ); + await win.webContents.executeJavaScript( + `Array.from(document.querySelectorAll('.assistant-composer button')).find(b=>b.textContent.trim()==='发送').click()`, + ); + }; + await sendChat( + JSON.stringify({ + message: '请确认要处理哪张课表?', + questions: [{ question: '请选择下一步', options: ['查看本班今天的作业'] }], + }), + ); + const questionVisible = `Array.from(document.querySelectorAll('.assistant-questions-dialog')).some(d=>d.getBoundingClientRect().height>0 && d.textContent.includes('请选择下一步'))`; + assert(await waitFor(win, questionVisible)); + await screenshot('assistant-question-dialog'); + await win.loadURL(origin + '/assistant'); + assert(await waitFor(win, questionVisible)); + const roundsBefore = await win.webContents.executeJavaScript( + `document.querySelectorAll('.assistant-message.user').length`, + ); + await win.webContents.executeJavaScript( + `document.querySelector('.assistant-questions-dialog .question-options button').click()`, + ); + assert( + await waitFor( + win, + `Array.from(document.querySelectorAll('.assistant-questions-dialog .el-dialog__footer button')).some(b=>b.textContent.trim()==='发送回答'&&!b.disabled)`, + ), + ); + await win.webContents.executeJavaScript( + `Array.from(document.querySelectorAll('.assistant-questions-dialog .el-dialog__footer button')).find(b=>b.textContent.trim()==='发送回答').click()`, + ); + assert( + await waitFor( + win, + `document.querySelectorAll('.assistant-message.user').length===${roundsBefore + 1} && Array.from(document.querySelectorAll('.assistant-composer button')).some(b=>b.textContent.trim()==='发送'&&!b.disabled)===false && !(${questionVisible})`, + ), + ); + // 输入为空时发送按钮禁用,等待后台结束由停止生成按钮消失判断。 + assert( + await waitFor( + win, + `!Array.from(document.querySelectorAll('.assistant-composer button')).some(b=>b.textContent.trim()==='停止生成')`, + ), + ); + record('模型提问弹出交互窗口,刷新可恢复,回答作为同一对话的新一轮继续', true); + const layout = await request('/time-layouts', 'POST', { + classId: cls.id, + name: title + '删除作息', + points: [], + }); + const day = await request('/class-plans', 'POST', { + classId: cls.id, + name: title + '待删除课表', + timeLayoutId: layout.id, + weekday: 1, + }); + await sendChat(JSON.stringify({ operations: [{ action: 'plans.delete', target: { id: day.id } }] })); + assert( + await waitFor( + win, + `document.querySelector('.assistant-step')?.textContent.includes(${JSON.stringify(day.name)}) && document.querySelector('.assistant-step .el-tag')?.textContent.includes('待确认')`, + ), + ); + assert( + (await request('/class-plans?classId=' + encodeURIComponent(cls.id))).some((p) => p.id === day.id), + ); + await win.webContents.executeJavaScript( + `Array.from(document.querySelectorAll('.assistant-plan-actions button')).find(b=>b.textContent.trim()==='确认执行').click()`, + ); + assert( + await waitFor( + win, + `(() => {const box=document.querySelector('.el-message-box');if(!box?.textContent.includes(${JSON.stringify(day.name)})||!box.getBoundingClientRect().height)return false;for(let node=box;node;node=node.parentElement){const style=getComputedStyle(node);if(style.display==='none'||style.visibility==='hidden'||Number(style.opacity)<0.99)return false;}return true;})()`, + ), + ); + await win.webContents.capturePage(); + await new Promise((resolve) => setTimeout(resolve, 150)); + await screenshot('assistant-delete-confirm'); + await win.webContents.executeJavaScript( + `Array.from(document.querySelectorAll('.el-message-box__btns button')).find(b=>b.textContent.trim()==='取消').click()`, + ); + assert( + (await request('/class-plans?classId=' + encodeURIComponent(cls.id))).some((p) => p.id === day.id), + ); + record('删除课表先显示预览及危险操作确认窗口,取消不会删除', true); + // 对话删除不回滚已完成的作业,也不执行其余待确认删除计划。 + const current = (await request('/ai/conversations'))[0]; + await win.webContents.executeJavaScript( + `Array.from(document.querySelectorAll('.agent-header-actions button')).find(b=>b.textContent.trim()==='删除对话').click()`, + ); + assert(await waitFor(win, `document.querySelector('.el-message-box')?.textContent.includes('删除对话')`)); + await win.webContents.executeJavaScript( + `Array.from(document.querySelectorAll('.el-message-box__btns button')).find(b=>b.textContent.trim()==='删除对话').click()`, + ); + assert( + await waitFor( + win, + `!document.querySelector('.assistant-step') && !document.querySelector('.assistant-message')`, + ), + ); + assert(!(await request('/ai/conversations')).some((c) => c.id === current.id)); + assert.equal((await request('/homeworks?keyword=' + encodeURIComponent(title))).length, 1); + assert( + (await request('/class-plans?classId=' + encodeURIComponent(cls.id))).some((p) => p.id === day.id), + ); + await request('/class-plans/' + day.id, 'DELETE'); + await request('/time-layouts/' + layout.id, 'DELETE'); + record('界面可以确认删除当前对话,轮次消失,已执行作业保留且待确认课表未删除', true); + const cachedBefore = await request('/update/client/releases'); const cacheVersion = `0.0.0-ai-${Date.now()}`; const cacheTask = JSON.stringify({ diff --git a/scripts/ui-smoke/run.mjs b/scripts/ui-smoke/run.mjs index 92329a4..3ccef25 100644 --- a/scripts/ui-smoke/run.mjs +++ b/scripts/ui-smoke/run.mjs @@ -104,9 +104,9 @@ const child = spawn(executable, [entry], { }), }); const timeout = setTimeout(() => { - console.error('[ui-smoke] 后台验收超过 120 秒,终止验证进程'); + console.error('[ui-smoke] 后台验收超过 180 秒,终止验证进程'); child.kill(); -}, 120_000); +}, 180_000); child.on('exit', async (code) => { clearTimeout(timeout); diff --git a/scripts/verify-ai-replies.cjs b/scripts/verify-ai-replies.cjs new file mode 100644 index 0000000..c8e6469 --- /dev/null +++ b/scripts/verify-ai-replies.cjs @@ -0,0 +1,55 @@ +/** 真实模型回复解析器的快速回归;不加载业务库,不访问模型服务。 */ +const fs = require('node:fs'); +const vm = require('node:vm'); +const path = require('node:path'); +const assert = require('node:assert/strict'); +const ts = require('typescript'); +const { createRequire } = require('node:module'); +const requireServer = createRequire(path.resolve(__dirname, '../packages/server/package.json')); +const output = {}; +const source = fs.readFileSync( + path.resolve(__dirname, '../packages/server/src/modules/ai/model-reply.ts'), + 'utf8', +); +vm.runInNewContext( + ts.transpileModule(source, { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }, + }).outputText, + { exports: output, require: requireServer }, +); +const parse = output.parseModelReply; +for (const sample of [ + '请确认是否删除“周一课表”?确认后我会继续。', + JSON.stringify({ message: '请确认是否删除“周一课表”?', queries: [], operations: [] }), + JSON.stringify({ questions: [{ question: '要删除哪张课表?', options: ['周一', '周五'] }] }), + JSON.stringify({ question: '请选择要删除的课表。' }), + JSON.stringify({ questions: ['请选择要删除的课表。'] }), + JSON.stringify({ + questions: [{ text: '请选择课表', options: [{ label: '周一', description: '每周一' }] }], + }), + JSON.stringify('Would you like to continue?'), +]) { + const reply = parse(sample); + assert(reply.questions.length > 0); + assert.equal(reply.operations.length, 0); + assert.equal(reply.queries.length, 0); +} +assert(parse('请确认是否删除课表?').questions[0].options.includes('继续生成操作预览')); +const deletion = { + message: '请确认删除', + operations: [{ action: 'plans.delete', target: { id: 'existing-plan' } }], +}; +const plan = parse(JSON.stringify(deletion)); +assert.equal(plan.operations[0].target.id, 'existing-plan'); +assert(!plan.questions?.length); +const mixed = parse(JSON.stringify({ ...deletion, questions: [{ text: '请选择课表' }] })); +assert.equal(mixed.operations.length, 0); +for (const sample of [ + '空白', + '已删除课表。', + '{"message":"确认删除吗?"', + '{"operations":[{"action":"plans.delete","target":{"id":10}}]}', + '{"operations":{}}', +]) + assert.throws(() => parse(sample)); +console.log('PASS:追问兼容、删除预览保留、问题优先及损坏协议拒绝');