Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
195ee3b90a |
No files matched your search
@@ -45,6 +45,10 @@ description: 多轮对话、文件处理与操作计划,核对后通过现有
|
|||||||
|
|
||||||
## 对话与轮次
|
## 对话与轮次
|
||||||
|
|
||||||
对话历史按账号保存在服务器。每次发送是一轮,右侧横条可跳转轮次,新对话独立保存。助手缺少必要信息时会显示问题卡片,可选答案或在输入框自由回答;追问阶段不执行写入。格式自动修正每轮至多一次,失败后保留明确的重试入口。
|
对话历史按账号保存在服务器。每次发送是一轮,右侧横条可跳转轮次,新对话独立保存。助手缺少必要信息时会弹出提问窗口,可选答案或自由回答。关闭窗口后可通过历史消息中的“回答问题”再次打开,刷新页面也能恢复待回答的问题;追问阶段不执行写入。格式自动修正每轮至多一次,失败后保留明确的重试入口。
|
||||||
|
|
||||||
勾选“本轮明确替换当前待确认计划”后,新计划形成时只使选中的旧计划失效,历史记录保留。不勾选时保留旧计划;新建对话不影响其他对话的计划。
|
勾选“本轮明确替换当前待确认计划”后,新计划形成时只使选中的旧计划失效,历史记录保留。不勾选时保留旧计划;新建对话不影响其他对话的计划。
|
||||||
|
|
||||||
|
删除课表等危险操作时,目标明确后会先生成变更预览,点击“确认执行”才弹出危险操作确认窗口。聊天中的“确认”回答只用于继续生成预览,不代替最终执行确认。
|
||||||
|
|
||||||
|
在对话历史中选择对话后,可点击“删除对话”。确认后清除该对话的轮次和暂存附件,未完成计划失效;已执行的业务操作及审计记录保留。仍有后台任务时,请先停止或等待完成再删除。
|
||||||
|
Before Width: | Height: | Size: 50 KiB After Width: | Height: | Size: 47 KiB |
|
Before Width: | Height: | Size: 84 KiB After Width: | Height: | Size: 81 KiB |
|
After Width: | Height: | Size: 83 KiB |
|
Before Width: | Height: | Size: 81 KiB After Width: | Height: | Size: 82 KiB |
|
After Width: | Height: | Size: 86 KiB |
|
Before Width: | Height: | Size: 71 KiB After Width: | Height: | Size: 105 KiB |
|
Before Width: | Height: | Size: 106 KiB After Width: | Height: | Size: 104 KiB |
|
Before Width: | Height: | Size: 133 KiB After Width: | Height: | Size: 133 KiB |
|
Before Width: | Height: | Size: 96 KiB After Width: | Height: | Size: 96 KiB |
|
Before Width: | Height: | Size: 139 KiB After Width: | Height: | Size: 135 KiB |
|
Before Width: | Height: | Size: 94 KiB After Width: | Height: | Size: 93 KiB |
|
Before Width: | Height: | Size: 69 KiB After Width: | Height: | Size: 69 KiB |
@@ -813,6 +813,21 @@ try {
|
|||||||
assert.equal(incompleteBody.code, 'AI_TASK_INCOMPLETE');
|
assert.equal(incompleteBody.code, 'AI_TASK_INCOMPLETE');
|
||||||
assert(!incompleteBody.message.includes('换一种说法'));
|
assert(!incompleteBody.message.includes('换一种说法'));
|
||||||
check('持续异常保持明确未完成状态和重试入口,不伪报执行成功');
|
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: ['数学', '语文'] }] });
|
modelReplies.push({ questions: [{ id: 'subject', text: '请选择科目', options: ['数学', '语文'] }] });
|
||||||
const clarification = await api('/ai/interpret', teacher, 'POST', { text: '给这个班布置作业' });
|
const clarification = await api('/ai/interpret', teacher, 'POST', { text: '给这个班布置作业' });
|
||||||
assert.equal(clarification.planId, null);
|
assert.equal(clarification.planId, null);
|
||||||
@@ -870,6 +885,10 @@ try {
|
|||||||
});
|
});
|
||||||
const reader = connection.body!.getReader();
|
const reader = connection.body!.getReader();
|
||||||
assert((await reader.read()).value!.length > 0);
|
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();
|
await reader.cancel();
|
||||||
releaseModel();
|
releaseModel();
|
||||||
modelHold = undefined;
|
modelHold = undefined;
|
||||||
@@ -1184,6 +1203,63 @@ try {
|
|||||||
assert.notEqual(tf.find((f) => f.path === path)!.id, af.find((f) => f.path === path)!.id);
|
assert.notEqual(tf.find((f) => f.path === path)!.id, af.find((f) => f.path === path)!.id);
|
||||||
}
|
}
|
||||||
check('三层目录自动补建父目录,同名目录按教师身份独立保存');
|
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} 项`);
|
console.log(`AI 隔离验收通过:${checks} 项`);
|
||||||
} finally {
|
} finally {
|
||||||
globalThis.fetch = realFetch;
|
globalThis.fetch = realFetch;
|
||||||
|
|||||||
@@ -27,6 +27,14 @@ import { setTimeout as delay } from 'node:timers/promises';
|
|||||||
|
|
||||||
const router = Router();
|
const router = Router();
|
||||||
router.use(authenticate());
|
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) => {
|
router.post('/conversations', requirePermission('ai:use'), async (req, res) => {
|
||||||
sendOk(res, await tasks.createConversation(getAuthUser(req)));
|
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 {
|
import {
|
||||||
dayKeyLocal,
|
dayKeyLocal,
|
||||||
type AiInterpretResult,
|
type AiInterpretResult,
|
||||||
@@ -17,30 +17,6 @@ import { planWithModel, sanitizePrompt, type AgentRun } from './model-planner.js
|
|||||||
import { getAiSettings } from './ai.service.js';
|
import { getAiSettings } from './ai.service.js';
|
||||||
import type { AiInterpretInput } from './ai.schemas.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> = {
|
const aliases: Record<string, string> = {
|
||||||
create_homework: 'homeworks.create',
|
create_homework: 'homeworks.create',
|
||||||
create_notification: 'notifications.create',
|
create_notification: 'notifications.create',
|
||||||
@@ -48,10 +24,7 @@ const aliases: Record<string, string> = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/** 本地确定性解析只用于 mock 和原有模型之外的文件、查询入口,不新增任何模型出站数据。 */
|
/** 本地确定性解析只用于 mock 和原有模型之外的文件、查询入口,不新增任何模型出站数据。 */
|
||||||
function localReply(
|
function localReply(input: AiInterpretInput, classes: { id: string; name: string }[]): ModelReply | null {
|
||||||
input: AiInterpretInput,
|
|
||||||
classes: { id: string; name: string }[],
|
|
||||||
): z.infer<typeof replySchema> | null {
|
|
||||||
const classId =
|
const classId =
|
||||||
input.classId ||
|
input.classId ||
|
||||||
classes.find((item) => input.text.includes(item.name))?.id ||
|
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')
|
const classes = tools.some((item) => item.action === 'classes.list')
|
||||||
? ((await runRead(user, { action: 'classes.list' })) as { id: string; name: string }[])
|
? ((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') {
|
if (settings.provider === 'mock') {
|
||||||
try {
|
try {
|
||||||
reply = replySchema.parse(JSON.parse(input.text));
|
reply = normalizeModelReply(JSON.parse(input.text));
|
||||||
} catch {
|
} catch {
|
||||||
/* 自然语言示例继续走本地解析。 */
|
/* 自然语言示例继续走本地解析。 */
|
||||||
}
|
}
|
||||||
@@ -186,6 +159,7 @@ export async function interpretConversation(
|
|||||||
});
|
});
|
||||||
else reply = replySchema.parse({ message: '离线示例未识别此任务,请配置模型或补充具体操作。' });
|
else reply = replySchema.parse({ message: '离线示例未识别此任务,请配置模型或补充具体操作。' });
|
||||||
}
|
}
|
||||||
|
reply = normalizeModelReply(reply);
|
||||||
if (reply.questions?.length)
|
if (reply.questions?.length)
|
||||||
return {
|
return {
|
||||||
planId: null,
|
planId: null,
|
||||||
@@ -252,7 +226,7 @@ export async function interpretConversation(
|
|||||||
{ role: 'assistant' as const, content: JSON.stringify(reply).slice(0, 8000) },
|
{ role: 'assistant' as const, content: JSON.stringify(reply).slice(0, 8000) },
|
||||||
{
|
{
|
||||||
role: 'user' as const,
|
role: 'user' as const,
|
||||||
content: `预览校验未通过:${sanitizePrompt(error.message)}。请查询真实数据后修正参数,不能省略用户要求。信息不足时提出具体问题。`,
|
content: `预览校验未通过:${sanitizePrompt(error.message)}。请查询真实数据后修正参数,不能省略用户要求。信息不足时通过 questions:[{id,text,options?}] 提出具体问题,并清空 operations 和 queries。`,
|
||||||
},
|
},
|
||||||
].slice(-20),
|
].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 { setTimeout as delay } from 'node:timers/promises';
|
||||||
import {
|
import {
|
||||||
dayKeyLocal,
|
dayKeyLocal,
|
||||||
@@ -18,50 +18,7 @@ import { redact } from './business-read.js';
|
|||||||
import type { AiInterpretInput } from './ai.schemas.js';
|
import type { AiInterpretInput } from './ai.schemas.js';
|
||||||
import { modelEndpoint, readCompletion } from './model-transport.js';
|
import { modelEndpoint, readCompletion } from './model-transport.js';
|
||||||
|
|
||||||
const operationSchema = z
|
export { parseModelReply } from './model-reply.js';
|
||||||
.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));
|
|
||||||
}
|
|
||||||
|
|
||||||
function visibleMessage(content: string): string | undefined {
|
function visibleMessage(content: string): string | undefined {
|
||||||
const match = content.match(/"message"\s*:\s*"((?:[^"\\]|\\.)*)/);
|
const match = content.match(/"message"\s*:\s*"((?:[^"\\]|\\.)*)/);
|
||||||
@@ -107,9 +64,11 @@ export async function planWithModel(
|
|||||||
{
|
{
|
||||||
role: 'system',
|
role: 'system',
|
||||||
content: [
|
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 只写简短进度或给用户的回复。',
|
'例如普通回复:{"message":"你好,需要处理什么?","queries":[],"operations":[]};查询:{"message":"正在查询班级","queries":[{"action":"classes.list"}],"operations":[]}。禁止 Markdown 围栏,message 只写简短进度或给用户的回复。',
|
||||||
'缺少用户才能提供的必要信息时,返回 questions:[{id,text,options?}],operations 和 queries 必须为空,等待用户回答。',
|
'缺少用户才能提供的必要信息时,返回 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。信息不足时追问。',
|
'queries 只能查询,operations 是待确认写操作,不能声称已执行。先查询真实 id 和现状,再规划修改;不猜测班级、账号、学生、课程和时间点 id。信息不足时追问。',
|
||||||
'仅可选择工具目录中的 action。工具 schema.target 列出路径参数,schema.params 是 params 的 JSON Schema。查询条件放 query。所有数据和动作遵循操作者的实时权限。',
|
'仅可选择工具目录中的 action。工具 schema.target 列出路径参数,schema.params 是 params 的 JSON Schema。查询条件放 query。所有数据和动作遵循操作者的实时权限。',
|
||||||
'数据库备份/恢复/清空/切换/SQL、服务器配置/启停/升级和密钥维护禁止执行。密码字段留空,由用户在专门表单输入。',
|
'数据库备份/恢复/清空/切换/SQL、服务器配置/启停/升级和密钥维护禁止执行。密码字段留空,由用户在专门表单输入。',
|
||||||
@@ -178,7 +137,7 @@ export async function planWithModel(
|
|||||||
'AI_PROVIDER_ERROR',
|
'AI_PROVIDER_ERROR',
|
||||||
`模型服务暂不可用(HTTP ${response.status}),请检查服务地址、模型与密钥。任务尚未执行。`,
|
`模型服务暂不可用(HTTP ${response.status}),请检查服务地址、模型与密钥。任务尚未执行。`,
|
||||||
);
|
);
|
||||||
let reply: z.infer<typeof replySchema>;
|
let reply: ModelReply;
|
||||||
try {
|
try {
|
||||||
let published = '';
|
let published = '';
|
||||||
let lastReasoningUpdate = 0;
|
let lastReasoningUpdate = 0;
|
||||||
@@ -212,7 +171,7 @@ export async function planWithModel(
|
|||||||
messages.push({
|
messages.push({
|
||||||
role: 'user',
|
role: 'user',
|
||||||
content:
|
content:
|
||||||
'上一轮输出未通过校验或被截断。请重新输出完整 JSON 对象,包含 message 字符串、queries 数组和 operations 数组;不使用 Markdown,不添加解释。不确定的业务参数请在 message 中追问,不猜测。',
|
'上一轮输出未通过校验或被截断。请重新输出完整 JSON 对象,包含 message 字符串、queries 数组和 operations 数组;不使用 Markdown,不添加解释。缺少用户信息时返回 questions:[{id,text,options?}],并令 queries 和 operations 为空;不要在 message 中反复询问确认,不猜测业务参数。',
|
||||||
});
|
});
|
||||||
continue;
|
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 type { AiAgentEvent, AiConversationResult, AiTaskDto } from '@classhelper/shared';
|
||||||
import { prisma } from '../../lib/db.js';
|
import { prisma } from '../../lib/db.js';
|
||||||
import { ApiError } from '../../lib/http.js';
|
import { ApiError } from '../../lib/http.js';
|
||||||
|
import { logger } from '../../lib/logger.js';
|
||||||
import { assertPermission, loadAuthPrincipal } from '../../lib/authz/index.js';
|
import { assertPermission, loadAuthPrincipal } from '../../lib/authz/index.js';
|
||||||
import { loadSessionUser } from '../../lib/authz/session.js';
|
import { loadSessionUser } from '../../lib/authz/session.js';
|
||||||
import { encryptSecret, decryptSecret } from '../../lib/secrets.js';
|
import { encryptSecret, decryptSecret } from '../../lib/secrets.js';
|
||||||
@@ -141,14 +142,28 @@ export async function createTask(user: TokenPayload, input: AiInterpretInput) {
|
|||||||
messages: context.map((item) => ({ ...item, content: sanitizePrompt(item.content).slice(0, 8000) })),
|
messages: context.map((item) => ({ ...item, content: sanitizePrompt(item.content).slice(0, 8000) })),
|
||||||
};
|
};
|
||||||
Object.assign(safe, { accessStamp: await accessStamp(user) });
|
Object.assign(safe, { accessStamp: await accessStamp(user) });
|
||||||
const row = await prisma.aiTask.create({
|
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: {
|
data: {
|
||||||
userId: user.sub,
|
userId: user.sub,
|
||||||
conversationId: conversation.id,
|
conversationId: conversation.id,
|
||||||
turnNumber: (previous.at(-1)?.turnNumber ?? 0) + 1,
|
turnNumber: (latest?.turnNumber ?? 0) + 1,
|
||||||
input: encryptSecret(JSON.stringify(safe)),
|
input: encryptSecret(JSON.stringify(safe)),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
});
|
||||||
if (last && inherited?.length) {
|
if (last && inherited?.length) {
|
||||||
for (const attachment of inherited) {
|
for (const attachment of inherited) {
|
||||||
const source = attachmentPath(last.id, attachment.id),
|
const source = attachmentPath(last.id, attachment.id),
|
||||||
@@ -158,10 +173,6 @@ export async function createTask(user: TokenPayload, input: AiInterpretInput) {
|
|||||||
await fsp.copyFile(source, target);
|
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 };
|
return { id: row.id, conversationId: conversation.id };
|
||||||
}
|
}
|
||||||
export async function stageAttachment(
|
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)));
|
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 { hashAttachment, importFileBase64 } from '@/composables/assistantFiles';
|
||||||
import { findClassInSession } from '@/composables/useClassInSession';
|
import { findClassInSession } from '@/composables/useClassInSession';
|
||||||
import AssistantData from '@/components/AssistantData.vue';
|
import AssistantData from '@/components/AssistantData.vue';
|
||||||
|
import AssistantQuestions from '@/components/AssistantQuestions.vue';
|
||||||
import UrgentClassWarning from '@/components/UrgentClassWarning.vue';
|
import UrgentClassWarning from '@/components/UrgentClassWarning.vue';
|
||||||
import { observeTask } from '@/composables/assistantStream';
|
import { observeTask } from '@/composables/assistantStream';
|
||||||
interface ChatMessage {
|
interface ChatMessage {
|
||||||
@@ -32,22 +33,44 @@ interface ChatMessage {
|
|||||||
const auth = useAuthStore();
|
const auth = useAuthStore();
|
||||||
let viewEpoch = 0;
|
let viewEpoch = 0;
|
||||||
const replacePlan = ref(false);
|
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 conversationId = ref('');
|
||||||
const conversations = ref<{ id: string; title: string }[]>([]);
|
const conversations = ref<{ id: string; title: string }[]>([]);
|
||||||
|
let conversationListRequest = 0;
|
||||||
async function loadConversations() {
|
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) {
|
async function openConversation(id: string) {
|
||||||
if ((busy.value || executing.value) && !observing) return;
|
if ((busy.value || executing.value) && !observing) return;
|
||||||
viewEpoch++;
|
questionsVisible.value = false;
|
||||||
|
questionSource.value = undefined;
|
||||||
|
const epoch = ++viewEpoch;
|
||||||
controller?.abort();
|
controller?.abort();
|
||||||
busy.value = false;
|
busy.value = false;
|
||||||
executing.value = false;
|
executing.value = false;
|
||||||
|
questionsVisible.value = false;
|
||||||
|
questionSource.value = undefined;
|
||||||
conversationId.value = id;
|
conversationId.value = id;
|
||||||
attachments.value = [];
|
attachments.value = [];
|
||||||
files.clear();
|
files.clear();
|
||||||
replacePlan.value = false;
|
replacePlan.value = false;
|
||||||
const turns = await api.get<AiTaskDto[]>(`/ai/conversations/${id}`);
|
const turns = await api.get<AiTaskDto[]>(`/ai/conversations/${id}`);
|
||||||
|
if (epoch !== viewEpoch || disposed) return;
|
||||||
messages.value = turns.flatMap((t) => [
|
messages.value = turns.flatMap((t) => [
|
||||||
{ role: 'user' as const, content: t.text },
|
{ role: 'user' as const, content: t.text },
|
||||||
{
|
{
|
||||||
@@ -67,6 +90,48 @@ async function openConversation(id: string) {
|
|||||||
lastRequest = last ? { text: last.text, conversationId: id } : undefined;
|
lastRequest = last ? { text: last.text, conversationId: id } : undefined;
|
||||||
clearCredentials();
|
clearCredentials();
|
||||||
if (last && ['planning', 'executing'].includes(last.state)) await resumeTask(last.id, true);
|
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() {
|
async function olderConversations() {
|
||||||
const older = await api.get<{ id: string; title: string }[]>('/ai/conversations', {
|
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);
|
if (lastRequest) await send(true);
|
||||||
}
|
}
|
||||||
async function send(retrying = false): Promise<void> {
|
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 epoch = viewEpoch;
|
||||||
const supersedesTaskId = replacePlan.value && pending.value ? taskId.value : undefined;
|
const supersedesTaskId = replacePlan.value && pending.value ? taskId.value : undefined;
|
||||||
busy.value = true;
|
busy.value = true;
|
||||||
@@ -310,6 +382,7 @@ async function send(retrying = false): Promise<void> {
|
|||||||
observing = false;
|
observing = false;
|
||||||
if (message) message.state = controller.signal.aborted || error.value ? 'stopped' : 'done';
|
if (message) message.state = controller.signal.aborted || error.value ? 'stopped' : 'done';
|
||||||
busy.value = false;
|
busy.value = false;
|
||||||
|
if (message?.result?.questions?.length && !disposed) showQuestions(message);
|
||||||
if (!disposed) {
|
if (!disposed) {
|
||||||
taskHistory.value = await aiApi.tasks().catch(() => taskHistory.value);
|
taskHistory.value = await aiApi.tasks().catch(() => taskHistory.value);
|
||||||
await loadConversations();
|
await loadConversations();
|
||||||
@@ -324,7 +397,9 @@ function composerKey(event: KeyboardEvent): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
async function newConversation(): Promise<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++;
|
viewEpoch++;
|
||||||
controller?.abort();
|
controller?.abort();
|
||||||
busy.value = false;
|
busy.value = false;
|
||||||
@@ -481,6 +556,7 @@ async function resumeTask(id: string, preserveHistory = false): Promise<void> {
|
|||||||
error.value = '';
|
error.value = '';
|
||||||
const epoch = viewEpoch;
|
const epoch = viewEpoch;
|
||||||
const saved = await aiApi.task(id);
|
const saved = await aiApi.task(id);
|
||||||
|
if (disposed || epoch !== viewEpoch) return;
|
||||||
taskId.value = id;
|
taskId.value = id;
|
||||||
lastRequest = { text: saved.text };
|
lastRequest = { text: saved.text };
|
||||||
const message = reactive<ChatMessage>({
|
const message = reactive<ChatMessage>({
|
||||||
@@ -496,6 +572,7 @@ async function resumeTask(id: string, preserveHistory = false): Promise<void> {
|
|||||||
clearCredentials();
|
clearCredentials();
|
||||||
if (saved.error) error.value = saved.error;
|
if (saved.error) error.value = saved.error;
|
||||||
if (!['planning', 'executing'].includes(saved.state)) {
|
if (!['planning', 'executing'].includes(saved.state)) {
|
||||||
|
if (saved.state === 'waiting_input') showQuestions(message);
|
||||||
await scroll();
|
await scroll();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -530,6 +607,7 @@ async function resumeTask(id: string, preserveHistory = false): Promise<void> {
|
|||||||
message.state = error.value ? 'stopped' : 'done';
|
message.state = error.value ? 'stopped' : 'done';
|
||||||
busy.value = false;
|
busy.value = false;
|
||||||
executing.value = false;
|
executing.value = false;
|
||||||
|
if (message.result?.questions?.length && !disposed) showQuestions(message);
|
||||||
await scroll();
|
await scroll();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -574,12 +652,20 @@ onBeforeUnmount(() => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="agent-header-actions">
|
<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-button v-if="conversations.length >= 30" @click="olderConversations">更多对话</el-button>
|
||||||
<el-select
|
<el-select
|
||||||
v-if="conversations.length"
|
v-if="conversations.length"
|
||||||
:model-value="conversationId"
|
:model-value="conversationId"
|
||||||
placeholder="对话历史"
|
placeholder="对话历史"
|
||||||
:disabled="(busy || executing) && !observing"
|
:disabled="deletingConversation || ((busy || executing) && !observing)"
|
||||||
@change="openConversation"
|
@change="openConversation"
|
||||||
>
|
>
|
||||||
<el-option
|
<el-option
|
||||||
@@ -589,7 +675,10 @@ onBeforeUnmount(() => {
|
|||||||
:label="item.title || '新对话'"
|
:label="item.title || '新对话'"
|
||||||
/>
|
/>
|
||||||
</el-select>
|
</el-select>
|
||||||
<el-button :disabled="hashing || ((busy || executing) && !observing)" @click="newConversation">
|
<el-button
|
||||||
|
:disabled="deletingConversation || hashing || ((busy || executing) && !observing)"
|
||||||
|
@click="newConversation"
|
||||||
|
>
|
||||||
新对话
|
新对话
|
||||||
</el-button>
|
</el-button>
|
||||||
<el-select
|
<el-select
|
||||||
@@ -681,19 +770,7 @@ onBeforeUnmount(() => {
|
|||||||
class="assistant-question"
|
class="assistant-question"
|
||||||
>
|
>
|
||||||
<strong>{{ question.text }}</strong>
|
<strong>{{ question.text }}</strong>
|
||||||
<div class="question-options">
|
<el-button :disabled="busy || executing" @click="showQuestions(message)">回答问题</el-button>
|
||||||
<el-button
|
|
||||||
v-for="option in question.options || []"
|
|
||||||
:key="option"
|
|
||||||
:disabled="busy"
|
|
||||||
@click="
|
|
||||||
text = question.text + ':' + option;
|
|
||||||
send();
|
|
||||||
"
|
|
||||||
>
|
|
||||||
{{ option }}
|
|
||||||
</el-button>
|
|
||||||
</div>
|
|
||||||
<small>也可以在下方输入框自由回答。</small>
|
<small>也可以在下方输入框自由回答。</small>
|
||||||
</el-card>
|
</el-card>
|
||||||
<el-button
|
<el-button
|
||||||
@@ -813,6 +890,11 @@ onBeforeUnmount(() => {
|
|||||||
<el-progress v-if="executing && progress > 0" :percentage="progress" />
|
<el-progress v-if="executing && progress > 0" :percentage="progress" />
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</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-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">
|
<el-button v-if="error && !active?.steps.length && !busy && !executing" @click="retryTask">
|
||||||
重试上次任务
|
重试上次任务
|
||||||
|
|||||||
@@ -108,6 +108,124 @@ module.exports = async function runAssistantChecks({ win, target, record, waitFo
|
|||||||
);
|
);
|
||||||
assert.equal((await request('/homeworks?keyword=' + encodeURIComponent(title))).length, 1);
|
assert.equal((await request('/homeworks?keyword=' + encodeURIComponent(title))).length, 1);
|
||||||
record('AI 界面确认后通过原业务端点执行并显示结果', true);
|
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 cachedBefore = await request('/update/client/releases');
|
||||||
const cacheVersion = `0.0.0-ai-${Date.now()}`;
|
const cacheVersion = `0.0.0-ai-${Date.now()}`;
|
||||||
const cacheTask = JSON.stringify({
|
const cacheTask = JSON.stringify({
|
||||||
|
|||||||
@@ -104,9 +104,9 @@ const child = spawn(executable, [entry], {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
const timeout = setTimeout(() => {
|
const timeout = setTimeout(() => {
|
||||||
console.error('[ui-smoke] 后台验收超过 120 秒,终止验证进程');
|
console.error('[ui-smoke] 后台验收超过 180 秒,终止验证进程');
|
||||||
child.kill();
|
child.kill();
|
||||||
}, 120_000);
|
}, 180_000);
|
||||||
|
|
||||||
child.on('exit', async (code) => {
|
child.on('exit', async (code) => {
|
||||||
clearTimeout(timeout);
|
clearTimeout(timeout);
|
||||||
|
|||||||
@@ -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:追问兼容、删除预览保留、问题优先及损坏协议拒绝');
|
||||||