feat: 完善 AI 对话、每日作息与课件目录体验

新增持久化对话、追问卡片和轮次导航;支持每日子时间表、切换保留课程与自动课间;完善课件逐层目录、学期周次同步及两端自适应。同步迁移、文档和回归截图。

验证:后端 262/262、AI 55 项、Web 81/81、桌面 71/71、授权 23 项;构建、类型、Lint 与文档检查通过。
This commit is contained in:
LoveChengke committed 2026-11-08 09:07:10 +08:00
1 parent cdb64c5499
commit 9351203deb
59 files changed
+1277 -149

No files matched your search

+6
View File
@@ -42,3 +42,9 @@ description: 多轮对话、文件处理与操作计划,核对后通过现有
`mock` 用于离线示例和自动化验收,真实服务失败不会自动切换为 mock 或发布内容。`pnpm verify:ai` 使用临时数据库和模型 stub 验证权限、计划、附件和重复提交,不访问外网。
相关功能:[课件](courseware.md)、[课表](schedules.md)、[作业](homeworks.md)、[通知](notifications.md)、[角色与权限](../dev/permissions.md)。
## 对话与轮次
对话历史按账号保存在服务器。每次发送是一轮,右侧横条可跳转轮次,新对话独立保存。助手缺少必要信息时会显示问题卡片,可选答案或在输入框自由回答;追问阶段不执行写入。格式自动修正每轮至多一次,失败后保留明确的重试入口。
勾选“本轮明确替换当前待确认计划”后,新计划形成时只使选中的旧计划失效,历史记录保留。不勾选时保留旧计划;新建对话不影响其他对话的计划。
+4
View File
@@ -40,3 +40,7 @@
使用反向代理时,需允许课件上传大小和足够的读写超时。仓库的 Nginx 样例单独为 `/api/courseware/` 配置 512 MB 和 1800 秒超时,其他接口维持原有大小限制。
开发验收:`pnpm verify:courseware` 自动使用隔离数据库和临时文件目录,不读取或向真实班级发送课件。
## 文件夹浏览
课件默认按文件夹逐层浏览,只显示当前层文件和直属子目录。使用面包屑或返回上级切换目录;多位教师的目录按教师身份区分。上传与新建目录默认使用当前位置,未分类文件位于根目录。日期归档视图仍可用于按日期查找文件。
+6
View File
@@ -51,3 +51,9 @@ Web 管理端统一从「教学事务 → 课表档案」查看周课表并编
离线导入完整 ClassIsland 档案可创建班级自有作息,不依赖在线联动插件。
完整导入保留 1–9 周轮换、空课、停用、群组和预定;旧预览界面的单双周展示不代表新模型只能表达双周。
见[表格与课表导入](imports.md)。修改后广播 schedule:updated,客户端刷新。
## 每日作息差异
导入的每日作息不一致时,时间表按日期生成独立子表,同日单双周也可分别维护。子表独立保存完整作息,父级用于归组。周视图按课时对齐;点击日期或课程后,时间列显示对应日期的作息,点击时间列标题清除选择后显示带星期标记的差异时间。切换子表保留可对应的课程,节数不足时阻止切换并保留原草稿。
导入或保存时间表时自动补齐两节课之间的空白,包括午休。已有命名休息、活动及显式空课保留,不在最后一节之后追加休息。旧混合时间表请使用原文件预览后重新导入,不自动猜测空课归属。
Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 105 KiB

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 107 KiB

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 131 KiB

After

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 100 KiB

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 139 KiB

After

Width:  |  Height:  |  Size: 139 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 93 KiB

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 KiB

After

Width:  |  Height:  |  Size: 69 KiB

