| 1 | import { ipcMain } from 'electron' |
| 2 | import log from 'electron-log/main.js' |
| 3 | import type { IpcContext } from '../../ipc/context' |
| 4 | import { resolveGlobalModelTimeouts, resolveModelConfigForTask } from '../../config/model-config-utils' |
| 5 | import { |
| 6 | getStylePackageDirectory, |
| 7 | saveGeneratedStylePreview |
| 8 | } from '../catalog' |
| 9 | import { generateStylePreviewHtml } from './generator' |
| 10 | import { |
| 11 | enqueueHtmlThumbnail, |
| 12 | waitForHtmlThumbnailTask |
| 13 | } from '../../io/thumbnails/html-thumbnail-service' |
| 14 | |
| 15 | export function registerStylePreviewHandlers(ctx: IpcContext): void { |
| 16 | ipcMain.handle('styles:generatePreview', async (_event, payload) => { |
| 17 | const styleId = typeof payload?.styleId === 'string' ? payload.styleId.trim() : '' |
| 18 | if (!styleId) throw new Error('styleId 为空') |
| 19 | |
| 20 | log.info('[styles:generatePreview] requested', { styleId }) |
| 21 | const activeModel = await resolveModelConfigForTask(ctx, { |
| 22 | modelConfigId: payload?.modelConfigId, |
| 23 | purpose: 'styles:generatePreview' |
| 24 | }) |
| 25 | const modelTimeouts = await resolveGlobalModelTimeouts(ctx) |
| 26 | const previewHtml = await generateStylePreviewHtml({ |
| 27 | styleId, |
| 28 | stylePackageDir: getStylePackageDirectory(styleId), |
| 29 | provider: activeModel.provider, |
| 30 | apiKey: activeModel.apiKey, |
| 31 | model: activeModel.model, |
| 32 | baseUrl: activeModel.baseUrl, |
| 33 | maxTokens: activeModel.maxTokens, |
| 34 | modelRuntime: ctx.modelRuntime, |
| 35 | modelTimeoutMs: modelTimeouts.document |
| 36 | }) |
| 37 | const result = await saveGeneratedStylePreview(styleId, previewHtml) |
| 38 | const thumbnailTask = await enqueueHtmlThumbnail( |
| 39 | { resourceType: 'style', resourceId: styleId, sourcePath: result.previewPath }, |
| 40 | { force: true } |
| 41 | ) |
| 42 | const completedThumbnail = |
| 43 | thumbnailTask.status === 'completed' |
| 44 | ? thumbnailTask |
| 45 | : await waitForHtmlThumbnailTask('style', styleId) |
| 46 | |
| 47 | return { success: true, ...result, thumbnailPath: completedThumbnail.thumbnailPath } |
| 48 | }) |
| 49 | } |
| 50 |