@studious-lms/server 1.26.0 → 1.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +3 -1
- package/.github/workflows/npm-publish.yml +1 -0
- package/AGENTS.md +84 -0
- package/dist/models/cloudStorage.d.ts +11 -0
- package/dist/models/cloudStorage.d.ts.map +1 -1
- package/dist/models/cloudStorage.js +18 -2
- package/dist/models/cloudStorage.js.map +1 -1
- package/dist/models/conversation.d.ts +1 -0
- package/dist/models/conversation.d.ts.map +1 -1
- package/dist/models/labChat.d.ts +40 -0
- package/dist/models/labChat.d.ts.map +1 -1
- package/dist/models/labChat.js +32 -2
- package/dist/models/labChat.js.map +1 -1
- package/dist/models/message.d.ts +3 -0
- package/dist/models/message.d.ts.map +1 -1
- package/dist/pipelines/aiLabChat.d.ts +2 -0
- package/dist/pipelines/aiLabChat.d.ts.map +1 -1
- package/dist/pipelines/aiLabChat.js +60 -16
- package/dist/pipelines/aiLabChat.js.map +1 -1
- package/dist/pipelines/aiLabChatContract.d.ts +170 -2
- package/dist/pipelines/aiLabChatContract.d.ts.map +1 -1
- package/dist/pipelines/aiLabChatContract.js +30 -2
- package/dist/pipelines/aiLabChatContract.js.map +1 -1
- package/dist/pipelines/aiNewtonChat.d.ts.map +1 -1
- package/dist/pipelines/aiNewtonChat.js +30 -5
- package/dist/pipelines/aiNewtonChat.js.map +1 -1
- package/dist/pipelines/labChatPrompt.d.ts +1 -1
- package/dist/pipelines/labChatPrompt.d.ts.map +1 -1
- package/dist/pipelines/labChatPrompt.js +13 -14
- package/dist/pipelines/labChatPrompt.js.map +1 -1
- package/dist/routers/_app.d.ts +220 -10
- package/dist/routers/_app.d.ts.map +1 -1
- package/dist/routers/admin.d.ts +0 -1
- package/dist/routers/admin.d.ts.map +1 -1
- package/dist/routers/conversation.d.ts +1 -0
- package/dist/routers/conversation.d.ts.map +1 -1
- package/dist/routers/labChat.d.ts +10 -0
- package/dist/routers/labChat.d.ts.map +1 -1
- package/dist/routers/labChat.js +6 -3
- package/dist/routers/labChat.js.map +1 -1
- package/dist/routers/message.d.ts +37 -4
- package/dist/routers/message.d.ts.map +1 -1
- package/dist/routers/message.js +24 -7
- package/dist/routers/message.js.map +1 -1
- package/dist/routers/parent.d.ts +18 -0
- package/dist/routers/parent.d.ts.map +1 -1
- package/dist/routers/parent.js +10 -3
- package/dist/routers/parent.js.map +1 -1
- package/dist/routers/studentProgress.d.ts +44 -0
- package/dist/routers/studentProgress.d.ts.map +1 -1
- package/dist/routers/studentProgress.js +12 -3
- package/dist/routers/studentProgress.js.map +1 -1
- package/dist/routes/aiStream.js +32 -2
- package/dist/routes/aiStream.js.map +1 -1
- package/dist/seedDatabase.d.ts.map +1 -1
- package/dist/seedDatabase.js +107 -3
- package/dist/seedDatabase.js.map +1 -1
- package/dist/services/adminUser.d.ts +0 -1
- package/dist/services/adminUser.d.ts.map +1 -1
- package/dist/services/adminUser.js +7 -4
- package/dist/services/adminUser.js.map +1 -1
- package/dist/services/aiChatStream.d.ts +15 -0
- package/dist/services/aiChatStream.d.ts.map +1 -1
- package/dist/services/aiChatStream.js +144 -74
- package/dist/services/aiChatStream.js.map +1 -1
- package/dist/services/aiGeneration.d.ts +4 -0
- package/dist/services/aiGeneration.d.ts.map +1 -0
- package/dist/services/aiGeneration.js +88 -0
- package/dist/services/aiGeneration.js.map +1 -0
- package/dist/services/aiProposalTools.d.ts +4 -1
- package/dist/services/aiProposalTools.d.ts.map +1 -1
- package/dist/services/aiProposalTools.js +128 -3
- package/dist/services/aiProposalTools.js.map +1 -1
- package/dist/services/aiProposals.d.ts +70 -0
- package/dist/services/aiProposals.d.ts.map +1 -0
- package/dist/services/aiProposals.js +363 -0
- package/dist/services/aiProposals.js.map +1 -0
- package/dist/services/conversation.d.ts +1 -0
- package/dist/services/conversation.d.ts.map +1 -1
- package/dist/services/labChat.d.ts +10 -0
- package/dist/services/labChat.d.ts.map +1 -1
- package/dist/services/labChat.js +52 -3
- package/dist/services/labChat.js.map +1 -1
- package/dist/services/message.d.ts +24 -8
- package/dist/services/message.d.ts.map +1 -1
- package/dist/services/message.js +170 -117
- package/dist/services/message.js.map +1 -1
- package/dist/services/parentPortal.d.ts +14 -0
- package/dist/services/parentPortal.d.ts.map +1 -1
- package/dist/services/parentPortal.js +72 -2
- package/dist/services/parentPortal.js.map +1 -1
- package/dist/services/studentProgress.d.ts +50 -0
- package/dist/services/studentProgress.d.ts.map +1 -1
- package/dist/services/studentProgress.js +107 -2
- package/dist/services/studentProgress.js.map +1 -1
- package/dist/utils/inference.d.ts +10 -0
- package/dist/utils/inference.d.ts.map +1 -1
- package/dist/utils/inference.js +77 -2
- package/dist/utils/inference.js.map +1 -1
- package/dist/workers/processors/createRunJobWorker.js +17 -16
- package/dist/workers/processors/createRunJobWorker.js.map +1 -1
- package/package.json +1 -1
- package/prisma/migrations/20260811130000_add_ai_message_feedback/migration.sql +7 -0
- package/prisma/schema.prisma +8 -0
- package/src/models/cloudStorage.ts +19 -0
- package/src/models/labChat.ts +34 -0
- package/src/pipelines/aiLabChat.ts +79 -18
- package/src/pipelines/aiLabChatContract.ts +35 -0
- package/src/pipelines/aiNewtonChat.ts +34 -2
- package/src/pipelines/labChatPrompt.ts +11 -12
- package/src/routers/labChat.ts +5 -0
- package/src/routers/message.ts +34 -5
- package/src/routers/parent.ts +11 -0
- package/src/routers/studentProgress.ts +15 -0
- package/src/routes/aiStream.ts +32 -0
- package/src/seedDatabase.ts +107 -2
- package/src/services/adminUser.ts +5 -2
- package/src/services/aiChatStream.ts +83 -7
- package/src/services/aiGeneration.ts +92 -0
- package/src/services/aiProposalTools.ts +166 -1
- package/src/services/aiProposals.ts +428 -0
- package/src/services/labChat.ts +65 -0
- package/src/services/message.ts +205 -142
- package/src/services/parentPortal.ts +85 -0
- package/src/services/studentProgress.ts +135 -0
- package/src/utils/inference.ts +85 -0
- package/src/workers/processors/createRunJobWorker.ts +17 -17
- package/tests/unit/services/adminUser.test.ts +75 -0
- package/tests/unit/utils/adminPanelAccess.test.ts +26 -0
|
@@ -22,6 +22,9 @@ import type {
|
|
|
22
22
|
WorksheetToCreate,
|
|
23
23
|
SectionToCreate,
|
|
24
24
|
DocToCreate,
|
|
25
|
+
AssignmentUpdate,
|
|
26
|
+
WorksheetUpdate,
|
|
27
|
+
SectionUpdate,
|
|
25
28
|
} from '../pipelines/aiLabChatContract.js';
|
|
26
29
|
|
|
27
30
|
export interface LabProposals {
|
|
@@ -29,10 +32,21 @@ export interface LabProposals {
|
|
|
29
32
|
worksheets: WorksheetToCreate[];
|
|
30
33
|
sections: SectionToCreate[];
|
|
31
34
|
docs: DocToCreate[];
|
|
35
|
+
assignmentUpdates: AssignmentUpdate[];
|
|
36
|
+
worksheetUpdates: WorksheetUpdate[];
|
|
37
|
+
sectionUpdates: SectionUpdate[];
|
|
32
38
|
}
|
|
33
39
|
|
|
34
40
|
export function createLabProposals(): LabProposals {
|
|
35
|
-
return {
|
|
41
|
+
return {
|
|
42
|
+
assignments: [],
|
|
43
|
+
worksheets: [],
|
|
44
|
+
sections: [],
|
|
45
|
+
docs: [],
|
|
46
|
+
assignmentUpdates: [],
|
|
47
|
+
worksheetUpdates: [],
|
|
48
|
+
sectionUpdates: [],
|
|
49
|
+
};
|
|
36
50
|
}
|
|
37
51
|
|
|
38
52
|
function normalizeDueDate(input?: string | null): string {
|
|
@@ -82,6 +96,34 @@ interface ProposeAssignmentArgs {
|
|
|
82
96
|
acceptWorksheet?: boolean;
|
|
83
97
|
}
|
|
84
98
|
|
|
99
|
+
interface ProposeUpdateAssignmentArgs {
|
|
100
|
+
id: string;
|
|
101
|
+
targetTitle: string;
|
|
102
|
+
title?: string;
|
|
103
|
+
instructions?: string;
|
|
104
|
+
dueDate?: string;
|
|
105
|
+
type?: AssignmentType;
|
|
106
|
+
maxGrade?: number;
|
|
107
|
+
acceptFiles?: boolean;
|
|
108
|
+
acceptExtendedResponse?: boolean;
|
|
109
|
+
acceptWorksheet?: boolean;
|
|
110
|
+
sectionId?: string | null;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
interface ProposeUpdateWorksheetArgs {
|
|
114
|
+
id: string;
|
|
115
|
+
targetTitle: string;
|
|
116
|
+
name?: string;
|
|
117
|
+
addQuestions?: ProposeWorksheetArgs['questions'];
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
interface ProposeUpdateSectionArgs {
|
|
121
|
+
id: string;
|
|
122
|
+
targetTitle: string;
|
|
123
|
+
name: string;
|
|
124
|
+
color?: string | null;
|
|
125
|
+
}
|
|
126
|
+
|
|
85
127
|
interface GenerateDocumentArgs {
|
|
86
128
|
title: string;
|
|
87
129
|
content: string;
|
|
@@ -235,6 +277,129 @@ export function labProposalTools(proposals: LabProposals): ToolSet {
|
|
|
235
277
|
},
|
|
236
278
|
},
|
|
237
279
|
|
|
280
|
+
propose_update_assignment: {
|
|
281
|
+
description:
|
|
282
|
+
'Propose changes to an EXISTING assignment. Only pass the fields that should change; use the assignment id from CLASS CONTEXT.',
|
|
283
|
+
inputSchema: jsonSchema({
|
|
284
|
+
type: 'object',
|
|
285
|
+
properties: {
|
|
286
|
+
id: { type: 'string', description: 'Database id of the existing assignment' },
|
|
287
|
+
targetTitle: { type: 'string', description: "The assignment's current title (shown on the approval card)" },
|
|
288
|
+
title: { type: 'string', description: 'New title, if renaming' },
|
|
289
|
+
instructions: { type: 'string' },
|
|
290
|
+
dueDate: { type: 'string', description: 'ISO 8601 datetime' },
|
|
291
|
+
type: { type: 'string', enum: ASSIGNMENT_TYPES as unknown as string[] },
|
|
292
|
+
maxGrade: { type: 'number' },
|
|
293
|
+
acceptFiles: { type: 'boolean' },
|
|
294
|
+
acceptExtendedResponse: { type: 'boolean' },
|
|
295
|
+
acceptWorksheet: { type: 'boolean' },
|
|
296
|
+
sectionId: { type: 'string', description: 'Move to this section (id from CLASS CONTEXT)' },
|
|
297
|
+
},
|
|
298
|
+
required: ['id', 'targetTitle'],
|
|
299
|
+
}),
|
|
300
|
+
execute: async (args: ProposeUpdateAssignmentArgs) => {
|
|
301
|
+
proposals.assignmentUpdates.push({
|
|
302
|
+
...args,
|
|
303
|
+
dueDate: args.dueDate ? normalizeDueDate(args.dueDate) : undefined,
|
|
304
|
+
});
|
|
305
|
+
return `Update to assignment "${args.targetTitle}" proposed.`;
|
|
306
|
+
},
|
|
307
|
+
},
|
|
308
|
+
|
|
309
|
+
propose_update_worksheet: {
|
|
310
|
+
description:
|
|
311
|
+
'Propose changes to an EXISTING worksheet: rename it and/or append new questions. Use the worksheet id from CLASS CONTEXT.',
|
|
312
|
+
inputSchema: jsonSchema({
|
|
313
|
+
type: 'object',
|
|
314
|
+
properties: {
|
|
315
|
+
id: { type: 'string', description: 'Database id of the existing worksheet' },
|
|
316
|
+
targetTitle: { type: 'string', description: "The worksheet's current name (shown on the approval card)" },
|
|
317
|
+
name: { type: 'string', description: 'New name, if renaming' },
|
|
318
|
+
addQuestions: {
|
|
319
|
+
type: 'array',
|
|
320
|
+
description: 'New questions to append to the worksheet',
|
|
321
|
+
items: {
|
|
322
|
+
type: 'object',
|
|
323
|
+
properties: {
|
|
324
|
+
type: { type: 'string', enum: QUESTION_TYPES as unknown as string[] },
|
|
325
|
+
question: { type: 'string' },
|
|
326
|
+
answer: { type: 'string' },
|
|
327
|
+
options: {
|
|
328
|
+
type: 'array',
|
|
329
|
+
items: {
|
|
330
|
+
type: 'object',
|
|
331
|
+
properties: {
|
|
332
|
+
text: { type: 'string' },
|
|
333
|
+
isCorrect: { type: 'boolean' },
|
|
334
|
+
},
|
|
335
|
+
required: ['text', 'isCorrect'],
|
|
336
|
+
},
|
|
337
|
+
},
|
|
338
|
+
markScheme: {
|
|
339
|
+
type: 'array',
|
|
340
|
+
items: {
|
|
341
|
+
type: 'object',
|
|
342
|
+
properties: {
|
|
343
|
+
points: { type: 'number' },
|
|
344
|
+
description: { type: 'string' },
|
|
345
|
+
},
|
|
346
|
+
required: ['points', 'description'],
|
|
347
|
+
},
|
|
348
|
+
},
|
|
349
|
+
points: { type: 'number' },
|
|
350
|
+
},
|
|
351
|
+
required: ['type', 'question'],
|
|
352
|
+
},
|
|
353
|
+
},
|
|
354
|
+
},
|
|
355
|
+
required: ['id', 'targetTitle'],
|
|
356
|
+
}),
|
|
357
|
+
execute: async ({ id, targetTitle, name, addQuestions }: ProposeUpdateWorksheetArgs) => {
|
|
358
|
+
proposals.worksheetUpdates.push({
|
|
359
|
+
id,
|
|
360
|
+
targetTitle,
|
|
361
|
+
name,
|
|
362
|
+
addQuestions: (addQuestions ?? []).map((q, index) => ({
|
|
363
|
+
type: q.type,
|
|
364
|
+
question: q.question,
|
|
365
|
+
answer: q.answer ?? '',
|
|
366
|
+
options: (q.options ?? []).map((o) => ({
|
|
367
|
+
id: v4(),
|
|
368
|
+
text: o.text,
|
|
369
|
+
isCorrect: o.isCorrect,
|
|
370
|
+
})),
|
|
371
|
+
markScheme: (q.markScheme ?? []).map((m) => ({
|
|
372
|
+
id: v4(),
|
|
373
|
+
points: m.points,
|
|
374
|
+
description: m.description,
|
|
375
|
+
})),
|
|
376
|
+
points: q.points ?? 0,
|
|
377
|
+
order: index,
|
|
378
|
+
})),
|
|
379
|
+
});
|
|
380
|
+
return `Update to worksheet "${targetTitle}" proposed.`;
|
|
381
|
+
},
|
|
382
|
+
},
|
|
383
|
+
|
|
384
|
+
propose_update_section: {
|
|
385
|
+
description:
|
|
386
|
+
'Propose changes to an EXISTING section (rename and/or recolor). Use the section id from CLASS CONTEXT. Always pass name (the resulting name, even if unchanged).',
|
|
387
|
+
inputSchema: jsonSchema({
|
|
388
|
+
type: 'object',
|
|
389
|
+
properties: {
|
|
390
|
+
id: { type: 'string', description: 'Database id of the existing section' },
|
|
391
|
+
targetTitle: { type: 'string', description: "The section's current name (shown on the approval card)" },
|
|
392
|
+
name: { type: 'string', description: 'Resulting section name (pass the current name if only changing color)' },
|
|
393
|
+
color: { type: 'string', description: 'Optional hex color like #3b82f6' },
|
|
394
|
+
},
|
|
395
|
+
required: ['id', 'targetTitle', 'name'],
|
|
396
|
+
}),
|
|
397
|
+
execute: async ({ id, targetTitle, name, color }: ProposeUpdateSectionArgs) => {
|
|
398
|
+
proposals.sectionUpdates.push({ id, targetTitle, name, color: color ?? null });
|
|
399
|
+
return `Update to section "${targetTitle}" proposed.`;
|
|
400
|
+
},
|
|
401
|
+
},
|
|
402
|
+
|
|
238
403
|
generate_document: {
|
|
239
404
|
description:
|
|
240
405
|
'Generate a downloadable file and attach it to this message. Pick the best format for the request — pptx for slides, xlsx/csv for data, docx for editable handouts, pdf for print-ready docs, png/jpeg for charts/diagrams/figures (NOT pdf for visuals). Use py/js/ts only when the teacher explicitly wants source code. Always set format explicitly.',
|
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI creation proposals – defer-and-confirm flow for Lab chat.
|
|
3
|
+
*
|
|
4
|
+
* The lab pipeline records every `propose_*` tool call as a pending creation
|
|
5
|
+
* on the AI message's meta (`meta.pendingCreations`). Nothing is created at
|
|
6
|
+
* generation time: the teacher approves or dismisses each proposal from the
|
|
7
|
+
* chat, and approval creates the real entity server-side.
|
|
8
|
+
*/
|
|
9
|
+
import { TRPCError } from "@trpc/server";
|
|
10
|
+
import { v4 } from "uuid";
|
|
11
|
+
import { prisma } from "../lib/prisma.js";
|
|
12
|
+
import { chatChannel, pusher } from "../lib/pusher.js";
|
|
13
|
+
import { logger } from "../utils/logger.js";
|
|
14
|
+
import {
|
|
15
|
+
findConversationMembership,
|
|
16
|
+
findMessageByIdMinimal,
|
|
17
|
+
messageFileSelect,
|
|
18
|
+
} from "../models/message.js";
|
|
19
|
+
import { createAssignmentRecord, updateAssignmentRecord } from "./assignment.js";
|
|
20
|
+
import {
|
|
21
|
+
createWorksheetRecord,
|
|
22
|
+
addQuestionToWorksheet,
|
|
23
|
+
updateWorksheetRecord,
|
|
24
|
+
} from "./worksheet.js";
|
|
25
|
+
import { createSectionRecord, updateSectionRecord } from "./section.js";
|
|
26
|
+
import type { StreamPart } from "./aiChatStream.js";
|
|
27
|
+
import type { LabProposals } from "./aiProposalTools.js";
|
|
28
|
+
import type {
|
|
29
|
+
AssignmentToCreate,
|
|
30
|
+
WorksheetToCreate,
|
|
31
|
+
SectionToCreate,
|
|
32
|
+
AssignmentUpdate,
|
|
33
|
+
WorksheetUpdate,
|
|
34
|
+
SectionUpdate,
|
|
35
|
+
} from "../pipelines/aiLabChatContract.js";
|
|
36
|
+
|
|
37
|
+
export type PendingCreationStatus = "pending" | "approved" | "dismissed";
|
|
38
|
+
|
|
39
|
+
export type PendingCreation =
|
|
40
|
+
| { id: string; kind: "assignment"; title: string; payload: AssignmentToCreate; status: PendingCreationStatus; createdId?: string }
|
|
41
|
+
| { id: string; kind: "worksheet"; title: string; payload: WorksheetToCreate; status: PendingCreationStatus; createdId?: string }
|
|
42
|
+
| { id: string; kind: "section"; title: string; payload: SectionToCreate; status: PendingCreationStatus; createdId?: string }
|
|
43
|
+
| { id: string; kind: "assignmentUpdate"; title: string; payload: AssignmentUpdate; status: PendingCreationStatus; createdId?: string }
|
|
44
|
+
| { id: string; kind: "worksheetUpdate"; title: string; payload: WorksheetUpdate; status: PendingCreationStatus; createdId?: string }
|
|
45
|
+
| { id: string; kind: "sectionUpdate"; title: string; payload: SectionUpdate; status: PendingCreationStatus; createdId?: string };
|
|
46
|
+
|
|
47
|
+
const PROPOSAL_TOOL_KIND: Record<string, PendingCreation["kind"]> = {
|
|
48
|
+
propose_assignment: "assignment",
|
|
49
|
+
propose_worksheet: "worksheet",
|
|
50
|
+
propose_section: "section",
|
|
51
|
+
propose_update_assignment: "assignmentUpdate",
|
|
52
|
+
propose_update_worksheet: "worksheetUpdate",
|
|
53
|
+
propose_update_section: "sectionUpdate",
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Turn the stream's accumulated proposals into pending creations and stamp
|
|
58
|
+
* each `propose_*` tool part with its proposal id so the client can render
|
|
59
|
+
* the confirmation card inline at the tool-call position.
|
|
60
|
+
*/
|
|
61
|
+
export function buildPendingCreations(
|
|
62
|
+
proposals: LabProposals,
|
|
63
|
+
parts: StreamPart[],
|
|
64
|
+
): { pendingCreations: PendingCreation[]; parts: StreamPart[] } {
|
|
65
|
+
const pendingCreations: PendingCreation[] = [
|
|
66
|
+
...proposals.assignments.map((payload): PendingCreation => ({
|
|
67
|
+
id: v4(), kind: "assignment", title: payload.title, payload, status: "pending",
|
|
68
|
+
})),
|
|
69
|
+
...proposals.worksheets.map((payload): PendingCreation => ({
|
|
70
|
+
id: v4(), kind: "worksheet", title: payload.title, payload, status: "pending",
|
|
71
|
+
})),
|
|
72
|
+
...proposals.sections.map((payload): PendingCreation => ({
|
|
73
|
+
id: v4(), kind: "section", title: payload.name, payload, status: "pending",
|
|
74
|
+
})),
|
|
75
|
+
...proposals.assignmentUpdates.map((payload): PendingCreation => ({
|
|
76
|
+
id: v4(), kind: "assignmentUpdate", title: payload.targetTitle, payload, status: "pending",
|
|
77
|
+
})),
|
|
78
|
+
...proposals.worksheetUpdates.map((payload): PendingCreation => ({
|
|
79
|
+
id: v4(), kind: "worksheetUpdate", title: payload.targetTitle, payload, status: "pending",
|
|
80
|
+
})),
|
|
81
|
+
...proposals.sectionUpdates.map((payload): PendingCreation => ({
|
|
82
|
+
id: v4(), kind: "sectionUpdate", title: payload.targetTitle, payload, status: "pending",
|
|
83
|
+
})),
|
|
84
|
+
];
|
|
85
|
+
|
|
86
|
+
const remaining = new Map<PendingCreation["kind"], PendingCreation[]>();
|
|
87
|
+
for (const creation of pendingCreations) {
|
|
88
|
+
const list = remaining.get(creation.kind) ?? [];
|
|
89
|
+
list.push(creation);
|
|
90
|
+
remaining.set(creation.kind, list);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const stamped = parts.map((part) => {
|
|
94
|
+
if (part.type !== "tool") return part;
|
|
95
|
+
const kind = PROPOSAL_TOOL_KIND[part.toolName];
|
|
96
|
+
if (!kind) return part;
|
|
97
|
+
const list = remaining.get(kind);
|
|
98
|
+
if (!list || list.length === 0) return part;
|
|
99
|
+
// Prefer a title match; fall back to stream order.
|
|
100
|
+
const idx = part.title
|
|
101
|
+
? list.findIndex((c) => c.title.trim().toLowerCase() === part.title!.trim().toLowerCase())
|
|
102
|
+
: 0;
|
|
103
|
+
const creation = list.splice(idx >= 0 ? idx : 0, 1)[0];
|
|
104
|
+
return { ...part, proposalId: creation.id };
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
return { pendingCreations, parts: stamped };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const RESOLVE_MAX_RETRIES = 5;
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Compare-and-swap a proposal's status inside message meta. Returns the new
|
|
114
|
+
* meta on success, or null when the proposal was not in `fromStatus`.
|
|
115
|
+
*/
|
|
116
|
+
async function casProposalStatus(
|
|
117
|
+
messageId: string,
|
|
118
|
+
proposalId: string,
|
|
119
|
+
fromStatus: PendingCreationStatus,
|
|
120
|
+
patch: Partial<Pick<PendingCreation, "status" | "createdId">>,
|
|
121
|
+
): Promise<Record<string, unknown> | null> {
|
|
122
|
+
for (let attempt = 0; attempt < RESOLVE_MAX_RETRIES; attempt++) {
|
|
123
|
+
const msg = await prisma.message.findUnique({
|
|
124
|
+
where: { id: messageId },
|
|
125
|
+
select: { meta: true },
|
|
126
|
+
});
|
|
127
|
+
if (!msg) {
|
|
128
|
+
throw new TRPCError({ code: "NOT_FOUND", message: "Message not found" });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const currentMeta = (msg.meta as Record<string, unknown>) ?? {};
|
|
132
|
+
const creations = Array.isArray(currentMeta.pendingCreations)
|
|
133
|
+
? (currentMeta.pendingCreations as PendingCreation[])
|
|
134
|
+
: [];
|
|
135
|
+
const target = creations.find((c) => c.id === proposalId);
|
|
136
|
+
if (!target) {
|
|
137
|
+
throw new TRPCError({ code: "NOT_FOUND", message: "Proposal not found" });
|
|
138
|
+
}
|
|
139
|
+
if (target.status !== fromStatus) return null;
|
|
140
|
+
|
|
141
|
+
const newMeta = {
|
|
142
|
+
...currentMeta,
|
|
143
|
+
pendingCreations: creations.map((c) =>
|
|
144
|
+
c.id === proposalId ? { ...c, ...patch } : c,
|
|
145
|
+
),
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
const newMetaJson = JSON.stringify(newMeta);
|
|
149
|
+
const currentMetaJson = msg.meta === null ? null : JSON.stringify(msg.meta);
|
|
150
|
+
const updatedCount =
|
|
151
|
+
currentMetaJson === null
|
|
152
|
+
? await prisma.$executeRaw`
|
|
153
|
+
UPDATE "Message" SET meta = ${newMetaJson}::jsonb
|
|
154
|
+
WHERE id = ${messageId} AND meta IS NULL
|
|
155
|
+
`
|
|
156
|
+
: await prisma.$executeRaw`
|
|
157
|
+
UPDATE "Message" SET meta = ${newMetaJson}::jsonb
|
|
158
|
+
WHERE id = ${messageId} AND meta = ${currentMetaJson}::jsonb
|
|
159
|
+
`;
|
|
160
|
+
|
|
161
|
+
if (Number(updatedCount) > 0) return newMeta;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
throw new TRPCError({
|
|
165
|
+
code: "CONFLICT",
|
|
166
|
+
message: "Failed to update proposal after retries due to concurrent updates",
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async function broadcastMessageMeta(messageId: string, conversationId: string) {
|
|
171
|
+
const updated = await prisma.message.findUnique({
|
|
172
|
+
where: { id: messageId },
|
|
173
|
+
include: {
|
|
174
|
+
sender: {
|
|
175
|
+
select: {
|
|
176
|
+
id: true,
|
|
177
|
+
username: true,
|
|
178
|
+
profile: { select: { displayName: true, profilePicture: true } },
|
|
179
|
+
},
|
|
180
|
+
},
|
|
181
|
+
attachments: { select: messageFileSelect },
|
|
182
|
+
mentions: { select: { userId: true } },
|
|
183
|
+
},
|
|
184
|
+
});
|
|
185
|
+
if (!updated) return;
|
|
186
|
+
|
|
187
|
+
try {
|
|
188
|
+
await pusher.trigger(chatChannel(conversationId), "message-updated", {
|
|
189
|
+
id: updated.id,
|
|
190
|
+
content: updated.content,
|
|
191
|
+
senderId: updated.senderId,
|
|
192
|
+
conversationId: updated.conversationId,
|
|
193
|
+
status: updated.status,
|
|
194
|
+
createdAt: updated.createdAt,
|
|
195
|
+
sender: updated.sender,
|
|
196
|
+
attachments: updated.attachments ?? [],
|
|
197
|
+
meta: updated.meta,
|
|
198
|
+
mentionedUserIds: updated.mentions.map((m) => m.userId),
|
|
199
|
+
});
|
|
200
|
+
} catch (error) {
|
|
201
|
+
logger.error("Failed to broadcast proposal resolution via Pusher", {
|
|
202
|
+
error,
|
|
203
|
+
messageId,
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Create or update the proposed entity; returns the affected entity's id. */
|
|
209
|
+
async function createProposedEntity(
|
|
210
|
+
userId: string,
|
|
211
|
+
classId: string,
|
|
212
|
+
proposal: PendingCreation,
|
|
213
|
+
): Promise<string> {
|
|
214
|
+
switch (proposal.kind) {
|
|
215
|
+
case "sectionUpdate": {
|
|
216
|
+
const payload = proposal.payload;
|
|
217
|
+
await updateSectionRecord(userId, {
|
|
218
|
+
id: payload.id,
|
|
219
|
+
classId,
|
|
220
|
+
name: payload.name,
|
|
221
|
+
color: payload.color ?? undefined,
|
|
222
|
+
});
|
|
223
|
+
return payload.id;
|
|
224
|
+
}
|
|
225
|
+
case "worksheetUpdate": {
|
|
226
|
+
const payload = proposal.payload;
|
|
227
|
+
if (payload.name) {
|
|
228
|
+
await updateWorksheetRecord(payload.id, userId, { name: payload.name });
|
|
229
|
+
}
|
|
230
|
+
for (const question of payload.addQuestions ?? []) {
|
|
231
|
+
await addQuestionToWorksheet(payload.id, userId, {
|
|
232
|
+
question: question.question,
|
|
233
|
+
answer: question.answer,
|
|
234
|
+
points: question.points,
|
|
235
|
+
options: question.options,
|
|
236
|
+
markScheme: question.markScheme,
|
|
237
|
+
type: question.type,
|
|
238
|
+
order: question.order,
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
return payload.id;
|
|
242
|
+
}
|
|
243
|
+
case "assignmentUpdate": {
|
|
244
|
+
const payload = proposal.payload;
|
|
245
|
+
await updateAssignmentRecord(userId, {
|
|
246
|
+
id: payload.id,
|
|
247
|
+
classId,
|
|
248
|
+
title: payload.title,
|
|
249
|
+
instructions: payload.instructions,
|
|
250
|
+
dueDate: payload.dueDate,
|
|
251
|
+
type: payload.type,
|
|
252
|
+
maxGrade: payload.maxGrade,
|
|
253
|
+
acceptFiles: payload.acceptFiles,
|
|
254
|
+
acceptExtendedResponse: payload.acceptExtendedResponse,
|
|
255
|
+
acceptWorksheet: payload.acceptWorksheet,
|
|
256
|
+
sectionId: payload.sectionId,
|
|
257
|
+
});
|
|
258
|
+
return payload.id;
|
|
259
|
+
}
|
|
260
|
+
case "section": {
|
|
261
|
+
const section = await createSectionRecord(userId, {
|
|
262
|
+
classId,
|
|
263
|
+
name: proposal.payload.name,
|
|
264
|
+
color: proposal.payload.color ?? undefined,
|
|
265
|
+
});
|
|
266
|
+
return section.id;
|
|
267
|
+
}
|
|
268
|
+
case "worksheet": {
|
|
269
|
+
const worksheet = await createWorksheetRecord(classId, proposal.payload.title);
|
|
270
|
+
for (const question of proposal.payload.questions) {
|
|
271
|
+
await addQuestionToWorksheet(worksheet.id, userId, {
|
|
272
|
+
question: question.question,
|
|
273
|
+
answer: question.answer,
|
|
274
|
+
points: question.points,
|
|
275
|
+
options: question.options,
|
|
276
|
+
markScheme: question.markScheme,
|
|
277
|
+
type: question.type,
|
|
278
|
+
order: question.order,
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
return worksheet.id;
|
|
282
|
+
}
|
|
283
|
+
case "assignment": {
|
|
284
|
+
const payload = proposal.payload;
|
|
285
|
+
const assignment = await createAssignmentRecord(userId, {
|
|
286
|
+
classId,
|
|
287
|
+
title: payload.title,
|
|
288
|
+
instructions: payload.instructions,
|
|
289
|
+
dueDate: payload.dueDate,
|
|
290
|
+
type: payload.type,
|
|
291
|
+
maxGrade: payload.maxGrade,
|
|
292
|
+
acceptFiles: payload.acceptFiles,
|
|
293
|
+
acceptExtendedResponse: payload.acceptExtendedResponse,
|
|
294
|
+
acceptWorksheet: payload.acceptWorksheet,
|
|
295
|
+
gradingBoundaryId: payload.gradingBoundaryId ?? undefined,
|
|
296
|
+
markSchemeId: payload.markSchemeId ?? undefined,
|
|
297
|
+
worksheetIds: payload.worksheetIds,
|
|
298
|
+
studentIds: payload.studentIds,
|
|
299
|
+
sectionId: payload.sectionId ?? undefined,
|
|
300
|
+
existingFileIds: payload.attachments.map((a) => a.id),
|
|
301
|
+
});
|
|
302
|
+
return assignment.id;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Approve or dismiss a pending AI creation proposal. Approval creates the
|
|
309
|
+
* entity server-side; both outcomes persist to message meta and broadcast a
|
|
310
|
+
* `message-updated` event so every client (and reloads) see the final state.
|
|
311
|
+
*/
|
|
312
|
+
export async function resolveAiProposal(
|
|
313
|
+
userId: string,
|
|
314
|
+
input: { messageId: string; proposalId: string; action: "approve" | "dismiss" },
|
|
315
|
+
) {
|
|
316
|
+
const { messageId, proposalId, action } = input;
|
|
317
|
+
|
|
318
|
+
const message = await findMessageByIdMinimal(messageId);
|
|
319
|
+
if (!message) {
|
|
320
|
+
throw new TRPCError({ code: "NOT_FOUND", message: "Message not found" });
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
const membership = await findConversationMembership(
|
|
324
|
+
message.conversationId,
|
|
325
|
+
userId,
|
|
326
|
+
);
|
|
327
|
+
if (!membership) {
|
|
328
|
+
throw new TRPCError({
|
|
329
|
+
code: "FORBIDDEN",
|
|
330
|
+
message: "Not a member of this conversation",
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const labChat = await prisma.labChat.findFirst({
|
|
335
|
+
where: { conversationId: message.conversationId },
|
|
336
|
+
select: { classId: true },
|
|
337
|
+
});
|
|
338
|
+
if (!labChat) {
|
|
339
|
+
throw new TRPCError({
|
|
340
|
+
code: "BAD_REQUEST",
|
|
341
|
+
message: "Proposals can only be resolved in lab chats",
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const teaches = await prisma.class.findFirst({
|
|
346
|
+
where: { id: labChat.classId, teachers: { some: { id: userId } } },
|
|
347
|
+
select: { id: true },
|
|
348
|
+
});
|
|
349
|
+
if (!teaches) {
|
|
350
|
+
throw new TRPCError({
|
|
351
|
+
code: "FORBIDDEN",
|
|
352
|
+
message: "Only class teachers can resolve proposals",
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const currentMeta = await prisma.message.findUnique({
|
|
357
|
+
where: { id: messageId },
|
|
358
|
+
select: { meta: true },
|
|
359
|
+
});
|
|
360
|
+
const creations = Array.isArray(
|
|
361
|
+
(currentMeta?.meta as Record<string, unknown> | null)?.pendingCreations,
|
|
362
|
+
)
|
|
363
|
+
? ((currentMeta!.meta as Record<string, unknown>)
|
|
364
|
+
.pendingCreations as PendingCreation[])
|
|
365
|
+
: [];
|
|
366
|
+
const proposal = creations.find((c) => c.id === proposalId);
|
|
367
|
+
if (!proposal) {
|
|
368
|
+
throw new TRPCError({ code: "NOT_FOUND", message: "Proposal not found" });
|
|
369
|
+
}
|
|
370
|
+
if (proposal.status !== "pending") {
|
|
371
|
+
return {
|
|
372
|
+
status: proposal.status,
|
|
373
|
+
createdId: proposal.createdId ?? null,
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
if (action === "dismiss") {
|
|
378
|
+
const meta = await casProposalStatus(messageId, proposalId, "pending", {
|
|
379
|
+
status: "dismissed",
|
|
380
|
+
});
|
|
381
|
+
if (meta) {
|
|
382
|
+
await broadcastMessageMeta(messageId, message.conversationId);
|
|
383
|
+
}
|
|
384
|
+
return { status: "dismissed" as const, createdId: null };
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// Approve: claim the proposal first so concurrent approvals create at most
|
|
388
|
+
// one entity, then create and record the created id (roll back on failure).
|
|
389
|
+
const claimed = await casProposalStatus(messageId, proposalId, "pending", {
|
|
390
|
+
status: "approved",
|
|
391
|
+
});
|
|
392
|
+
if (!claimed) {
|
|
393
|
+
const msg = await prisma.message.findUnique({
|
|
394
|
+
where: { id: messageId },
|
|
395
|
+
select: { meta: true },
|
|
396
|
+
});
|
|
397
|
+
const latest = (
|
|
398
|
+
((msg?.meta as Record<string, unknown> | null)?.pendingCreations ??
|
|
399
|
+
[]) as PendingCreation[]
|
|
400
|
+
).find((c) => c.id === proposalId);
|
|
401
|
+
return {
|
|
402
|
+
status: latest?.status ?? "pending",
|
|
403
|
+
createdId: latest?.createdId ?? null,
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
try {
|
|
408
|
+
const createdId = await createProposedEntity(userId, labChat.classId, proposal);
|
|
409
|
+
await casProposalStatus(messageId, proposalId, "approved", { createdId });
|
|
410
|
+
await broadcastMessageMeta(messageId, message.conversationId);
|
|
411
|
+
return { status: "approved" as const, createdId };
|
|
412
|
+
} catch (error) {
|
|
413
|
+
logger.error("Failed to create approved AI proposal", {
|
|
414
|
+
error,
|
|
415
|
+
messageId,
|
|
416
|
+
proposalId,
|
|
417
|
+
kind: proposal.kind,
|
|
418
|
+
});
|
|
419
|
+
await casProposalStatus(messageId, proposalId, "approved", {
|
|
420
|
+
status: "pending",
|
|
421
|
+
}).catch(() => null);
|
|
422
|
+
await broadcastMessageMeta(messageId, message.conversationId);
|
|
423
|
+
throw new TRPCError({
|
|
424
|
+
code: "INTERNAL_SERVER_ERROR",
|
|
425
|
+
message: "Failed to create the approved item",
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
}
|
package/src/services/labChat.ts
CHANGED
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
findLabChatByMember,
|
|
12
12
|
findLabChatByTeacher,
|
|
13
13
|
findLabChatById,
|
|
14
|
+
findClassContextForStarterPrompts,
|
|
14
15
|
findClassMembership,
|
|
15
16
|
findLabChatsByClass,
|
|
16
17
|
findLabChatForPost,
|
|
@@ -203,6 +204,70 @@ export async function getLabChat(userId: string, labChatId: string) {
|
|
|
203
204
|
};
|
|
204
205
|
}
|
|
205
206
|
|
|
207
|
+
const GENERIC_STARTER_PROMPTS = [
|
|
208
|
+
"Create a quiz on this week's topic",
|
|
209
|
+
"Draft a worksheet with 10 practice questions",
|
|
210
|
+
"Plan a lesson with objectives and activities",
|
|
211
|
+
"Suggest an assignment with a mark scheme",
|
|
212
|
+
];
|
|
213
|
+
|
|
214
|
+
const MAX_STARTER_PROMPTS = 5;
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Suggest starter prompts for a class's lab chat, derived from recent
|
|
218
|
+
* class context (upcoming due work, recent assignments, units, subject).
|
|
219
|
+
* Pure heuristics — no LLM call — so it stays cheap and fast. Falls back
|
|
220
|
+
* to generic defaults when the class has no usable context.
|
|
221
|
+
*/
|
|
222
|
+
export async function getStarterPrompts(userId: string, classId: string) {
|
|
223
|
+
const classContext = await findClassContextForStarterPrompts(
|
|
224
|
+
classId,
|
|
225
|
+
userId
|
|
226
|
+
);
|
|
227
|
+
if (!classContext) {
|
|
228
|
+
throw new TRPCError({
|
|
229
|
+
code: "FORBIDDEN",
|
|
230
|
+
message: "Not a teacher in this class",
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const prompts: string[] = [];
|
|
235
|
+
const now = new Date();
|
|
236
|
+
|
|
237
|
+
const published = classContext.assignments.filter((a) => !a.inProgress);
|
|
238
|
+
const upcoming = published
|
|
239
|
+
.filter((a) => a.dueDate > now)
|
|
240
|
+
.sort((a, b) => a.dueDate.getTime() - b.dueDate.getTime())[0];
|
|
241
|
+
if (upcoming) {
|
|
242
|
+
prompts.push(
|
|
243
|
+
`Create a worksheet to help students prepare for "${upcoming.title}"`
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const recent = published.find((a) => a.title !== upcoming?.title);
|
|
248
|
+
if (recent) {
|
|
249
|
+
prompts.push(`Draft a quiz reviewing "${recent.title}"`);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const unit = classContext.sections[0];
|
|
253
|
+
if (unit) {
|
|
254
|
+
prompts.push(`Plan a lesson for the unit "${unit.name}"`);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
if (classContext.subject) {
|
|
258
|
+
prompts.push(
|
|
259
|
+
`Suggest a ${classContext.subject} assignment with a mark scheme`
|
|
260
|
+
);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
for (const generic of GENERIC_STARTER_PROMPTS) {
|
|
264
|
+
if (prompts.length >= 3) break;
|
|
265
|
+
if (!prompts.includes(generic)) prompts.push(generic);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
return { prompts: prompts.slice(0, MAX_STARTER_PROMPTS) };
|
|
269
|
+
}
|
|
270
|
+
|
|
206
271
|
export async function listLabChats(userId: string, classId: string) {
|
|
207
272
|
const classMembership = await findClassMembership(classId, userId);
|
|
208
273
|
if (!classMembership) {
|