@@ -83,6 +83,59 @@ export async function runQuickSmoke(win: BrowserWindow): Promise<void> {
return result.detail;
});
}
await check('主窗口最小与常规尺寸、深浅主题及关怀字号无页面横向溢出', async () => {
const bounds = win.getContentBounds();
const appearance = await win.webContents.executeJavaScript(
`({className:document.documentElement.className,style:document.documentElement.getAttribute('style')})`,
);
const shots = path.resolve(app.getAppPath(), '../../docs/screenshots/desktop-responsive');
fs.mkdirSync(shots, { recursive: true });
await win.webContents.executeJavaScript('window.__classhelperSmoke__.islandEditorSmoke(true)');
try {
for (const [width, height] of [
[1000, 540],
[1242, 582],
[1920, 1080],
])
for (const theme of ['light', 'dark']) {
win.setContentSize(width!, height!);
await win.webContents.executeJavaScript(
`document.documentElement.classList.toggle('dark',${theme === 'dark'});document.documentElement.classList.toggle('care-mode',${theme === 'dark'});document.documentElement.style.setProperty('--ch-font-scale',${JSON.stringify(theme === 'dark' ? '1.5' : '1')})`,
);
for (const route of [
'/schedule',
'/homeworks',
'/notifications',
'/grades',
'/courseware',
'/settings/general',
'/settings/appearance',
'/settings/island',
'/settings/island/editor',
'/settings/reminder',
'/settings/account',
'/settings/about',
]) {
await win.webContents.executeJavaScript(`location.hash=${JSON.stringify('#' + route)}`);
await new Promise((resolve) => setTimeout(resolve, 150));
if (
!(await win.webContents.executeJavaScript('document.documentElement.scrollWidth<=innerWidth+1'))
)
throw new Error(`${route} ${width} ${theme} 页面溢出`);
}
fs.writeFileSync(
path.join(shots, `main-${width}-${theme}.png`),
(await win.webContents.capturePage()).toPNG(),
);
}
} finally {
await win.webContents.executeJavaScript(
`document.documentElement.className=${JSON.stringify(appearance.className)};document.documentElement.setAttribute('style',${JSON.stringify(appearance.style || '')});window.__classhelperSmoke__.islandEditorSmoke(false)`,
);
win.setContentSize(bounds.width, bounds.height);
}
return '1000×540、1242×582、1920×1080,截图保存在 docs/screenshots/desktop-responsive';
});
await verifyAgentSmoke(check);
await verifyLayoutSmoke(check);
await verifyCoursewareSmoke(check);
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { countDates } from '@classhelper/ui';
import { countDates, CoursewareFolders } from '@classhelper/ui';
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import {
@@ -24,11 +24,16 @@ async function refreshLocal() {
// 两个来源的教师与目录不通用,切换时清空,避免看到空列表却找不到原因。
watch(library, () => {
teacher.value = '';
folderPath.value = '';
folderOwner.value = '';
});
const items = ref<CoursewareDto[]>([]),
loading = ref(false),
offline = ref(false),
error = ref('');
const folderPath = ref(''),
folderOwner = ref(''),
grouping = ref('folder');
const query = ref(''),
category = ref(''),
date = ref(''),
@@ -38,6 +43,11 @@ const dateSource = computed(() =>
source.value.filter(
(item) =>
(!query.value || `${item.name} ${item.teacher.name}`.includes(query.value)) &&
(grouping.value !== 'folder' ||
((item.folderPath || '') === folderPath.value &&
(folderOwner.value
? item.teacher.id === folderOwner.value
: new Set(items.value.map((i) => i.teacher.id)).size <= 1))) &&
(!category.value || item.category === category.value) &&
(!teacher.value || item.teacher.name === teacher.value),
),
@@ -112,6 +122,16 @@ onUnmounted(() => {
</script>
<template>
<div class="page courseware-page">
<el-radio-group v-model="grouping">
<el-radio-button value="folder">文件夹</el-radio-button>
<el-radio-button value="date">日期归档</el-radio-button>
</el-radio-group>
<CoursewareFolders
v-if="grouping === 'folder'"
v-model:path="folderPath"
v-model:owner="folderOwner"
:items="source"
/>
<header class="page-header">
<div>
<h2 class="page-title">课件</h2>
@@ -219,7 +219,7 @@ onMounted(async () => {
}
.about-extra {
margin-left: auto;
margin-left: 12px;
margin-right: 12px;
font-size: 12px;
font-weight: 400;
@@ -0,0 +1,8 @@
ALTER TABLE "TimeLayout" ADD COLUMN "parentId" TEXT;
ALTER TABLE "TimeLayoutItem" ADD COLUMN "slotKey" TEXT NOT NULL DEFAULT '';
ALTER TABLE "TimeLayoutItem" ADD COLUMN "isAutoBreak" BOOLEAN NOT NULL DEFAULT false;
ALTER TABLE "AiTask" ADD COLUMN "conversationId" TEXT;
ALTER TABLE "AiTask" ADD COLUMN "turnNumber" INTEGER NOT NULL DEFAULT 1;
CREATE UNIQUE INDEX "AiTask_conversationId_turnNumber_key" ON "AiTask"("conversationId", "turnNumber");
CREATE TABLE "AiConversation" ("id" TEXT NOT NULL PRIMARY KEY, "userId" TEXT NOT NULL, "title" TEXT NOT NULL DEFAULT '', "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, "updatedAt" DATETIME NOT NULL);
CREATE INDEX "AiConversation_userId_updatedAt_idx" ON "AiConversation"("userId", "updatedAt");
+16
View File
@@ -401,6 +401,7 @@ model NotificationRead {
/// 课表时间配置(ClassIsland 同款 JSON 导入后的节次时间表)
model TimeLayout {
parentId String?
id String @id @default(cuid())
classId String?
name String
@@ -648,6 +649,8 @@ model Exam {
/// 服务端不用单机 Profile:全校共享时间表 + 班级日课表替代档案。
model TimeLayoutItem {
slotKey String @default("")
isAutoBreak Boolean @default(false)
id String @id @default(cuid())
timeLayoutId String
position Int
@@ -832,6 +835,9 @@ model AiPlanStep {
/// 持久化后台任务;输入、结果和阶段消息加密,连接断开不取消任务。
model AiTask {
conversationId String?
turnNumber Int @default(1)
@@unique([conversationId, turnNumber])
id String @id @default(cuid())
userId String
state String @default("preparing")
@@ -844,3 +850,13 @@ model AiTask {
@@index([userId, createdAt])
}
/// 账号所属对话;内容仍使用 AiTask 的加密输入与结果。
model AiConversation {
id String @id @default(cuid())
userId String
title String @default("")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([userId, updatedAt])
}
+112 -2
View File
@@ -1,3 +1,9 @@
import { savePlan } from '../src/modules/class-plans/class-plans.service.js';
import { planSchema } from '../src/modules/class-plans/class-plans.schemas.js';
import { createFolder, listFolders } from '../src/modules/courseware/courseware.service.js';
import { importYamlClassPlan } from '../src/modules/imports/class-plan-yaml.service.js';
import { updateTermWeeks, autoTermWeeks } from '../src/modules/term/term.service.js';
import { buildAutoTermWeeks } from '@classhelper/shared';
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { createHash } from 'node:crypto';
@@ -570,7 +576,10 @@ try {
const day = await execute((await confirm(dayPlan))[0]!);
const entries = [
{ timeLayoutItemId: layout.points[0].id, courseId: mathA.id },
{ timeLayoutItemId: layout.points[1].id, courseId: null },
{
timeLayoutItemId: layout.points.filter((p: { timeType: string }) => p.timeType === 'LESSON')[1].id,
courseId: null,
},
];
const coursePlan = await interpret([
{ action: 'plans.entries', target: { id: day.id }, params: { entries } },
@@ -794,7 +803,7 @@ try {
modelReplies.push(' ', { message: '自动修正成功' });
assert.equal((await api('/ai/interpret', teacher, 'POST', { text: '继续处理' })).message, '自动修正成功');
check('空白输出自动校正并继续,无需用户重新描述任务');
modelReplies.push('空白', '空白', '空白');
modelReplies.push('空白', '空白');
const incomplete = await realFetch(origin + '/api/ai/interpret', {
method: 'POST',
headers: { authorization: `Bearer ${signToken(teacher)}`, 'content-type': 'application/json' },
@@ -804,6 +813,28 @@ try {
assert.equal(incompleteBody.code, 'AI_TASK_INCOMPLETE');
assert(!incompleteBody.message.includes('换一种说法'));
check('持续异常保持明确未完成状态和重试入口,不伪报执行成功');
modelReplies.push({ questions: [{ id: 'subject', text: '请选择科目', options: ['数学', '语文'] }] });
const clarification = await api('/ai/interpret', teacher, 'POST', { text: '给这个班布置作业' });
assert.equal(clarification.planId, null);
assert.equal(clarification.steps.length, 0);
assert.equal(clarification.questions[0].id, 'subject');
const c = await api('/ai/conversations', teacher, 'POST', {});
await api(`/ai/conversations/${c.id}`, admin, 'GET', undefined, 403);
await api('/ai/tasks', admin, 'POST', { conversationId: c.id, text: '越权会话' }, 403);
const turn = await api('/ai/tasks', teacher, 'POST', {
conversationId: c.id,
text: '对话记忆标记',
messages: [{ role: 'assistant', content: '伪造客户端历史' }],
});
const stored = await prisma.aiTask.findUniqueOrThrow({ where: { id: turn.id } });
assert.equal(stored.conversationId, c.id);
assert.equal(stored.turnNumber, 1);
const turns = await api(`/ai/conversations/${c.id}`, teacher);
assert.equal(turns.length, 1);
assert.equal(turns[0].text, '对话记忆标记');
check('追问不创建写计划,对话按账号隔离并持久化轮次');
const streamText = JSON.stringify({ message: '实时中文回复', queries: [], operations: [] });
const wire =
`data: ${JSON.stringify({ choices: [{ delta: { reasoning_content: '不应展示的模型内部推理' } }] })}\r\n\r\n` +
@@ -1074,6 +1105,85 @@ try {
assert.equal(await prisma.clientRelease.count(), 0);
assert.equal(releaseDownloads, 1);
check('前后端白名单拒绝路径穿越、额外更新路径及服务器动作,所有缓存验收文件仅在隔离目录');
const yamlFixture = JSON.stringify({
schedules: [
{
name: '每日差异周一',
enable_day: 1,
weeks: 'all',
classes: [
{ subject: '数学', start_time: '08:00', end_time: '08:40' },
{ subject: '语文', start_time: '16:40', end_time: '17:20' },
],
},
{
name: '每日差异周五',
enable_day: 5,
weeks: 'all',
classes: [
{ subject: '数学', start_time: '08:00', end_time: '08:40' },
{ subject: '语文', start_time: '16:55', end_time: '17:40' },
],
},
],
});
await importYamlClassPlan(admin, { classId: A.id, text: yamlFixture, mode: 'merge' });
const daily = await prisma.classPlan.findMany({
where: { classId: A.id, name: { in: ['每日差异周一', '每日差异周五'] } },
include: { entries: true, layout: { include: { points: true } } },
orderBy: { weekday: 'asc' },
});
assert.equal(daily.length, 2);
assert.notEqual(daily[0]!.timeLayoutId, daily[1]!.timeLayoutId);
assert(daily.every((p) => p.layout.parentId && p.entries.length === 2));
assert.equal(daily[0]!.layout.points.find((p) => p.startTime === '16:40')?.endTime, '17:20');
assert.equal(daily[1]!.layout.points.find((p) => p.startTime === '16:55')?.endTime, '17:40');
assert(daily.every((p) => p.layout.points.filter((t) => t.isAutoBreak).length === 1));
const lessonIds = daily
.flatMap((p) => p.layout.points.filter((t) => t.timeType === 'LESSON').map((t) => t.id))
.sort();
await importYamlClassPlan(admin, { classId: A.id, text: yamlFixture, mode: 'merge' });
assert.equal(await prisma.timeLayoutItem.count({ where: { id: { in: lessonIds } } }), 4);
check('每日差异导入生成独立子表,末节时间准确,自动课间不改变课时外键且重导幂等');
await savePlan(
admin,
planSchema.parse({ classId: A.id, name: daily[0]!.name, timeLayoutId: daily[1]!.timeLayoutId }),
daily[0]!.id,
);
const rebound = await prisma.classPlanEntry.findMany({
where: { classPlanId: daily[0]!.id },
include: { timePoint: true },
});
assert.equal(rebound.length, 2);
assert(rebound.every((e) => e.timePoint.timeLayoutId === daily[1]!.timeLayoutId));
assert.deepEqual(rebound.map((e) => e.courseId).sort(), daily[0]!.entries.map((e) => e.courseId).sort());
check('服务端切换子时间表事务重绑外键并完整保留课程');
const initial = buildAutoTermWeeks('2026-09-07', 20);
initial[0]!.note = '人工备注';
await updateTermWeeks(admin, { maxTermWeeks: 30, termStartDate: '2026-09-07', weeks: initial });
const thirty = await autoTermWeeks(admin, { maxTermWeeks: 30, termStartDate: '2026-09-07' });
assert.equal(thirty.weeks.length, 30);
await assert.rejects(() => updateTermWeeks(admin, { maxTermWeeks: 20, weeks: initial }), /请先缩短/);
await prisma.class.updateMany({ where: { archivedYearId: null }, data: { termWeeks: 20 } });
const twenty = await updateTermWeeks(admin, {
maxTermWeeks: 20,
weeks: initial,
termStartDate: '2026-09-07',
});
assert.equal(twenty.weeks.length, 20);
assert.equal(twenty.weeks[0]!.note, '人工备注');
check('全校总周数 20→30→20 正确保存,显式保存保留人工备注');
await createFolder(teacher, '回归课件/必修一/第一课');
await createFolder(admin, '回归课件/必修一/第一课');
const tf = await listFolders(teacher),
af = await listFolders(admin);
for (const path of ['回归课件', '回归课件/必修一', '回归课件/必修一/第一课']) {
assert(tf.some((f) => f.path === path));
assert(af.some((f) => f.path === path));
assert.notEqual(tf.find((f) => f.path === path)!.id, af.find((f) => f.path === path)!.id);
}
check('三层目录自动补建父目录,同名目录按教师身份独立保存');
console.log(`AI 隔离验收通过:${checks} 项`);
} finally {
globalThis.fetch = realFetch;
+3 -1
View File
@@ -2215,7 +2215,9 @@ async function main() {
mergeImport.status === 200 &&
mergeData?.merged === 1 &&
mergeData?.replaced === 1 &&
mergeData?.layout?.items?.length === 4,
mergeData?.layout?.items?.length === 5 &&
mergeData.layout.items.filter((item) => item.type === 'class').length === 3 &&
mergeData.layout.items.filter((item) => item.type === 'break').length === 2,
`合并=${mergeData?.merged} 新增=${mergeData?.replaced} 共=${mergeData?.layout?.items?.length}`,
);
+3 -1
View File
@@ -73,6 +73,7 @@ export const SNAPSHOT_TABLES = [
'ClientRelease',
'AiAudit',
'AiPlanStep',
'AiConversation',
'AiTask',
] as const;
@@ -150,7 +151,8 @@ export function assertValidSnapshot(value: unknown): asserts value is DatabaseSn
(table.startsWith('Courseware') ||
table === 'PermissionAudit' ||
table === 'AiPlanStep' ||
table === 'AiTask')
table === 'AiTask' ||
table === 'AiConversation')
)
continue;
if (!Array.isArray(rows)) {
+24 -1
View File
@@ -27,6 +27,29 @@ import { setTimeout as delay } from 'node:timers/promises';
const router = Router();
router.use(authenticate());
router.post('/conversations', requirePermission('ai:use'), async (req, res) => {
sendOk(res, await tasks.createConversation(getAuthUser(req)));
});
router.get('/conversations', requirePermission('ai:use'), async (req, res) => {
sendOk(
res,
await tasks.conversations(
getAuthUser(req),
typeof req.query.before === 'string' ? req.query.before : undefined,
),
);
});
router.get(
'/conversations/:id',
requirePermission('ai:use'),
validate({ params: planIdSchema }),
async (req, res) => {
const before = Number(req.query.before);
if (req.query.before !== undefined && (!Number.isInteger(before) || before < 1))
throw ApiError.badRequest('轮次游标无效');
sendOk(res, await tasks.conversationTurns(getAuthUser(req), String(req.params.id), before || undefined));
},
);
router.get(
'/tasks/:id/events',
@@ -63,7 +86,7 @@ router.get(
sent.add(JSON.stringify(event));
}
}
if (['ready', 'succeeded'].includes(current.state) && current.result) {
if (['ready', 'succeeded', 'waiting_input'].includes(current.state) && current.result) {
send({ type: 'result', result: current.result });
break;
}
@@ -19,6 +19,8 @@ export const discoverModelsSchema = updateAiSettingsSchema.pick({ baseUrl: true,
/** `POST /api/ai/interpret`:一句中文原话 */
export const aiInterpretSchema = z.object({
supersedesTaskId: z.string().min(1).max(100).optional(),
conversationId: z.string().min(1).max(100).optional(),
text: z.string().trim().min(1, '请说明要做的事').max(8000),
messages: z
.array(z.object({ role: z.enum(['user', 'assistant']), content: z.string().max(8000) }).strict())
+25 -1
View File
@@ -27,6 +27,16 @@ const operationSchema = z
})
.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([]),
@@ -176,6 +186,20 @@ export async function interpretConversation(
});
else reply = replySchema.parse({ message: '离线示例未识别此任务,请配置模型或补充具体操作。' });
}
if (reply.questions?.length)
return {
planId: null,
steps: [],
results: modelResults,
message: reply.message || reply.questions.map((q) => q.text).join(';'),
questions: reply.questions,
action: 'unknown',
params: {},
preview: { summary: '请补充必要信息', warnings: [] },
confidence: 0,
needConfirm: false,
rawReply: null,
};
const results: AiConversationResult['results'] = [...modelResults];
for (const query of reply.queries)
results.push({
@@ -215,7 +239,7 @@ export async function interpretConversation(
settings.provider !== 'openai' ||
!(error instanceof ApiError) ||
![400, 422].includes(error.status) ||
(run.corrections ?? 0) >= 2
(run.corrections ?? 0) >= 1
)
throw error;
run.emit?.({ type: 'status', message: '参数需要调整,正在自动核对并修正预览' });
@@ -29,12 +29,26 @@ const operationSchema = z
.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.queries.length > 0 || value.operations.length > 0,
(value) =>
!!value.message?.trim() ||
!!value.questions?.length ||
value.queries.length > 0 ||
value.operations.length > 0,
'回复不能是空对象',
);
@@ -95,6 +109,7 @@ export async function planWithModel(
content: [
'你是 ClassHelper 助手。只输出严格 JSON:{message,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 必须为空,等待用户回答。',
'queries 只能查询,operations 是待确认写操作,不能声称已执行。先查询真实 id 和现状,再规划修改;不猜测班级、账号、学生、课程和时间点 id。信息不足时追问。',
'仅可选择工具目录中的 action。工具 schema.target 列出路径参数,schema.params 是 params 的 JSON Schema。查询条件放 query。所有数据和动作遵循操作者的实时权限。',
'数据库备份/恢复/清空/切换/SQL、服务器配置/启停/升级和密钥维护禁止执行。密码字段留空,由用户在专门表单输入。',
@@ -112,7 +127,8 @@ export async function planWithModel(
];
const results: AiConversationResult['results'] = [];
const apiKey = decryptSecret(await getSetting(SETTING_KEYS.aiApiKey));
let corrections = 0;
let corrections = run.corrections ?? 0;
const seenQueries = new Set<string>();
for (let round = 0; round < 12; round++) {
signal.throwIfAborted();
await run.authorize?.();
@@ -185,13 +201,14 @@ export async function planWithModel(
reply = parseModelReply(completion.content);
} catch {
signal.throwIfAborted();
if (++corrections >= 3)
run.corrections = ++corrections;
if (corrections > 1)
throw new ApiError(
502,
'AI_TASK_INCOMPLETE',
'任务已保留,但模型暂未给出可执行方案。自动校正已尝试三次,可点击继续重试;尚未执行任何更改。',
'任务已保留,但模型暂未给出可执行方案。自动校正已尝试一次,可点击继续重试;尚未执行任何更改。',
);
run.emit?.({ type: 'status', message: `正在自动校正回复(${corrections}/3)` });
run.emit?.({ type: 'status', message: `正在自动校正回复(${corrections}/1)` });
messages.push({
role: 'user',
content:
@@ -199,9 +216,21 @@ export async function planWithModel(
});
continue;
}
corrections = 0;
if (reply.questions?.length) return { reply: { ...reply, operations: [], queries: [] }, results };
if (!reply.queries.length) return { reply, results };
for (const query of reply.queries) {
const signature = JSON.stringify(query);
if (seenQueries.has(signature))
return {
reply: {
message: '已有查询结果仍不足以确定你的意图,请补充需要处理的对象或期望结果。',
questions: [{ id: 'clarify-task', text: '请补充你要处理的对象和具体要求。' }],
queries: [],
operations: [],
},
results,
};
seenQueries.add(signature);
signal.throwIfAborted();
run.emit?.({
type: 'status',
+148 -7
View File
@@ -16,7 +16,7 @@ import { coursewareRoot } from '../courseware/courseware.service.js';
import { interpretConversation } from './conversation.js';
import { sanitizePrompt } from './model-planner.js';
import { runRead } from './actions.js';
import { confirmPlan, getPlan, preparePlan } from './plans.js';
import { confirmPlan, getPlan, preparePlan, discardPlan } from './plans.js';
import type { AiInterpretInput } from './ai.schemas.js';
const active = new Map<string, AbortController>();
@@ -71,7 +71,7 @@ export async function createTask(user: TokenPayload, input: AiInterpretInput) {
const expired = await prisma.aiTask.findMany({
where: {
userId: user.sub,
state: { in: ['preparing', 'ready', 'failed', 'stopped', 'succeeded'] },
state: { in: ['preparing', 'ready', 'failed', 'stopped', 'succeeded', 'waiting_input'] },
updatedAt: { lt: new Date(Date.now() - 24 * 60 * 60 * 1000) },
},
take: 20,
@@ -82,16 +82,87 @@ export async function createTask(user: TokenPayload, input: AiInterpretInput) {
3
)
throw ApiError.conflict('请等待现有后台任务完成');
const conversation = input.conversationId
? await ownedConversation(user, input.conversationId)
: await createConversation(user);
if (input.supersedesTaskId) {
const old = await owned(user, input.supersedesTaskId);
if (old.conversationId !== conversation.id || old.state !== 'ready')
throw ApiError.conflict('只能替换本对话中明确选中的待确认计划');
}
const previous = await prisma.aiTask.findMany({
where: { userId: user.sub, conversationId: conversation.id },
orderBy: { turnNumber: 'asc' },
});
if (previous.some((t) => ['planning', 'executing'].includes(t.state)))
throw ApiError.conflict('当前对话仍在处理,请等待完成');
const history: { role: 'user' | 'assistant'; content: string }[] = [];
for (const old of previous) {
const checked = await task(user, old.id);
history.push({ role: 'user', content: checked.text });
if (checked.result)
history.push({
role: 'assistant',
content:
checked.result.message +
'\n' +
JSON.stringify(
checked.result.steps.map((s) => ({ action: s.action, status: s.status, summary: s.summary })),
),
});
}
const context =
history.length > 18
? [
{
role: 'user' as const,
content:
'此前用户需求摘要:' +
history
.slice(0, -18)
.filter((m) => m.role === 'user')
.map((m) => m.content.slice(0, 300))
.join(';')
.slice(-7000),
},
...history.slice(-18),
]
: history;
const last = previous.at(-1);
const inherited =
last?.state === 'waiting_input' && !input.attachments?.length
? decode<AiInterpretInput>(last.input).attachments
: undefined;
const safe = {
...input,
attachments: input.attachments?.length ? input.attachments : inherited,
text: sanitizePrompt(input.text),
messages: input.messages?.map((item) => ({ ...item, content: sanitizePrompt(item.content) })),
conversationId: conversation.id,
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, input: encryptSecret(JSON.stringify(safe)) },
data: {
userId: user.sub,
conversationId: conversation.id,
turnNumber: (previous.at(-1)?.turnNumber ?? 0) + 1,
input: encryptSecret(JSON.stringify(safe)),
},
});
return { id: row.id };
if (last && inherited?.length) {
for (const attachment of inherited) {
const source = attachmentPath(last.id, attachment.id),
target = attachmentPath(row.id, attachment.id);
if (!fs.existsSync(source)) throw ApiError.badRequest('原附件暂存已过期,请重新上传后继续');
await fsp.mkdir(path.dirname(target), { recursive: true });
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(
user: TokenPayload,
@@ -174,6 +245,9 @@ export async function task(user: TokenPayload, id: string): Promise<AiTaskDto> {
}
return {
id,
classId: decode<AiInterpretInput>(row.input).classId,
conversationId: row.conversationId,
turnNumber: row.turnNumber,
state: row.state,
text: decode<AiInterpretInput>(row.input).text,
result,
@@ -283,12 +357,29 @@ export async function startTask(user: TokenPayload, id: string) {
await prisma.aiTask.update({
where: { id },
data: {
state: result.steps.length ? 'ready' : 'succeeded',
state: result.questions?.length ? 'waiting_input' : result.steps.length ? 'ready' : 'succeeded',
result: encryptSecret(JSON.stringify(result)),
},
});
if (input.supersedesTaskId && result.steps.length) {
const old = await owned(user, input.supersedesTaskId);
if (old.conversationId !== row.conversationId || old.state !== 'ready')
throw ApiError.conflict('原计划已变化,替换未完成,请分别核对计划');
if (active.has(old.id)) throw ApiError.conflict('原计划正在执行,不能替换');
const claimed = await prisma.aiTask.updateMany({
where: { id: old.id, state: 'ready' },
data: { state: 'superseded' },
});
if (!claimed.count) throw ApiError.conflict('原计划已变化,替换未完成');
const oldResult = decode<AiConversationResult>(old.result);
if (oldResult.planId) await discardPlan(user, oldResult.planId);
await prisma.aiTask.updateMany({
where: { id: old.id, state: 'ready' },
data: { state: 'superseded' },
});
}
emit({ type: 'status', message: result.steps.length ? '变更预览已准备,等待确认' : '处理完成' });
if (!result.steps.length) await cleanup(id, input);
if (!result.steps.length && !result.questions?.length) await cleanup(id, input);
});
}
@@ -364,3 +455,53 @@ export async function stopTask(user: TokenPayload, id: string) {
data: { state: 'stopped', error: '任务已按你的要求停止。' },
});
}
export async function createConversation(user: TokenPayload) {
await assertPermission(user, 'ai:use');
return prisma.aiConversation.create({ data: { userId: user.sub } });
}
async function ownedConversation(user: TokenPayload, id: string) {
await assertPermission(user, 'ai:use');
const row = await prisma.aiConversation.findFirst({ where: { id, userId: user.sub } });
if (!row) throw ApiError.forbidden('无法访问此对话');
return row;
}
export async function conversations(user: TokenPayload, before?: string) {
await assertPermission(user, 'ai:use');
const legacy = await prisma.aiTask.findMany({
where: { userId: user.sub, conversationId: null },
take: 100,
});
for (const old of legacy)
await prisma.$transaction(async (tx) => {
const c = await tx.aiConversation.upsert({
where: { id: old.id },
create: {
id: old.id,
userId: user.sub,
title: sanitizePrompt(decode<AiInterpretInput>(old.input).text).slice(0, 80),
createdAt: old.createdAt,
},
update: {},
});
await tx.aiTask.updateMany({
where: { id: old.id, conversationId: null },
data: { conversationId: c.id },
});
});
return prisma.aiConversation.findMany({
where: { userId: user.sub },
orderBy: [{ updatedAt: 'desc' }, { id: 'desc' }],
take: 30,
...(before ? { cursor: { id: before }, skip: 1 } : {}),
});
}
export async function conversationTurns(user: TokenPayload, id: string, before?: number) {
await ownedConversation(user, id);
const rows = await prisma.aiTask.findMany({
where: { conversationId: id, userId: user.sub, ...(before ? { turnNumber: { lt: before } } : {}) },
orderBy: { turnNumber: 'desc' },
take: 30,
});
return Promise.all(rows.reverse().map((row) => task(user, row.id)));
}
@@ -0,0 +1,45 @@
import type { Prisma } from '../../generated/prisma/client.js';
export async function fillLayoutBreaks(tx: Prisma.TransactionClient, id: string) {
await tx.timeLayoutItem.deleteMany({ where: { timeLayoutId: id, isAutoBreak: true } });
const points = await tx.timeLayoutItem.findMany({
where: { timeLayoutId: id },
orderBy: [{ startTime: 'asc' }, { position: 'asc' }],
});
const lessons = points.filter((p) => p.timeType === 'LESSON');
for (let i = 0; i < lessons.length; i++)
if (!lessons[i]!.slotKey)
await tx.timeLayoutItem.update({ where: { id: lessons[i]!.id }, data: { slotKey: `lesson-${i + 1}` } });
for (let i = 1; i < lessons.length; i++) {
const left = lessons[i - 1]!,
right = lessons[i]!;
let cursor = left.endTime;
for (const occupied of points
.filter((p) => p.timeType !== 'DIVIDER' && p.startTime < right.startTime && p.endTime > left.endTime)
.sort((a, b) => a.startTime.localeCompare(b.startTime))) {
const end = occupied.startTime < right.startTime ? occupied.startTime : right.startTime;
if (cursor < end) await add(cursor, end, i);
if (occupied.endTime > cursor) cursor = occupied.endTime;
}
if (cursor < right.startTime) await add(cursor, right.startTime, i);
}
async function add(startTime: string, endTime: string, index: number) {
await tx.timeLayoutItem.create({
data: {
timeLayoutId: id,
position: index * 2 - 1,
startTime,
endTime,
timeType: 'BREAK',
breakName: '课间休息',
isAutoBreak: true,
slotKey: `break-${index}-${startTime}`,
},
});
}
const ordered = await tx.timeLayoutItem.findMany({
where: { timeLayoutId: id },
orderBy: [{ startTime: 'asc' }, { position: 'asc' }],
});
for (const [position, p] of ordered.entries())
await tx.timeLayoutItem.update({ where: { id: p.id }, data: { position } });
}
@@ -8,6 +8,8 @@ export const scopeQuery = z.object({
export const pointSchema = z
.object({
id: z.string().min(1).optional(),
slotKey: z.string().max(100).default(''),
isAutoBreak: z.boolean().default(false),
name: z.string().max(64).default(''),
startTime: timeSchema,
endTime: timeSchema,
@@ -19,6 +21,7 @@ export const pointSchema = z
})
.refine((p) => p.timeType === 'DIVIDER' || p.startTime < p.endTime, '结束时间必须晚于开始时间');
export const layoutSchema = z.object({
parentId: z.string().min(1).nullish(),
name: z.string().trim().min(1).max(64),
classId: z.string().nullish(),
points: z.array(pointSchema).max(100),
@@ -1,3 +1,4 @@
import { fillLayoutBreaks } from './auto-breaks.js';
import { assertAdmin, assertHeadOnly, assertPermissionOrClassDevice } from '../../lib/authz/index.js';
import { SOCKET_EVENTS } from '@classhelper/shared';
import { prisma } from '../../lib/db.js';
@@ -43,11 +44,18 @@ export async function saveLayout(user: TokenPayload, input: z.infer<typeof layou
await assertLayoutWrite(user, layoutClassId, id);
if (existing && input.classId !== undefined && input.classId !== existing.classId)
throw ApiError.forbidden('不能移动时间表到其他班级');
if (input.parentId) {
const parent = await prisma.timeLayout.findUnique({ where: { id: input.parentId } });
if (!parent || parent.id === id || parent.classId !== layoutClassId || parent.parentId)
throw ApiError.badRequest('父时间表无效或范围不一致');
}
// 默认课程属于具体班级:全校时间表不保留默认课程,非上课时间点也不保留。
const points = input.points.map((point) => ({
...point,
defaultClassId: point.timeType === 'LESSON' && layoutClassId ? (point.defaultClassId ?? null) : null,
}));
const points = input.points
.filter((p) => !p.isAutoBreak)
.map((point) => ({
...point,
defaultClassId: point.timeType === 'LESSON' && layoutClassId ? (point.defaultClassId ?? null) : null,
}));
const defaultIds = [...new Set(points.flatMap((p) => (p.defaultClassId ? [p.defaultClassId] : [])))];
if (defaultIds.length && layoutClassId) {
const count = await prisma.course.count({
@@ -59,9 +67,17 @@ export async function saveLayout(user: TokenPayload, input: z.infer<typeof layou
if (new Set(pointIds).size !== pointIds.length) throw ApiError.badRequest('时间点不能重复');
const result = await prisma.$transaction(async (tx) => {
const layout = id
? await tx.timeLayout.update({ where: { id }, data: { name: input.name } })
? await tx.timeLayout.update({
where: { id },
data: { name: input.name, ...(input.parentId !== undefined ? { parentId: input.parentId } : {}) },
})
: await tx.timeLayout.create({
data: { name: input.name, classId: input.classId ?? null, source: 'manual' },
data: {
name: input.name,
classId: input.classId ?? null,
parentId: input.parentId,
source: 'manual',
},
});
const owned = await tx.timeLayoutItem.findMany({
where: { timeLayoutId: layout.id },
@@ -75,6 +91,7 @@ export async function saveLayout(user: TokenPayload, input: z.infer<typeof layou
if (pointId) await tx.timeLayoutItem.update({ where: { id: pointId }, data: { ...data, position } });
else await tx.timeLayoutItem.create({ data: { ...data, position, timeLayoutId: layout.id } });
}
await fillLayoutBreaks(tx, layout.id);
return tx.timeLayout.findUniqueOrThrow({
where: { id: layout.id },
include: { points: { orderBy: { position: 'asc' } } },
@@ -152,16 +169,54 @@ export async function savePlan(user: TokenPayload, input: z.infer<typeof planSch
input = { ...input, weekEnd: Math.min(input.weekEnd, maxWeek) };
if (id && (await requirePlan(user, id)).classId !== input.classId)
throw ApiError.badRequest('不能移动课表到另一班');
const layout = await prisma.timeLayout.findUnique({ where: { id: input.timeLayoutId } });
const layout = await prisma.timeLayout.findUnique({
where: { id: input.timeLayoutId },
include: { points: { orderBy: { position: 'asc' } } },
});
if (!layout || (layout.classId && layout.classId !== input.classId))
throw ApiError.badRequest('时间表不属于本班或全校');
if (input.associatedGroup) {
const group = await prisma.classPlanGroup.findUnique({ where: { id: input.associatedGroup } });
if (group?.classId !== input.classId) throw ApiError.badRequest('课表群组不属于本班');
}
const result = id
? await prisma.classPlan.update({ where: { id }, data: input })
: await prisma.classPlan.create({ data: input });
const previous = id ? await requirePlan(user, id) : null;
const changes =
previous && previous.timeLayoutId !== layout.id
? previous.entries.map((entry) => {
const oldLessons = previous.layout.points.filter((p) => p.timeType === 'LESSON');
const source = oldLessons.find((p) => p.id === entry.timeLayoutItemId);
const lessons = layout.points.filter((p) => p.timeType === 'LESSON');
const target =
lessons.find((p) => source?.slotKey && p.slotKey === source.slotKey) ||
lessons[oldLessons.findIndex((p) => p.id === source?.id)];
if (!target) throw ApiError.conflict('目标时间表课时不足,原课表已保留,请先处理差异');
return { id: entry.id, target: target.id };
})
: [];
const result = await prisma.$transaction(async (tx) => {
const row = id
? await tx.classPlan.update({ where: { id }, data: input })
: await tx.classPlan.create({ data: input });
// 先删除再重建,避免槽位交换命中日课表/时间点的组合唯一键。
if (changes.length && previous) {
await tx.classPlanEntry.deleteMany({ where: { classPlanId: previous.id } });
for (const entry of previous.entries) {
const target = changes.find((c) => c.id === entry.id)!;
await tx.classPlanEntry.create({
data: {
id: entry.id,
classPlanId: previous.id,
timeLayoutItemId: target.target,
courseId: entry.courseId,
isEnabled: entry.isEnabled,
isChangedClass: entry.isChangedClass,
location: entry.location,
},
});
}
}
return row;
});
await notifyScheduleChanged(input.classId);
return result;
}
@@ -317,6 +372,7 @@ export async function deleteLayout(user: TokenPayload, id: string) {
const layout = await prisma.timeLayout.findUnique({ where: { id } });
if (!layout) throw ApiError.notFound('时间表不存在');
await assertLayoutWrite(user, layout.classId, id);
if (await prisma.timeLayout.count({ where: { parentId: id } })) throw ApiError.conflict('仍有子时间表');
if (await prisma.classPlan.count({ where: { timeLayoutId: id } }))
throw ApiError.conflict('仍有课表使用该时间表');
await prisma.timeLayout.delete({ where: { id } });
@@ -47,9 +47,12 @@ export async function exportProfile(user: TokenPayload, classId: string) {
l.id,
{
Name: l.name,
ParentTimeLayoutId: l.parentId,
IsOverlay: l.isOverlay,
OverlaySourceId: l.overlaySourceId,
Layouts: l.points.map((p) => ({
SlotKey: p.slotKey,
IsAutoBreak: p.isAutoBreak,
Name: p.name,
StartTime: p.startTime,
EndTime: p.endTime,
@@ -1,3 +1,4 @@
import { fillLayoutBreaks } from './auto-breaks.js';
import { createHash } from 'node:crypto';
import { z } from 'zod';
import { isDayKey, dayKeyLocal } from '@classhelper/shared';
@@ -102,6 +103,17 @@ export async function importProfile(user: TokenPayload, classId: string, payload
await tx.scheduledClassPlan.deleteMany({ where: { classId } });
await tx.classPlan.deleteMany({ where: { classId } });
}
for (const [id, value] of Object.entries(layouts)) {
const parent = object(value).ParentTimeLayoutId;
if (
parent != null &&
(typeof parent !== 'string' ||
!layouts[parent] ||
parent === id ||
object(layouts[parent]).ParentTimeLayoutId)
)
throw ApiError.badRequest('父时间表不存在或存在循环、嵌套关系');
}
const layoutIds = new Map<string, { id: string; lessons: string[] }>();
for (const [id, value] of Object.entries(layouts)) {
const l = object(value),
@@ -129,6 +141,8 @@ export async function importProfile(user: TokenPayload, classId: string, payload
if (timeType !== 'DIVIDER' && startTime >= endTime)
throw ApiError.badRequest('时间点结束必须晚于开始');
const pointData = {
slotKey: typeof p.SlotKey === 'string' ? p.SlotKey.slice(0, 100) : '',
isAutoBreak: p.IsAutoBreak === true,
timeLayoutId: created.id,
position,
name: String(p.Name || '').slice(0, 64),
@@ -151,6 +165,14 @@ export async function importProfile(user: TokenPayload, classId: string, payload
await tx.timeLayoutItem.deleteMany({ where: { timeLayoutId: created.id, id: { notIn: pointIds } } });
layoutIds.set(id, { id: created.id, lessons });
}
for (const [id, value] of Object.entries(layouts)) {
const target = layoutIds.get(id),
parent = layoutIds.get(String(object(value).ParentTimeLayoutId));
if (target) {
await tx.timeLayout.update({ where: { id: target.id }, data: { parentId: parent?.id ?? null } });
await fillLayoutBreaks(tx, target.id);
}
}
for (const [id, value] of Object.entries(layouts)) {
const source = layoutIds.get(String(object(value).OverlaySourceId)),
target = layoutIds.get(id);
@@ -205,6 +205,14 @@ export async function listFolders(user: TokenPayload) {
}
export async function createFolder(user: TokenPayload, folderPath: string) {
await assertPermission(user, 'courseware:write');
for (let i = 1; i < folderPath.split('/').length; i++) {
const parent = folderPath.split('/').slice(0, i).join('/');
await prisma.coursewareFolder.upsert({
where: { ownerId_path: { ownerId: user.sub, path: parent } },
create: { ownerId: user.sub, path: parent },
update: {},
});
}
const row = await prisma.coursewareFolder.upsert({
where: { ownerId_path: { ownerId: user.sub, path: folderPath } },
create: { ownerId: user.sub, path: folderPath },
@@ -20,8 +20,7 @@ import type { ClassPlanYamlImportInput } from './imports.schemas.js';
* 这里把它**归一化成 ClassIsland 兼容的 `{ TimeLayouts, ClassPlans, Subjects }` 载荷**,
* 再交给 `importProfile()` 写入:
* - merge / replace、稳定 id、事务回滚、权限与 `notifyScheduleChanged` 全部复用现有一份实现;
* - 全部 schedules 里出现过的不同 (start_time, end_time) 合并成一张时间表,
* LESSON 时间点按时间排序,同一天没列出的时间点写成空课(IsEmpty);
* - 作息存在差异时按日期与周相位生成独立子时间表,保留当天显式空课;
* - 单双周映射:all → WeekCountDiv=0,odd → 1/2,even → 2/2;
* - enable_day 1=周一 … 7=周日,ClassIsland 的 WeekDay 同样 1=周一 … 7=周日,直接对应。
*
@@ -605,45 +604,44 @@ export function buildClassIslandProfile(
...(subject.initial ? { Initial: subject.initial } : {}),
};
}
const layouts: Record<string, unknown> = {
'yaml-layout': {
Name: LAYOUT_NAME,
Layouts: parsed.layout.map((point) => ({
StartTime: point.startTime,
EndTime: point.endTime,
TimeType: 0,
Name: '',
})),
},
};
const signatures = new Set(
parsed.schedules.map((s) => JSON.stringify(s.lessons.map((l) => [l.startTime, l.endTime]))),
);
const split = signatures.size > 1;
const layouts: Record<string, unknown> = {};
const plans: Record<string, unknown> = {};
if (split) layouts['yaml-layout'] = { Name: LAYOUT_NAME, Layouts: [] };
for (const schedule of parsed.schedules) {
const lessonByTime = new Map(
schedule.lessons
.filter((lesson) => lesson.subject)
.map((lesson) => [`${lesson.startTime}-${lesson.endTime}`, lesson]),
);
const classes = parsed.layout.map((point) => {
const lesson = lessonByTime.get(`${point.startTime}-${point.endTime}`);
if (!lesson) return { IsEmpty: true, IsEnabled: true };
return {
SubjectId: `yaml-subject-${lesson.subject}`,
IsEnabled: true,
Location: lesson.location || '',
};
});
plans[`yaml-plan-${schedule.weekday}-${schedule.parity.toLowerCase()}`] = {
const key = `yaml-plan-${schedule.weekday}-${schedule.parity.toLowerCase()}`;
const layoutId = split
? `yaml-layout-${schedule.weekday}-${schedule.parity.toLowerCase()}`
: 'yaml-layout';
const lessons = [...schedule.lessons].sort((a, b) => a.startTime.localeCompare(b.startTime));
layouts[layoutId] = {
Name: split
? `${WEEKDAY_LABELS[schedule.weekday - 1]}${schedule.parity === 'ALL' ? '' : schedule.parity === 'ODD' ? '(单周)' : '(双周)'}`
: LAYOUT_NAME,
ParentTimeLayoutId: split ? 'yaml-layout' : null,
Layouts: lessons.map((l, i) => ({
StartTime: l.startTime,
EndTime: l.endTime,
TimeType: 0,
Name: `第 ${i + 1} 节`,
SlotKey: `lesson-${i + 1}`,
})),
};
plans[key] = {
Name: schedule.name,
TimeLayoutId: 'yaml-layout',
TimeRule: {
WeekDay: schedule.weekday,
WeekCountDiv: parityDiv(schedule.parity),
WeekCountDivTotal: 2,
},
TimeLayoutId: layoutId,
TimeRule: { WeekDay: schedule.weekday, WeekCountDiv: parityDiv(schedule.parity), WeekCountDivTotal: 2 },
WeekStart: 1,
WeekEnd: weekEnd,
IsEnabled: true,
Classes: classes,
Classes: lessons.map((l) =>
l.subject
? { SubjectId: `yaml-subject-${l.subject}`, IsEnabled: true, Location: l.location || '' }
: { IsEmpty: true, IsEnabled: true },
),
};
}
return { TimeLayouts: layouts, ClassPlans: plans, Subjects: subjects };
@@ -667,7 +665,12 @@ export async function previewYamlClassPlan(
entries: parsed.entries,
subjects: parsed.subjectNames,
missingSubjects: parsed.subjectNames.filter((name) => !existing.has(name)),
layoutNames: parsed.layout.length > 0 ? [LAYOUT_NAME] : [],
layoutNames:
parsed.layout.length > 0
? Object.values(
buildClassIslandProfile(parsed, 1).TimeLayouts as Record<string, { Name: string }>,
).map((l) => l.Name)
: [],
planCount: parsed.planCount,
errors: parsed.errors,
warnings: parsed.warnings,
@@ -368,6 +368,8 @@ export async function importTimeLayout(
const previousPoint = candidates.find((old) => old.endTime === p.endTime) || candidates[0];
if (previousPoint) claimed.add(previousPoint.id);
return {
slotKey: previousPoint?.slotKey || '',
isAutoBreak: false,
id: previousPoint?.id,
position,
name: p.name,
@@ -25,6 +25,7 @@ export const updateTermWeeksSchema = z.object({
});
export const autoTermWeeksSchema = z.object({
maxTermWeeks: z.coerce.number().int().min(1).max(60).optional(),
classId: z.string().min(1).nullish(),
termStartDate: termStartDateSchema.optional(),
maxWeek: z.coerce.number().int().min(1).max(60).optional(),
@@ -13,7 +13,7 @@ import { ApiError } from '../../lib/http.js';
import type { TokenPayload } from '../../lib/jwt.js';
import { logger } from '../../lib/logger.js';
import { getMaxTermWeeks, loadTermContext, resolveCurrentWeek } from '../../lib/term.js';
import { SETTING_KEYS, setSetting } from '../../lib/settings.js';
import { SETTING_KEYS } from '../../lib/settings.js';
import { emitToClass } from '../../realtime/bus.js';
import { SOCKET_EVENTS } from '@classhelper/shared';
import type { AutoTermWeeksInput, UpdateTermWeeksInput } from './term.schemas.js';
@@ -111,6 +111,24 @@ export async function updateTermWeeks(
}
await prisma.$transaction([
...(!scope && input.termStartDate
? [
prisma.appSetting.upsert({
where: { key: SETTING_KEYS.termStartDate },
create: { key: SETTING_KEYS.termStartDate, value: input.termStartDate },
update: { value: input.termStartDate },
}),
]
: []),
...(input.maxTermWeeks !== undefined
? [
prisma.appSetting.upsert({
where: { key: SETTING_KEYS.termMaxWeeks },
create: { key: SETTING_KEYS.termMaxWeeks, value: String(maximum) },
update: { value: String(maximum) },
}),
]
: []),
prisma.termWeek.deleteMany({ where: { classId: scope } }),
...(input.weeks.length > 0
? [
@@ -130,15 +148,7 @@ export async function updateTermWeeks(
: []),
]);
// 全校默认没有"班级记录"可以挂开学日期,写进全局设置(`term.startDate`)。
// 需求:「服务端可设置学期开始日期,以保证当前周次正确,管理员也可以随时纠正」——
// 原先这一级只能来自 `.env`,改一次要动文件 + 重启。
if (input.termStartDate && !scope) {
await setSetting(SETTING_KEYS.termStartDate, input.termStartDate);
}
logger.info(`学期周次已更新:范围=${scope || '全校默认'} 周数=${input.weeks.length} 由 ${user.name} 执行`);
if (input.maxTermWeeks !== undefined) await setSetting(SETTING_KEYS.termMaxWeeks, String(maximum));
logger.info(`学期周次已更新:范围=${scope || '全校默认'} 周数=${input.weeks.length}`);
await publishTermChange(scope);
return readTermWeeks(scope);
}
@@ -155,12 +165,17 @@ export async function autoTermWeeks(user: TokenPayload, input: AutoTermWeeksInpu
else assertAdmin(user);
const context = await loadTermContext(scope || null);
const termStartDate = input.termStartDate || context.termStartDate || env.termStartDate;
const maxWeek = input.maxWeek ?? context.maxWeek;
const maxWeek = scope ? context.maxWeek : (input.maxTermWeeks ?? input.maxWeek ?? context.maxWeek);
const weeks = buildAutoTermWeeks(termStartDate, maxWeek);
if (weeks.length === 0) throw ApiError.badRequest('请先填写学期开始日期(第 1 教学周的周一)');
return updateTermWeeks(user, { classId: scope || null, termStartDate, weeks });
return updateTermWeeks(user, {
classId: scope || null,
termStartDate,
weeks,
...(scope ? {} : { maxTermWeeks: input.maxTermWeeks }),
});
}
/* ------------------------------------------------------------------ 调休建议(联网,可选) */
+6
View File
@@ -41,18 +41,24 @@ export interface AiPlanStep extends AiOperation {
request?: AiExecutionRequest;
}
export interface AiConversationRequest {
supersedesTaskId?: string;
conversationId?: string;
text: string;
classId?: string;
messages?: { role: 'user' | 'assistant'; content: string }[];
attachments?: AiAttachment[];
}
export interface AiConversationResult {
questions?: { id: string; text: string; options?: string[] }[];
planId: string | null;
message: string;
steps: AiPlanStep[];
results: { action: string; label: string; data: unknown; operation?: AiOperation }[];
}
export interface AiTaskDto {
classId?: string;
conversationId?: string | null;
turnNumber?: number;
id: string;
state: string;
text: string;
+3
View File
@@ -4,6 +4,8 @@ import type { CourseBrief, ScheduleDto } from './types.js';
export const TIME_POINT_TYPES = ['LESSON', 'BREAK', 'DIVIDER', 'ACTION'] as const;
export type TimePointType = (typeof TIME_POINT_TYPES)[number];
export interface TimePointDto {
slotKey?: string;
isAutoBreak?: boolean;
id: string;
position: number;
name: string;
@@ -18,6 +20,7 @@ export interface TimePointDto {
actionSet: string;
}
export interface TimeLayoutDetailDto {
parentId?: string | null;
id: string;
name: string;
classId: string | null;
+97
View File
@@ -0,0 +1,97 @@
<script setup lang="ts">
import { computed } from 'vue';
const props = defineProps<{
items: { folderPath?: string; teacher: { id: string; name: string } }[];
folders?: { path: string }[];
owner?: string;
path: string;
}>();
const emit = defineEmits<{ 'update:path': [value: string]; 'update:owner': [value: string] }>();
const teachers = computed(() => [...new Map(props.items.map((i) => [i.teacher.id, i.teacher])).values()]);
const children = computed(() => {
const paths = [
...props.items.filter((i) => !props.owner || i.teacher.id === props.owner).map((i) => i.folderPath || ''),
...(props.folders || []).map((f) => f.path),
];
if (teachers.value.length > 1 && !props.owner) return [];
const prefix = props.path ? props.path + '/' : '';
return [
...new Set(
paths
.filter((p) => p.startsWith(prefix) && p !== props.path)
.map((p) => p.slice(prefix.length).split('/')[0])
.filter(Boolean),
),
].sort();
});
</script>
<template>
<div class="courseware-folders">
<label v-if="teachers.length > 1">
教师
<select
:value="owner"
@change="
emit('update:owner', ($event.target as HTMLSelectElement).value);
emit('update:path', '');
"
>
<option value="">选择教师</option>
<option v-for="t in teachers" :key="t.id" :value="t.id">{{ t.name }}</option>
</select>
</label>
<nav aria-label="文件夹路径">
<button @click="emit('update:path', '')">根目录</button>
<template v-for="(part, index) in path.split('/').filter(Boolean)" :key="index">
<span>/</span>
<button
@click="
emit(
'update:path',
path
.split('/')
.slice(0, index + 1)
.join('/'),
)
"
>
{{ part }}
</button>
</template>
</nav>
<button v-if="path" @click="emit('update:path', path.split('/').slice(0, -1).join('/'))">返回上级</button>
<div class="folder-children">
<button
v-for="name in children"
:key="name"
@click="emit('update:path', path ? path + '/' + name : name)"
>
📁 {{ name }}
</button>
</div>
</div>
</template>
<style scoped>
.courseware-folders {
display: grid;
gap: 12px;
padding: 12px 0;
}
.courseware-folders nav,
.folder-children {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.courseware-folders button,
.courseware-folders select {
padding: 8px 12px;
border: 1px solid var(--el-border-color);
border-radius: 6px;
background: var(--el-bg-color);
color: var(--el-text-color-primary);
max-width: 100%;
overflow-wrap: anywhere;
cursor: pointer;
}
</style>
+2
View File
@@ -14,3 +14,5 @@ declare module 'vue' {
ChDatePicker: typeof ChDatePicker;
}
}
export { default as CoursewareFolders } from './CoursewareFolders.vue';
+33
View File
@@ -264,3 +264,36 @@ html.care-mode .ch-calendar .el-date-picker {
flex-wrap: wrap;
}
}
/* 长内容与窄窗口保持可操作,滚动留在业务容器内。 */
html body :is(.page-header, .filters, .toolbar, .filter-bar, .page-actions) {
flex-wrap: wrap;
row-gap: 12px;
min-width: 0;
}
html body :is(.page-header, .filters, .toolbar, .filter-bar) > * {
max-width: 100%;
min-width: 0;
}
html body :is(.el-dialog, .el-message-box) {
max-width: calc(100vw - 32px);
max-height: calc(100dvh - 32px);
overflow: auto;
}
html body :is(.el-dialog__body, .el-card__body) {
overflow-wrap: anywhere;
}
html body :is(.el-form-item__content, .el-select, .el-input) {
min-width: 0;
}
@media (max-width: 600px) {
html body .page {
padding: 16px;
}
html body :is(.filters, .filter-bar) > * {
flex: 1 1 160px;
}
html body .el-dialog {
width: calc(100vw - 32px) !important;
}
}
@@ -62,7 +62,16 @@ const emit = defineEmits<{
placeholder="选择时间表"
@change="emit('change-layout', $event)"
>
<el-option v-for="item in props.layouts" :key="item.id" :value="item.id" :label="item.name" />
<el-option
v-for="item in props.layouts"
:key="item.id"
:value="item.id"
:label="
item.parentId
? (props.layouts.find((p) => p.id === item.parentId)?.name || '') + ' / ' + item.name
: item.name
"
/>
</el-select>
<button class="text-command" type="button" @click="emit('edit-layout')">
<ArchiveIcon name="clock" />
@@ -30,6 +30,7 @@ const layout = defineModel<TimeLayoutDetailDto | undefined>('layout', { default:
const emit = defineEmits<{
'select-layout': [id: string];
create: [];
'create-child': [parentId: string];
clone: [];
save: [];
refresh: [];
@@ -67,7 +68,13 @@ let reorderFrom = '';
let reorderTo = '';
let draftSequence = 0;
const visibleLayouts = computed(() => props.layouts.filter((item) => item.name.includes(search.value)));
const visibleLayouts = computed(() =>
props.layouts
.filter((item) => !item.parentId)
.flatMap((parent) => [parent, ...props.layouts.filter((child) => child.parentId === parent.id)])
.filter((item) => item.name.includes(search.value))
.map((item) => ({ ...item, name: item.parentId ? ' ↳ ' + item.name : item.name })),
);
const points = computed(() => layout.value?.points ?? []);
const selected = computed<TimePointDto | undefined>(() =>
points.value.find((point) => point.id === selectedId.value),
@@ -346,6 +353,14 @@ onUnmounted(() => {
</aside>
<main class="layout-main">
<button
v-if="layout && !layout.parentId"
class="command"
:disabled="!canCreate"
@click="emit('create-child', layout.id)"
>
新建子时间表
</button>
<header class="layout-toolbar">
<button class="command" :disabled="!canEdit || !layout" @click="addPoint('LESSON')">
<ArchiveIcon name="lesson" />
@@ -1,6 +1,8 @@
import { sha256 } from '@noble/hashes/sha2.js';
import type { AiAttachment } from '@classhelper/shared';
let attachmentSequence = 0;
export async function hashAttachment(file: File, signal?: AbortSignal): Promise<AiAttachment> {
const hash = sha256.create();
const reader = file.stream().getReader();
@@ -16,7 +18,7 @@ export async function hashAttachment(file: File, signal?: AbortSignal): Promise<
reader.releaseLock();
}
return {
id: crypto.randomUUID(),
id: `attachment-${Date.now().toString(36)}-${++attachmentSequence}-${Math.random().toString(36).slice(2)}`,
name: file.name,
size: file.size,
sha256: [...hash.digest()].map((value) => value.toString(16).padStart(2, '0')).join(''),
+257 -38
View File
@@ -22,6 +22,7 @@ import AssistantData from '@/components/AssistantData.vue';
import UrgentClassWarning from '@/components/UrgentClassWarning.vue';
import { observeTask } from '@/composables/assistantStream';
interface ChatMessage {
taskId?: string;
role: 'user' | 'assistant';
content: string;
result?: AiConversationResult;
@@ -29,6 +30,85 @@ interface ChatMessage {
state?: 'working' | 'done' | 'stopped';
}
const auth = useAuthStore();
let viewEpoch = 0;
const replacePlan = ref(false);
const conversationId = ref('');
const conversations = ref<{ id: string; title: string }[]>([]);
async function loadConversations() {
conversations.value = await api.get('/ai/conversations');
}
async function openConversation(id: string) {
if ((busy.value || executing.value) && !observing) return;
viewEpoch++;
controller?.abort();
busy.value = false;
executing.value = false;
conversationId.value = id;
attachments.value = [];
files.clear();
replacePlan.value = false;
const turns = await api.get<AiTaskDto[]>(`/ai/conversations/${id}`);
messages.value = turns.flatMap((t) => [
{ role: 'user' as const, content: t.text },
{
role: 'assistant' as const,
taskId: t.id,
activity: t.events.filter((e) => e.type === 'status').map((e) => e.message),
content: t.result?.message || t.error || '',
result: t.result,
state: 'done' as const,
},
]);
const last = turns.at(-1);
error.value = last?.error || '';
classId.value = last?.classId || '';
taskId.value = last?.id || '';
active.value = last?.result;
lastRequest = last ? { text: last.text, conversationId: id } : undefined;
clearCredentials();
if (last && ['planning', 'executing'].includes(last.state)) await resumeTask(last.id, true);
}
async function olderConversations() {
const older = await api.get<{ id: string; title: string }[]>('/ai/conversations', {
before: conversations.value.at(-1)?.id,
});
conversations.value.push(...older);
}
async function olderTurns() {
const first = messages.value.find((m) => m.taskId);
if (!first?.taskId) return;
const before = await api.get<AiTaskDto>(`/ai/tasks/${first.taskId}`);
if (!before.turnNumber) return;
const older = await api.get<AiTaskDto[]>(`/ai/conversations/${conversationId.value}`, {
before: before.turnNumber,
});
messages.value.unshift(
...older.flatMap((t) => [
{ role: 'user' as const, content: t.text, taskId: t.id },
{ role: 'assistant' as const, content: t.result?.message || '', result: t.result, taskId: t.id },
]),
);
}
const currentTurn = ref(0);
function onConversationScroll() {
const box = conversation.value;
if (!box) return;
followScroll.value = box.scrollHeight - box.scrollTop - box.clientHeight < 100;
const top = box.getBoundingClientRect().top;
const sections = [...box.querySelectorAll('.assistant-message.user')];
let active = 0;
sections.forEach((node, index) => {
if (node.getBoundingClientRect().top <= top + 100) active = index;
});
currentTurn.value = Math.max(0, active);
}
function jumpTurn(index: number) {
currentTurn.value = index;
conversation.value
?.querySelectorAll('.assistant-message.user')
[index]?.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
const text = ref(''),
classId = ref(''),
classes = ref<ClassDto[]>([]),
@@ -147,19 +227,22 @@ async function retryTask(): Promise<void> {
}
async function send(retrying = false): Promise<void> {
if ((!retrying && !text.value.trim()) || busy.value || executing.value || hashing.value) return;
const epoch = viewEpoch;
const supersedesTaskId = replacePlan.value && pending.value ? taskId.value : undefined;
busy.value = true;
error.value = '';
controller = new AbortController();
let message: ChatMessage | undefined;
const uploadFiles = attachments.value.map((attachment) => ({ attachment, file: files.get(attachment.id) }));
try {
if (active.value?.planId && pending.value) await aiApi.discard(active.value.planId);
clearCredentials();
active.value = undefined;
const content = retrying ? lastRequest!.text : text.value.trim(),
history = messages.value.slice(-18).map(({ role, content }) => ({ role, content }));
if (!retrying) {
lastRequest = {
supersedesTaskId,
conversationId: conversationId.value || undefined,
text: content,
classId: classId.value || undefined,
messages: history,
@@ -173,7 +256,11 @@ async function send(retrying = false): Promise<void> {
followScroll.value = true;
await scroll();
if (!retrying || !taskId.value) {
if (!conversationId.value)
conversationId.value = (await api.post<{ id: string }>('/ai/conversations', {})).id;
lastRequest!.conversationId = conversationId.value;
taskId.value = (await aiApi.createTask(lastRequest!)).id;
message.taskId = taskId.value;
message.activity!.push(
attachments.value.length ? '正在上传附件,完成后将转入后台' : '任务已提交到后台',
);
@@ -190,7 +277,7 @@ async function send(retrying = false): Promise<void> {
await observeTask(
taskId.value,
(event) => {
if (disposed || controller?.signal.aborted) return;
if (disposed || epoch !== viewEpoch || controller?.signal.aborted) return;
if (event.type === 'status' && message!.activity?.at(-1) !== event.message)
message!.activity = [...(message!.activity ?? []), event.message].slice(-60);
if (event.type === 'message') message!.content = event.text;
@@ -199,7 +286,7 @@ async function send(retrying = false): Promise<void> {
controller.signal,
),
);
if (disposed) return;
if (disposed || epoch !== viewEpoch) return;
active.value = result;
message.content = result.message;
message.result = result;
@@ -210,6 +297,7 @@ async function send(retrying = false): Promise<void> {
}
for (const step of result.steps) credentials[step.id] = {};
} catch (e) {
if (epoch !== viewEpoch) return;
if (controller.signal.aborted) {
if (message) message.content = '已停止生成,任务已保留,可继续重试。';
} else if (!disposed && !axios.isCancel(e)) {
@@ -218,10 +306,14 @@ async function send(retrying = false): Promise<void> {
if (typeof e === 'object' && e && 'code' in e && e.code === 'AI_NOT_CONFIGURED') disabled.value = true;
}
} finally {
if (epoch !== viewEpoch) return;
observing = false;
if (message) message.state = controller.signal.aborted || error.value ? 'stopped' : 'done';
busy.value = false;
if (!disposed) taskHistory.value = await aiApi.tasks().catch(() => taskHistory.value);
if (!disposed) {
taskHistory.value = await aiApi.tasks().catch(() => taskHistory.value);
await loadConversations();
}
await scroll();
}
}
@@ -232,19 +324,17 @@ function composerKey(event: KeyboardEvent): void {
}
}
async function newConversation(): Promise<void> {
if (busy.value || executing.value || hashing.value) return;
if (pending.value && active.value?.planId) {
try {
await ElMessageBox.confirm('开始新对话将取消当前待确认计划。', '新对话', {
confirmButtonText: '开始新对话',
cancelButtonText: '保留当前对话',
});
} catch {
return;
}
await aiApi.discard(active.value.planId);
}
if (hashing.value || ((busy.value || executing.value) && !observing)) return;
viewEpoch++;
controller?.abort();
busy.value = false;
executing.value = false;
observing = false;
conversationId.value = (await api.post<{ id: string }>('/ai/conversations', {})).id;
await loadConversations();
clearCredentials();
replacePlan.value = false;
classId.value = '';
active.value = undefined;
messages.value = [];
attachments.value = [];
@@ -386,9 +476,10 @@ async function stopGeneration(): Promise<void> {
if (taskId.value) await aiApi.stopTask(taskId.value);
controller?.abort();
}
async function resumeTask(id: string): Promise<void> {
async function resumeTask(id: string, preserveHistory = false): Promise<void> {
if (busy.value || executing.value) return;
error.value = '';
const epoch = viewEpoch;
const saved = await aiApi.task(id);
taskId.value = id;
lastRequest = { text: saved.text };
@@ -399,7 +490,8 @@ async function resumeTask(id: string): Promise<void> {
state: 'done',
result: saved.result,
});
messages.value = [{ role: 'user', content: saved.text }, message];
if (preserveHistory) messages.value[messages.value.length - 1] = message;
else messages.value = [{ role: 'user', content: saved.text }, message];
active.value = saved.result;
clearCredentials();
if (saved.error) error.value = saved.error;
@@ -416,6 +508,7 @@ async function resumeTask(id: string): Promise<void> {
await observeTask(
id,
(event) => {
if (epoch !== viewEpoch) return;
if (event.type === 'status' && message.activity!.at(-1) !== event.message)
message.activity!.push(event.message);
if (event.type === 'message') message.content = event.text;
@@ -424,13 +517,16 @@ async function resumeTask(id: string): Promise<void> {
controller.signal,
),
);
if (epoch !== viewEpoch) return;
active.value = result;
message.result = result;
message.content = saved.state === 'executing' ? '任务已完成。' : result.message;
clearCredentials();
} catch (e) {
if (epoch !== viewEpoch) return;
if (!disposed && !controller.signal.aborted) error.value = failure(e);
} finally {
if (epoch !== viewEpoch) return;
message.state = error.value ? 'stopped' : 'done';
busy.value = false;
executing.value = false;
@@ -446,11 +542,8 @@ onMounted(async () => {
aiApi.capabilities(),
classApi.list().catch(() => []),
]);
taskHistory.value = await aiApi.tasks();
const latest =
taskHistory.value.find((item) => ['planning', 'executing'].includes(item.state)) ??
taskHistory.value[0];
if (latest) await resumeTask(latest.id);
await loadConversations();
if (conversations.value[0]) await openConversation(conversations.value[0].id);
} catch (e) {
error.value = failure(e);
}
@@ -481,21 +574,24 @@ onBeforeUnmount(() => {
</div>
</div>
<div class="agent-header-actions">
<el-button v-if="conversations.length >= 30" @click="olderConversations">更多对话</el-button>
<el-select
v-if="taskHistory.length"
:model-value="taskId"
placeholder="最近任务"
:disabled="busy || executing"
@change="resumeTask"
v-if="conversations.length"
:model-value="conversationId"
placeholder="对话历史"
:disabled="(busy || executing) && !observing"
@change="openConversation"
>
<el-option
v-for="item in taskHistory"
v-for="item in conversations"
:key="item.id"
:value="item.id"
:label="item.text.slice(0, 24)"
:label="item.title || '新对话'"
/>
</el-select>
<el-button :disabled="busy || executing || hashing" @click="newConversation">新对话</el-button>
<el-button :disabled="hashing || ((busy || executing) && !observing)" @click="newConversation">
新对话
</el-button>
<el-select
v-model="classId"
clearable
@@ -508,17 +604,37 @@ onBeforeUnmount(() => {
<el-button v-if="auth.can('ai:manage')" @click="$router.push('/ai-settings')">模型设置</el-button>
</div>
</header>
<el-checkbox v-if="pending" v-model="replacePlan">本轮明确替换当前待确认计划(历史记录保留)</el-checkbox>
<select
class="mobile-turn-select"
aria-label="跳转对话轮次"
:value="currentTurn"
@change="jumpTurn(Number(($event.target as HTMLSelectElement).value))"
>
<option v-for="(turn, index) in messages.filter((m) => m.role === 'user')" :key="index" :value="index">
第 {{ index + 1 }} 轮:{{ turn.content.slice(0, 16) }}
</option>
</select>
<nav class="turn-navigation" aria-label="对话轮次">
<button
v-for="(turn, index) in messages.filter((m) => m.role === 'user')"
:key="index"
:title="turn.content"
:aria-current="index === currentTurn ? 'step' : undefined"
:aria-label="`跳转第 ${index + 1} 轮:${turn.content}`"
@click="jumpTurn(index)"
>
<span>{{ index + 1 }}</span>
</button>
</nav>
<div
ref="conversation"
class="assistant-conversation"
aria-live="polite"
:aria-busy="busy || executing"
@scroll="
followScroll =
!conversation ||
conversation.scrollHeight - conversation.scrollTop - conversation.clientHeight < 100
"
@scroll="onConversationScroll"
>
<el-button v-if="messages.length >= 60" @click="olderTurns">加载更早轮次</el-button>
<div v-if="!messages.length" class="assistant-welcome">
<span class="agent-welcome-mark" aria-hidden="true">✦</span>
<h2>有什么可以帮你?</h2>
@@ -559,6 +675,38 @@ onBeforeUnmount(() => {
<li v-for="(activity, n) in message.activity" :key="n">{{ activity }}</li>
</ol>
</details>
<el-card
v-for="question in message.result?.questions || []"
:key="question.id"
class="assistant-question"
>
<strong>{{ question.text }}</strong>
<div class="question-options">
<el-button
v-for="option in question.options || []"
:key="option"
:disabled="busy"
@click="
text = question.text + ':' + option;
send();
"
>
{{ option }}
</el-button>
</div>
<small>也可以在下方输入框自由回答。</small>
</el-card>
<el-button
v-if="message.result?.planId && message.taskId"
:disabled="busy || executing"
@click="
active = message.result;
taskId = message.taskId!;
clearCredentials();
"
>
查看此轮计划
</el-button>
<p v-if="message.content">{{ message.content }}</p>
<span v-else-if="message.state === 'working'" class="agent-placeholder">
正在准备回复
@@ -716,9 +864,79 @@ onBeforeUnmount(() => {
</template>
<style scoped>
.mobile-turn-select {
display: none;
}
.turn-navigation button {
opacity: 0.45;
}
.turn-navigation button[aria-current='step'] {
opacity: 1;
}
@media (max-width: 600px) {
.mobile-turn-select {
display: block;
width: 100%;
margin: 8px 0;
max-width: 100%;
padding: 6px;
background: var(--el-bg-color);
color: var(--el-text-color-primary);
border: 1px solid var(--el-border-color);
}
.turn-navigation {
display: none !important;
}
}
.turn-navigation {
position: absolute;
right: 12px;
top: 100px;
display: flex;
flex-direction: column;
gap: 8px;
max-height: 60%;
overflow: auto;
z-index: 2;
}
.turn-navigation button {
width: 28px;
min-height: 24px;
border: 0;
background: transparent;
border-top: 3px solid var(--el-color-primary);
cursor: pointer;
}
.turn-navigation span {
font-size: 10px;
}
.question-options {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 12px 0;
}
.assistant-page {
position: relative;
}
.assistant-conversation {
padding-right: 44px;
}
@media (max-width: 600px) {
.turn-navigation {
right: 4px;
top: 150px;
max-height: 25%;
}
.assistant-conversation {
padding-right: 32px;
}
}
.assistant-page {
max-width: none;
padding: 0;
padding: 16px 24px;
display: flex;
flex-direction: column;
height: 100%;
@@ -738,7 +956,7 @@ onBeforeUnmount(() => {
text-align: center;
}
.assistant-welcome h2 {
font-size: 2em;
font-size: clamp(22px, 1.5em, 36px);
font-weight: 600;
}
.assistant-examples,
@@ -944,6 +1162,7 @@ details > summary {
@media (max-width: 720px) {
.assistant-page {
height: 100%;
padding: 16px;
}
.agent-header {
flex-wrap: wrap;
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { CoursewareFolders } from '@classhelper/ui';
import { countDates } from '@classhelper/ui';
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { SOCKET_EVENTS } from '@classhelper/shared';
@@ -60,7 +61,11 @@ const canWrite = computed(() => auth.can('courseware:write'));
const folders = ref<CoursewareFolderDto[]>([]),
folderPath = ref(''),
folderFilter = ref('');
const grouping = ref<'date' | 'folder'>('date');
const grouping = ref<'date' | 'folder'>('folder');
const folderOwner = ref('');
watch(folderFilter, (value) => {
folderPath.value = value;
});
const teacher = ref('');
const teachers = computed(() => [...new Set(items.value.map((item) => item.teacher.name))]);
async function newFolder() {
@@ -69,7 +74,7 @@ async function newFolder() {
'输入文件夹名称,可用 / 创建多层分类,如 地理/必修一',
'新建文件夹',
);
const path = String(value ?? '').trim();
const path = [folderFilter.value, String(value ?? '').trim()].filter(Boolean).join('/');
if (!path) return;
await api.post('/courseware/folders', { path });
await refresh();
@@ -88,9 +93,10 @@ const dateSource = computed(() =>
(!query.value || `${item.name} ${item.teacher.name}`.includes(query.value)) &&
(!category.value || item.category === category.value) &&
(grouping.value !== 'folder' ||
!folderFilter.value ||
item.folderPath === folderFilter.value ||
item.folderPath?.startsWith(folderFilter.value + '/')) &&
((item.folderPath || '') === folderFilter.value &&
(folderOwner.value
? item.teacher.id === folderOwner.value
: new Set(items.value.map((i) => i.teacher.id)).size <= 1))) &&
(!teacher.value || item.teacher.name === teacher.value),
),
);
@@ -298,6 +304,13 @@ onMounted(() => void refresh());
</el-select>
<ch-date-picker v-model="date" :marks="dateMarks" value-format="YYYY-MM-DD" placeholder="归档日期" />
</div>
<CoursewareFolders
v-if="grouping === 'folder'"
v-model:path="folderFilter"
v-model:owner="folderOwner"
:items="items"
:folders="folders"
/>
<el-table :data="filtered" empty-text="暂无课件">
<el-table-column prop="name" label="文件名称" min-width="220" show-overflow-tooltip />
<el-table-column label="分类 / 归档位置" min-width="230">
+67 -22
View File
@@ -175,13 +175,19 @@ watch(
},
{ flush: 'sync' },
);
async function newLayout() {
async function newLayout(parentId?: string) {
if (!canCreateTime.value || saving.value) return;
const { value } = await ElMessageBox.prompt('输入时间表名称', '新时间表');
const result = await api.post<TimeLayoutDetailDto>('/time-layouts', {
name: value,
classId: classId.value || null,
points: [],
parentId,
points: parentId
? layouts.value
.find((l) => l.id === parentId)
?.points.filter((p) => !p.isAutoBreak)
.map((p) => ({ ...p, id: undefined })) || []
: [],
});
selectedLayout.value = result.id;
await load();
@@ -192,7 +198,9 @@ async function persistLayout(item: TimeLayoutDetailDto) {
throw new Error('时间点的结束时间必须晚于开始时间');
const result = await api.put<TimeLayoutDetailDto>(`/time-layouts/${item.id}`, {
...item,
points: item.points.map((p) => ({ ...p, id: p.id.startsWith('draft-') ? undefined : p.id || undefined })),
points: item.points
.filter((p) => !p.isAutoBreak)
.map((p) => ({ ...p, id: p.id.startsWith('draft-') ? undefined : p.id || undefined })),
});
layouts.value = layouts.value.map((p) => (p.id === result.id ? result : p));
layoutBaseline.value[result.id] = JSON.stringify(result);
@@ -606,15 +614,20 @@ function changeLayout(value: string) {
if (!plan.value) return;
const old = layouts.value.find((l) => l.id === plan.value!.timeLayoutId);
const next = layouts.value.find((l) => l.id === value);
// 时间点通过时间与类型匹配,不能把原外键带进另一张时间表。
plan.value.entries = plan.value.entries.flatMap((e) => {
const oldPoint = old?.points.find((p) => p.id === e.timeLayoutItemId);
const target = next?.points.find(
(p) =>
p.timeType === 'LESSON' && p.startTime === oldPoint?.startTime && p.endTime === oldPoint?.endTime,
);
return target ? [{ ...e, id: '', timeLayoutItemId: target.id }] : [];
const oldLessons = old?.points.filter((p) => p.timeType === 'LESSON') || [];
const nextLessons = next?.points.filter((p) => p.timeType === 'LESSON') || [];
const mapped = plan.value.entries.map((e) => {
const source = oldLessons.find((p) => p.id === e.timeLayoutItemId);
const target =
nextLessons.find((p) => source?.slotKey && p.slotKey === source.slotKey) ||
nextLessons[oldLessons.findIndex((p) => p.id === source?.id)];
return target ? { ...e, id: '', timeLayoutItemId: target.id } : undefined;
});
if (mapped.some((e) => !e)) {
ElMessage.warning('目标时间表节数不足,请先增加课时;原课程已保留。');
return;
}
plan.value.entries = mapped.filter((e): e is NonNullable<typeof e> => Boolean(e));
plan.value.timeLayoutId = value;
selectedLayout.value = value;
}
@@ -753,20 +766,46 @@ type GridRow = {
function pointKey(p: Pick<TimePointDto, 'startTime' | 'endTime' | 'timeType'>) {
return `${p.startTime}|${p.endTime}|${p.timeType}`;
}
const focusedDay = ref<number | null>(null);
function dayPoints(day: number) {
return layouts.value.find((l) => l.id === dayPlan(day)?.timeLayoutId)?.points || [];
}
function visualKey(p: TimePointDto, points: TimePointDto[]) {
return (
p.slotKey ||
(p.timeType === 'LESSON'
? `lesson-${points.filter((x) => x.timeType === 'LESSON').findIndex((x) => x.id === p.id) + 1}`
: pointKey(p))
);
}
const gridRows = computed(() => {
const rows = new Map<string, GridRow>();
for (const day of weekDays.value) {
const l = layouts.value.find((l) => l.id === dayPlan(day.day)?.timeLayoutId);
for (const p of l?.points || []) rows.set(pointKey(p), { ...p, key: pointKey(p) });
}
for (const day of weekDays.value)
for (const p of dayPoints(day.day)) {
const key = visualKey(p, dayPoints(day.day));
if (!rows.has(key)) rows.set(key, { ...p, key });
}
return [...rows.values()].sort(
(a, b) => a.startTime.localeCompare(b.startTime) || a.endTime.localeCompare(b.endTime),
);
});
function gridPoint(day: number, row: GridRow) {
return layouts.value
.find((l) => l.id === dayPlan(day)?.timeLayoutId)
?.points.find((p) => pointKey(p) === row.key);
const points = dayPoints(day);
return points.find((p) => visualKey(p, points) === row.key);
}
function rowTimes(row: GridRow) {
const byTime = new Map<string, string[]>();
for (const day of weekDays.value) {
if (focusedDay.value !== null && day.day !== focusedDay.value) continue;
const p = gridPoint(day.day, row);
if (!p) continue;
const key = `${p.startTime}–${p.endTime}`;
byTime.set(key, [...(byTime.get(key) || []), day.label]);
}
return [...byTime].map(([time, days]) => ({
time,
label: focusedDay.value === null && byTime.size > 1 ? days.join('、') : '',
}));
}
function gridEntry(day: number, row: GridRow) {
const point = gridPoint(day, row);
@@ -780,6 +819,7 @@ function selectCell(day: number, row?: GridRow) {
if (!p) return;
selectedPlan.value = p.id;
selectedDay.value = day;
focusedDay.value = day;
if (row) activePoint.value = gridPoint(day, row)?.id || '';
}
function isSelectedCell(day: number, row: GridRow) {
@@ -1107,7 +1147,7 @@ function selectPlanItem(id: string) {
</template>
</div>
<div v-if="viewMode === 'week'" class="week-view">
<div v-if="viewMode === 'week'" class="week-view" @keydown.esc="focusedDay = null">
<div class="week-scroll">
<table class="schedule-grid" aria-label="周课表">
<colgroup>
@@ -1116,7 +1156,9 @@ function selectPlanItem(id: string) {
</colgroup>
<thead>
<tr>
<th scope="col" class="time-heading">时间</th>
<th scope="col" class="time-heading">
<button class="text-command" @click="focusedDay = null">时间(清除选择)</button>
</th>
<th
v-for="day in weekDays"
:key="day.day"
@@ -1157,8 +1199,10 @@ function selectPlanItem(id: string) {
:class="{ 'non-lesson-row': row.timeType !== 'LESSON' }"
>
<th scope="row" class="time-cell">
<span>{{ row.startTime }}</span>
<small v-if="row.timeType !== 'DIVIDER'">{{ row.endTime }}</small>
<template v-for="time in rowTimes(row)" :key="time.time">
<span>{{ time.time }}</span>
<small v-if="time.label">{{ time.label }}</small>
</template>
</th>
<td
v-for="day in weekDays"
@@ -1449,6 +1493,7 @@ function selectPlanItem(id: string) {
:plan-count="layoutPlanCount"
@select-layout="selectedLayout = $event"
@create="newLayout"
@create-child="newLayout($event)"
@clone="cloneLayout"
@save="saveLayout"
@refresh="refresh"
+39 -2
View File
@@ -13,10 +13,12 @@
* `classId` 留空 = 全校默认;某个班有自己的配置时优先用它。
*/
import { useAuthStore } from '@/stores/auth';
import { computed, onMounted, ref } from 'vue';
import { computed, onMounted, ref, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
getMaxTermWeeks,
buildAutoTermWeeks,
shiftDayKey,
validateTermWeeks,
isDayKey,
type ClassDto,
@@ -97,7 +99,7 @@ async function autoGenerate(): Promise<void> {
...(scope.value ? {} : { maxTermWeeks: maxTermWeeks.value }),
classId: scope.value || null,
termStartDate: termStartDate.value,
maxWeek: term.value?.maxWeek ?? getMaxTermWeeks(),
maxWeek: scope.value ? term.value?.maxWeek : maxTermWeeks.value,
});
term.value = result;
weeks.value = result.weeks.map((item) => ({ ...item }));
@@ -107,7 +109,42 @@ async function autoGenerate(): Promise<void> {
}
}
watch(maxTermWeeks, (maximum, previous) => {
if (
scope.value ||
!term.value ||
(maximum === getMaxTermWeeks(term.value.maxTermWeeks) && previous === maximum)
)
return;
const last = weeks.value.at(-1);
if (!last) {
if (isDayKey(termStartDate.value)) weeks.value = buildAutoTermWeeks(termStartDate.value, maximum);
return;
}
if (maximum > (last.weekNumber ?? 0) && isDayKey(last.endDate)) {
for (
let n = last.weekNumber + 1, start = shiftDayKey(last.endDate, 1);
n <= maximum;
n++, start = shiftDayKey(start, 7)
) {
weeks.value.push({ weekNumber: n, startDate: start, endDate: shiftDayKey(start, 6), note: '' });
}
}
});
async function save(): Promise<void> {
const removed = weeks.value.filter((w) => w.weekNumber > maxTermWeeks.value);
if (!scope.value && removed.length) {
try {
await ElMessageBox.confirm(
`将移除第 ${removed.map((w) => w.weekNumber).join('、')} 周日期区间,确认保存?`,
'缩短学期',
);
} catch {
return;
}
weeks.value = weeks.value.filter((w) => w.weekNumber <= maxTermWeeks.value);
}
if (saving.value) return;
const errors = validateTermWeeks(weeks.value);
if (!isDayKey(termStartDate.value)) errors.unshift('请填写有效的学期开始日期');
+43
View File
@@ -319,6 +319,49 @@ module.exports = async function runAssistantChecks({ win, target, record, waitFo
await win.webContents.executeJavaScript(`document.querySelector('.ch-guide [data-action=skip]').click()`);
assert(await waitFor(win, `!document.querySelector('.ch-guide')`));
record('共享日历支持深色与150%关怀模式,全屏引导在390px小屏无横向溢出', true);
for (const [width, height] of [
[360, 800],
[768, 1024],
[1366, 768],
[1920, 1080],
]) {
win.setContentSize(width, height);
for (const route of [
'assistant',
'courseware',
'term-weeks',
'plan-editor',
'dashboard',
'classes',
'students',
'teachers',
'promotion',
'archives',
'homeworks',
'notifications',
'grades',
'ai-settings',
'database',
'permissions',
'clients',
'system-settings',
]) {
await win.loadURL(origin + '/' + route);
assert(
await waitFor(
win,
`location.pathname === ${JSON.stringify('/' + route)} && Boolean(document.querySelector('.page, .page-container'))`,
),
);
await new Promise((resolve) => setTimeout(resolve, 100));
assert(
await waitFor(win, `document.documentElement.scrollWidth<=innerWidth+1`),
route + ' 页面溢出 ' + width,
);
}
await screenshot('responsive-' + width);
}
record('全部Web业务页面在360/768/1366/1920宽度无页面横向溢出', true);
} catch (error) {
record('AI 与共享控件隔离界面验收', false, error.stack || error.message);
} finally {