scene-generator.ts 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  1. /**
  2. * Stage 2: Scene content and action generation.
  3. *
  4. * Generates full scenes (slide/quiz/interactive/pbl with actions)
  5. * from scene outlines.
  6. */
  7. import { nanoid } from 'nanoid';
  8. import katex from 'katex';
  9. import { MAX_VISION_IMAGES } from '@/lib/constants/generation';
  10. import type {
  11. SceneOutline,
  12. GeneratedSlideContent,
  13. GeneratedQuizContent,
  14. GeneratedInteractiveContent,
  15. GeneratedPBLContent,
  16. ScientificModel,
  17. PdfImage,
  18. ImageMapping,
  19. } from '@/lib/types/generation';
  20. import type { LanguageModel } from 'ai';
  21. import type { StageStore } from '@/lib/api/stage-api';
  22. import { createStageAPI } from '@/lib/api/stage-api';
  23. import { generatePBLContent } from '@/lib/pbl/generate-pbl';
  24. import { buildPrompt, PROMPT_IDS } from './prompts';
  25. import { postProcessInteractiveHtml } from './interactive-post-processor';
  26. import { parseActionsFromStructuredOutput } from './action-parser';
  27. import { parseJsonResponse } from './json-repair';
  28. import {
  29. buildCourseContext,
  30. formatAgentsForPrompt,
  31. formatTeacherPersonaForPrompt,
  32. formatImageDescription,
  33. formatImagePlaceholder,
  34. } from './prompt-formatters';
  35. import type { PPTElement, Slide, SlideBackground, SlideTheme } from '@/lib/types/slides';
  36. import type { QuizQuestion } from '@/lib/types/stage';
  37. import type { Action } from '@/lib/types/action';
  38. import type {
  39. AgentInfo,
  40. SceneGenerationContext,
  41. GeneratedSlideData,
  42. AICallFn,
  43. GenerationResult,
  44. GenerationCallbacks,
  45. } from './pipeline-types';
  46. import { createLogger } from '@/lib/logger';
  47. const log = createLogger('Generation');
  48. // ==================== Stage 2: Full Scenes (Two-Step) ====================
  49. /**
  50. * Stage 3: Generate full scenes (parallel version)
  51. *
  52. * Two steps:
  53. * - Step 3.1: Outline -> Page content (slide/quiz)
  54. * - Step 3.2: Content + script -> Action list
  55. *
  56. * All scenes generated in parallel using Promise.all
  57. */
  58. export async function generateFullScenes(
  59. sceneOutlines: SceneOutline[],
  60. store: StageStore,
  61. aiCall: AICallFn,
  62. callbacks?: GenerationCallbacks,
  63. ): Promise<GenerationResult<string[]>> {
  64. const api = createStageAPI(store);
  65. const totalScenes = sceneOutlines.length;
  66. let completedCount = 0;
  67. callbacks?.onProgress?.({
  68. currentStage: 3,
  69. overallProgress: 66,
  70. stageProgress: 0,
  71. statusMessage: `正在并行生成 ${totalScenes} 个场景...`,
  72. scenesGenerated: 0,
  73. totalScenes,
  74. });
  75. // Generate all scenes in parallel
  76. const results = await Promise.all(
  77. sceneOutlines.map(async (outline, index) => {
  78. try {
  79. const sceneId = await generateSingleScene(outline, api, aiCall);
  80. // Update progress (not atomic, but sufficient for UI display)
  81. completedCount++;
  82. callbacks?.onProgress?.({
  83. currentStage: 3,
  84. overallProgress: 66 + Math.floor((completedCount / totalScenes) * 34),
  85. stageProgress: Math.floor((completedCount / totalScenes) * 100),
  86. statusMessage: `已完成 ${completedCount}/${totalScenes} 个场景`,
  87. scenesGenerated: completedCount,
  88. totalScenes,
  89. });
  90. return { success: true, sceneId, index };
  91. } catch (error) {
  92. completedCount++;
  93. callbacks?.onError?.(`Failed to generate scene ${outline.title}: ${error}`);
  94. return { success: false, sceneId: null, index };
  95. }
  96. }),
  97. );
  98. // Collect successful sceneIds in original order
  99. const sceneIds = results
  100. .filter(
  101. (r): r is { success: true; sceneId: string; index: number } =>
  102. r.success && r.sceneId !== null,
  103. )
  104. .sort((a, b) => a.index - b.index)
  105. .map((r) => r.sceneId);
  106. return { success: true, data: sceneIds };
  107. }
  108. /**
  109. * Generate a single scene (two-step process)
  110. *
  111. * Step 3.1: Generate content
  112. * Step 3.2: Generate Actions
  113. */
  114. async function generateSingleScene(
  115. outline: SceneOutline,
  116. api: ReturnType<typeof createStageAPI>,
  117. aiCall: AICallFn,
  118. ): Promise<string | null> {
  119. // Step 3.1: Generate content
  120. log.info(`Step 3.1: Generating content for: ${outline.title}`);
  121. const content = await generateSceneContent(outline, aiCall);
  122. if (!content) {
  123. log.error(`Failed to generate content for: ${outline.title}`);
  124. return null;
  125. }
  126. // Step 3.2: Generate Actions
  127. log.info(`Step 3.2: Generating actions for: ${outline.title}`);
  128. const actions = await generateSceneActions(outline, content, aiCall);
  129. log.info(`Generated ${actions.length} actions for: ${outline.title}`);
  130. // Create complete Scene
  131. return createSceneWithActions(outline, content, actions, api);
  132. }
  133. /**
  134. * Step 3.1: Generate content based on outline
  135. */
  136. export async function generateSceneContent(
  137. outline: SceneOutline,
  138. aiCall: AICallFn,
  139. assignedImages?: PdfImage[],
  140. imageMapping?: ImageMapping,
  141. languageModel?: LanguageModel,
  142. visionEnabled?: boolean,
  143. generatedMediaMapping?: ImageMapping,
  144. agents?: AgentInfo[],
  145. ): Promise<
  146. | GeneratedSlideContent
  147. | GeneratedQuizContent
  148. | GeneratedInteractiveContent
  149. | GeneratedPBLContent
  150. | null
  151. > {
  152. // If outline is interactive but missing interactiveConfig, fall back to slide
  153. if (outline.type === 'interactive' && !outline.interactiveConfig) {
  154. log.warn(
  155. `Interactive outline "${outline.title}" missing interactiveConfig, falling back to slide`,
  156. );
  157. const fallbackOutline = { ...outline, type: 'slide' as const };
  158. return generateSlideContent(
  159. fallbackOutline,
  160. aiCall,
  161. assignedImages,
  162. imageMapping,
  163. visionEnabled,
  164. generatedMediaMapping,
  165. agents,
  166. );
  167. }
  168. switch (outline.type) {
  169. case 'slide':
  170. return generateSlideContent(
  171. outline,
  172. aiCall,
  173. assignedImages,
  174. imageMapping,
  175. visionEnabled,
  176. generatedMediaMapping,
  177. agents,
  178. );
  179. case 'quiz':
  180. return generateQuizContent(outline, aiCall);
  181. case 'interactive':
  182. return generateInteractiveContent(outline, aiCall, outline.language);
  183. case 'pbl':
  184. return generatePBLSceneContent(outline, languageModel);
  185. default:
  186. return null;
  187. }
  188. }
  189. /**
  190. * Check if a string looks like an image ID (e.g., "img_1", "img_2")
  191. * rather than a base64 data URL or actual URL
  192. *
  193. * This function distinguishes between:
  194. * - Image IDs: "img_1", "img_2", etc. → returns true
  195. * - Base64 data URLs: "data:image/..." → returns false
  196. * - HTTP URLs: "http://...", "https://..." → returns false
  197. * - Relative paths: "/images/..." → returns false
  198. */
  199. function isImageIdReference(value: string): boolean {
  200. if (!value) return false;
  201. // Exclude real URLs and paths
  202. if (value.startsWith('data:')) return false;
  203. if (value.startsWith('http://') || value.startsWith('https://')) return false;
  204. if (value.startsWith('/')) return false; // Relative paths
  205. // Match image ID format: img_1, img_2, etc.
  206. return /^img_\d+$/i.test(value);
  207. }
  208. /**
  209. * Check if a string looks like a generated image/video ID (e.g., "gen_img_1", "gen_img_xK8f2mQ")
  210. * These are placeholders for AI-generated media, not PDF-extracted images.
  211. */
  212. function isGeneratedImageId(value: string): boolean {
  213. if (!value) return false;
  214. return /^gen_(img|vid)_[\w-]+$/i.test(value);
  215. }
  216. /**
  217. * Resolve image ID references in src field to actual base64 URLs
  218. *
  219. * AI generates: { type: "image", src: "img_1", ... }
  220. * This function replaces: { type: "image", src: "data:image/png;base64,...", ... }
  221. *
  222. * Design rationale (Plan B):
  223. * - Simpler: AI only needs to know one field (src)
  224. * - Consistent: Generated JSON structure matches final PPTImageElement
  225. * - Intuitive: src is the image source, first as ID then as actual URL
  226. * - Less prompt complexity: No need to explain imageId vs src distinction
  227. */
  228. function resolveImageIds(
  229. elements: GeneratedSlideData['elements'],
  230. imageMapping?: ImageMapping,
  231. generatedMediaMapping?: ImageMapping,
  232. ): GeneratedSlideData['elements'] {
  233. return elements
  234. .map((el) => {
  235. if (el.type === 'image') {
  236. if (!('src' in el)) {
  237. log.warn(`Image element missing src, removing element`);
  238. return null; // Remove invalid image elements
  239. }
  240. const src = el.src as string;
  241. // If src is an image ID reference, replace with actual URL
  242. if (isImageIdReference(src)) {
  243. if (!imageMapping || !imageMapping[src]) {
  244. log.warn(`No mapping for image ID: ${src}, removing element`);
  245. return null; // Remove invalid image elements
  246. }
  247. log.debug(`Resolved image ID "${src}" to base64 URL`);
  248. return { ...el, src: imageMapping[src] };
  249. }
  250. // Generated image reference — keep as placeholder for async backfill
  251. if (isGeneratedImageId(src)) {
  252. if (generatedMediaMapping && generatedMediaMapping[src]) {
  253. log.debug(`Resolved generated image ID "${src}" to URL`);
  254. return { ...el, src: generatedMediaMapping[src] };
  255. }
  256. // Keep element with placeholder ID — frontend renders skeleton
  257. log.debug(`Keeping generated image placeholder: ${src}`);
  258. return el;
  259. }
  260. }
  261. if (el.type === 'video') {
  262. if (!('src' in el)) {
  263. log.warn(`Video element missing src, removing element`);
  264. return null;
  265. }
  266. const src = el.src as string;
  267. if (isGeneratedImageId(src)) {
  268. if (generatedMediaMapping && generatedMediaMapping[src]) {
  269. log.debug(`Resolved generated video ID "${src}" to URL`);
  270. return { ...el, src: generatedMediaMapping[src] };
  271. }
  272. // Keep element with placeholder ID — frontend renders skeleton
  273. log.debug(`Keeping generated video placeholder: ${src}`);
  274. return el;
  275. }
  276. }
  277. return el;
  278. })
  279. .filter((el): el is NonNullable<typeof el> => el !== null);
  280. }
  281. /**
  282. * Fix elements with missing required fields
  283. * Adds default values for fields that AI might not have generated correctly
  284. */
  285. function fixElementDefaults(
  286. elements: GeneratedSlideData['elements'],
  287. assignedImages?: PdfImage[],
  288. ): GeneratedSlideData['elements'] {
  289. return elements.map((el) => {
  290. // Fix line elements
  291. if (el.type === 'line') {
  292. const lineEl = el as Record<string, unknown>;
  293. // Ensure points field exists with default values
  294. if (!lineEl.points || !Array.isArray(lineEl.points) || lineEl.points.length !== 2) {
  295. log.warn(`Line element missing points, adding defaults`);
  296. lineEl.points = ['', ''] as [string, string]; // Default: no markers on either end
  297. }
  298. // Ensure start/end exist
  299. if (!lineEl.start || !Array.isArray(lineEl.start)) {
  300. lineEl.start = [el.left ?? 0, el.top ?? 0];
  301. }
  302. if (!lineEl.end || !Array.isArray(lineEl.end)) {
  303. lineEl.end = [(el.left ?? 0) + (el.width ?? 100), (el.top ?? 0) + (el.height ?? 0)];
  304. }
  305. // Ensure style exists
  306. if (!lineEl.style) {
  307. lineEl.style = 'solid';
  308. }
  309. // Ensure color exists
  310. if (!lineEl.color) {
  311. lineEl.color = '#333333';
  312. }
  313. return lineEl as typeof el;
  314. }
  315. // Fix text elements
  316. if (el.type === 'text') {
  317. const textEl = el as Record<string, unknown>;
  318. if (!textEl.defaultFontName) {
  319. textEl.defaultFontName = 'Microsoft YaHei';
  320. }
  321. if (!textEl.defaultColor) {
  322. textEl.defaultColor = '#333333';
  323. }
  324. if (!textEl.content) {
  325. textEl.content = '';
  326. }
  327. return textEl as typeof el;
  328. }
  329. // Fix image elements
  330. if (el.type === 'image') {
  331. const imageEl = el as Record<string, unknown>;
  332. if (imageEl.fixedRatio === undefined) {
  333. imageEl.fixedRatio = true;
  334. }
  335. // Correct dimensions using known aspect ratio (src is still img_id at this point)
  336. if (assignedImages && typeof imageEl.src === 'string') {
  337. const imgMeta = assignedImages.find((img) => img.id === imageEl.src);
  338. if (imgMeta?.width && imgMeta?.height) {
  339. const knownRatio = imgMeta.width / imgMeta.height;
  340. const curW = (el.width || 400) as number;
  341. const curH = (el.height || 300) as number;
  342. if (Math.abs(curW / curH - knownRatio) / knownRatio > 0.1) {
  343. // Keep width, correct height
  344. const newH = Math.round(curW / knownRatio);
  345. if (newH > 462) {
  346. // canvas 562.5 - margins 50×2
  347. const newW = Math.round(462 * knownRatio);
  348. imageEl.width = newW;
  349. imageEl.height = 462;
  350. } else {
  351. imageEl.height = newH;
  352. }
  353. }
  354. }
  355. }
  356. return imageEl as typeof el;
  357. }
  358. // Fix shape elements
  359. if (el.type === 'shape') {
  360. const shapeEl = el as Record<string, unknown>;
  361. if (!shapeEl.viewBox) {
  362. shapeEl.viewBox = `0 0 ${el.width ?? 100} ${el.height ?? 100}`;
  363. }
  364. if (!shapeEl.path) {
  365. // Default to rectangle
  366. const w = el.width ?? 100;
  367. const h = el.height ?? 100;
  368. shapeEl.path = `M0 0 L${w} 0 L${w} ${h} L0 ${h} Z`;
  369. }
  370. if (!shapeEl.fill) {
  371. shapeEl.fill = '#5b9bd5';
  372. }
  373. if (shapeEl.fixedRatio === undefined) {
  374. shapeEl.fixedRatio = false;
  375. }
  376. return shapeEl as typeof el;
  377. }
  378. return el;
  379. });
  380. }
  381. /**
  382. * Process LaTeX elements: render latex string to HTML using KaTeX.
  383. * Fills in html and fixedRatio fields.
  384. * Elements that fail conversion are removed.
  385. */
  386. function processLatexElements(
  387. elements: GeneratedSlideData['elements'],
  388. ): GeneratedSlideData['elements'] {
  389. return elements
  390. .map((el) => {
  391. if (el.type !== 'latex') return el;
  392. const latexStr = el.latex as string | undefined;
  393. if (!latexStr) {
  394. log.warn('Latex element missing latex string, removing');
  395. return null;
  396. }
  397. try {
  398. const html = katex.renderToString(latexStr, {
  399. throwOnError: false,
  400. displayMode: true,
  401. output: 'html',
  402. });
  403. return {
  404. ...el,
  405. html,
  406. fixedRatio: true,
  407. };
  408. } catch (err) {
  409. log.warn(`Failed to render latex "${latexStr}":`, err);
  410. return null;
  411. }
  412. })
  413. .filter((el): el is NonNullable<typeof el> => el !== null);
  414. }
  415. /**
  416. * Generate slide content
  417. */
  418. async function generateSlideContent(
  419. outline: SceneOutline,
  420. aiCall: AICallFn,
  421. assignedImages?: PdfImage[],
  422. imageMapping?: ImageMapping,
  423. visionEnabled?: boolean,
  424. generatedMediaMapping?: ImageMapping,
  425. agents?: AgentInfo[],
  426. ): Promise<GeneratedSlideContent | null> {
  427. const lang = outline.language || 'zh-CN';
  428. // Build assigned images description for the prompt
  429. let assignedImagesText = '无可用图片,禁止插入任何 image 元素';
  430. let visionImages: Array<{ id: string; src: string }> | undefined;
  431. if (assignedImages && assignedImages.length > 0) {
  432. if (visionEnabled && imageMapping) {
  433. // Vision mode: split into vision images and text-only
  434. const withSrc = assignedImages.filter((img) => imageMapping[img.id]);
  435. const visionSlice = withSrc.slice(0, MAX_VISION_IMAGES);
  436. const textOnlySlice = withSrc.slice(MAX_VISION_IMAGES);
  437. const noSrcImages = assignedImages.filter((img) => !imageMapping[img.id]);
  438. const visionDescriptions = visionSlice.map((img) => formatImagePlaceholder(img, lang));
  439. const textDescriptions = [...textOnlySlice, ...noSrcImages].map((img) =>
  440. formatImageDescription(img, lang),
  441. );
  442. assignedImagesText = [...visionDescriptions, ...textDescriptions].join('\n');
  443. visionImages = visionSlice.map((img) => ({
  444. id: img.id,
  445. src: imageMapping[img.id],
  446. width: img.width,
  447. height: img.height,
  448. }));
  449. } else {
  450. assignedImagesText = assignedImages
  451. .map((img) => formatImageDescription(img, lang))
  452. .join('\n');
  453. }
  454. }
  455. // Add generated media placeholders info (images + videos)
  456. if (outline.mediaGenerations && outline.mediaGenerations.length > 0) {
  457. const genImgDescs = outline.mediaGenerations
  458. .filter((mg) => mg.type === 'image')
  459. .map((mg) => `- ${mg.elementId}: "${mg.prompt}" (aspect ratio: ${mg.aspectRatio || '16:9'})`)
  460. .join('\n');
  461. const genVidDescs = outline.mediaGenerations
  462. .filter((mg) => mg.type === 'video')
  463. .map((mg) => `- ${mg.elementId}: "${mg.prompt}" (aspect ratio: ${mg.aspectRatio || '16:9'})`)
  464. .join('\n');
  465. const mediaParts: string[] = [];
  466. if (genImgDescs) {
  467. mediaParts.push(`AI-Generated Images (use these IDs as image element src):\n${genImgDescs}`);
  468. }
  469. if (genVidDescs) {
  470. mediaParts.push(`AI-Generated Videos (use these IDs as video element src):\n${genVidDescs}`);
  471. }
  472. if (mediaParts.length > 0) {
  473. const mediaText = mediaParts.join('\n\n');
  474. if (assignedImagesText.includes('禁止插入') || assignedImagesText.includes('No images')) {
  475. assignedImagesText = mediaText;
  476. } else {
  477. assignedImagesText += `\n\n${mediaText}`;
  478. }
  479. }
  480. }
  481. // Canvas dimensions (matching viewportSize and viewportRatio)
  482. const canvasWidth = 1000;
  483. const canvasHeight = 562.5;
  484. const teacherContext = formatTeacherPersonaForPrompt(agents);
  485. const prompts = buildPrompt(PROMPT_IDS.SLIDE_CONTENT, {
  486. title: outline.title,
  487. description: outline.description,
  488. keyPoints: (outline.keyPoints || []).map((p, i) => `${i + 1}. ${p}`).join('\n'),
  489. elements: '(根据要点自动生成)',
  490. assignedImages: assignedImagesText,
  491. canvas_width: canvasWidth,
  492. canvas_height: canvasHeight,
  493. teacherContext,
  494. });
  495. if (!prompts) {
  496. return null;
  497. }
  498. log.debug(`Generating slide content for: ${outline.title}`);
  499. if (assignedImages && assignedImages.length > 0) {
  500. log.debug(`Assigned images: ${assignedImages.map((img) => img.id).join(', ')}`);
  501. }
  502. if (visionImages && visionImages.length > 0) {
  503. log.debug(`Vision images: ${visionImages.map((img) => img.id).join(', ')}`);
  504. }
  505. const response = await aiCall(prompts.system, prompts.user, visionImages);
  506. const generatedData = parseJsonResponse<GeneratedSlideData>(response);
  507. if (!generatedData || !generatedData.elements || !Array.isArray(generatedData.elements)) {
  508. log.error(`Failed to parse AI response for: ${outline.title}`);
  509. return null;
  510. }
  511. log.debug(`Got ${generatedData.elements.length} elements for: ${outline.title}`);
  512. // Debug: Log image elements before resolution
  513. const imageElements = generatedData.elements.filter((el) => el.type === 'image');
  514. if (imageElements.length > 0) {
  515. log.debug(
  516. `Image elements before resolution:`,
  517. imageElements.map((el) => ({
  518. type: el.type,
  519. src:
  520. (el as Record<string, unknown>).src &&
  521. String((el as Record<string, unknown>).src).substring(0, 50),
  522. })),
  523. );
  524. log.debug(`imageMapping keys:`, imageMapping ? Object.keys(imageMapping).length : '0 keys');
  525. }
  526. // Fix elements with missing required fields + aspect ratio correction (while src is still img_id)
  527. const fixedElements = fixElementDefaults(generatedData.elements, assignedImages);
  528. log.debug(`After element fixing: ${fixedElements.length} elements`);
  529. // Process LaTeX elements: render latex string → HTML via KaTeX
  530. const latexProcessedElements = processLatexElements(fixedElements);
  531. log.debug(`After LaTeX processing: ${latexProcessedElements.length} elements`);
  532. // Resolve image_id references to actual URLs
  533. const resolvedElements = resolveImageIds(
  534. latexProcessedElements,
  535. imageMapping,
  536. generatedMediaMapping,
  537. );
  538. log.debug(`After image resolution: ${resolvedElements.length} elements`);
  539. // Process elements, assign unique IDs
  540. const processedElements: PPTElement[] = resolvedElements.map((el) => ({
  541. ...el,
  542. id: `${el.type}_${nanoid(8)}`,
  543. rotate: 0,
  544. })) as PPTElement[];
  545. // Process background
  546. let background: SlideBackground | undefined;
  547. if (generatedData.background) {
  548. if (generatedData.background.type === 'solid' && generatedData.background.color) {
  549. background = { type: 'solid', color: generatedData.background.color };
  550. } else if (generatedData.background.type === 'gradient' && generatedData.background.gradient) {
  551. background = {
  552. type: 'gradient',
  553. gradient: generatedData.background.gradient,
  554. };
  555. }
  556. }
  557. return {
  558. elements: processedElements,
  559. background,
  560. remark: generatedData.remark || outline.description,
  561. };
  562. }
  563. /**
  564. * Generate quiz content
  565. */
  566. async function generateQuizContent(
  567. outline: SceneOutline,
  568. aiCall: AICallFn,
  569. ): Promise<GeneratedQuizContent | null> {
  570. const quizConfig = outline.quizConfig || {
  571. questionCount: 3,
  572. difficulty: 'medium',
  573. questionTypes: ['single'],
  574. };
  575. const prompts = buildPrompt(PROMPT_IDS.QUIZ_CONTENT, {
  576. title: outline.title,
  577. description: outline.description,
  578. keyPoints: (outline.keyPoints || []).map((p, i) => `${i + 1}. ${p}`).join('\n'),
  579. questionCount: quizConfig.questionCount,
  580. difficulty: quizConfig.difficulty,
  581. questionTypes: quizConfig.questionTypes.join(', '),
  582. });
  583. if (!prompts) {
  584. return null;
  585. }
  586. log.debug(`Generating quiz content for: ${outline.title}`);
  587. const response = await aiCall(prompts.system, prompts.user);
  588. const generatedQuestions = parseJsonResponse<QuizQuestion[]>(response);
  589. if (!generatedQuestions || !Array.isArray(generatedQuestions)) {
  590. log.error(`Failed to parse AI response for: ${outline.title}`);
  591. return null;
  592. }
  593. log.debug(`Got ${generatedQuestions.length} questions for: ${outline.title}`);
  594. // Ensure each question has an ID and normalize options format
  595. const questions: QuizQuestion[] = generatedQuestions.map((q) => {
  596. const isText = q.type === 'short_answer';
  597. return {
  598. ...q,
  599. id: q.id || `q_${nanoid(8)}`,
  600. options: isText ? undefined : normalizeQuizOptions(q.options),
  601. answer: isText ? undefined : normalizeQuizAnswer(q as unknown as Record<string, unknown>),
  602. hasAnswer: isText ? false : true,
  603. };
  604. });
  605. return { questions };
  606. }
  607. /**
  608. * Normalize quiz options from AI response.
  609. * AI may generate plain strings ["OptionA", "OptionB"] or QuizOption objects.
  610. * This normalizes to QuizOption[] format: { value: "A", label: "OptionA" }
  611. */
  612. function normalizeQuizOptions(
  613. options: unknown[] | undefined,
  614. ): { value: string; label: string }[] | undefined {
  615. if (!options || !Array.isArray(options)) return undefined;
  616. return options.map((opt, index) => {
  617. const letter = String.fromCharCode(65 + index); // A, B, C, D...
  618. if (typeof opt === 'string') {
  619. return { value: letter, label: opt };
  620. }
  621. if (typeof opt === 'object' && opt !== null) {
  622. const obj = opt as Record<string, unknown>;
  623. return {
  624. value: typeof obj.value === 'string' ? obj.value : letter,
  625. label: typeof obj.label === 'string' ? obj.label : String(obj.value || obj.text || letter),
  626. };
  627. }
  628. return { value: letter, label: String(opt) };
  629. });
  630. }
  631. /**
  632. * Normalize quiz answer from AI response.
  633. * AI may generate correctAnswer as string or string[], under various field names.
  634. * This normalizes to string[] format matching option values.
  635. */
  636. function normalizeQuizAnswer(question: Record<string, unknown>): string[] | undefined {
  637. // AI might use "correctAnswer", "answer", or "correct_answer"
  638. const raw =
  639. question.answer ??
  640. question.correctAnswer ??
  641. (question as Record<string, unknown>).correct_answer;
  642. if (!raw) return undefined;
  643. if (Array.isArray(raw)) {
  644. return raw.map(String);
  645. }
  646. return [String(raw)];
  647. }
  648. /**
  649. * Generate interactive page content
  650. * Two AI calls + post-processing:
  651. * 1. Scientific modeling -> ScientificModel (with fallback)
  652. * 2. HTML generation with constraints -> post-processed HTML
  653. */
  654. async function generateInteractiveContent(
  655. outline: SceneOutline,
  656. aiCall: AICallFn,
  657. language: 'zh-CN' | 'en-US' = 'zh-CN',
  658. ): Promise<GeneratedInteractiveContent | null> {
  659. const config = outline.interactiveConfig!;
  660. // Step 1: Scientific modeling (with fallback on failure)
  661. let scientificModel: ScientificModel | undefined;
  662. try {
  663. const modelPrompts = buildPrompt(PROMPT_IDS.INTERACTIVE_SCIENTIFIC_MODEL, {
  664. subject: config.subject || '',
  665. conceptName: config.conceptName,
  666. conceptOverview: config.conceptOverview,
  667. keyPoints: (outline.keyPoints || []).map((p, i) => `${i + 1}. ${p}`).join('\n'),
  668. designIdea: config.designIdea,
  669. });
  670. if (modelPrompts) {
  671. log.info(`Step 1: Scientific modeling for: ${outline.title}`);
  672. const modelResponse = await aiCall(modelPrompts.system, modelPrompts.user);
  673. const parsed = parseJsonResponse<ScientificModel>(modelResponse);
  674. if (parsed && parsed.core_formulas) {
  675. scientificModel = parsed;
  676. log.info(
  677. `Scientific model: ${parsed.core_formulas.length} formulas, ${parsed.constraints?.length || 0} constraints`,
  678. );
  679. }
  680. }
  681. } catch (error) {
  682. log.warn(`Scientific modeling failed, continuing without: ${error}`);
  683. }
  684. // Format scientific constraints for HTML generation prompt
  685. let scientificConstraints = 'No specific scientific constraints available.';
  686. if (scientificModel) {
  687. const lines: string[] = [];
  688. if (scientificModel.core_formulas?.length) {
  689. lines.push(`Core Formulas: ${scientificModel.core_formulas.join('; ')}`);
  690. }
  691. if (scientificModel.mechanism?.length) {
  692. lines.push(`Mechanisms: ${scientificModel.mechanism.join('; ')}`);
  693. }
  694. if (scientificModel.constraints?.length) {
  695. lines.push(`Must Obey: ${scientificModel.constraints.join('; ')}`);
  696. }
  697. if (scientificModel.forbidden_errors?.length) {
  698. lines.push(`Forbidden Errors: ${scientificModel.forbidden_errors.join('; ')}`);
  699. }
  700. scientificConstraints = lines.join('\n');
  701. }
  702. // Step 2: HTML generation
  703. const htmlPrompts = buildPrompt(PROMPT_IDS.INTERACTIVE_HTML, {
  704. conceptName: config.conceptName,
  705. subject: config.subject || '',
  706. conceptOverview: config.conceptOverview,
  707. keyPoints: (outline.keyPoints || []).map((p, i) => `${i + 1}. ${p}`).join('\n'),
  708. scientificConstraints,
  709. designIdea: config.designIdea,
  710. language,
  711. });
  712. if (!htmlPrompts) {
  713. log.error(`Failed to build HTML prompt for: ${outline.title}`);
  714. return null;
  715. }
  716. log.info(`Step 2: Generating HTML for: ${outline.title}`);
  717. const htmlResponse = await aiCall(htmlPrompts.system, htmlPrompts.user);
  718. // Extract HTML from response
  719. const rawHtml = extractHtml(htmlResponse);
  720. if (!rawHtml) {
  721. log.error(`Failed to extract HTML from response for: ${outline.title}`);
  722. return null;
  723. }
  724. // Step 3: Post-process HTML (LaTeX delimiter conversion + KaTeX injection)
  725. const processedHtml = postProcessInteractiveHtml(rawHtml);
  726. log.info(`Post-processed HTML (${processedHtml.length} chars) for: ${outline.title}`);
  727. return {
  728. html: processedHtml,
  729. scientificModel,
  730. };
  731. }
  732. /**
  733. * Generate PBL project content
  734. * Uses the agentic loop from lib/pbl/generate-pbl.ts
  735. */
  736. async function generatePBLSceneContent(
  737. outline: SceneOutline,
  738. languageModel?: LanguageModel,
  739. ): Promise<GeneratedPBLContent | null> {
  740. if (!languageModel) {
  741. log.error('LanguageModel required for PBL generation');
  742. return null;
  743. }
  744. const pblConfig = outline.pblConfig;
  745. if (!pblConfig) {
  746. log.error(`PBL outline "${outline.title}" missing pblConfig`);
  747. return null;
  748. }
  749. log.info(`Generating PBL content for: ${outline.title}`);
  750. try {
  751. const projectConfig = await generatePBLContent(
  752. {
  753. projectTopic: pblConfig.projectTopic,
  754. projectDescription: pblConfig.projectDescription,
  755. targetSkills: pblConfig.targetSkills,
  756. issueCount: pblConfig.issueCount,
  757. language: pblConfig.language,
  758. },
  759. languageModel,
  760. {
  761. onProgress: (msg) => log.info(`${msg}`),
  762. },
  763. );
  764. log.info(
  765. `PBL generated: ${projectConfig.agents.length} agents, ${projectConfig.issueboard.issues.length} issues`,
  766. );
  767. return { projectConfig };
  768. } catch (error) {
  769. log.error(`Failed:`, error);
  770. return null;
  771. }
  772. }
  773. /**
  774. * Extract HTML document from AI response.
  775. * Tries to find <!DOCTYPE html>...</html> first, then falls back to code block extraction.
  776. */
  777. function extractHtml(response: string): string | null {
  778. // Strategy 1: Find complete HTML document
  779. const doctypeStart = response.indexOf('<!DOCTYPE html>');
  780. const htmlTagStart = response.indexOf('<html');
  781. const start = doctypeStart !== -1 ? doctypeStart : htmlTagStart;
  782. if (start !== -1) {
  783. const htmlEnd = response.lastIndexOf('</html>');
  784. if (htmlEnd !== -1) {
  785. return response.substring(start, htmlEnd + 7);
  786. }
  787. }
  788. // Strategy 2: Extract from code block
  789. const codeBlockMatch = response.match(/```(?:html)?\s*([\s\S]*?)```/);
  790. if (codeBlockMatch) {
  791. const content = codeBlockMatch[1].trim();
  792. if (content.includes('<html') || content.includes('<!DOCTYPE')) {
  793. return content;
  794. }
  795. }
  796. // Strategy 3: If response itself looks like HTML
  797. const trimmed = response.trim();
  798. if (trimmed.startsWith('<!DOCTYPE') || trimmed.startsWith('<html')) {
  799. return trimmed;
  800. }
  801. log.error('Could not extract HTML from response');
  802. log.error('Response preview:', response.substring(0, 200));
  803. return null;
  804. }
  805. /**
  806. * Step 3.2: Generate Actions based on content and script
  807. */
  808. export async function generateSceneActions(
  809. outline: SceneOutline,
  810. content:
  811. | GeneratedSlideContent
  812. | GeneratedQuizContent
  813. | GeneratedInteractiveContent
  814. | GeneratedPBLContent,
  815. aiCall: AICallFn,
  816. ctx?: SceneGenerationContext,
  817. agents?: AgentInfo[],
  818. userProfile?: string,
  819. ): Promise<Action[]> {
  820. const agentsText = formatAgentsForPrompt(agents);
  821. if (outline.type === 'slide' && 'elements' in content) {
  822. // Format element list for AI to select from
  823. const elementsText = formatElementsForPrompt(content.elements);
  824. const prompts = buildPrompt(PROMPT_IDS.SLIDE_ACTIONS, {
  825. title: outline.title,
  826. keyPoints: (outline.keyPoints || []).map((p, i) => `${i + 1}. ${p}`).join('\n'),
  827. description: outline.description,
  828. elements: elementsText,
  829. courseContext: buildCourseContext(ctx),
  830. agents: agentsText,
  831. userProfile: userProfile || '',
  832. });
  833. if (!prompts) {
  834. return generateDefaultSlideActions(outline, content.elements);
  835. }
  836. const response = await aiCall(prompts.system, prompts.user);
  837. const actions = parseActionsFromStructuredOutput(response, outline.type);
  838. if (actions.length > 0) {
  839. // Validate and fill in Action IDs
  840. return processActions(actions, content.elements, agents);
  841. }
  842. return generateDefaultSlideActions(outline, content.elements);
  843. }
  844. if (outline.type === 'quiz' && 'questions' in content) {
  845. // Format question list for AI reference
  846. const questionsText = formatQuestionsForPrompt(content.questions);
  847. const prompts = buildPrompt(PROMPT_IDS.QUIZ_ACTIONS, {
  848. title: outline.title,
  849. keyPoints: (outline.keyPoints || []).map((p, i) => `${i + 1}. ${p}`).join('\n'),
  850. description: outline.description,
  851. questions: questionsText,
  852. courseContext: buildCourseContext(ctx),
  853. agents: agentsText,
  854. });
  855. if (!prompts) {
  856. return generateDefaultQuizActions(outline);
  857. }
  858. const response = await aiCall(prompts.system, prompts.user);
  859. const actions = parseActionsFromStructuredOutput(response, outline.type);
  860. if (actions.length > 0) {
  861. return processActions(actions, [], agents);
  862. }
  863. return generateDefaultQuizActions(outline);
  864. }
  865. if (outline.type === 'interactive' && 'html' in content) {
  866. const config = outline.interactiveConfig;
  867. const agentsText = formatAgentsForPrompt(agents);
  868. const prompts = buildPrompt(PROMPT_IDS.INTERACTIVE_ACTIONS, {
  869. title: outline.title,
  870. keyPoints: (outline.keyPoints || []).map((p, i) => `${i + 1}. ${p}`).join('\n'),
  871. description: outline.description,
  872. conceptName: config?.conceptName || outline.title,
  873. designIdea: config?.designIdea || '',
  874. courseContext: buildCourseContext(ctx),
  875. agents: agentsText,
  876. });
  877. if (!prompts) {
  878. return generateDefaultInteractiveActions(outline);
  879. }
  880. const response = await aiCall(prompts.system, prompts.user);
  881. const actions = parseActionsFromStructuredOutput(response, outline.type);
  882. if (actions.length > 0) {
  883. return processActions(actions, [], agents);
  884. }
  885. return generateDefaultInteractiveActions(outline);
  886. }
  887. if (outline.type === 'pbl' && 'projectConfig' in content) {
  888. const pblConfig = outline.pblConfig;
  889. const agentsText = formatAgentsForPrompt(agents);
  890. const prompts = buildPrompt(PROMPT_IDS.PBL_ACTIONS, {
  891. title: outline.title,
  892. keyPoints: (outline.keyPoints || []).map((p, i) => `${i + 1}. ${p}`).join('\n'),
  893. description: outline.description,
  894. projectTopic: pblConfig?.projectTopic || outline.title,
  895. projectDescription: pblConfig?.projectDescription || outline.description,
  896. courseContext: buildCourseContext(ctx),
  897. agents: agentsText,
  898. });
  899. if (!prompts) {
  900. return generateDefaultPBLActions(outline);
  901. }
  902. const response = await aiCall(prompts.system, prompts.user);
  903. const actions = parseActionsFromStructuredOutput(response, outline.type);
  904. if (actions.length > 0) {
  905. return processActions(actions, [], agents);
  906. }
  907. return generateDefaultPBLActions(outline);
  908. }
  909. return [];
  910. }
  911. /**
  912. * Generate default PBL Actions (fallback)
  913. */
  914. function generateDefaultPBLActions(_outline: SceneOutline): Action[] {
  915. return [
  916. {
  917. id: `action_${nanoid(8)}`,
  918. type: 'speech',
  919. title: 'PBL 项目介绍',
  920. text: '现在让我们开始一个项目式学习活动。请选择你的角色,查看任务看板,开始协作完成项目。',
  921. },
  922. ];
  923. }
  924. /**
  925. * Format element list for AI to select elementId
  926. */
  927. function formatElementsForPrompt(elements: PPTElement[]): string {
  928. return elements
  929. .map((el) => {
  930. let summary = '';
  931. if (el.type === 'text' && 'content' in el) {
  932. // Extract text content summary (strip HTML tags)
  933. const textContent = ((el.content as string) || '').replace(/<[^>]*>/g, '').substring(0, 50);
  934. summary = `Content summary: "${textContent}${textContent.length >= 50 ? '...' : ''}"`;
  935. } else if (el.type === 'chart' && 'chartType' in el) {
  936. summary = `Chart type: ${el.chartType}`;
  937. } else if (el.type === 'image') {
  938. summary = 'Image element';
  939. } else if (el.type === 'shape' && 'shapeName' in el) {
  940. summary = `Shape: ${el.shapeName || 'unknown'}`;
  941. } else if (el.type === 'latex' && 'latex' in el) {
  942. summary = `Formula: ${((el.latex as string) || '').substring(0, 30)}`;
  943. } else {
  944. summary = `${el.type} element`;
  945. }
  946. return `- id: "${el.id}", type: "${el.type}", ${summary}`;
  947. })
  948. .join('\n');
  949. }
  950. /**
  951. * Format question list for AI reference
  952. */
  953. function formatQuestionsForPrompt(questions: QuizQuestion[]): string {
  954. return questions
  955. .map((q, i) => {
  956. const optionsText = q.options
  957. ? `Options: ${q.options.map((o) => `${o.value}. ${o.label}`).join(', ')}`
  958. : '';
  959. return `Q${i + 1} (${q.type}): ${q.question}\n${optionsText}`;
  960. })
  961. .join('\n\n');
  962. }
  963. /**
  964. * Process and validate Actions
  965. */
  966. function processActions(actions: Action[], elements: PPTElement[], agents?: AgentInfo[]): Action[] {
  967. const elementIds = new Set(elements.map((el) => el.id));
  968. const agentIds = new Set(agents?.map((a) => a.id) || []);
  969. const studentAgents = agents?.filter((a) => a.role === 'student') || [];
  970. const nonTeacherAgents = agents?.filter((a) => a.role !== 'teacher') || [];
  971. return actions.map((action) => {
  972. // Ensure each action has an ID
  973. const processedAction: Action = {
  974. ...action,
  975. id: action.id || `action_${nanoid(8)}`,
  976. };
  977. // Validate spotlight elementId
  978. if (processedAction.type === 'spotlight') {
  979. const spotlightAction = processedAction;
  980. if (!spotlightAction.elementId || !elementIds.has(spotlightAction.elementId)) {
  981. // If elementId is invalid, try selecting the first element
  982. if (elements.length > 0) {
  983. spotlightAction.elementId = elements[0].id;
  984. log.warn(
  985. `Invalid elementId, falling back to first element: ${spotlightAction.elementId}`,
  986. );
  987. }
  988. }
  989. }
  990. // Validate/fill discussion agentId
  991. if (processedAction.type === 'discussion' && agents && agents.length > 0) {
  992. if (processedAction.agentId && agentIds.has(processedAction.agentId)) {
  993. // agentId valid — keep it
  994. } else {
  995. // agentId missing or invalid — pick a random student, or non-teacher, or skip
  996. const pool = studentAgents.length > 0 ? studentAgents : nonTeacherAgents;
  997. if (pool.length > 0) {
  998. const picked = pool[Math.floor(Math.random() * pool.length)];
  999. log.warn(
  1000. `Discussion agentId "${processedAction.agentId || '(none)'}" invalid, assigned: ${picked.id} (${picked.name})`,
  1001. );
  1002. processedAction.agentId = picked.id;
  1003. }
  1004. }
  1005. }
  1006. return processedAction;
  1007. });
  1008. }
  1009. /**
  1010. * Generate default slide Actions (fallback)
  1011. */
  1012. function generateDefaultSlideActions(outline: SceneOutline, elements: PPTElement[]): Action[] {
  1013. const actions: Action[] = [];
  1014. // Add spotlight for text elements
  1015. const textElements = elements.filter((el) => el.type === 'text');
  1016. if (textElements.length > 0) {
  1017. actions.push({
  1018. id: `action_${nanoid(8)}`,
  1019. type: 'spotlight',
  1020. title: '聚焦重点',
  1021. elementId: textElements[0].id,
  1022. });
  1023. }
  1024. // Add opening speech based on key points
  1025. const speechText = outline.keyPoints?.length
  1026. ? outline.keyPoints.join('。') + '。'
  1027. : outline.description || outline.title;
  1028. actions.push({
  1029. id: `action_${nanoid(8)}`,
  1030. type: 'speech',
  1031. title: '场景讲解',
  1032. text: speechText,
  1033. });
  1034. return actions;
  1035. }
  1036. /**
  1037. * Generate default quiz Actions (fallback)
  1038. */
  1039. function generateDefaultQuizActions(_outline: SceneOutline): Action[] {
  1040. return [
  1041. {
  1042. id: `action_${nanoid(8)}`,
  1043. type: 'speech',
  1044. title: '测验引导',
  1045. text: '现在让我们来做一个小测验,检验一下学习成果。',
  1046. },
  1047. ];
  1048. }
  1049. /**
  1050. * Generate default interactive Actions (fallback)
  1051. */
  1052. function generateDefaultInteractiveActions(_outline: SceneOutline): Action[] {
  1053. return [
  1054. {
  1055. id: `action_${nanoid(8)}`,
  1056. type: 'speech',
  1057. title: '交互引导',
  1058. text: '现在让我们通过交互式可视化来探索这个概念。请尝试操作页面中的元素,观察变化。',
  1059. },
  1060. ];
  1061. }
  1062. /**
  1063. * Create a complete scene with Actions
  1064. */
  1065. export function createSceneWithActions(
  1066. outline: SceneOutline,
  1067. content:
  1068. | GeneratedSlideContent
  1069. | GeneratedQuizContent
  1070. | GeneratedInteractiveContent
  1071. | GeneratedPBLContent,
  1072. actions: Action[],
  1073. api: ReturnType<typeof createStageAPI>,
  1074. ): string | null {
  1075. if (outline.type === 'slide' && 'elements' in content) {
  1076. // Build complete Slide object
  1077. const defaultTheme: SlideTheme = {
  1078. backgroundColor: '#ffffff',
  1079. themeColors: ['#5b9bd5', '#ed7d31', '#a5a5a5', '#ffc000', '#4472c4'],
  1080. fontColor: '#333333',
  1081. fontName: 'Microsoft YaHei',
  1082. outline: { color: '#d14424', width: 2, style: 'solid' },
  1083. shadow: { h: 0, v: 0, blur: 10, color: '#000000' },
  1084. };
  1085. const slide: Slide = {
  1086. id: nanoid(),
  1087. viewportSize: 1000,
  1088. viewportRatio: 0.5625,
  1089. theme: defaultTheme,
  1090. elements: content.elements,
  1091. background: content.background,
  1092. };
  1093. const sceneResult = api.scene.create({
  1094. type: 'slide',
  1095. title: outline.title,
  1096. order: outline.order,
  1097. content: {
  1098. type: 'slide',
  1099. canvas: slide,
  1100. },
  1101. actions,
  1102. });
  1103. return sceneResult.success ? (sceneResult.data ?? null) : null;
  1104. }
  1105. if (outline.type === 'quiz' && 'questions' in content) {
  1106. const sceneResult = api.scene.create({
  1107. type: 'quiz',
  1108. title: outline.title,
  1109. order: outline.order,
  1110. content: {
  1111. type: 'quiz',
  1112. questions: content.questions,
  1113. },
  1114. actions,
  1115. });
  1116. return sceneResult.success ? (sceneResult.data ?? null) : null;
  1117. }
  1118. if (outline.type === 'interactive' && 'html' in content) {
  1119. const sceneResult = api.scene.create({
  1120. type: 'interactive',
  1121. title: outline.title,
  1122. order: outline.order,
  1123. content: {
  1124. type: 'interactive',
  1125. url: '',
  1126. html: content.html,
  1127. },
  1128. actions,
  1129. });
  1130. return sceneResult.success ? (sceneResult.data ?? null) : null;
  1131. }
  1132. if (outline.type === 'pbl' && 'projectConfig' in content) {
  1133. const sceneResult = api.scene.create({
  1134. type: 'pbl',
  1135. title: outline.title,
  1136. order: outline.order,
  1137. content: {
  1138. type: 'pbl',
  1139. projectConfig: content.projectConfig,
  1140. },
  1141. actions,
  1142. });
  1143. return sceneResult.success ? (sceneResult.data ?? null) : null;
  1144. }
  1145. return null;
  1146. }