Skip to content

Formerly KrillinAI, VideoTranslation and Dubbing Tool for 120+ Languages. Open-source AI workspace for creators, powered by Codex. Video downloader, video translation, create videos, images, audios, and edits with Agents in one place. For your Social Media like YouTube, TikTok, Instagram, etc.

feat: add article writing workflow

Joshua58ef4e04dc08
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index db203b19..7d5af2a1 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -27,6 +27,8 @@ jobs:
go-version-file: runtime/krillinai/go.mod
cache-dependency-path: runtime/krillinai/go.sum
- run: pnpm install --frozen-lockfile
+ - name: Validate writing templates
+ run: pnpm --filter @opencreator/writing-templates test
- name: Audit high severity dependencies
run: pnpm audit --audit-level high --ignore-registry-errors
timeout-minutes: 5
diff --git a/apps/daemon/package.json b/apps/daemon/package.json
index 7787ab41..55c50ff1 100644
--- a/apps/daemon/package.json
+++ b/apps/daemon/package.json
@@ -3,35 +3,42 @@
"version": "0.1.0",
"type": "module",
"scripts": {
- "predev": "pnpm --filter @opencreator/protocol build && pnpm --filter @opencreator/config build && pnpm --filter @opencreator/skill-market build",
+ "predev": "pnpm --filter @opencreator/protocol build && pnpm --filter @opencreator/config build && pnpm --filter @opencreator/skill-market build && pnpm --filter @opencreator/writing-templates build",
"dev": "node scripts/dev.mjs",
- "prebuild": "pnpm --filter @opencreator/protocol build && pnpm --filter @opencreator/config build && pnpm --filter @opencreator/skill-market build",
+ "prebuild": "pnpm --filter @opencreator/protocol build && pnpm --filter @opencreator/config build && pnpm --filter @opencreator/skill-market build && pnpm --filter @opencreator/writing-templates build",
"build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json",
- "pretypecheck": "pnpm --filter @opencreator/protocol build && pnpm --filter @opencreator/config build && pnpm --filter @opencreator/skill-market build",
+ "pretypecheck": "pnpm --filter @opencreator/protocol build && pnpm --filter @opencreator/config build && pnpm --filter @opencreator/skill-market build && pnpm --filter @opencreator/writing-templates build",
"typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.test.json",
- "pretest": "pnpm --filter @opencreator/protocol build && pnpm --filter @opencreator/config build && pnpm --filter @opencreator/skill-market build",
+ "pretest": "pnpm --filter @opencreator/protocol build && pnpm --filter @opencreator/config build && pnpm --filter @opencreator/skill-market build && pnpm --filter @opencreator/writing-templates build",
"test": "vitest run --passWithNoTests",
"generate:codex-protocol": "node scripts/generate-codex-app-server-protocol.mjs",
"verify:schedule-upgrade": "node --import tsx scripts/verify-scheduled-task-upgrade.ts"
},
"dependencies": {
- "@opencreator/config": "workspace:*",
- "@opencreator/protocol": "workspace:*",
- "@opencreator/skill-market": "workspace:*",
"@fastify/cors": "^11.0.1",
"@iarna/toml": "2.2.5",
"@modelcontextprotocol/sdk": "1.29.0",
+ "@opencreator/config": "workspace:*",
+ "@opencreator/protocol": "workspace:*",
+ "@opencreator/skill-market": "workspace:*",
+ "@opencreator/writing-templates": "workspace:*",
"better-sqlite3": "^12.11.1",
+ "cheerio": "1.1.2",
"cron-parser": "^5.6.1",
"cross-spawn": "^7.0.6",
"fastify": "^5.2.1",
"https-proxy-agent": "^7.0.6",
+ "marked": "^18.0.12",
"nanoid": "^5.0.9",
+ "pdf-parse": "1.1.1",
+ "pdfkit": "^0.20.2",
"yaml": "^2.8.1",
"zod": "^3.25.76"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.13",
- "@types/cross-spawn": "^6.0.6"
+ "@types/cross-spawn": "^6.0.6",
+ "@types/pdf-parse": "1.1.5",
+ "@types/pdfkit": "^0.17.6"
}
}
diff --git a/apps/daemon/src/api/routes.creator.ts b/apps/daemon/src/api/routes.creator.ts
index c7c20d50..d4e2ad65 100644
--- a/apps/daemon/src/api/routes.creator.ts
+++ b/apps/daemon/src/api/routes.creator.ts
@@ -60,6 +60,11 @@ import {
CreatorSourceUploadError,
type CreatorSourceUploadService
} from '../creator/source-upload.js';
+import {
+ CREATOR_DOCUMENT_UPLOAD_CONTENT_TYPE,
+ CreatorDocumentUploadError,
+ type CreatorDocumentUploadService
+} from '../creator/document-upload.js';
export async function registerCreatorRoutes(
server: FastifyInstance,
@@ -73,6 +78,7 @@ export async function registerCreatorRoutes(
projectCoverService?: CreatorProjectCoverService;
referenceImageUploadService?: CreatorReferenceImageUploadService;
sourceUploadService?: CreatorSourceUploadService;
+ documentUploadService?: CreatorDocumentUploadService;
artifactImportService?: CreatorArtifactImportService;
jobsRoot: string;
dispatcher: CreatorCommandDispatcher;
@@ -152,6 +158,78 @@ export async function registerCreatorRoutes(
}
}
);
+ server.post<{ Body: Readable }>(
+ '/creator/jobs/:id/article-image',
+ async (request, reply) => {
+ const { id } = request.params as { id: string };
+ try {
+ const query = readObject(request.query);
+ if (!isReadable(request.body)) {
+ throw new TypeError('body must be an image stream');
+ }
+ const response = await options.referenceImageUploadService!.upload({
+ jobId: id,
+ expectedRevision: readQueryInteger(query.expectedRevision, 'expectedRevision'),
+ fileName: readString(query.fileName, 'fileName'),
+ mimeType: readString(query.mime, 'mime'),
+ lastModified: query.lastModified === undefined
+ ? null
+ : readQueryInteger(query.lastModified, 'lastModified'),
+ source: request.body,
+ purpose: 'article'
+ });
+ events.publish({
+ id: `snapshot:${response.job.revision}`,
+ jobId: response.job.id,
+ revision: response.job.revision,
+ kind: 'snapshot_changed',
+ payload: { revision: response.job.revision }
+ });
+ return reply.code(response.deduplicated ? 200 : 201).send(response);
+ } catch (error) {
+ return sendCreatorError(reply, error);
+ }
+ }
+ );
+ }
+
+ if (options.documentUploadService !== undefined) {
+ server.addContentTypeParser(
+ CREATOR_DOCUMENT_UPLOAD_CONTENT_TYPE,
+ (_request, payload, done) => done(null, payload)
+ );
+ server.post<{ Body: Readable }>(
+ '/creator/jobs/:id/source-document',
+ async (request, reply) => {
+ const { id } = request.params as { id: string };
+ try {
+ const query = readObject(request.query);
+ if (!isReadable(request.body)) {
+ throw new TypeError('body must be a document stream');
+ }
+ const response = await options.documentUploadService!.upload({
+ jobId: id,
+ expectedRevision: readQueryInteger(query.expectedRevision, 'expectedRevision'),
+ fileName: readString(query.fileName, 'fileName'),
+ mimeType: readString(query.mime, 'mime'),
+ lastModified: query.lastModified === undefined
+ ? null
+ : readQueryInteger(query.lastModified, 'lastModified'),
+ source: request.body
+ });
+ events.publish({
+ id: `snapshot:${response.job.revision}`,
+ jobId: response.job.id,
+ revision: response.job.revision,
+ kind: 'snapshot_changed',
+ payload: { revision: response.job.revision }
+ });
+ return reply.code(response.deduplicated ? 200 : 201).send(response);
+ } catch (error) {
+ return sendCreatorError(reply, error);
+ }
+ }
+ );
}
if (options.artifactImportService !== undefined) {
@@ -836,6 +914,10 @@ function sendCreatorError(reply: FastifyReply, error: unknown) {
return reply.code(error.statusCode)
.send(apiError(error.code as RuntimeErrorCode, error.message));
}
+ if (error instanceof CreatorDocumentUploadError) {
+ return reply.code(error.statusCode)
+ .send(apiError(error.code as RuntimeErrorCode, error.message));
+ }
if (error instanceof CreatorCommandError) {
const status = error.code === 'creator_job_not_found'
? 404
@@ -1018,6 +1100,11 @@ function creatorArtifactContentType(fileName: string): string {
if (extension === '.mp3') return 'audio/mpeg';
if (extension === '.wav') return 'audio/wav';
if (extension === '.m4a') return 'audio/mp4';
+ if (extension === '.md' || extension === '.markdown') return 'text/markdown; charset=utf-8';
+ if (extension === '.txt') return 'text/plain; charset=utf-8';
+ if (extension === '.json') return 'application/json; charset=utf-8';
+ if (extension === '.pdf') return 'application/pdf';
+ if (extension === '.html' || extension === '.htm') return 'text/html; charset=utf-8';
return 'application/octet-stream';
}
diff --git a/apps/daemon/src/api/server.ts b/apps/daemon/src/api/server.ts
index bd393189..0afba7e2 100644
--- a/apps/daemon/src/api/server.ts
+++ b/apps/daemon/src/api/server.ts
@@ -59,6 +59,10 @@ import { createClipExecutor } from '../creator/clip/executor.js';
import { createStickmanExecutor } from '../creator/stickman/executor.js';
import { createSmartDubbingExecutor } from '../creator/smart-dubbing/executor.js';
import { createXiaohongshuPostExecutor } from '../creator/xiaohongshu/executor.js';
+import { createWechatArticleExecutor } from '../creator/article/executor.js';
+import { createArticleImageGenerator } from '../creator/article/image-generator.js';
+import { createArticleSourceExtractor } from '../creator/article/source-extractor.js';
+import { createWechatArticleModel } from '../creator/article/model.js';
import { createCreatorProjectCoverService } from '../creator/project-cover.js';
import { createVideoGenerationService } from '../video-generation/service.js';
import {
@@ -69,6 +73,10 @@ import {
createCreatorSourceUploadService,
type CreatorSourceUploadService
} from '../creator/source-upload.js';
+import {
+ createCreatorDocumentUploadService,
+ type CreatorDocumentUploadService
+} from '../creator/document-upload.js';
import { createCreatorArtifactImportService } from '../creator/artifact-import.js';
import { validateMediaFile, type MediaProbe } from '../creator/validators/media.js';
import {
@@ -241,6 +249,8 @@ export type BuildServerInput = {
creatorReferenceImageUploadService?: CreatorReferenceImageUploadService;
creatorReferenceImageMaxSizeBytes?: number;
creatorSourceUploadService?: CreatorSourceUploadService;
+ creatorDocumentUploadService?: CreatorDocumentUploadService;
+ creatorDocumentMaxSizeBytes?: number;
creatorSourceMediaProbe?(path: string): Promise<MediaProbe>;
creatorSourceMaxSizeBytes?: number;
creatorYtDlpPath?: string;
@@ -511,6 +521,7 @@ export async function buildServer(input: BuildServerInput) {
let creatorFfmpegPath: string | undefined;
let creatorFfprobePath: string | undefined;
let creatorYtDlpUpdateManager = input.creatorYtDlpUpdateManager;
+ let getCreatorYtDlpRuntime: (() => ReturnType<typeof resolveYtDlpRuntime>) | undefined;
try {
const runtimeManifest = readKrillinRuntimeManifest(creatorRuntimeRoot);
verifyKrillinRuntimeManifest(creatorRuntimeRoot, runtimeManifest);
@@ -548,6 +559,7 @@ export async function buildServer(input: BuildServerInput) {
}
const getYtDlpRuntime = () =>
creatorYtDlpUpdateManager?.getRuntime() ?? ytDlp;
+ getCreatorYtDlpRuntime = getYtDlpRuntime;
if (input.creatorExecutors === undefined) {
creatorExecutors.push(createKrillinExecutor({
resourceRoot: creatorRuntimeRoot,
@@ -614,6 +626,14 @@ export async function buildServer(input: BuildServerInput) {
probeVideo: path => validateMediaFile(path, creatorFfprobePath!)
}));
}
+ creatorExecutors.push(createWechatArticleExecutor({
+ sourceExtractor: createArticleSourceExtractor({
+ configStore: creatorServicesConfigStore,
+ getYtDlpRuntime: getCreatorYtDlpRuntime
+ }),
+ model: createWechatArticleModel({ configStore: creatorServicesConfigStore }),
+ imageGenerator: createArticleImageGenerator({ configStore: creatorServicesConfigStore })
+ }));
}
const creatorProjectCoverService = createCreatorProjectCoverService({
jobsRoot: creatorJobsRoot,
@@ -638,6 +658,14 @@ export async function buildServer(input: BuildServerInput) {
creator: creatorService,
maxSizeBytes: input.creatorReferenceImageMaxSizeBytes
});
+ const creatorDocumentUploadService = input.creatorDocumentUploadService
+ ?? createCreatorDocumentUploadService({
+ jobsRoot: creatorJobsRoot,
+ creator: creatorService,
+ ...(input.creatorDocumentMaxSizeBytes === undefined
+ ? {}
+ : { maxSizeBytes: input.creatorDocumentMaxSizeBytes })
+ });
const creatorArtifactImportService = createCreatorArtifactImportService({
jobsRoot: creatorJobsRoot,
creator: creatorService
@@ -1025,6 +1053,7 @@ export async function buildServer(input: BuildServerInput) {
projectCoverService: creatorProjectCoverService,
referenceImageUploadService: creatorReferenceImageUploadService,
sourceUploadService: creatorSourceUploadService,
+ documentUploadService: creatorDocumentUploadService,
artifactImportService: creatorArtifactImportService,
dispatcher: creatorCommandDispatcher,
stageRunner: creatorStageRunner
diff --git a/apps/daemon/src/creator/article/document-generator.ts b/apps/daemon/src/creator/article/document-generator.ts
new file mode 100644
index 00000000..de1670ce
--- /dev/null
+++ b/apps/daemon/src/creator/article/document-generator.ts
@@ -0,0 +1,404 @@
+import type {
+ CreatorArtifact,
+ WechatArticleLayoutStyleId
+} from '@opencreator/protocol';
+import { existsSync } from 'node:fs';
+import { createWriteStream } from 'node:fs';
+import { readFile, writeFile } from 'node:fs/promises';
+import { extname } from 'node:path';
+import { finished } from 'node:stream/promises';
+import { marked, Renderer, type Token, type Tokens } from 'marked';
+import PDFDocument from 'pdfkit';
+
+type ArticleImageSource = {
+ path: string;
+ mimeType: string;
+};
+
+type ArticleDocumentInput = {
+ markdown: string;
+ title: string;
+ layoutStyleId: WechatArticleLayoutStyleId;
+ artifacts: CreatorArtifact[];
+};
+
+type PdfFont = {
+ regular: string;
+ bold: string;
+};
+
+const layoutAccents: Record<WechatArticleLayoutStyleId, string> = {
+ minimal: '#1f2937',
+ business: '#0f766e',
+ editorial: '#b42318',
+ vibrant: '#2563eb',
+ technical: '#4338ca',
+ podcast: '#7c3aed',
+ newsroom: '#b45309'
+};
+
+export async function writeArticleHtml(
+ path: string,
+ input: ArticleDocumentInput
+): Promise<number> {
+ const images = await imageSources(input.artifacts);
+ const renderer = new Renderer();
+ renderer.html = token => `<pre>${escapeHtml(token.text)}</pre>`;
+ renderer.image = token => {
+ const source = images.get(normalizeHref(token.href));
+ const src = source?.dataUri ?? safeRemoteImageUrl(token.href);
+ if (!src) return `<p class="missing-image">${escapeHtml(token.text || 'Image')}</p>`;
+ const caption = token.text.trim()
+ ? `<figcaption>${escapeHtml(token.text)}</figcaption>`
+ : '';
+ return `<figure><img src="${escapeAttribute(src)}" alt="${escapeAttribute(token.text)}">${caption}</figure>`;
+ };
+ renderer.link = token => {
+ const href = safeLinkUrl(token.href);
+ const label = marked.parseInline(token.text, { renderer }) as string;
+ return href
+ ? `<a href="${escapeAttribute(href)}">${label}</a>`
+ : label;
+ };
+ const body = marked.parse(input.markdown, {
+ gfm: true,
+ renderer
+ }) as string;
+ const accent = layoutAccents[input.layoutStyleId];
+ const html = `<!doctype html>
+<html lang="zh-CN">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>${escapeHtml(input.title)}</title>
+<style>
+:root { color-scheme: light; --accent: ${accent}; }
+* { box-sizing: border-box; }
+body { margin: 0; background: #f3f4f6; color: #202124; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans CJK SC", "Microsoft YaHei", sans-serif; }
+article { width: min(100% - 32px, 760px); margin: 32px auto; padding: 52px 58px 64px; background: #fff; }
+h1, h2, h3, h4 { color: #111827; line-height: 1.35; }
+h1 { margin: 0 0 32px; font-size: 32px; }
+h2 { margin: 42px 0 18px; padding-left: 12px; border-left: 4px solid var(--accent); font-size: 23px; }
+h3 { margin: 30px 0 14px; font-size: 18px; }
+p, li { font-size: 16px; line-height: 1.85; }
+p { margin: 0 0 18px; }
+ul, ol { margin: 0 0 22px; padding-left: 28px; }
+blockquote { margin: 26px 0; padding: 16px 20px; border-left: 4px solid var(--accent); background: #f7f7f8; color: #4b5563; }
+blockquote p { margin: 0; }
+figure { margin: 30px 0; }
+img { display: block; width: 100%; height: auto; }
+figcaption { margin-top: 9px; color: #6b7280; font-size: 13px; text-align: center; }
+pre { overflow-x: auto; margin: 22px 0; padding: 16px; background: #111827; color: #f9fafb; font-size: 13px; line-height: 1.65; white-space: pre-wrap; }
+code { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
+table { width: 100%; margin: 24px 0; border-collapse: collapse; font-size: 14px; }
+th, td { padding: 10px 12px; border: 1px solid #d1d5db; text-align: left; }
+th { background: #f3f4f6; }
+hr { margin: 34px 0; border: 0; border-top: 1px solid #d1d5db; }
+a { color: var(--accent); }
+.missing-image { padding: 18px; background: #f3f4f6; color: #6b7280; text-align: center; }
+@media (max-width: 640px) { article { width: 100%; margin: 0; padding: 30px 22px 48px; } h1 { font-size: 27px; } }
+@media print { body { background: #fff; } article { width: auto; margin: 0 auto; padding: 0; } }
+</style>
+</head>
+<body><article data-layout="${input.layoutStyleId}">${body}</article></body>
+</html>
+`;
+ await writeFile(path, html, 'utf8');
+ return Buffer.byteLength(html, 'utf8');
+}
+
+export async function writeArticlePdf(
+ path: string,
+ input: ArticleDocumentInput
+): Promise<number> {
+ const fonts = resolvePdfFonts();
+ const images = await imageSources(input.artifacts);
+ const document = new PDFDocument({
+ size: 'A4',
+ margins: { top: 58, right: 62, bottom: 58, left: 62 },
+ bufferPages: true,
+ info: { Title: input.title, Creator: 'OpenCreator' }
+ });
+ document.registerFont('ArticleRegular', fonts.regular);
+ document.registerFont('ArticleBold', fonts.bold);
+ const output = createWriteStream(path, { mode: 0o600 });
+ document.pipe(output);
+ const accent = layoutAccents[input.layoutStyleId];
+ renderPdfTokens(document, marked.lexer(input.markdown, { gfm: true }), images, accent);
+ const pages = document.bufferedPageRange();
+ for (let index = pages.start; index < pages.start + pages.count; index += 1) {
+ document.switchToPage(index);
+ document.font('ArticleRegular').fontSize(8).fillColor('#8a8f98').text(
+ String(index - pages.start + 1),
+ document.page.margins.left,
+ document.page.height - document.page.margins.bottom - 20,
+ { width: contentWidth(document), align: 'center', lineBreak: false }
+ );
+ }
+ document.end();
+ await finished(output);
+ return (await readFile(path)).byteLength;
+}
+
+function renderPdfTokens(
+ document: PDFKit.PDFDocument,
+ tokens: Token[],
+ images: Map<string, ArticleImageSource & { dataUri: string }>,
+ accent: string
+): void {
+ for (const token of tokens) {
+ if (token.type === 'space' || token.type === 'def') continue;
+ if (token.type === 'heading') {
+ const heading = token as Tokens.Heading;
+ const sizes = [25, 19, 15, 13, 12, 11];
+ ensurePdfSpace(document, heading.depth === 1 ? 58 : 42);
+ document
+ .font('ArticleBold')
+ .fontSize(sizes[heading.depth - 1] ?? 11)
+ .fillColor(heading.depth === 2 ? accent : '#17191c')
+ .text(inlineText(heading.tokens), { lineGap: 4 });
+ document.moveDown(heading.depth === 1 ? 0.85 : 0.55);
+ continue;
+ }
+ if (token.type === 'paragraph' || token.type === 'text') {
+ const inlineTokens = (token as Tokens.Paragraph | Tokens.Text).tokens ?? [];
+ const imageTokens = collectInlineImages(inlineTokens);
+ const text = inlineText(inlineTokens).trim();
+ if (text) {
+ document.font('ArticleRegular').fontSize(11).fillColor('#2f3338').text(text, {
+ lineGap: 5,
+ paragraphGap: 9
+ });
+ }
+ for (const image of imageTokens) renderPdfImage(document, image, images);
+ continue;
+ }
+ if (token.type === 'blockquote') {
+ const text = blockText((token as Tokens.Blockquote).tokens);
+ ensurePdfSpace(document, 52);
+ const startY = document.y;
+ document.font('ArticleRegular').fontSize(10.5).fillColor('#50545a').text(text, {
+ indent: 14,
+ lineGap: 4,
+ paragraphGap: 8
+ });
+ document.save().strokeColor(accent).lineWidth(3)
+ .moveTo(document.page.margins.left, startY)
+ .lineTo(document.page.margins.left, document.y - 5).stroke().restore();
+ document.moveDown(0.5);
+ continue;
+ }
+ if (token.type === 'list') {
+ const list = token as Tokens.List;
+ for (const [index, item] of list.items.entries()) {
+ const marker = list.ordered ? `${Number(list.start || 1) + index}.` : '-';
+ document.font('ArticleRegular').fontSize(11).fillColor('#2f3338').text(
+ `${marker} ${blockText(item.tokens)}`,
+ { indent: 8, lineGap: 4, paragraphGap: 6 }
+ );
+ }
+ document.moveDown(0.4);
+ continue;
+ }
+ if (token.type === 'code') {
+ const code = token as Tokens.Code;
+ ensurePdfSpace(document, 70);
+ const top = document.y;
+ const height = document.heightOfString(code.text, { width: contentWidth(document) - 24, lineGap: 3 }) + 22;
+ document.save().fillColor('#f1f3f5').roundedRect(document.page.margins.left, top, contentWidth(document), height, 4).fill().restore();
+ document.font('ArticleRegular').fontSize(9).fillColor('#333840').text(code.text, document.page.margins.left + 12, top + 10, {
+ width: contentWidth(document) - 24,
+ lineGap: 3
+ });
+ document.y = top + height + 12;
+ continue;
+ }
+ if (token.type === 'table') {
+ const table = token as Tokens.Table;
+ ensurePdfSpace(document, 65);
+ const rows = [table.header, ...table.rows];
+ for (const [index, row] of rows.entries()) {
+ document
+ .font(index === 0 ? 'ArticleBold' : 'ArticleRegular')
+ .fontSize(9.5)
+ .fillColor('#30343a')
+ .text(row.map(cell => inlineText(cell.tokens)).join(' | '), { lineGap: 3, paragraphGap: 5 });
+ document.moveTo(document.page.margins.left, document.y - 2)
+ .lineTo(document.page.width - document.page.margins.right, document.y - 2)
+ .strokeColor('#d7d9dd').lineWidth(0.5).stroke();
+ }
+ document.moveDown(0.6);
+ continue;
+ }
+ if (token.type === 'hr') {
+ document.moveDown(0.5);
+ document.moveTo(document.page.margins.left, document.y)
+ .lineTo(document.page.width - document.page.margins.right, document.y)
+ .strokeColor('#d7d9dd').lineWidth(0.7).stroke();
+ document.moveDown(1);
+ continue;
+ }
+ if (token.type === 'html') {
+ document.font('ArticleRegular').fontSize(9.5).fillColor('#555b63').text((token as Tokens.HTML).text, { lineGap: 3, paragraphGap: 8 });
+ }
+ }
+}
+
+function renderPdfImage(
+ document: PDFKit.PDFDocument,
+ token: Tokens.Image,
+ images: Map<string, ArticleImageSource & { dataUri: string }>
+): void {
+ const source = images.get(normalizeHref(token.href));
+ if (source === undefined || source.mimeType === 'image/webp') {
+ document.font('ArticleRegular').fontSize(9).fillColor('#737981').text(`[${token.text || 'Image'}]`, {
+ align: 'center',
+ paragraphGap: 8
+ });
+ return;
+ }
+ try {
+ const width = contentWidth(document);
+ const height = Math.min(width * 2 / 3, document.page.height * 0.56);
+ ensurePdfSpace(document, height + 24);
+ document.image(source.path, document.page.margins.left, document.y, {
+ fit: [width, height],
+ align: 'center',
+ valign: 'center'
+ });
+ document.y += height + 8;
+ if (token.text.trim()) {
+ document.font('ArticleRegular').fontSize(8.5).fillColor('#777d85').text(token.text, { align: 'center', paragraphGap: 10 });
+ }
+ } catch {
+ document.font('ArticleRegular').fontSize(9).fillColor('#737981').text(`[${token.text || 'Image'}]`, { align: 'center', paragraphGap: 8 });
+ }
+}
+
+function collectInlineImages(tokens: Token[]): Tokens.Image[] {
+ return tokens.flatMap(token => {
+ if (token.type === 'image') return [token as Tokens.Image];
+ const nested = 'tokens' in token && Array.isArray(token.tokens) ? token.tokens : [];
+ return collectInlineImages(nested);
+ });
+}
+
+function inlineText(tokens: Token[]): string {
+ return tokens.map(token => {
+ if (token.type === 'image') return '';
+ if (token.type === 'br') return '\n';
+ if (token.type === 'codespan') return (token as Tokens.Codespan).text;
+ if (token.type === 'text' || token.type === 'escape' || token.type === 'html') {
+ const nested = 'tokens' in token && Array.isArray(token.tokens) ? token.tokens : [];
+ return nested.length > 0 ? inlineText(nested) : ('text' in token && typeof token.text === 'string' ? token.text : '');
+ }
+ if ('tokens' in token && Array.isArray(token.tokens)) return inlineText(token.tokens);
+ return 'text' in token && typeof token.text === 'string' ? token.text : '';
+ }).join('');
+}
+
+function blockText(tokens: Token[]): string {
+ return tokens.map(token => {
+ if (token.type === 'paragraph' || token.type === 'text' || token.type === 'heading') {
+ const nested = 'tokens' in token && Array.isArray(token.tokens) ? token.tokens : [];
+ return inlineText(nested);
+ }
+ if (token.type === 'list') return (token as Tokens.List).items.map(item => blockText(item.tokens)).join('\n');
+ if (token.type === 'code') return (token as Tokens.Code).text;
+ if (token.type === 'html') return (token as Tokens.HTML).text;
+ if (token.type === 'blockquote') return blockText((token as Tokens.Blockquote).tokens);
+ return '';
+ }).filter(Boolean).join('\n');
+}
+
+function ensurePdfSpace(document: PDFKit.PDFDocument, height: number): void {
+ if (document.y + height <= document.page.height - document.page.margins.bottom) return;
+ document.addPage();
+}
+
+function contentWidth(document: PDFKit.PDFDocument): number {
+ return document.page.width - document.page.margins.left - document.page.margins.right;
+}
+
+async function imageSources(artifacts: CreatorArtifact[]): Promise<Map<string, ArticleImageSource & { dataUri: string }>> {
+ const sources = new Map<string, ArticleImageSource & { dataUri: string }>();
+ for (const artifact of [...artifacts].reverse()) {
+ if (artifact.kind !== 'article_image' || artifact.status !== 'completed' || artifact.path === null) continue;
+ const fileName = metadataString(artifact.metadata.fileName);
+ if (!fileName || sources.has(fileName)) continue;
+ const mimeType = metadataString(artifact.metadata.mimeType) || imageMimeType(fileName);
+ const content = await readFile(artifact.path).catch(() => undefined);
+ if (content === undefined) continue;
+ const source = {
+ path: artifact.path,
+ mimeType,
+ dataUri: `data:${mimeType};base64,${content.toString('base64')}`
+ };
+ sources.set(fileName, source);
+ sources.set(`./${fileName}`, source);
+ }
+ return sources;
+}
+
+function resolvePdfFonts(): PdfFont {
+ const candidates: PdfFont[] = process.platform === 'darwin'
+ ? [
+ { regular: '/Library/Fonts/RODE Noto Sans CJK SC R.otf', bold: '/Library/Fonts/RODE Noto Sans CJK SC B.otf' },
+ { regular: '/System/Library/Fonts/STHeiti Light.ttc', bold: '/System/Library/Fonts/STHeiti Medium.ttc' }
+ ]
+ : process.platform === 'win32'
+ ? [
+ { regular: 'C:\\Windows\\Fonts\\msyh.ttc', bold: 'C:\\Windows\\Fonts\\msyhbd.ttc' },
+ { regular: 'C:\\Windows\\Fonts\\simhei.ttf', bold: 'C:\\Windows\\Fonts\\simhei.ttf' }
+ ]
+ : [
+ { regular: '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc', bold: '/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc' },
+ { regular: '/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc', bold: '/usr/share/fonts/truetype/noto/NotoSansCJK-Bold.ttc' },
+ { regular: '/usr/share/fonts/opentype/source-han-sans/SourceHanSansSC-Regular.otf', bold: '/usr/share/fonts/opentype/source-han-sans/SourceHanSansSC-Bold.otf' }
+ ];
+ const selected = candidates.find(candidate => existsSync(candidate.regular));
+ if (selected === undefined) {
+ throw new Error('No CJK font is available for PDF generation');
+ }
+ return {
+ regular: selected.regular,
+ bold: existsSync(selected.bold) ? selected.bold : selected.regular
+ };
+}
+
+function metadataString(value: unknown): string {
+ return typeof value === 'string' ? value : '';
+}
+
+function imageMimeType(fileName: string): string {
+ const extension = extname(fileName).toLowerCase();
+ if (extension === '.jpg' || extension === '.jpeg') return 'image/jpeg';
+ if (extension === '.webp') return 'image/webp';
+ return 'image/png';
+}
+
+function normalizeHref(value: string): string {
+ return decodeURIComponent(value).replace(/^\.\//u, '');
+}
+
+function safeRemoteImageUrl(value: string): string {
+ return /^https?:\/\//iu.test(value) ? value : '';
+}
+
+function safeLinkUrl(value: string): string {
+ return /^(?:https?:\/\/|mailto:)/iu.test(value) ? value : '';
+}
+
+function escapeHtml(value: string): string {
+ return value.replace(/[&<>"']/gu, character => ({
+ '&': '&amp;',
+ '<': '&lt;',
+ '>': '&gt;',
+ '"': '&quot;',
+ "'": '&#39;'
+ })[character]!);
+}
+
+function escapeAttribute(value: string): string {
+ return escapeHtml(value);
+}
diff --git a/apps/daemon/src/creator/article/executor.ts b/apps/daemon/src/creator/article/executor.ts
new file mode 100644
index 00000000..588a0a06
--- /dev/null
+++ b/apps/daemon/src/creator/article/executor.ts
@@ -0,0 +1,656 @@
+import {
+ wechatArticleImageStyles,
+ wechatArticleLayoutStyles,
+ type CreatorArtifact,
+ type CreatorJson,
+ type WechatArticleImagePlanItem,
+ type WechatArticleImageStyleId,
+ type WechatArticleLayoutStyleId,
+ type WechatArticleSourceLink,
+ type WechatArticleTopic
+} from '@opencreator/protocol';
+import {
+ getWritingTemplate,
+ getWritingTemplateStagePrompt,
+ type WritingTemplateStage
+} from '@opencreator/writing-templates';
+import { createHash } from 'node:crypto';
+import { readFile, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import type { CreatorExecutor, CreatorExecutorResult } from '../executor.js';
+import { CreatorExecutorError } from '../executor.js';
+import { validateImageFile } from '../validators/image.js';
+import { writeArticleHtml, writeArticlePdf } from './document-generator.js';
+import type { ArticleImageGenerationResult } from './image-generator.js';
+import type { ExtractedArticleSource } from './source-extractor.js';
+
+export function createWechatArticleExecutor(input: {
+ sourceExtractor: {
+ extract(request: {
+ links: WechatArticleSourceLink[];
+ documents: CreatorArtifact[];
+ workdir: string;
+ signal: AbortSignal;
+ reportProgress(progress: Record<string, string | number | null>): void;
+ }): Promise<ExtractedArticleSource[]>;
+ };
+ model: {
+ generateTopics(request: {
+ sources: ExtractedArticleSource[];
+ writingPrompt: string;
+ templatePrompt: string;
+ count: number;
+ signal: AbortSignal;
+ }): Promise<WechatArticleTopic[]>;
+ generateOutline(request: {
+ sources: ExtractedArticleSource[];
+ topic: WechatArticleTopic;
+ writingPrompt: string;
+ templatePrompt: string;
+ signal: AbortSignal;
+ }): Promise<string>;
+ generateArticle(request: {
+ sources: ExtractedArticleSource[];
+ topic: WechatArticleTopic;
+ outline: string;
+ writingPrompt: string;
+ templatePrompt: string;
+ layoutPrompt: string;
+ signal: AbortSignal;
+ }): Promise<string>;
+ generateImagePlan?(request: {
+ articleMarkdown: string;
+ count: number;
+ stylePrompt: string;
+ customPrompt: string;
+ signal: AbortSignal;
+ }): Promise<WechatArticleImagePlanItem[]>;
+ };
+ imageGenerator?: {
+ generate(request: { prompt: string; signal: AbortSignal }): Promise<ArticleImageGenerationResult>;
+ };
+}): CreatorExecutor {
+ return {
+ id: 'wechat-article',
+ async run(stage) {
+ const state = stage.job.state;
+ if (stage.stageRun.stageId === 'sources') {
+ const documentIds = readStringArray(state.sourceDocumentArtifactIds);
+ const documents = stage.job.artifacts.filter(artifact => (
+ documentIds.includes(artifact.id)
+ && artifact.kind === 'source_document'
+ && artifact.status === 'completed'
+ ));
+ const links = readSourceLinks(state.sourceLinks);
+ const sourceSignature = createSourceSignature(links, documents);
+ stage.reportProgress({ phase: 'collecting_sources', percent: 5, completed: 0, failed: 0, total: links.length + documents.length });
+ const sources = await input.sourceExtractor.extract({
+ links,
+ documents,
+ workdir: stage.workdir,
+ signal: stage.signal,
+ reportProgress: stage.reportProgress
+ });
+ const sourcesPath = join(stage.workdir, 'article-sources.json');
+ await writeJson(sourcesPath, sources);
+ const sourceArtifactIds = documents.map(artifact => artifact.id);
+ return {
+ outputs: [{
+ kind: 'article_sources',
+ status: 'completed',
+ path: sourcesPath,
+ sourceArtifactIds,
+ metadata: sourceMetadata(sources, sourceSignature)
+ }],
+ progress: { phase: 'completed', percent: 100, completed: sources.length, failed: 0, total: links.length + documents.length }
+ };
+ }
+
+ if (stage.stageRun.stageId === 'topics') {
+ const documentIds = readStringArray(state.sourceDocumentArtifactIds);
+ const documents = stage.job.artifacts.filter(artifact => (
+ documentIds.includes(artifact.id)
+ && artifact.kind === 'source_document'
+ && artifact.status === 'completed'
+ ));
+ const links = readSourceLinks(state.sourceLinks);
+ const sourceSignature = createSourceSignature(links, documents);
+ const cachedSourceArtifact = stage.inputArtifacts.find(artifact => (
+ artifact.kind === 'article_sources'
+ && artifact.status === 'completed'
+ && artifact.metadata.sourceSignature === sourceSignature
+ ));
+ let sources: ExtractedArticleSource[];
+ let sourceOutput: CreatorExecutorResult['outputs'][number] | undefined;
+ if (cachedSourceArtifact !== undefined) {
+ sources = await readArtifactJson<ExtractedArticleSource[]>([cachedSourceArtifact], 'article_sources');
+ } else {
+ stage.reportProgress({ phase: 'collecting_sources', percent: 5, completed: 0, failed: 0, total: links.length + documents.length });
+ sources = await input.sourceExtractor.extract({
+ links,
+ documents,
+ workdir: stage.workdir,
+ signal: stage.signal,
+ reportProgress: stage.reportProgress
+ });
+ const sourcesPath = join(stage.workdir, 'article-sources.json');
+ await writeJson(sourcesPath, sources);
+ sourceOutput = {
+ kind: 'article_sources',
+ status: 'completed',
+ path: sourcesPath,
+ sourceArtifactIds: documents.map(artifact => artifact.id),
+ metadata: sourceMetadata(sources, sourceSignature)
+ };
+ }
+ stage.reportProgress({ phase: 'generating_topics', percent: 55, completed: sources.length, failed: 0, total: links.length + documents.length });
+ const topics = await input.model.generateTopics({
+ sources,
+ writingPrompt: readString(state.writingPrompt),
+ templatePrompt: resolveTemplatePrompt(state.presetId, state.templatePrompt, 'topics'),
+ count: readTopicCount(state.topicCount),
+ signal: stage.signal
+ });
+ const topicsPath = join(stage.workdir, 'article-topics.json');
+ await writeJson(topicsPath, topics);
+ const sourceArtifactIds = cachedSourceArtifact === undefined
+ ? documents.map(artifact => artifact.id)
+ : [cachedSourceArtifact.id];
+ const outputs: CreatorExecutorResult['outputs'] = [
+ ...(sourceOutput === undefined ? [] : [sourceOutput]),
+ {
+ kind: 'article_topics',
+ status: 'completed',
+ path: topicsPath,
+ sourceArtifactIds,
+ metadata: {
+ fileName: 'article-topics.json',
+ mimeType: 'application/json',
+ topics,
+ ...templateTrace(state.presetId)
+ }
+ }
+ ];
+ return {
+ outputs,
+ progress: { phase: 'completed', percent: 100, completed: topics.length, failed: 0, total: topics.length }
+ };
+ }
+
+ if (stage.stageRun.stageId === 'document') {
+ const markdown = readString(state.articleMarkdown)
+ || await readArtifactText(stage.inputArtifacts, 'article_markdown');
+ if (!markdown.trim()) {
+ throw new CreatorExecutorError('creator_stage_input_missing', 'Article content is required');
+ }
+ stage.reportProgress({ phase: 'preparing_document', percent: 20, completed: 0, failed: 0, total: 3 });
+ const title = firstHeading(markdown) || readString(state.articleTitle) || '公众号文章';
+ const fileStem = safeFileName(title) || 'wechat-article';
+ const markdownFileName = `${fileStem}.md`;
+ const htmlFileName = `${fileStem}.html`;
+ const pdfFileName = `${fileStem}.pdf`;
+ const markdownPath = join(stage.workdir, markdownFileName);
+ const htmlPath = join(stage.workdir, htmlFileName);
+ const pdfPath = join(stage.workdir, pdfFileName);
+ const content = `${markdown.trim()}\n`;
+ const layoutStyleId = readLayoutStyle(state.layoutStyleId);
+ await writeFile(markdownPath, content, 'utf8');
+ const [htmlBytes, pdfBytes] = await Promise.all([
+ writeArticleHtml(htmlPath, { markdown, title, layoutStyleId, artifacts: stage.job.artifacts }),
+ writeArticlePdf(pdfPath, { markdown, title, layoutStyleId, artifacts: stage.job.artifacts })
+ ]);
+ const sourceArtifactIds = documentSourceArtifactIds(markdown, stage.inputArtifacts, stage.job.artifacts);
+ const baseMetadata = {
+ title,
+ characterCount: [...markdown].length,
+ topicId: readString(state.selectedTopicId),
+ layoutStyleId,
+ ...templateTrace(state.presetId)
+ };
+ return {
+ outputs: [
+ {
+ kind: 'article_document',
+ status: 'completed',
+ path: markdownPath,
+ sourceArtifactIds,
+ metadata: {
+ ...baseMetadata,
+ fileName: markdownFileName,
+ mimeType: 'text/markdown',
+ documentFormat: 'markdown',
+ bytes: Buffer.byteLength(content, 'utf8')
+ }
+ },
+ {
+ kind: 'article_document',
+ status: 'completed',
+ path: htmlPath,
+ sourceArtifactIds,
+ metadata: {
+ ...baseMetadata,
+ fileName: htmlFileName,
+ mimeType: 'text/html',
+ documentFormat: 'html',
+ bytes: htmlBytes
+ }
+ },
+ {
+ kind: 'article_document',
+ status: 'completed',
+ path: pdfPath,
+ sourceArtifactIds,
+ metadata: {
+ ...baseMetadata,
+ fileName: pdfFileName,
+ mimeType: 'application/pdf',
+ documentFormat: 'pdf',
+ bytes: pdfBytes
+ }
+ }
+ ],
+ progress: { phase: 'completed', percent: 100, completed: 3, failed: 0, total: 3 }
+ };
+ }
+
+ if (stage.stageRun.stageId === 'images') {
+ if (input.model.generateImagePlan === undefined || input.imageGenerator === undefined) {
+ throw new CreatorExecutorError('creator_runtime_dependency_missing', 'Article image generation is unavailable');
+ }
+ const markdown = readString(state.articleMarkdown)
+ || await readArtifactText(stage.inputArtifacts, 'article_markdown');
+ if (!markdown.trim()) {
+ throw new CreatorExecutorError('creator_stage_input_missing', 'Article content is required before generating images');
+ }
+ const planningMarkdown = stripGeneratedArticleImages(markdown);
+ const count = readArticleImageCount(state.articleImageCount);
+ const style = readArticleImageStyle(state.articleImageStyleId);
+ const stylePrompt = articleImageStyleInstructions(style);
+ stage.reportProgress({ phase: 'planning_article_images', percent: 5, completed: 0, failed: 0, total: count });
+ const plan = await input.model.generateImagePlan({
+ articleMarkdown: planningMarkdown,
+ count,
+ stylePrompt,
+ customPrompt: readString(state.articleImagePrompt),
+ signal: stage.signal
+ });
+ if (plan.length === 0) {
+ throw new CreatorExecutorError('creator_llm_empty_response', 'Article image planning returned no images');
+ }
+ const articleArtifact = stage.inputArtifacts.find(artifact => artifact.kind === 'article_markdown');
+ const outputs: CreatorExecutorResult['outputs'] = [];
+ const failures: Array<{ candidate: number; message: string }> = [];
+ let firstFailure: unknown;
+ for (const [index, item] of plan.slice(0, count).entries()) {
+ try {
+ const articleContext = articleSectionContext(planningMarkdown, item.placementHeading);
+ const generated = await input.imageGenerator.generate({
+ prompt: [
+ stylePrompt,
+ 'The image must accurately represent the referenced article section. Preserve its concrete subject, setting, actions, relationships, mood, and factual meaning. Do not introduce unrelated themes or generic decorative scenes.',
+ `Placement heading: ${item.placementHeading}`,
+ `Caption intent: ${item.caption}`,
+ `Relevant article content:\n${articleContext}`,
+ 'Visual plan:',
+ item.prompt,
+ 'Landscape editorial illustration for a WeChat article, 3:2 composition.',
+ 'Do not render titles, paragraphs, logos, watermarks, UI, or illegible decorative text.'
+ ].join('\n\n'),
+ signal: stage.signal
+ });
+ const extension = extensionForMime(generated.mime);
+ const fileName = `article-image-${String(index + 1).padStart(2, '0')}.${extension}`;
+ const path = join(stage.workdir, fileName);
+ await writeFile(path, generated.content);
+ const metadata = await validateImageFile(path);
+ outputs.push({
+ kind: 'article_image',
+ status: 'completed',
+ path,
+ sourceArtifactIds: articleArtifact === undefined ? [] : [articleArtifact.id],
+ metadata: {
+ ...metadata,
+ fileName,
+ mimeType: generated.mime,
+ imageIndex: index + 1,
+ caption: item.caption,
+ placementHeading: item.placementHeading,
+ articleContext,
+ prompt: item.prompt,
+ imageStyleId: style,
+ provider: generated.provider,
+ model: generated.model
+ }
+ });
+ } catch (error) {
+ if (
+ error instanceof CreatorExecutorError
+ && (error.code === 'creator_image_config_missing' || error.code === 'creator_stage_canceled')
+ ) throw error;
+ firstFailure ??= error;
+ failures.push({
+ candidate: index + 1,
+ message: error instanceof Error ? error.message : 'Article image generation failed'
+ });
+ }
+ stage.reportProgress({
+ phase: 'generating_article_images',
+ percent: 10 + Math.round(((index + 1) / Math.max(1, plan.length)) * 85),
+ completed: outputs.length,
+ failed: failures.length,
+ total: plan.length
+ });
+ }
+ if (outputs.length === 0) {
+ if (firstFailure instanceof CreatorExecutorError) throw firstFailure;
+ throw new CreatorExecutorError('image_generation_failed', failures[0]?.message ?? 'Article image generation failed');
+ }
+ return {
+ outputs,
+ progress: {
+ phase: 'completed',
+ percent: 100,
+ completed: outputs.length,
+ failed: failures.length,
+ total: plan.length,
+ ...(failures.length > 0 ? { status: 'partial_success', failures } : {})
+ }
+ };
+ }
+
+ const sources = await readSources(stage.inputArtifacts);
+ const topics = readTopics(state.topics).length > 0
+ ? readTopics(state.topics)
+ : await readArtifactJson<WechatArticleTopic[]>(stage.inputArtifacts, 'article_topics');
+ const topic = selectTopic(topics, readString(state.selectedTopicId));
+ if (stage.stageRun.stageId === 'outline') {
+ stage.reportProgress({ phase: 'generating_outline', percent: 15 });
+ const outline = await input.model.generateOutline({
+ sources,
+ topic,
+ writingPrompt: readString(state.writingPrompt),
+ templatePrompt: resolveTemplatePrompt(state.presetId, state.templatePrompt, 'outline'),
+ signal: stage.signal
+ });
+ const path = join(stage.workdir, 'article-outline.md');
+ await writeFile(path, `${outline.trim()}\n`, 'utf8');
+ return {
+ outputs: [{
+ kind: 'article_outline',
+ status: 'completed',
+ path,
+ metadata: {
+ fileName: 'article-outline.md',
+ mimeType: 'text/markdown',
+ outline: outline.trim(),
+ topicId: topic.id,
+ ...templateTrace(state.presetId)
+ }
+ }],
+ progress: { phase: 'completed', percent: 100, completed: 1, failed: 0, total: 1 }
+ };
+ }
+
+ if (stage.stageRun.stageId === 'article') {
+ const outline = readString(state.outline)
+ || await readArtifactText(stage.inputArtifacts, 'article_outline');
+ if (!outline.trim()) {
+ throw new CreatorExecutorError('creator_stage_input_missing', 'Article outline is required');
+ }
+ stage.reportProgress({ phase: 'writing_article', percent: 10 });
+ const markdown = await input.model.generateArticle({
+ sources,
+ topic,
+ outline,
+ writingPrompt: readString(state.writingPrompt),
+ templatePrompt: resolveTemplatePrompt(state.presetId, state.templatePrompt, 'article'),
+ layoutPrompt: layoutInstructions(readLayoutStyle(state.layoutStyleId)),
+ signal: stage.signal
+ });
+ const path = join(stage.workdir, 'wechat-article.md');
+ await writeFile(path, `${markdown.trim()}\n`, 'utf8');
+ return {
+ outputs: [{
+ kind: 'article_markdown',
+ status: 'completed',
+ path,
+ metadata: {
+ fileName: 'wechat-article.md',
+ mimeType: 'text/markdown',
+ title: firstHeading(markdown) || topic.title,
+ characterCount: [...markdown].length,
+ topicId: topic.id,
+ ...templateTrace(state.presetId)
+ }
+ }],
+ progress: { phase: 'completed', percent: 100, completed: 1, failed: 0, total: 1 }
+ };
+ }
+
+ throw new CreatorExecutorError('creator_stage_not_found', `Unsupported article stage: ${stage.stageRun.stageId}`);
+ }
+ };
+}
+
+function readSourceLinks(value: CreatorJson | undefined): WechatArticleSourceLink[] {
+ if (!Array.isArray(value)) return [];
+ return value.flatMap(item => {
+ if (!isRecord(item) || typeof item.id !== 'string' || typeof item.url !== 'string') return [];
+ if (item.kind !== 'video' && item.kind !== 'webpage') return [];
+ return [{
+ id: item.id,
+ url: item.url,
+ kind: item.kind,
+ label: typeof item.label === 'string' ? item.label : ''
+ }];
+ });
+}
+
+function readTopics(value: CreatorJson | undefined): WechatArticleTopic[] {
+ if (!Array.isArray(value)) return [];
+ return value.flatMap(item => {
+ if (!isRecord(item) || typeof item.id !== 'string' || typeof item.title !== 'string') return [];
+ return [{
+ id: item.id,
+ title: item.title,
+ angle: typeof item.angle === 'string' ? item.angle : '',
+ summary: typeof item.summary === 'string' ? item.summary : ''
+ }];
+ });
+}
+
+function selectTopic(topics: WechatArticleTopic[], selectedId: string): WechatArticleTopic {
+ const topic = topics.find(candidate => candidate.id === selectedId) ?? (topics.length === 1 ? topics[0] : undefined);
+ if (topic === undefined) {
+ throw new CreatorExecutorError('creator_stage_input_missing', 'Select an article topic before continuing');
+ }
+ return topic;
+}
+
+async function readSources(artifacts: CreatorArtifact[]): Promise<ExtractedArticleSource[]> {
+ return readArtifactJson<ExtractedArticleSource[]>(artifacts, 'article_sources');
+}
+
+function documentSourceArtifactIds(
+ markdown: string,
+ inputArtifacts: CreatorArtifact[],
+ jobArtifacts: CreatorArtifact[]
+): string[] {
+ const ids = new Set(inputArtifacts
+ .filter(artifact => artifact.kind === 'article_markdown')
+ .map(artifact => artifact.id));
+ for (const artifact of jobArtifacts) {
+ if (artifact.kind !== 'article_image' || artifact.status !== 'completed') continue;
+ const fileName = readString(artifact.metadata.fileName);
+ if (fileName && (markdown.includes(`](${fileName})`) || markdown.includes(`](./${fileName})`))) {
+ ids.add(artifact.id);
+ }
+ }
+ return [...ids];
+}
+
+async function readArtifactJson<T>(artifacts: CreatorArtifact[], kind: string): Promise<T> {
+ const text = await readArtifactText(artifacts, kind);
+ return JSON.parse(text) as T;
+}
+
+async function readArtifactText(artifacts: CreatorArtifact[], kind: string): Promise<string> {
+ const artifact = artifacts.find(candidate => candidate.kind === kind && candidate.path !== null);
+ if (artifact?.path === null || artifact === undefined) {
+ throw new CreatorExecutorError('creator_stage_input_missing', `Missing ${kind} artifact`);
+ }
+ return readFile(artifact.path, 'utf8');
+}
+
+function readString(value: CreatorJson | undefined): string {
+ return typeof value === 'string' ? value.trim() : '';
+}
+
+function readStringArray(value: CreatorJson | undefined): string[] {
+ return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];
+}
+
+function readTopicCount(value: CreatorJson | undefined): number {
+ return typeof value === 'number' && Number.isInteger(value)
+ ? Math.max(3, Math.min(10, value))
+ : 5;
+}
+
+function readLayoutStyle(value: CreatorJson | undefined): WechatArticleLayoutStyleId {
+ return wechatArticleLayoutStyles.some(style => style.id === value)
+ ? value as WechatArticleLayoutStyleId
+ : 'minimal';
+}
+
+function readArticleImageCount(value: CreatorJson | undefined): number {
+ return typeof value === 'number' && Number.isInteger(value)
+ ? Math.max(1, Math.min(10, value))
+ : 5;
+}
+
+function readArticleImageStyle(value: CreatorJson | undefined): WechatArticleImageStyleId {
+ return wechatArticleImageStyles.some(style => style.id === value)
+ ? value as WechatArticleImageStyleId
+ : 'editorial';
+}
+
+function articleImageStyleInstructions(id: WechatArticleImageStyleId): string {
+ return wechatArticleImageStyles.find(style => style.id === id)?.instructions ?? '';
+}
+
+function stripGeneratedArticleImages(markdown: string): string {
+ return markdown
+ .replace(/^[ \t]*!\[[^\]\n]*\]\((?:\.\/)?article-image-\d+\.(?:png|jpe?g|webp)\)[ \t]*$/gim, '')
+ .replace(/\n{3,}/g, '\n\n')
+ .trim();
+}
+
+function articleSectionContext(markdown: string, placementHeading: string): string {
+ const lines = markdown.split('\n');
+ const requestedHeading = normalizeArticleHeading(placementHeading);
+ const headings = lines.flatMap((line, lineIndex) => {
+ const match = /^(#{1,6})\s+(.+?)\s*$/.exec(line);
+ return match === null
+ ? []
+ : [{ lineIndex, level: match[1]!.length, normalized: normalizeArticleHeading(match[2]!) }];
+ });
+ const matched = headings.find(heading => heading.normalized === requestedHeading)
+ ?? headings.find(heading => (
+ requestedHeading.length > 0
+ && (heading.normalized.includes(requestedHeading) || requestedHeading.includes(heading.normalized))
+ ));
+ if (matched === undefined) return markdown.trim().slice(0, 2_000);
+
+ const nextHeading = headings.find(heading => (
+ heading.lineIndex > matched.lineIndex
+ && heading.level <= matched.level
+ ));
+ const section = lines
+ .slice(matched.lineIndex, nextHeading?.lineIndex ?? lines.length)
+ .join('\n')
+ .trim();
+ return (section || markdown.trim()).slice(0, 2_000);
+}
+
+function normalizeArticleHeading(value: string): string {
+ return value
+ .replace(/^#{1,6}\s*/, '')
+ .replace(/[\s*_`\[\]()()【】《》::,.,。!?!?-]+/g, '')
+ .toLocaleLowerCase();
+}
+
+function extensionForMime(mime: ArticleImageGenerationResult['mime']): string {
+ if (mime === 'image/jpeg') return 'jpg';
+ if (mime === 'image/webp') return 'webp';
+ return 'png';
+}
+
+function layoutInstructions(id: WechatArticleLayoutStyleId): string {
+ return wechatArticleLayoutStyles.find(style => style.id === id)?.instructions ?? '';
+}
+
+function resolveTemplatePrompt(
+ presetValue: CreatorJson | undefined,
+ customValue: CreatorJson | undefined,
+ stage: WritingTemplateStage
+): string {
+ const presetId = readString(presetValue);
+ const template = presetId ? getWritingTemplate(presetId) : undefined;
+ const packagedPrompt = template ? getWritingTemplateStagePrompt(template.id, stage) : '';
+ const customPrompt = readString(customValue);
+ if (!customPrompt || customPrompt === template?.instructions) return packagedPrompt;
+ return [packagedPrompt, `用户补充的模板要求:\n${customPrompt}`].filter(Boolean).join('\n\n');
+}
+
+function templateTrace(presetValue: CreatorJson | undefined) {
+ const template = getWritingTemplate(readString(presetValue));
+ return {
+ writingTemplateId: template?.id ?? null,
+ writingTemplateVersion: template?.version ?? null,
+ writingTemplateRevision: template?.source.revision ?? null,
+ writingTemplateHash: template?.contentHash ?? null
+ };
+}
+
+function firstHeading(markdown: string): string {
+ return /^#\s+(.+)$/m.exec(markdown)?.[1]?.trim() ?? '';
+}
+
+function safeFileName(value: string): string {
+ return value.trim().replace(/[\\/:*?"<>|]/g, '-').replace(/\s+/g, ' ').slice(0, 80);
+}
+
+function isRecord(value: CreatorJson): value is Record<string, CreatorJson> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function writeJson(path: string, value: unknown): Promise<void> {
+ return writeFile(path, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
+}
+
+function createSourceSignature(
+ links: WechatArticleSourceLink[],
+ documents: CreatorArtifact[]
+): string {
+ const payload = {
+ links: links.map(link => ({ id: link.id, url: link.url, kind: link.kind })),
+ documents: documents.map(artifact => ({
+ id: artifact.id,
+ fileName: artifact.metadata.fileName ?? null,
+ bytes: artifact.metadata.bytes ?? null,
+ sha256: artifact.metadata.sha256 ?? null
+ }))
+ };
+ return createHash('sha256').update(JSON.stringify(payload)).digest('hex');
+}
+
+function sourceMetadata(sources: ExtractedArticleSource[], sourceSignature: string) {
+ return {
+ fileName: 'article-sources.json',
+ mimeType: 'application/json',
+ sourceSignature,
+ sourceCount: sources.length,
+ sourceTitles: sources.map(source => source.title),
+ automaticTranscriptCount: sources.filter(source => source.transcriptType === 'automatic').length
+ };
+}
diff --git a/apps/daemon/src/creator/article/image-generator.ts b/apps/daemon/src/creator/article/image-generator.ts
new file mode 100644
index 00000000..95836036
--- /dev/null
+++ b/apps/daemon/src/creator/article/image-generator.ts
@@ -0,0 +1,57 @@
+import type { ImageGenerationProvider } from '@opencreator/protocol';
+import type { CreatorServicesConfigStore } from '../../creator-services/config-store.js';
+import {
+ generateImageContents,
+ ImageGenerationProviderError,
+ type GeneratedImageContent
+} from '../../image-generation/provider.js';
+import { CreatorExecutorError } from '../executor.js';
+
+export type ArticleImageGenerationResult = GeneratedImageContent & {
+ provider: ImageGenerationProvider;
+ model: string;
+};
+
+export function createArticleImageGenerator(input: {
+ configStore: Pick<CreatorServicesConfigStore, 'read'>;
+ generate?: typeof generateImageContents;
+}) {
+ const generate = input.generate ?? generateImageContents;
+ return {
+ async generate(request: {
+ prompt: string;
+ signal: AbortSignal;
+ }): Promise<ArticleImageGenerationResult> {
+ const config = await input.configStore.read();
+ const provider = config.image.provider;
+ try {
+ const result = await generate({
+ prompt: request.prompt,
+ provider,
+ size: '1536x1024',
+ quality: 'medium',
+ count: 1
+ }, config, { signal: request.signal });
+ const image = result.contents[0];
+ if (image === undefined) {
+ throw new ImageGenerationProviderError('upstream_error', 'The image provider returned no image');
+ }
+ return { ...image, provider, model: result.model };
+ } catch (error) {
+ if (error instanceof ImageGenerationProviderError) {
+ throw error.code === 'config_missing'
+ ? new CreatorExecutorError('creator_image_config_missing', error.message)
+ : new CreatorExecutorError('image_generation_failed', error.message);
+ }
+ if (error instanceof DOMException && error.name === 'AbortError') {
+ throw new CreatorExecutorError('creator_stage_canceled', 'Creator stage was canceled');
+ }
+ if (error instanceof CreatorExecutorError) throw error;
+ throw new CreatorExecutorError(
+ 'image_generation_failed',
+ error instanceof Error ? error.message : 'Article image generation failed'
+ );
+ }
+ }
+ };
+}
diff --git a/apps/daemon/src/creator/article/model.ts b/apps/daemon/src/creator/article/model.ts
new file mode 100644
index 00000000..89233d77
--- /dev/null
+++ b/apps/daemon/src/creator/article/model.ts
@@ -0,0 +1,193 @@
+import type { WechatArticleImagePlanItem, WechatArticleTopic } from '@opencreator/protocol';
+import { z } from 'zod';
+import type { CreatorServicesConfigStore } from '../../creator-services/config-store.js';
+import {
+ creatorServiceErrorMessage,
+ fetchCreatorService,
+ openAiCompatibleEndpoint
+} from '../../creator-services/upstream-fetch.js';
+import { CreatorExecutorError } from '../executor.js';
+import type { ExtractedArticleSource } from './source-extractor.js';
+
+const topicsSchema = z.object({
+ topics: z.array(z.object({
+ title: z.string().min(1).max(160),
+ angle: z.string().max(500).default(''),
+ summary: z.string().max(1_000).default('')
+ }).strict()).min(1).max(10)
+}).strict();
+
+const imagePlanSchema = z.object({
+ images: z.array(z.object({
+ caption: z.string().min(1).max(200),
+ placementHeading: z.string().min(1).max(200),
+ prompt: z.string().min(1).max(2_000)
+ }).strict()).min(1).max(10)
+}).strict();
+
+export function createWechatArticleModel(input: {
+ configStore: Pick<CreatorServicesConfigStore, 'read'>;
+ fetchImpl?: typeof fetch;
+}) {
+ async function complete(request: {
+ prompt: string;
+ signal: AbortSignal;
+ json?: boolean;
+ }): Promise<string> {
+ const config = await input.configStore.read();
+ if (!config.llm.apiKey.trim() || !config.llm.model.trim()) {
+ throw new CreatorExecutorError('creator_llm_config_missing', 'LLM configuration is incomplete');
+ }
+ const response = await fetchCreatorService({
+ endpoint: openAiCompatibleEndpoint(config.llm.baseUrl, 'chat/completions'),
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${config.llm.apiKey}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ model: config.llm.model,
+ ...(request.json && config.llm.jsonMode ? { response_format: { type: 'json_object' } } : {}),
+ messages: [{ role: 'user', content: request.prompt }]
+ }),
+ proxy: config.proxy,
+ signal: request.signal,
+ maxResponseBytes: 4 * 1024 * 1024,
+ fetchImpl: input.fetchImpl
+ });
+ if (!response.ok) {
+ throw new CreatorExecutorError(
+ 'creator_llm_upstream_error',
+ await creatorServiceErrorMessage(response, 'Article writing')
+ );
+ }
+ const payload = await response.json() as {
+ choices?: Array<{ message?: { content?: string | Array<{ text?: string }> } }>;
+ };
+ const raw = payload.choices?.[0]?.message?.content;
+ const content = typeof raw === 'string'
+ ? raw
+ : Array.isArray(raw)
+ ? raw.map(item => item.text ?? '').join('')
+ : '';
+ if (!content.trim()) {
+ throw new CreatorExecutorError('creator_llm_empty_response', 'Article writing returned no content');
+ }
+ return content.trim();
+ }
+
+ return {
+ async generateTopics(request: {
+ sources: ExtractedArticleSource[];
+ writingPrompt: string;
+ templatePrompt: string;
+ count: number;
+ signal: AbortSignal;
+ }): Promise<WechatArticleTopic[]> {
+ const parsed = topicsSchema.parse(parseJson(await complete({
+ json: true,
+ signal: request.signal,
+ prompt: [
+ '你是一名资深微信公众号主编。请根据来源和用户要求提出可直接写作的选题。',
+ `生成 ${request.count} 个差异明显的选题,只输出严格 JSON:{"topics":[{"title":"标题","angle":"核心切入角度","summary":"文章内容摘要"}]}`,
+ '标题要具体、克制、有信息量,不使用虚假数据或来源没有支持的结论。',
+ request.templatePrompt.trim() ? `文章模板规则:\n${request.templatePrompt}` : '',
+ request.writingPrompt.trim() ? `用户写作要求:${request.writingPrompt}` : '用户没有额外写作要求。',
+ sourcePrompt(request.sources)
+ ].filter(Boolean).join('\n\n')
+ })));
+ return parsed.topics.slice(0, request.count).map((topic, index) => ({
+ id: `topic-${index + 1}`,
+ ...topic
+ }));
+ },
+ generateOutline(request: {
+ sources: ExtractedArticleSource[];
+ topic: WechatArticleTopic;
+ writingPrompt: string;
+ templatePrompt: string;
+ signal: AbortSignal;
+ }): Promise<string> {
+ return complete({
+ signal: request.signal,
+ prompt: [
+ '你是一名资深微信公众号主编。请为选定选题生成可编辑的文章大纲。',
+ '使用 Markdown。第一行是文章标题,随后列出导语、二到五个主体章节及每节要点、结尾。',
+ '大纲要形成完整论证或叙事推进,明确哪些事实来自素材,禁止虚构。不要直接写成全文。',
+ `选题:${JSON.stringify(request.topic)}`,
+ request.templatePrompt.trim() ? `文章模板规则:\n${request.templatePrompt}` : '',
+ request.writingPrompt.trim() ? `用户写作要求:${request.writingPrompt}` : '用户没有额外写作要求。',
+ sourcePrompt(request.sources)
+ ].filter(Boolean).join('\n\n')
+ });
+ },
+ generateArticle(request: {
+ sources: ExtractedArticleSource[];
+ topic: WechatArticleTopic;
+ outline: string;
+ writingPrompt: string;
+ templatePrompt: string;
+ layoutPrompt: string;
+ signal: AbortSignal;
+ }): Promise<string> {
+ return complete({
+ signal: request.signal,
+ prompt: [
+ '你是一名资深微信公众号作者。请按选题和大纲完成一篇可直接编辑发布的中文文章。',
+ '只输出 Markdown 正文,从一级标题开始。保持事实边界,来源没有的信息不要编造;不要输出写作说明。',
+ `选题:${JSON.stringify(request.topic)}`,
+ `大纲:\n${request.outline}`,
+ request.templatePrompt.trim() ? `文章模板要求:${request.templatePrompt}` : '',
+ request.layoutPrompt.trim() ? `Markdown 排版要求:${request.layoutPrompt}` : '',
+ request.writingPrompt.trim() ? `用户写作要求:${request.writingPrompt}` : '',
+ sourcePrompt(request.sources)
+ ].filter(Boolean).join('\n\n')
+ });
+ },
+ async generateImagePlan(request: {
+ articleMarkdown: string;
+ count: number;
+ stylePrompt: string;
+ customPrompt: string;
+ signal: AbortSignal;
+ }): Promise<WechatArticleImagePlanItem[]> {
+ const parsed = imagePlanSchema.parse(parseJson(await complete({
+ json: true,
+ signal: request.signal,
+ prompt: [
+ '你是一名资深视觉编辑。请为下面这篇微信公众号文章规划内容互不重复的配图。',
+ `生成 ${request.count} 张配图,只输出严格 JSON:{"images":[{"caption":"图片说明","placementHeading":"建议放在哪个章节标题之后","prompt":"可直接用于图像生成模型的完整英文提示词"}]}`,
+ 'placementHeading 必须原样复制文章中真实存在的 Markdown 标题,优先选择二级或三级标题。',
+ '每张图必须服务于所选章节的具体内容,并覆盖不同的核心段落。prompt 要准确呈现该章节中的人物、对象、场景、动作、关系或数据含义;抽象内容可以使用贴合原意的视觉隐喻,但禁止生成与正文无关的装饰性画面。',
+ '主体、场景和视觉隐喻要具体。不要把文章标题、段落文字、Logo、水印或大段可见文字放进画面。',
+ `统一视觉风格:${request.stylePrompt}`,
+ request.customPrompt.trim() ? `用户补充的配图要求:${request.customPrompt}` : '',
+ `文章正文:\n${request.articleMarkdown.slice(0, 100_000)}`
+ ].filter(Boolean).join('\n\n')
+ })));
+ return parsed.images.slice(0, request.count).map((item, index) => ({
+ id: `article-image-${index + 1}`,
+ ...item
+ }));
+ }
+ };
+}
+
+function sourcePrompt(sources: ExtractedArticleSource[]): string {
+ if (sources.length === 0) return '本次没有内容来源,请基于用户要求写作,并避免捏造具体事实和数据。';
+ let remaining = 120_000;
+ const sections: string[] = [];
+ for (const [index, source] of sources.entries()) {
+ if (remaining <= 0) break;
+ const header = `[来源 ${index + 1}] ${source.title}\n出处:${source.origin}\n`;
+ const content = source.content.slice(0, Math.max(0, remaining - header.length));
+ sections.push(`${header}${content}`);
+ remaining -= header.length + content.length;
+ }
+ return `内容来源:\n${sections.join('\n\n')}`;
+}
+
+function parseJson(value: string): unknown {
+ const fenced = /^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(value.trim());
+ return JSON.parse(fenced?.[1] ?? value);
+}
diff --git a/apps/daemon/src/creator/article/source-extractor.ts b/apps/daemon/src/creator/article/source-extractor.ts
new file mode 100644
index 00000000..fa3d15e9
--- /dev/null
+++ b/apps/daemon/src/creator/article/source-extractor.ts
@@ -0,0 +1,318 @@
+import type { CreatorArtifact, WechatArticleSourceLink } from '@opencreator/protocol';
+import { load } from 'cheerio';
+import { createRequire } from 'node:module';
+import { readFile } from 'node:fs/promises';
+import { extname } from 'node:path';
+import type { CreatorServicesConfigStore } from '../../creator-services/config-store.js';
+import { fetchCreatorService } from '../../creator-services/upstream-fetch.js';
+import { CreatorExecutorError } from '../executor.js';
+import { spawnCreatorProcess } from '../process-tree.js';
+import { withYtDlpProxy } from '../yt-dlp/args.js';
+import type { YtDlpRuntime } from '../yt-dlp/runtime.js';
+
+const MAX_SOURCE_CHARS = 50_000;
+const require = createRequire(import.meta.url);
+const pdfParse = require('pdf-parse') as (buffer: Buffer) => Promise<{ text: string }>;
+
+export type ExtractedArticleSource = {
+ id: string;
+ type: 'video' | 'webpage' | 'document';
+ title: string;
+ origin: string;
+ content: string;
+ transcriptType?: 'human' | 'automatic';
+ transcriptLanguage?: string;
+};
+
+export function createArticleSourceExtractor(input: {
+ configStore: Pick<CreatorServicesConfigStore, 'read'>;
+ getYtDlpRuntime?(): YtDlpRuntime | undefined;
+ runYtDlp?: typeof runYtDlp;
+ fetchService?: typeof fetchCreatorService;
+}) {
+ const fetchService = input.fetchService ?? fetchCreatorService;
+ const readVideoMetadata = input.runYtDlp ?? runYtDlp;
+ return {
+ async extract(request: {
+ links: WechatArticleSourceLink[];
+ documents: CreatorArtifact[];
+ workdir: string;
+ signal: AbortSignal;
+ reportProgress(progress: Record<string, string | number | null>): void;
+ }): Promise<ExtractedArticleSource[]> {
+ const config = await input.configStore.read();
+ const total = request.links.length + request.documents.length;
+ const sources: ExtractedArticleSource[] = [];
+ let completed = 0;
+ for (const link of request.links) {
+ assertNotAborted(request.signal);
+ request.reportProgress({
+ phase: link.kind === 'video' ? 'reading_video' : 'reading_webpage',
+ percent: total === 0 ? 25 : Math.round(10 + completed / total * 35),
+ message: link.label || link.url
+ });
+ sources.push(link.kind === 'video'
+ ? await extractVideo(
+ link,
+ config.proxy,
+ request.signal,
+ input.getYtDlpRuntime?.(),
+ readVideoMetadata,
+ fetchService
+ )
+ : await extractWebpage(link, config.proxy, request.signal, fetchService));
+ completed += 1;
+ }
+ for (const artifact of request.documents) {
+ assertNotAborted(request.signal);
+ const fileName = readMetadataString(artifact.metadata.fileName) ?? 'document';
+ request.reportProgress({
+ phase: 'reading_document',
+ percent: total === 0 ? 25 : Math.round(10 + completed / total * 35),
+ message: fileName
+ });
+ sources.push(await extractDocument(artifact));
+ completed += 1;
+ }
+ return sources;
+ }
+ };
+}
+
+async function extractWebpage(
+ link: WechatArticleSourceLink,
+ proxy: string,
+ signal: AbortSignal,
+ fetchService: typeof fetchCreatorService
+): Promise<ExtractedArticleSource> {
+ const endpoint = new URL(link.url);
+ if (endpoint.protocol !== 'http:' && endpoint.protocol !== 'https:') {
+ throw new CreatorExecutorError('creator_source_unavailable', `Unsupported webpage URL: ${link.url}`);
+ }
+ const response = await fetchService({
+ endpoint,
+ method: 'GET',
+ headers: {
+ Accept: 'text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.5',
+ 'User-Agent': 'OpenCreator/1.0'
+ },
+ proxy,
+ signal,
+ maxResponseBytes: 5 * 1024 * 1024
+ });
+ if (!response.ok) {
+ throw new CreatorExecutorError(
+ 'creator_source_unavailable',
+ `Unable to read webpage (${response.status}): ${link.url}`
+ );
+ }
+ const html = await response.text();
+ const $ = load(html);
+ $('script,style,noscript,svg,nav,footer,form').remove();
+ const title = cleanText(
+ $('meta[property="og:title"]').attr('content')
+ || $('h1').first().text()
+ || $('title').first().text()
+ ) || link.label || link.url;
+ const root = $('#js_content,.rich_media_content,article,main,[role="main"]').first();
+ const content = cleanText((root.length > 0 ? root : $('body')).text()).slice(0, MAX_SOURCE_CHARS);
+ if (!content) {
+ throw new CreatorExecutorError('creator_source_empty', `No readable text found at ${link.url}`);
+ }
+ return { id: link.id, type: 'webpage', title, origin: link.url, content };
+}
+
+async function extractVideo(
+ link: WechatArticleSourceLink,
+ proxy: string,
+ signal: AbortSignal,
+ runtime: YtDlpRuntime | undefined,
+ readVideoMetadata: typeof runYtDlp,
+ fetchService: typeof fetchCreatorService
+): Promise<ExtractedArticleSource> {
+ if (runtime === undefined) {
+ throw new CreatorExecutorError(
+ 'creator_runtime_dependency_missing',
+ 'Video sources require the yt-dlp runtime component'
+ );
+ }
+ const payload = JSON.parse(await readVideoMetadata(runtime, link.url, proxy, signal)) as Record<string, unknown>;
+ const title = readString(payload.title) ?? link.label ?? link.url;
+ const description = readString(payload.description) ?? '';
+ const humanCaption = chooseCaption(payload.subtitles);
+ const automaticCaption = chooseCaption(payload.automatic_captions);
+ const caption = humanCaption ?? automaticCaption;
+ if (caption === undefined) {
+ throw new CreatorExecutorError(
+ 'creator_source_transcript_missing',
+ `No subtitles are available for video: ${link.url}`
+ );
+ }
+ const response = await fetchService({
+ endpoint: new URL(caption.url),
+ method: 'GET',
+ headers: { Accept: 'text/vtt,text/plain,application/json,application/xml,*/*' },
+ proxy,
+ signal,
+ maxResponseBytes: 8 * 1024 * 1024
+ });
+ if (!response.ok) {
+ throw new CreatorExecutorError(
+ 'creator_source_unavailable',
+ `Unable to download subtitles (${response.status}): ${link.url}`
+ );
+ }
+ const captions = parseCaptions(await response.text(), caption.ext);
+ if (!captions) {
+ throw new CreatorExecutorError(
+ 'creator_source_transcript_missing',
+ `No readable subtitles are available for video: ${link.url}`
+ );
+ }
+ const content = [description, captions].filter(Boolean).join('\n\n').slice(0, MAX_SOURCE_CHARS);
+ return {
+ id: link.id,
+ type: 'video',
+ title,
+ origin: link.url,
+ content,
+ transcriptType: humanCaption === undefined ? 'automatic' : 'human',
+ transcriptLanguage: caption.language
+ };
+}
+
+async function extractDocument(artifact: CreatorArtifact): Promise<ExtractedArticleSource> {
+ if (artifact.path === null) {
+ throw new CreatorExecutorError('creator_source_unavailable', 'Source document file is missing');
+ }
+ const fileName = readMetadataString(artifact.metadata.fileName) ?? 'document';
+ const extension = extname(fileName).toLowerCase();
+ const buffer = await readFile(artifact.path);
+ let content: string;
+ if (extension === '.pdf') {
+ content = cleanText((await pdfParse(buffer)).text);
+ } else if (extension === '.html' || extension === '.htm') {
+ const $ = load(buffer.toString('utf8'));
+ $('script,style,noscript,svg,nav,footer,form').remove();
+ content = cleanText($('article,main,[role="main"]').first().text() || $('body').text());
+ } else {
+ content = buffer.toString('utf8').trim();
+ }
+ if (!content) {
+ throw new CreatorExecutorError('creator_source_empty', `No readable text found in ${fileName}`);
+ }
+ return {
+ id: artifact.id,
+ type: 'document',
+ title: fileName,
+ origin: fileName,
+ content: content.slice(0, MAX_SOURCE_CHARS)
+ };
+}
+
+function runYtDlp(
+ runtime: YtDlpRuntime,
+ url: string,
+ proxy: string,
+ signal: AbortSignal
+): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const child = spawnCreatorProcess(runtime.executable, [
+ ...runtime.prefixArgs,
+ ...withYtDlpProxy(['--dump-single-json', '--no-playlist', url], proxy)
+ ], {
+ env: { ...process.env, ...runtime.env },
+ stdio: ['ignore', 'pipe', 'pipe']
+ }, signal);
+ let stdout = '';
+ let stderr = '';
+ child.stdout?.on('data', chunk => { stdout += String(chunk); });
+ child.stderr?.on('data', chunk => { stderr += String(chunk); });
+ child.once('error', reject);
+ child.once('exit', code => {
+ if (code === 0 && stdout.trim()) resolve(stdout);
+ else reject(new CreatorExecutorError(
+ 'creator_source_unavailable',
+ stderr.trim().slice(-500) || `Unable to read video source: ${url}`
+ ));
+ });
+ });
+}
+
+function chooseCaption(value: unknown): { url: string; ext: string; language: string } | undefined {
+ if (!isRecord(value)) return undefined;
+ const languages = [...new Set(['zh-Hans', 'zh-CN', 'zh', 'en-US', 'en', ...Object.keys(value)])];
+ for (const language of languages) {
+ const formats = value[language];
+ if (!Array.isArray(formats)) continue;
+ const candidates = formats.filter(isRecord);
+ const preferred = ['vtt', 'json3', 'srv3', 'ttml', 'srt', 'ass']
+ .flatMap(ext => candidates.filter(item => item.ext === ext))
+ .at(0) ?? candidates[0];
+ if (preferred !== undefined && typeof preferred.url === 'string') {
+ return {
+ url: preferred.url,
+ ext: typeof preferred.ext === 'string' ? preferred.ext : '',
+ language
+ };
+ }
+ }
+ return undefined;
+}
+
+function parseCaptions(value: string, extension: string): string {
+ if (extension === 'json3') {
+ try {
+ const payload = JSON.parse(value) as { events?: Array<{ segs?: Array<{ utf8?: unknown }> }> };
+ return (payload.events ?? [])
+ .flatMap(event => event.segs ?? [])
+ .map(segment => typeof segment.utf8 === 'string' ? segment.utf8 : '')
+ .join('')
+ .replace(/\n{3,}/g, '\n\n')
+ .trim()
+ .slice(0, MAX_SOURCE_CHARS);
+ } catch {
+ return '';
+ }
+ }
+ if (extension === 'srv3' || extension === 'ttml' || /^\s*</.test(value)) {
+ const $ = load(value, { xmlMode: true });
+ return cleanText($.root().text()).slice(0, MAX_SOURCE_CHARS);
+ }
+ return cleanCaptions(value);
+}
+
+function cleanCaptions(value: string): string {
+ return value
+ .replace(/^WEBVTT[^\n]*\n/i, '')
+ .replace(/^\d\d:\d\d(?::\d\d)?[.,]\d+\s+-->.*$/gm, '')
+ .replace(/^\d+$/gm, '')
+ .replace(/<[^>]+>/g, '')
+ .split(/\r?\n/)
+ .map(line => line.trim())
+ .filter((line, index, lines) => line && line !== lines[index - 1])
+ .join('\n')
+ .slice(0, MAX_SOURCE_CHARS);
+}
+
+function cleanText(value: string): string {
+ return value.replace(/\s+/g, ' ').trim();
+}
+
+function readMetadataString(value: unknown): string | undefined {
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
+}
+
+function readString(value: unknown): string | undefined {
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function assertNotAborted(signal: AbortSignal): void {
+ if (signal.aborted) {
+ throw new CreatorExecutorError('creator_stage_canceled', 'Creator stage was canceled');
+ }
+}
diff --git a/apps/daemon/src/creator/document-upload.ts b/apps/daemon/src/creator/document-upload.ts
new file mode 100644
index 00000000..76a6c7eb
--- /dev/null
+++ b/apps/daemon/src/creator/document-upload.ts
@@ -0,0 +1,181 @@
+import type { CreatorSourceUploadResponse } from '@opencreator/protocol';
+import { createHash, randomBytes } from 'node:crypto';
+import { createWriteStream } from 'node:fs';
+import { mkdir, rename, rm } from 'node:fs/promises';
+import { basename, extname, join, resolve } from 'node:path';
+import { Transform, type Readable } from 'node:stream';
+import { pipeline } from 'node:stream/promises';
+import { CreatorServiceError, type CreatorService } from './service.js';
+
+export const CREATOR_DOCUMENT_UPLOAD_CONTENT_TYPE =
+ 'application/vnd.opencreator.creator-document';
+export const CREATOR_DOCUMENT_MAX_SIZE_BYTES = 25 * 1024 * 1024;
+
+export type CreatorDocumentUploadService = ReturnType<typeof createCreatorDocumentUploadService>;
+
+export class CreatorDocumentUploadError extends Error {
+ constructor(
+ readonly code: string,
+ message: string,
+ readonly statusCode: number
+ ) {
+ super(message);
+ this.name = 'CreatorDocumentUploadError';
+ }
+}
+
+export function createCreatorDocumentUploadService(input: {
+ jobsRoot: string;
+ creator: CreatorService;
+ maxSizeBytes?: number;
+}) {
+ const jobsRoot = resolve(input.jobsRoot);
+ const maxSizeBytes = input.maxSizeBytes ?? CREATOR_DOCUMENT_MAX_SIZE_BYTES;
+
+ return {
+ async upload(request: {
+ jobId: string;
+ expectedRevision: number;
+ fileName: string;
+ mimeType: string;
+ lastModified: number | null;
+ source: Readable;
+ }): Promise<CreatorSourceUploadResponse> {
+ const current = input.creator.getJob(request.jobId);
+ if (current === undefined) {
+ throw new CreatorDocumentUploadError('creator_job_not_found', 'Creator job not found', 404);
+ }
+ if (current.revision !== request.expectedRevision) {
+ throw new CreatorDocumentUploadError(
+ 'creator_revision_conflict',
+ 'Creator job revision changed',
+ 409
+ );
+ }
+ const fileName = safeFileName(request.fileName);
+ const extension = safeExtension(fileName);
+ const mimeType = safeMimeType(request.mimeType, extension);
+ const uploadDir = join(jobsRoot, safeJobSegment(request.jobId), 'documents');
+ await mkdir(uploadDir, { recursive: true, mode: 0o700 });
+ const token = randomBytes(12).toString('hex');
+ const temporaryPath = join(uploadDir, `.${token}.upload`);
+ const finalPath = join(uploadDir, `document-${token}${extension}`);
+ const hash = createHash('sha256');
+ let size = 0;
+ const meter = new Transform({
+ transform(chunk: Buffer, _encoding, callback) {
+ size += chunk.length;
+ if (size > maxSizeBytes) {
+ callback(new CreatorDocumentUploadError(
+ 'creator_document_too_large',
+ `Document exceeds the ${maxSizeBytes} byte limit`,
+ 413
+ ));
+ return;
+ }
+ hash.update(chunk);
+ callback(null, chunk);
+ }
+ });
+
+ try {
+ await pipeline(
+ request.source,
+ meter,
+ createWriteStream(temporaryPath, { flags: 'wx', mode: 0o600 })
+ );
+ if (size === 0) {
+ throw new CreatorDocumentUploadError(
+ 'creator_document_empty',
+ 'Document must not be empty',
+ 400
+ );
+ }
+ await rename(temporaryPath, finalPath);
+ try {
+ const response = input.creator.registerSourceDocument(request.jobId, {
+ expectedRevision: request.expectedRevision,
+ path: finalPath,
+ fileName,
+ mimeType,
+ size,
+ sha256: hash.digest('hex'),
+ lastModified: request.lastModified
+ });
+ if (response.deduplicated) await rm(finalPath, { force: true });
+ return response;
+ } catch (error) {
+ await rm(finalPath, { force: true }).catch(() => undefined);
+ throw error;
+ }
+ } catch (error) {
+ await rm(temporaryPath, { force: true }).catch(() => undefined);
+ if (error instanceof CreatorDocumentUploadError || error instanceof CreatorServiceError) {
+ throw error;
+ }
+ throw new CreatorDocumentUploadError(
+ 'creator_document_upload_failed',
+ error instanceof Error ? error.message : 'Document upload failed',
+ 500
+ );
+ }
+ }
+ };
+}
+
+function safeJobSegment(value: string): string {
+ if (!/^creator_job_[A-Za-z0-9_-]+$/.test(value)) {
+ throw new CreatorDocumentUploadError('creator_job_not_found', 'Creator job not found', 404);
+ }
+ return value;
+}
+
+function safeFileName(value: string): string {
+ const safe = basename(value.replaceAll('\\', '/'))
+ .replace(/[\u0000-\u001f\u007f]/g, '')
+ .trim();
+ if (!safe) {
+ throw new CreatorDocumentUploadError(
+ 'creator_document_invalid',
+ 'Document file name is invalid',
+ 400
+ );
+ }
+ return safe.slice(0, 255);
+}
+
+function safeExtension(fileName: string): '.pdf' | '.txt' | '.md' | '.markdown' | '.html' | '.htm' {
+ const extension = extname(fileName).toLowerCase();
+ if (['.pdf', '.txt', '.md', '.markdown', '.html', '.htm'].includes(extension)) {
+ return extension as '.pdf' | '.txt' | '.md' | '.markdown' | '.html' | '.htm';
+ }
+ throw new CreatorDocumentUploadError(
+ 'creator_document_type_unsupported',
+ `Document type is not supported: ${extension || 'unknown'}`,
+ 415
+ );
+}
+
+function safeMimeType(value: string, extension: string): string {
+ const mimeType = value.split(';', 1)[0]?.trim().toLowerCase() ?? '';
+ const allowed = new Set([
+ 'application/pdf',
+ 'text/plain',
+ 'text/markdown',
+ 'text/html',
+ 'application/octet-stream',
+ ''
+ ]);
+ if (!allowed.has(mimeType)) {
+ throw new CreatorDocumentUploadError(
+ 'creator_document_type_unsupported',
+ `Document MIME type is not supported: ${mimeType}`,
+ 415
+ );
+ }
+ if (mimeType && mimeType !== 'application/octet-stream') return mimeType;
+ if (extension === '.pdf') return 'application/pdf';
+ if (extension === '.html' || extension === '.htm') return 'text/html';
+ if (extension === '.md' || extension === '.markdown') return 'text/markdown';
+ return 'text/plain';
+}
diff --git a/apps/daemon/src/creator/reference-image-upload.ts b/apps/daemon/src/creator/reference-image-upload.ts
index be238c01..37181482 100644
--- a/apps/daemon/src/creator/reference-image-upload.ts
+++ b/apps/daemon/src/creator/reference-image-upload.ts
@@ -42,6 +42,7 @@ export function createCreatorReferenceImageUploadService(input: {
mimeType: string;
lastModified: number | null;
source: Readable;
+ purpose?: 'reference' | 'article';
}): Promise<CreatorSourceUploadResponse> {
const current = input.creator.getJob(request.jobId);
if (current === undefined) {
@@ -62,12 +63,13 @@ export function createCreatorReferenceImageUploadService(input: {
const jobSegment = safeJobSegment(request.jobId);
const fileName = safeFileName(request.fileName);
const mimeType = safeMimeType(request.mimeType);
- const uploadDir = join(jobsRoot, jobSegment, 'references');
+ const purpose = request.purpose ?? 'reference';
+ const uploadDir = join(jobsRoot, jobSegment, purpose === 'article' ? 'article-images' : 'references');
await mkdir(uploadDir, { recursive: true });
const token = randomBytes(12).toString('hex');
const extension = safeExtension(fileName, mimeType);
const temporaryPath = join(uploadDir, `.${token}.upload`);
- const finalPath = join(uploadDir, `reference-${token}${extension}`);
+ const finalPath = join(uploadDir, `${purpose === 'article' ? 'article-image' : 'reference'}-${token}${extension}`);
const hash = createHash('sha256');
let size = 0;
const meter = new Transform({
@@ -112,7 +114,10 @@ export function createCreatorReferenceImageUploadService(input: {
const sha256 = hash.digest('hex');
await rename(temporaryPath, finalPath);
try {
- const response = input.creator.registerReferenceImage(request.jobId, {
+ const register = purpose === 'article'
+ ? input.creator.registerArticleImage
+ : input.creator.registerReferenceImage;
+ const response = register(request.jobId, {
expectedRevision: request.expectedRevision,
path: finalPath,
fileName,
diff --git a/apps/daemon/src/creator/service.ts b/apps/daemon/src/creator/service.ts
index 6c152b35..9fedf31e 100644
--- a/apps/daemon/src/creator/service.ts
+++ b/apps/daemon/src/creator/service.ts
@@ -9,6 +9,7 @@ import type {
CreatorJobStatus,
CreatorJson
} from '@opencreator/protocol';
+import { wechatArticleSourceLimit } from '@opencreator/protocol';
import { writeFileSync } from 'node:fs';
import { basename, extname, join, dirname } from 'node:path';
import type { CreatorRepository } from './repository.js';
@@ -406,6 +407,184 @@ export function createCreatorService(input: {
};
});
},
+ registerArticleImage(jobId: string, input: {
+ expectedRevision: number;
+ path: string;
+ fileName: string;
+ mimeType: string;
+ size: number;
+ sha256: string;
+ lastModified: number | null;
+ format: 'png' | 'jpeg' | 'webp';
+ }): { job: CreatorJob; artifact: CreatorArtifact; deduplicated: boolean } {
+ return repository.transaction(() => {
+ const current = repository.getJob(jobId);
+ if (current === undefined) {
+ throw new CreatorServiceError('creator_job_not_found', 'Creator job not found');
+ }
+ if (current.revision !== input.expectedRevision) {
+ throw new CreatorServiceError(
+ 'creator_revision_conflict',
+ 'Creator job revision changed',
+ current.revision
+ );
+ }
+ if (current.templateId !== 'wechat-article') {
+ throw new CreatorServiceError(
+ 'creator_article_image_upload_unsupported',
+ 'Article image upload is only supported for WeChat article jobs'
+ );
+ }
+ const duplicate = [...current.artifacts].reverse().find(artifact => (
+ artifact.kind === 'article_image'
+ && artifact.status === 'completed'
+ && artifact.metadata.source === 'local-upload'
+ && artifact.metadata.sha256 === input.sha256
+ ));
+ const selectedIds = readStringArray(current.state.manualArticleImageArtifactIds);
+ if (duplicate !== undefined && selectedIds.includes(duplicate.id)) {
+ return { job: current, artifact: duplicate, deduplicated: true };
+ }
+ const extension = input.format === 'jpeg' ? 'jpg' : input.format;
+ const articleFileName = `article-upload-${input.sha256.slice(0, 12)}.${extension}`;
+ const artifact = duplicate ?? repository.insertArtifact({
+ jobId,
+ kind: 'article_image',
+ status: 'completed',
+ path: input.path,
+ sourceArtifactIds: [],
+ metadata: {
+ fileName: articleFileName,
+ originalFileName: input.fileName,
+ mimeType: input.mimeType,
+ size: input.size,
+ bytes: input.size,
+ sha256: input.sha256,
+ lastModified: input.lastModified,
+ format: input.format,
+ source: 'local-upload'
+ }
+ });
+ const revision = current.revision + 1;
+ const template = templates.get(current.templateId, current.templateVersion);
+ repository.updateJob({
+ id: jobId,
+ status: current.status,
+ revision,
+ state: template.inputSchema.parse({
+ ...current.state,
+ manualArticleImageArtifactIds: [...new Set([...selectedIds, artifact.id])]
+ }) as Record<string, CreatorJson>
+ });
+ repository.insertActivity({
+ jobId,
+ revision,
+ actor: 'user',
+ action: 'register-article-image',
+ summary: duplicate === undefined ? '上传文章配图' : '重新插入文章配图',
+ details: {
+ objectId: input.fileName,
+ affectedArtifactIds: [artifact.id]
+ }
+ });
+ return {
+ job: repository.getJob(jobId)!,
+ artifact,
+ deduplicated: duplicate !== undefined
+ };
+ });
+ },
+ registerSourceDocument(jobId: string, input: {
+ expectedRevision: number;
+ path: string;
+ fileName: string;
+ mimeType: string;
+ size: number;
+ sha256: string;
+ lastModified: number | null;
+ }): { job: CreatorJob; artifact: CreatorArtifact; deduplicated: boolean } {
+ return repository.transaction(() => {
+ const current = repository.getJob(jobId);
+ if (current === undefined) {
+ throw new CreatorServiceError('creator_job_not_found', 'Creator job not found');
+ }
+ if (current.revision !== input.expectedRevision) {
+ throw new CreatorServiceError(
+ 'creator_revision_conflict',
+ 'Creator job revision changed',
+ current.revision
+ );
+ }
+ if (current.templateId !== 'wechat-article') {
+ throw new CreatorServiceError(
+ 'creator_document_upload_unsupported',
+ 'Document upload is only supported for WeChat article jobs'
+ );
+ }
+ const duplicate = [...current.artifacts].reverse().find(artifact => (
+ artifact.kind === 'source_document'
+ && artifact.status === 'completed'
+ && artifact.metadata.sha256 === input.sha256
+ ));
+ const selectedIds = readStringArray(current.state.sourceDocumentArtifactIds);
+ if (duplicate !== undefined && selectedIds.includes(duplicate.id)) {
+ return { job: current, artifact: duplicate, deduplicated: true };
+ }
+ const sourceLinkCount = Array.isArray(current.state.sourceLinks)
+ ? current.state.sourceLinks.length
+ : 0;
+ if (sourceLinkCount + selectedIds.length >= wechatArticleSourceLimit) {
+ throw new CreatorServiceError(
+ 'creator_source_limit_exceeded',
+ `A WeChat article can use at most ${wechatArticleSourceLimit} inspiration sources`
+ );
+ }
+ const artifact = duplicate ?? repository.insertArtifact({
+ jobId,
+ kind: 'source_document',
+ status: 'completed',
+ path: input.path,
+ sourceArtifactIds: [],
+ metadata: {
+ fileName: input.fileName,
+ mimeType: input.mimeType,
+ size: input.size,
+ bytes: input.size,
+ sha256: input.sha256,
+ lastModified: input.lastModified,
+ source: 'local-upload'
+ }
+ });
+ const revision = current.revision + 1;
+ const template = templates.get(current.templateId, current.templateVersion);
+ repository.updateJob({
+ id: jobId,
+ status: 'draft',
+ revision,
+ state: template.inputSchema.parse({
+ ...current.state,
+ sourceDocumentArtifactIds: [...new Set([...selectedIds, artifact.id])],
+ currentStage: null
+ }) as Record<string, CreatorJson>
+ });
+ repository.insertActivity({
+ jobId,
+ revision,
+ actor: 'user',
+ action: 'register-source-document',
+ summary: duplicate === undefined ? '上传内容灵感' : '重新选择内容灵感',
+ details: {
+ objectId: input.fileName,
+ affectedArtifactIds: [artifact.id]
+ }
+ });
+ return {
+ job: repository.getJob(jobId)!,
+ artifact,
+ deduplicated: duplicate !== undefined
+ };
+ });
+ },
bindAgentThread(jobId: string, threadId: string): CreatorJob {
return repository.transaction(() => {
const current = repository.getJob(jobId);
@@ -788,6 +967,10 @@ export function createCreatorService(input: {
};
}
+function readStringArray(value: CreatorJson | undefined): string[] {
+ return Array.isArray(value) ? value.filter(item => typeof item === 'string') : [];
+}
+
function shouldClearTtsConfigurationRequest(
job: CreatorJob,
nextState: Record<string, CreatorJson>
diff --git a/apps/daemon/src/creator/stage-runner.ts b/apps/daemon/src/creator/stage-runner.ts
index 8c94fe57..b3322367 100644
--- a/apps/daemon/src/creator/stage-runner.ts
+++ b/apps/daemon/src/creator/stage-runner.ts
@@ -480,6 +480,13 @@ function errorCode(error: unknown): string {
}
function resultSnapshotDescription(stageId: string, templateId: string): string {
+ if (templateId === 'wechat-article') {
+ if (stageId === 'sources') return '解析内容灵感';
+ if (stageId === 'topics') return '生成候选选题';
+ if (stageId === 'outline') return '生成文章大纲';
+ if (stageId === 'article') return '撰写公众号文章';
+ if (stageId === 'images') return '生成文章配图';
+ }
if (stageId === 'subtitle') return '生成字幕';
if (stageId === 'tts') return '生成配音';
if (stageId === 'render-horizontal') return '合成横屏视频';
diff --git a/apps/daemon/src/creator/templates/registry.ts b/apps/daemon/src/creator/templates/registry.ts
index e1d33f58..5ba42d19 100644
--- a/apps/daemon/src/creator/templates/registry.ts
+++ b/apps/daemon/src/creator/templates/registry.ts
@@ -13,6 +13,7 @@ import { createAutoClipTemplate } from './auto-clip.js';
import { createStickmanVideoTemplate } from './stickman-video.js';
import { createSmartDubbingTemplate } from './smart-dubbing.js';
import { createXiaohongshuPostTemplate } from './xiaohongshu-post.js';
+import { createWechatArticleTemplate } from './wechat-article.js';
import type {
CreatorTemplateDefinition,
CreatorTemplateRegistry
@@ -28,6 +29,7 @@ export {
createStickmanVideoTemplate,
createSmartDubbingTemplate,
createXiaohongshuPostTemplate,
+ createWechatArticleTemplate,
createLegacyVideoDownloadTemplate,
createVideoDownloadTemplate,
createVideoTranslationTemplate
@@ -45,6 +47,7 @@ export function createDefaultCreatorTemplateRegistry(): CreatorTemplateRegistry
createSmartDubbingTemplate(),
createXiaohongshuPostTemplate(),
createVideoGenerationTemplate(),
+ createWechatArticleTemplate(),
createAutoClipTemplate(),
createStickmanVideoTemplate()
]);
diff --git a/apps/daemon/src/creator/templates/wechat-article.ts b/apps/daemon/src/creator/templates/wechat-article.ts
new file mode 100644
index 00000000..5e62fcf2
--- /dev/null
+++ b/apps/daemon/src/creator/templates/wechat-article.ts
@@ -0,0 +1,180 @@
+import {
+ wechatArticleImageStyleIds,
+ wechatArticleLayoutStyleIds,
+ wechatArticleSourceLimit
+} from '@opencreator/protocol';
+import {
+ getWritingTemplate,
+ normalizeWritingTemplateId
+} from '@opencreator/writing-templates';
+import { z } from 'zod';
+import type { CreatorTemplateDefinition } from './types.js';
+
+const record = z.record(z.string(), z.unknown()) as never;
+const sourceLink = z.object({
+ id: z.string().min(1).max(128),
+ url: z.string().url().max(2_048),
+ kind: z.enum(['video', 'webpage']),
+ label: z.string().max(256)
+}).strict();
+const topic = z.object({
+ id: z.string().min(1).max(128),
+ title: z.string().min(1).max(160),
+ angle: z.string().max(500),
+ summary: z.string().max(1_000)
+}).strict();
+
+export function createWechatArticleTemplate(): CreatorTemplateDefinition {
+ return {
+ id: 'wechat-article',
+ version: 1,
+ renderer: 'wechat-article',
+ inputSchema: z.object({
+ sourceLinks: z.array(sourceLink).max(wechatArticleSourceLimit).default([]),
+ sourceDocumentArtifactIds: z.array(z.string()).max(wechatArticleSourceLimit).default([]),
+ writingPrompt: z.string().max(6_000).default(''),
+ topicCount: z.number().int().min(3).max(10).default(5),
+ topics: z.array(topic).max(10).default([]),
+ selectedTopicId: z.string().max(128).default(''),
+ outline: z.string().max(30_000).default(''),
+ articleTitle: z.string().max(200).default(''),
+ articleMarkdown: z.string().max(120_000).default(''),
+ autoGenerateImages: z.boolean().default(true),
+ articleImageCount: z.number().int().min(1).max(10).default(5),
+ articleImageStyleId: z.enum(wechatArticleImageStyleIds).default('editorial'),
+ articleImagePrompt: z.string().max(2_000).default(''),
+ manualArticleImageArtifactIds: z.array(z.string()).max(50).default([]),
+ hiddenArticleImageArtifactIds: z.array(z.string()).max(100).default([]),
+ articleImagePlacementCustomized: z.boolean().default(false),
+ presetId: z.string().max(96).transform(normalizeWritingTemplateId).refine(
+ id => id === '' || getWritingTemplate(id) !== undefined,
+ 'Unknown writing template'
+ ).default(''),
+ layoutStyleId: z.enum(wechatArticleLayoutStyleIds).default('minimal'),
+ templatePrompt: z.string().max(8_000).default(''),
+ workspacePhase: z.enum(['compose', 'result']).default('compose'),
+ currentStep: z.union([
+ z.literal(0), z.literal(1), z.literal(2), z.literal(3), z.literal(4), z.literal(5)
+ ]).default(0),
+ furthestStep: z.union([
+ z.literal(0), z.literal(1), z.literal(2), z.literal(3), z.literal(4), z.literal(5)
+ ]).default(0),
+ currentStage: z.string().nullable().default(null)
+ }).passthrough().superRefine((state, context) => {
+ if (state.sourceLinks.length + state.sourceDocumentArtifactIds.length <= wechatArticleSourceLimit) return;
+ context.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `A WeChat article can use at most ${wechatArticleSourceLimit} inspiration sources`,
+ path: ['sourceLinks']
+ });
+ }) as never,
+ stages: [
+ {
+ id: 'sources',
+ executor: 'wechat-article',
+ completesJob: false,
+ resultVersionPolicy: 'none',
+ allowedJobStatuses: ['draft', 'running', 'completed', 'failed', 'needs_input'],
+ inputArtifacts: [{
+ kind: 'source_document',
+ selector: 'latest-completed',
+ optional: true
+ }],
+ outputArtifacts: [{ kind: 'article_sources', status: 'completed' }]
+ },
+ {
+ id: 'topics',
+ executor: 'wechat-article',
+ dependsOn: ['sources'],
+ completesJob: false,
+ resultVersionPolicy: 'none',
+ allowedJobStatuses: ['draft', 'running', 'completed', 'failed', 'needs_input'],
+ inputArtifacts: [
+ { kind: 'article_sources', selector: 'latest-completed', optional: true },
+ { kind: 'source_document', selector: 'latest-completed', optional: true }
+ ],
+ outputArtifacts: [
+ { kind: 'article_sources', status: 'completed' },
+ { kind: 'article_topics', status: 'completed' }
+ ]
+ },
+ {
+ id: 'outline',
+ executor: 'wechat-article',
+ dependsOn: ['topics'],
+ completesJob: false,
+ resultVersionPolicy: 'none',
+ allowedJobStatuses: ['draft', 'running', 'completed', 'failed', 'needs_input'],
+ inputArtifacts: [
+ { kind: 'article_sources', selector: 'latest-completed' },
+ { kind: 'article_topics', selector: 'latest-completed' }
+ ],
+ outputArtifacts: [{ kind: 'article_outline', status: 'completed' }]
+ },
+ {
+ id: 'article',
+ executor: 'wechat-article',
+ dependsOn: ['outline'],
+ completesJob: false,
+ resultVersionPolicy: 'none',
+ allowedJobStatuses: ['draft', 'running', 'completed', 'failed', 'needs_input'],
+ inputArtifacts: [
+ { kind: 'article_sources', selector: 'latest-completed' },
+ { kind: 'article_topics', selector: 'latest-completed' },
+ { kind: 'article_outline', selector: 'latest-completed' }
+ ],
+ outputArtifacts: [{ kind: 'article_markdown', status: 'completed' }]
+ },
+ {
+ id: 'images',
+ executor: 'wechat-article',
+ dependsOn: ['article'],
+ optional: true,
+ completesJob: false,
+ resultVersionPolicy: 'snapshot',
+ allowedJobStatuses: ['draft', 'running', 'completed', 'failed', 'needs_input'],
+ inputArtifacts: [
+ { kind: 'article_markdown', selector: 'latest-completed' }
+ ],
+ outputArtifacts: [{ kind: 'article_image', status: 'completed' }]
+ },
+ {
+ id: 'document',
+ executor: 'wechat-article',
+ dependsOn: ['article'],
+ resultVersionPolicy: 'snapshot',
+ allowedJobStatuses: ['draft', 'running', 'completed', 'failed', 'needs_input'],
+ inputArtifacts: [
+ { kind: 'article_markdown', selector: 'latest-completed' },
+ { kind: 'article_image', selector: 'latest-completed', optional: true }
+ ],
+ outputArtifacts: [{ kind: 'article_document', status: 'completed' }]
+ }
+ ],
+ actions: [
+ {
+ id: 'update-settings',
+ inputSchema: record,
+ allowedStages: ['sources', 'topics', 'outline', 'article', 'images', 'document']
+ },
+ {
+ id: 'run-stage',
+ inputSchema: record,
+ allowedStages: ['sources', 'topics', 'outline', 'article', 'images', 'document']
+ },
+ {
+ id: 'undo-action',
+ inputSchema: record,
+ allowedStages: ['sources', 'topics', 'outline', 'article', 'images', 'document']
+ }
+ ],
+ outputs: [{ kind: 'article_document', required: true }],
+ agentGuidance: [
+ '帮助用户完成微信公众号文章写作。',
+ '来源可以为空,也可以包含 sourceLinks 和 sourceDocumentArtifactIds;有来源时先运行 sources 读取网页、文档或视频字幕。',
+ '再运行 topics 生成多个选题,用户确认 selectedTopicId 后运行 outline,再确认大纲并运行 article;用户完成编辑和排版后运行 document 生成最终文档。',
+ '用户可编辑 topics、outline、articleMarkdown、presetId、layoutStyleId、templatePrompt、articleImageCount、articleImageStyleId 和 articleImagePrompt;文章编辑阶段可按需运行 images 自动生成配图。',
+ '最终交付必须是 article_document 文档产物,内容与用户确认的 articleMarkdown 一致。'
+ ].join(' ')
+ };
+}
diff --git a/apps/daemon/test/integration/creator-api.test.ts b/apps/daemon/test/integration/creator-api.test.ts
index eede5904..97e74910 100644
--- a/apps/daemon/test/integration/creator-api.test.ts
+++ b/apps/daemon/test/integration/creator-api.test.ts
@@ -27,6 +27,33 @@ afterEach(async () => {
});
describe('creator api', () => {
+ it('uploads a persistent inline image for a WeChat article', async () => {
+ await setupServer({});
+ const created = await request('POST', '/creator/jobs', {
+ projectId: 'project_article_image',
+ templateId: 'wechat-article'
+ });
+ const job = created.json().job;
+ const uploaded = await server!.inject({
+ method: 'POST',
+ url: `/creator/jobs/${job.id}/article-image?expectedRevision=${job.revision}&fileName=photo.png&mime=image%2Fpng&lastModified=123`,
+ headers: {
+ authorization: 'Bearer secret',
+ 'content-type': 'application/vnd.opencreator.creator-reference-image'
+ },
+ payload: png('article-inline-image')
+ });
+
+ expect(uploaded.statusCode).toBe(201);
+ expect(uploaded.json()).toMatchObject({
+ job: { state: { manualArticleImageArtifactIds: [expect.any(String)] } },
+ artifact: {
+ kind: 'article_image',
+ metadata: { originalFileName: 'photo.png', source: 'local-upload' }
+ }
+ });
+ });
+
it('deletes an inactive creator job', async () => {
await setupServer({});
const created = await request('POST', '/creator/jobs', {
@@ -661,6 +688,13 @@ async function request(
}) as unknown as TestResponse;
}
+function png(label: string): Buffer {
+ return Buffer.concat([
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ Buffer.from(label.padEnd(24, '.'))
+ ]);
+}
+
async function readSseFrames(url: string, expected: number): Promise<Array<{
id: string;
event: string;
diff --git a/apps/daemon/test/unit/creator-service.test.ts b/apps/daemon/test/unit/creator-service.test.ts
index 9425395d..58128dea 100644
--- a/apps/daemon/test/unit/creator-service.test.ts
+++ b/apps/daemon/test/unit/creator-service.test.ts
@@ -29,6 +29,118 @@ function setup() {
}
describe('creator service', () => {
+ it('registers and deduplicates manually uploaded article images', () => {
+ const { db, service } = setup();
+ const job = service.createJob({
+ projectId: 'project_1',
+ templateId: 'wechat-article',
+ state: {}
+ });
+ const first = service.registerArticleImage(job.id, {
+ expectedRevision: job.revision,
+ path: join(tempDir, 'article-image.png'),
+ fileName: '配图.png',
+ mimeType: 'image/png',
+ size: 256,
+ sha256: '1234567890abcdef',
+ lastModified: null,
+ format: 'png'
+ });
+ const second = service.registerArticleImage(job.id, {
+ expectedRevision: first.job.revision,
+ path: join(tempDir, 'duplicate.png'),
+ fileName: '配图.png',
+ mimeType: 'image/png',
+ size: 256,
+ sha256: '1234567890abcdef',
+ lastModified: null,
+ format: 'png'
+ });
+
+ expect(first.artifact).toMatchObject({
+ kind: 'article_image',
+ metadata: {
+ fileName: 'article-upload-1234567890ab.png',
+ originalFileName: '配图.png',
+ source: 'local-upload'
+ }
+ });
+ expect(first.job.state.manualArticleImageArtifactIds).toEqual([first.artifact.id]);
+ expect(second.deduplicated).toBe(true);
+ expect(second.job.artifacts.filter(artifact => artifact.kind === 'article_image')).toHaveLength(1);
+ db.close();
+ });
+
+ it('registers and deduplicates source documents for WeChat article jobs', () => {
+ const { db, service } = setup();
+ const job = service.createJob({
+ projectId: 'project_1',
+ templateId: 'wechat-article',
+ state: {}
+ });
+ const first = service.registerSourceDocument(job.id, {
+ expectedRevision: job.revision,
+ path: join(tempDir, 'source.pdf'),
+ fileName: 'source.pdf',
+ mimeType: 'application/pdf',
+ size: 128,
+ sha256: 'same-document',
+ lastModified: null
+ });
+ const second = service.registerSourceDocument(job.id, {
+ expectedRevision: first.job.revision,
+ path: join(tempDir, 'duplicate.pdf'),
+ fileName: 'source.pdf',
+ mimeType: 'application/pdf',
+ size: 128,
+ sha256: 'same-document',
+ lastModified: null
+ });
+
+ expect(first.deduplicated).toBe(false);
+ expect(second.deduplicated).toBe(true);
+ expect(second.job.state.sourceDocumentArtifactIds).toEqual([first.artifact.id]);
+ expect(second.job.artifacts.filter(artifact => artifact.kind === 'source_document')).toHaveLength(1);
+ db.close();
+ });
+
+ it('rejects a source document when links and documents already total 10', () => {
+ const { db, service } = setup();
+ const sourceLinks = Array.from({ length: 9 }, (_, index) => ({
+ id: `source-${index}`,
+ url: `https://example.com/${index}`,
+ kind: 'webpage' as const,
+ label: `Source ${index}`
+ }));
+ const job = service.createJob({
+ projectId: 'project_1',
+ templateId: 'wechat-article',
+ state: { sourceLinks }
+ });
+ const tenth = service.registerSourceDocument(job.id, {
+ expectedRevision: job.revision,
+ path: join(tempDir, 'tenth.pdf'),
+ fileName: 'tenth.pdf',
+ mimeType: 'application/pdf',
+ size: 128,
+ sha256: 'tenth-document',
+ lastModified: null
+ });
+
+ expect(() => service.registerSourceDocument(job.id, {
+ expectedRevision: tenth.job.revision,
+ path: join(tempDir, 'eleventh.pdf'),
+ fileName: 'eleventh.pdf',
+ mimeType: 'application/pdf',
+ size: 128,
+ sha256: 'eleventh-document',
+ lastModified: null
+ })).toThrowError(expect.objectContaining<Partial<CreatorServiceError>>({
+ code: 'creator_source_limit_exceeded'
+ }));
+ db.close();
+ });
+
it('deletes inactive jobs and rejects jobs with an active stage', () => {
const { db, service } = setup();
const inactive = service.createJob({
diff --git a/apps/daemon/test/unit/creator-wechat-article.test.ts b/apps/daemon/test/unit/creator-wechat-article.test.ts
new file mode 100644
index 00000000..12480ae4
--- /dev/null
+++ b/apps/daemon/test/unit/creator-wechat-article.test.ts
@@ -0,0 +1,542 @@
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createWechatArticleExecutor } from '../../src/creator/article/executor.js';
+import { createArticleSourceExtractor } from '../../src/creator/article/source-extractor.js';
+import { createDefaultCreatorTemplateRegistry } from '../../src/creator/templates/registry.js';
+
+let workRoot = '';
+
+afterEach(async () => {
+ if (workRoot) await rm(workRoot, { recursive: true, force: true });
+ workRoot = '';
+});
+
+describe('wechat article creator template', () => {
+ it('registers a shared-runtime template with source parsing and writing stages', () => {
+ const template = createDefaultCreatorTemplateRegistry().get('wechat-article', 1);
+ expect(template.renderer).toBe('wechat-article');
+ expect(template.stages.map(stage => ({ id: stage.id, executor: stage.executor }))).toEqual([
+ { id: 'sources', executor: 'wechat-article' },
+ { id: 'topics', executor: 'wechat-article' },
+ { id: 'outline', executor: 'wechat-article' },
+ { id: 'article', executor: 'wechat-article' },
+ { id: 'images', executor: 'wechat-article' },
+ { id: 'document', executor: 'wechat-article' }
+ ]);
+ expect(template.outputs).toEqual([{ kind: 'article_document', required: true }]);
+ expect(template.inputSchema.parse({ layoutStyleId: 'technical' })).toEqual(expect.objectContaining({ layoutStyleId: 'technical' }));
+ expect(template.inputSchema.parse({ layoutStyleId: 'podcast' })).toEqual(expect.objectContaining({ layoutStyleId: 'podcast' }));
+ expect(template.inputSchema.parse({ layoutStyleId: 'newsroom' })).toEqual(expect.objectContaining({ layoutStyleId: 'newsroom' }));
+ expect(template.inputSchema.parse({})).toEqual(expect.objectContaining({
+ autoGenerateImages: true,
+ articleImageCount: 5,
+ articleImageStyleId: 'editorial'
+ }));
+ expect(template.inputSchema.safeParse({ articleImageCount: 11 }).success).toBe(false);
+ expect(template.inputSchema.parse({}).presetId).toBe('');
+ expect(template.inputSchema.parse({ presetId: 'community.sun-style-writing' })).toEqual(expect.objectContaining({ presetId: 'community.sun-style-writing' }));
+ expect(template.inputSchema.parse({ presetId: 'community.khazix-writer' })).toEqual(expect.objectContaining({ presetId: 'community.khazix-writer' }));
+ expect(template.inputSchema.parse({ presetId: 'community.research-paper-writing' })).toEqual(expect.objectContaining({ presetId: 'community.research-paper-writing' }));
+ expect(template.inputSchema.parse({ presetId: 'community.restrained-narrative' })).toEqual(expect.objectContaining({ presetId: 'community.sun-style-writing' }));
+ expect(template.inputSchema.safeParse({ presetId: 'community.unknown-template' }).success).toBe(false);
+ expect(template.inputSchema.parse({ currentStep: 5, furthestStep: 5 })).toEqual(expect.objectContaining({ currentStep: 5, furthestStep: 5 }));
+ });
+
+ it('limits links and documents to 10 combined inspiration sources', () => {
+ const template = createDefaultCreatorTemplateRegistry().get('wechat-article', 1);
+ const sourceLinks = Array.from({ length: 6 }, (_, index) => ({
+ id: `source-${index}`,
+ url: `https://example.com/${index}`,
+ kind: 'webpage' as const,
+ label: `Source ${index}`
+ }));
+
+ expect(template.inputSchema.safeParse({
+ sourceLinks,
+ sourceDocumentArtifactIds: ['doc-1', 'doc-2', 'doc-3', 'doc-4']
+ }).success).toBe(true);
+ expect(template.inputSchema.safeParse({
+ sourceLinks,
+ sourceDocumentArtifactIds: ['doc-1', 'doc-2', 'doc-3', 'doc-4', 'doc-5']
+ }).success).toBe(false);
+ });
+
+ it('produces editable topics, outline, and downloadable document formats in sequence', async () => {
+ workRoot = await mkdtemp(join(tmpdir(), 'wechat-article-'));
+ const sourceExtractor = {
+ extract: vi.fn(async () => [{
+ id: 'source-1',
+ type: 'webpage' as const,
+ title: 'AI 产品落地',
+ origin: 'https://example.com/article',
+ content: '材料正文'
+ }])
+ };
+ const topics = [{ id: 'topic-1', title: 'AI 产品落地的三个误区', angle: '从失败案例切入', summary: '解释三个常见误区' }];
+ const model = {
+ generateTopics: vi.fn(async () => topics),
+ generateOutline: vi.fn(async () => '# AI 产品落地的三个误区\n\n## 误区一\n\n- 只看模型能力'),
+ generateArticle: vi.fn(async () => '# AI 产品落地的三个误区\n\n真正困难的不是接入模型。')
+ };
+ const executor = createWechatArticleExecutor({ sourceExtractor, model });
+ await Promise.all([
+ mkdir(join(workRoot, 'sources')),
+ mkdir(join(workRoot, 'topics')),
+ mkdir(join(workRoot, 'outline')),
+ mkdir(join(workRoot, 'article')),
+ mkdir(join(workRoot, 'document'))
+ ]);
+
+ const sourceState = {
+ sourceLinks: [{ id: 'source-1', url: 'https://example.com/article', kind: 'webpage', label: 'example.com' }],
+ sourceDocumentArtifactIds: [],
+ presetId: 'insight'
+ };
+ const sourcesResult = await executor.run(stageInput({
+ stageId: 'sources',
+ workdir: join(workRoot, 'sources'),
+ state: sourceState,
+ inputArtifacts: []
+ }));
+ const sourcesOutput = sourcesResult.outputs[0]!;
+ expect(sourcesOutput).toMatchObject({
+ kind: 'article_sources',
+ status: 'completed',
+ metadata: expect.objectContaining({ sourceCount: 1, sourceSignature: expect.any(String) })
+ });
+
+ const sourceArtifact = outputArtifact('sources-artifact', sourcesOutput);
+ const topicsResult = await executor.run(stageInput({
+ stageId: 'topics',
+ workdir: join(workRoot, 'topics'),
+ state: {
+ ...sourceState,
+ writingPrompt: '面向产品经理',
+ topicCount: 5
+ },
+ inputArtifacts: [sourceArtifact]
+ }));
+ const topicsOutput = topicsResult.outputs.find(output => output.kind === 'article_topics')!;
+ expect(topicsOutput.metadata?.topics).toEqual(topics);
+ expect(sourceExtractor.extract).toHaveBeenCalledTimes(1);
+ expect(model.generateTopics).toHaveBeenCalledWith(expect.objectContaining({
+ sources: [expect.objectContaining({ content: '材料正文' })],
+ templatePrompt: expect.stringContaining('深度洞察写作规则')
+ }));
+
+ const topicArtifact = outputArtifact('topics-artifact', topicsOutput);
+ const outlineResult = await executor.run(stageInput({
+ stageId: 'outline',
+ workdir: join(workRoot, 'outline'),
+ state: { topics, selectedTopicId: 'topic-1', writingPrompt: '面向产品经理', presetId: 'insight' },
+ inputArtifacts: [sourceArtifact, topicArtifact]
+ }));
+ const outlineOutput = outlineResult.outputs[0]!;
+ expect(outlineOutput.kind).toBe('article_outline');
+ expect(await readFile(outlineOutput.path!, 'utf8')).toContain('## 误区一');
+ expect(model.generateOutline).toHaveBeenCalledWith(expect.objectContaining({
+ templatePrompt: expect.stringContaining('深度洞察写作规则')
+ }));
+
+ const articleResult = await executor.run(stageInput({
+ stageId: 'article',
+ workdir: join(workRoot, 'article'),
+ state: {
+ topics,
+ selectedTopicId: 'topic-1',
+ outline: '# AI 产品落地的三个误区\n\n## 误区一',
+ writingPrompt: '面向产品经理',
+ presetId: 'insight',
+ templatePrompt: '先给结论',
+ layoutStyleId: 'business'
+ },
+ inputArtifacts: [sourceArtifact, topicArtifact, outputArtifact('outline-artifact', outlineOutput)]
+ }));
+ const articleOutput = articleResult.outputs[0]!;
+ expect(articleOutput).toMatchObject({ kind: 'article_markdown', status: 'completed' });
+ expect(articleOutput.metadata).toEqual(expect.objectContaining({
+ writingTemplateId: 'insight',
+ writingTemplateVersion: '1.0.0',
+ writingTemplateHash: expect.stringMatching(/^[a-f0-9]{64}$/)
+ }));
+ expect(await readFile(articleOutput.path!, 'utf8')).toContain('真正困难的不是接入模型');
+ expect(model.generateArticle).toHaveBeenCalledWith(expect.objectContaining({
+ outline: expect.stringContaining('误区一'),
+ templatePrompt: expect.stringMatching(/深度洞察写作规则[\s\S]*先给结论/),
+ layoutPrompt: expect.stringContaining('商业报告式 Markdown 结构')
+ }));
+
+ const editedMarkdown = '# 用户修改后的标题\n\n这是用户确认后的正文。';
+ const documentResult = await executor.run(stageInput({
+ stageId: 'document',
+ workdir: join(workRoot, 'document'),
+ state: {
+ articleMarkdown: editedMarkdown,
+ selectedTopicId: 'topic-1',
+ layoutStyleId: 'business'
+ },
+ inputArtifacts: [outputArtifact('article-artifact', articleOutput)]
+ }));
+ expect(documentResult.progress).toEqual(expect.objectContaining({ completed: 3, failed: 0, total: 3 }));
+ expect(documentResult.outputs).toHaveLength(3);
+ expect(documentResult.outputs.map(output => output.metadata?.documentFormat)).toEqual(['markdown', 'html', 'pdf']);
+ for (const output of documentResult.outputs) {
+ expect(output).toMatchObject({
+ kind: 'article_document',
+ status: 'completed',
+ metadata: expect.objectContaining({
+ title: '用户修改后的标题',
+ layoutStyleId: 'business',
+ bytes: expect.any(Number)
+ })
+ });
+ }
+ const [markdownDocument, htmlDocument, pdfDocument] = documentResult.outputs;
+ expect(markdownDocument?.metadata?.fileName).toBe('用户修改后的标题.md');
+ expect(await readFile(markdownDocument!.path!, 'utf8')).toBe(`${editedMarkdown}\n`);
+ expect(htmlDocument?.metadata?.fileName).toBe('用户修改后的标题.html');
+ expect(await readFile(htmlDocument!.path!, 'utf8')).toContain('<body><article data-layout="business">');
+ expect(pdfDocument?.metadata?.fileName).toBe('用户修改后的标题.pdf');
+ expect((await readFile(pdfDocument!.path!)).subarray(0, 5).toString()).toBe('%PDF-');
+ });
+
+ it('plans and generates distinct article image artifacts from the edited article', async () => {
+ workRoot = await mkdtemp(join(tmpdir(), 'wechat-article-images-'));
+ const imagesWorkdir = join(workRoot, 'images');
+ await mkdir(imagesWorkdir);
+ const articlePath = join(workRoot, 'article.md');
+ await writeFile(articlePath, '# AI 产品落地\n\n## 真实问题\n\n正文内容。', 'utf8');
+ const generateImagePlan = vi.fn(async () => [
+ { id: 'article-image-1', caption: '团队讨论落地问题', placementHeading: '真实问题', prompt: 'A product team reviewing a deployment map' },
+ { id: 'article-image-2', caption: '复杂系统关系', placementHeading: '解决路径', prompt: 'An editorial systems diagram without text' }
+ ]);
+ const generateImage = vi.fn(async () => ({
+ content: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wn6zkAAAAAASUVORK5CYII=', 'base64'),
+ mime: 'image/png' as const,
+ provider: 'openai' as const,
+ model: 'gpt-image-1'
+ }));
+ const executor = createWechatArticleExecutor({
+ sourceExtractor: { extract: vi.fn(async () => []) },
+ model: {
+ generateTopics: vi.fn(),
+ generateOutline: vi.fn(),
+ generateArticle: vi.fn(),
+ generateImagePlan
+ },
+ imageGenerator: { generate: generateImage }
+ });
+
+ const result = await executor.run(stageInput({
+ stageId: 'images',
+ workdir: imagesWorkdir,
+ state: {
+ articleMarkdown: '# AI 产品落地\n\n## 真实问题\n\n![旧配图](./article-image-01.png)\n\n正文内容。',
+ articleImageCount: 2,
+ articleImageStyleId: 'three-dimensional',
+ articleImagePrompt: '使用克制的蓝绿色'
+ },
+ inputArtifacts: [outputArtifact('article-1', {
+ kind: 'article_markdown',
+ status: 'completed',
+ path: articlePath
+ })]
+ }));
+
+ expect(generateImagePlan).toHaveBeenCalledWith(expect.objectContaining({
+ articleMarkdown: '# AI 产品落地\n\n## 真实问题\n\n正文内容。',
+ count: 2,
+ stylePrompt: expect.stringContaining('isometric 3D illustration'),
+ customPrompt: '使用克制的蓝绿色'
+ }));
+ expect(generateImage).toHaveBeenCalledTimes(2);
+ const generatedImageRequests = generateImage.mock.calls as unknown as Array<[{ prompt: string }]>;
+ const firstImagePrompt = generatedImageRequests[0]?.[0].prompt ?? '';
+ expect(firstImagePrompt).toContain('Placement heading: 真实问题');
+ expect(firstImagePrompt).toContain('Relevant article content:\n## 真实问题\n\n正文内容。');
+ expect(firstImagePrompt).toContain('A product team reviewing a deployment map');
+ expect(result.outputs).toHaveLength(2);
+ expect(result.outputs[0]).toMatchObject({
+ kind: 'article_image',
+ status: 'completed',
+ sourceArtifactIds: ['article-1'],
+ metadata: expect.objectContaining({
+ imageIndex: 1,
+ imageStyleId: 'three-dimensional',
+ caption: '团队讨论落地问题',
+ placementHeading: '真实问题',
+ articleContext: '## 真实问题\n\n正文内容。',
+ provider: 'openai',
+ model: 'gpt-image-1'
+ })
+ });
+ });
+
+ it('re-extracts sources before topics when the cached source signature is stale', async () => {
+ workRoot = await mkdtemp(join(tmpdir(), 'wechat-article-stale-source-'));
+ const cachedPath = join(workRoot, 'cached-sources.json');
+ const topicsWorkdir = join(workRoot, 'topics');
+ await Promise.all([
+ writeFile(cachedPath, '[]\n', 'utf8'),
+ mkdir(topicsWorkdir)
+ ]);
+ const sourceExtractor = {
+ extract: vi.fn(async () => [{
+ id: 'source-new',
+ type: 'webpage' as const,
+ title: '新来源',
+ origin: 'https://example.com/new',
+ content: '新来源正文'
+ }])
+ };
+ const model = {
+ generateTopics: vi.fn(async () => [{ id: 'topic-1', title: '新选题', angle: '', summary: '' }]),
+ generateOutline: vi.fn(),
+ generateArticle: vi.fn()
+ };
+ const executor = createWechatArticleExecutor({ sourceExtractor, model });
+ const result = await executor.run(stageInput({
+ stageId: 'topics',
+ workdir: topicsWorkdir,
+ state: {
+ sourceLinks: [{ id: 'source-new', url: 'https://example.com/new', kind: 'webpage', label: 'example.com' }],
+ sourceDocumentArtifactIds: [],
+ writingPrompt: '根据新资料写作'
+ },
+ inputArtifacts: [{
+ id: 'cached-source-artifact',
+ kind: 'article_sources',
+ status: 'completed',
+ path: cachedPath,
+ metadata: { sourceSignature: 'stale' }
+ }]
+ }));
+
+ expect(sourceExtractor.extract).toHaveBeenCalledTimes(1);
+ expect(result.outputs.map(output => output.kind)).toEqual(['article_sources', 'article_topics']);
+ expect(model.generateTopics).toHaveBeenCalledWith(expect.objectContaining({
+ sources: [expect.objectContaining({ content: '新来源正文' })],
+ templatePrompt: ''
+ }));
+ });
+
+ it('loads the pinned community skill rules for topic generation', async () => {
+ workRoot = await mkdtemp(join(tmpdir(), 'wechat-article-community-template-'));
+ const topicsWorkdir = join(workRoot, 'topics');
+ await mkdir(topicsWorkdir);
+ const model = {
+ generateTopics: vi.fn(async (_request: { templatePrompt: string }) => [{ id: 'topic-1', title: '一个具体故事', angle: '', summary: '' }]),
+ generateOutline: vi.fn(),
+ generateArticle: vi.fn()
+ };
+ const executor = createWechatArticleExecutor({
+ sourceExtractor: { extract: vi.fn(async () => []) },
+ model
+ });
+
+ const result = await executor.run(stageInput({
+ stageId: 'topics',
+ workdir: topicsWorkdir,
+ state: {
+ sourceLinks: [],
+ sourceDocumentArtifactIds: [],
+ writingPrompt: '写一篇人物经历',
+ presetId: 'community.sun-style-writing'
+ },
+ inputArtifacts: []
+ }));
+
+ expect(model.generateTopics).toHaveBeenCalledWith(expect.objectContaining({
+ templatePrompt: expect.stringContaining('选题规则')
+ }));
+ expect(model.generateTopics.mock.calls[0]?.[0].templatePrompt).not.toContain('成稿检查');
+ expect(result.outputs.find(output => output.kind === 'article_topics')?.metadata).toEqual(expect.objectContaining({
+ writingTemplateId: 'community.sun-style-writing',
+ writingTemplateRevision: 'fe970dc15113ea0c3807f19f1d3118f63f9d9079'
+ }));
+ });
+
+ it('extracts selected local text documents into bounded source material', async () => {
+ workRoot = await mkdtemp(join(tmpdir(), 'wechat-article-source-'));
+ const path = join(workRoot, 'source.md');
+ await writeFile(path, '# 原始标题\n\n这是用于写作的正文。', 'utf8');
+ const extractor = createArticleSourceExtractor({
+ configStore: { read: vi.fn(async () => ({ proxy: '' })) } as never
+ });
+ const sources = await extractor.extract({
+ links: [],
+ documents: [{
+ id: 'document-1',
+ kind: 'source_document',
+ status: 'completed',
+ path,
+ metadata: { fileName: 'source.md' }
+ } as never],
+ workdir: workRoot,
+ signal: new AbortController().signal,
+ reportProgress: vi.fn()
+ });
+
+ expect(sources).toEqual([expect.objectContaining({
+ id: 'document-1',
+ type: 'document',
+ title: 'source.md',
+ content: expect.stringContaining('用于写作的正文')
+ })]);
+ });
+
+ it('extracts the main body from a WeChat-style webpage', async () => {
+ const extractor = createArticleSourceExtractor({
+ configStore: { read: vi.fn(async () => ({ proxy: '' })) } as never,
+ fetchService: vi.fn(async () => new Response([
+ '<html><head><title>页面标题</title></head><body>',
+ '<nav>无关导航</nav>',
+ '<h1>公众号文章标题</h1>',
+ '<div id="js_content"><p>第一段正文。</p><p>第二段正文。</p></div>',
+ '<footer>无关页脚</footer>',
+ '</body></html>'
+ ].join(''), { status: 200 })) as never
+ });
+
+ const sources = await extractor.extract({
+ links: [{ id: 'web-1', url: 'https://mp.weixin.qq.com/s/example', kind: 'webpage', label: '微信公众平台' }],
+ documents: [],
+ workdir: '/tmp',
+ signal: new AbortController().signal,
+ reportProgress: vi.fn()
+ });
+
+ expect(sources[0]).toEqual(expect.objectContaining({
+ title: '公众号文章标题',
+ content: '第一段正文。第二段正文。'
+ }));
+ expect(sources[0]?.content).not.toContain('无关导航');
+ });
+
+ it('prefers human subtitles over automatic captions', async () => {
+ const fetchService = vi.fn(async () => new Response([
+ 'WEBVTT',
+ '',
+ '00:00:00.000 --> 00:00:02.000',
+ '人工字幕第一句。',
+ '',
+ '00:00:02.000 --> 00:00:04.000',
+ '人工字幕第二句。'
+ ].join('\n'), { status: 200 }));
+ const extractor = createArticleSourceExtractor({
+ configStore: { read: vi.fn(async () => ({ proxy: '' })) } as never,
+ getYtDlpRuntime: () => ({ version: 'test', executable: '/tmp/yt-dlp', prefixArgs: [], env: {} }),
+ runYtDlp: vi.fn(async () => JSON.stringify({
+ title: '字幕测试视频',
+ subtitles: {
+ zh: [{ ext: 'vtt', url: 'https://example.com/human.vtt' }]
+ },
+ automatic_captions: {
+ 'zh-CN': [{ ext: 'json3', url: 'https://example.com/captions.json3' }]
+ }
+ })),
+ fetchService: fetchService as never
+ });
+
+ const sources = await extractor.extract({
+ links: [{ id: 'video-1', url: 'https://www.youtube.com/watch?v=test', kind: 'video', label: 'YouTube' }],
+ documents: [],
+ workdir: '/tmp',
+ signal: new AbortController().signal,
+ reportProgress: vi.fn()
+ });
+
+ expect(sources).toEqual([expect.objectContaining({
+ title: '字幕测试视频',
+ content: '人工字幕第一句。\n人工字幕第二句。',
+ transcriptType: 'human',
+ transcriptLanguage: 'zh'
+ })]);
+ expect(fetchService).toHaveBeenCalledWith(expect.objectContaining({
+ endpoint: new URL('https://example.com/human.vtt')
+ }));
+ });
+
+ it('uses automatic captions when no human subtitles are available', async () => {
+ const extractor = createArticleSourceExtractor({
+ configStore: { read: vi.fn(async () => ({ proxy: '' })) } as never,
+ getYtDlpRuntime: () => ({ version: 'test', executable: '/tmp/yt-dlp', prefixArgs: [], env: {} }),
+ runYtDlp: vi.fn(async () => JSON.stringify({
+ title: '自动字幕测试',
+ automatic_captions: {
+ 'zh-CN': [{ ext: 'json3', url: 'https://example.com/automatic.json3' }]
+ }
+ })),
+ fetchService: vi.fn(async () => new Response(JSON.stringify({
+ events: [{ segs: [{ utf8: '自动字幕内容。' }] }]
+ }), { status: 200 })) as never
+ });
+
+ const sources = await extractor.extract({
+ links: [{ id: 'video-1', url: 'https://www.youtube.com/watch?v=test', kind: 'video', label: 'YouTube' }],
+ documents: [],
+ workdir: '/tmp',
+ signal: new AbortController().signal,
+ reportProgress: vi.fn()
+ });
+
+ expect(sources[0]).toEqual(expect.objectContaining({
+ content: '自动字幕内容。',
+ transcriptType: 'automatic',
+ transcriptLanguage: 'zh-CN'
+ }));
+ });
+
+ it('rejects a video source when the platform exposes no subtitles', async () => {
+ const extractor = createArticleSourceExtractor({
+ configStore: { read: vi.fn(async () => ({ proxy: '' })) } as never,
+ getYtDlpRuntime: () => ({ version: 'test', executable: '/tmp/yt-dlp', prefixArgs: [], env: {} }),
+ runYtDlp: vi.fn(async () => JSON.stringify({ title: '无字幕视频' }))
+ });
+
+ await expect(extractor.extract({
+ links: [{ id: 'video-1', url: 'https://www.bilibili.com/video/BV1test', kind: 'video', label: 'Bilibili' }],
+ documents: [],
+ workdir: '/tmp',
+ signal: new AbortController().signal,
+ reportProgress: vi.fn()
+ })).rejects.toMatchObject({ code: 'creator_source_transcript_missing' });
+ });
+});
+
+function stageInput(input: {
+ stageId: string;
+ workdir: string;
+ state: Record<string, unknown>;
+ inputArtifacts: unknown[];
+}) {
+ return {
+ stageRun: { stageId: input.stageId },
+ job: { state: input.state, artifacts: input.inputArtifacts },
+ inputArtifacts: input.inputArtifacts,
+ workdir: input.workdir,
+ signal: new AbortController().signal,
+ reportProgress: vi.fn()
+ } as never;
+}
+
+function outputArtifact(id: string, output: {
+ kind: string;
+ status: string;
+ path: string | null;
+ sourceArtifactIds?: string[];
+ metadata?: Record<string, unknown>;
+}) {
+ return {
+ id,
+ jobId: 'job-1',
+ kind: output.kind,
+ status: output.status,
+ path: output.path,
+ sourceArtifactIds: output.sourceArtifactIds ?? [],
+ metadata: output.metadata ?? {},
+ createdAt: '2026-09-07T00:00:00.000Z'
+ } as never;
+}
diff --git a/apps/web/package.json b/apps/web/package.json
index 04cd38af..f564585a 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -4,18 +4,19 @@
"private": true,
"type": "module",
"scripts": {
- "predev": "pnpm --filter @opencreator/desktop prepare:creator-runtime && pnpm --filter @opencreator/desktop prepare:codex-runtime && pnpm --filter @opencreator/protocol build && pnpm --filter @opencreator/skill-market build",
+ "predev": "pnpm --filter @opencreator/desktop prepare:creator-runtime && pnpm --filter @opencreator/desktop prepare:codex-runtime && pnpm --filter @opencreator/protocol build && pnpm --filter @opencreator/skill-market build && pnpm --filter @opencreator/writing-templates build",
"dev": "vite --host 127.0.0.1",
- "prebuild": "pnpm --filter @opencreator/protocol build && pnpm --filter @opencreator/skill-market build",
+ "prebuild": "pnpm --filter @opencreator/protocol build && pnpm --filter @opencreator/skill-market build && pnpm --filter @opencreator/writing-templates build",
"build": "tsc -p tsconfig.json && vite build",
- "pretypecheck": "pnpm --filter @opencreator/protocol build && pnpm --filter @opencreator/skill-market build",
+ "pretypecheck": "pnpm --filter @opencreator/protocol build && pnpm --filter @opencreator/skill-market build && pnpm --filter @opencreator/writing-templates build",
"typecheck": "tsc -p tsconfig.json --noEmit",
- "pretest": "pnpm --filter @opencreator/protocol build && pnpm --filter @opencreator/skill-market build",
+ "pretest": "pnpm --filter @opencreator/protocol build && pnpm --filter @opencreator/skill-market build && pnpm --filter @opencreator/writing-templates build",
"test": "vitest run --passWithNoTests"
},
"dependencies": {
"@opencreator/protocol": "workspace:*",
"@opencreator/skill-market": "workspace:*",
+ "@opencreator/writing-templates": "workspace:*",
"@codemirror/commands": "^6.10.4",
"@codemirror/lang-css": "^6.3.1",
"@codemirror/lang-html": "^6.4.11",
diff --git a/apps/web/public/dashboard/wechat-article/image-styles/documentary-v2.webp b/apps/web/public/dashboard/wechat-article/image-styles/documentary-v2.webp
new file mode 100644
index 00000000..40b25994
Binary files /dev/null and b/apps/web/public/dashboard/wechat-article/image-styles/documentary-v2.webp differ
diff --git a/apps/web/public/dashboard/wechat-article/image-styles/documentary.webp b/apps/web/public/dashboard/wechat-article/image-styles/documentary.webp
new file mode 100644
index 00000000..c9d526c6
Binary files /dev/null and b/apps/web/public/dashboard/wechat-article/image-styles/documentary.webp differ
diff --git a/apps/web/public/dashboard/wechat-article/image-styles/editorial-v2.webp b/apps/web/public/dashboard/wechat-article/image-styles/editorial-v2.webp
new file mode 100644
index 00000000..93d5e661
Binary files /dev/null and b/apps/web/public/dashboard/wechat-article/image-styles/editorial-v2.webp differ
diff --git a/apps/web/public/dashboard/wechat-article/image-styles/editorial.webp b/apps/web/public/dashboard/wechat-article/image-styles/editorial.webp
new file mode 100644
index 00000000..b41827e6
Binary files /dev/null and b/apps/web/public/dashboard/wechat-article/image-styles/editorial.webp differ
diff --git a/apps/web/public/dashboard/wechat-article/image-styles/illustration.webp b/apps/web/public/dashboard/wechat-article/image-styles/illustration.webp
new file mode 100644
index 00000000..1a40830e
Binary files /dev/null and b/apps/web/public/dashboard/wechat-article/image-styles/illustration.webp differ
diff --git a/apps/web/public/dashboard/wechat-article/image-styles/infographic.webp b/apps/web/public/dashboard/wechat-article/image-styles/infographic.webp
new file mode 100644
index 00000000..da549b2d
Binary files /dev/null and b/apps/web/public/dashboard/wechat-article/image-styles/infographic.webp differ
diff --git a/apps/web/public/dashboard/wechat-article/image-styles/minimal-v2.webp b/apps/web/public/dashboard/wechat-article/image-styles/minimal-v2.webp
new file mode 100644
index 00000000..4c20e72f
Binary files /dev/null and b/apps/web/public/dashboard/wechat-article/image-styles/minimal-v2.webp differ
diff --git a/apps/web/public/dashboard/wechat-article/image-styles/minimal.webp b/apps/web/public/dashboard/wechat-article/image-styles/minimal.webp
new file mode 100644
index 00000000..b257f92f
Binary files /dev/null and b/apps/web/public/dashboard/wechat-article/image-styles/minimal.webp differ
diff --git a/apps/web/public/dashboard/wechat-article/image-styles/three-dimensional-v2.webp b/apps/web/public/dashboard/wechat-article/image-styles/three-dimensional-v2.webp
new file mode 100644
index 00000000..a2a44e7b
Binary files /dev/null and b/apps/web/public/dashboard/wechat-article/image-styles/three-dimensional-v2.webp differ
diff --git a/apps/web/public/dashboard/wechat-article/image-styles/three-dimensional.webp b/apps/web/public/dashboard/wechat-article/image-styles/three-dimensional.webp
new file mode 100644
index 00000000..cc15c43d
Binary files /dev/null and b/apps/web/public/dashboard/wechat-article/image-styles/three-dimensional.webp differ
diff --git a/apps/web/src/components/markdown/MarkdownRenderer.test.tsx b/apps/web/src/components/markdown/MarkdownRenderer.test.tsx
index c1d443ca..0556526a 100644
--- a/apps/web/src/components/markdown/MarkdownRenderer.test.tsx
+++ b/apps/web/src/components/markdown/MarkdownRenderer.test.tsx
@@ -170,6 +170,22 @@ describe('MarkdownRenderer', () => {
expect(document.querySelector('img')).not.toBeInTheDocument();
});
+ it('renders only image references explicitly resolved by the caller', () => {
+ const { container } = render(
+ <MarkdownRenderer
+ variant="document"
+ text={'![文章配图](./article-image-01.png)\n\n![外部图片](https://example.com/a.png)'}
+ resolveImageSrc={href => href === './article-image-01.png' ? 'blob:article-image-01' : undefined}
+ />
+ );
+
+ expect(screen.getByRole('img', { name: '文章配图' })).toHaveAttribute('src', 'blob:article-image-01');
+ expect(screen.getByRole('img', { name: '文章配图' }).closest('p')).toHaveClass('md-p-image-only');
+ expect(screen.getByText(/外部图片/)).toBeInTheDocument();
+ expect(screen.queryByRole('img', { name: '外部图片' })).not.toBeInTheDocument();
+ expect(container.querySelectorAll('.md-p-image-only')).toHaveLength(1);
+ });
+
it('keeps user variant conservative', () => {
render(<MarkdownRenderer variant="user" text={'# 不是标题\n1. 不是列表\n*不是斜体*\n`是代码`'} />);
diff --git a/apps/web/src/components/markdown/MarkdownRenderer.tsx b/apps/web/src/components/markdown/MarkdownRenderer.tsx
index 017e4260..7403e63f 100644
--- a/apps/web/src/components/markdown/MarkdownRenderer.tsx
+++ b/apps/web/src/components/markdown/MarkdownRenderer.tsx
@@ -11,6 +11,7 @@ export type MarkdownRendererProps = {
className?: string;
onLinkClick?: MarkdownLinkClickHandler;
linkifyWorkspaceFiles?: boolean;
+ resolveImageSrc?(href: string): string | undefined;
};
const PRIVATE_CITATION_MARKER = /[ \t]*\uE200(?:cite|filecite|navlist)\uE202[^\uE201]*\uE201/gu;
@@ -79,12 +80,16 @@ function renderBlock(block: MarkdownBlock, key: number, options: MarkdownRendere
}
switch (block.kind) {
- case 'paragraph':
+ case 'paragraph': {
+ const imageOnlyMatch = /^!\[[^\]\n]*\]\(([^)\s]+)\)$/u.exec(block.text.trim());
+ const imageOnly = imageOnlyMatch !== null
+ && options.resolveImageSrc?.(imageOnlyMatch[1]!) !== undefined;
return (
- <p key={key} className="md-p">
+ <p key={key} className={`md-p${imageOnly ? ' md-p-image-only' : ''}`}>
{renderInlineMarkdown(block.text, options)}
</p>
);
+ }
case 'heading': {
const Tag = `h${block.level}` as 'h1' | 'h2' | 'h3' | 'h4';
return (
diff --git a/apps/web/src/components/markdown/clipboard.test.ts b/apps/web/src/components/markdown/clipboard.test.ts
new file mode 100644
index 00000000..d81c1d87
--- /dev/null
+++ b/apps/web/src/components/markdown/clipboard.test.ts
@@ -0,0 +1,65 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { copyRichContent } from './clipboard.js';
+
+type ClipboardItemValue = Blob | Promise<Blob>;
+
+class TestClipboardItem {
+ constructor(readonly data: Record<string, ClipboardItemValue>) {}
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe('copyRichContent', () => {
+ it('copies styled HTML and plain text in one clipboard item', async () => {
+ const write = vi.fn(async () => undefined);
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: { write, writeText: vi.fn() }
+ });
+ vi.stubGlobal('ClipboardItem', TestClipboardItem);
+ const root = document.createElement('article');
+ root.innerHTML = '<h1 style="color: rgb(40, 91, 120)">标题</h1><p style="background-color: transparent; border: 0 none rgb(0, 0, 0)">正文</p><blockquote style="background-color: rgb(244, 248, 246); border-left: 4px solid rgb(47, 125, 104)">引用</blockquote><img src="data:image/png;base64,AA==" alt="配图">';
+ document.body.append(root);
+
+ await expect(copyRichContent(root, '# 标题\n\n正文')).resolves.toBe('rich');
+ expect(write).toHaveBeenCalledTimes(1);
+ const writeCalls = write.mock.calls as unknown as Array<[TestClipboardItem[]]>;
+ const item = writeCalls[0]![0][0]!;
+ expect(Object.keys(item.data)).toEqual(['text/html', 'text/plain']);
+ const html = await readBlobText(await item.data['text/html']!);
+ expect(html).toContain('OpenCreator rich article');
+ expect(html).toContain('color: rgb(40, 91, 120)');
+ expect(html).toContain('background-color: rgb(244, 248, 246)');
+ expect(html).toContain('border-left: 4px solid rgb(47, 125, 104)');
+ expect(html).not.toContain('background-color: transparent');
+ expect(html).not.toContain('background-color: rgba(0, 0, 0, 0)');
+ expect(html).toContain('data:image/png;base64,AA==');
+ expect(html).not.toContain('alt="配图"');
+ expect(html).toContain('width: 100%');
+ });
+
+ it('falls back to Markdown when rich clipboard access is unavailable', async () => {
+ const writeText = vi.fn(async () => undefined);
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: { writeText }
+ });
+ const root = document.createElement('article');
+ root.textContent = '标题正文';
+
+ await expect(copyRichContent(root, '# 标题\n\n正文')).resolves.toBe('plain');
+ expect(writeText).toHaveBeenCalledWith('# 标题\n\n正文');
+ });
+});
+
+function readBlobText(blob: Blob): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.addEventListener('load', () => resolve(String(reader.result)));
+ reader.addEventListener('error', () => reject(reader.error));
+ reader.readAsText(blob);
+ });
+}
diff --git a/apps/web/src/components/markdown/clipboard.ts b/apps/web/src/components/markdown/clipboard.ts
index cb228809..fefa6949 100644
--- a/apps/web/src/components/markdown/clipboard.ts
+++ b/apps/web/src/components/markdown/clipboard.ts
@@ -7,3 +7,162 @@ export async function copyToClipboard(text: string): Promise<boolean> {
return false;
}
}
+
+export type RichClipboardCopyResult = 'rich' | 'plain' | 'failed';
+
+const richTextStyleProperties = [
+ 'border-radius',
+ 'box-sizing',
+ 'color',
+ 'display',
+ 'font-family',
+ 'font-size',
+ 'font-style',
+ 'font-weight',
+ 'letter-spacing',
+ 'line-height',
+ 'list-style-position',
+ 'list-style-type',
+ 'margin-bottom',
+ 'margin-left',
+ 'margin-right',
+ 'margin-top',
+ 'overflow-wrap',
+ 'padding-bottom',
+ 'padding-left',
+ 'padding-right',
+ 'padding-top',
+ 'text-align',
+ 'text-transform',
+ 'vertical-align',
+ 'white-space',
+ 'word-break'
+] as const;
+
+export async function copyRichContent(
+ root: HTMLElement,
+ fallbackText: string
+): Promise<RichClipboardCopyResult> {
+ const plainText = root.innerText?.trim() || root.textContent?.trim() || fallbackText;
+ try {
+ if (
+ typeof navigator !== 'undefined'
+ && navigator.clipboard?.write
+ && typeof ClipboardItem !== 'undefined'
+ ) {
+ const html = serializeRichContent(root);
+ const item = new ClipboardItem({
+ 'text/html': html.then(value => new Blob([value], { type: 'text/html' })),
+ 'text/plain': new Blob([plainText], { type: 'text/plain' })
+ });
+ await navigator.clipboard.write([item]);
+ return 'rich';
+ }
+ } catch {
+ // Fall through to the plain-text clipboard for browsers that reject rich clipboard data.
+ }
+ return await copyToClipboard(fallbackText) ? 'plain' : 'failed';
+}
+
+async function serializeRichContent(root: HTMLElement): Promise<string> {
+ const clone = root.cloneNode(true) as HTMLElement;
+ const sourceElements = [root, ...root.querySelectorAll<HTMLElement>('*')];
+ const clonedElements = [clone, ...clone.querySelectorAll<HTMLElement>('*')];
+
+ sourceElements.forEach((source, index) => {
+ const target = clonedElements[index];
+ if (target === undefined) return;
+ const computed = window.getComputedStyle(source);
+ target.removeAttribute('style');
+ richTextStyleProperties.forEach(property => {
+ const value = computed.getPropertyValue(property);
+ if (value) target.style.setProperty(property, value);
+ });
+ copyVisibleBackground(computed, target);
+ copyVisibleBorders(computed, target);
+ copyVisibleTextDecoration(computed, target);
+ });
+
+ await inlineCopiedImages(sourceElements, clonedElements);
+ clone.querySelectorAll('button, script, style').forEach(element => element.remove());
+ clone.style.setProperty('width', '100%');
+ clone.style.setProperty('max-width', '100%');
+ clone.style.setProperty('height', 'auto');
+ clone.style.setProperty('margin', '0');
+ clone.style.setProperty('box-shadow', 'none');
+
+ clone.querySelectorAll<HTMLImageElement>('img').forEach(image => {
+ image.removeAttribute('srcset');
+ image.removeAttribute('alt');
+ image.removeAttribute('title');
+ image.style.setProperty('display', 'block');
+ image.style.setProperty('width', '100%');
+ image.style.setProperty('max-width', '100%');
+ image.style.setProperty('height', 'auto');
+ image.style.setProperty('object-fit', 'contain');
+ });
+
+ return `<!-- OpenCreator rich article -->${clone.outerHTML}`;
+}
+
+function copyVisibleBackground(computed: CSSStyleDeclaration, target: HTMLElement): void {
+ const color = computed.getPropertyValue('background-color');
+ if (!isTransparentColor(color)) target.style.setProperty('background-color', color);
+}
+
+function copyVisibleBorders(computed: CSSStyleDeclaration, target: HTMLElement): void {
+ (['top', 'right', 'bottom', 'left'] as const).forEach(side => {
+ const style = computed.getPropertyValue(`border-${side}-style`);
+ const width = computed.getPropertyValue(`border-${side}-width`);
+ const color = computed.getPropertyValue(`border-${side}-color`);
+ if (style === 'none' || style === 'hidden' || parseFloat(width) <= 0 || isTransparentColor(color)) return;
+ target.style.setProperty(`border-${side}`, `${width} ${style} ${color}`);
+ });
+}
+
+function copyVisibleTextDecoration(computed: CSSStyleDeclaration, target: HTMLElement): void {
+ const line = computed.getPropertyValue('text-decoration-line');
+ if (!line || line === 'none') return;
+ target.style.setProperty('text-decoration-line', line);
+ target.style.setProperty('text-decoration-color', computed.getPropertyValue('text-decoration-color'));
+ target.style.setProperty('text-decoration-style', computed.getPropertyValue('text-decoration-style'));
+ target.style.setProperty('text-decoration-thickness', computed.getPropertyValue('text-decoration-thickness'));
+ target.style.setProperty('text-underline-offset', computed.getPropertyValue('text-underline-offset'));
+}
+
+function isTransparentColor(value: string): boolean {
+ const normalized = value.trim().toLocaleLowerCase().replace(/\s+/g, '');
+ return normalized === ''
+ || normalized === 'transparent'
+ || normalized === 'rgba(0,0,0,0)'
+ || normalized.endsWith(',0)');
+}
+
+async function inlineCopiedImages(
+ sourceElements: HTMLElement[],
+ clonedElements: HTMLElement[]
+): Promise<void> {
+ await Promise.all(sourceElements.map(async (source, index) => {
+ if (!(source instanceof HTMLImageElement)) return;
+ const target = clonedElements[index];
+ if (!(target instanceof HTMLImageElement)) return;
+ const src = source.currentSrc || source.src;
+ if (!src || src.startsWith('data:')) return;
+ try {
+ const response = await fetch(src);
+ if (!response.ok) return;
+ target.src = await blobToDataUrl(await response.blob());
+ } catch {
+ // Keep the original URL when an external image cannot be read because of CORS.
+ }
+ }));
+}
+
+function blobToDataUrl(blob: Blob): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.addEventListener('load', () => resolve(String(reader.result)));
+ reader.addEventListener('error', () => reject(reader.error ?? new Error('Unable to read image')));
+ reader.readAsDataURL(blob);
+ });
+}
diff --git a/apps/web/src/components/markdown/markdown-inline.tsx b/apps/web/src/components/markdown/markdown-inline.tsx
index a7564ea6..348913f1 100644
--- a/apps/web/src/components/markdown/markdown-inline.tsx
+++ b/apps/web/src/components/markdown/markdown-inline.tsx
@@ -232,6 +232,7 @@ export function renderInlineMarkdown(
variant: MarkdownVariant;
onLinkClick?: MarkdownLinkClickHandler;
linkifyWorkspaceFiles?: boolean;
+ resolveImageSrc?(href: string): string | undefined;
}
): ReactNode {
const output: ReactNode[] = [];
@@ -269,7 +270,10 @@ export function renderInlineMarkdown(
));
} else if (match[3] !== undefined) {
const alt = match[2]?.trim();
- output.push(<Fragment key={key++}>{alt ? `${alt} [图片]` : '[图片]'}</Fragment>);
+ const src = options.resolveImageSrc?.(match[3]);
+ output.push(src
+ ? <img key={key++} className="md-image" src={src} alt={alt ?? ''} />
+ : <Fragment key={key++}>{alt ? `${alt} [图片]` : '[图片]'}</Fragment>);
} else if (match[4] && match[5]) {
output.push(renderLink(match[5], match[4], key++, {
allowRelative,
diff --git a/apps/web/src/features/dashboard/CreatorCollaborationPanel.test.tsx b/apps/web/src/features/dashboard/CreatorCollaborationPanel.test.tsx
index 61fbdf69..4d5d011b 100644
--- a/apps/web/src/features/dashboard/CreatorCollaborationPanel.test.tsx
+++ b/apps/web/src/features/dashboard/CreatorCollaborationPanel.test.tsx
@@ -6,6 +6,7 @@ import CreatorCollaborationPanel from './CreatorCollaborationPanel.js';
import {
coverPanelAdapter,
smartDubbingPanelAdapter,
+ wechatArticlePanelAdapter,
xiaohongshuPostPanelAdapter,
videoDownloadPanelAdapter,
videoGenerationPanelAdapter
@@ -484,8 +485,126 @@ describe('CreatorCollaborationPanel', () => {
expect(screen.getByRole('progressbar', { name: '生成小红书帖子进度' }))
.toHaveAttribute('aria-valuenow', '20');
});
+
+ it('语义化公众号写作动态,过滤界面状态并显示标准阶段进度', () => {
+ render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={wechatArticleJob()}
+ service={{ applyAction: vi.fn(), runAgentTurn: vi.fn() } as never}
+ >
+ <CreatorCollaborationPanel
+ adapter={wechatArticlePanelAdapter}
+ stepLabel="正在生成选题"
+ contextSummary="2 个内容灵感"
+ />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ expect(screen.getAllByText('完善了写作要求')).toHaveLength(1);
+ expect(screen.getByText('写作要求、文章模板')).toBeInTheDocument();
+ expect(screen.getByText('2 次修改')).toBeInTheDocument();
+ expect(screen.queryByText(/currentStep|furthestStep/)).not.toBeInTheDocument();
+ expect(screen.getByText('上传了内容灵感')).toBeInTheDocument();
+ expect(screen.getByText('生成候选选题')).toBeInTheDocument();
+ expect(screen.getByText('55%')).toBeInTheDocument();
+ expect(screen.getByRole('progressbar', { name: '生成候选选题进度' }))
+ .toHaveAttribute('aria-valuenow', '55');
+ });
+
+ it('为公众号内容灵感解析阶段提供稳定文案和真实进度', () => {
+ const localize = (zh: string) => zh;
+ const stage = {
+ stageId: 'sources',
+ progress: { phase: 'reading_video', percent: 30, completed: 0, failed: 0, total: 1 }
+ } as never;
+
+ expect(wechatArticlePanelAdapter.stageLabel('sources', localize)).toBe('解析内容灵感');
+ expect(wechatArticlePanelAdapter.phaseLabel('reading_video', localize)).toBe('读取视频内容');
+ expect(wechatArticlePanelAdapter.readStageProgress(stage)).toEqual(expect.objectContaining({ percent: 30 }));
+ expect(wechatArticlePanelAdapter.succeededProgressText?.(stage, localize)).toBe('内容灵感已解析');
+
+ const imageStage = {
+ stageId: 'images',
+ progress: { phase: 'generating_article_images', percent: 68, completed: 3, failed: 0, total: 5 }
+ } as never;
+ expect(wechatArticlePanelAdapter.stageLabel('images', localize)).toBe('生成文章配图');
+ expect(wechatArticlePanelAdapter.phaseLabel('generating_article_images', localize)).toBe('生成文章配图');
+ expect(wechatArticlePanelAdapter.readStageProgress(imageStage)).toEqual(expect.objectContaining({
+ percent: 68,
+ completed: 3,
+ total: 5
+ }));
+ expect(wechatArticlePanelAdapter.succeededProgressText?.(imageStage, localize)).toBe('文章配图已生成');
+
+ expect(wechatArticlePanelAdapter.normalizeActivity({
+ id: 'outline-update',
+ jobId: 'wechat-job',
+ revision: 1,
+ actor: 'user',
+ action: 'update-settings:draft',
+ summary: '更新创作设置',
+ details: { objectId: 'outline' },
+ createdAt: '2026-09-07T09:00:00.000Z'
+ }, localize)).toEqual({ label: '生成了文章大纲', fields: [] });
+ expect(wechatArticlePanelAdapter.normalizeActivity({
+ id: 'image-update',
+ jobId: 'wechat-job',
+ revision: 2,
+ actor: 'user',
+ action: 'update-settings:draft',
+ summary: '更新创作设置',
+ details: { objectId: 'articleImageStyleId,articleImageCount' },
+ createdAt: '2026-09-07T09:00:01.000Z'
+ }, localize)).toEqual({
+ label: '调整了文章配图',
+ fields: ['生图风格', '配图数量']
+ });
+ });
});
+function wechatArticleJob(): CreatorJob {
+ const jobId = 'wechat_article_job';
+ return {
+ id: jobId,
+ projectId: 'project_1',
+ templateId: 'wechat-article',
+ templateVersion: 1,
+ status: 'running',
+ revision: 5,
+ state: { currentStage: 'topics' },
+ agentThreadId: null,
+ stages: [{
+ id: 'wechat_topics_stage',
+ jobId,
+ stageId: 'topics',
+ executor: 'wechat-article',
+ status: 'running',
+ dispatchStatus: 'claimed',
+ claimOwner: 'scheduler_1',
+ claimExpiresAt: null,
+ attempt: 1,
+ idempotencyKey: 'wechat-topics-1',
+ progress: { phase: 'generating_topics', percent: 55, completed: 2, failed: 0, total: 2 },
+ errorCode: null,
+ errorMessage: null,
+ startedAt: '2026-09-07T09:00:05.000Z',
+ finishedAt: null
+ }],
+ artifacts: [],
+ activities: [
+ { id: 'ui', jobId, revision: 1, actor: 'user', action: 'update-settings:draft', summary: '更新创作设置', details: { objectId: 'currentStep,furthestStep' }, createdAt: '2026-09-07T09:00:01.000Z' },
+ { id: 'brief', jobId, revision: 2, actor: 'user', action: 'update-settings:draft', summary: '更新创作设置', details: { objectId: 'writingPrompt' }, createdAt: '2026-09-07T09:00:02.000Z' },
+ { id: 'template', jobId, revision: 3, actor: 'user', action: 'update-settings:draft', summary: '更新创作设置', details: { objectId: 'presetId' }, createdAt: '2026-09-07T09:00:03.000Z' },
+ { id: 'upload', jobId, revision: 4, actor: 'user', action: 'register-source-document', summary: '上传写作来源', details: { objectId: 'source.pdf' }, createdAt: '2026-09-07T09:00:04.000Z' },
+ { id: 'run', jobId, revision: 5, actor: 'user', action: 'run-stage', summary: '启动阶段 topics', details: { stageId: 'topics' }, createdAt: '2026-09-07T09:00:05.000Z' }
+ ],
+ createdAt: '2026-09-07T09:00:00.000Z',
+ updatedAt: '2026-09-07T09:00:05.000Z'
+ };
+}
+
function xiaohongshuPostJob(): CreatorJob {
const createdAt = '2026-09-08T08:00:00.000Z';
return {
diff --git a/apps/web/src/features/dashboard/DashboardPage.test.tsx b/apps/web/src/features/dashboard/DashboardPage.test.tsx
index 79f9740c..efe2e010 100644
--- a/apps/web/src/features/dashboard/DashboardPage.test.tsx
+++ b/apps/web/src/features/dashboard/DashboardPage.test.tsx
@@ -728,8 +728,9 @@ describe('DashboardPage', () => {
expect(within(videoTranslationCard).getByText('HOT')).toBeInTheDocument();
expect(within(videoTranslationCard).queryByText('NEW')).not.toBeInTheDocument();
const appCards = Array.from(container.querySelectorAll('.dashboard-app-card'));
- expect(appCards).toHaveLength(7);
+ expect(appCards).toHaveLength(8);
expect(appCards.map(card => card.querySelector('strong')?.textContent)).toEqual([
+ '文章写作',
'视频翻译',
'视频下载',
'封面生成',
@@ -742,6 +743,9 @@ describe('DashboardPage', () => {
expect(screen.queryByRole('button', { name: /^自动剪辑/ })).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: /^智能配音/ })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /^视频生成/ })).toBeInTheDocument();
+ const articleCard = screen.getByRole('button', { name: /^文章写作/ });
+ expect(within(articleCard).getByText('公众号、X 等平台文章')).toBeInTheDocument();
+ expect(within(articleCard).getByText('NEW')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: /^数字人口播/ })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: /^视频转格式/ })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: /^画面扩展/ })).not.toBeInTheDocument();
@@ -757,6 +761,19 @@ describe('DashboardPage', () => {
.toBeInTheDocument();
});
+ it('opens the WeChat article writer from the app directory', () => {
+ const { container } = render(<DashboardPage onSelectPrompt={vi.fn()} />);
+ fireEvent.click(screen.getByRole('button', { name: /^文章写作/ }));
+ expect(screen.getByRole('heading', { name: '文章写作' })).toBeInTheDocument();
+ expect(screen.getByText('公众号、X 等平台文章')).toBeInTheDocument();
+ expect(screen.getByRole('navigation', { name: '文章写作流程' })).toBeInTheDocument();
+ expect(screen.getByText('从右侧添加链接或文件。没有资料也可以继续写作。')).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: '继续' }));
+ expect(screen.getByText('写作模板')).toBeInTheDocument();
+ expect(screen.queryByText('排版模板')).not.toBeInTheDocument();
+ expect(container.querySelector('.wechat-layout-list')).not.toBeInTheDocument();
+ });
+
it('opens the video translation workspace and keeps its result in place', async () => {
const onSelectPrompt = vi.fn();
render(
diff --git a/apps/web/src/features/dashboard/DashboardPage.tsx b/apps/web/src/features/dashboard/DashboardPage.tsx
index 5e7481d5..7eb9fdf8 100644
--- a/apps/web/src/features/dashboard/DashboardPage.tsx
+++ b/apps/web/src/features/dashboard/DashboardPage.tsx
@@ -11,6 +11,7 @@ import {
Languages,
Mic2,
PenLine,
+ Newspaper,
Search,
ServerOff,
Sparkles,
@@ -25,6 +26,7 @@ import DigitalAvatarWorkspace from './DigitalAvatarWorkspace.js';
import ImageGenerationWorkspace from './ImageGenerationWorkspace.js';
import SmartDubbingWorkspace from './SmartDubbingWorkspace.js';
import XiaohongshuPostWorkspace from './XiaohongshuPostWorkspace.js';
+import WechatArticleWorkspace from './WechatArticleWorkspace.js';
import StickmanVideoWorkspace from './StickmanVideoWorkspace.js';
import VideoDownloadWorkspace from './VideoDownloadWorkspace.js';
import VideoTranslationWorkspace from './VideoTranslationWorkspace.js';
@@ -87,6 +89,15 @@ const featuredTools: FeaturedEntry[] = [
];
const creatorTools: DashboardEntry[] = [
+ {
+ title: '文章写作',
+ description: '公众号、X 等平台文章',
+ prompt: '帮我根据内容灵感写一篇适合公众号、X 等平台发布的文章,先给出选题和大纲,再完成正文。',
+ category: '文案创作',
+ icon: Newspaper,
+ badge: 'NEW',
+ workspace: 'wechat-article'
+ },
{
title: '视频翻译',
description: '字幕、配音与口型同步',
@@ -336,6 +347,15 @@ export default function DashboardPage(props: {
));
}
+ if (activeWorkspace === 'wechat-article') {
+ return renderCreatorWorkspace('wechat-article', (
+ <WechatArticleWorkspace
+ promptHint={activePromptHint}
+ onBack={closeWorkspace}
+ />
+ ));
+ }
+
if (activeWorkspace === 'image-generation') {
return renderCreatorWorkspace('image-generation', (
<ImageGenerationWorkspace
@@ -820,6 +840,7 @@ function createCreationKeySuffix(): string {
const englishDashboardLabels: Record<string, string> = {
全部: 'All',
+ 内容创作: 'Content Creation',
视频创作: 'Video Creation',
图像创作: 'Image Creation',
文案创作: 'Writing',
@@ -830,6 +851,8 @@ const englishDashboardLabels: Record<string, string> = {
视频翻译配音: 'Translate & Dub Video',
数字人口播: 'Digital Avatar',
视频翻译: 'Video Translation',
+ 文章写作: 'Article Writer',
+ '公众号、X 等平台文章': 'Articles for WeChat, X, and more',
'字幕、配音与口型同步': 'Subtitles, dubbing, and lip sync',
视频生成: 'Video Generation',
文字或参考图生成视频片段: 'Generate video clips from text or a reference image',
diff --git a/apps/web/src/features/dashboard/WechatArticleWorkspace.test.tsx b/apps/web/src/features/dashboard/WechatArticleWorkspace.test.tsx
new file mode 100644
index 00000000..c4c0d7af
--- /dev/null
+++ b/apps/web/src/features/dashboard/WechatArticleWorkspace.test.tsx
@@ -0,0 +1,1096 @@
+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import type { CreatorActionRequest, CreatorJob } from '@opencreator/protocol';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { LanguageProvider } from '../../i18n/LanguageProvider.js';
+import WechatArticleWorkspace from './WechatArticleWorkspace.js';
+import { CreatorSessionProvider } from './creator-session-store.js';
+
+describe('WechatArticleWorkspace', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ it('opens layout templates after article editing and generates a document result', async () => {
+ const job = articleJob();
+ const applyAction = vi.fn(async (_jobId: string, request: CreatorActionRequest) => {
+ if (request.action === 'update-settings') {
+ Object.assign(job.state, readPatch(request));
+ }
+ if (request.action === 'run-stage' && request.input.stageId === 'document') {
+ job.artifacts.push(...documentArtifacts());
+ job.stages.push({
+ id: 'document-stage-1',
+ jobId: job.id,
+ stageId: 'document',
+ executor: 'wechat-article',
+ status: 'succeeded',
+ dispatchStatus: 'finished',
+ claimOwner: null,
+ claimExpiresAt: null,
+ attempt: 1,
+ idempotencyKey: null,
+ progress: { phase: 'completed', percent: 100, completed: 3, failed: 0, total: 3 },
+ errorCode: null,
+ errorMessage: null,
+ startedAt: '2026-09-07T08:01:00.000Z',
+ finishedAt: '2026-09-07T08:01:01.000Z'
+ });
+ }
+ job.revision += 1;
+ return actionResponse(job, request.action);
+ });
+ const openArtifact = vi.fn(async () => new Response('# 示例文章\n\n正文内容。', {
+ status: 200,
+ headers: { 'content-type': 'text/markdown' }
+ }));
+ const NativeURL = URL;
+ class TestURL extends NativeURL {
+ static createObjectURL = vi.fn(() => 'blob:article-document');
+ static revokeObjectURL = vi.fn();
+ }
+ vi.stubGlobal('URL', TestURL);
+ const clickDownload = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => undefined);
+
+ const { container } = render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job}
+ service={{ applyAction, openArtifact, runAgentTurn: vi.fn() } as never}
+ >
+ <WechatArticleWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ await screen.findByRole('textbox', { name: '文章正文编辑器' });
+ expect(screen.getByText('20 字')).toBeInTheDocument();
+ expect(screen.queryByText('排版模板')).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: '完成编辑,选择排版' }));
+
+ await screen.findByText('排版模板');
+ expect(screen.getByRole('heading', { level: 2, name: '文章预览' }).parentElement).toHaveClass('wechat-layout-preview-heading');
+ expect(screen.getByRole('complementary', { name: '排版模板' })).toHaveClass('wechat-layout-sidebar');
+ expect(container.querySelector('.wechat-layout-workbench > .wechat-layout-preview-pane + .wechat-layout-sidebar')).toBeInTheDocument();
+ expect(within(container.querySelector('.wechat-layout-preview-heading')!).getByRole('button', { name: '复制图文' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: '生成文档' })).toBeInTheDocument();
+ const layoutCategories = screen.getByRole('group', { name: '排版模板分类' });
+ expect(within(layoutCategories).getByRole('button', { name: '推荐' })).toHaveAttribute('aria-pressed', 'true');
+ expect(container.querySelectorAll('.wechat-layout-list button')).toHaveLength(4);
+
+ fireEvent.click(within(layoutCategories).getByRole('button', { name: '资讯' }));
+ expect(container.querySelectorAll('.wechat-layout-list button')).toHaveLength(1);
+ expect(screen.getByRole('button', { name: /^热点简报/ })).toBeInTheDocument();
+
+ fireEvent.click(within(layoutCategories).getByRole('button', { name: '科技' }));
+ expect(container.querySelectorAll('.wechat-layout-list button')).toHaveLength(3);
+ const podcastLayout = screen.getByRole('button', { name: /^播客访谈/ });
+ expect(within(podcastLayout).getByText('嘉宾发言')).toBeInTheDocument();
+ fireEvent.click(podcastLayout);
+ expect(container.querySelector('.wechat-article-preview')).toHaveAttribute('data-layout', 'podcast');
+
+ fireEvent.click(within(layoutCategories).getByRole('button', { name: '商业' }));
+
+ const businessLayout = screen.getByRole('button', { name: /^商业报告/ });
+ expect(within(businessLayout).getByText('内容摘要')).toBeInTheDocument();
+ fireEvent.click(businessLayout);
+
+ expect(businessLayout).toHaveAttribute('data-selected', 'true');
+ await waitFor(() => {
+ expect(container.querySelector('.wechat-article-preview')).toHaveAttribute('data-layout', 'business');
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: '生成文档' }));
+
+ await waitFor(() => {
+ expect(applyAction).toHaveBeenCalledWith(job.id, expect.objectContaining({
+ action: 'run-stage',
+ input: { stageId: 'document' }
+ }));
+ });
+ expect(screen.queryByRole('navigation', { name: '文章写作流程' })).not.toBeInTheDocument();
+ expect(screen.getByRole('tab', { name: '生成物' })).toHaveAttribute('aria-selected', 'true');
+ expect(screen.getByText('示例文章.md')).toBeInTheDocument();
+ expect(screen.getByText('示例文章.html')).toBeInTheDocument();
+ expect(screen.getByText('示例文章.pdf')).toBeInTheDocument();
+ expect(screen.getByRole('tab', { name: '配图' })).toBeInTheDocument();
+ expect(container.querySelector('.wechat-result-preview')).not.toBeInTheDocument();
+ expect(container.querySelector('.creator-collaboration-panel')).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: '下载 Markdown 文档' }));
+ await waitFor(() => expect(openArtifact).toHaveBeenCalledWith(job.id, 'article-document-1'));
+ expect(clickDownload).toHaveBeenCalledTimes(1);
+
+ fireEvent.click(screen.getByRole('button', { name: '调整文章' }));
+ expect(await screen.findByRole('textbox', { name: '文章正文编辑器' })).toBeInTheDocument();
+ });
+
+ it('edits article text beside configurable automatic image generation settings', async () => {
+ const job = articleJob();
+ const applyAction = vi.fn(async (_jobId: string, request: CreatorActionRequest) => {
+ if (request.action === 'update-settings') Object.assign(job.state, readPatch(request));
+ job.revision += 1;
+ return actionResponse(job, request.action);
+ });
+ render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job}
+ service={{ applyAction, runAgentTurn: vi.fn() } as never}
+ >
+ <WechatArticleWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ expect(screen.getByRole('textbox', { name: '文章正文编辑器' })).toBeInTheDocument();
+ const imagePanel = screen.getByRole('complementary', { name: '文章配图设置' });
+ expect(within(imagePanel).getByRole('checkbox')).toBeChecked();
+ expect(within(imagePanel).getByRole('button', { name: '适中' })).toHaveAttribute('aria-pressed', 'true');
+ expect(imagePanel.querySelectorAll('.wechat-image-style-grid img')).toHaveLength(6);
+ expect(imagePanel.querySelector('.wechat-image-style-grid img')).toHaveAttribute(
+ 'src',
+ '/dashboard/wechat-article/image-styles/editorial-v2.webp'
+ );
+ expect(imagePanel.querySelectorAll('.wechat-image-style-grid img')[1]).toHaveAttribute(
+ 'src',
+ '/dashboard/wechat-article/image-styles/minimal-v2.webp'
+ );
+ expect(imagePanel.querySelectorAll('.wechat-image-style-grid img')[2]).toHaveAttribute(
+ 'src',
+ '/dashboard/wechat-article/image-styles/documentary-v2.webp'
+ );
+ expect(imagePanel.querySelectorAll('.wechat-image-style-grid img')[4]).toHaveAttribute(
+ 'src',
+ '/dashboard/wechat-article/image-styles/three-dimensional-v2.webp'
+ );
+
+ fireEvent.click(within(imagePanel).getByRole('button', { name: '多图' }));
+ fireEvent.click(within(imagePanel).getByRole('button', { name: '增加配图数量' }));
+ expect(within(imagePanel).getByRole('slider', { name: '配图数量' })).toHaveValue('9');
+ fireEvent.click(within(imagePanel).getByRole('button', { name: /现代插画/ }));
+ expect(within(imagePanel).queryByRole('textbox')).not.toBeInTheDocument();
+ fireEvent.click(within(imagePanel).getByRole('button', { name: '生成 9 张配图' }));
+
+ await waitFor(() => {
+ expect(applyAction).toHaveBeenCalledWith(job.id, expect.objectContaining({
+ action: 'run-stage',
+ input: { stageId: 'images' }
+ }));
+ });
+ expect(job.state).toEqual(expect.objectContaining({
+ autoGenerateImages: true,
+ articleImageCount: 9,
+ articleImageStyleId: 'illustration'
+ }));
+ });
+
+ it('generates the outline directly from the selected topic action', async () => {
+ const job = articleJob();
+ job.state.currentStep = 2;
+ job.state.furthestStep = 2;
+ job.state.outline = '';
+ job.state.articleMarkdown = '';
+ const applyAction = vi.fn(async (_jobId: string, request: CreatorActionRequest) => {
+ if (request.action === 'update-settings') Object.assign(job.state, readPatch(request));
+ job.revision += 1;
+ return actionResponse(job, request.action);
+ });
+ render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job}
+ service={{ applyAction, runAgentTurn: vi.fn() } as never}
+ >
+ <WechatArticleWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: '生成大纲' }));
+
+ expect(await screen.findByRole('heading', { name: '文章大纲' })).toBeInTheDocument();
+ await waitFor(() => {
+ expect(applyAction).toHaveBeenCalledWith(job.id, expect.objectContaining({
+ action: 'run-stage',
+ input: { stageId: 'outline' }
+ }));
+ });
+ expect(screen.queryByRole('button', { name: '使用这个选题' })).not.toBeInTheDocument();
+ });
+
+ it('inserts generated images at their planned article headings and renders them in preview', async () => {
+ const job = articleJob();
+ job.state.articleMarkdown = '# 示例文章\n\n## 第一部分\n\n![旧配图](./article-image-01.png)\n\n第一段正文。\n\n## 第二部分\n\n第二段正文。';
+ const firstImage = articleImageArtifact('article-image-1', 2, 1);
+ firstImage.metadata.fileName = 'article-image-01.png';
+ firstImage.metadata.caption = '第一部分配图';
+ firstImage.metadata.placementHeading = '第一部分';
+ const secondImage = articleImageArtifact('article-image-2', 2, 2);
+ secondImage.metadata.fileName = 'article-image-02.png';
+ secondImage.metadata.caption = '第二部分配图';
+ secondImage.metadata.placementHeading = '## 第二部分';
+ job.artifacts.push(firstImage, secondImage);
+ const openArtifact = vi.fn(async () => new Response(
+ new Blob(['image'], { type: 'image/png' }),
+ { status: 200, headers: { 'content-type': 'image/png' } }
+ ));
+ const NativeURL = URL;
+ class TestURL extends NativeURL {
+ static createObjectURL = vi.fn(() => `blob:article-image-${TestURL.createObjectURL.mock.calls.length}`);
+ static revokeObjectURL = vi.fn();
+ }
+ vi.stubGlobal('URL', TestURL);
+
+ const { container, unmount } = render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job}
+ service={{ applyAction: vi.fn(), openArtifact, runAgentTurn: vi.fn() } as never}
+ >
+ <WechatArticleWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ const editor = container.querySelector('.wechat-article-editor') as HTMLElement;
+ await waitFor(() => {
+ expect(within(editor).getByRole('img', { name: '第一部分配图' })).toBeInTheDocument();
+ expect(within(editor).getByRole('img', { name: '第二部分配图' })).toBeInTheDocument();
+ });
+ const editorMarkdown = readArticleEditorMarkdown(editor);
+ expect(editorMarkdown).toContain('## 第一部分\n\n![第一部分配图](./article-image-01.png)\n\n第一段正文。');
+ expect(editorMarkdown).toContain('## 第二部分\n\n![第二部分配图](./article-image-02.png)\n\n第二段正文。');
+ expect(editorMarkdown).not.toContain('旧配图');
+ expect(editorMarkdown.match(/!\[/g)).toHaveLength(2);
+ expect(within(screen.getByRole('complementary', { name: '文章配图设置' })).queryByText('已生成配图')).not.toBeInTheDocument();
+
+ const figures = Array.from(editor.querySelectorAll('.wechat-article-inline-image'));
+ const textBlocks = Array.from(editor.querySelectorAll('.wechat-article-editor-segment')) as HTMLTextAreaElement[];
+ expect(textBlocks[0]?.value.endsWith('\n')).toBe(false);
+ expect(textBlocks[1]?.value.startsWith('\n')).toBe(false);
+ const targetBlock = textBlocks.at(-1)!;
+ targetBlock.setSelectionRange(targetBlock.value.length, targetBlock.value.length);
+ const dataTransfer = {
+ effectAllowed: 'none',
+ dropEffect: 'none',
+ setData: vi.fn()
+ };
+ fireEvent.dragStart(figures[0]!, { dataTransfer });
+ fireEvent.dragOver(targetBlock, { dataTransfer });
+ expect(container.querySelector('.wechat-article-image-drop-indicator')).toBeInTheDocument();
+ fireEvent.drop(targetBlock, { dataTransfer });
+ expect(container.querySelector('.wechat-article-image-drop-indicator')).not.toBeInTheDocument();
+
+ await waitFor(() => {
+ const movedEditor = container.querySelector('.wechat-article-editor') as HTMLElement;
+ const movedMarkdown = readArticleEditorMarkdown(movedEditor);
+ expect(movedMarkdown.indexOf('![第二部分配图]')).toBeLessThan(movedMarkdown.indexOf('![第一部分配图]'));
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: '完成编辑,选择排版' }));
+ const preview = container.querySelector('.wechat-article-preview') as HTMLElement;
+ await waitFor(() => expect(within(preview).getAllByRole('img').map(image => image.getAttribute('alt'))).toEqual([
+ '第二部分配图',
+ '第一部分配图'
+ ]));
+ unmount();
+ });
+
+ it('uploads, replaces, and removes inline article images at the editor cursor', async () => {
+ const job = articleJob();
+ let uploadIndex = 0;
+ const applyAction = vi.fn(async (_jobId: string, request: CreatorActionRequest) => {
+ if (request.action === 'update-settings') Object.assign(job.state, readPatch(request));
+ job.revision += 1;
+ return actionResponse(job, request.action);
+ });
+ const uploadArticleImage = vi.fn(async (_jobId: string, input: { file: File }) => {
+ uploadIndex += 1;
+ const artifact = manualArticleImageArtifact(`manual-image-${uploadIndex}`, input.file.name, uploadIndex);
+ job.artifacts.push(artifact);
+ job.state.manualArticleImageArtifactIds = [
+ ...((job.state.manualArticleImageArtifactIds as string[] | undefined) ?? []),
+ artifact.id
+ ];
+ job.revision += 1;
+ return { job: structuredClone(job), artifact, deduplicated: false };
+ });
+ const openArtifact = vi.fn(async () => new Response(
+ new Blob(['image'], { type: 'image/png' }),
+ { status: 200, headers: { 'content-type': 'image/png' } }
+ ));
+ const NativeURL = URL;
+ class TestURL extends NativeURL {
+ static createObjectURL = vi.fn(() => `blob:manual-article-image-${TestURL.createObjectURL.mock.calls.length}`);
+ static revokeObjectURL = vi.fn();
+ }
+ vi.stubGlobal('URL', TestURL);
+
+ const { container } = render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job}
+ service={{ applyAction, uploadArticleImage, openArtifact, runAgentTurn: vi.fn() } as never}
+ >
+ <WechatArticleWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ const editor = screen.getByRole('textbox', { name: '文章正文编辑器' }) as HTMLTextAreaElement;
+ const insertionOffset = editor.value.indexOf('## 第一部分');
+ editor.setSelectionRange(insertionOffset, insertionOffset);
+ fireEvent.select(editor);
+ fireEvent.click(screen.getByRole('button', { name: '插入图片' }));
+ const fileInput = container.querySelector('input[type="file"][accept^="image/png"]') as HTMLInputElement;
+ const firstFile = new File(['first'], '我的配图.png', { type: 'image/png' });
+ fireEvent.change(fileInput, { target: { files: [firstFile] } });
+
+ await waitFor(() => expect(screen.getByRole('img', { name: '我的配图' })).toBeInTheDocument());
+ expect(uploadArticleImage).toHaveBeenCalledWith(job.id, expect.objectContaining({ file: firstFile }));
+ const textBeforeImage = container.querySelector('.wechat-article-editor-segment') as HTMLTextAreaElement;
+ expect(textBeforeImage.value).toContain('# 示例文章');
+ expect(textBeforeImage.value).not.toContain('## 第一部分');
+
+ fireEvent.click(screen.getByRole('button', { name: '替换图片' }));
+ const replacement = new File(['replacement'], '替换配图.webp', { type: 'image/webp' });
+ fireEvent.change(fileInput, { target: { files: [replacement] } });
+ await waitFor(() => expect(screen.getByRole('img', { name: '替换配图' })).toBeInTheDocument());
+ expect(screen.queryByRole('img', { name: '我的配图' })).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: '删除图片' }));
+ await waitFor(() => expect(screen.queryByRole('img', { name: '替换配图' })).not.toBeInTheDocument());
+ expect(screen.getByRole('status')).toHaveTextContent('图片已从正文移除');
+ });
+
+ it('shows the latest generated article images in the result and downloads them individually', async () => {
+ const job = articleJob();
+ job.state.workspacePhase = 'result';
+ job.state.articleImageStyleId = 'documentary';
+ job.artifacts.push(
+ articleImageArtifact('old-image', 1, 1),
+ articleImageArtifact('article-image-1', 2, 1),
+ articleImageArtifact('article-image-2', 2, 2),
+ documentArtifact()
+ );
+ const openArtifact = vi.fn(async (_jobId: string, artifactId: string) => new Response(
+ new Blob([artifactId], { type: 'image/png' }),
+ { status: 200, headers: { 'content-type': 'image/png' } }
+ ));
+ const NativeURL = URL;
+ class TestURL extends NativeURL {
+ static createObjectURL = vi.fn((blob: Blob) => `blob:${blob.size}`);
+ static revokeObjectURL = vi.fn();
+ }
+ vi.stubGlobal('URL', TestURL);
+ const clickDownload = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => undefined);
+
+ const { unmount } = render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job}
+ service={{ applyAction: vi.fn(), openArtifact, runAgentTurn: vi.fn() } as never}
+ >
+ <WechatArticleWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ expect(screen.queryByText('2 张可单独下载的配图')).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('tab', { name: '配图' }));
+ expect(await screen.findByText('2 张可单独下载')).toBeInTheDocument();
+ expect(screen.queryByText('旧版配图')).not.toBeInTheDocument();
+ expect(await screen.findByRole('img', { name: '文章配图 1' })).toBeInTheDocument();
+ expect(screen.getByRole('img', { name: '文章配图 2' })).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: '下载配图 2' }));
+ expect(clickDownload).toHaveBeenCalledTimes(1);
+ unmount();
+ });
+
+ it('manages links and dropped files in a 10-item inspiration library', async () => {
+ const job = inspirationJob();
+ const applyAction = vi.fn(async (_jobId: string, request: CreatorActionRequest) => {
+ if (request.action === 'update-settings') Object.assign(job.state, readPatch(request));
+ job.revision += 1;
+ return actionResponse(job, request.action);
+ });
+ const uploadSourceDocument = vi.fn(async (_jobId: string, input: { file: File }) => {
+ const artifact = sourceDocumentArtifact('source-document-1', input.file.name);
+ job.artifacts.push(artifact);
+ job.state.sourceDocumentArtifactIds = [artifact.id];
+ job.revision += 1;
+ return { job: structuredClone(job), artifact, deduplicated: false };
+ });
+ const { container } = render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job}
+ service={{ applyAction, uploadSourceDocument, runAgentTurn: vi.fn() } as never}
+ >
+ <WechatArticleWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ expect(screen.getByRole('complementary', { name: '内容灵感' })).toBeInTheDocument();
+ expect(screen.getByText('0/10')).toBeInTheDocument();
+ const inspirationAdd = container.querySelector('.wechat-inspiration-add')!;
+ const linkSection = container.querySelector('.wechat-inspiration-link-section')!;
+ const dropzone = container.querySelector('.wechat-inspiration-dropzone')!;
+ expect(Array.from(inspirationAdd.children).indexOf(linkSection)).toBeLessThan(
+ Array.from(inspirationAdd.children).indexOf(dropzone)
+ );
+ const urlInput = screen.getByRole('textbox', { name: '视频或网页链接' });
+ fireEvent.change(urlInput, { target: { value: 'https://www.bilibili.com/video/BV1test' } });
+ fireEvent.click(screen.getByRole('button', { name: '添加' }));
+ expect(screen.getByText('1/10')).toBeInTheDocument();
+
+ const file = new File(['article notes'], 'notes.md', { type: 'text/markdown' });
+ fireEvent.drop(dropzone, { dataTransfer: { files: [file], dropEffect: 'copy' } });
+ await waitFor(() => expect(uploadSourceDocument).toHaveBeenCalledWith(job.id, expect.objectContaining({ file })));
+ expect(await screen.findByText('2/10')).toBeInTheDocument();
+ expect(screen.getByText('notes.md')).toBeInTheDocument();
+ expect(screen.getByRole('status')).toHaveTextContent('文件已加入内容灵感');
+ });
+
+ it('parses inspiration before opening the writing brief', async () => {
+ const job = inspirationJob(1);
+ const applyAction = vi.fn(async (_jobId: string, request: CreatorActionRequest) => {
+ if (request.action === 'update-settings') Object.assign(job.state, readPatch(request));
+ if (request.action === 'run-stage' && request.input.stageId === 'sources') {
+ job.artifacts.push(articleSourcesArtifact('article-sources-1', 1));
+ job.stages.push(sourceStage('succeeded'));
+ job.status = 'draft';
+ }
+ job.revision += 1;
+ return actionResponse(job, request.action);
+ });
+ render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job}
+ service={{ applyAction, runAgentTurn: vi.fn() } as never}
+ >
+ <WechatArticleWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: '解析灵感并继续' }));
+
+ await waitFor(() => expect(applyAction).toHaveBeenCalledWith(job.id, expect.objectContaining({
+ action: 'run-stage',
+ input: { stageId: 'sources' }
+ })));
+ expect(await screen.findByRole('heading', { name: '写作要求' })).toBeInTheDocument();
+ expect(screen.getByRole('status')).toHaveTextContent('已解析 1 个内容灵感,其中 1 个视频使用自动字幕');
+ });
+
+ it('keeps the writing brief primary and selects templates from a searchable library', async () => {
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue({
+ left: 44,
+ width: 920
+ } as DOMRect);
+ const job = inspirationJob();
+ job.state.currentStep = 1;
+ job.state.furthestStep = 1;
+ job.state.presetId = 'insight';
+ const applyAction = vi.fn(async (_jobId: string, request: CreatorActionRequest) => {
+ if (request.action === 'update-settings') Object.assign(job.state, readPatch(request));
+ job.revision += 1;
+ return actionResponse(job, request.action);
+ });
+ render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job}
+ service={{ applyAction, runAgentTurn: vi.fn() } as never}
+ >
+ <WechatArticleWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ expect(screen.getByRole('textbox', { name: '提示词' })).toBeInTheDocument();
+ expect(screen.getByText('深度洞察')).toBeInTheDocument();
+ expect(screen.queryByRole('dialog', { name: '文章模板库' })).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: '更换模板' }));
+ const library = screen.getByRole('dialog', { name: '文章模板库' });
+ expect(library.parentElement).toHaveClass('wechat-template-library-overlay');
+ expect(library.parentElement?.parentElement).toBe(document.body);
+ expect(library.parentElement?.style.getPropertyValue('--wechat-template-library-left')).toBe('44px');
+ expect(library.parentElement?.style.getPropertyValue('--wechat-template-library-width')).toBe('920px');
+ const filters = within(library).getByRole('group', { name: '模板标签' });
+ expect(within(filters).getAllByRole('button')).toHaveLength(10);
+ expect(within(filters).getByRole('button', { name: '热门' })).toHaveAttribute('aria-pressed', 'true');
+ expect(within(library).queryByRole('button', { name: /深度洞察/ })).not.toBeInTheDocument();
+ expect(within(library).getByRole('button', { name: /孙割写作\.skill/ })).toBeInTheDocument();
+ expect(within(library).getByRole('button', { name: /卡兹克公众号长文写作/ })).toBeInTheDocument();
+ expect(within(library).getByRole('button', { name: /科研论文写作/ })).toBeInTheDocument();
+ fireEvent.click(within(filters).getByRole('button', { name: '社区' }));
+ expect(within(library).getByRole('button', { name: /孙割写作\.skill/ })).toBeInTheDocument();
+ expect(within(library).getByRole('button', { name: /卡兹克公众号长文写作/ })).toBeInTheDocument();
+ expect(within(library).queryByRole('button', { name: /深度洞察/ })).not.toBeInTheDocument();
+ fireEvent.click(within(filters).getByRole('button', { name: '科技' }));
+ expect(within(library).getByRole('button', { name: /卡兹克公众号长文写作/ })).toBeInTheDocument();
+ expect(within(library).queryByRole('button', { name: /孙割写作\.skill/ })).not.toBeInTheDocument();
+ fireEvent.click(within(filters).getByRole('button', { name: '科研' }));
+ expect(within(library).getByRole('button', { name: /科研论文写作/ })).toBeInTheDocument();
+ expect(within(library).queryByRole('button', { name: /卡兹克公众号长文写作/ })).not.toBeInTheDocument();
+ fireEvent.click(within(filters).getByRole('button', { name: '全部' }));
+ const search = within(library).getByRole('textbox', { name: '搜索文章模板' });
+ fireEvent.change(search, { target: { value: '教程' } });
+ expect(within(library).getByRole('button', { name: /实用教程/ })).toBeInTheDocument();
+ expect(within(library).queryByRole('button', { name: /故事叙事/ })).not.toBeInTheDocument();
+
+ fireEvent.change(search, { target: { value: '' } });
+ expect(within(library).getByRole('button', { name: /卡兹克公众号长文写作/ })).toBeInTheDocument();
+ fireEvent.click(within(library).getByRole('button', { name: /孙割写作\.skill/ }));
+ expect(within(library).getByText('社区贡献')).toBeInTheDocument();
+ expect(within(library).getByRole('link', { name: '查看模板来源' })).toHaveAttribute(
+ 'href',
+ 'https://github.com/KKKKhazix/sun-style-writing'
+ );
+ fireEvent.click(within(library).getByRole('button', { name: /故事叙事/ }));
+ fireEvent.click(within(library).getByRole('button', { name: '使用这个模板' }));
+
+ expect(screen.queryByRole('dialog', { name: '文章模板库' })).not.toBeInTheDocument();
+ expect(screen.getByText('故事叙事')).toBeInTheDocument();
+ });
+
+ it('starts without a selected template and exposes the template list', () => {
+ const job = inspirationJob();
+ job.state.currentStep = 1;
+ job.state.furthestStep = 1;
+ const applyAction = vi.fn();
+ const { container } = render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job}
+ service={{ applyAction, runAgentTurn: vi.fn() } as never}
+ >
+ <WechatArticleWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ const list = screen.getByRole('group', { name: '文章模板列表' });
+ const inlineFilters = screen.getByRole('group', { name: '写作模板标签' });
+ const templateButtons = within(list).getAllByRole('button');
+ expect(templateButtons).toHaveLength(3);
+ expect(templateButtons[0]).toHaveAccessibleName(/孙割写作\.skill/);
+ expect(templateButtons[1]).toHaveAccessibleName(/卡兹克公众号长文写作/);
+ expect(templateButtons[2]).toHaveAccessibleName(/科研论文写作/);
+ expect(container.querySelector('.wechat-current-template')).not.toBeInTheDocument();
+
+ expect(within(inlineFilters).queryByRole('button', { name: '全部' })).not.toBeInTheDocument();
+ expect(within(inlineFilters).queryByRole('button', { name: '社区' })).not.toBeInTheDocument();
+ expect(within(inlineFilters).getAllByRole('button')).toHaveLength(8);
+ expect(within(inlineFilters).getByRole('button', { name: '热门' })).toHaveAttribute('aria-pressed', 'true');
+ fireEvent.click(within(inlineFilters).getByRole('button', { name: '科技' }));
+ expect(within(list).getAllByRole('button')).toHaveLength(4);
+ expect(within(list).queryByRole('button', { name: /孙割写作\.skill/ })).not.toBeInTheDocument();
+ fireEvent.click(within(inlineFilters).getByRole('button', { name: '科技' }));
+ expect(within(list).getAllByRole('button')).toHaveLength(7);
+
+ fireEvent.click(within(inlineFilters).getByRole('button', { name: '科研' }));
+ expect(within(list).getAllByRole('button')).toHaveLength(1);
+ expect(within(list).getByRole('button', { name: /科研论文写作/ })).toBeInTheDocument();
+ fireEvent.click(within(inlineFilters).getByRole('button', { name: '科研' }));
+
+ fireEvent.click(within(list).getByRole('button', { name: /故事叙事/ }));
+
+ expect(screen.queryByRole('group', { name: '文章模板列表' })).not.toBeInTheDocument();
+ expect(container.querySelector('.wechat-current-template')).toHaveTextContent('故事叙事');
+
+ fireEvent.click(screen.getByRole('button', { name: '取消文章模板' }));
+
+ expect(screen.getByRole('group', { name: '文章模板列表' })).toBeInTheDocument();
+ expect(container.querySelector('.wechat-current-template')).not.toBeInTheDocument();
+ });
+
+ it('localizes writing template metadata to the active app language', () => {
+ const job = inspirationJob();
+ job.state.currentStep = 1;
+ job.state.furthestStep = 1;
+ job.state.presetId = 'community.khazix-writer';
+ job.state.templatePrompt = '';
+
+ render(
+ <LanguageProvider initialPreference="en-US">
+ <CreatorSessionProvider
+ initialJob={job}
+ service={{ applyAction: vi.fn(), runAgentTurn: vi.fn() } as never}
+ >
+ <WechatArticleWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ expect(screen.getByText('Khazix Long-form WeChat Writing')).toBeInTheDocument();
+ expect(screen.getByText('Conversational long-form writing built on real experience and progressive argument')).toBeInTheDocument();
+ expect(screen.queryByText('卡兹克公众号长文写作')).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByText('Template instructions'));
+ expect((screen.getByRole('textbox', { name: 'Template instructions' }) as HTMLTextAreaElement).value).toContain('Begin with a source-supported event');
+ });
+
+ it('turns legacy template validation failures into a readable toast', async () => {
+ vi.useFakeTimers();
+ const job = inspirationJob();
+ job.state.currentStep = 1;
+ job.state.furthestStep = 1;
+ job.state.presetId = 'insight';
+ const validationError = Object.assign(new Error(JSON.stringify([{
+ received: '',
+ code: 'invalid_enum_value',
+ options: ['insight', 'story', 'tutorial', 'news-analysis'],
+ path: ['presetId'],
+ message: 'Invalid enum value'
+ }])), { code: 'creator_request_invalid' });
+ const applyAction = vi.fn(async () => Promise.reject(validationError));
+ render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job}
+ service={{ applyAction, runAgentTurn: vi.fn() } as never}
+ >
+ <WechatArticleWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: '取消文章模板' }));
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(350);
+ });
+ expect(screen.getByRole('alert')).toHaveTextContent('文章模板状态已更新,请刷新页面后重新选择');
+ expect(screen.getByRole('alert')).not.toHaveTextContent('invalid_enum_value');
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(4_000);
+ });
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ });
+
+ it('opens jobs that use the previous community template id with the renamed template selected', () => {
+ const job = inspirationJob();
+ job.state.currentStep = 1;
+ job.state.furthestStep = 1;
+ job.state.presetId = 'community.restrained-narrative';
+
+ render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job}
+ service={{ applyAction: vi.fn(), runAgentTurn: vi.fn() } as never}
+ >
+ <WechatArticleWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ expect(screen.getByText('孙割写作.skill')).toBeInTheDocument();
+ expect(screen.queryByRole('group', { name: '文章模板列表' })).not.toBeInTheDocument();
+ });
+
+ it('stays on inspiration and shows a toast when a video has no subtitles', async () => {
+ const job = inspirationJob(1);
+ job.state.sourceLinks = [{
+ id: 'video-1',
+ url: 'https://www.youtube.com/watch?v=test',
+ kind: 'video',
+ label: 'youtube.com'
+ }];
+ const applyAction = vi.fn(async (_jobId: string, request: CreatorActionRequest) => {
+ if (request.action === 'update-settings') Object.assign(job.state, readPatch(request));
+ if (request.action === 'run-stage' && request.input.stageId === 'sources') {
+ job.stages.push(sourceStage('failed'));
+ job.status = 'failed';
+ }
+ job.revision += 1;
+ return actionResponse(job, request.action);
+ });
+ render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job}
+ service={{ applyAction, runAgentTurn: vi.fn() } as never}
+ >
+ <WechatArticleWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: '解析灵感并继续' }));
+
+ expect(await screen.findByRole('alert')).toHaveTextContent('没有找到可用的视频字幕:youtube.com');
+ expect(screen.getByRole('heading', { name: '添加内容灵感' })).toBeInTheDocument();
+ expect(screen.queryByRole('heading', { name: '写作要求' })).not.toBeInTheDocument();
+ });
+
+ it('automatically dismisses non-configuration stage errors', async () => {
+ vi.useFakeTimers();
+ const job = inspirationJob(1);
+ job.stages.push(sourceStage('failed'));
+ job.status = 'failed';
+ render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job}
+ service={{ applyAction: vi.fn(), runAgentTurn: vi.fn() } as never}
+ >
+ <WechatArticleWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ expect(screen.getByRole('alert')).toHaveTextContent('没有找到可用的视频字幕:youtube.com');
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(4_000);
+ });
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ });
+
+ it('shows document upload failures in a centered toast instead of the page footer', async () => {
+ const job = inspirationJob();
+ const uploadError = Object.assign(
+ new Error('Document exceeds the 26214400 byte limit'),
+ { code: 'creator_document_too_large' }
+ );
+ const uploadSourceDocument = vi.fn(async () => Promise.reject(uploadError));
+ const { container } = render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job}
+ service={{ applyAction: vi.fn(), uploadSourceDocument, runAgentTurn: vi.fn() } as never}
+ >
+ <WechatArticleWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ const file = new File(['oversized'], 'large.pdf', { type: 'application/pdf' });
+ fireEvent.drop(container.querySelector('.wechat-inspiration-dropzone')!, {
+ dataTransfer: { files: [file], dropEffect: 'copy' }
+ });
+
+ await waitFor(() => {
+ expect(container.querySelector('.wechat-article-toast')).toHaveTextContent('文件不能超过 25 MB');
+ expect(container.querySelector('.creator-tool-error')).not.toBeInTheDocument();
+ });
+ });
+
+ it('disables adding more inspiration when the shared limit is reached', () => {
+ const job = inspirationJob(10);
+ render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job}
+ service={{ applyAction: vi.fn(), runAgentTurn: vi.fn() } as never}
+ >
+ <WechatArticleWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ expect(screen.getByText('10/10')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: '添加' })).toBeDisabled();
+ expect(screen.getByRole('button', { name: '选择文件' })).toBeDisabled();
+ expect(screen.getByText('已达到 10 个内容灵感上限')).toBeInTheDocument();
+ });
+
+ it('renders form errors in the shared toast instead of below the workspace', async () => {
+ const { container } = render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={inspirationJob()}
+ service={{ applyAction: vi.fn(), runAgentTurn: vi.fn() } as never}
+ >
+ <WechatArticleWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: '添加' }));
+
+ expect(await screen.findByRole('alert')).toHaveTextContent('请输入有效的网页或视频链接');
+ expect(container.querySelector('.wechat-article-toast')).toBeInTheDocument();
+ expect(container.querySelector('.creator-tool-error')).not.toBeInTheDocument();
+ });
+
+ it('shows missing image service configuration below the editor with a settings link', () => {
+ const job = articleJob();
+ job.stages.push({
+ id: 'images-stage-failed',
+ jobId: job.id,
+ stageId: 'images',
+ executor: 'wechat-article',
+ status: 'failed',
+ dispatchStatus: 'finished',
+ claimOwner: null,
+ claimExpiresAt: null,
+ attempt: 1,
+ idempotencyKey: null,
+ progress: { phase: 'failed', percent: 0, completed: 0, failed: 1, total: 1 },
+ errorCode: 'creator_image_config_missing',
+ errorMessage: 'Image generation service is not configured',
+ startedAt: '2026-09-07T08:00:00.000Z',
+ finishedAt: '2026-09-07T08:00:01.000Z'
+ });
+
+ const { container } = render(
+ <LanguageProvider initialPreference="zh-CN">
+ <CreatorSessionProvider
+ initialJob={job}
+ service={{ applyAction: vi.fn(), runAgentTurn: vi.fn() } as never}
+ >
+ <WechatArticleWorkspace onBack={vi.fn()} />
+ </CreatorSessionProvider>
+ </LanguageProvider>
+ );
+
+ const notice = screen.getByRole('alert');
+ expect(notice).toHaveClass('video-translation-run-notice', 'is-error');
+ expect(notice).toHaveTextContent('请先配置图像生成服务');
+ expect(screen.getByRole('link', { name: '打开图像生成设置' })).toHaveAttribute(
+ 'href',
+ '#/settings?tab=ai-services&section=image'
+ );
+ expect(container.querySelector('.wechat-article-toast')).not.toBeInTheDocument();
+ expect(container.querySelector('.wechat-article-footer-stack > .wechat-article-run-notice + .wechat-article-actions')).toBeInTheDocument();
+ });
+});
+
+function readArticleEditorMarkdown(editor: HTMLElement): string {
+ return Array.from(editor.children).map(element => {
+ const markdown = element.getAttribute('data-markdown');
+ if (markdown !== null) return markdown;
+ const textarea = element instanceof HTMLTextAreaElement
+ ? element
+ : element.querySelector('textarea');
+ return textarea?.value ?? '';
+ }).join('');
+}
+
+function readPatch(request: CreatorActionRequest): Record<string, unknown> {
+ const patch = request.input.patch;
+ return typeof patch === 'object' && patch !== null && !Array.isArray(patch)
+ ? patch
+ : {};
+}
+
+function actionResponse(job: CreatorJob, action: string) {
+ return {
+ job: structuredClone(job),
+ receipt: {
+ actor: 'user' as const,
+ action,
+ summary: action,
+ affectedArtifacts: [],
+ newRevision: job.revision,
+ createdAt: job.updatedAt
+ }
+ };
+}
+
+function documentArtifacts(): CreatorJob['artifacts'] {
+ return [
+ documentArtifact('markdown', 'md', 'text/markdown', 128),
+ documentArtifact('html', 'html', 'text/html', 512),
+ documentArtifact('pdf', 'pdf', 'application/pdf', 2048)
+ ];
+}
+
+function documentArtifact(
+ format = 'markdown',
+ extension = 'md',
+ mimeType = 'text/markdown',
+ bytes = 128
+): CreatorJob['artifacts'][number] {
+ return {
+ id: format === 'markdown' ? 'article-document-1' : `article-document-${format}`,
+ jobId: 'creator_job_wechat_article_ui',
+ kind: 'article_document',
+ version: 1,
+ status: 'completed',
+ path: `/tmp/示例文章.${extension}`,
+ sourceArtifactIds: ['article-artifact-1'],
+ metadata: {
+ fileName: `示例文章.${extension}`,
+ mimeType,
+ documentFormat: format,
+ resultVersion: 1,
+ title: '示例文章',
+ bytes,
+ characterCount: 28,
+ layoutStyleId: 'business'
+ },
+ createdAt: '2026-09-07T08:01:01.000Z'
+ };
+}
+
+function articleImageArtifact(id: string, resultVersion: number, imageIndex: number): CreatorJob['artifacts'][number] {
+ return {
+ id,
+ jobId: 'creator_job_wechat_article_ui',
+ kind: 'article_image',
+ version: resultVersion,
+ status: 'completed',
+ path: `/tmp/${id}.png`,
+ sourceArtifactIds: ['article-artifact-1'],
+ metadata: {
+ fileName: `${id}.png`,
+ mimeType: 'image/png',
+ resultVersion,
+ imageIndex,
+ caption: resultVersion === 1 ? '旧版配图' : `新版配图 ${imageIndex}`,
+ placementHeading: `第 ${imageIndex} 节`,
+ imageStyleId: 'documentary'
+ },
+ createdAt: `2026-09-07T08:02:0${imageIndex}.000Z`
+ };
+}
+
+function manualArticleImageArtifact(id: string, originalFileName: string, index: number): CreatorJob['artifacts'][number] {
+ const extension = originalFileName.split('.').pop() || 'png';
+ return {
+ id,
+ jobId: 'creator_job_wechat_article_ui',
+ kind: 'article_image',
+ version: index,
+ status: 'completed',
+ path: `/tmp/${id}.${extension}`,
+ sourceArtifactIds: [],
+ metadata: {
+ fileName: `article-upload-${index}.${extension}`,
+ originalFileName,
+ mimeType: extension === 'webp' ? 'image/webp' : 'image/png',
+ source: 'local-upload'
+ },
+ createdAt: `2026-09-07T08:00:0${index}.000Z`
+ };
+}
+
+function sourceDocumentArtifact(id: string, fileName: string): CreatorJob['artifacts'][number] {
+ return {
+ id,
+ jobId: 'creator_job_wechat_article_inspiration',
+ kind: 'source_document',
+ version: 1,
+ status: 'completed',
+ path: `/tmp/${fileName}`,
+ sourceArtifactIds: [],
+ metadata: { fileName, bytes: 13, mimeType: 'text/markdown' },
+ createdAt: '2026-09-07T08:00:00.000Z'
+ };
+}
+
+function articleSourcesArtifact(id: string, automaticTranscriptCount = 0): CreatorJob['artifacts'][number] {
+ return {
+ id,
+ jobId: 'creator_job_wechat_article_inspiration',
+ kind: 'article_sources',
+ version: 1,
+ status: 'completed',
+ path: '/tmp/article-sources.json',
+ sourceArtifactIds: [],
+ metadata: {
+ fileName: 'article-sources.json',
+ mimeType: 'application/json',
+ sourceCount: 1,
+ automaticTranscriptCount
+ },
+ createdAt: '2026-09-07T08:00:01.000Z'
+ };
+}
+
+function sourceStage(status: 'succeeded' | 'failed'): CreatorJob['stages'][number] {
+ return {
+ id: `sources-stage-${status}`,
+ jobId: 'creator_job_wechat_article_inspiration',
+ stageId: 'sources',
+ executor: 'wechat-article',
+ status,
+ dispatchStatus: 'finished',
+ claimOwner: null,
+ claimExpiresAt: null,
+ attempt: 1,
+ idempotencyKey: null,
+ progress: { phase: status === 'succeeded' ? 'completed' : 'reading_video', message: 'youtube.com' },
+ errorCode: status === 'failed' ? 'creator_source_transcript_missing' : null,
+ errorMessage: status === 'failed' ? 'No subtitles are available for video' : null,
+ startedAt: '2026-09-07T08:00:00.000Z',
+ finishedAt: '2026-09-07T08:00:01.000Z'
+ };
+}
+
+function inspirationJob(sourceCount = 0): CreatorJob {
+ const createdAt = '2026-09-07T08:00:00.000Z';
+ return {
+ id: 'creator_job_wechat_article_inspiration',
+ projectId: 'project_1',
+ templateId: 'wechat-article',
+ templateVersion: 1,
+ status: 'draft',
+ revision: 0,
+ state: {
+ sourceLinks: Array.from({ length: sourceCount }, (_, index) => ({
+ id: `source-${index}`,
+ url: `https://example.com/${index}`,
+ kind: 'webpage',
+ label: `example.com/${index}`
+ })),
+ sourceDocumentArtifactIds: [],
+ currentStep: 0,
+ furthestStep: 0
+ },
+ agentThreadId: null,
+ stages: [],
+ artifacts: [],
+ activities: [],
+ createdAt,
+ updatedAt: createdAt
+ };
+}
+
+function articleJob(): CreatorJob {
+ const createdAt = '2026-09-07T08:00:00.000Z';
+ return {
+ id: 'creator_job_wechat_article_ui',
+ projectId: 'project_1',
+ templateId: 'wechat-article',
+ templateVersion: 1,
+ status: 'completed',
+ revision: 0,
+ state: {
+ topics: [{ id: 'topic-1', title: '示例文章', angle: '测试角度', summary: '测试摘要' }],
+ selectedTopicId: 'topic-1',
+ outline: '# 示例文章\n\n## 第一部分',
+ articleMarkdown: '# 示例文章\n\n**这是一段导语。**\n\n## 第一部分\n\n正文内容。',
+ layoutStyleId: 'minimal',
+ currentStep: 4,
+ furthestStep: 4
+ },
+ agentThreadId: null,
+ stages: [],
+ artifacts: [{
+ id: 'article-artifact-1',
+ jobId: 'creator_job_wechat_article_ui',
+ kind: 'article_markdown',
+ version: 1,
+ status: 'completed',
+ path: '/tmp/wechat-article.md',
+ sourceArtifactIds: [],
+ metadata: { fileName: 'wechat-article.md' },
+ createdAt
+ }],
+ activities: [],
+ createdAt,
+ updatedAt: createdAt
+ };
+}
diff --git a/apps/web/src/features/dashboard/WechatArticleWorkspace.tsx b/apps/web/src/features/dashboard/WechatArticleWorkspace.tsx
new file mode 100644
index 00000000..72996587
--- /dev/null
+++ b/apps/web/src/features/dashboard/WechatArticleWorkspace.tsx
@@ -0,0 +1,2108 @@
+import {
+ wechatArticleLayoutStyles,
+ wechatArticleSourceLimit,
+ type CreatorArtifact,
+ type CreatorJson,
+ type WechatArticleImageStyleId,
+ type WechatArticleLayoutCategoryId,
+ type WechatArticleLayoutStyleId,
+ type WechatArticlePresetId,
+ type WechatArticlePresetCategoryId,
+ type WechatArticleSourceLink,
+ type WechatArticleTopic
+} from '@opencreator/protocol';
+import {
+ localizeWritingTemplate,
+ normalizeWritingTemplateId,
+ writingTemplates as wechatArticlePresetCatalog,
+ type WritingTemplateDomainId
+} from '@opencreator/writing-templates';
+import {
+ CircleAlert,
+ Check,
+ Clipboard,
+ ChevronDown,
+ Download,
+ ExternalLink,
+ FileText,
+ Image as ImageIcon,
+ ImagePlus,
+ ImageUp,
+ Library,
+ Link2,
+ LoaderCircle,
+ Minus,
+ PackageOpen,
+ Plus,
+ Search,
+ Settings2,
+ Sparkles,
+ Trash2,
+ Upload,
+ X
+} from 'lucide-react';
+import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties } from 'react';
+import { createPortal } from 'react-dom';
+import { copyRichContent } from '../../components/markdown/clipboard.js';
+import { MarkdownRenderer } from '../../components/markdown/MarkdownRenderer.js';
+import { useAppLanguage } from '../../i18n/LanguageProvider.js';
+import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';
+import CreatorTaskSummary from './CreatorTaskSummary.js';
+import CreatorToolShell from './CreatorToolShell.js';
+import { useOptionalCreatorSession } from './creator-session-store.js';
+
+type ArticleStep = 0 | 1 | 2 | 3 | 4 | 5;
+type ArticleWorkspacePhase = 'compose' | 'result';
+type ArticleResultTab = 'outputs' | 'images' | 'settings';
+type ArticleToast = { id: number; message: string; tone: 'error' | 'success' };
+type ArticleEditorPart =
+ | { kind: 'text'; markdown: string }
+ | { kind: 'image'; markdown: string; alt: string; href: string; src: string; artifactId: string };
+type ArticleImageUploadIntent =
+ | { mode: 'insert'; partIndex: number; offset: number }
+ | { mode: 'replace'; partIndex: number; artifactId: string; href: string };
+type ArticleImageDropTarget = { partIndex: number; offset: number; top: number };
+type ArticleTemplateCategory = 'all' | WechatArticlePresetCategoryId;
+type ArticleTemplateTopFilter = 'all' | 'popular' | 'community' | WritingTemplateDomainId;
+type TemplateLibraryAnchor = { left: number; width: number };
+
+const stepLabels = [
+ ['内容灵感', 'Inspiration'],
+ ['写作要求', 'Writing brief'],
+ ['选择选题', 'Choose topic'],
+ ['确认大纲', 'Review outline'],
+ ['编辑文章', 'Edit article'],
+ ['排版预览', 'Layout & preview']
+] as const;
+
+const articleTemplateCategories: ReadonlyArray<{
+ id: ArticleTemplateCategory;
+ zh: string;
+ en: string;
+}> = [
+ { id: 'all', zh: '全部模板', en: 'All templates' },
+ { id: 'analysis', zh: '深度观点', en: 'Analysis' },
+ { id: 'story', zh: '故事人物', en: 'Stories' },
+ { id: 'practical', zh: '教程干货', en: 'Practical' },
+ { id: 'news', zh: '热点解读', en: 'News' }
+];
+
+const articleTemplateTopFilters: ReadonlyArray<{
+ id: ArticleTemplateTopFilter;
+ zh: string;
+ en: string;
+}> = [
+ { id: 'all', zh: '全部', en: 'All' },
+ { id: 'popular', zh: '热门', en: 'Popular' },
+ { id: 'community', zh: '社区', en: 'Community' },
+ { id: 'technology', zh: '科技', en: 'Technology' },
+ { id: 'finance', zh: '财经', en: 'Finance' },
+ { id: 'emotion', zh: '情感', en: 'Relationships' },
+ { id: 'workplace', zh: '职场', en: 'Workplace' },
+ { id: 'education', zh: '教育', en: 'Education' },
+ { id: 'research', zh: '科研', en: 'Research' },
+ { id: 'lifestyle', zh: '生活', en: 'Lifestyle' }
+];
+
+const articleTemplateInlineFilters = articleTemplateTopFilters.filter(filter => (
+ filter.id !== 'all' && filter.id !== 'community'
+));
+
+const articleImageDensityOptions = [
+ { id: 'few', count: 2, zh: '少图', en: 'Few' },
+ { id: 'balanced', count: 5, zh: '适中', en: 'Balanced' },
+ { id: 'many', count: 8, zh: '多图', en: 'Many' }
+] as const;
+
+const articleLayoutCategoryOptions: ReadonlyArray<{
+ id: WechatArticleLayoutCategoryId;
+ zh: string;
+ en: string;
+}> = [
+ { id: 'recommended', zh: '推荐', en: 'Recommended' },
+ { id: 'technology', zh: '科技', en: 'Technology' },
+ { id: 'business', zh: '商业', en: 'Business' },
+ { id: 'news', zh: '资讯', en: 'News' },
+ { id: 'lifestyle', zh: '生活', en: 'Lifestyle' },
+ { id: 'humanities', zh: '人文', en: 'Humanities' }
+];
+
+const articleImageStyleOptions: ReadonlyArray<{
+ id: WechatArticleImageStyleId;
+ zh: string;
+ en: string;
+ descriptionZh: string;
+ descriptionEn: string;
+ previewSrc: string;
+}> = [
+ { id: 'editorial', zh: '杂志视觉', en: 'Editorial', descriptionZh: '克制、有重点的编辑配图', descriptionEn: 'Polished editorial composition', previewSrc: '/dashboard/wechat-article/image-styles/editorial-v2.webp' },
+ { id: 'minimal', zh: '极简概念', en: 'Minimal', descriptionZh: '留白与视觉隐喻', descriptionEn: 'Negative space and visual metaphor', previewSrc: '/dashboard/wechat-article/image-styles/minimal-v2.webp' },
+ { id: 'documentary', zh: '纪实摄影', en: 'Documentary', descriptionZh: '真实场景与自然光线', descriptionEn: 'Natural, credible real-world scenes', previewSrc: '/dashboard/wechat-article/image-styles/documentary-v2.webp' },
+ { id: 'illustration', zh: '现代插画', en: 'Illustration', descriptionZh: '叙事感与印刷质感', descriptionEn: 'Narrative editorial illustration', previewSrc: '/dashboard/wechat-article/image-styles/illustration.webp' },
+ { id: 'three-dimensional', zh: '3D 视觉', en: '3D Visual', descriptionZh: '材质、空间与柔和光影', descriptionEn: 'Tactile materials and soft lighting', previewSrc: '/dashboard/wechat-article/image-styles/three-dimensional-v2.webp' },
+ { id: 'infographic', zh: '数据图解', en: 'Infographic', descriptionZh: '结构清晰的信息可视化', descriptionEn: 'Structured information visualization', previewSrc: '/dashboard/wechat-article/image-styles/infographic.webp' }
+];
+
+export default function WechatArticleWorkspace(props: {
+ onBack(): void;
+ promptHint?: string;
+}) {
+ const l = useLocalizedCopy();
+ const { language } = useAppLanguage();
+ const wechatArticlePresets = useMemo(
+ () => wechatArticlePresetCatalog.map(preset => localizeWritingTemplate(preset, language)),
+ [language]
+ );
+ const session = useOptionalCreatorSession();
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const articleImageInputRef = useRef<HTMLInputElement>(null);
+ const articleImageUploadIntentRef = useRef<ArticleImageUploadIntent>();
+ const activeArticleSelectionRef = useRef<{ partIndex: number; offset: number }>();
+ const draggedArticleImagePartRef = useRef<number>();
+ const templateLibraryAnchorRef = useRef<HTMLDivElement>(null);
+ const articlePreviewRef = useRef<HTMLDivElement>(null);
+ const toastIdRef = useRef(0);
+ const pendingSourceParseRef = useRef(false);
+ const [currentStep, setCurrentStep] = useState<ArticleStep>(() => readStep(session?.state.currentStep));
+ const [furthestStep, setFurthestStep] = useState<ArticleStep>(() => readStep(session?.state.furthestStep));
+ const [sourceLinks, setSourceLinks] = useState<WechatArticleSourceLink[]>(() => readLinks(session?.state.sourceLinks));
+ const [urlInput, setUrlInput] = useState('');
+ const [writingPrompt, setWritingPrompt] = useState(() => readString(session?.state.writingPrompt));
+ const [topicCount, setTopicCount] = useState(() => readTopicCount(session?.state.topicCount));
+ const [topics, setTopics] = useState<WechatArticleTopic[]>(() => readTopics(session?.state.topics));
+ const [selectedTopicId, setSelectedTopicId] = useState(() => readString(session?.state.selectedTopicId));
+ const [outline, setOutline] = useState(() => readString(session?.state.outline));
+ const initialPreset = readPreset(session?.state.presetId);
+ const [presetId, setPresetId] = useState<WechatArticlePresetId>(initialPreset);
+ const [templatePrompt, setTemplatePrompt] = useState(() => (
+ readString(session?.state.templatePrompt)
+ || wechatArticlePresets.find(preset => preset.id === initialPreset)?.instructions
+ || ''
+ ));
+ const [layoutStyleId, setLayoutStyleId] = useState<WechatArticleLayoutStyleId>(() => (
+ readLayoutStyle(session?.state.layoutStyleId)
+ ));
+ const [layoutCategoryId, setLayoutCategoryId] = useState<WechatArticleLayoutCategoryId>('recommended');
+ const [templateLibraryOpen, setTemplateLibraryOpen] = useState(false);
+ const [templateLibraryAnchor, setTemplateLibraryAnchor] = useState<TemplateLibraryAnchor>();
+ const [templateQuery, setTemplateQuery] = useState('');
+ const [templateTopFilter, setTemplateTopFilter] = useState<ArticleTemplateTopFilter>('popular');
+ const [templateCategory, setTemplateCategory] = useState<ArticleTemplateCategory>('all');
+ const [previewPresetId, setPreviewPresetId] = useState<WechatArticlePresetId>(initialPreset);
+ const [articleMarkdown, setArticleMarkdown] = useState(() => readString(session?.state.articleMarkdown));
+ const [autoGenerateImages, setAutoGenerateImages] = useState(() => readBoolean(session?.state.autoGenerateImages, true));
+ const [articleImageCount, setArticleImageCount] = useState(() => readArticleImageCount(session?.state.articleImageCount));
+ const [articleImageStyleId, setArticleImageStyleId] = useState<WechatArticleImageStyleId>(() => readArticleImageStyle(session?.state.articleImageStyleId));
+ const [articleImageUrls, setArticleImageUrls] = useState<Record<string, string>>({});
+ const [uploadingArticleImage, setUploadingArticleImage] = useState(false);
+ const [draggedArticleImagePartIndex, setDraggedArticleImagePartIndex] = useState<number>();
+ const [articleImageDropTarget, setArticleImageDropTarget] = useState<ArticleImageDropTarget>();
+ const [copyingArticle, setCopyingArticle] = useState(false);
+ const [uploading, setUploading] = useState(false);
+ const [sourceDragActive, setSourceDragActive] = useState(false);
+ const [error, setError] = useState('');
+ const [toast, setToast] = useState<ArticleToast | null>(null);
+ const [dismissedErrorKey, setDismissedErrorKey] = useState('');
+ const [taskControlPending, setTaskControlPending] = useState<'canceling' | 'resuming'>();
+
+ const selectedDocumentIds = useMemo(
+ () => readStringArray(session?.state.sourceDocumentArtifactIds),
+ [session?.state.sourceDocumentArtifactIds]
+ );
+ const documentArtifacts = useMemo(() => selectedDocuments(
+ session?.job.artifacts ?? [],
+ selectedDocumentIds
+ ), [session?.job.artifacts, selectedDocumentIds]);
+ const sourceCount = sourceLinks.length + selectedDocumentIds.length;
+ const remainingSourceCount = Math.max(0, wechatArticleSourceLimit - sourceCount);
+ const sourceLimitReached = remainingSourceCount === 0;
+ const sourcesArtifact = latestArtifact(session?.job.artifacts ?? [], 'article_sources');
+ const topicsArtifact = latestArtifact(session?.job.artifacts ?? [], 'article_topics');
+ const outlineArtifact = latestArtifact(session?.job.artifacts ?? [], 'article_outline');
+ const articleArtifact = latestArtifact(session?.job.artifacts ?? [], 'article_markdown');
+ const manualArticleImageArtifactIds = useMemo(
+ () => readStringArray(session?.state.manualArticleImageArtifactIds),
+ [session?.state.manualArticleImageArtifactIds]
+ );
+ const hiddenArticleImageArtifactIds = useMemo(
+ () => readStringArray(session?.state.hiddenArticleImageArtifactIds),
+ [session?.state.hiddenArticleImageArtifactIds]
+ );
+ const articleImagePlacementCustomized = readBoolean(session?.state.articleImagePlacementCustomized, false);
+ const generatedArticleImageArtifacts = useMemo(
+ () => latestArticleImages(session?.job.artifacts ?? [])
+ .filter(artifact => !hiddenArticleImageArtifactIds.includes(artifact.id)),
+ [hiddenArticleImageArtifactIds, session?.job.artifacts]
+ );
+ const manualArticleImageArtifacts = useMemo(
+ () => selectedManualArticleImages(session?.job.artifacts ?? [], manualArticleImageArtifactIds)
+ .filter(artifact => !hiddenArticleImageArtifactIds.includes(artifact.id)),
+ [hiddenArticleImageArtifactIds, manualArticleImageArtifactIds, session?.job.artifacts]
+ );
+ const articleImageArtifacts = useMemo(
+ () => [...generatedArticleImageArtifacts, ...manualArticleImageArtifacts],
+ [generatedArticleImageArtifacts, manualArticleImageArtifacts]
+ );
+ const articleImageSetKey = useMemo(
+ () => generatedArticleImageArtifacts.map(artifact => artifact.id).join('|'),
+ [generatedArticleImageArtifacts]
+ );
+ const articleImagePreviewSources = useMemo(() => {
+ const sources: Record<string, string> = {};
+ for (const artifact of articleImageArtifacts) {
+ const fileName = readString(artifact.metadata.fileName);
+ const url = articleImageUrls[artifact.id];
+ if (!fileName || !url) continue;
+ sources[fileName] = url;
+ sources[`./${fileName}`] = url;
+ }
+ return sources;
+ }, [articleImageArtifacts, articleImageUrls]);
+ const articleImageArtifactsByHref = useMemo(() => {
+ const artifacts: Record<string, CreatorArtifact> = {};
+ for (const artifact of articleImageArtifacts) {
+ const fileName = readString(artifact.metadata.fileName);
+ if (!fileName) continue;
+ artifacts[fileName] = artifact;
+ artifacts[`./${fileName}`] = artifact;
+ }
+ return artifacts;
+ }, [articleImageArtifacts]);
+ const articleEditorParts = useMemo(
+ () => splitArticleEditorParts(articleMarkdown, articleImagePreviewSources, articleImageArtifactsByHref),
+ [articleImageArtifactsByHref, articleImagePreviewSources, articleMarkdown]
+ );
+ const articleDocumentArtifacts = useMemo(
+ () => latestArticleDocuments(session?.job.artifacts ?? []),
+ [session?.job.artifacts]
+ );
+ const finalDocumentArtifact = articleDocumentArtifacts.find(artifact => readString(artifact.metadata.documentFormat) === 'markdown')
+ ?? articleDocumentArtifacts[0];
+ const [workspacePhase, setWorkspacePhase] = useState<ArticleWorkspacePhase>(() => (
+ readWorkspacePhase(session?.state.workspacePhase, finalDocumentArtifact !== undefined)
+ ));
+ const [resultTab, setResultTab] = useState<ArticleResultTab>('outputs');
+ const knownDocumentArtifactIdRef = useRef(finalDocumentArtifact?.id);
+ const placedArticleImageSetRef = useRef('');
+ const latestStage = session?.job.stages.at(-1);
+ const running = latestStage?.status === 'queued' || latestStage?.status === 'running';
+ const documentRunning = running && latestStage?.stageId === 'document';
+ const imageRunning = running && latestStage?.stageId === 'images';
+ const presetValidationError = isPresetValidationError(session?.error?.message ?? '');
+ const sessionErrorMessage = uploading || toast !== null || presetValidationError
+ ? ''
+ : formatArticleSessionError(session?.error?.code, session?.error?.message, l);
+ const visibleError = error || (latestStage?.status === 'failed'
+ ? formatArticleStageError(latestStage.errorCode, latestStage.errorMessage, readString(latestStage.progress.message), l)
+ : sessionErrorMessage);
+ const visibleErrorKey = visibleError
+ ? error
+ ? `local:${visibleError}`
+ : latestStage?.status === 'failed'
+ ? `stage:${latestStage.id}:${visibleError}`
+ : `session:${session?.error?.code ?? ''}:${visibleError}`
+ : '';
+ const configurationIssue = latestStage?.status === 'failed'
+ ? latestStage.errorCode === 'creator_llm_config_missing'
+ ? {
+ href: '#/settings?tab=ai-services&section=text',
+ label: l('打开文本模型设置', 'Open text model settings')
+ }
+ : latestStage.errorCode === 'creator_image_config_missing'
+ ? {
+ href: '#/settings?tab=ai-services&section=image',
+ label: l('打开图像生成设置', 'Open image generation settings')
+ }
+ : null
+ : null;
+ const activeToast = toast ?? (visibleError && configurationIssue === null && visibleErrorKey !== dismissedErrorKey
+ ? { id: -1, message: visibleError, tone: 'error' as const }
+ : null);
+ const selectedTopic = topics.find(topic => topic.id === selectedTopicId);
+ const selectedPreset = wechatArticlePresets.find(preset => preset.id === presetId);
+ const selectedLayout = wechatArticleLayoutStyles.find(style => style.id === layoutStyleId);
+ const selectedArticleImageStyle = articleImageStyleOptions.find(style => style.id === articleImageStyleId);
+ const articleCharacterCount = useMemo(() => countArticleCharacters(articleMarkdown), [articleMarkdown]);
+ const filteredLayoutStyles = useMemo(
+ () => wechatArticleLayoutStyles.filter(style => style.categories.includes(layoutCategoryId)),
+ [layoutCategoryId]
+ );
+ const topFilteredPresets = useMemo(() => wechatArticlePresets.filter(preset => {
+ if (templateTopFilter === 'all') return true;
+ if (templateTopFilter === 'popular') return preset.status === 'featured';
+ if (templateTopFilter === 'community') return preset.source.type === 'github';
+ return preset.domains.includes(templateTopFilter);
+ }), [templateTopFilter, wechatArticlePresets]);
+ const filteredPresets = useMemo(() => {
+ const query = templateQuery.trim().toLocaleLowerCase();
+ return topFilteredPresets.filter(preset => {
+ const matchesCategory = templateCategory === 'all' || preset.categoryId === templateCategory;
+ const matchesQuery = !query || [preset.name, preset.description, preset.author, preset.source.repository ?? '', ...preset.tags]
+ .some(value => value.toLocaleLowerCase().includes(query));
+ return matchesCategory && matchesQuery;
+ });
+ }, [templateCategory, templateQuery, topFilteredPresets]);
+ const previewPreset = filteredPresets.find(preset => preset.id === previewPresetId) ?? filteredPresets[0];
+
+ useEffect(() => {
+ if (activeToast === null) return;
+ const timer = window.setTimeout(() => {
+ if (toast !== null) {
+ setToast(current => current?.id === toast.id ? null : current);
+ return;
+ }
+ setDismissedErrorKey(visibleErrorKey);
+ }, 4_000);
+ return () => window.clearTimeout(timer);
+ }, [activeToast?.id, activeToast?.message, toast?.id, visibleErrorKey]);
+
+ useEffect(() => {
+ if (!visibleErrorKey) setDismissedErrorKey('');
+ }, [visibleErrorKey]);
+
+ useEffect(() => {
+ const catalogPreset = wechatArticlePresetCatalog.find(preset => preset.id === presetId);
+ const localizedPreset = wechatArticlePresets.find(preset => preset.id === presetId);
+ if (catalogPreset === undefined || localizedPreset === undefined) return;
+ const defaultInstructions = [
+ catalogPreset.instructions,
+ ...Object.values(catalogPreset.localizations).map(localization => localization.instructions)
+ ];
+ if (!defaultInstructions.includes(templatePrompt) || templatePrompt === localizedPreset.instructions) return;
+ setTemplatePrompt(localizedPreset.instructions);
+ session?.updateDraft({ templatePrompt: localizedPreset.instructions });
+ }, [language, presetId, session, templatePrompt, wechatArticlePresets]);
+
+ useEffect(() => {
+ if (session === null || articleImageArtifacts.length === 0 || typeof URL.createObjectURL !== 'function') {
+ setArticleImageUrls({});
+ return undefined;
+ }
+ let active = true;
+ const objectUrls: string[] = [];
+ void Promise.all(articleImageArtifacts.map(async artifact => {
+ const response = await session.openArtifact(artifact.id);
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ const url = URL.createObjectURL(await response.blob());
+ objectUrls.push(url);
+ return [artifact.id, url] as const;
+ })).then(entries => {
+ if (active) setArticleImageUrls(Object.fromEntries(entries));
+ }).catch(() => {
+ if (active) setArticleImageUrls({});
+ });
+ return () => {
+ active = false;
+ objectUrls.forEach(url => URL.revokeObjectURL(url));
+ };
+ }, [articleImageArtifacts, session?.openArtifact]);
+
+ useEffect(() => {
+ if (!presetValidationError || !session?.error?.message) return;
+ showToast(formatArticleSessionError(session.error.code, session.error.message, l), 'error');
+ session.clearError();
+ }, [presetValidationError, session?.error?.code, session?.error?.message]);
+
+ useEffect(() => {
+ if (!templateLibraryOpen) return;
+ const update = () => updateTemplateLibraryAnchor();
+ update();
+ window.addEventListener('resize', update);
+ window.addEventListener('scroll', update, true);
+ return () => {
+ window.removeEventListener('resize', update);
+ window.removeEventListener('scroll', update, true);
+ };
+ }, [templateLibraryOpen]);
+
+ useEffect(() => {
+ if (!pendingSourceParseRef.current || sourcesArtifact === undefined) return;
+ pendingSourceParseRef.current = false;
+ const next = Math.max(furthestStep, 1) as ArticleStep;
+ setCurrentStep(1);
+ setFurthestStep(next);
+ session?.updateDraft({ currentStep: 1, furthestStep: next });
+ const parsedCount = readNumber(sourcesArtifact.metadata.sourceCount);
+ const automaticCount = readNumber(sourcesArtifact.metadata.automaticTranscriptCount);
+ showToast(automaticCount > 0
+ ? l(`已解析 ${parsedCount} 个内容灵感,其中 ${automaticCount} 个视频使用自动字幕`, `${parsedCount} inspiration sources parsed; ${automaticCount} video transcripts are automatic.`)
+ : l(`已解析 ${parsedCount} 个内容灵感`, `${parsedCount} inspiration sources parsed.`), 'success');
+ }, [sourcesArtifact?.id]);
+
+ useEffect(() => {
+ if (
+ pendingSourceParseRef.current
+ && latestStage?.stageId === 'sources'
+ && (latestStage.status === 'failed' || latestStage.status === 'canceled')
+ ) {
+ pendingSourceParseRef.current = false;
+ }
+ }, [latestStage?.id, latestStage?.status]);
+
+ useEffect(() => {
+ if (!templateLibraryOpen) return;
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event.key === 'Escape') setTemplateLibraryOpen(false);
+ };
+ window.addEventListener('keydown', handleKeyDown);
+ return () => window.removeEventListener('keydown', handleKeyDown);
+ }, [templateLibraryOpen]);
+
+ useEffect(() => {
+ if (
+ finalDocumentArtifact === undefined
+ || finalDocumentArtifact.id === knownDocumentArtifactIdRef.current
+ ) return;
+ knownDocumentArtifactIdRef.current = finalDocumentArtifact.id;
+ setWorkspacePhase('result');
+ setResultTab('outputs');
+ session?.updateDraft({ workspacePhase: 'result' });
+ }, [finalDocumentArtifact?.id]);
+
+ useEffect(() => {
+ const saved = readTopics(session?.state.topics);
+ if (saved.length > 0) {
+ setTopics(saved);
+ advanceTo(2);
+ return;
+ }
+ const generated = readTopics(topicsArtifact?.metadata.topics);
+ if (generated.length === 0) return;
+ setTopics(generated);
+ setSelectedTopicId(current => generated.some(topic => topic.id === current) ? current : '');
+ advanceTo(2);
+ }, [topicsArtifact?.id]);
+
+ useEffect(() => {
+ const saved = readString(session?.state.outline);
+ if (saved) {
+ setOutline(saved);
+ advanceTo(3);
+ return;
+ }
+ const generated = readString(outlineArtifact?.metadata.outline);
+ if (!generated) return;
+ setOutline(generated);
+ advanceTo(3);
+ }, [outlineArtifact?.id]);
+
+ useEffect(() => {
+ if (session === null || articleArtifact === undefined) return;
+ const saved = readString(session.state.articleMarkdown);
+ if (saved) {
+ setArticleMarkdown(saved);
+ advanceTo(4);
+ return;
+ }
+ let active = true;
+ void session.openArtifact(articleArtifact.id)
+ .then(async response => {
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ const markdown = await response.text();
+ if (!active) return;
+ setArticleMarkdown(markdown.trim());
+ advanceTo(4);
+ })
+ .catch(cause => {
+ if (active) setError(cause instanceof Error ? cause.message : String(cause));
+ });
+ return () => { active = false; };
+ }, [articleArtifact?.id]);
+
+ useEffect(() => {
+ if (!articleImageSetKey || !articleMarkdown.trim() || placedArticleImageSetRef.current === articleImageSetKey) return;
+ placedArticleImageSetRef.current = articleImageSetKey;
+ if (
+ articleImagePlacementCustomized
+ && generatedArticleImageArtifacts.every(artifact => articleMarkdown.includes(`](${articleImageMarkdownHref(artifact)})`))
+ ) return;
+ const nextMarkdown = insertGeneratedArticleImages(articleMarkdown, generatedArticleImageArtifacts);
+ if (nextMarkdown === articleMarkdown) return;
+ setArticleMarkdown(nextMarkdown);
+ session?.updateDraft({ articleMarkdown: nextMarkdown });
+ showToast(l('配图已插入正文对应位置', 'Images were inserted into the relevant article sections.'), 'success');
+ }, [articleImagePlacementCustomized, articleImageSetKey, articleMarkdown, generatedArticleImageArtifacts, session]);
+
+ function advanceTo(step: ArticleStep) {
+ setCurrentStep(previous => Math.max(previous, step) as ArticleStep);
+ setFurthestStep(previous => Math.max(previous, step) as ArticleStep);
+ }
+
+ function openStep(step: ArticleStep) {
+ if (step > furthestStep) return;
+ setCurrentStep(step);
+ session?.updateDraft({ currentStep: step, furthestStep: Math.max(furthestStep, step) });
+ }
+
+ function updateArticleEditorPart(partIndex: number, markdown: string) {
+ const nextMarkdown = articleEditorParts
+ .map((part, index) => index === partIndex && part.kind === 'text' ? markdown : part.markdown)
+ .join('');
+ setArticleMarkdown(nextMarkdown);
+ session?.updateDraft({ articleMarkdown: nextMarkdown });
+ }
+
+ function rememberArticleEditorSelection(partIndex: number, offset: number) {
+ activeArticleSelectionRef.current = { partIndex, offset };
+ }
+
+ function openArticleImagePicker(intent?: ArticleImageUploadIntent) {
+ if (uploadingArticleImage) return;
+ if (intent !== undefined) {
+ articleImageUploadIntentRef.current = intent;
+ } else {
+ const activeSelection = activeArticleSelectionRef.current;
+ if (activeSelection !== undefined && articleEditorParts[activeSelection.partIndex]?.kind === 'text') {
+ articleImageUploadIntentRef.current = { mode: 'insert', ...activeSelection };
+ } else {
+ let partIndex = articleEditorParts.length - 1;
+ while (partIndex > 0 && articleEditorParts[partIndex]?.kind !== 'text') partIndex -= 1;
+ const part = articleEditorParts[partIndex];
+ articleImageUploadIntentRef.current = {
+ mode: 'insert',
+ partIndex: Math.max(0, partIndex),
+ offset: part?.kind === 'text' ? part.markdown.length : articleMarkdown.length
+ };
+ }
+ }
+ if (articleImageInputRef.current !== null) articleImageInputRef.current.value = '';
+ articleImageInputRef.current?.click();
+ }
+
+ async function uploadArticleImage(file: File) {
+ if (session === null || uploadingArticleImage) return;
+ const intent = articleImageUploadIntentRef.current;
+ if (intent === undefined) return;
+ setUploadingArticleImage(true);
+ try {
+ const artifact = await session.uploadArticleImage(file);
+ const fileName = readString(artifact.metadata.fileName);
+ if (!fileName) throw new Error('Uploaded article image has no file name');
+ const alt = imageAltFromFileName(readString(artifact.metadata.originalFileName) || file.name, l);
+ const imageMarkdown = `![${alt}](./${fileName})`;
+ let nextMarkdown = articleEditorParts.map((part, index) => {
+ if (index !== intent.partIndex) return part.markdown;
+ if (intent.mode === 'replace' && part.kind === 'image') return imageMarkdown;
+ if (intent.mode !== 'insert' || part.kind !== 'text') return part.markdown;
+ return insertMarkdownImageAt(part.markdown, intent.offset, imageMarkdown);
+ }).join('');
+ if (intent.mode === 'insert' && articleEditorParts[intent.partIndex]?.kind !== 'text') {
+ nextMarkdown = insertMarkdownImageAt(articleMarkdown, articleMarkdown.length, imageMarkdown);
+ }
+ const replacedArtifact = intent.mode === 'replace'
+ ? articleImageArtifacts.find(candidate => candidate.id === intent.artifactId)
+ : undefined;
+ const replacingGeneratedImage = replacedArtifact !== undefined
+ && replacedArtifact.metadata.source !== 'local-upload';
+ const hiddenIds = replacingGeneratedImage
+ ? [...new Set([...hiddenArticleImageArtifactIds, replacedArtifact.id])]
+ : hiddenArticleImageArtifactIds;
+ const nextManualIds = intent.mode === 'replace'
+ && replacedArtifact?.metadata.source === 'local-upload'
+ && !nextMarkdown.includes(`](${intent.href})`)
+ ? [...new Set([...manualArticleImageArtifactIds.filter(id => id !== replacedArtifact.id), artifact.id])]
+ : undefined;
+ setArticleMarkdown(nextMarkdown);
+ session.updateDraft({
+ articleMarkdown: nextMarkdown,
+ hiddenArticleImageArtifactIds: hiddenIds,
+ ...(nextManualIds === undefined ? {} : { manualArticleImageArtifactIds: nextManualIds })
+ });
+ showToast(intent.mode === 'replace'
+ ? l('图片已替换', 'Image replaced.')
+ : l('图片已插入正文', 'Image inserted into the article.'), 'success');
+ } catch (cause) {
+ showToast(formatArticleImageUploadError(cause, l), 'error');
+ } finally {
+ setUploadingArticleImage(false);
+ articleImageUploadIntentRef.current = undefined;
+ }
+ }
+
+ function removeArticleImage(partIndex: number, artifactId: string, href: string) {
+ const nextMarkdown = articleEditorParts
+ .map((part, index) => index === partIndex && part.kind === 'image' ? '' : part.markdown)
+ .join('')
+ .replace(/\n{3,}/gu, '\n\n');
+ const artifact = articleImageArtifacts.find(candidate => candidate.id === artifactId);
+ const hiddenIds = artifact?.metadata.source === 'local-upload'
+ ? hiddenArticleImageArtifactIds
+ : [...new Set([...hiddenArticleImageArtifactIds, artifactId])];
+ const nextManualIds = artifact?.metadata.source === 'local-upload'
+ && !nextMarkdown.includes(`](${href})`)
+ ? manualArticleImageArtifactIds.filter(id => id !== artifactId)
+ : manualArticleImageArtifactIds;
+ setArticleMarkdown(nextMarkdown);
+ session?.updateDraft({
+ articleMarkdown: nextMarkdown,
+ hiddenArticleImageArtifactIds: hiddenIds,
+ manualArticleImageArtifactIds: nextManualIds
+ });
+ showToast(l('图片已从正文移除', 'Image removed from the article.'), 'success');
+ }
+
+ function moveArticleImage(targetPartIndex: number, offset: number) {
+ const sourcePartIndex = draggedArticleImagePartRef.current;
+ const sourcePart = sourcePartIndex === undefined ? undefined : articleEditorParts[sourcePartIndex];
+ const targetPart = articleEditorParts[targetPartIndex];
+ if (sourcePart?.kind !== 'image' || targetPart?.kind !== 'text') return;
+ const nextMarkdown = articleEditorParts.map((part, index) => {
+ if (index === sourcePartIndex) return '';
+ if (index === targetPartIndex) return insertMarkdownImageAt(part.markdown, offset, sourcePart.markdown);
+ return part.markdown;
+ }).join('').replace(/\n{3,}/gu, '\n\n');
+ setArticleMarkdown(nextMarkdown);
+ session?.updateDraft({
+ articleMarkdown: nextMarkdown,
+ articleImagePlacementCustomized: true
+ });
+ draggedArticleImagePartRef.current = undefined;
+ setDraggedArticleImagePartIndex(undefined);
+ setArticleImageDropTarget(undefined);
+ showToast(l('图片位置已更新', 'Image position updated.'), 'success');
+ }
+
+ function addSourceLink() {
+ setError('');
+ let url: URL;
+ try {
+ url = new URL(urlInput.trim());
+ if (!['http:', 'https:'].includes(url.protocol)) throw new Error();
+ } catch {
+ setError(l('请输入有效的网页或视频链接', 'Enter a valid webpage or video URL.'));
+ return;
+ }
+ if (sourceLinks.some(link => link.url === url.toString())) {
+ setError(l('这个链接已经添加过了', 'This URL has already been added.'));
+ return;
+ }
+ if (sourceLimitReached) {
+ setError(l(`内容灵感最多添加 ${wechatArticleSourceLimit} 个`, `You can add up to ${wechatArticleSourceLimit} inspiration sources.`));
+ return;
+ }
+ const kind = isVideoUrl(url) ? 'video' : 'webpage';
+ const next = [...sourceLinks, {
+ id: createId('source'),
+ url: url.toString(),
+ kind,
+ label: url.hostname
+ } satisfies WechatArticleSourceLink];
+ setSourceLinks(next);
+ setUrlInput('');
+ session?.updateDraft({ sourceLinks: next });
+ }
+
+ function removeSourceLink(id: string) {
+ const next = sourceLinks.filter(link => link.id !== id);
+ setSourceLinks(next);
+ session?.updateDraft({ sourceLinks: next });
+ }
+
+ function removeDocument(id: string) {
+ const next = selectedDocumentIds.filter(artifactId => artifactId !== id);
+ session?.updateDraft({ sourceDocumentArtifactIds: next });
+ }
+
+ async function uploadDocuments(files: FileList | File[] | null) {
+ if (session === null || files === null || files.length === 0) return;
+ const selectedFiles = Array.from(files);
+ if (selectedFiles.length > remainingSourceCount) {
+ showToast(remainingSourceCount === 0
+ ? l(`内容灵感最多添加 ${wechatArticleSourceLimit} 个`, `You can add up to ${wechatArticleSourceLimit} inspiration sources.`)
+ : l(`还可以添加 ${remainingSourceCount} 个内容灵感,请减少本次选择的文件`, `You can add ${remainingSourceCount} more inspiration sources. Select fewer files.`), 'error');
+ if (fileInputRef.current) fileInputRef.current.value = '';
+ return;
+ }
+ setUploading(true);
+ setError('');
+ setToast(null);
+ try {
+ for (const file of selectedFiles) await session.uploadSourceDocument(file);
+ showToast(l('文件已加入内容灵感', 'Files added to inspiration.'), 'success');
+ } catch (cause) {
+ session.clearError();
+ showToast(formatDocumentUploadError(cause, l), 'error');
+ } finally {
+ setUploading(false);
+ if (fileInputRef.current) fileInputRef.current.value = '';
+ }
+ }
+
+ function openFilePicker() {
+ if (fileInputRef.current === null || sourceLimitReached || uploading) return;
+ fileInputRef.current.value = '';
+ fileInputRef.current.click();
+ }
+
+ function showToast(message: string, tone: ArticleToast['tone']) {
+ toastIdRef.current += 1;
+ setToast({ id: toastIdRef.current, message, tone });
+ }
+
+ async function continueFromInspiration() {
+ if (session === null || uploading || running) return;
+ setError('');
+ if (sourceCount === 0) {
+ const next = Math.max(furthestStep, 1) as ArticleStep;
+ setCurrentStep(1);
+ setFurthestStep(next);
+ session.updateDraft({ currentStep: 1, furthestStep: next });
+ return;
+ }
+ setTopics([]);
+ setSelectedTopicId('');
+ setOutline('');
+ setArticleMarkdown('');
+ pendingSourceParseRef.current = true;
+ const started = await runStage('sources', {
+ sourceLinks,
+ sourceDocumentArtifactIds: selectedDocumentIds,
+ topics: [],
+ selectedTopicId: '',
+ outline: '',
+ articleMarkdown: '',
+ currentStep: 0
+ });
+ if (!started) pendingSourceParseRef.current = false;
+ }
+
+ async function continueFromBrief() {
+ setError('');
+ if (!writingPrompt.trim() && sourceLinks.length === 0 && documentArtifacts.length === 0) {
+ setError(l('没有内容灵感时,请至少填写一个写作主题或要求', 'Add a writing topic or instruction when no inspiration is provided.'));
+ return;
+ }
+ session?.updateDraft({ writingPrompt, topicCount, presetId, layoutStyleId, templatePrompt });
+ const next = Math.max(furthestStep, 2) as ArticleStep;
+ setFurthestStep(next);
+ setCurrentStep(2);
+ await generateTopics();
+ }
+
+ async function runStage(stageId: 'sources' | 'topics' | 'outline' | 'article' | 'images' | 'document', patch: Record<string, CreatorJson>): Promise<boolean> {
+ if (session === null || running) return false;
+ setError('');
+ session.updateDraft(patch, { semantic: true });
+ try {
+ await session.flush();
+ await session.applyAction({ actor: 'user', action: 'run-stage', input: { stageId } });
+ return true;
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : String(cause));
+ return false;
+ }
+ }
+
+ async function generateTopics() {
+ if (!writingPrompt.trim() && sourceLinks.length === 0 && documentArtifacts.length === 0) {
+ setError(l('请填写写作主题,或添加至少一个内容灵感', 'Enter a writing topic or add at least one inspiration source.'));
+ openStep(1);
+ return;
+ }
+ setTopics([]);
+ setSelectedTopicId('');
+ setOutline('');
+ setArticleMarkdown('');
+ await runStage('topics', {
+ sourceLinks,
+ writingPrompt: writingPrompt.trim(),
+ topicCount,
+ presetId,
+ templatePrompt: templatePrompt.trim(),
+ topics: [],
+ selectedTopicId: '',
+ outline: '',
+ articleMarkdown: '',
+ currentStep: 2,
+ furthestStep: Math.max(furthestStep, 2)
+ });
+ }
+
+ async function generateOutline() {
+ if (selectedTopic === undefined) {
+ setError(l('请先选择一个选题', 'Select a topic first.'));
+ return;
+ }
+ const nextFurthestStep = Math.max(furthestStep, 3) as ArticleStep;
+ setCurrentStep(3);
+ setFurthestStep(nextFurthestStep);
+ setOutline('');
+ setArticleMarkdown('');
+ await runStage('outline', {
+ topics,
+ selectedTopicId,
+ outline: '',
+ articleMarkdown: '',
+ currentStep: 3,
+ furthestStep: nextFurthestStep
+ });
+ }
+
+ async function generateArticle() {
+ if (!outline.trim()) {
+ setError(l('请先确认文章大纲', 'Review the article outline first.'));
+ return;
+ }
+ setArticleMarkdown('');
+ await runStage('article', {
+ topics,
+ selectedTopicId,
+ outline: outline.trim(),
+ writingPrompt: writingPrompt.trim(),
+ presetId,
+ layoutStyleId,
+ templatePrompt: templatePrompt.trim(),
+ articleMarkdown: '',
+ currentStep: 4,
+ furthestStep: Math.max(furthestStep, 4)
+ });
+ }
+
+ async function generateArticleImages() {
+ if (!articleMarkdown.trim() || !autoGenerateImages || running) return;
+ const started = await runStage('images', {
+ articleMarkdown: articleMarkdown.trim(),
+ autoGenerateImages,
+ articleImageCount,
+ articleImageStyleId,
+ articleImagePlacementCustomized: false,
+ currentStep: 4,
+ furthestStep: Math.max(furthestStep, 4)
+ });
+ if (started) {
+ showToast(l(`正在生成 ${articleImageCount} 张配图`, `Generating ${articleImageCount} article images.`), 'success');
+ }
+ }
+
+ function updateArticleImageCount(value: number) {
+ const next = Math.max(1, Math.min(10, Math.round(value)));
+ setArticleImageCount(next);
+ session?.updateDraft({ articleImageCount: next });
+ }
+
+ function updateAutoGenerateImages(enabled: boolean) {
+ setAutoGenerateImages(enabled);
+ session?.updateDraft({ autoGenerateImages: enabled });
+ }
+
+ function selectArticleImageStyle(id: WechatArticleImageStyleId) {
+ setArticleImageStyleId(id);
+ session?.updateDraft({ articleImageStyleId: id });
+ }
+
+ function updateTopic(id: string, field: keyof Pick<WechatArticleTopic, 'title' | 'angle' | 'summary'>, value: string) {
+ const next = topics.map(topic => topic.id === id ? { ...topic, [field]: value } : topic);
+ setTopics(next);
+ session?.updateDraft({ topics: next });
+ }
+
+ function selectPreset(id: WechatArticlePresetId) {
+ const preset = wechatArticlePresets.find(candidate => candidate.id === id)!;
+ session?.clearError();
+ setPresetId(id);
+ setTemplatePrompt(preset.instructions);
+ session?.updateDraft({ presetId: id, templatePrompt: preset.instructions });
+ }
+
+ function clearPreset() {
+ session?.clearError();
+ setPresetId('');
+ setPreviewPresetId('');
+ setTemplatePrompt('');
+ session?.updateDraft({ presetId: '', templatePrompt: '' });
+ }
+
+ function openTemplateLibrary() {
+ updateTemplateLibraryAnchor();
+ setPreviewPresetId(presetId);
+ setTemplateQuery('');
+ setTemplateTopFilter('popular');
+ setTemplateCategory('all');
+ setTemplateLibraryOpen(true);
+ }
+
+ function updateTemplateLibraryAnchor() {
+ const rect = templateLibraryAnchorRef.current?.getBoundingClientRect();
+ if (rect === undefined || rect.width <= 0) return;
+ const left = Math.max(18, Math.round(rect.left));
+ setTemplateLibraryAnchor({
+ left,
+ width: Math.max(320, Math.min(Math.round(rect.width), window.innerWidth - left - 18))
+ });
+ }
+
+ function usePreviewPreset() {
+ if (previewPreset === undefined) return;
+ selectPreset(previewPreset.id);
+ setTemplateLibraryOpen(false);
+ }
+
+ function selectTemplateTopFilter(id: ArticleTemplateTopFilter) {
+ setTemplateTopFilter(id);
+ setTemplateCategory('all');
+ setTemplateQuery('');
+ }
+
+ function selectInlineTemplateTopFilter(id: ArticleTemplateTopFilter) {
+ selectTemplateTopFilter(templateTopFilter === id ? 'all' : id);
+ }
+
+ function selectLayoutStyle(id: WechatArticleLayoutStyleId) {
+ setLayoutStyleId(id);
+ session?.updateDraft({ layoutStyleId: id });
+ }
+
+ async function copyMarkdown() {
+ const preview = articlePreviewRef.current;
+ if (preview === null || copyingArticle) return;
+ setCopyingArticle(true);
+ try {
+ const result = await copyRichContent(preview, articleMarkdown);
+ if (result === 'rich') {
+ showToast(l('图文和排版已复制,可直接粘贴', 'Article content, images, and styling copied.'), 'success');
+ } else if (result === 'plain') {
+ showToast(l('当前浏览器不支持复制图文,已复制 Markdown', 'Rich copy is unavailable; Markdown was copied instead.'), 'success');
+ } else {
+ showToast(l('复制失败,请手动选择正文', 'Copy failed. Select the article manually.'), 'error');
+ }
+ } finally {
+ setCopyingArticle(false);
+ }
+ }
+
+ async function generateDocument() {
+ if (!articleMarkdown.trim() || running) return;
+ setWorkspacePhase('result');
+ setResultTab('outputs');
+ await runStage('document', {
+ articleMarkdown,
+ layoutStyleId,
+ workspacePhase: 'result',
+ currentStep: 5,
+ furthestStep: 5
+ });
+ }
+
+ async function downloadDocument(artifact: CreatorArtifact) {
+ if (session === null || typeof URL.createObjectURL !== 'function') return;
+ setError('');
+ try {
+ const response = await session.openArtifact(artifact.id);
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ const url = URL.createObjectURL(await response.blob());
+ const anchor = document.createElement('a');
+ anchor.href = url;
+ anchor.download = readString(artifact.metadata.fileName)
+ || `${safeFileName(selectedTopic?.title || l('公众号文章', 'wechat-article'))}.md`;
+ anchor.click();
+ window.setTimeout(() => URL.revokeObjectURL(url), 0);
+ showToast(l('文档已开始下载', 'The document download has started.'), 'success');
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : String(cause));
+ }
+ }
+
+ async function downloadArticleImage(artifact: CreatorArtifact) {
+ if (session === null || typeof URL.createObjectURL !== 'function') return;
+ try {
+ const existingUrl = articleImageUrls[artifact.id];
+ let temporaryUrl = '';
+ if (!existingUrl) {
+ const response = await session.openArtifact(artifact.id);
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ temporaryUrl = URL.createObjectURL(await response.blob());
+ }
+ const anchor = document.createElement('a');
+ anchor.href = existingUrl || temporaryUrl;
+ anchor.download = readString(artifact.metadata.fileName) || `article-image-${readNumber(artifact.metadata.imageIndex) || 1}.png`;
+ anchor.click();
+ if (temporaryUrl) window.setTimeout(() => URL.revokeObjectURL(temporaryUrl), 0);
+ } catch (cause) {
+ showToast(cause instanceof Error ? cause.message : String(cause), 'error');
+ }
+ }
+
+ function adjustArticle() {
+ setWorkspacePhase('compose');
+ setCurrentStep(4);
+ setFurthestStep(5);
+ setResultTab('outputs');
+ knownDocumentArtifactIdRef.current = finalDocumentArtifact?.id;
+ session?.updateDraft({ workspacePhase: 'compose', currentStep: 4, furthestStep: 5 });
+ }
+
+ async function cancelTask() {
+ if (session === null || taskControlPending !== undefined) return;
+ setTaskControlPending('canceling');
+ try { await session.cancelJob(); } catch (cause) { setError(String(cause)); }
+ finally { setTaskControlPending(undefined); }
+ }
+
+ async function resumeTask() {
+ if (session === null || taskControlPending !== undefined) return;
+ setTaskControlPending('resuming');
+ try { await session.resumeJob(); } catch (cause) { setError(String(cause)); }
+ finally { setTaskControlPending(undefined); }
+ }
+
+ const context = workspacePhase === 'result'
+ ? finalDocumentArtifact === undefined
+ ? l('正在生成文章文档', 'Generating the article document')
+ : l('文章文档与配图产出', 'Article documents and image outputs')
+ : currentStep === 0
+ ? l(`${sourceCount} 个内容灵感`, `${sourceCount} inspiration sources`)
+ : currentStep === 1
+ ? l('正在设置写作要求与模板', 'Setting the writing brief and template')
+ : currentStep === 2
+ ? l(`${topics.length} 个候选选题`, `${topics.length} topic options`)
+ : currentStep === 3
+ ? l('正在确认文章大纲', 'Reviewing the article outline')
+ : currentStep === 4
+ ? l('正在编辑微信公众号文章', 'Editing the WeChat article')
+ : l('正在选择排版并预览成稿', 'Choosing a layout and previewing the final article');
+
+ return (
+ <CreatorToolShell
+ title={l('文章写作', 'Article Writer')}
+ subtitle={l('公众号、X 等平台文章', 'Articles for WeChat, X, and more')}
+ context={context}
+ stepLabel={workspacePhase === 'result'
+ ? documentRunning
+ ? l('正在生成文档', 'Generating document')
+ : l('项目结果', 'Project results')
+ : running
+ ? l('正在生成内容', 'Generating content')
+ : l(stepLabels[currentStep]![0], stepLabels[currentStep]![1])}
+ currentIssue={visibleError || undefined}
+ suggestions={[l('选题更有观点一些', 'Make the topics more opinionated'), l('让文章更简洁', 'Make the article more concise')]}
+ placeholder={props.promptHint ?? l('描述文章主题、读者和表达要求', 'Describe the topic, audience, and writing style')}
+ onBack={props.onBack}
+ onCancelTask={() => void cancelTask()}
+ onResumeTask={() => void resumeTask()}
+ taskControlPending={taskControlPending}
+ contentClassName="wechat-article-workspace-content"
+ >
+ <div className="creator-tool-stack wechat-article-stack" data-phase={workspacePhase} data-step={currentStep}>
+ {activeToast ? (
+ <div className="wechat-article-toast" data-tone={activeToast.tone} role={activeToast.tone === 'error' ? 'alert' : 'status'}>
+ <span>{activeToast.tone === 'error' ? <CircleAlert size={17} /> : <Check size={17} />}</span>
+ <div>
+ <p>{activeToast.message}</p>
+ </div>
+ <button type="button" aria-label={l('关闭提示', 'Dismiss notification')} onClick={() => {
+ setToast(null);
+ setDismissedErrorKey(visibleErrorKey);
+ setError('');
+ session?.clearError();
+ }}><X size={15} /></button>
+ </div>
+ ) : null}
+ {workspacePhase === 'compose' ? <nav className="video-translation-steps creator-tool-steps wechat-article-steps" aria-label={l('文章写作流程', 'Article writing workflow')}>
+ <ol>
+ {stepLabels.map(([zh, en], index) => {
+ const active = currentStep === index;
+ const completed = index < currentStep;
+ return (
+ <li key={zh} data-active={active} data-completed={completed}>
+ <button type="button" disabled={index > furthestStep} aria-current={active ? 'step' : undefined} onClick={() => openStep(index as ArticleStep)}>
+ <span>{completed ? <Check size={13} /> : index + 1}</span>
+ <strong>{l(zh, en)}</strong>
+ </button>
+ </li>
+ );
+ })}
+ </ol>
+ </nav> : null}
+
+ {workspacePhase === 'compose' ? <div className="wechat-article-scroll" data-step={currentStep}>
+ {currentStep === 0 ? (
+ <section className="creator-tool-panel wechat-inspiration-panel">
+ <div className="creator-tool-panel-heading wechat-inspiration-heading">
+ <div><h2>{l('添加内容灵感', 'Add inspiration')}</h2><p>{l('添加视频、网页或本地文档,为选题和写作提供参考。也可以不添加,直接进入下一步。', 'Add videos, webpages, or local documents as writing references, or continue without them.')}</p></div>
+ </div>
+ <div className="wechat-inspiration-workbench">
+ <aside className="wechat-inspiration-library" aria-label={l('内容灵感', 'Inspiration library')}>
+ <header>
+ <div>
+ <strong>{l('内容灵感', 'Inspiration')}</strong>
+ <span>{l('本次写作使用的全部资料', 'All references used for this article')}</span>
+ </div>
+ <b aria-label={l(`已添加 ${sourceCount} 个,最多 ${wechatArticleSourceLimit} 个`, `${sourceCount} of ${wechatArticleSourceLimit} sources added`)}>{sourceCount}/{wechatArticleSourceLimit}</b>
+ </header>
+ {sourceCount > 0 ? (
+ <div className="wechat-source-list">
+ {sourceLinks.map(link => (
+ <div key={link.id}><span><Link2 size={15} /></span><div><strong>{link.kind === 'video' ? l('视频链接', 'Video') : l('网页链接', 'Webpage')}</strong><small>{link.url}</small></div><button type="button" aria-label={l(`移除 ${link.url}`, `Remove ${link.url}`)} title={l('移除', 'Remove')} onClick={() => removeSourceLink(link.id)}><X size={16} /></button></div>
+ ))}
+ {documentArtifacts.map(artifact => {
+ const fileName = readString(artifact.metadata.fileName) || l('灵感文件', 'Inspiration file');
+ return <div key={artifact.id}><span><FileText size={15} /></span><div><strong>{fileName}</strong><small>{formatBytes(readNumber(artifact.metadata.bytes))}</small></div><button type="button" aria-label={l(`移除 ${fileName}`, `Remove ${fileName}`)} title={l('移除', 'Remove')} onClick={() => removeDocument(artifact.id)}><X size={16} /></button></div>;
+ })}
+ </div>
+ ) : <div className="wechat-empty-source"><FileText size={22} /><strong>{l('还没有内容灵感', 'No inspiration yet')}</strong><p>{l('从右侧添加链接或文件。没有资料也可以继续写作。', 'Add a link or file from the right. You can also continue without sources.')}</p></div>}
+ </aside>
+
+ <div className="wechat-inspiration-add">
+ <div className="wechat-inspiration-link-section">
+ <div><strong>{l('添加链接', 'Add a link')}</strong><span>{l('支持 YouTube、B站和普通网页', 'Supports YouTube, Bilibili, and webpages')}</span></div>
+ <label className="creator-tool-field">
+ <span>{l('视频或网页链接', 'Video or webpage URL')}</span>
+ <div className="wechat-inline-input">
+ <Link2 size={16} aria-hidden="true" />
+ <input aria-label={l('视频或网页链接', 'Video or webpage URL')} disabled={sourceLimitReached} value={urlInput} onChange={event => setUrlInput(event.target.value)} onKeyDown={event => { if (event.key === 'Enter') { event.preventDefault(); addSourceLink(); } }} placeholder="https://" />
+ <button type="button" disabled={sourceLimitReached} onClick={addSourceLink}><Plus size={16} /><span>{l('添加', 'Add')}</span></button>
+ </div>
+ </label>
+ </div>
+
+ <div
+ className="wechat-inspiration-dropzone"
+ data-active={sourceDragActive}
+ data-disabled={sourceLimitReached || uploading}
+ onDragEnter={event => { event.preventDefault(); if (!sourceLimitReached && !uploading) setSourceDragActive(true); }}
+ onDragOver={event => { event.preventDefault(); event.dataTransfer.dropEffect = sourceLimitReached || uploading ? 'none' : 'copy'; }}
+ onDragLeave={event => {
+ if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setSourceDragActive(false);
+ }}
+ onDrop={event => {
+ event.preventDefault();
+ setSourceDragActive(false);
+ if (!sourceLimitReached && !uploading) void uploadDocuments(event.dataTransfer.files);
+ }}
+ >
+ <span className="wechat-inspiration-drop-icon">{uploading ? <LoaderCircle className="smart-dubbing-spinner" size={22} /> : <Upload size={22} />}</span>
+ <strong>{uploading ? l('正在上传文件', 'Uploading files') : l('上传本地文件', 'Upload local files')}</strong>
+ <p>{sourceLimitReached
+ ? l('已达到 10 个内容灵感上限', 'The 10-source limit has been reached.')
+ : l('拖放文件到这里,或从电脑中选择', 'Drop files here, or choose them from your computer.')}</p>
+ <button type="button" disabled={sourceLimitReached || uploading} onClick={openFilePicker}>{l('选择文件', 'Choose files')}</button>
+ <small>{l('PDF、Markdown、TXT、HTML,单个文件不超过 25 MB', 'PDF, Markdown, TXT, or HTML, up to 25 MB each')}</small>
+ </div>
+
+ <div className="wechat-inspiration-capacity">
+ <span>{l(`还可以添加 ${remainingSourceCount} 个内容灵感`, `${remainingSourceCount} inspiration slots remaining`)}</span>
+ <small>{l('链接和文件合计最多 10 个', 'Links and files share the 10-source limit')}</small>
+ </div>
+ <input ref={fileInputRef} hidden multiple type="file" accept=".pdf,.txt,.md,.markdown,.html,.htm,application/pdf,text/plain,text/markdown,text/html" onChange={event => void uploadDocuments(event.target.files)} />
+ </div>
+ </div>
+ </section>
+ ) : null}
+
+ {currentStep === 1 ? (
+ <div className="wechat-brief-grid" ref={templateLibraryAnchorRef}>
+ <section className="creator-tool-panel wechat-writing-brief-panel">
+ <div className="creator-tool-panel-heading"><div><h2>{l('写作要求', 'Writing brief')}</h2><p>{l('说明主题、目标读者、篇幅、语气和必须覆盖的观点', 'Describe the topic, audience, length, tone, and required points.')}</p></div></div>
+ <label className="creator-tool-field"><span>{l('提示词', 'Instructions')}</span><textarea rows={15} value={writingPrompt} onChange={event => { setWritingPrompt(event.target.value); session?.updateDraft({ writingPrompt: event.target.value }); }} placeholder={l('例如:面向 AI 产品经理,写一篇 2000 字左右的深度分析,重点讨论实际落地中的三个误区。', 'For example: Write a 2,000-word analysis for AI product managers, focusing on three common implementation mistakes.')} /></label>
+ <label className="creator-tool-field wechat-topic-count"><span>{l('候选选题数量', 'Topic options')}</span><input type="number" min={3} max={10} value={topicCount} onChange={event => { const value = Math.max(3, Math.min(10, Number(event.target.value) || 5)); setTopicCount(value); session?.updateDraft({ topicCount: value }); }} /></label>
+ </section>
+ <section className="creator-tool-panel wechat-template-selection-panel">
+ <div className="creator-tool-panel-heading"><div><h2>{l('写作模板', 'Writing template')}</h2><p>{l('模板负责文章结构,写作要求仍以左侧提示词为准', 'The template guides structure while the writing brief remains primary.')}</p></div></div>
+ {selectedPreset ? <>
+ <div className="wechat-current-template">
+ <span><Library size={18} /></span>
+ <div>
+ <strong>{selectedPreset.name}</strong>
+ {selectedPreset.source.type === 'github' ? <small className="wechat-template-community-badge">{l('社区模板', 'Community')}</small> : null}
+ <p>{selectedPreset.description}</p>
+ <div>{selectedPreset.tags.map(tag => <i key={tag}>{tag}</i>)}</div>
+ </div>
+ <button type="button" aria-label={l('取消文章模板', 'Clear article template')} title={l('取消选择', 'Clear selection')} onClick={clearPreset}><X size={15} /></button>
+ </div>
+ <button className="wechat-template-library-trigger" type="button" onClick={openTemplateLibrary}><Library size={15} />{l('更换模板', 'Change template')}</button>
+ <details className="wechat-template-instructions">
+ <summary>{l('模板补充要求', 'Template instructions')}<ChevronDown size={15} /></summary>
+ <label className="creator-tool-field"><textarea aria-label={l('模板补充要求', 'Template instructions')} rows={8} value={templatePrompt} onChange={event => { setTemplatePrompt(event.target.value); session?.updateDraft({ templatePrompt: event.target.value }); }} /></label>
+ </details>
+ </> : <>
+ <div className="wechat-template-inline-filters" role="group" aria-label={l('写作模板标签', 'Writing template tags')}>
+ {articleTemplateInlineFilters.map(filter => <button key={filter.id} type="button" aria-pressed={templateTopFilter === filter.id} data-selected={templateTopFilter === filter.id} onClick={() => selectInlineTemplateTopFilter(filter.id)}>{l(filter.zh, filter.en)}</button>)}
+ </div>
+ <div className="wechat-template-inline-list" role="group" aria-label={l('文章模板列表', 'Article template list')}>
+ {topFilteredPresets.map(preset => <button key={preset.id} type="button" onClick={() => selectPreset(preset.id)}><span><FileText size={15} /></span><div><strong>{preset.name}</strong><p>{preset.description}</p></div>{preset.source.type === 'github' ? <small>{l('社区', 'Community')}</small> : null}</button>)}
+ </div>
+ <button className="wechat-template-library-trigger" type="button" onClick={openTemplateLibrary}><Library size={15} />{l('查看全部模板', 'Browse all templates')}</button>
+ </>}
+ </section>
+ </div>
+ ) : null}
+
+ {currentStep === 2 ? (
+ <section className="creator-tool-panel wechat-topics-panel">
+ <div className="creator-tool-panel-heading"><div><h2>{l('候选选题', 'Topic options')}</h2><p>{l('生成后可以直接修改标题、角度和摘要,再选择一个继续', 'Edit any title, angle, or summary, then choose one to continue.')}</p></div><button className="wechat-generate-button" type="button" disabled={running} onClick={() => void generateTopics()}>{running && latestStage?.stageId === 'topics' ? <LoaderCircle className="smart-dubbing-spinner" size={16} /> : <Sparkles size={16} />}{topics.length ? l('重新生成', 'Regenerate') : l('生成选题', 'Generate topics')}</button></div>
+ {topics.length ? <div className="wechat-topic-list">{topics.map((topic, index) => <article key={topic.id} data-selected={selectedTopicId === topic.id} onClick={() => { setSelectedTopicId(topic.id); session?.updateDraft({ selectedTopicId: topic.id }); }}><header><span>{String(index + 1).padStart(2, '0')}</span><input aria-label={l('选题标题', 'Topic title')} value={topic.title} onClick={event => event.stopPropagation()} onChange={event => updateTopic(topic.id, 'title', event.target.value)} /><button type="button" aria-label={l('选择选题', 'Select topic')}><span>{selectedTopicId === topic.id ? <Check size={14} /> : null}</span></button></header><label>{l('切入角度', 'Angle')}<textarea rows={2} value={topic.angle} onClick={event => event.stopPropagation()} onChange={event => updateTopic(topic.id, 'angle', event.target.value)} /></label><label>{l('内容摘要', 'Summary')}<textarea rows={3} value={topic.summary} onClick={event => event.stopPropagation()} onChange={event => updateTopic(topic.id, 'summary', event.target.value)} /></label></article>)}</div> : <div className="wechat-generation-empty"><Sparkles size={25} /><strong>{running ? l('正在分析来源并生成选题', 'Analyzing sources and generating topics') : l('准备生成候选选题', 'Ready to generate topic options')}</strong><p>{l('默认生成 5 个方向不同、可直接编辑的选题', 'Generate five distinct, editable topic options by default.')}</p></div>}
+ </section>
+ ) : null}
+
+ {currentStep === 3 ? (
+ <section className="creator-tool-panel wechat-outline-panel">
+ <div className="creator-tool-panel-heading"><div><h2>{l('文章大纲', 'Article outline')}</h2></div>{outline ? <button className="wechat-generate-button" type="button" disabled={running} onClick={() => void generateOutline()}><Sparkles size={16} />{l('重新生成', 'Regenerate')}</button> : null}</div>
+ {outline ? <label className="creator-tool-field"><textarea aria-label={l('文章大纲编辑器', 'Article outline editor')} className="wechat-outline-editor" rows={22} value={outline} onChange={event => { setOutline(event.target.value); session?.updateDraft({ outline: event.target.value }); }} /></label> : <div className="wechat-generation-empty"><FileText size={25} /><strong>{running ? l('正在生成文章大纲', 'Generating the outline') : l('选题已确定', 'Topic selected')}</strong><p>{selectedTopic?.title}</p><button className="creator-tool-primary" type="button" disabled={running} onClick={() => void generateOutline()}>{running ? <LoaderCircle className="smart-dubbing-spinner" size={16} /> : <Sparkles size={16} />}{l('生成大纲', 'Generate outline')}</button></div>}
+ </section>
+ ) : null}
+
+ {currentStep === 4 ? (
+ <section className="creator-tool-panel wechat-article-panel">
+ <div className="creator-tool-panel-heading"><div className="wechat-article-title-row"><h2>{l('文章正文', 'Article')}</h2>{articleMarkdown ? <span className="wechat-article-character-count">{l(`${formatNumber(articleCharacterCount)} 字`, `${formatNumber(articleCharacterCount)} characters`)}</span> : null}</div>{articleMarkdown ? <div className="wechat-article-toolbar"><button className="wechat-insert-image-button" type="button" disabled={uploadingArticleImage} onClick={() => openArticleImagePicker()}>{uploadingArticleImage ? <LoaderCircle className="smart-dubbing-spinner" size={16} /> : <ImagePlus size={16} />}{l('插入图片', 'Insert image')}</button><button className="wechat-generate-button" type="button" disabled={running} onClick={() => void generateArticle()}>{running ? <LoaderCircle className="smart-dubbing-spinner" size={16} /> : <Sparkles size={16} />}{l('重新生成', 'Regenerate')}</button></div> : null}</div>
+ {articleMarkdown ? <div className="wechat-article-edit-workbench">
+ <div className="wechat-article-editor-pane">
+ <div className="wechat-article-editor" aria-label={l('文章正文', 'Article body')}>
+ {articleEditorParts.map((part, index) => part.kind === 'image' ? (
+ <figure
+ className="wechat-article-inline-image"
+ key={`${part.href}-${index}`}
+ data-markdown={part.markdown}
+ data-dragging={draggedArticleImagePartIndex === index}
+ draggable={!uploadingArticleImage}
+ onDragStart={event => {
+ draggedArticleImagePartRef.current = index;
+ setDraggedArticleImagePartIndex(index);
+ event.dataTransfer.effectAllowed = 'move';
+ event.dataTransfer.setData('text/plain', part.markdown);
+ }}
+ onDragEnd={() => {
+ draggedArticleImagePartRef.current = undefined;
+ setDraggedArticleImagePartIndex(undefined);
+ setArticleImageDropTarget(undefined);
+ }}
+ >
+ <img src={part.src} alt={part.alt} />
+ <div className="wechat-article-inline-image-actions">
+ <button type="button" title={l('替换图片', 'Replace image')} aria-label={l('替换图片', 'Replace image')} disabled={uploadingArticleImage} onClick={() => openArticleImagePicker({ mode: 'replace', partIndex: index, artifactId: part.artifactId, href: part.href })}><ImageUp size={15} /></button>
+ <button type="button" title={l('删除图片', 'Delete image')} aria-label={l('删除图片', 'Delete image')} onClick={() => removeArticleImage(index, part.artifactId, part.href)}><Trash2 size={15} /></button>
+ </div>
+ </figure>
+ ) : (
+ <ArticleEditorTextBlock
+ key={`text-${index}`}
+ value={part.markdown}
+ onChange={markdown => updateArticleEditorPart(index, markdown)}
+ onSelect={offset => rememberArticleEditorSelection(index, offset)}
+ imageDragging={draggedArticleImagePartIndex !== undefined}
+ imageDropTarget={articleImageDropTarget?.partIndex === index ? articleImageDropTarget : undefined}
+ trimLeadingWhitespace={articleEditorParts[index - 1]?.kind === 'image'}
+ trimTrailingWhitespace={articleEditorParts[index + 1]?.kind === 'image'}
+ onImageDragOver={target => setArticleImageDropTarget({ partIndex: index, ...target })}
+ onImageDragLeave={() => setArticleImageDropTarget(current => current?.partIndex === index ? undefined : current)}
+ onImageDrop={offset => moveArticleImage(index, offset)}
+ label={index === 0 ? l('文章正文编辑器', 'Article editor') : l(`文章正文编辑器第 ${index + 1} 段`, `Article editor section ${index + 1}`)}
+ />
+ ))}
+ </div>
+ <input ref={articleImageInputRef} hidden type="file" accept="image/png,image/jpeg,image/webp,.png,.jpg,.jpeg,.webp" onChange={event => { const file = event.target.files?.[0]; if (file !== undefined) void uploadArticleImage(file); }} />
+ </div>
+ <aside className="wechat-article-image-panel" aria-label={l('文章配图设置', 'Article image settings')}>
+ <header className="wechat-article-image-heading">
+ <div><span><ImageIcon size={16} /></span><div><strong>{l('文章配图', 'Article images')}</strong><small>{l('根据正文自动规划并生成', 'Plan and generate from the article')}</small></div></div>
+ <label className="wechat-image-toggle"><input type="checkbox" checked={autoGenerateImages} onChange={event => updateAutoGenerateImages(event.target.checked)} /><span aria-hidden="true" /></label>
+ </header>
+ <div className="wechat-article-image-settings" data-disabled={!autoGenerateImages}>
+ <div className="wechat-image-setting-block">
+ <div className="wechat-image-setting-label"><strong>{l('配图数量', 'Image count')}</strong><span>{articleImageCount}</span></div>
+ <div className="wechat-image-density" role="group" aria-label={l('配图数量档位', 'Image density')}>
+ {articleImageDensityOptions.map(option => <button key={option.id} type="button" aria-pressed={articleImageCount === option.count} data-selected={articleImageCount === option.count} disabled={!autoGenerateImages} onClick={() => updateArticleImageCount(option.count)}>{l(option.zh, option.en)}</button>)}
+ </div>
+ <div className="wechat-image-count-control">
+ <button type="button" aria-label={l('减少配图数量', 'Decrease image count')} disabled={!autoGenerateImages || articleImageCount <= 1} onClick={() => updateArticleImageCount(articleImageCount - 1)}><Minus size={14} /></button>
+ <input type="range" min={1} max={10} step={1} value={articleImageCount} disabled={!autoGenerateImages} aria-label={l('配图数量', 'Image count')} onChange={event => updateArticleImageCount(Number(event.target.value))} />
+ <button type="button" aria-label={l('增加配图数量', 'Increase image count')} disabled={!autoGenerateImages || articleImageCount >= 10} onClick={() => updateArticleImageCount(articleImageCount + 1)}><Plus size={14} /></button>
+ </div>
+ </div>
+ <div className="wechat-image-setting-block">
+ <div className="wechat-image-setting-label"><strong>{l('生图风格', 'Image style')}</strong></div>
+ <div className="wechat-image-style-grid" role="group" aria-label={l('生图风格', 'Image style')}>
+ {articleImageStyleOptions.map(style => <button key={style.id} type="button" data-style={style.id} data-selected={articleImageStyleId === style.id} aria-pressed={articleImageStyleId === style.id} disabled={!autoGenerateImages} onClick={() => selectArticleImageStyle(style.id)}><img src={style.previewSrc} alt="" aria-hidden="true" /><strong>{l(style.zh, style.en)}</strong><small>{l(style.descriptionZh, style.descriptionEn)}</small>{articleImageStyleId === style.id ? <b><Check size={11} /></b> : null}</button>)}
+ </div>
+ </div>
+ <button className="wechat-generate-images" type="button" disabled={!autoGenerateImages || imageRunning || running} onClick={() => void generateArticleImages()}>{imageRunning ? <LoaderCircle className="smart-dubbing-spinner" size={15} /> : <Sparkles size={15} />}{imageRunning ? l('正在生成配图', 'Generating images') : articleImageArtifacts.length > 0 ? l(`重新生成 ${articleImageCount} 张`, `Regenerate ${articleImageCount}`) : l(`生成 ${articleImageCount} 张配图`, `Generate ${articleImageCount} images`)}</button>
+ </div>
+ </aside>
+ </div> : <div className="wechat-generation-empty"><FileText size={25} /><strong>{running ? l('正在撰写文章', 'Writing the article') : l('大纲已确认', 'Outline ready')}</strong><p>{l('将按照选题、大纲、来源和文章模板生成完整正文', 'Generate the full article from the topic, outline, sources, and article template.')}</p><button className="creator-tool-primary" type="button" disabled={running} onClick={() => void generateArticle()}>{running ? <LoaderCircle className="smart-dubbing-spinner" size={16} /> : <Sparkles size={16} />}{l('开始写作', 'Write article')}</button></div>}
+ </section>
+ ) : null}
+
+ {currentStep === 5 ? (
+ <section className="creator-tool-panel wechat-article-panel">
+ <div className="wechat-layout-workbench">
+ <div className="wechat-layout-preview-pane">
+ <div className="wechat-layout-preview-heading"><h2>{l('文章预览', 'Article preview')}</h2><button type="button" disabled={!articleMarkdown || copyingArticle} onClick={() => void copyMarkdown()}>{copyingArticle ? <LoaderCircle className="smart-dubbing-spinner" size={14} /> : <Clipboard size={14} />}{copyingArticle ? l('正在复制', 'Copying') : l('复制图文', 'Copy article')}</button></div>
+ <div ref={articlePreviewRef} className="wechat-article-preview" data-layout={layoutStyleId}><MarkdownRenderer text={articleMarkdown} variant="document" resolveImageSrc={href => articleImagePreviewSources[href]} /></div>
+ </div>
+ <aside className="wechat-layout-sidebar" aria-label={l('排版模板', 'Layout templates')}>
+ <div className="wechat-layout-sidebar-heading"><strong>{l('排版模板', 'Layout templates')}</strong></div>
+ <div className="wechat-layout-filters" role="group" aria-label={l('排版模板分类', 'Layout template categories')}>
+ {articleLayoutCategoryOptions.map(category => (
+ <button
+ key={category.id}
+ type="button"
+ data-selected={layoutCategoryId === category.id}
+ aria-pressed={layoutCategoryId === category.id}
+ onClick={() => setLayoutCategoryId(category.id)}
+ >
+ {l(category.zh, category.en)}
+ </button>
+ ))}
+ </div>
+ <div className="wechat-layout-list">
+ {filteredLayoutStyles.map(style => (
+ <button key={style.id} type="button" data-layout={style.id} data-selected={layoutStyleId === style.id} onClick={() => selectLayoutStyle(style.id)}>
+ <WechatArticleStylePreview layout={style.id} />
+ <div className="wechat-layout-meta">
+ <strong>{style.name}</strong>
+ <small>{style.description}</small>
+ <span className="wechat-layout-features">{style.features.map(feature => <i key={feature}>{feature}</i>)}</span>
+ </div>
+ {layoutStyleId === style.id ? <span className="wechat-layout-selected"><Check size={13} /></span> : null}
+ </button>
+ ))}
+ </div>
+ </aside>
+ </div>
+ </section>
+ ) : null}
+
+ </div> : (
+ <section className="video-result-workspace wechat-result-workspace" aria-label={l('公众号文章项目产出', 'WeChat article project outputs')}>
+ <div className="video-result-toolbar">
+ <div className="video-result-tabs" role="tablist" aria-label={l('文章结果类型', 'Article result types')}>
+ <button type="button" role="tab" aria-selected={resultTab === 'outputs'} onClick={() => setResultTab('outputs')}>
+ <PackageOpen size={15} strokeWidth={1.8} aria-hidden="true" />
+ {l('生成物', 'Outputs')}
+ </button>
+ <button type="button" role="tab" aria-selected={resultTab === 'images'} onClick={() => setResultTab('images')}>
+ <ImageIcon size={15} strokeWidth={1.8} aria-hidden="true" />
+ {l('配图', 'Images')}
+ </button>
+ <button type="button" role="tab" aria-selected={resultTab === 'settings'} onClick={() => setResultTab('settings')}>
+ <Settings2 size={15} strokeWidth={1.8} aria-hidden="true" />
+ {l('任务设置', 'Settings')}
+ </button>
+ </div>
+ </div>
+
+ <div className="creator-result-layout">
+ <div className="video-result-pane">
+ {resultTab === 'outputs' ? (
+ <>
+ <header className="video-result-pane-heading">
+ <div>
+ <h2>{finalDocumentArtifact ? l('文章文档', 'Article documents') : l('正在生成文档', 'Generating documents')}</h2>
+ <p>{finalDocumentArtifact
+ ? l('已生成 Markdown、HTML 和 PDF,可按发布场景下载使用', 'Markdown, HTML, and PDF are ready for different publishing workflows.')
+ : l('正在整理你确认的正文和排版设置', 'Preparing the approved article and layout settings.')}</p>
+ </div>
+ <button type="button" onClick={adjustArticle}>
+ <Settings2 size={15} strokeWidth={1.8} aria-hidden="true" />
+ {l('调整文章', 'Adjust article')}
+ </button>
+ </header>
+
+ {finalDocumentArtifact ? (
+ <div className="wechat-result-content">
+ <div className="wechat-result-document-list">
+ {articleDocumentArtifacts.map(artifact => {
+ const format = articleDocumentFormat(artifact);
+ const formatLabel = articleDocumentFormatLabel(format);
+ return <div className="video-result-file-row" key={artifact.id}>
+ <span aria-hidden="true"><FileText size={19} strokeWidth={1.7} /></span>
+ <div>
+ <strong>{readString(artifact.metadata.fileName) || `wechat-article.${format}`}</strong>
+ <small>{formatLabel} · {formatBytes(readNumber(artifact.metadata.bytes))}</small>
+ </div>
+ <button
+ type="button"
+ onClick={() => void downloadDocument(artifact)}
+ aria-label={l(`下载 ${formatLabel} 文档`, `Download ${formatLabel} document`)}
+ title={l(`下载 ${formatLabel} 文档`, `Download ${formatLabel} document`)}
+ >
+ <Download size={16} strokeWidth={1.8} aria-hidden="true" />
+ </button>
+ </div>;
+ })}
+ </div>
+ </div>
+ ) : (
+ <div className="video-result-empty">
+ {documentRunning
+ ? <LoaderCircle className="smart-dubbing-spinner" size={26} aria-hidden="true" />
+ : <FileText size={26} strokeWidth={1.5} aria-hidden="true" />}
+ <strong>{documentRunning ? l('正在生成文章文档', 'Generating the article document') : l('尚未生成文章文档', 'No article document yet')}</strong>
+ <p>{documentRunning
+ ? l('完成后会自动显示 Markdown、HTML 和 PDF 文档', 'Markdown, HTML, and PDF will appear automatically when ready.')
+ : visibleError || l('返回调整文章后可以重新生成', 'Return to the article and generate it again.')}</p>
+ </div>
+ )}
+ </>
+ ) : resultTab === 'images' ? (
+ <>
+ <header className="video-result-pane-heading">
+ <div>
+ <h2>{l('文章配图', 'Article images')}</h2>
+ <p>{articleImageArtifacts.length > 0
+ ? l(`${articleImageArtifacts.length} 张配图已插入正文,也可以单独下载`, `${articleImageArtifacts.length} images are placed in the article and can be downloaded separately.`)
+ : l('当前文章没有生成或插入配图', 'This article has no generated or inserted images.')}</p>
+ </div>
+ <button type="button" onClick={adjustArticle}>
+ <Settings2 size={15} strokeWidth={1.8} aria-hidden="true" />
+ {l('调整配图', 'Adjust images')}
+ </button>
+ </header>
+ {articleImageArtifacts.length > 0 ? <section className="wechat-result-image-assets">
+ <header><div><strong>{l('全部配图', 'All images')}</strong><small>{l(`${articleImageArtifacts.length} 张可单独下载`, `${articleImageArtifacts.length} downloadable images`)}</small></div><span>{l(selectedArticleImageStyle?.zh ?? '文章配图', selectedArticleImageStyle?.en ?? 'Article images')}</span></header>
+ <div>{articleImageArtifacts.map((artifact, index) => <article key={artifact.id}>
+ <div>{articleImageUrls[artifact.id] ? <img src={articleImageUrls[artifact.id]} alt={`${l('文章配图', 'Article image')} ${index + 1}`} /> : <ImageIcon size={20} />}</div>
+ <section><strong>{readString(artifact.metadata.caption) || `${l('配图', 'Image')} ${index + 1}`}</strong><small>{readString(artifact.metadata.placementHeading) || '-'}</small></section>
+ <button type="button" aria-label={`${l('下载配图', 'Download image')} ${index + 1}`} onClick={() => void downloadArticleImage(artifact)}><Download size={15} /></button>
+ </article>)}</div>
+ </section> : <div className="video-result-empty">
+ <ImageIcon size={26} strokeWidth={1.5} aria-hidden="true" />
+ <strong>{l('暂无文章配图', 'No article images')}</strong>
+ <p>{l('返回文章编辑可以开启自动配图或手动插入图片', 'Return to article editing to generate or insert images.')}</p>
+ </div>}
+ </>
+ ) : (
+ <>
+ <header className="video-result-pane-heading">
+ <div><h2>{l('当前文档设置', 'Current document settings')}</h2></div>
+ <button type="button" onClick={adjustArticle}>
+ <Settings2 size={15} strokeWidth={1.8} aria-hidden="true" />
+ {l('调整设置', 'Adjust settings')}
+ </button>
+ </header>
+ <dl className="video-result-settings">
+ <div><dt>{l('选定选题', 'Topic')}</dt><dd>{selectedTopic?.title || '-'}</dd></div>
+ <div><dt>{l('文章模板', 'Article template')}</dt><dd>{selectedPreset?.name || '-'}</dd></div>
+ <div><dt>{l('排版风格', 'Layout style')}</dt><dd>{selectedLayout?.name || '-'}</dd></div>
+ <div><dt>{l('文章配图', 'Article images')}</dt><dd>{autoGenerateImages ? l(`${articleImageArtifacts.length || articleImageCount} 张 · ${selectedArticleImageStyle?.zh ?? ''}`, `${articleImageArtifacts.length || articleImageCount} · ${selectedArticleImageStyle?.en ?? ''}`) : l('未启用', 'Disabled')}</dd></div>
+ <div><dt>{l('内容灵感', 'Inspiration')}</dt><dd>{sourceCount}</dd></div>
+ <div><dt>{l('正文字符数', 'Characters')}</dt><dd>{formatNumber([...articleMarkdown].length)}</dd></div>
+ <div><dt>{l('文档格式', 'Document formats')}</dt><dd>Markdown (.md) / HTML (.html) / PDF (.pdf)</dd></div>
+ </dl>
+ </>
+ )}
+ </div>
+
+ <CreatorTaskSummary
+ sourceIcon={FileText}
+ sourceLabel={l('文章标题', 'Article title')}
+ sourceValue={readString(finalDocumentArtifact?.metadata.title) || selectedTopic?.title || l('公众号文章', 'WeChat article')}
+ items={[
+ { label: l('文章模板', 'Article template'), value: selectedPreset?.name || '-' },
+ { label: l('排版风格', 'Layout style'), value: selectedLayout?.name || '-' },
+ { label: l('文章配图', 'Article images'), value: autoGenerateImages ? l(`${articleImageArtifacts.length || articleImageCount} 张`, String(articleImageArtifacts.length || articleImageCount)) : l('未启用', 'Disabled') },
+ { label: l('正文字符数', 'Characters'), value: formatNumber(readNumber(finalDocumentArtifact?.metadata.characterCount) || [...articleMarkdown].length) },
+ { label: l('内容灵感', 'Inspiration'), value: String(sourceCount) }
+ ]}
+ note={finalDocumentArtifact
+ ? l('已生成可下载的 Markdown、HTML 和 PDF 文档', 'Downloadable Markdown, HTML, and PDF documents are ready.')
+ : l('文档生成完成后会自动出现在这里', 'The document will appear here when generation finishes.')}
+ />
+ </div>
+
+ </section>
+ )}
+
+ {templateLibraryOpen ? createPortal(
+ <div className="wechat-template-library-overlay" style={templateLibraryAnchor ? {
+ '--wechat-template-library-left': `${templateLibraryAnchor.left}px`,
+ '--wechat-template-library-width': `${templateLibraryAnchor.width}px`
+ } as CSSProperties : undefined} onMouseDown={event => {
+ if (event.target === event.currentTarget) setTemplateLibraryOpen(false);
+ }}>
+ <section className="wechat-template-library" role="dialog" aria-modal="true" aria-labelledby="wechat-template-library-title">
+ <header>
+ <div><h2 id="wechat-template-library-title">{l('文章模板库', 'Article template library')}</h2><p>{l('按写作场景查找模板,选择后仍可修改补充要求', 'Find a template by writing scenario and customize it afterward.')}</p></div>
+ <button type="button" aria-label={l('关闭模板库', 'Close template library')} onClick={() => setTemplateLibraryOpen(false)}><X size={18} /></button>
+ </header>
+ <div className="wechat-template-top-filters" role="group" aria-label={l('模板标签', 'Template tags')}>
+ {articleTemplateTopFilters.map(filter => <button key={filter.id} type="button" aria-pressed={templateTopFilter === filter.id} data-selected={templateTopFilter === filter.id} onClick={() => selectTemplateTopFilter(filter.id)}>{l(filter.zh, filter.en)}</button>)}
+ </div>
+ <div className="wechat-template-library-body">
+ <aside className="wechat-template-categories" aria-label={l('模板分类', 'Template categories')}>
+ {articleTemplateCategories.map(category => {
+ const count = category.id === 'all'
+ ? topFilteredPresets.length
+ : topFilteredPresets.filter(preset => preset.categoryId === category.id).length;
+ return <button key={category.id} type="button" data-selected={templateCategory === category.id} onClick={() => setTemplateCategory(category.id)}><span>{l(category.zh, category.en)}</span><small>{count}</small></button>;
+ })}
+ </aside>
+ <div className="wechat-template-browser">
+ <label className="wechat-template-search"><Search size={16} /><input autoFocus aria-label={l('搜索文章模板', 'Search article templates')} value={templateQuery} onChange={event => setTemplateQuery(event.target.value)} placeholder={l('搜索模板、场景或关键词', 'Search templates, scenarios, or keywords')} /></label>
+ {filteredPresets.length > 0 ? <div className="wechat-template-grid">{filteredPresets.map(preset => {
+ return <button key={preset.id} type="button" data-selected={previewPreset?.id === preset.id} onClick={() => setPreviewPresetId(preset.id)}><span><FileText size={17} /></span><strong>{preset.name}</strong>{preset.source.type === 'github' ? <small className="wechat-template-community-badge">{l('社区', 'Community')}</small> : null}<p>{preset.description}</p><div>{preset.tags.slice(0, 2).map(tag => <i key={tag}>{tag}</i>)}</div>{previewPreset?.id === preset.id ? <b><Check size={13} /></b> : null}</button>;
+ })}</div> : <div className="wechat-template-empty"><Search size={22} /><strong>{l('没有匹配的模板', 'No matching templates')}</strong><p>{l('试试其他关键词或分类', 'Try another keyword or category.')}</p></div>}
+ </div>
+ <aside className="wechat-template-detail">
+ {previewPreset ? <>
+ <span>{l(articleTemplateCategories.find(category => category.id === previewPreset.categoryId)?.zh ?? '其他', articleTemplateCategories.find(category => category.id === previewPreset.categoryId)?.en ?? 'Other')}</span>
+ <h3>{previewPreset.name}</h3>
+ <p>{previewPreset.description}</p>
+ <div className="wechat-template-detail-tags">{previewPreset.tags.map(tag => <i key={tag}>{tag}</i>)}</div>
+ {previewPreset.source.type === 'github' ? <div className="wechat-template-source"><div><strong>{l('社区贡献', 'Community contribution')}</strong><span>{previewPreset.author}</span></div>{previewPreset.source.url ? <a href={previewPreset.source.url} target="_blank" rel="noreferrer" aria-label={l('查看模板来源', 'View template source')}><ExternalLink size={14} /></a> : null}<small>{previewPreset.source.license} · {previewPreset.version}</small></div> : null}
+ <div className="wechat-template-structure"><strong>{l('推荐结构', 'Suggested structure')}</strong><ol>{previewPreset.structure.map(item => <li key={item}>{item}</li>)}</ol></div>
+ <button type="button" onClick={usePreviewPreset}>{previewPreset.id === presetId ? l('继续使用这个模板', 'Keep using this template') : l('使用这个模板', 'Use this template')}</button>
+ </> : null}
+ </aside>
+ </div>
+ </section>
+ </div>, document.body
+ ) : null}
+
+ {workspacePhase === 'compose' ? <div className="wechat-article-footer-stack">
+ {configurationIssue && visibleError ? (
+ <div className="video-translation-run-notice is-error wechat-article-run-notice" role="alert">
+ <span>{visibleError}</span>
+ <a href={configurationIssue.href}>{configurationIssue.label}</a>
+ </div>
+ ) : null}
+ <footer className="video-translation-wizard-actions wechat-article-actions">
+ <button className="video-translation-secondary-action" type="button" onClick={() => currentStep === 0 ? props.onBack() : openStep((currentStep - 1) as ArticleStep)}>{currentStep === 0 ? l('返回', 'Back') : l('上一步', 'Back')}</button>
+ {currentStep === 0 ? <button className="video-translation-primary-action" type="button" disabled={running || uploading} onClick={() => void continueFromInspiration()}>{running && latestStage?.stageId === 'sources' ? <LoaderCircle className="smart-dubbing-spinner" size={15} /> : null}{sourceCount > 0 ? l('解析灵感并继续', 'Parse inspiration and continue') : l('继续', 'Continue')}</button> : null}
+ {currentStep === 1 ? <button className="video-translation-primary-action" type="button" disabled={running} onClick={() => void continueFromBrief()}>{l('继续生成选题', 'Continue to topics')}</button> : null}
+ {currentStep === 2 && topics.length > 0 ? <button className="video-translation-primary-action" type="button" disabled={!selectedTopicId || running} onClick={() => void generateOutline()}><Sparkles size={15} />{l('生成大纲', 'Generate outline')}</button> : null}
+ {currentStep === 3 && outline ? <button className="video-translation-primary-action" type="button" disabled={running} onClick={() => { setCurrentStep(4); setFurthestStep(Math.max(furthestStep, 4) as ArticleStep); void generateArticle(); }}>{l('确认大纲,开始写作', 'Approve outline and write')}</button> : null}
+ {currentStep === 4 && articleMarkdown ? <button className="video-translation-primary-action" type="button" disabled={running} onClick={() => { setCurrentStep(5); setFurthestStep(5); session?.updateDraft({ currentStep: 5, furthestStep: 5 }); }}>{l('完成编辑,选择排版', 'Finish editing and choose layout')}</button> : null}
+ {currentStep === 5 ? <button className="video-translation-primary-action" type="button" disabled={!articleMarkdown || running} onClick={() => void generateDocument()}>{documentRunning ? <LoaderCircle className="smart-dubbing-spinner" size={15} /> : <PackageOpen size={15} />}{documentRunning ? l('正在生成文档', 'Generating document') : l('生成文档', 'Generate document')}</button> : null}
+ </footer>
+ </div> : null}
+ </div>
+ </CreatorToolShell>
+ );
+}
+
+function ArticleEditorTextBlock(props: {
+ value: string;
+ label: string;
+ imageDragging: boolean;
+ imageDropTarget?: { offset: number; top: number };
+ trimLeadingWhitespace: boolean;
+ trimTrailingWhitespace: boolean;
+ onChange(value: string): void;
+ onSelect(offset: number): void;
+ onImageDragOver(target: { offset: number; top: number }): void;
+ onImageDragLeave(): void;
+ onImageDrop(offset: number): void;
+}) {
+ const ref = useRef<HTMLTextAreaElement>(null);
+ const displayed = articleEditorDisplayValue(
+ props.value,
+ props.trimLeadingWhitespace,
+ props.trimTrailingWhitespace
+ );
+
+ useLayoutEffect(() => {
+ const textarea = ref.current;
+ if (textarea === null) return;
+ textarea.style.height = '0px';
+ textarea.style.height = `${displayed.value ? Math.max(48, textarea.scrollHeight) : 18}px`;
+ }, [displayed.value]);
+
+ return (
+ <div
+ className="wechat-article-editor-text-block"
+ data-image-drop-active={props.imageDropTarget !== undefined}
+ data-markdown={props.value}
+ >
+ <textarea
+ ref={ref}
+ className="wechat-article-editor-segment"
+ data-empty={displayed.value.length === 0}
+ value={displayed.value}
+ onChange={event => props.onChange(`${displayed.prefix}${event.target.value}${displayed.suffix}`)}
+ onClick={event => props.onSelect(displayed.prefix.length + event.currentTarget.selectionStart)}
+ onKeyUp={event => props.onSelect(displayed.prefix.length + event.currentTarget.selectionStart)}
+ onSelect={event => props.onSelect(displayed.prefix.length + event.currentTarget.selectionStart)}
+ onDragOver={event => {
+ if (!props.imageDragging) return;
+ event.preventDefault();
+ event.dataTransfer.dropEffect = 'move';
+ props.onImageDragOver(articleImageDropPoint(event.currentTarget, event.clientY));
+ }}
+ onDragLeave={props.onImageDragLeave}
+ onDrop={event => {
+ if (!props.imageDragging) return;
+ event.preventDefault();
+ props.onImageDrop(displayed.prefix.length + articleImageDropPoint(event.currentTarget, event.clientY).offset);
+ }}
+ aria-label={props.label}
+ />
+ {props.imageDropTarget !== undefined ? (
+ <span
+ className="wechat-article-image-drop-indicator"
+ style={{ top: props.imageDropTarget.top }}
+ aria-hidden="true"
+ />
+ ) : null}
+ </div>
+ );
+}
+
+function articleEditorDisplayValue(
+ value: string,
+ trimLeadingWhitespace: boolean,
+ trimTrailingWhitespace: boolean
+): { value: string; prefix: string; suffix: string } {
+ const prefix = trimLeadingWhitespace
+ ? /^(?:[ \t]*\n)+/u.exec(value)?.[0] ?? ''
+ : '';
+ const withoutPrefix = value.slice(prefix.length);
+ const suffix = trimTrailingWhitespace
+ ? /(?:\n[ \t]*)+$/u.exec(withoutPrefix)?.[0] ?? ''
+ : '';
+ return {
+ value: withoutPrefix.slice(0, withoutPrefix.length - suffix.length),
+ prefix,
+ suffix
+ };
+}
+
+function articleImageDropPoint(
+ textarea: HTMLTextAreaElement,
+ clientY: number
+): { offset: number; top: number } {
+ const rect = textarea.getBoundingClientRect();
+ if (rect.height <= 0 || textarea.clientWidth <= 0) {
+ return { offset: textarea.selectionStart, top: 0 };
+ }
+ const offsets = articleParagraphBoundaryOffsets(textarea.value);
+ const computed = window.getComputedStyle(textarea);
+ const mirror = document.createElement('div');
+ mirror.style.position = 'fixed';
+ mirror.style.left = '-100000px';
+ mirror.style.top = '0';
+ mirror.style.visibility = 'hidden';
+ mirror.style.pointerEvents = 'none';
+ mirror.style.boxSizing = computed.boxSizing;
+ mirror.style.width = `${textarea.clientWidth}px`;
+ mirror.style.padding = computed.padding;
+ mirror.style.border = computed.border;
+ mirror.style.font = computed.font;
+ mirror.style.letterSpacing = computed.letterSpacing;
+ mirror.style.lineHeight = computed.lineHeight;
+ mirror.style.whiteSpace = 'pre-wrap';
+ mirror.style.overflowWrap = computed.overflowWrap || 'break-word';
+ mirror.style.wordBreak = computed.wordBreak;
+
+ const markers: Array<{ offset: number; element: HTMLSpanElement }> = [];
+ let cursor = 0;
+ offsets.forEach(offset => {
+ mirror.append(document.createTextNode(textarea.value.slice(cursor, offset)));
+ const marker = document.createElement('span');
+ marker.textContent = '\u200b';
+ mirror.append(marker);
+ markers.push({ offset, element: marker });
+ cursor = offset;
+ });
+ mirror.append(document.createTextNode(textarea.value.slice(cursor)));
+ document.body.append(mirror);
+ const targetY = clientY - rect.top + textarea.scrollTop;
+ const positions = markers.map(marker => ({
+ offset: marker.offset,
+ top: marker.element.offsetTop
+ }));
+ mirror.remove();
+ const closest = positions.reduce((best, candidate) => (
+ Math.abs(candidate.top - targetY) < Math.abs(best.top - targetY) ? candidate : best
+ ));
+ return {
+ offset: closest.offset,
+ top: Math.max(0, Math.min(rect.height, closest.top - textarea.scrollTop))
+ };
+}
+
+function articleParagraphBoundaryOffsets(value: string): number[] {
+ const offsets = new Set<number>([0, value.length]);
+ for (const match of value.matchAll(/\n[ \t]*\n/gu)) {
+ if (match.index !== undefined) offsets.add(match.index + match[0].length);
+ }
+ return [...offsets].sort((left, right) => left - right);
+}
+
+function WechatArticleStylePreview(props: { layout: WechatArticleLayoutStyleId }) {
+ return (
+ <span className="wechat-layout-sample" data-layout={props.layout} aria-hidden="true">
+ <i className="wechat-layout-sample-kicker" />
+ <i className="wechat-layout-sample-title" />
+ <i className="wechat-layout-sample-lead" />
+ <i className="wechat-layout-sample-heading"><b>01</b><em /></i>
+ <i className="wechat-layout-sample-lines"><b /><b /><b /></i>
+ <i className="wechat-layout-sample-callout"><b /><em /></i>
+ </span>
+ );
+}
+
+function readStep(value: CreatorJson | undefined): ArticleStep {
+ return typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= 5 ? value as ArticleStep : 0;
+}
+
+function readString(value: CreatorJson | undefined): string {
+ return typeof value === 'string' ? value : '';
+}
+
+function readNumber(value: CreatorJson | undefined): number {
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0;
+}
+
+function readBoolean(value: CreatorJson | undefined, fallback: boolean): boolean {
+ return typeof value === 'boolean' ? value : fallback;
+}
+
+function readStringArray(value: CreatorJson | undefined): string[] {
+ return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];
+}
+
+function readTopicCount(value: CreatorJson | undefined): number {
+ return typeof value === 'number' ? Math.max(3, Math.min(10, Math.round(value))) : 5;
+}
+
+function readArticleImageCount(value: CreatorJson | undefined): number {
+ return typeof value === 'number' ? Math.max(1, Math.min(10, Math.round(value))) : 5;
+}
+
+function readArticleImageStyle(value: CreatorJson | undefined): WechatArticleImageStyleId {
+ return articleImageStyleOptions.some(style => style.id === value)
+ ? value as WechatArticleImageStyleId
+ : 'editorial';
+}
+
+function splitArticleEditorParts(
+ markdown: string,
+ imageSources: Record<string, string>,
+ artifactsByHref: Record<string, CreatorArtifact>
+): ArticleEditorPart[] {
+ const parts: ArticleEditorPart[] = [];
+ const imagePattern = /!\[([^\]\n]*)\]\(([^)\s]+)\)/gu;
+ let cursor = 0;
+
+ for (const match of markdown.matchAll(imagePattern)) {
+ const href = match[2]!;
+ const src = imageSources[href];
+ const artifact = artifactsByHref[href];
+ if (!src || artifact === undefined || match.index === undefined) continue;
+ if (match.index > cursor) parts.push({ kind: 'text', markdown: markdown.slice(cursor, match.index) });
+ parts.push({
+ kind: 'image',
+ markdown: match[0],
+ alt: match[1]?.trim() || '',
+ href,
+ src,
+ artifactId: artifact.id
+ });
+ cursor = match.index + match[0].length;
+ }
+
+ if (cursor < markdown.length || parts.length === 0) {
+ parts.push({ kind: 'text', markdown: markdown.slice(cursor) });
+ }
+ return parts;
+}
+
+function readPreset(value: CreatorJson | undefined): WechatArticlePresetId {
+ const normalized = normalizeWritingTemplateId(readString(value));
+ return wechatArticlePresetCatalog.some(preset => preset.id === normalized) ? normalized : '';
+}
+
+function readLayoutStyle(value: CreatorJson | undefined): WechatArticleLayoutStyleId {
+ return wechatArticleLayoutStyles.some(style => style.id === value)
+ ? value as WechatArticleLayoutStyleId
+ : 'minimal';
+}
+
+function readWorkspacePhase(value: CreatorJson | undefined, hasDocument: boolean): ArticleWorkspacePhase {
+ if (value === 'compose' || value === 'result') return value;
+ return hasDocument ? 'result' : 'compose';
+}
+
+function readLinks(value: CreatorJson | undefined): WechatArticleSourceLink[] {
+ if (!Array.isArray(value)) return [];
+ return value.flatMap(item => {
+ if (!isRecord(item) || typeof item.id !== 'string' || typeof item.url !== 'string') return [];
+ if (item.kind !== 'video' && item.kind !== 'webpage') return [];
+ return [{ id: item.id, url: item.url, kind: item.kind, label: typeof item.label === 'string' ? item.label : '' }];
+ });
+}
+
+function readTopics(value: CreatorJson | undefined): WechatArticleTopic[] {
+ if (!Array.isArray(value)) return [];
+ return value.flatMap(item => {
+ if (!isRecord(item) || typeof item.id !== 'string' || typeof item.title !== 'string') return [];
+ return [{ id: item.id, title: item.title, angle: typeof item.angle === 'string' ? item.angle : '', summary: typeof item.summary === 'string' ? item.summary : '' }];
+ });
+}
+
+function isRecord(value: CreatorJson): value is Record<string, CreatorJson> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function latestArtifact(artifacts: CreatorArtifact[], kind: string): CreatorArtifact | undefined {
+ return [...artifacts].reverse().find(artifact => artifact.kind === kind && artifact.status === 'completed');
+}
+
+function latestArticleDocuments(artifacts: CreatorArtifact[]): CreatorArtifact[] {
+ const documents = artifacts.filter(artifact => artifact.kind === 'article_document' && artifact.status === 'completed');
+ if (documents.length === 0) return [];
+ const latestVersion = Math.max(...documents.map(artifact => readNumber(artifact.metadata.resultVersion) || artifact.version || 1));
+ const formatOrder = new Map([['markdown', 0], ['html', 1], ['pdf', 2]]);
+ return documents
+ .filter(artifact => (readNumber(artifact.metadata.resultVersion) || artifact.version || 1) === latestVersion)
+ .sort((left, right) => (
+ (formatOrder.get(articleDocumentFormat(left)) ?? 99)
+ - (formatOrder.get(articleDocumentFormat(right)) ?? 99)
+ ));
+}
+
+function articleDocumentFormat(artifact: CreatorArtifact): string {
+ const explicit = readString(artifact.metadata.documentFormat).toLowerCase();
+ if (explicit) return explicit;
+ const fileName = readString(artifact.metadata.fileName).toLowerCase();
+ if (fileName.endsWith('.html')) return 'html';
+ if (fileName.endsWith('.pdf')) return 'pdf';
+ return 'markdown';
+}
+
+function articleDocumentFormatLabel(format: string): string {
+ if (format === 'html') return 'HTML';
+ if (format === 'pdf') return 'PDF';
+ return 'Markdown';
+}
+
+function latestArticleImages(artifacts: CreatorArtifact[]): CreatorArtifact[] {
+ const images = artifacts.filter(artifact => (
+ artifact.kind === 'article_image'
+ && artifact.status === 'completed'
+ && artifact.metadata.source !== 'local-upload'
+ ));
+ if (images.length === 0) return [];
+ const latestVersion = Math.max(...images.map(artifact => readNumber(artifact.metadata.resultVersion) || artifact.version || 1));
+ return images
+ .filter(artifact => (readNumber(artifact.metadata.resultVersion) || artifact.version || 1) === latestVersion)
+ .sort((left, right) => readNumber(left.metadata.imageIndex) - readNumber(right.metadata.imageIndex));
+}
+
+function selectedManualArticleImages(artifacts: CreatorArtifact[], ids: string[]): CreatorArtifact[] {
+ const selected = new Map(artifacts
+ .filter(artifact => (
+ artifact.kind === 'article_image'
+ && artifact.status === 'completed'
+ && artifact.metadata.source === 'local-upload'
+ && ids.includes(artifact.id)
+ ))
+ .map(artifact => [artifact.id, artifact]));
+ return ids.flatMap(id => selected.get(id) ?? []);
+}
+
+function insertMarkdownImageAt(markdown: string, requestedOffset: number, imageMarkdown: string): string {
+ const offset = Math.max(0, Math.min(markdown.length, requestedOffset));
+ const before = markdown.slice(0, offset);
+ const after = markdown.slice(offset);
+ const leadingBreak = before.length === 0 || before.endsWith('\n\n') ? '' : before.endsWith('\n') ? '\n' : '\n\n';
+ const trailingBreak = after.length === 0 || after.startsWith('\n\n') ? '' : after.startsWith('\n') ? '\n' : '\n\n';
+ return `${before}${leadingBreak}${imageMarkdown}${trailingBreak}${after}`;
+}
+
+function articleImageMarkdownHref(artifact: CreatorArtifact): string {
+ const fileName = readString(artifact.metadata.fileName);
+ return fileName ? `./${fileName}` : '';
+}
+
+function imageAltFromFileName(fileName: string, l: (zh: string, en: string) => string): string {
+ const baseName = fileName.replace(/\.[^.]+$/u, '').trim();
+ return baseName && !isOpaqueImageFileName(baseName)
+ ? baseName
+ : l('文章配图', 'Article image');
+}
+
+function isOpaqueImageFileName(value: string): boolean {
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(value)
+ || /^[0-9a-f]{24,}$/iu.test(value);
+}
+
+function insertGeneratedArticleImages(markdown: string, artifacts: CreatorArtifact[]): string {
+ const cleanMarkdown = stripGeneratedArticleImages(markdown);
+ const lines = cleanMarkdown.split('\n');
+ const headings = lines.flatMap((line, lineIndex) => {
+ const match = /^(#{1,6})\s+(.+?)\s*$/.exec(line);
+ return match === null ? [] : [{ lineIndex, level: match[1]!.length, normalized: normalizeArticleHeading(match[2]!) }];
+ });
+ const sectionHeadings = headings.filter(heading => heading.level >= 2);
+ const fallbackHeadings = sectionHeadings.length > 0 ? sectionHeadings : headings;
+ const placements = new Map<number, string[]>();
+
+ artifacts.forEach((artifact, index) => {
+ const requestedHeading = normalizeArticleHeading(readString(artifact.metadata.placementHeading));
+ const matchedHeading = requestedHeading
+ ? headings.find(heading => heading.normalized === requestedHeading)
+ ?? headings.find(heading => heading.normalized.includes(requestedHeading) || requestedHeading.includes(heading.normalized))
+ : undefined;
+ const fallbackIndex = fallbackHeadings.length === 0
+ ? lines.length - 1
+ : Math.min(fallbackHeadings.length - 1, Math.floor(index * fallbackHeadings.length / Math.max(1, artifacts.length)));
+ const lineIndex = matchedHeading?.lineIndex ?? fallbackHeadings[fallbackIndex]?.lineIndex ?? lines.length - 1;
+ const fileName = readString(artifact.metadata.fileName) || `article-image-${String(index + 1).padStart(2, '0')}.png`;
+ const caption = sanitizeMarkdownImageAlt(readString(artifact.metadata.caption) || `文章配图 ${index + 1}`);
+ const references = placements.get(lineIndex) ?? [];
+ references.push(`![${caption}](./${fileName})`);
+ placements.set(lineIndex, references);
+ });
+
+ const output: string[] = [];
+ lines.forEach((line, lineIndex) => {
+ output.push(line);
+ const references = placements.get(lineIndex);
+ if (references !== undefined) output.push('', ...references.flatMap(reference => [reference, '']));
+ });
+ return output.join('\n').replace(/\n{3,}/g, '\n\n').trim();
+}
+
+function stripGeneratedArticleImages(markdown: string): string {
+ return markdown
+ .replace(/^[ \t]*!\[[^\]\n]*\]\((?:\.\/)?article-image-\d+\.(?:png|jpe?g|webp)\)[ \t]*$/gim, '')
+ .replace(/\n{3,}/g, '\n\n')
+ .trim();
+}
+
+function normalizeArticleHeading(value: string): string {
+ return value
+ .replace(/^#{1,6}\s*/, '')
+ .replace(/[\s*_`\[\]()()【】《》::,.,。!?!?-]+/g, '')
+ .toLocaleLowerCase();
+}
+
+function sanitizeMarkdownImageAlt(value: string): string {
+ return value.replace(/[\[\]\r\n]+/g, ' ').trim();
+}
+
+function selectedDocuments(artifacts: CreatorArtifact[], ids: string[]): CreatorArtifact[] {
+ return artifacts.filter(artifact => ids.includes(artifact.id) && artifact.kind === 'source_document' && artifact.status === 'completed');
+}
+
+function isVideoUrl(url: URL): boolean {
+ return /(^|\.)(youtube\.com|youtu\.be|bilibili\.com|b23\.tv)$/i.test(url.hostname);
+}
+
+function createId(prefix: string): string {
+ return typeof crypto.randomUUID === 'function' ? `${prefix}-${crypto.randomUUID()}` : `${prefix}-${Date.now()}`;
+}
+
+function formatBytes(value: number): string {
+ if (value < 1024) return `${value} B`;
+ if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`;
+ return `${(value / 1024 / 1024).toFixed(1)} MB`;
+}
+
+function formatNumber(value: number): string {
+ return new Intl.NumberFormat().format(value);
+}
+
+function countArticleCharacters(markdown: string): number {
+ const visibleText = markdown
+ .replace(/!\[[^\]]*\]\([^)]*\)/gu, '')
+ .replace(/\[([^\]]+)\]\([^)]*\)/gu, '$1')
+ .replace(/^\s*(?:```|~~~).*$/gmu, '')
+ .replace(/`([^`]*)`/gu, '$1')
+ .replace(/^\s*(?:#{1,6}|>|[-+*]|\d+[.)])\s+/gmu, '')
+ .replace(/^\s*(?:-{3,}|_{3,}|\*{3,})\s*$/gmu, '')
+ .replace(/<[^>]+>/gu, '')
+ .replace(/[*_~|]/gu, '')
+ .replace(/\s+/gu, '');
+ return [...visibleText].length;
+}
+
+function formatDocumentUploadError(
+ cause: unknown,
+ l: (zh: string, en: string) => string
+): string {
+ const candidate = cause as { code?: unknown; message?: unknown };
+ const code = typeof candidate?.code === 'string' ? candidate.code : '';
+ const message = typeof candidate?.message === 'string' ? candidate.message : String(cause);
+ if (code === 'creator_document_too_large' || /Document exceeds the \d+ byte limit/i.test(message)) {
+ return l('文件不能超过 25 MB', 'The file must be 25 MB or smaller.');
+ }
+ if (code === 'creator_document_empty') return l('不能上传空文件', 'The file is empty.');
+ if (code === 'creator_document_type_unsupported') {
+ return l('仅支持 PDF、Markdown、TXT 和 HTML 文件', 'Only PDF, Markdown, TXT, and HTML files are supported.');
+ }
+ return message || l('文件上传失败,请重试', 'File upload failed. Try again.');
+}
+
+function formatArticleImageUploadError(
+ cause: unknown,
+ l: (zh: string, en: string) => string
+): string {
+ const candidate = cause as { code?: unknown; message?: unknown };
+ const code = typeof candidate?.code === 'string' ? candidate.code : '';
+ const message = typeof candidate?.message === 'string' ? candidate.message : String(cause);
+ if (code === 'creator_reference_too_large') {
+ return l('图片不能超过 20 MB', 'The image must be 20 MB or smaller.');
+ }
+ if (code === 'creator_reference_empty') return l('不能上传空图片', 'The image is empty.');
+ if (code === 'creator_reference_invalid' || code === 'creator_reference_type_unsupported') {
+ return l('仅支持 PNG、JPG 和 WebP 图片', 'Only PNG, JPG, and WebP images are supported.');
+ }
+ return message || l('图片上传失败,请重试', 'Image upload failed. Try again.');
+}
+
+function formatArticleStageError(
+ code: string | null | undefined,
+ message: string | null | undefined,
+ sourceName: string,
+ l: (zh: string, en: string) => string
+): string {
+ const target = sourceName ? `:${sourceName}` : '';
+ if (code === 'creator_source_transcript_missing') {
+ return l(`没有找到可用的视频字幕${target}`, `No usable video subtitles were found${sourceName ? `: ${sourceName}` : ''}.`);
+ }
+ if (code === 'creator_runtime_dependency_missing') {
+ return l('缺少视频解析组件,暂时无法读取视频字幕', 'The video parser is unavailable, so subtitles cannot be read.');
+ }
+ if (code === 'creator_source_empty') {
+ return l(`没有提取到可用正文${target}`, `No readable content was extracted${sourceName ? `: ${sourceName}` : ''}.`);
+ }
+ if (code === 'creator_source_unavailable') {
+ return l(`无法读取这个内容灵感,请检查链接或文件${target}`, `This inspiration source could not be read${sourceName ? `: ${sourceName}` : ''}.`);
+ }
+ if (code === 'creator_image_config_missing') {
+ return l('请先配置图像生成服务', 'Configure an image generation service first.');
+ }
+ if (code === 'image_generation_failed') {
+ return l('文章配图生成失败,请检查图像服务后重试', 'Article image generation failed. Check the image service and try again.');
+ }
+ return message || l('生成失败,请检查写作模型配置后重试', 'Generation failed. Check the text model settings and try again.');
+}
+
+function formatArticleSessionError(
+ code: string | undefined,
+ message: string | undefined,
+ l: (zh: string, en: string) => string
+): string {
+ if (!message) return '';
+ if (isPresetValidationError(message)) {
+ return l('文章模板状态已更新,请刷新页面后重新选择', 'The article template state changed. Refresh the page and choose again.');
+ }
+ if (code === 'creator_revision_conflict') {
+ return l('文章已在其他位置更新,请刷新后继续', 'The article changed elsewhere. Refresh before continuing.');
+ }
+ return message;
+}
+
+function isPresetValidationError(message: string): boolean {
+ try {
+ const issues = JSON.parse(message) as unknown;
+ return Array.isArray(issues) && issues.some(issue => (
+ isUnknownRecord(issue)
+ && Array.isArray(issue.path)
+ && issue.path.includes('presetId')
+ ));
+ } catch {
+ return message.includes('presetId')
+ && (message.includes('invalid_enum_value') || message.includes('Unknown writing template'));
+ }
+}
+
+function isUnknownRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function safeFileName(value: string): string {
+ return value.trim().replace(/[\\/:*?"<>|]/g, '-').replace(/\s+/g, ' ').slice(0, 80) || 'wechat-article';
+}
diff --git a/apps/web/src/features/dashboard/creator-panel-adapters.ts b/apps/web/src/features/dashboard/creator-panel-adapters.ts
index 4c6b27c2..3c2d72a7 100644
--- a/apps/web/src/features/dashboard/creator-panel-adapters.ts
+++ b/apps/web/src/features/dashboard/creator-panel-adapters.ts
@@ -400,6 +400,58 @@ export const xiaohongshuPostPanelAdapter: CreatorPanelAdapter = {
}
};
+export const wechatArticlePanelAdapter: CreatorPanelAdapter = {
+ id: 'wechat-article',
+ composerPlaceholder: l => l(
+ '询问写作进度,或调整选题、结构、正文和配图要求',
+ 'Ask about progress or adjust the topic, structure, article, and images'
+ ),
+ stageLabel(stageId, l) {
+ if (stageId === 'sources') return l('解析内容灵感', 'Parse inspiration sources');
+ if (stageId === 'topics') return l('生成候选选题', 'Generate topic options');
+ if (stageId === 'outline') return l('生成文章大纲', 'Generate article outline');
+ if (stageId === 'article') return l('撰写文章正文', 'Write article');
+ if (stageId === 'images') return l('生成文章配图', 'Generate article images');
+ if (stageId === 'document') return l('生成文章文档', 'Generate article document');
+ return l('文章写作', 'Article writing');
+ },
+ phaseLabel(phase, l) {
+ const labels: Record<string, string> = {
+ collecting_sources: l('整理内容灵感', 'Collecting inspiration'),
+ reading_video: l('读取视频内容', 'Reading video content'),
+ reading_webpage: l('读取网页内容', 'Reading webpage content'),
+ reading_document: l('读取文档内容', 'Reading document content'),
+ generating_topics: l('生成候选选题', 'Generating topic options'),
+ generating_outline: l('生成文章大纲', 'Generating the article outline'),
+ writing_article: l('撰写文章正文', 'Writing the article'),
+ planning_article_images: l('规划文章配图', 'Planning article images'),
+ generating_article_images: l('生成文章配图', 'Generating article images'),
+ preparing_document: l('整理文章文档', 'Preparing the article document'),
+ completed: l('内容已生成', 'Content generated')
+ };
+ return labels[phase] ?? genericPhaseLabel(phase, l);
+ },
+ activityStageId: readActivityStageId,
+ normalizeActivity(activity, l) {
+ if (activity.action.startsWith('update-settings')) {
+ return normalizeWechatArticleUpdateActivity(activity, l);
+ }
+ return normalizeCommonActivity(activity, l, wechatArticlePanelAdapter, {
+ 'register-source-document': l('上传了内容灵感', 'Uploaded an inspiration source')
+ }, wechatArticleFieldLabel);
+ },
+ readStageProgress: readStandardProgress,
+ succeededProgressText(stage, l) {
+ if (stage.stageId === 'sources') return l('内容灵感已解析', 'Inspiration sources parsed');
+ if (stage.stageId === 'topics') return l('候选选题已生成', 'Topic options generated');
+ if (stage.stageId === 'outline') return l('文章大纲已生成', 'Article outline generated');
+ if (stage.stageId === 'article') return l('文章正文已生成', 'Article generated');
+ if (stage.stageId === 'images') return l('文章配图已生成', 'Article images generated');
+ if (stage.stageId === 'document') return l('文章文档已生成', 'Article document generated');
+ return null;
+ }
+};
+
export const videoGenerationPanelAdapter: CreatorPanelAdapter = {
id: 'video-generation',
composerPlaceholder: l => l(
@@ -480,6 +532,7 @@ export function creatorPanelAdapterFor(templateId: string): CreatorPanelAdapter
if (templateId === 'video-download') return videoDownloadPanelAdapter;
if (templateId === 'smart-dubbing') return smartDubbingPanelAdapter;
if (templateId === 'xiaohongshu-post') return xiaohongshuPostPanelAdapter;
+ if (templateId === 'wechat-article') return wechatArticlePanelAdapter;
if (templateId === 'cover') return coverPanelAdapter;
if (templateId === 'video-generation') return videoGenerationPanelAdapter;
return genericAdapter;
@@ -641,6 +694,30 @@ function xiaohongshuPostFieldLabel(
return labels[field] ?? null;
}
+function wechatArticleFieldLabel(
+ field: string,
+ l: CreatorPanelLocalize
+): string | null {
+ const labels: Record<string, string> = {
+ sourceLinks: l('链接灵感', 'Linked inspiration'),
+ sourceDocumentArtifactIds: l('文档灵感', 'Document inspiration'),
+ writingPrompt: l('写作要求', 'Writing brief'),
+ topicCount: l('选题数量', 'Topic count'),
+ topics: l('候选选题', 'Topic options'),
+ selectedTopicId: l('选定选题', 'Selected topic'),
+ outline: l('文章大纲', 'Article outline'),
+ presetId: l('文章模板', 'Article template'),
+ layoutStyleId: l('排版风格', 'Layout style'),
+ templatePrompt: l('模板要求', 'Template instructions'),
+ articleMarkdown: l('文章正文', 'Article content'),
+ autoGenerateImages: l('文章配图', 'Article images'),
+ articleImageCount: l('配图数量', 'Image count'),
+ articleImageStyleId: l('生图风格', 'Image style'),
+ articleImagePrompt: l('配图要求', 'Image direction')
+ };
+ return labels[field] ?? null;
+}
+
function videoGenerationFieldLabel(
field: string,
l: CreatorPanelLocalize
@@ -656,6 +733,55 @@ function videoGenerationFieldLabel(
return labels[field] ?? null;
}
+function normalizeWechatArticleUpdateActivity(
+ activity: CreatorActivity,
+ l: CreatorPanelLocalize
+): NormalizedCreatorActivity | null {
+ const objectId = readString(activity.details.objectId) ?? '';
+ const fieldIds = objectId.split(',').filter(field => wechatArticleFieldLabel(field, l) !== null);
+ if (fieldIds.length === 0) return null;
+ const fieldSet = new Set(fieldIds);
+
+ if (fieldSet.has('selectedTopicId')) {
+ return { label: l('选定了文章选题', 'Selected the article topic'), fields: [] };
+ }
+ if (fieldSet.has('outline')) {
+ return { label: l('生成了文章大纲', 'Generated the article outline'), fields: [] };
+ }
+ if (fieldSet.has('articleMarkdown')) {
+ return { label: l('生成了文章正文', 'Generated the article'), fields: [] };
+ }
+ if (fieldSet.has('topics')) {
+ return { label: l('生成了候选选题', 'Generated topic options'), fields: [] };
+ }
+
+ const fields = [...new Set(fieldIds
+ .map(field => wechatArticleFieldLabel(field, l))
+ .filter((field): field is string => field !== null))];
+ const hasImageSettings = fieldIds.some(field => [
+ 'autoGenerateImages',
+ 'articleImageCount',
+ 'articleImageStyleId',
+ 'articleImagePrompt'
+ ].includes(field));
+ if (hasImageSettings) {
+ return { label: l('调整了文章配图', 'Adjusted article images'), fields };
+ }
+ if (fieldSet.has('layoutStyleId')) {
+ return { label: l('选择了排版风格', 'Selected the layout style'), fields };
+ }
+ const hasWritingBrief = fieldIds.some(field => [
+ 'writingPrompt',
+ 'topicCount',
+ 'presetId',
+ 'templatePrompt'
+ ].includes(field));
+ if (hasWritingBrief) {
+ return { label: l('完善了写作要求', 'Refined the writing brief'), fields };
+ }
+ return { label: l('更新了内容灵感', 'Updated inspiration sources'), fields };
+}
+
function readActivityStageId(activity: CreatorActivity): string | null {
const structured = readString(activity.details.stageId);
if (structured !== null) return structured;
diff --git a/apps/web/src/features/dashboard/creator-session-store.tsx b/apps/web/src/features/dashboard/creator-session-store.tsx
index 1c63a569..63bb8f42 100644
--- a/apps/web/src/features/dashboard/creator-session-store.tsx
+++ b/apps/web/src/features/dashboard/creator-session-store.tsx
@@ -7,6 +7,7 @@ import type {
CreatorAgentSession,
CreatorAgentTurn,
CreatorAgentTurnRequest,
+ CreatorArtifact,
CreatorEventEnvelope,
CreatorJob,
CreatorJson,
@@ -42,6 +43,8 @@ type CreatorSessionContextValue = {
resumeJob(): Promise<void>;
uploadSourceVideo(file: File): Promise<void>;
uploadReferenceImage(file: File): Promise<void>;
+ uploadArticleImage(file: File): Promise<CreatorArtifact>;
+ uploadSourceDocument(file: File): Promise<void>;
openArtifact(artifactId: string): Promise<Response>;
agentSession: CreatorAgentSession | null;
turns: CreatorAgentTurn[];
@@ -78,7 +81,9 @@ export function CreatorSessionProvider(props: {
| 'getJob'
| 'openArtifact'
| 'uploadReferenceImage'
+ | 'uploadArticleImage'
| 'uploadSourceVideo'
+ | 'uploadSourceDocument'
| 'cancelJob'
| 'resumeJob'
| 'subscribeJobEvents'>>;
@@ -395,6 +400,55 @@ export function CreatorSessionProvider(props: {
}
}, [ensurePersistedJob, flush, props.service]);
+ const uploadArticleImage = useCallback(async (file: File): Promise<CreatorArtifact> => {
+ if (props.service.uploadArticleImage === undefined) {
+ throw new Error('Creator article image upload transport is unavailable');
+ }
+ let requestRevision = confirmedRef.current.revision;
+ try {
+ await flush();
+ await ensurePersistedJob();
+ requestRevision = confirmedRef.current.revision;
+ const response = await props.service.uploadArticleImage(confirmedRef.current.id, {
+ file,
+ expectedRevision: requestRevision
+ });
+ confirmedRef.current = response.job;
+ setConfirmedJob(response.job);
+ setError(null);
+ return response.artifact;
+ } catch (cause) {
+ if (!isSupersededRevisionConflict(cause, requestRevision, confirmedRef.current.revision)) {
+ setError(toSessionError(cause));
+ }
+ throw cause;
+ }
+ }, [ensurePersistedJob, flush, props.service]);
+
+ const uploadSourceDocument = useCallback(async (file: File) => {
+ if (props.service.uploadSourceDocument === undefined) {
+ throw new Error('Creator document upload transport is unavailable');
+ }
+ let requestRevision = confirmedRef.current.revision;
+ try {
+ await flush();
+ await ensurePersistedJob();
+ requestRevision = confirmedRef.current.revision;
+ const response = await props.service.uploadSourceDocument(confirmedRef.current.id, {
+ file,
+ expectedRevision: requestRevision
+ });
+ confirmedRef.current = response.job;
+ setConfirmedJob(response.job);
+ setError(null);
+ } catch (cause) {
+ if (!isSupersededRevisionConflict(cause, requestRevision, confirmedRef.current.revision)) {
+ setError(toSessionError(cause));
+ }
+ throw cause;
+ }
+ }, [ensurePersistedJob, flush, props.service]);
+
const cancelJob = useCallback(async () => {
if (props.service.cancelJob === undefined) {
throw new Error('Creator job cancellation is unavailable');
@@ -549,7 +603,9 @@ export function CreatorSessionProvider(props: {
cancelJob,
resumeJob,
uploadReferenceImage,
+ uploadSourceDocument,
uploadSourceVideo,
+ uploadArticleImage,
openArtifact,
agentSession,
turns,
@@ -560,7 +616,7 @@ export function CreatorSessionProvider(props: {
steerAgentTurn,
interruptAgentTurn,
respondAgentApproval
- }), [agentBusy, agentSession, applyAction, applyRemoteSnapshot, approvals, cancelJob, clearError, confirmedJob, conflictedFields, draft, error, flush, interruptAgentTurn, items, openArtifact, respondAgentApproval, resumeJob, runAgentTurn, steerAgentTurn, turns, updateDraft, uploadReferenceImage, uploadSourceVideo]);
+ }), [agentBusy, agentSession, applyAction, applyRemoteSnapshot, approvals, cancelJob, clearError, confirmedJob, conflictedFields, draft, error, flush, interruptAgentTurn, items, openArtifact, respondAgentApproval, resumeJob, runAgentTurn, steerAgentTurn, turns, updateDraft, uploadArticleImage, uploadReferenceImage, uploadSourceDocument, uploadSourceVideo]);
return (
<CreatorSessionContext.Provider value={value}>
diff --git a/apps/web/src/features/dashboard/creator-workspace.ts b/apps/web/src/features/dashboard/creator-workspace.ts
index b534a95f..03cdffe2 100644
--- a/apps/web/src/features/dashboard/creator-workspace.ts
+++ b/apps/web/src/features/dashboard/creator-workspace.ts
@@ -5,6 +5,7 @@ export type CreatorWorkspace =
| 'auto-clips'
| 'smart-dubbing'
| 'xiaohongshu-post'
+ | 'wechat-article'
| 'digital-avatar'
| 'cover-generator'
| 'image-generation'
@@ -17,6 +18,7 @@ export const creatorWorkspaces = [
'auto-clips',
'smart-dubbing',
'xiaohongshu-post',
+ 'wechat-article',
'digital-avatar',
'cover-generator',
'image-generation',
@@ -28,6 +30,7 @@ export const visibleCreatorWorkspaces = [
'video-download',
'smart-dubbing',
'xiaohongshu-post',
+ 'wechat-article',
'cover-generator',
'image-generation',
'video-generation'
@@ -40,6 +43,7 @@ export const creatorRuntimeWorkspaces = [
'auto-clips',
'smart-dubbing',
'xiaohongshu-post',
+ 'wechat-article',
'cover-generator',
'image-generation',
'video-generation'
@@ -54,6 +58,7 @@ const templateByWorkspace: Record<CreatorRuntimeWorkspace, string> = {
'auto-clips': 'auto-clip',
'smart-dubbing': 'smart-dubbing',
'xiaohongshu-post': 'xiaohongshu-post',
+ 'wechat-article': 'wechat-article',
'cover-generator': 'cover',
'image-generation': 'image-generation',
'video-generation': 'video-generation'
diff --git a/apps/web/src/features/dashboard/dashboard.css b/apps/web/src/features/dashboard/dashboard.css
index b64e39e0..7007d440 100644
--- a/apps/web/src/features/dashboard/dashboard.css
+++ b/apps/web/src/features/dashboard/dashboard.css
@@ -1337,7 +1337,7 @@
height: 100%;
min-width: 960px;
display: grid;
- grid-template-columns: minmax(620px, 2fr) minmax(320px, 1fr);
+ grid-template-columns: minmax(640px, 3fr) minmax(320px, 1fr);
}
.creator-workspace-main {
@@ -1407,7 +1407,7 @@
}
.creator-tool-stack {
- width: min(880px, 100%);
+ width: min(1120px, 100%);
display: grid;
gap: 14px;
margin: 0 auto;
@@ -1471,7 +1471,9 @@
font-weight: 650;
}
-.creator-tool-panel-heading h2 {
+.creator-tool-panel-heading h2,
+.wechat-layout-preview-heading h2 {
+ margin: 0;
font-size: 17px;
font-weight: 650;
line-height: 1.3;
@@ -2411,6 +2413,3255 @@
}
}
+.wechat-article-workspace-content {
+ overflow: hidden;
+}
+
+.wechat-article-stack {
+ position: relative;
+ height: 100%;
+ grid-template-rows: auto minmax(0, 1fr) auto;
+}
+
+.wechat-article-stack[data-step="4"] {
+ row-gap: 0;
+}
+
+.wechat-article-toast {
+ position: absolute;
+ z-index: 12;
+ top: 60px;
+ left: 50%;
+ width: min(420px, calc(100% - 32px));
+ min-height: 44px;
+ display: grid;
+ grid-template-columns: 24px minmax(0, 1fr) 28px;
+ align-items: center;
+ gap: 8px;
+ padding: 9px 9px 9px 12px;
+ border: 1px solid var(--border-strong);
+ border-radius: 8px;
+ background: var(--surface);
+ box-shadow: 0 12px 32px color-mix(in srgb, var(--text) 14%, transparent);
+ color: var(--text);
+ transform: translateX(-50%);
+ box-sizing: border-box;
+}
+
+.wechat-article-toast > span {
+ width: 24px;
+ height: 24px;
+ display: grid;
+ place-items: center;
+ color: var(--danger);
+}
+
+.wechat-article-toast[data-tone="success"] > span {
+ color: var(--success);
+}
+
+.wechat-article-toast > div {
+ min-width: 0;
+ display: grid;
+ gap: 3px;
+}
+
+.wechat-article-toast p {
+ min-width: 0;
+ color: var(--text);
+ font-size: 12px;
+ line-height: 1.45;
+}
+
+.wechat-article-toast a {
+ width: fit-content;
+ color: var(--accent);
+ font-size: 11px;
+ font-weight: 650;
+ text-decoration: none;
+}
+
+.wechat-article-toast a:hover {
+ text-decoration: underline;
+}
+
+.wechat-article-toast button {
+ width: 28px;
+ height: 28px;
+ display: grid;
+ place-items: center;
+ border: 0;
+ border-radius: 6px;
+ background: transparent;
+ color: var(--muted);
+}
+
+.wechat-article-toast button:hover {
+ background: var(--surface-2);
+ color: var(--text);
+}
+
+.wechat-article-toast button:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 1px;
+}
+
+.wechat-article-stack[data-phase="result"] {
+ grid-template-rows: minmax(0, 1fr);
+}
+
+.wechat-result-workspace .creator-result-layout {
+ flex: 1 1 auto;
+ min-height: 0;
+ grid-template-rows: minmax(0, 1fr);
+ align-items: stretch;
+ overflow: hidden;
+}
+
+.wechat-result-workspace .creator-result-layout > .creator-task-summary {
+ align-self: start;
+}
+
+.wechat-result-content {
+ display: grid;
+ align-content: start;
+ gap: 18px;
+}
+
+.wechat-result-document-list {
+ display: grid;
+ gap: 10px;
+}
+
+.wechat-result-image-assets {
+ display: grid;
+ gap: 10px;
+ padding: 14px;
+ border: 1px solid var(--border-hairline);
+ border-radius: 8px;
+ background: var(--surface);
+}
+
+.wechat-result-image-assets > header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+}
+
+.wechat-result-image-assets > header > div {
+ min-width: 0;
+ display: grid;
+ gap: 2px;
+}
+
+.wechat-result-image-assets > header strong {
+ font-size: 12px;
+}
+
+.wechat-result-image-assets > header small {
+ color: var(--muted);
+ font-size: 10px;
+}
+
+.wechat-result-image-assets > header > span {
+ flex: 0 0 auto;
+ padding: 3px 6px;
+ border-radius: 5px;
+ background: color-mix(in srgb, var(--accent) 9%, var(--surface-2));
+ color: var(--accent);
+ font-size: 9px;
+ font-weight: 650;
+}
+
+.wechat-result-image-assets > div {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 8px;
+}
+
+.wechat-result-image-assets article {
+ min-width: 0;
+ display: grid;
+ grid-template-columns: 76px minmax(0, 1fr) 30px;
+ align-items: center;
+ gap: 9px;
+ padding: 7px;
+ border: 1px solid var(--border-hairline);
+ border-radius: 7px;
+ background: var(--surface-2);
+}
+
+.wechat-result-image-assets article > div {
+ width: 76px;
+ aspect-ratio: 3 / 2;
+ display: grid;
+ place-items: center;
+ overflow: hidden;
+ border-radius: 5px;
+ background: var(--surface-3);
+ color: var(--subtle);
+}
+
+.wechat-result-image-assets img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+
+.wechat-result-image-assets article > section {
+ min-width: 0;
+ display: grid;
+ gap: 3px;
+}
+
+.wechat-result-image-assets article > section strong,
+.wechat-result-image-assets article > section small {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.wechat-result-image-assets article > section strong {
+ font-size: 10px;
+}
+
+.wechat-result-image-assets article > section small {
+ color: var(--subtle);
+ font-size: 9px;
+}
+
+.wechat-result-image-assets article > button {
+ width: 30px;
+ height: 30px;
+ display: grid;
+ place-items: center;
+ padding: 0;
+ border: 0;
+ border-radius: 6px;
+ background: transparent;
+ color: var(--muted);
+}
+
+.wechat-result-image-assets article > button:hover {
+ background: var(--state-hover-bg);
+ color: var(--text);
+}
+
+.video-translation-steps.wechat-article-steps ol {
+ grid-template-columns: repeat(6, minmax(0, 1fr));
+}
+
+.wechat-article-scroll {
+ min-height: 0;
+ overflow-y: auto;
+ padding: 2px;
+ scrollbar-gutter: stable;
+}
+
+.wechat-article-scroll[data-step="4"] {
+ overflow: hidden;
+ scrollbar-gutter: auto;
+}
+
+.wechat-article-scroll[data-step="4"] > .wechat-article-panel {
+ height: 100%;
+ min-height: 0;
+ display: grid;
+ grid-template-rows: auto minmax(0, 1fr);
+}
+
+.wechat-inspiration-panel {
+ overflow: hidden;
+ padding: 0;
+}
+
+.wechat-inspiration-heading {
+ margin: 0;
+ padding: 20px;
+ border-bottom: 1px solid var(--border-hairline);
+}
+
+.wechat-inspiration-workbench {
+ min-height: 430px;
+ display: grid;
+ grid-template-columns: 280px minmax(0, 1fr);
+}
+
+.wechat-inspiration-library {
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ padding: 18px;
+ border-right: 1px solid var(--border-hairline);
+ background: color-mix(in srgb, var(--surface-2) 64%, var(--surface));
+}
+
+.wechat-inspiration-library > header {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 12px;
+}
+
+.wechat-inspiration-library > header > div,
+.wechat-inspiration-link-section > div {
+ min-width: 0;
+ display: grid;
+ gap: 3px;
+}
+
+.wechat-inspiration-library > header strong,
+.wechat-inspiration-link-section > div strong {
+ color: var(--text);
+ font-size: 13px;
+ font-weight: 650;
+}
+
+.wechat-inspiration-library > header span,
+.wechat-inspiration-link-section > div span {
+ color: var(--muted);
+ font-size: 11px;
+ line-height: 1.4;
+}
+
+.wechat-inspiration-library > header b {
+ flex: 0 0 auto;
+ min-width: 42px;
+ padding: 4px 7px;
+ border: 1px solid color-mix(in srgb, var(--accent) 24%, var(--border));
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--accent) 7%, var(--surface));
+ color: var(--accent);
+ font-size: 11px;
+ font-weight: 700;
+ text-align: center;
+}
+
+.wechat-inspiration-add {
+ min-width: 0;
+ display: grid;
+ align-content: start;
+ gap: 22px;
+ padding: 24px;
+}
+
+.wechat-inspiration-dropzone {
+ min-height: 220px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ padding: 28px;
+ border: 1px dashed var(--border);
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--surface-2) 54%, transparent);
+ text-align: center;
+ transition: border-color 140ms ease, background-color 140ms ease;
+}
+
+.wechat-inspiration-dropzone[data-active="true"] {
+ border-color: var(--accent);
+ background: color-mix(in srgb, var(--accent) 6%, var(--surface));
+}
+
+.wechat-inspiration-dropzone[data-disabled="true"] {
+ background: var(--surface-2);
+}
+
+.wechat-inspiration-drop-icon {
+ width: 42px;
+ height: 42px;
+ display: grid;
+ place-items: center;
+ margin-bottom: 2px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: var(--surface);
+ color: var(--accent);
+}
+
+.wechat-inspiration-dropzone > strong {
+ color: var(--text);
+ font-size: 14px;
+}
+
+.wechat-inspiration-dropzone > p {
+ color: var(--muted);
+ font-size: 12px;
+ line-height: 1.45;
+}
+
+.wechat-inspiration-dropzone > button {
+ min-height: 34px;
+ margin-top: 3px;
+ padding: 0 14px;
+ border: 1px solid var(--accent);
+ border-radius: 7px;
+ background: var(--accent);
+ color: var(--on-accent);
+ font-size: 12px;
+ font-weight: 650;
+}
+
+.wechat-inspiration-dropzone > small {
+ margin-top: 2px;
+ color: var(--subtle);
+ font-size: 10px;
+ line-height: 1.4;
+}
+
+.wechat-inspiration-link-section {
+ display: grid;
+ gap: 11px;
+}
+
+.wechat-inline-input {
+ min-height: 42px;
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr) auto;
+ align-items: center;
+ gap: 9px;
+ padding: 0 8px 0 12px;
+ border: 1px solid var(--border);
+ border-radius: 7px;
+ background: var(--surface);
+}
+
+.wechat-inline-input:focus-within {
+ border-color: var(--accent);
+}
+
+.wechat-inline-input > svg {
+ color: var(--subtle);
+}
+
+.wechat-inline-input input {
+ min-width: 0;
+ height: 40px;
+ padding: 0;
+ border: 0;
+ outline: 0;
+ background: transparent;
+ color: var(--text);
+}
+
+.wechat-inline-input button,
+.wechat-generate-button,
+.wechat-article-toolbar > button {
+ min-height: 32px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ padding: 0 11px;
+ border: 1px solid var(--border);
+ border-radius: 7px;
+ background: var(--surface-2);
+ color: var(--text);
+ font-size: 12px;
+ font-weight: 600;
+}
+
+.wechat-inline-input input:disabled {
+ color: var(--subtle);
+ cursor: not-allowed;
+}
+
+.wechat-inline-input button:disabled,
+.wechat-inspiration-dropzone > button:disabled {
+ opacity: .48;
+ cursor: not-allowed;
+}
+
+.wechat-inspiration-capacity {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding-top: 14px;
+ border-top: 1px solid var(--border-hairline);
+ color: var(--muted);
+ font-size: 11px;
+}
+
+.wechat-inspiration-capacity small {
+ color: var(--subtle);
+ text-align: right;
+}
+
+.wechat-source-list {
+ min-height: 0;
+ display: grid;
+ align-content: start;
+ gap: 8px;
+ overflow-y: auto;
+}
+
+.wechat-source-list > div {
+ min-width: 0;
+ display: grid;
+ grid-template-columns: 30px minmax(0, 1fr) 28px;
+ align-items: center;
+ gap: 9px;
+ padding: 9px 10px;
+ border: 1px solid var(--border-hairline);
+ border-radius: 7px;
+ background: var(--surface-2);
+}
+
+.wechat-source-list > div > span {
+ width: 30px;
+ height: 30px;
+ display: grid;
+ place-items: center;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ color: var(--muted);
+}
+
+.wechat-source-list > div > div {
+ min-width: 0;
+ display: grid;
+ gap: 2px;
+}
+
+.wechat-source-list strong {
+ font-size: 12px;
+}
+
+.wechat-source-list small {
+ color: var(--muted);
+ font-size: 11px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.wechat-source-list button {
+ width: 28px;
+ height: 28px;
+ display: grid;
+ place-items: center;
+ border: 0;
+ background: transparent;
+ color: var(--subtle);
+}
+
+.wechat-source-list button:hover {
+ color: var(--text);
+ background: var(--surface);
+}
+
+.wechat-inspiration-panel button:focus-visible,
+.wechat-inspiration-panel input:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+}
+
+.wechat-inspiration-library .wechat-empty-source {
+ flex: 1 1 auto;
+ min-height: 240px;
+ margin: 0;
+ padding: 24px 12px;
+ border: 0;
+ background: transparent;
+}
+
+.wechat-inspiration-library .wechat-empty-source strong {
+ color: var(--text);
+ font-size: 12px;
+}
+
+.wechat-empty-source,
+.wechat-generation-empty {
+ min-height: 180px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 9px;
+ margin-top: 18px;
+ padding: 28px;
+ border: 1px dashed var(--border);
+ border-radius: 7px;
+ color: var(--muted);
+ text-align: center;
+}
+
+.wechat-empty-source p,
+.wechat-generation-empty p {
+ max-width: 520px;
+ color: var(--muted);
+ font-size: 12px;
+ line-height: 1.55;
+}
+
+.wechat-generation-empty strong {
+ color: var(--text);
+ font-size: 14px;
+}
+
+.wechat-brief-grid {
+ display: grid;
+ grid-template-columns: minmax(0, 2fr) minmax(280px, 1fr);
+ align-items: stretch;
+ gap: 14px;
+}
+
+.wechat-writing-brief-panel,
+.wechat-template-selection-panel {
+ min-height: 480px;
+}
+
+.wechat-writing-brief-panel {
+ display: flex;
+ flex-direction: column;
+}
+
+.wechat-writing-brief-panel > .creator-tool-field:first-of-type {
+ flex: 1 1 auto;
+}
+
+.wechat-writing-brief-panel > .creator-tool-field:first-of-type textarea {
+ min-height: 330px;
+}
+
+.wechat-template-selection-panel {
+ display: flex;
+ flex-direction: column;
+}
+
+.wechat-current-template {
+ position: relative;
+ display: grid;
+ grid-template-columns: 38px minmax(0, 1fr);
+ gap: 11px;
+ padding: 15px 0;
+ border-top: 1px solid var(--border-hairline);
+ border-bottom: 1px solid var(--border-hairline);
+}
+
+.wechat-current-template > button {
+ position: absolute;
+ top: 10px;
+ right: 0;
+ width: 28px;
+ height: 28px;
+ display: grid;
+ place-items: center;
+ padding: 0;
+ border: 0;
+ border-radius: 6px;
+ background: transparent;
+ color: var(--muted);
+}
+
+.wechat-current-template > button:hover {
+ background: var(--state-hover-bg);
+ color: var(--text);
+}
+
+.wechat-current-template > span {
+ width: 38px;
+ height: 38px;
+ display: grid;
+ place-items: center;
+ border-radius: 7px;
+ background: color-mix(in srgb, var(--accent) 9%, var(--surface-2));
+ color: var(--accent);
+}
+
+.wechat-current-template > div {
+ min-width: 0;
+ display: grid;
+ gap: 5px;
+}
+
+.wechat-current-template strong {
+ padding-right: 34px;
+ font-size: 14px;
+}
+
+.wechat-current-template .wechat-template-community-badge {
+ width: fit-content;
+ padding: 2px 5px;
+ border-radius: 4px;
+ background: color-mix(in srgb, var(--accent) 10%, var(--surface-2));
+ color: var(--accent);
+ font-size: 9px;
+ font-weight: 650;
+}
+
+.wechat-current-template p {
+ color: var(--muted);
+ font-size: 11px;
+ line-height: 1.5;
+}
+
+.wechat-current-template > div > div,
+.wechat-template-grid button > div,
+.wechat-template-detail-tags {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 5px;
+}
+
+.wechat-current-template i,
+.wechat-template-grid i,
+.wechat-template-detail-tags i {
+ padding: 3px 6px;
+ border-radius: 4px;
+ background: var(--surface-2);
+ color: var(--subtle);
+ font-size: 9px;
+ font-style: normal;
+ line-height: 1.2;
+}
+
+.wechat-template-inline-list {
+ flex: 1 1 auto;
+ min-height: 0;
+ max-height: 360px;
+ display: grid;
+ align-content: start;
+ gap: 7px;
+ overflow-y: auto;
+ padding-right: 3px;
+ scrollbar-gutter: stable;
+}
+
+.wechat-template-inline-filters {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 5px;
+ margin-bottom: 10px;
+}
+
+.wechat-template-inline-filters button {
+ min-height: 27px;
+ padding: 0 9px;
+ border: 1px solid var(--border-hairline);
+ border-radius: 6px;
+ background: transparent;
+ color: var(--muted);
+ font-size: 10px;
+ font-weight: 550;
+}
+
+.wechat-template-inline-filters button:hover {
+ border-color: var(--border);
+ background: var(--state-hover-bg);
+ color: var(--text);
+}
+
+.wechat-template-inline-filters button[data-selected="true"] {
+ border-color: color-mix(in srgb, var(--accent) 28%, var(--border-hairline));
+ background: var(--accent-soft);
+ color: var(--text);
+ font-weight: 650;
+}
+
+.wechat-template-inline-list > button {
+ position: relative;
+ min-width: 0;
+ min-height: 62px;
+ display: grid;
+ grid-template-columns: 32px minmax(0, 1fr) auto;
+ align-items: center;
+ gap: 10px;
+ padding: 10px;
+ border: 1px solid var(--border-hairline);
+ border-radius: 7px;
+ background: color-mix(in srgb, var(--surface) 84%, var(--surface-page));
+ color: var(--text);
+ text-align: left;
+}
+
+.wechat-template-inline-list > button:hover {
+ border-color: color-mix(in srgb, var(--accent) 28%, var(--border));
+ background: color-mix(in srgb, var(--accent) 4%, var(--surface));
+}
+
+.wechat-template-inline-list > button > span {
+ width: 32px;
+ height: 32px;
+ display: grid;
+ place-items: center;
+ border-radius: 6px;
+ background: var(--surface-2);
+ color: var(--muted);
+}
+
+.wechat-template-inline-list > button > div {
+ min-width: 0;
+ display: grid;
+ gap: 3px;
+}
+
+.wechat-template-inline-list strong,
+.wechat-template-inline-list p {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.wechat-template-inline-list strong {
+ font-size: 12px;
+}
+
+.wechat-template-inline-list p {
+ color: var(--muted);
+ font-size: 10px;
+}
+
+.wechat-template-inline-list small {
+ padding: 3px 5px;
+ border-radius: 4px;
+ background: color-mix(in srgb, var(--accent) 10%, var(--surface-2));
+ color: var(--accent);
+ font-size: 9px;
+ font-weight: 650;
+}
+
+.wechat-template-library-trigger {
+ min-height: 38px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 7px;
+ margin-top: 14px;
+ padding: 0 13px;
+ border: 1px solid var(--border);
+ border-radius: 7px;
+ background: var(--surface-2);
+ color: var(--text);
+ font-size: 12px;
+ font-weight: 650;
+}
+
+.wechat-template-library-trigger:hover {
+ border-color: var(--border-strong);
+ background: var(--surface-3);
+}
+
+.wechat-template-instructions {
+ margin-top: auto;
+ padding-top: 18px;
+}
+
+.wechat-template-instructions summary {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ padding: 10px 0;
+ border-top: 1px solid var(--border-hairline);
+ color: var(--muted);
+ cursor: pointer;
+ font-size: 12px;
+ font-weight: 600;
+ list-style: none;
+}
+
+.wechat-template-instructions summary::-webkit-details-marker {
+ display: none;
+}
+
+.wechat-template-instructions summary svg {
+ transition: transform 140ms ease;
+}
+
+.wechat-template-instructions[open] summary svg {
+ transform: rotate(180deg);
+}
+
+.wechat-template-instructions textarea {
+ min-height: 150px;
+ resize: vertical;
+}
+
+.wechat-template-library-overlay {
+ position: fixed;
+ z-index: 100;
+ inset: 0;
+ display: block;
+ background: color-mix(in srgb, var(--scrim) 82%, transparent);
+ backdrop-filter: blur(5px);
+}
+
+.wechat-template-library {
+ position: absolute;
+ top: 50%;
+ left: var(--wechat-template-library-left, 18px);
+ width: min(
+ var(--wechat-template-library-width, 1040px),
+ calc(100vw - var(--wechat-template-library-left, 18px) - 18px)
+ );
+ height: min(660px, calc(100vh - 36px));
+ min-height: 0;
+ display: grid;
+ grid-template-rows: auto auto minmax(0, 1fr);
+ overflow: hidden;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: var(--surface);
+ box-shadow: var(--shadow-dialog);
+ transform: translateY(-50%);
+}
+
+.wechat-template-library > header {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 18px;
+ padding: 18px 20px;
+ border-bottom: 1px solid var(--border-hairline);
+}
+
+.wechat-template-library > header h2,
+.wechat-template-library > header p {
+ margin: 0;
+}
+
+.wechat-template-library > header h2 {
+ font-size: 18px;
+}
+
+.wechat-template-library > header p {
+ margin-top: 4px;
+ color: var(--muted);
+ font-size: 12px;
+}
+
+.wechat-template-library > header > button {
+ width: 30px;
+ height: 30px;
+ display: grid;
+ place-items: center;
+ padding: 0;
+ border: 0;
+ border-radius: 6px;
+ background: transparent;
+ color: var(--muted);
+}
+
+.wechat-template-library > header > button:hover {
+ background: var(--surface-2);
+ color: var(--text);
+}
+
+.wechat-template-top-filters {
+ min-width: 0;
+ display: flex;
+ gap: 5px;
+ overflow-x: auto;
+ padding: 9px 16px;
+ border-bottom: 1px solid var(--border-hairline);
+ background: color-mix(in srgb, var(--surface-2) 24%, var(--surface));
+ scrollbar-width: none;
+}
+
+.wechat-template-top-filters::-webkit-scrollbar {
+ display: none;
+}
+
+.wechat-template-top-filters button {
+ flex: 0 0 auto;
+ min-height: 30px;
+ padding: 0 11px;
+ border: 1px solid transparent;
+ border-radius: 6px;
+ background: transparent;
+ color: var(--muted);
+ font-size: 12px;
+ font-weight: 550;
+}
+
+.wechat-template-top-filters button:hover {
+ background: var(--state-hover-bg);
+ color: var(--text);
+}
+
+.wechat-template-top-filters button[data-selected="true"] {
+ border-color: color-mix(in srgb, var(--accent) 24%, var(--border-hairline));
+ background: var(--accent-soft);
+ color: var(--text);
+ font-weight: 650;
+}
+
+.wechat-template-library-body {
+ min-height: 0;
+ display: grid;
+ grid-template-columns: 150px minmax(0, 1fr) 280px;
+}
+
+.wechat-template-categories {
+ min-width: 0;
+ display: grid;
+ align-content: start;
+ gap: 3px;
+ padding: 14px 10px;
+ border-right: 1px solid var(--border-hairline);
+ background: color-mix(in srgb, var(--surface-2) 46%, var(--surface));
+}
+
+.wechat-template-categories button {
+ min-height: 34px;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ padding: 0 9px;
+ border: 0;
+ border-radius: 6px;
+ background: transparent;
+ color: var(--muted);
+ font-size: 12px;
+ text-align: left;
+}
+
+.wechat-template-categories button:hover {
+ background: var(--state-hover-bg);
+ color: var(--text);
+}
+
+.wechat-template-categories button[data-selected="true"] {
+ background: var(--accent-soft);
+ color: var(--text);
+ font-weight: 650;
+}
+
+.wechat-template-categories small {
+ color: var(--subtle);
+ font-size: 11px;
+}
+
+.wechat-template-browser {
+ min-width: 0;
+ min-height: 0;
+ display: grid;
+ grid-template-rows: auto minmax(0, 1fr);
+ gap: 14px;
+ padding: 16px;
+}
+
+.wechat-template-search {
+ min-height: 38px;
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr);
+ align-items: center;
+ gap: 8px;
+ padding: 0 11px;
+ border: 1px solid var(--border);
+ border-radius: 7px;
+ background: var(--surface-page);
+ color: var(--subtle);
+}
+
+.wechat-template-search:focus-within {
+ border-color: var(--border-strong);
+ box-shadow: 0 0 0 2px color-mix(in srgb, var(--text) 5%, transparent);
+}
+
+.wechat-template-search input {
+ min-width: 0;
+ height: 36px;
+ padding: 0;
+ border: 0;
+ outline: 0;
+ background: transparent;
+ color: var(--text);
+ font-size: 13px;
+}
+
+.wechat-template-grid {
+ min-height: 0;
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ align-content: start;
+ gap: 9px;
+ overflow-y: auto;
+ padding-right: 3px;
+ scrollbar-gutter: stable;
+}
+
+.wechat-template-grid > button {
+ position: relative;
+ min-width: 0;
+ min-height: 142px;
+ display: grid;
+ grid-template-rows: 28px auto minmax(34px, auto) auto;
+ align-content: start;
+ gap: 6px;
+ padding: 13px;
+ border: 1px solid var(--border-hairline);
+ border-radius: 7px;
+ background: color-mix(in srgb, var(--surface) 84%, var(--surface-page));
+ color: var(--text);
+ text-align: left;
+}
+
+.wechat-template-grid > button:hover {
+ border-color: var(--border);
+ background: var(--surface-2);
+}
+
+.wechat-template-grid > button[data-selected="true"] {
+ border-color: color-mix(in srgb, var(--accent) 42%, var(--border));
+ background: color-mix(in srgb, var(--accent) 6%, var(--surface));
+ box-shadow: inset 2px 0 0 var(--accent);
+}
+
+.wechat-template-grid > button > span {
+ width: 28px;
+ height: 28px;
+ display: grid;
+ place-items: center;
+ border-radius: 6px;
+ background: var(--surface-2);
+ color: var(--muted);
+}
+
+.wechat-template-grid > button strong {
+ padding-right: 54px;
+ font-size: 13px;
+}
+
+.wechat-template-grid .wechat-template-community-badge {
+ position: absolute;
+ top: 15px;
+ right: 12px;
+ padding: 3px 5px;
+ border-radius: 4px;
+ background: color-mix(in srgb, var(--accent) 10%, var(--surface-2));
+ color: var(--accent);
+ font-size: 10px;
+ font-weight: 650;
+}
+
+.wechat-template-grid > button[data-selected="true"] .wechat-template-community-badge {
+ right: 39px;
+}
+
+.wechat-template-grid > button p {
+ margin: 0;
+ color: var(--muted);
+ font-size: 11px;
+ line-height: 1.5;
+}
+
+.wechat-template-grid > button b {
+ position: absolute;
+ top: 12px;
+ right: 12px;
+ width: 20px;
+ height: 20px;
+ display: grid;
+ place-items: center;
+ border-radius: 50%;
+ background: var(--accent);
+ color: var(--on-accent);
+}
+
+.wechat-template-detail {
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ padding: 22px 20px;
+ border-left: 1px solid var(--border-hairline);
+ background: color-mix(in srgb, var(--surface-2) 44%, var(--surface));
+}
+
+.wechat-template-detail > span {
+ color: var(--accent);
+ font-size: 11px;
+ font-weight: 650;
+}
+
+.wechat-template-detail h3 {
+ margin: 8px 0 0;
+ font-size: 18px;
+}
+
+.wechat-template-detail > p {
+ margin: 8px 0 14px;
+ color: var(--muted);
+ font-size: 12px;
+ line-height: 1.55;
+}
+
+.wechat-template-source {
+ width: 100%;
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 28px;
+ align-items: center;
+ gap: 4px 8px;
+ margin-top: 18px;
+ padding: 12px;
+ border: 1px solid var(--border-hairline);
+ border-radius: 7px;
+ background: var(--surface);
+ box-sizing: border-box;
+}
+
+.wechat-template-source > div {
+ min-width: 0;
+ display: grid;
+ gap: 3px;
+}
+
+.wechat-template-source strong,
+.wechat-template-source span {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.wechat-template-source strong {
+ color: var(--text);
+ font-size: 11px;
+}
+
+.wechat-template-source span,
+.wechat-template-source small {
+ color: var(--muted);
+ font-size: 10px;
+}
+
+.wechat-template-source small {
+ grid-column: 1 / -1;
+}
+
+.wechat-template-source > a {
+ width: 28px;
+ height: 28px;
+ display: grid;
+ place-items: center;
+ border-radius: 6px;
+ color: var(--muted);
+}
+
+.wechat-template-source > a:hover {
+ background: var(--state-hover-bg);
+ color: var(--text);
+}
+
+.wechat-template-structure {
+ width: 100%;
+ margin-top: 22px;
+ padding-top: 16px;
+ border-top: 1px solid var(--border-hairline);
+}
+
+.wechat-template-structure > strong {
+ font-size: 12px;
+}
+
+.wechat-template-structure ol {
+ display: grid;
+ gap: 10px;
+ margin: 13px 0 0;
+ padding: 0;
+ list-style: none;
+ counter-reset: article-template-step;
+}
+
+.wechat-template-structure li {
+ display: grid;
+ grid-template-columns: 22px minmax(0, 1fr);
+ align-items: center;
+ gap: 8px;
+ color: var(--muted);
+ font-size: 12px;
+ counter-increment: article-template-step;
+}
+
+.wechat-template-structure li::before {
+ content: counter(article-template-step, decimal-leading-zero);
+ color: var(--subtle);
+ font-size: 10px;
+ font-variant-numeric: tabular-nums;
+}
+
+.wechat-template-detail > button {
+ width: 100%;
+ min-height: 38px;
+ margin-top: auto;
+ border: 1px solid var(--accent);
+ border-radius: 7px;
+ background: var(--accent);
+ color: var(--on-accent);
+ font-size: 12px;
+ font-weight: 650;
+}
+
+.wechat-template-empty {
+ min-height: 220px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 7px;
+ color: var(--muted);
+ text-align: center;
+}
+
+.wechat-template-empty strong {
+ color: var(--text);
+ font-size: 12px;
+}
+
+.wechat-template-empty p {
+ margin: 0;
+ color: var(--muted);
+ font-size: 10px;
+}
+
+.wechat-topic-count {
+ max-width: 180px;
+ margin-top: 16px;
+}
+
+.wechat-topic-count input {
+ min-height: 38px;
+}
+
+.wechat-preset-list {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 8px;
+ margin-bottom: 16px;
+}
+
+.wechat-preset-list button {
+ min-width: 0;
+ display: grid;
+ gap: 4px;
+ padding: 11px;
+ border: 1px solid var(--border);
+ border-radius: 7px;
+ background: transparent;
+ color: var(--text);
+ text-align: left;
+}
+
+.wechat-preset-list button[data-selected="true"] {
+ border-color: var(--accent);
+ background: color-mix(in srgb, var(--accent) 7%, var(--surface));
+}
+
+.wechat-preset-list strong {
+ font-size: 12px;
+}
+
+.wechat-preset-list small {
+ color: var(--muted);
+ font-size: 10px;
+ line-height: 1.4;
+}
+
+.wechat-layout-workbench {
+ min-width: 0;
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(216px, 232px);
+ align-items: start;
+ gap: 22px;
+}
+
+.wechat-layout-sidebar {
+ position: sticky;
+ top: 0;
+ min-width: 0;
+ max-height: calc(100vh - 230px);
+ display: grid;
+ grid-template-rows: auto auto minmax(0, 1fr);
+ gap: 10px;
+ padding-left: 16px;
+ border-left: 1px solid var(--border-hairline);
+}
+
+.wechat-layout-sidebar-heading {
+ display: grid;
+ gap: 3px;
+}
+
+.wechat-layout-sidebar-heading strong {
+ font-size: 12px;
+}
+
+.wechat-layout-sidebar-heading small,
+.wechat-layout-preview-heading small {
+ color: var(--muted);
+ font-size: 10px;
+}
+
+.wechat-layout-filters {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+}
+
+.wechat-layout-filters button {
+ min-height: 26px;
+ padding: 0 9px;
+ border: 1px solid var(--border-hairline);
+ border-radius: 6px;
+ background: transparent;
+ color: var(--muted);
+ font-size: 10px;
+ font-weight: 600;
+}
+
+.wechat-layout-filters button:hover {
+ border-color: var(--border-strong);
+ color: var(--text);
+}
+
+.wechat-layout-filters button[data-selected="true"] {
+ border-color: color-mix(in srgb, var(--accent) 55%, var(--border));
+ background: color-mix(in srgb, var(--accent) 10%, var(--surface));
+ color: var(--accent);
+}
+
+.wechat-layout-preview-pane {
+ min-width: 0;
+ display: grid;
+ gap: 10px;
+}
+
+.wechat-layout-preview-heading {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 12px;
+}
+
+.wechat-layout-preview-heading button {
+ min-height: 28px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 5px;
+ padding: 0 9px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--surface-2);
+ color: var(--muted);
+ font-size: 11px;
+ font-weight: 600;
+}
+
+.wechat-layout-preview-heading button:hover {
+ border-color: var(--border-strong);
+ color: var(--text);
+}
+
+.wechat-layout-list {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 8px;
+}
+
+.wechat-layout-sidebar .wechat-layout-list {
+ grid-template-columns: minmax(0, 1fr);
+ overflow-y: auto;
+ padding-right: 3px;
+ scrollbar-gutter: stable;
+}
+
+.wechat-layout-sidebar .wechat-layout-list button {
+ min-height: 100px;
+ grid-template-columns: 64px minmax(0, 1fr);
+ gap: 9px;
+ padding: 7px 8px 7px 7px;
+}
+
+.wechat-layout-sidebar .wechat-layout-sample,
+.wechat-layout-sidebar .wechat-layout-list button[data-layout="business"] .wechat-layout-sample,
+.wechat-layout-sidebar .wechat-layout-list button[data-layout="podcast"] .wechat-layout-sample,
+.wechat-layout-sidebar .wechat-layout-list button[data-layout="newsroom"] .wechat-layout-sample {
+ width: 64px;
+ height: 84px;
+ grid-template-rows: 3px 9px 5px 14px 5px 16px;
+ gap: 4px;
+ padding: 6px;
+}
+
+.wechat-layout-sidebar .wechat-layout-sample-heading {
+ grid-template-columns: 12px minmax(0, 1fr);
+ gap: 3px;
+}
+
+.wechat-layout-sidebar .wechat-layout-sample-heading b {
+ font-size: 5px;
+}
+
+.wechat-layout-sidebar .wechat-layout-list button[data-layout="technical"] .wechat-layout-sample-heading b {
+ width: 11px;
+ height: 11px;
+}
+
+.wechat-layout-sidebar .wechat-layout-sample-callout {
+ gap: 3px;
+ padding: 4px;
+}
+
+.wechat-layout-sidebar .wechat-layout-meta small {
+ display: -webkit-box;
+ overflow: hidden;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 2;
+}
+
+.wechat-layout-sidebar .wechat-layout-features i:nth-child(n + 3) {
+ display: none;
+}
+
+.wechat-layout-list button {
+ position: relative;
+ min-width: 0;
+ min-height: 126px;
+ display: grid;
+ grid-template-columns: 82px minmax(0, 1fr);
+ align-items: center;
+ gap: 11px;
+ padding: 9px 10px 9px 9px;
+ border: 1px solid var(--border);
+ border-radius: 7px;
+ background: var(--surface);
+ color: var(--text);
+ text-align: left;
+}
+
+.wechat-layout-list button:hover {
+ border-color: var(--border-strong);
+ background: var(--surface-2);
+}
+
+.wechat-layout-list button[data-selected="true"] {
+ border-color: var(--accent);
+ box-shadow: inset 0 0 0 1px var(--accent);
+}
+
+.wechat-layout-sample {
+ --sample-accent: #2f7d68;
+ --sample-ink: #243330;
+ --sample-soft: #eaf3ef;
+ width: 82px;
+ height: 106px;
+ display: grid;
+ grid-template-rows: 4px 12px 7px 18px 1fr 22px;
+ gap: 6px;
+ box-sizing: border-box;
+ padding: 8px;
+ overflow: hidden;
+ border: 1px solid #dfe4e1;
+ border-radius: 4px;
+ background: #fff;
+ box-shadow: 0 2px 7px rgb(28 39 35 / 8%);
+}
+
+.wechat-layout-sample i,
+.wechat-layout-sample b,
+.wechat-layout-sample em {
+ display: block;
+ box-sizing: border-box;
+ margin: 0;
+ font-style: normal;
+}
+
+.wechat-layout-sample-kicker {
+ width: 18px;
+ border-radius: 1px;
+ background: var(--sample-accent);
+}
+
+.wechat-layout-sample-title {
+ width: 75%;
+ border-radius: 1px;
+ background: var(--sample-ink);
+}
+
+.wechat-layout-sample-lead {
+ width: 92%;
+ border-left: 2px solid var(--sample-accent);
+ background: var(--sample-soft);
+}
+
+.wechat-layout-sample-heading {
+ display: grid !important;
+ grid-template-columns: 15px minmax(0, 1fr);
+ align-items: center;
+ gap: 4px;
+}
+
+.wechat-layout-sample-heading b {
+ color: var(--sample-accent);
+ font: 700 6px/1 Arial, sans-serif;
+}
+
+.wechat-layout-sample-heading em {
+ width: 72%;
+ height: 4px;
+ border-radius: 1px;
+ background: var(--sample-ink);
+}
+
+.wechat-layout-sample-lines {
+ display: grid !important;
+ align-content: start;
+ gap: 4px;
+}
+
+.wechat-layout-sample-lines b {
+ height: 2px;
+ border-radius: 1px;
+ background: #cbd1ce;
+}
+
+.wechat-layout-sample-lines b:nth-child(2) {
+ width: 88%;
+}
+
+.wechat-layout-sample-lines b:nth-child(3) {
+ width: 65%;
+}
+
+.wechat-layout-sample-callout {
+ display: grid !important;
+ align-content: center;
+ gap: 4px;
+ padding: 5px;
+ border-left: 2px solid var(--sample-accent);
+ background: var(--sample-soft);
+}
+
+.wechat-layout-sample-callout b,
+.wechat-layout-sample-callout em {
+ width: 86%;
+ height: 2px;
+ background: color-mix(in srgb, var(--sample-accent) 58%, white);
+}
+
+.wechat-layout-sample-callout em {
+ width: 58%;
+}
+
+.wechat-layout-list button[data-layout="business"] .wechat-layout-sample {
+ --sample-accent: #285b78;
+ --sample-ink: #183b50;
+ --sample-soft: #e8f0f4;
+ border-top: 4px solid #285b78;
+ grid-template-rows: 2px 12px 9px 18px 1fr 22px;
+}
+
+.wechat-layout-list button[data-layout="business"] .wechat-layout-sample-kicker {
+ width: 30px;
+ background: #b58a45;
+}
+
+.wechat-layout-list button[data-layout="business"] .wechat-layout-sample-callout {
+ border: 1px solid #b9ced9;
+ border-left: 3px solid #285b78;
+}
+
+.wechat-layout-list button[data-layout="editorial"] .wechat-layout-sample {
+ --sample-accent: #8b3f45;
+ --sample-ink: #352d2d;
+ --sample-soft: #f7eeee;
+ padding-right: 10px;
+ padding-left: 10px;
+}
+
+.wechat-layout-list button[data-layout="editorial"] .wechat-layout-sample-kicker,
+.wechat-layout-list button[data-layout="editorial"] .wechat-layout-sample-title {
+ margin: 0 auto;
+}
+
+.wechat-layout-list button[data-layout="editorial"] .wechat-layout-sample-kicker {
+ width: 12px;
+ height: 2px;
+ align-self: end;
+}
+
+.wechat-layout-list button[data-layout="editorial"] .wechat-layout-sample-title {
+ width: 82%;
+}
+
+.wechat-layout-list button[data-layout="editorial"] .wechat-layout-sample-lead {
+ width: 100%;
+ border: 0;
+ border-top: 1px solid #d7b6b8;
+ border-bottom: 1px solid #d7b6b8;
+ background: transparent;
+}
+
+.wechat-layout-list button[data-layout="editorial"] .wechat-layout-sample-heading {
+ grid-template-columns: 1fr;
+}
+
+.wechat-layout-list button[data-layout="editorial"] .wechat-layout-sample-heading b {
+ display: none;
+}
+
+.wechat-layout-list button[data-layout="editorial"] .wechat-layout-sample-heading em {
+ width: 64%;
+ margin: 0 auto;
+}
+
+.wechat-layout-list button[data-layout="editorial"] .wechat-layout-sample-callout {
+ border: 0;
+ border-top: 1px solid #d7b6b8;
+ border-bottom: 1px solid #d7b6b8;
+ background: transparent;
+}
+
+.wechat-layout-list button[data-layout="vibrant"] .wechat-layout-sample {
+ --sample-accent: #217561;
+ --sample-ink: #174d43;
+ --sample-soft: #fff4c7;
+}
+
+.wechat-layout-list button[data-layout="vibrant"] .wechat-layout-sample-heading {
+ padding: 3px 4px;
+ border-left: 3px solid #217561;
+ background: #e8f3ef;
+}
+
+.wechat-layout-list button[data-layout="vibrant"] .wechat-layout-sample-heading b {
+ color: #a97812;
+}
+
+.wechat-layout-list button[data-layout="vibrant"] .wechat-layout-sample-callout {
+ border: 1px solid #ead58a;
+ border-left: 3px solid #dfaa2f;
+}
+
+.wechat-layout-list button[data-layout="technical"] .wechat-layout-sample {
+ --sample-accent: #16736a;
+ --sample-ink: #182927;
+ --sample-soft: #edf5f3;
+}
+
+.wechat-layout-list button[data-layout="technical"] .wechat-layout-sample-kicker {
+ width: 24px;
+ box-shadow: 29px 0 0 #d6534d;
+}
+
+.wechat-layout-list button[data-layout="technical"] .wechat-layout-sample-heading b {
+ width: 14px;
+ height: 14px;
+ display: grid;
+ place-items: center;
+ border-radius: 50%;
+ background: #16736a;
+ color: white;
+}
+
+.wechat-layout-list button[data-layout="technical"] .wechat-layout-sample-callout {
+ border: 0;
+ background: #1e2928;
+}
+
+.wechat-layout-list button[data-layout="technical"] .wechat-layout-sample-callout b,
+.wechat-layout-list button[data-layout="technical"] .wechat-layout-sample-callout em {
+ background: #6ab8ad;
+}
+
+.wechat-layout-list button[data-layout="podcast"] .wechat-layout-sample {
+ --sample-accent: #e7bd36;
+ --sample-ink: #262626;
+ --sample-soft: #fff7d6;
+ border-top: 4px solid #262626;
+ grid-template-rows: 2px 12px 9px 18px 1fr 22px;
+}
+
+.wechat-layout-list button[data-layout="podcast"] .wechat-layout-sample-kicker {
+ width: 29px;
+ background: #e7bd36;
+}
+
+.wechat-layout-list button[data-layout="podcast"] .wechat-layout-sample-heading {
+ grid-template-columns: 1fr;
+ justify-items: center;
+}
+
+.wechat-layout-list button[data-layout="podcast"] .wechat-layout-sample-heading b {
+ display: none;
+}
+
+.wechat-layout-list button[data-layout="podcast"] .wechat-layout-sample-heading em {
+ width: 72%;
+ height: 7px;
+ background: #f3d66f;
+ box-shadow: inset 0 3px 0 #262626;
+}
+
+.wechat-layout-list button[data-layout="podcast"] .wechat-layout-sample-callout {
+ border-left: 3px solid #e7bd36;
+ background: #fff;
+}
+
+.wechat-layout-list button[data-layout="podcast"] .wechat-layout-sample-callout b,
+.wechat-layout-list button[data-layout="podcast"] .wechat-layout-sample-callout em {
+ background: #777;
+}
+
+.wechat-layout-list button[data-layout="newsroom"] .wechat-layout-sample {
+ --sample-accent: #c74436;
+ --sample-ink: #292b2d;
+ --sample-soft: #f8ece9;
+ border-top: 4px solid #c74436;
+ grid-template-rows: 2px 12px 9px 18px 1fr 22px;
+}
+
+.wechat-layout-list button[data-layout="newsroom"] .wechat-layout-sample-kicker {
+ width: 28px;
+ background: #292b2d;
+}
+
+.wechat-layout-list button[data-layout="newsroom"] .wechat-layout-sample-heading {
+ border-bottom: 1px solid #c74436;
+}
+
+.wechat-layout-list button[data-layout="newsroom"] .wechat-layout-sample-callout {
+ border-left-color: #c74436;
+}
+
+.wechat-layout-meta {
+ min-width: 0;
+ display: grid;
+ align-content: center;
+ gap: 4px;
+}
+
+.wechat-layout-list button strong {
+ padding-right: 18px;
+ font-size: 12px;
+}
+
+.wechat-layout-list button small {
+ color: var(--muted);
+ font-size: 9.5px;
+ line-height: 1.45;
+}
+
+.wechat-layout-features {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 3px;
+ margin-top: 2px;
+}
+
+.wechat-layout-features i {
+ padding: 2px 4px;
+ border: 1px solid var(--border-hairline);
+ border-radius: 3px;
+ color: var(--subtle);
+ font-size: 8px;
+ font-style: normal;
+ line-height: 1.2;
+}
+
+.wechat-layout-selected {
+ position: absolute;
+ top: 8px;
+ right: 8px;
+ width: 18px;
+ height: 18px;
+ display: grid;
+ place-items: center;
+ border-radius: 50%;
+ background: var(--accent);
+}
+
+.wechat-layout-selected svg {
+ color: var(--accent-contrast);
+}
+
+.wechat-topic-list {
+ display: grid;
+ gap: 9px;
+}
+
+.wechat-topics-panel,
+.wechat-outline-panel,
+.wechat-article-panel {
+ padding: 4px;
+ border: 0;
+ background: transparent;
+}
+
+.wechat-topics-panel .creator-tool-panel-heading,
+.wechat-outline-panel .creator-tool-panel-heading,
+.wechat-article-panel .creator-tool-panel-heading {
+ padding: 0 2px;
+ margin-bottom: 16px;
+}
+
+.wechat-topic-list article {
+ display: grid;
+ gap: 12px;
+ padding: 15px 16px 16px;
+ border: 1px solid var(--border-hairline);
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--surface) 82%, var(--surface-page));
+ cursor: pointer;
+ transition: border-color 140ms ease, background-color 140ms ease, box-shadow 140ms ease;
+}
+
+.wechat-topic-list article:hover {
+ border-color: var(--border);
+ background: color-mix(in srgb, var(--surface-2) 72%, var(--surface-page));
+}
+
+.wechat-topic-list article[data-selected="true"] {
+ border-color: color-mix(in srgb, var(--accent) 38%, var(--border));
+ background: color-mix(in srgb, var(--accent) 6%, var(--surface));
+ box-shadow: inset 2px 0 0 var(--accent);
+}
+
+.wechat-topic-list header {
+ display: grid;
+ grid-template-columns: 30px minmax(0, 1fr) 26px;
+ align-items: center;
+ gap: 8px;
+}
+
+.wechat-topic-list header > span {
+ color: var(--subtle);
+ font-size: 11px;
+ font-variant-numeric: tabular-nums;
+}
+
+.wechat-topic-list input {
+ min-width: 0;
+ padding: 5px 0;
+ border: 0;
+ border-bottom: 1px solid transparent;
+ outline: 0;
+ background: transparent;
+ color: var(--text);
+ font-size: 14px;
+ font-weight: 650;
+}
+
+.wechat-topic-list input:focus {
+ border-bottom-color: var(--border-strong);
+}
+
+.wechat-topic-list header button {
+ width: 24px;
+ height: 24px;
+ display: grid;
+ place-items: center;
+ padding: 0;
+ border: 1px solid var(--border);
+ border-radius: 50%;
+ background: transparent;
+ color: transparent;
+ line-height: 0;
+ transition: border-color 140ms ease, background-color 140ms ease, color 140ms ease, box-shadow 140ms ease;
+}
+
+.wechat-topic-list header button svg {
+ display: block;
+}
+
+.wechat-topic-list header button:hover {
+ border-color: var(--border-strong);
+}
+
+.wechat-topic-list header button:focus-visible {
+ outline: 2px solid var(--state-focus-ring);
+ outline-offset: 2px;
+}
+
+.wechat-topic-list article[data-selected="true"] header button {
+ border-color: var(--accent);
+ background: var(--accent);
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 12%, transparent);
+ color: var(--on-accent);
+}
+
+.wechat-topic-list label {
+ display: grid;
+ grid-template-columns: 68px minmax(0, 1fr);
+ align-items: start;
+ gap: 10px;
+ color: var(--muted);
+ font-size: 11px;
+ line-height: 1.5;
+}
+
+.wechat-topic-list textarea {
+ width: 100%;
+ min-height: 42px;
+ box-sizing: border-box;
+ resize: vertical;
+ padding: 9px 11px;
+ border: 1px solid transparent;
+ border-radius: 6px;
+ outline: 0;
+ background: color-mix(in srgb, var(--surface-page) 78%, transparent);
+ box-shadow: inset 0 0 0 1px var(--border-hairline);
+ color: var(--text);
+ font: inherit;
+ font-size: 12px;
+ line-height: 1.55;
+ transition: border-color 140ms ease, background-color 140ms ease, box-shadow 140ms ease;
+}
+
+.wechat-topic-list textarea:hover {
+ background: color-mix(in srgb, var(--surface-page) 88%, transparent);
+ box-shadow: inset 0 0 0 1px var(--border);
+}
+
+.wechat-topic-list textarea:focus {
+ border-color: var(--border-strong);
+ background: var(--surface-page);
+ box-shadow: 0 0 0 2px color-mix(in srgb, var(--text) 5%, transparent);
+}
+
+.wechat-outline-editor {
+ min-height: 430px;
+ resize: none;
+ overflow-y: auto;
+ font-family: var(--font-mono);
+ line-height: 1.65;
+}
+
+.wechat-article-edit-workbench {
+ min-height: 0;
+ height: 100%;
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 350px;
+ overflow: hidden;
+ border: 1px solid var(--border-hairline);
+ border-radius: 8px;
+ background: var(--surface);
+}
+
+.wechat-article-editor-pane {
+ min-width: 0;
+ display: flex;
+ overflow: hidden;
+ padding: 0;
+}
+
+.wechat-article-editor-pane .wechat-article-editor {
+ min-height: 0;
+ height: 100%;
+ border: 0;
+ border-radius: 0;
+ box-shadow: none;
+}
+
+.wechat-article-image-panel {
+ min-width: 0;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ border-left: 1px solid var(--border-hairline);
+ background: color-mix(in srgb, var(--surface-2) 56%, var(--surface));
+}
+
+.wechat-article-image-heading {
+ min-height: 62px;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 12px 15px;
+ border-bottom: 1px solid var(--border-hairline);
+}
+
+.wechat-article-image-heading > div {
+ min-width: 0;
+ display: flex;
+ align-items: center;
+ gap: 9px;
+}
+
+.wechat-article-image-heading > div > span {
+ width: 30px;
+ height: 30px;
+ flex: 0 0 auto;
+ display: grid;
+ place-items: center;
+ border: 1px solid color-mix(in srgb, var(--accent) 20%, var(--border));
+ border-radius: 7px;
+ background: color-mix(in srgb, var(--accent) 8%, var(--surface));
+ color: var(--accent);
+}
+
+.wechat-article-image-heading > div > div {
+ min-width: 0;
+ display: grid;
+ gap: 2px;
+}
+
+.wechat-article-image-heading strong {
+ font-size: 13px;
+}
+
+.wechat-article-image-heading small {
+ overflow: hidden;
+ color: var(--muted);
+ font-size: 10px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.wechat-image-toggle {
+ position: relative;
+ width: 34px;
+ height: 20px;
+ flex: 0 0 auto;
+ cursor: pointer;
+}
+
+.wechat-image-toggle input {
+ position: absolute;
+ opacity: 0;
+ pointer-events: none;
+}
+
+.wechat-image-toggle > span {
+ position: absolute;
+ inset: 0;
+ border: 1px solid var(--border-strong);
+ border-radius: 10px;
+ background: var(--surface-3);
+ transition: background-color 140ms ease, border-color 140ms ease;
+}
+
+.wechat-image-toggle > span::after {
+ position: absolute;
+ top: 2px;
+ left: 2px;
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ background: var(--muted);
+ content: '';
+ transition: transform 140ms ease, background-color 140ms ease;
+}
+
+.wechat-image-toggle input:checked + span {
+ border-color: var(--accent);
+ background: var(--accent);
+}
+
+.wechat-image-toggle input:checked + span::after {
+ background: var(--on-accent);
+ transform: translateX(14px);
+}
+
+.wechat-image-toggle input:focus-visible + span {
+ outline: 2px solid var(--state-focus-ring);
+ outline-offset: 2px;
+}
+
+.wechat-article-image-settings {
+ display: grid;
+ gap: 18px;
+ padding: 15px;
+}
+
+.wechat-article-image-settings[data-disabled="true"] > :not(.wechat-generate-images) {
+ opacity: .48;
+}
+
+.wechat-image-setting-block {
+ display: grid;
+ gap: 10px;
+}
+
+.wechat-image-setting-label {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+}
+
+.wechat-image-setting-label strong {
+ color: var(--text);
+ font-size: 11px;
+ font-weight: 650;
+}
+
+.wechat-image-setting-label > span {
+ min-width: 24px;
+ padding: 2px 6px;
+ border-radius: 5px;
+ background: color-mix(in srgb, var(--accent) 9%, var(--surface));
+ color: var(--accent);
+ font-size: 10px;
+ font-weight: 700;
+ text-align: center;
+ font-variant-numeric: tabular-nums;
+}
+
+.wechat-image-density {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 5px;
+}
+
+.wechat-image-density button {
+ min-width: 0;
+ height: 30px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--surface);
+ color: var(--muted);
+ font-size: 10px;
+ font-weight: 600;
+}
+
+.wechat-image-density button[data-selected="true"] {
+ border-color: color-mix(in srgb, var(--accent) 55%, var(--border));
+ background: color-mix(in srgb, var(--accent) 9%, var(--surface));
+ color: var(--accent);
+}
+
+.wechat-image-count-control {
+ display: grid;
+ grid-template-columns: 28px minmax(0, 1fr) 28px;
+ align-items: center;
+ gap: 8px;
+}
+
+.wechat-image-count-control button {
+ width: 28px;
+ height: 28px;
+ display: grid;
+ place-items: center;
+ padding: 0;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--surface);
+ color: var(--muted);
+}
+
+.wechat-image-count-control input {
+ width: 100%;
+ accent-color: var(--accent);
+}
+
+.wechat-image-style-grid {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 7px;
+}
+
+.wechat-image-style-grid > button {
+ position: relative;
+ min-width: 0;
+ display: grid;
+ grid-template-columns: 58px minmax(0, 1fr);
+ grid-template-rows: auto auto;
+ gap: 2px 7px;
+ padding: 7px;
+ overflow: hidden;
+ border: 1px solid var(--border-hairline);
+ border-radius: 7px;
+ background: var(--surface);
+ color: var(--text);
+ text-align: left;
+}
+
+.wechat-image-style-grid > button[data-selected="true"] {
+ border-color: color-mix(in srgb, var(--accent) 50%, var(--border));
+ background: color-mix(in srgb, var(--accent) 6%, var(--surface));
+ box-shadow: inset 2px 0 0 var(--accent);
+}
+
+.wechat-image-style-grid > button > img {
+ grid-row: 1 / 3;
+ width: 58px;
+ height: 42px;
+ display: block;
+ overflow: hidden;
+ border-radius: 5px;
+ background: var(--surface-3);
+ object-fit: cover;
+}
+
+.wechat-image-style-grid > button > strong,
+.wechat-image-style-grid > button > small {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.wechat-image-style-grid > button > strong {
+ align-self: end;
+ font-size: 10px;
+}
+
+.wechat-image-style-grid > button > small {
+ color: var(--subtle);
+ font-size: 8px;
+}
+
+.wechat-image-style-grid > button > b {
+ position: absolute;
+ top: 4px;
+ right: 4px;
+ width: 15px;
+ height: 15px;
+ display: grid;
+ place-items: center;
+ border-radius: 50%;
+ background: var(--accent);
+ color: var(--on-accent);
+}
+
+.wechat-generate-images {
+ min-height: 38px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 7px;
+ border: 1px solid var(--accent);
+ border-radius: 7px;
+ background: var(--accent);
+ color: var(--on-accent);
+ font-size: 11px;
+ font-weight: 650;
+}
+
+.wechat-generate-images:disabled,
+.wechat-image-style-grid button:disabled,
+.wechat-image-density button:disabled,
+.wechat-image-count-control button:disabled {
+ cursor: not-allowed;
+ opacity: .5;
+}
+
+.wechat-article-toolbar {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.wechat-article-title-row {
+ display: flex;
+ align-items: baseline;
+ gap: 8px;
+}
+
+.wechat-article-character-count {
+ color: var(--muted);
+ font-size: 11px;
+ font-variant-numeric: tabular-nums;
+ line-height: 1;
+ white-space: nowrap;
+}
+
+.wechat-insert-image-button:disabled {
+ cursor: wait;
+ opacity: .55;
+}
+
+.wechat-article-toolbar .creator-tool-segmented {
+ min-width: 150px;
+}
+
+.wechat-article-toolbar .creator-tool-segmented button {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 5px;
+}
+
+.wechat-article-editor,
+.wechat-article-preview {
+ width: 100%;
+ min-height: 560px;
+ box-sizing: border-box;
+}
+
+.wechat-article-editor {
+ overflow-y: auto;
+ padding: 22px 26px 28px;
+ border: 1px solid var(--border-hairline);
+ border-radius: 8px;
+ outline: 0;
+ background: color-mix(in srgb, var(--surface-page) 88%, var(--surface));
+ box-shadow: inset 0 1px 0 color-mix(in srgb, var(--text) 3%, transparent);
+ color: var(--text);
+ caret-color: var(--accent-strong);
+ font-family: var(--font-mono);
+ font-size: 13px;
+ line-height: 1.8;
+ transition: border-color 140ms ease, background-color 140ms ease, box-shadow 140ms ease;
+}
+
+.wechat-article-editor-text-block {
+ position: relative;
+ width: 100%;
+ min-width: 0;
+}
+
+.wechat-article-editor-segment {
+ width: 100%;
+ min-height: 48px;
+ display: block;
+ resize: none;
+ overflow: hidden;
+ padding: 0;
+ border: 0;
+ outline: 0;
+ background: transparent;
+ color: inherit;
+ font: inherit;
+ line-height: inherit;
+ box-sizing: border-box;
+ transition: background-color 120ms ease, box-shadow 120ms ease;
+}
+
+.wechat-article-editor-segment[data-empty="true"] {
+ min-height: 18px;
+}
+
+.wechat-article-editor-text-block[data-image-drop-active="true"] .wechat-article-editor-segment {
+ background: color-mix(in srgb, var(--accent) 8%, transparent);
+}
+
+.wechat-article-image-drop-indicator {
+ position: absolute;
+ right: 0;
+ left: 0;
+ z-index: 2;
+ height: 2px;
+ pointer-events: none;
+ background: var(--accent);
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 14%, transparent);
+ transform: translateY(-50%);
+}
+
+.wechat-article-image-drop-indicator::before {
+ position: absolute;
+ top: 50%;
+ left: -3px;
+ width: 8px;
+ height: 8px;
+ border: 2px solid var(--surface);
+ border-radius: 50%;
+ background: var(--accent);
+ box-shadow: 0 0 0 1px var(--accent);
+ content: '';
+ transform: translateY(-50%);
+}
+
+.wechat-article-inline-image {
+ position: relative;
+ width: 100%;
+ display: grid;
+ place-items: center;
+ margin: 6px 0 8px;
+ cursor: grab;
+ transition: opacity 120ms ease;
+}
+
+.wechat-article-inline-image:active {
+ cursor: grabbing;
+}
+
+.wechat-article-inline-image[data-dragging="true"] {
+ opacity: .42;
+}
+
+.wechat-article-inline-image img {
+ width: 100%;
+ height: auto;
+ display: block;
+ border: 1px solid var(--border-hairline);
+ border-radius: 7px;
+ background: var(--surface-2);
+ object-fit: contain;
+}
+
+.wechat-article-inline-image-actions {
+ position: absolute;
+ top: 10px;
+ right: 10px;
+ display: flex;
+ gap: 6px;
+ opacity: 0;
+ transition: opacity 140ms ease;
+}
+
+.wechat-article-inline-image:hover .wechat-article-inline-image-actions,
+.wechat-article-inline-image:focus-within .wechat-article-inline-image-actions {
+ opacity: 1;
+}
+
+.wechat-article-inline-image-actions button {
+ width: 32px;
+ height: 32px;
+ display: grid;
+ place-items: center;
+ padding: 0;
+ border: 1px solid rgb(255 255 255 / 42%);
+ border-radius: 6px;
+ background: rgb(24 27 29 / 82%);
+ box-shadow: 0 4px 14px rgb(0 0 0 / 22%);
+ color: #fff;
+ backdrop-filter: blur(8px);
+}
+
+.wechat-article-inline-image-actions button:hover {
+ background: rgb(24 27 29 / 96%);
+}
+
+.wechat-article-inline-image-actions button:last-child:hover {
+ border-color: color-mix(in srgb, var(--danger) 70%, #fff);
+ color: color-mix(in srgb, var(--danger) 68%, #fff);
+}
+
+@media (hover: none) {
+ .wechat-article-inline-image-actions {
+ opacity: 1;
+ }
+}
+
+.wechat-article-editor:hover {
+ border-color: var(--border);
+}
+
+.wechat-article-editor:focus-within {
+ border-color: var(--border-strong);
+ background: var(--surface-page);
+ box-shadow: 0 0 0 2px color-mix(in srgb, var(--text) 5%, transparent);
+}
+
+.wechat-article-editor-segment::selection,
+.wechat-topic-list textarea::selection,
+.wechat-topic-list input::selection {
+ background: color-mix(in srgb, var(--accent) 24%, transparent);
+}
+
+.wechat-article-preview {
+ --article-accent: #2f7d68;
+ --article-accent-2: #c7963f;
+ --article-ink: #25312e;
+ --article-muted: #67736f;
+ --article-soft: #eef5f2;
+ max-width: 820px;
+ margin: 0 auto;
+ padding: 36px 42px 44px;
+ border: 1px solid #dfe4e1;
+ background: #fff;
+ box-shadow: 0 8px 30px rgb(27 37 33 / 6%);
+ color: var(--article-ink);
+}
+
+.wechat-article-preview .markdown-prose {
+ color: var(--article-ink);
+}
+
+.wechat-article-preview .md-p,
+.wechat-article-preview .md-ul li,
+.wechat-article-preview .md-ol li {
+ font-size: 16px;
+ line-height: 1.95;
+}
+
+.wechat-article-preview .md-p {
+ color: var(--article-ink);
+}
+
+.wechat-article-preview .md-image {
+ width: 100%;
+ height: auto;
+ display: block;
+ margin: 0;
+ border-radius: 6px;
+ object-fit: contain;
+}
+
+.wechat-article-preview .md-p-image-only {
+ width: 100%;
+ margin: 24px 0 10px;
+ padding: 0;
+ border: 0;
+ background: transparent;
+ line-height: 0;
+}
+
+.wechat-article-preview .md-h1 {
+ margin-bottom: 20px;
+ color: var(--article-ink);
+ font-size: 30px;
+ font-weight: 720;
+ line-height: 1.38;
+}
+
+.wechat-article-preview .md-h1 + .md-p:not(.md-p-image-only) {
+ margin: 0 0 30px;
+ padding: 15px 17px;
+ border-left: 4px solid var(--article-accent);
+ background: var(--article-soft);
+ color: var(--article-muted);
+ font-size: 15px;
+}
+
+.wechat-article-preview .md-h2 {
+ margin: 38px 0 16px;
+ color: var(--article-ink);
+ font-size: 21px;
+ font-weight: 700;
+ line-height: 1.5;
+}
+
+.wechat-article-preview .md-h3 {
+ margin: 25px 0 10px;
+ color: var(--article-accent);
+ font-size: 17px;
+}
+
+.wechat-article-preview strong {
+ color: var(--article-accent);
+}
+
+.wechat-article-preview .md-ul,
+.wechat-article-preview .md-ol {
+ margin: 18px 0;
+ padding-left: 26px;
+}
+
+.wechat-article-preview .md-ul li::marker,
+.wechat-article-preview .md-ol li::marker {
+ color: var(--article-accent);
+ font-weight: 700;
+}
+
+.wechat-article-preview .md-quote {
+ margin: 25px 0;
+ padding: 16px 18px;
+ border: 0;
+ border-left: 4px solid var(--article-accent);
+ background: var(--article-soft);
+ color: var(--article-muted);
+ font-size: 16px;
+ line-height: 1.85;
+}
+
+.wechat-article-preview .md-hr {
+ width: 54px;
+ margin: 38px auto;
+ border: 0;
+ border-top: 3px solid var(--article-accent);
+}
+
+.wechat-article-preview .md-table-wrap {
+ margin: 22px 0;
+ border-color: color-mix(in srgb, var(--article-accent) 25%, #dfe4e1);
+ border-radius: 4px;
+ box-shadow: none;
+}
+
+.wechat-article-preview .md-table {
+ font-size: 13px;
+}
+
+.wechat-article-preview .md-table th {
+ background: var(--article-soft);
+ color: var(--article-ink);
+}
+
+.wechat-article-preview[data-layout="minimal"] .md-h1 {
+ padding-bottom: 18px;
+ border-bottom: 1px solid #d8dfdc;
+}
+
+.wechat-article-preview[data-layout="minimal"] .md-h2 {
+ position: relative;
+ padding-left: 18px;
+}
+
+.wechat-article-preview[data-layout="minimal"] .md-h2::before {
+ position: absolute;
+ top: 0.55em;
+ left: 0;
+ width: 7px;
+ height: 7px;
+ background: var(--article-accent);
+ content: '';
+}
+
+.wechat-article-preview[data-layout="minimal"] .md-quote {
+ border: 1px solid #cfe0d9;
+ border-left: 4px solid var(--article-accent);
+ background: #f4f8f6;
+ color: #365f53;
+}
+
+.wechat-article-preview[data-layout="business"] {
+ --article-accent: #285b78;
+ --article-accent-2: #b58a45;
+ --article-ink: #18394d;
+ --article-muted: #526b78;
+ --article-soft: #edf3f6;
+ border-top: 7px solid var(--article-accent);
+}
+
+.wechat-article-preview[data-layout="business"] .md-h1 {
+ padding-right: 24px;
+ border-right: 5px solid var(--article-accent-2);
+}
+
+.wechat-article-preview[data-layout="business"] .md-h2 {
+ padding: 9px 13px;
+ border-left: 5px solid var(--article-accent);
+ background: var(--article-soft);
+ color: #18394d;
+ font-size: 20px;
+}
+
+.wechat-article-preview[data-layout="business"] .md-h3 {
+ padding-bottom: 7px;
+ border-bottom: 1px solid #cbd9e1;
+}
+
+.wechat-article-preview[data-layout="business"] .md-quote {
+ position: relative;
+ padding-top: 21px;
+ border: 1px solid #c5d7e0;
+ border-left: 5px solid var(--article-accent);
+ background: #f8fafb;
+ color: #34566a;
+}
+
+.wechat-article-preview[data-layout="business"] .md-quote::before {
+ position: absolute;
+ top: 0;
+ left: 17px;
+ width: 34px;
+ height: 4px;
+ background: var(--article-accent-2);
+ content: '';
+}
+
+.wechat-article-preview[data-layout="business"] .md-hr {
+ width: 100%;
+ border-top: 1px solid #c8d5dc;
+}
+
+.wechat-article-preview[data-layout="editorial"] {
+ --article-accent: #8b3f45;
+ --article-accent-2: #b99066;
+ --article-ink: #352d2d;
+ --article-muted: #736465;
+ --article-soft: #f8f1f0;
+ padding-right: 50px;
+ padding-left: 50px;
+ font-family: Georgia, 'Songti SC', 'STSong', serif;
+}
+
+.wechat-article-preview[data-layout="editorial"] .md-h1 {
+ color: #5f3034;
+ font-size: 32px;
+ font-weight: 600;
+ text-align: center;
+}
+
+.wechat-article-preview[data-layout="editorial"] .md-h1::after {
+ width: 48px;
+ height: 2px;
+ display: block;
+ margin: 18px auto 0;
+ background: var(--article-accent);
+ content: '';
+}
+
+.wechat-article-preview[data-layout="editorial"] .md-h1 + .md-p:not(.md-p-image-only) {
+ padding: 16px 8px;
+ border: 0;
+ border-top: 1px solid #d9bfc0;
+ border-bottom: 1px solid #d9bfc0;
+ background: transparent;
+ color: #715a5c;
+ font-style: italic;
+ text-align: center;
+}
+
+.wechat-article-preview[data-layout="editorial"] .md-h2 {
+ margin-top: 44px;
+ color: #67383c;
+ font-size: 22px;
+ font-weight: 600;
+ text-align: center;
+}
+
+.wechat-article-preview[data-layout="editorial"] .md-h2::before,
+.wechat-article-preview[data-layout="editorial"] .md-h2::after {
+ width: 18px;
+ height: 1px;
+ display: inline-block;
+ margin: 0 10px 6px;
+ background: #c99da0;
+ content: '';
+}
+
+.wechat-article-preview[data-layout="editorial"] .md-p {
+ line-height: 2.05;
+}
+
+.wechat-article-preview[data-layout="editorial"] .md-quote {
+ margin: 34px 12px;
+ padding: 22px 18px;
+ border: 0;
+ border-top: 1px solid #d8babb;
+ border-bottom: 1px solid #d8babb;
+ background: transparent;
+ color: #713d41;
+ font-size: 18px;
+ font-style: italic;
+ text-align: center;
+}
+
+.wechat-article-preview[data-layout="vibrant"] {
+ --article-accent: #217561;
+ --article-accent-2: #dfa72b;
+ --article-ink: #19453d;
+ --article-muted: #52716a;
+ --article-soft: #eaf4f0;
+ border-top: 7px solid var(--article-accent);
+}
+
+.wechat-article-preview[data-layout="vibrant"] .md-h1 {
+ color: #174f45;
+ text-decoration: underline;
+ text-decoration-color: #efd47f;
+ text-decoration-thickness: 7px;
+ text-underline-offset: -3px;
+}
+
+.wechat-article-preview[data-layout="vibrant"] .md-h2 {
+ width: fit-content;
+ margin-top: 38px;
+ padding: 7px 12px;
+ border-left: 5px solid var(--article-accent);
+ border-bottom: 3px solid var(--article-accent-2);
+ background: var(--article-soft);
+ color: #174f45;
+ font-size: 20px;
+}
+
+.wechat-article-preview[data-layout="vibrant"] .md-quote {
+ border: 1px solid #ead38a;
+ border-left: 5px solid var(--article-accent-2);
+ background: #fff9e8;
+ color: #66531f;
+}
+
+.wechat-article-preview[data-layout="vibrant"] .md-ol {
+ padding-left: 31px;
+}
+
+.wechat-article-preview[data-layout="vibrant"] .md-ol li {
+ margin: 10px 0;
+ padding: 8px 10px;
+ border-bottom: 1px solid #dbe8e3;
+ background: #f8fbfa;
+}
+
+.wechat-article-preview[data-layout="vibrant"] .md-ol li::marker {
+ color: var(--article-accent-2);
+ font-size: 17px;
+}
+
+.wechat-article-preview[data-layout="technical"] {
+ --article-accent: #16736a;
+ --article-accent-2: #d6534d;
+ --article-ink: #1c2d2a;
+ --article-muted: #586b67;
+ --article-soft: #edf5f3;
+ border-top: 7px solid #1d2927;
+}
+
+.wechat-article-preview[data-layout="technical"] .md-h1 {
+ padding-left: 18px;
+ border-left: 6px solid var(--article-accent);
+}
+
+.wechat-article-preview[data-layout="technical"] .md-h1::after {
+ width: 34px;
+ height: 4px;
+ display: block;
+ margin-top: 15px;
+ background: var(--article-accent-2);
+ content: '';
+}
+
+.wechat-article-preview[data-layout="technical"] .md-h2 {
+ padding: 9px 12px;
+ border: 1px solid #c8ddd8;
+ border-left: 5px solid var(--article-accent);
+ background: var(--article-soft);
+ font-size: 20px;
+}
+
+.wechat-article-preview[data-layout="technical"] .md-h3::before {
+ margin-right: 7px;
+ color: var(--article-accent-2);
+ content: '#';
+}
+
+.wechat-article-preview[data-layout="technical"] .md-quote {
+ border: 1px solid #e5c1be;
+ border-left: 5px solid var(--article-accent-2);
+ background: #fff5f4;
+ color: #6d4542;
+}
+
+.wechat-article-preview[data-layout="technical"] .md-code-block {
+ margin: 22px 0;
+ border: 0;
+ border-radius: 4px;
+ background: #1d2927;
+ color: #d9e7e3;
+}
+
+.wechat-article-preview[data-layout="technical"] .md-code-header {
+ border-bottom-color: #354541;
+ color: #8fc6bd;
+}
+
+.wechat-article-preview[data-layout="technical"] .md-code {
+ color: #d9e7e3;
+}
+
+.wechat-article-preview[data-layout="podcast"] {
+ --article-accent: #e4b927;
+ --article-accent-2: #285f63;
+ --article-ink: #292929;
+ --article-muted: #5d5d5d;
+ --article-soft: #fff7d6;
+ border-top: 7px solid #292929;
+}
+
+.wechat-article-preview[data-layout="podcast"] .md-h1 {
+ padding-bottom: 17px;
+ border-bottom: 5px solid var(--article-accent);
+ color: #222;
+}
+
+.wechat-article-preview[data-layout="podcast"] .md-h1 + .md-p:not(.md-p-image-only) {
+ border: 0;
+ background: #f7f7f5;
+ color: #5b5b58;
+}
+
+.wechat-article-preview[data-layout="podcast"] .md-h2 {
+ width: fit-content;
+ max-width: 100%;
+ margin-right: auto;
+ margin-left: auto;
+ padding: 3px 7px;
+ background: var(--article-accent);
+ color: #222;
+ font-size: 21px;
+ font-weight: 700;
+ text-align: center;
+}
+
+.wechat-article-preview[data-layout="podcast"] .md-h3 {
+ width: fit-content;
+ margin: 28px 0 8px;
+ padding: 5px 9px;
+ border-left: 4px solid var(--article-accent);
+ background: #285f63;
+ color: #fff;
+ font-size: 14px;
+ font-weight: 700;
+}
+
+.wechat-article-preview[data-layout="podcast"] .md-quote {
+ margin: 12px 0 27px;
+ padding: 8px 0 8px 14px;
+ border: 0;
+ border-left: 4px solid var(--article-accent);
+ background: #fff;
+ color: #555;
+ font-size: 15px;
+ font-style: italic;
+ line-height: 2;
+}
+
+.wechat-article-preview[data-layout="podcast"] .md-h3 + .md-quote {
+ margin-top: 0;
+ padding: 14px 16px;
+ background: var(--article-soft);
+}
+
+.wechat-article-preview[data-layout="podcast"] .md-hr {
+ width: 100%;
+ border-top: 1px solid #ded8c3;
+}
+
+.wechat-article-preview[data-layout="newsroom"] {
+ --article-accent: #c74436;
+ --article-accent-2: #297477;
+ --article-ink: #292b2d;
+ --article-muted: #666b6e;
+ --article-soft: #f8eeec;
+ border-top: 8px solid var(--article-accent);
+}
+
+.wechat-article-preview[data-layout="newsroom"] .md-h1 {
+ padding-bottom: 18px;
+ border-bottom: 3px solid #292b2d;
+ font-size: 31px;
+}
+
+.wechat-article-preview[data-layout="newsroom"] .md-h1 + .md-p:not(.md-p-image-only) {
+ border: 0;
+ border-top: 1px solid #eccac5;
+ border-bottom: 1px solid #eccac5;
+ background: var(--article-soft);
+ color: #603f3b;
+}
+
+.wechat-article-preview[data-layout="newsroom"] .md-h2 {
+ padding: 8px 0;
+ border-top: 2px solid #292b2d;
+ border-bottom: 1px solid #bfc2c3;
+}
+
+.wechat-article-preview[data-layout="newsroom"] .md-h2::before {
+ width: 9px;
+ height: 9px;
+ display: inline-block;
+ margin-right: 9px;
+ background: var(--article-accent);
+ content: '';
+}
+
+.wechat-article-preview[data-layout="newsroom"] .md-ul,
+.wechat-article-preview[data-layout="newsroom"] .md-ol {
+ padding: 13px 16px 13px 36px;
+ border-left: 4px solid var(--article-accent-2);
+ background: #f1f6f6;
+}
+
+.wechat-article-preview[data-layout="newsroom"] .md-quote {
+ border: 0;
+ border-top: 1px solid #d8a49d;
+ border-bottom: 1px solid #d8a49d;
+ background: transparent;
+ color: #743d36;
+ font-size: 17px;
+ font-weight: 600;
+}
+
+.wechat-article-preview[data-layout="newsroom"] .md-hr {
+ width: 100%;
+ border-top: 1px solid #c8cbcc;
+}
+
+.wechat-article-actions {
+ margin-top: 0;
+ padding-top: 14px;
+ border-top: 1px solid var(--border-hairline);
+}
+
+.wechat-article-footer-stack {
+ min-width: 0;
+ display: grid;
+ gap: 10px;
+}
+
+.wechat-article-run-notice {
+ margin: 0 auto;
+}
+
+.wechat-article-stack[data-step="4"] .wechat-article-actions {
+ padding-top: 8px;
+}
+
+@media (max-width: 900px) {
+ .wechat-brief-grid {
+ grid-template-columns: minmax(0, 1fr);
+ }
+
+ .wechat-inspiration-workbench {
+ grid-template-columns: 240px minmax(0, 1fr);
+ }
+
+ .wechat-layout-workbench {
+ grid-template-columns: minmax(0, 1fr) 220px;
+ gap: 16px;
+ }
+
+ .wechat-article-edit-workbench {
+ grid-template-columns: minmax(0, 1fr) 310px;
+ }
+
+ .wechat-article-toolbar {
+ align-items: stretch;
+ flex-direction: column;
+ }
+}
+
+@media (max-width: 760px) {
+ .video-translation-steps.wechat-article-steps strong {
+ font-size: 9px;
+ }
+
+ .wechat-preset-list {
+ grid-template-columns: minmax(0, 1fr);
+ }
+
+ .wechat-template-library-overlay {
+ padding: 0;
+ }
+
+ .wechat-template-library {
+ left: 8px;
+ width: calc(100vw - 16px);
+ height: calc(100vh - 16px);
+ }
+
+ .wechat-article-edit-workbench {
+ height: auto;
+ grid-template-columns: minmax(0, 1fr);
+ }
+
+ .wechat-article-scroll[data-step="4"] {
+ overflow-y: auto;
+ }
+
+ .wechat-article-scroll[data-step="4"] > .wechat-article-panel {
+ height: auto;
+ }
+
+ .wechat-article-image-panel {
+ border-top: 1px solid var(--border-hairline);
+ border-left: 0;
+ }
+
+ .wechat-article-editor-pane .wechat-article-editor {
+ min-height: 480px;
+ }
+
+ .wechat-result-image-assets > div {
+ grid-template-columns: minmax(0, 1fr);
+ }
+
+ .wechat-template-top-filters {
+ padding: 8px 10px;
+ }
+
+ .wechat-template-library-body {
+ display: block;
+ overflow-y: auto;
+ }
+
+ .wechat-template-categories {
+ display: flex;
+ overflow-x: auto;
+ padding: 9px 10px;
+ border-right: 0;
+ border-bottom: 1px solid var(--border-hairline);
+ }
+
+ .wechat-template-categories button {
+ flex: 0 0 auto;
+ gap: 12px;
+ }
+
+ .wechat-template-browser {
+ min-height: 430px;
+ }
+
+ .wechat-template-grid {
+ grid-template-columns: minmax(0, 1fr);
+ overflow-y: visible;
+ }
+
+ .wechat-template-detail {
+ min-height: 360px;
+ border-top: 1px solid var(--border-hairline);
+ border-left: 0;
+ }
+
+ .wechat-inspiration-workbench {
+ grid-template-columns: minmax(0, 1fr);
+ }
+
+ .wechat-inspiration-library {
+ min-height: 260px;
+ border-right: 0;
+ border-bottom: 1px solid var(--border-hairline);
+ }
+
+ .wechat-inspiration-add {
+ padding: 18px;
+ }
+
+ .wechat-inspiration-dropzone {
+ min-height: 190px;
+ padding: 22px 18px;
+ }
+
+ .wechat-inspiration-capacity {
+ align-items: flex-start;
+ flex-direction: column;
+ gap: 4px;
+ }
+
+ .wechat-inspiration-capacity small {
+ text-align: left;
+ }
+
+ .wechat-layout-list {
+ grid-template-columns: minmax(0, 1fr);
+ }
+
+ .wechat-layout-workbench {
+ grid-template-columns: minmax(0, 1fr);
+ }
+
+ .wechat-layout-sidebar {
+ position: static;
+ max-height: none;
+ padding-top: 12px;
+ padding-left: 0;
+ border-top: 1px solid var(--border-hairline);
+ border-left: 0;
+ }
+
+ .wechat-layout-sidebar .wechat-layout-list {
+ grid-template-columns: none;
+ grid-auto-columns: 220px;
+ grid-auto-flow: column;
+ overflow-x: auto;
+ overflow-y: hidden;
+ padding-right: 0;
+ padding-bottom: 3px;
+ }
+
+ .wechat-topic-list label {
+ grid-template-columns: minmax(0, 1fr);
+ }
+
+ .wechat-article-preview {
+ padding: 20px;
+ }
+}
+
.video-generation-result {
display: grid;
gap: 10px;
diff --git a/apps/web/src/services/creator-service.test.ts b/apps/web/src/services/creator-service.test.ts
index 03f9a5de..3a0185dd 100644
--- a/apps/web/src/services/creator-service.test.ts
+++ b/apps/web/src/services/creator-service.test.ts
@@ -52,6 +52,20 @@ describe('creator web service', () => {
}),
expectedRevision: 8
});
+ await service.uploadArticleImage('job_1', {
+ file: new File(['image'], 'article.png', {
+ type: 'image/png',
+ lastModified: 654
+ }),
+ expectedRevision: 9
+ });
+ await service.uploadSourceDocument('job_1', {
+ file: new File(['document'], 'source.pdf', {
+ type: 'application/pdf',
+ lastModified: 789
+ }),
+ expectedRevision: 9
+ });
await service.importArtifact('job_1', {
expectedRevision: 9,
sourceJobId: 'source job',
@@ -92,6 +106,16 @@ describe('creator web service', () => {
expect.any(File),
'application/vnd.opencreator.creator-reference-image'
);
+ expect(client.postBinary).toHaveBeenCalledWith(
+ '/creator/jobs/job_1/article-image?expectedRevision=9&fileName=article.png&mime=image%2Fpng&lastModified=654',
+ expect.any(File),
+ 'application/vnd.opencreator.creator-reference-image'
+ );
+ expect(client.postBinary).toHaveBeenCalledWith(
+ '/creator/jobs/job_1/source-document?expectedRevision=9&fileName=source.pdf&mime=application%2Fpdf&lastModified=789',
+ expect.any(File),
+ 'application/vnd.opencreator.creator-document'
+ );
expect(client.post).toHaveBeenNthCalledWith(
9,
'/creator/jobs/job_1/import-artifact',
diff --git a/apps/web/src/services/creator-service.ts b/apps/web/src/services/creator-service.ts
index 04ca2ca7..5c01ad10 100644
--- a/apps/web/src/services/creator-service.ts
+++ b/apps/web/src/services/creator-service.ts
@@ -31,6 +31,8 @@ const CREATOR_SOURCE_UPLOAD_CONTENT_TYPE =
'application/vnd.opencreator.creator-source';
const CREATOR_REFERENCE_IMAGE_CONTENT_TYPE =
'application/vnd.opencreator.creator-reference-image';
+const CREATOR_DOCUMENT_UPLOAD_CONTENT_TYPE =
+ 'application/vnd.opencreator.creator-document';
export type CreatorJobControlResponse = {
job: CreatorJob;
@@ -98,6 +100,44 @@ export function createCreatorService(client: ClientLike) {
CREATOR_REFERENCE_IMAGE_CONTENT_TYPE
) as Promise<CreatorSourceUploadResponse>;
},
+ uploadArticleImage(jobId: string, input: {
+ file: File;
+ expectedRevision: number;
+ }): Promise<CreatorSourceUploadResponse> {
+ if (client.postBinary === undefined) {
+ return Promise.reject(new Error('Creator article image upload transport is unavailable'));
+ }
+ const query = new URLSearchParams({
+ expectedRevision: String(input.expectedRevision),
+ fileName: input.file.name,
+ mime: input.file.type || 'application/octet-stream',
+ lastModified: String(input.file.lastModified)
+ });
+ return client.postBinary(
+ `/creator/jobs/${encodeURIComponent(jobId)}/article-image?${query.toString()}`,
+ input.file,
+ CREATOR_REFERENCE_IMAGE_CONTENT_TYPE
+ ) as Promise<CreatorSourceUploadResponse>;
+ },
+ uploadSourceDocument(jobId: string, input: {
+ file: File;
+ expectedRevision: number;
+ }): Promise<CreatorSourceUploadResponse> {
+ if (client.postBinary === undefined) {
+ return Promise.reject(new Error('Creator document upload transport is unavailable'));
+ }
+ const query = new URLSearchParams({
+ expectedRevision: String(input.expectedRevision),
+ fileName: input.file.name,
+ mime: input.file.type || 'application/octet-stream',
+ lastModified: String(input.file.lastModified)
+ });
+ return client.postBinary(
+ `/creator/jobs/${encodeURIComponent(jobId)}/source-document?${query.toString()}`,
+ input.file,
+ CREATOR_DOCUMENT_UPLOAD_CONTENT_TYPE
+ ) as Promise<CreatorSourceUploadResponse>;
+ },
importArtifact(
jobId: string,
request: CreatorArtifactImportRequest
diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.ts
index db7478e8..f5210fdc 100644
--- a/packages/protocol/src/index.ts
+++ b/packages/protocol/src/index.ts
@@ -10,3 +10,4 @@ export * from './media-generation.js';
export * from './settings.js';
export * from './smart-dubbing.js';
export * from './video-metadata.js';
+export * from './wechat-article.js';
diff --git a/packages/protocol/src/wechat-article.ts b/packages/protocol/src/wechat-article.ts
new file mode 100644
index 00000000..7005a75f
--- /dev/null
+++ b/packages/protocol/src/wechat-article.ts
@@ -0,0 +1,170 @@
+export const wechatArticlePresetIds = [
+ 'insight',
+ 'story',
+ 'tutorial',
+ 'news-analysis'
+] as const;
+
+export type WechatArticlePresetId = string;
+
+export const wechatArticlePresetCategoryIds = [
+ 'analysis',
+ 'story',
+ 'practical',
+ 'news'
+] as const;
+
+export type WechatArticlePresetCategoryId = typeof wechatArticlePresetCategoryIds[number];
+
+export const wechatArticleLayoutStyleIds = [
+ 'minimal',
+ 'business',
+ 'editorial',
+ 'vibrant',
+ 'technical',
+ 'podcast',
+ 'newsroom'
+] as const;
+
+export type WechatArticleLayoutStyleId = typeof wechatArticleLayoutStyleIds[number];
+
+export type WechatArticleSourceLink = {
+ id: string;
+ url: string;
+ kind: 'video' | 'webpage';
+ label: string;
+};
+
+export const wechatArticleSourceLimit = 10;
+
+export type WechatArticleTopic = {
+ id: string;
+ title: string;
+ angle: string;
+ summary: string;
+};
+
+export const wechatArticleImageStyleIds = [
+ 'editorial',
+ 'minimal',
+ 'documentary',
+ 'illustration',
+ 'three-dimensional',
+ 'infographic'
+] as const;
+
+export type WechatArticleImageStyleId = typeof wechatArticleImageStyleIds[number];
+
+export const wechatArticleImageStyles: ReadonlyArray<{
+ id: WechatArticleImageStyleId;
+ instructions: string;
+}> = [
+ {
+ id: 'editorial',
+ instructions: 'Editorial magazine visual, deliberate composition, restrained color contrast, strong focal subject, polished publication quality.'
+ },
+ {
+ id: 'minimal',
+ instructions: 'Minimal conceptual visual, generous negative space, few objects, clean geometry, refined neutral palette, clear visual metaphor.'
+ },
+ {
+ id: 'documentary',
+ instructions: 'Documentary photography, natural light, credible real-world environment, candid details, restrained color grading, no staged stock-photo look.'
+ },
+ {
+ id: 'illustration',
+ instructions: 'Contemporary editorial illustration, textured shapes, expressive but controlled color, clear narrative scene, sophisticated print quality.'
+ },
+ {
+ id: 'three-dimensional',
+ instructions: 'isometric 3D illustration, futuristic tech scene, floating platforms connected by glowing lines, central AI cube core, neon blue purple gradient background, soft lighting, glass material, minimal composition, clean, no text, high detail, 3:2.'
+ },
+ {
+ id: 'infographic',
+ instructions: 'Editorial data visualization, clear hierarchy, diagrams and visual relationships, minimal labels, accurate structure, clean publication layout.'
+ }
+];
+
+export type WechatArticleImagePlanItem = {
+ id: string;
+ caption: string;
+ placementHeading: string;
+ prompt: string;
+};
+
+export const wechatArticleLayoutCategoryIds = [
+ 'recommended',
+ 'technology',
+ 'business',
+ 'news',
+ 'lifestyle',
+ 'humanities'
+] as const;
+
+export type WechatArticleLayoutCategoryId = typeof wechatArticleLayoutCategoryIds[number];
+
+export const wechatArticleLayoutStyles: ReadonlyArray<{
+ id: WechatArticleLayoutStyleId;
+ categories: readonly WechatArticleLayoutCategoryId[];
+ name: string;
+ description: string;
+ features: readonly string[];
+ instructions: string;
+}> = [
+ {
+ id: 'minimal',
+ categories: ['recommended', 'technology', 'lifestyle'],
+ name: '知识手记',
+ description: '清爽但不单薄,适合观点、复盘与知识分享',
+ features: ['编号章节', '结论卡片', '阅读留白'],
+ instructions: '使用知识手记式 Markdown 结构。一级标题后用一段加粗导语概括核心判断;主体使用带 01、02、03 编号的二级标题;每节保持二到四个短段落。重要结论使用引用块形成结论卡片,操作要点使用列表,重要转场使用分隔线。结尾用一个简短的行动清单或总结收束。不要堆叠装饰符号。'
+ },
+ {
+ id: 'business',
+ categories: ['recommended', 'business'],
+ name: '商业报告',
+ description: '摘要先行、数据醒目,适合行业与公司内容',
+ features: ['内容摘要', '数据重点', '结论边栏'],
+ instructions: '使用商业报告式 Markdown 结构。一级标题后先写一段加粗的执行摘要;二级标题直接表达章节结论,三级标题用于拆分论据。数据、对比和关键事实优先使用列表或表格;引用块只承载关键判断或风险提示;章节之间使用分隔线。语气专业克制,结尾明确列出三项以内的决策建议或后续观察。'
+ },
+ {
+ id: 'editorial',
+ categories: ['lifestyle', 'humanities'],
+ name: '杂志特写',
+ description: '叙事舒展、金句突出,适合人物与深度故事',
+ features: ['题记导语', '叙事章节', '金句引用'],
+ instructions: '使用杂志特写式 Markdown 结构。一级标题简洁有叙事张力,随后用一段加粗的题记或导语建立场景;正文段落有长短变化,二级标题写成有画面感的章节标题。关键句单独使用引用块,重要转场使用分隔线;列表只在确有并列信息时使用。结尾回扣开篇场景或核心意象,保留余味,不使用教程式口号。'
+ },
+ {
+ id: 'vibrant',
+ categories: ['recommended', 'lifestyle', 'humanities'],
+ name: '行动清单',
+ description: '步骤鲜明、重点醒目,适合方法与实操内容',
+ features: ['步骤模块', '提示便签', '完成清单'],
+ instructions: '使用行动清单式 Markdown 结构。开篇先说明读者问题和完成后的收益;主体优先使用清晰的步骤编号和动作导向的二级标题。每一步包含目的、操作和注意事项;关键提醒使用引用块,检查项使用任务清单或无序列表,必要时用加粗突出动作。结尾提供可立即执行的完成清单。不要使用大量 emoji 或夸张符号。'
+ },
+ {
+ id: 'technical',
+ categories: ['recommended', 'technology', 'business'],
+ name: '技术教程',
+ description: '代码、参数和步骤层次清楚,适合产品与开发教程',
+ features: ['步骤导航', '代码区块', '避坑提示'],
+ instructions: '使用技术教程式 Markdown 结构。一级标题后用加粗导语说明适用对象、前置条件和最终结果;按步骤组织二级标题,三级标题解释原理或备选方案。命令、代码、配置和文件内容必须使用代码块;参数对比可使用表格;引用块用于“注意”“避坑”或兼容性提醒;结尾提供验证清单。不得编造无法由来源确认的命令、版本或配置。'
+ },
+ {
+ id: 'podcast',
+ categories: ['technology'],
+ name: '播客访谈',
+ description: '突出对话与原声观点,适合播客、圆桌和人物访谈',
+ features: ['嘉宾发言', '对话层级', '观点摘录'],
+ instructions: '使用播客访谈式 Markdown 结构。一级标题后用一段加粗导语交代节目、嘉宾和核心议题;开篇可选取二到三句最有代表性的原话作为引用块。主体使用概括核心观点的二级标题分章;需要呈现对话时,以“### 主持人 · 姓名”或“### 嘉宾 · 姓名”标明发言者,紧接引用块放置该人物的原话,不得把不同发言者合并在同一个引用块中。引用之后用普通段落补充背景、解释与事实核验。只把来源中可以确认的内容写成直接引语,不得改写后加引号或虚构发言。结尾整理节目来源、关键观点和延伸阅读。'
+ },
+ {
+ id: 'newsroom',
+ categories: ['news', 'business'],
+ name: '热点简报',
+ description: '先讲事实再做判断,适合新闻、事件与趋势解读',
+ features: ['事实速览', '时间脉络', '影响判断'],
+ instructions: '使用热点简报式 Markdown 结构。一级标题后用加粗导语在三句话内说明发生了什么、为什么重要;第一个二级章节为事实速览,用列表列出时间、主体和已确认信息;后续章节依次解释背景、影响和待观察事项。引用块用于标记核心判断,并明确区分事实与推测;分隔线用于切换事实和分析。结尾列出接下来值得关注的二到四个信号。'
+ }
+];
diff --git a/packages/writing-templates/CONTRIBUTING.md b/packages/writing-templates/CONTRIBUTING.md
new file mode 100644
index 00000000..62687b48
--- /dev/null
+++ b/packages/writing-templates/CONTRIBUTING.md
@@ -0,0 +1,25 @@
+# Contributing writing templates
+
+Writing templates are reviewed, declarative capability packages. They are not executable plugins.
+
+## Add a community template
+
+1. Create `templates/community/<slug>/`.
+2. Add `template.json`, the Markdown resources declared by `skill.stageResources`, and the upstream `LICENSE`.
+3. Use an id beginning with `community.` and a semantic version.
+4. Give the template a `sortOrder`; community templates should normally start at 100 or later.
+5. Pin GitHub sources to a full commit SHA. Do not point at a moving branch.
+6. Provide complete `zh-CN` and `en-US` localized metadata. Keep `name` as the canonical upstream name for attribution.
+7. Run `pnpm --filter @opencreator/writing-templates test`.
+
+Only `verified` and `featured` templates are published in the application. New pull requests should normally use `submitted`; maintainers change the status after license, content, safety, and generation-quality review.
+
+## Package rules
+
+- Allowed files: JSON manifests, Markdown/text resources, `LICENSE`, `NOTICE`, and `README.md`.
+- Scripts, binaries, executable files, symbolic links, remote runtime imports, and tool instructions are rejected.
+- A package may contain at most 32 files and 256 KiB. Each prompt resource may contain at most 64 KiB.
+- Keep quoted third-party material out of prompt resources unless redistribution rights are explicit.
+- Describe writing techniques instead of promising an exact imitation of a living author or public figure.
+
+The manifest contract is documented by `schema/writing-template.schema.json`. The generated catalog is build output and must not be edited by hand.
diff --git a/packages/writing-templates/README.md b/packages/writing-templates/README.md
new file mode 100644
index 00000000..5618d62a
--- /dev/null
+++ b/packages/writing-templates/README.md
@@ -0,0 +1,21 @@
+# OpenCreator writing templates
+
+This package is the registry shared by the Web template library and the Daemon writing pipeline.
+
+```text
+template.json + Markdown resources + LICENSE
+ |
+ v
+ build-catalog.mjs validation
+ |
+ v
+ generated read-only catalog
+ / \
+ Web metadata Daemon stage prompts
+```
+
+The application never executes code from a writing template and never fetches a moving GitHub branch at generation time. Community sources are copied into the repository after review, pinned to a commit SHA, attributed, hashed, and loaded only from the built catalog.
+
+`skill.stageResources` binds resources to `topics`, `outline`, `article`, and `review`. This keeps topic generation small while allowing article generation to load richer rules and a final checklist.
+
+See [CONTRIBUTING.md](./CONTRIBUTING.md) for the pull request format and validation rules.
diff --git a/packages/writing-templates/package.json b/packages/writing-templates/package.json
new file mode 100644
index 00000000..2c2e4e50
--- /dev/null
+++ b/packages/writing-templates/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@opencreator/writing-templates",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "types": "./dist/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "import": "./dist/index.js",
+ "default": "./dist/index.js"
+ }
+ },
+ "scripts": {
+ "build:catalog": "node scripts/build-catalog.mjs",
+ "build": "pnpm build:catalog && tsc -p tsconfig.json",
+ "typecheck": "pnpm build:catalog && tsc -p tsconfig.json --noEmit",
+ "test": "pnpm build:catalog && vitest run --passWithNoTests"
+ }
+}
diff --git a/packages/writing-templates/schema/writing-template.schema.json b/packages/writing-templates/schema/writing-template.schema.json
new file mode 100644
index 00000000..02ac0c9d
--- /dev/null
+++ b/packages/writing-templates/schema/writing-template.schema.json
@@ -0,0 +1,121 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://opencreator.ai/schemas/writing-template.schema.json",
+ "title": "OpenCreator Writing Template",
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "schemaVersion",
+ "id",
+ "version",
+ "name",
+ "description",
+ "localizations",
+ "categoryId",
+ "domains",
+ "tags",
+ "structure",
+ "instructions",
+ "author",
+ "status",
+ "sortOrder",
+ "source",
+ "skill"
+ ],
+ "properties": {
+ "schemaVersion": { "const": 1 },
+ "id": { "type": "string", "pattern": "^[a-z0-9]+(?:[.-][a-z0-9]+)*$", "maxLength": 96 },
+ "version": { "type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$" },
+ "name": { "type": "string", "minLength": 1, "maxLength": 64 },
+ "description": { "type": "string", "minLength": 1, "maxLength": 240 },
+ "localizations": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["zh-CN", "en-US"],
+ "properties": {
+ "zh-CN": { "$ref": "#/$defs/localization" },
+ "en-US": { "$ref": "#/$defs/localization" }
+ }
+ },
+ "categoryId": { "enum": ["analysis", "story", "practical", "news"] },
+ "domains": { "type": "array", "minItems": 1, "maxItems": 6, "uniqueItems": true, "items": { "enum": ["technology", "finance", "emotion", "workplace", "education", "research", "lifestyle"] } },
+ "tags": { "type": "array", "minItems": 1, "maxItems": 8, "items": { "type": "string", "minLength": 1, "maxLength": 24 } },
+ "structure": { "type": "array", "minItems": 2, "maxItems": 12, "items": { "type": "string", "minLength": 1, "maxLength": 80 } },
+ "instructions": { "type": "string", "maxLength": 8000 },
+ "author": { "type": "string", "minLength": 1, "maxLength": 80 },
+ "status": { "enum": ["submitted", "verified", "featured", "deprecated"] },
+ "sortOrder": { "type": "integer", "minimum": 0, "maximum": 10000 },
+ "source": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["type", "license"],
+ "properties": {
+ "type": { "enum": ["official", "github"] },
+ "repository": { "type": "string" },
+ "revision": { "type": "string" },
+ "url": { "type": "string", "format": "uri" },
+ "license": { "type": "string", "minLength": 1 }
+ }
+ },
+ "skill": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["stageResources"],
+ "properties": {
+ "stageResources": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["article"],
+ "properties": {
+ "topics": { "$ref": "#/$defs/resources" },
+ "outline": { "$ref": "#/$defs/resources" },
+ "article": { "$ref": "#/$defs/resources" },
+ "review": { "$ref": "#/$defs/resources" }
+ }
+ }
+ }
+ }
+ },
+ "$defs": {
+ "localization": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["name", "description", "tags", "structure", "instructions"],
+ "properties": {
+ "name": { "type": "string", "minLength": 1, "maxLength": 64 },
+ "description": { "type": "string", "minLength": 1, "maxLength": 240 },
+ "tags": { "type": "array", "minItems": 1, "maxItems": 8, "items": { "type": "string", "minLength": 1, "maxLength": 24 } },
+ "structure": { "type": "array", "minItems": 2, "maxItems": 12, "items": { "type": "string", "minLength": 1, "maxLength": 80 } },
+ "instructions": { "type": "string", "maxLength": 8000 }
+ }
+ },
+ "resources": {
+ "type": "array",
+ "minItems": 1,
+ "maxItems": 8,
+ "items": { "type": "string", "pattern": "^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$)).+\\.(?:md|txt)$" }
+ }
+ },
+ "allOf": [
+ {
+ "if": {
+ "properties": {
+ "source": {
+ "properties": { "type": { "const": "github" } },
+ "required": ["type"]
+ }
+ }
+ },
+ "then": {
+ "properties": {
+ "source": {
+ "required": ["repository", "revision", "url", "license"],
+ "properties": {
+ "revision": { "pattern": "^[a-f0-9]{40}$" }
+ }
+ }
+ }
+ }
+ }
+ ]
+}
diff --git a/packages/writing-templates/scripts/build-catalog.mjs b/packages/writing-templates/scripts/build-catalog.mjs
new file mode 100644
index 00000000..658fd505
--- /dev/null
+++ b/packages/writing-templates/scripts/build-catalog.mjs
@@ -0,0 +1,266 @@
+import { createHash } from 'node:crypto';
+import { lstat, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
+import { dirname, extname, join, relative, resolve, sep } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const templatesRoot = join(packageRoot, 'templates');
+const outputPath = join(packageRoot, 'src', 'generated', 'catalog.json');
+const templateKinds = ['official', 'community'];
+const stages = ['topics', 'outline', 'article', 'review'];
+const categories = new Set(['analysis', 'story', 'practical', 'news']);
+const domains = new Set(['technology', 'finance', 'emotion', 'workplace', 'education', 'research', 'lifestyle']);
+const statuses = new Set(['submitted', 'verified', 'featured', 'deprecated']);
+const locales = ['zh-CN', 'en-US'];
+const allowedNames = new Set(['template.json', 'LICENSE', 'NOTICE', 'README.md']);
+const allowedExtensions = new Set(['.md', '.txt', '.json']);
+const idPattern = /^[a-z0-9]+(?:[.-][a-z0-9]+)*$/;
+const semverPattern = /^\d+\.\d+\.\d+$/;
+const commitPattern = /^[a-f0-9]{40}$/;
+const maxFiles = 32;
+const maxPackageBytes = 256 * 1024;
+const maxResourceBytes = 64 * 1024;
+
+const entries = [];
+const ids = new Set();
+
+for (const kind of templateKinds) {
+ const kindRoot = join(templatesRoot, kind);
+ for (const directoryName of await sortedDirectories(kindRoot)) {
+ const templateRoot = join(kindRoot, directoryName);
+ await assertSafePackage(templateRoot);
+ if (kind === 'community') await assertRegularFile(join(templateRoot, 'LICENSE'), templateRoot, 'LICENSE is required');
+ const manifest = JSON.parse(await readFile(join(templateRoot, 'template.json'), 'utf8'));
+ validateManifest(manifest, kind, directoryName);
+ if (ids.has(manifest.id)) fail(templateRoot, `duplicate template id: ${manifest.id}`);
+ ids.add(manifest.id);
+
+ const stagePrompts = {};
+ const hashedResources = [];
+ for (const stage of stages) {
+ const resources = manifest.skill.stageResources[stage] ?? [];
+ if (!Array.isArray(resources)) fail(templateRoot, `skill.stageResources.${stage} must be an array`);
+ const contents = [];
+ for (const resource of resources) {
+ const resourcePath = safeResourcePath(templateRoot, resource);
+ const content = await readFile(resourcePath, 'utf8');
+ if (Buffer.byteLength(content) > maxResourceBytes) {
+ fail(templateRoot, `${resource} exceeds ${maxResourceBytes} bytes`);
+ }
+ assertSafePrompt(content, templateRoot, resource);
+ contents.push(content.trim());
+ hashedResources.push([resource, content]);
+ }
+ if (contents.length > 0) stagePrompts[stage] = contents.join('\n\n');
+ }
+
+ const source = normalizeSource(manifest.source);
+ const publicManifest = {
+ schemaVersion: 1,
+ id: manifest.id,
+ version: manifest.version,
+ name: manifest.name,
+ description: manifest.description,
+ localizations: manifest.localizations,
+ categoryId: manifest.categoryId,
+ domains: manifest.domains,
+ tags: manifest.tags,
+ structure: manifest.structure,
+ instructions: manifest.instructions,
+ author: manifest.author,
+ status: manifest.status,
+ sortOrder: manifest.sortOrder,
+ source
+ };
+ const contentHash = createHash('sha256')
+ .update(JSON.stringify(publicManifest))
+ .update(JSON.stringify(hashedResources))
+ .digest('hex');
+
+ if (manifest.status === 'verified' || manifest.status === 'featured') {
+ entries.push({ ...publicManifest, contentHash, stagePrompts });
+ }
+ }
+}
+
+entries.sort((left, right) => (
+ templateSourceRank(left) - templateSourceRank(right)
+ || left.sortOrder - right.sortOrder
+ || left.id.localeCompare(right.id)
+));
+await mkdir(dirname(outputPath), { recursive: true });
+await writeFile(outputPath, `${JSON.stringify(entries, null, 2)}\n`, 'utf8');
+process.stdout.write(`Validated ${ids.size} writing templates; published ${entries.length}.\n`);
+
+async function sortedDirectories(root) {
+ try {
+ return (await readdir(root, { withFileTypes: true }))
+ .filter(entry => entry.isDirectory())
+ .map(entry => entry.name)
+ .sort();
+ } catch (error) {
+ if (error?.code === 'ENOENT') return [];
+ throw error;
+ }
+}
+
+async function assertSafePackage(root) {
+ let fileCount = 0;
+ let totalBytes = 0;
+ const pending = [root];
+ while (pending.length > 0) {
+ const current = pending.pop();
+ const currentStat = await lstat(current);
+ if (currentStat.isSymbolicLink()) fail(root, `symbolic links are not allowed: ${relative(root, current)}`);
+ if (currentStat.isDirectory()) {
+ for (const entry of await readdir(current)) pending.push(join(current, entry));
+ continue;
+ }
+ fileCount += 1;
+ totalBytes += currentStat.size;
+ const name = current.slice(current.lastIndexOf(sep) + 1);
+ if (!allowedNames.has(name) && !allowedExtensions.has(extname(name).toLowerCase())) {
+ fail(root, `unsupported file type: ${relative(root, current)}`);
+ }
+ if ((currentStat.mode & 0o111) !== 0) fail(root, `executable files are not allowed: ${relative(root, current)}`);
+ }
+ if (fileCount > maxFiles) fail(root, `package contains more than ${maxFiles} files`);
+ if (totalBytes > maxPackageBytes) fail(root, `package exceeds ${maxPackageBytes} bytes`);
+}
+
+function validateManifest(value, kind, directoryName) {
+ if (!isRecord(value)) fail(directoryName, 'template.json must contain an object');
+ const allowedKeys = new Set([
+ 'schemaVersion', 'id', 'version', 'name', 'description', 'localizations', 'categoryId', 'tags',
+ 'domains', 'structure', 'instructions', 'author', 'status', 'sortOrder', 'source', 'skill'
+ ]);
+ for (const key of Object.keys(value)) if (!allowedKeys.has(key)) fail(directoryName, `unknown manifest field: ${key}`);
+ if (value.schemaVersion !== 1) fail(directoryName, 'schemaVersion must be 1');
+ if (typeof value.id !== 'string' || !idPattern.test(value.id) || value.id.length > 96) fail(directoryName, 'id is invalid');
+ if (kind === 'community' && !value.id.startsWith('community.')) fail(directoryName, 'community ids must start with community.');
+ if (kind === 'official' && value.id.includes('.')) fail(directoryName, 'official ids must not use a namespace');
+ if (typeof value.version !== 'string' || !semverPattern.test(value.version)) fail(directoryName, 'version must be semantic x.y.z');
+ assertString(value.name, directoryName, 'name', 64);
+ assertString(value.description, directoryName, 'description', 240);
+ validateLocalizations(value.localizations, directoryName);
+ assertString(value.author, directoryName, 'author', 80);
+ if (typeof value.instructions !== 'string' || value.instructions.length > 8_000) fail(directoryName, 'instructions is invalid');
+ if (!categories.has(value.categoryId)) fail(directoryName, 'categoryId is invalid');
+ assertStringArray(value.domains, directoryName, 'domains', 1, 6, 24);
+ if (new Set(value.domains).size !== value.domains.length || value.domains.some(domain => !domains.has(domain))) {
+ fail(directoryName, 'domains is invalid');
+ }
+ if (!statuses.has(value.status)) fail(directoryName, 'status is invalid');
+ if (!Number.isInteger(value.sortOrder) || value.sortOrder < 0 || value.sortOrder > 10_000) fail(directoryName, 'sortOrder is invalid');
+ assertStringArray(value.tags, directoryName, 'tags', 1, 8, 24);
+ assertStringArray(value.structure, directoryName, 'structure', 2, 12, 80);
+ if (!isRecord(value.source) || !isRecord(value.skill) || !isRecord(value.skill.stageResources)) {
+ fail(directoryName, 'source and skill.stageResources are required');
+ }
+ for (const stage of Object.keys(value.skill.stageResources)) {
+ if (!stages.includes(stage)) fail(directoryName, `unknown writing stage: ${stage}`);
+ const resources = value.skill.stageResources[stage];
+ if (!Array.isArray(resources) || resources.length === 0 || resources.length > 8) {
+ fail(directoryName, `skill.stageResources.${stage} must contain 1 to 8 resources`);
+ }
+ }
+ if (!Array.isArray(value.skill.stageResources.article) || value.skill.stageResources.article.length === 0) {
+ fail(directoryName, 'skill.stageResources.article is required');
+ }
+ assertString(value.source.license, directoryName, 'source.license', 80);
+ if (kind === 'community') {
+ if (value.source.type !== 'github') fail(directoryName, 'community source.type must be github');
+ assertString(value.source.repository, directoryName, 'source.repository', 160);
+ if (!commitPattern.test(value.source.revision)) fail(directoryName, 'community source.revision must be a full commit SHA');
+ assertString(value.source.url, directoryName, 'source.url', 500);
+ assertString(value.source.license, directoryName, 'source.license', 80);
+ } else if (value.source.type !== 'official') {
+ fail(directoryName, 'official source.type must be official');
+ }
+}
+
+function validateLocalizations(value, root) {
+ if (!isRecord(value)) fail(root, 'localizations is required');
+ const keys = Object.keys(value);
+ if (keys.length !== locales.length || keys.some(locale => !locales.includes(locale))) {
+ fail(root, `localizations must contain exactly ${locales.join(', ')}`);
+ }
+ for (const locale of locales) {
+ const localization = value[locale];
+ if (!isRecord(localization)) fail(root, `localizations.${locale} is invalid`);
+ const allowedKeys = new Set(['name', 'description', 'tags', 'structure', 'instructions']);
+ for (const key of Object.keys(localization)) {
+ if (!allowedKeys.has(key)) fail(root, `unknown localizations.${locale} field: ${key}`);
+ }
+ assertString(localization.name, root, `localizations.${locale}.name`, 64);
+ assertString(localization.description, root, `localizations.${locale}.description`, 240);
+ assertStringArray(localization.tags, root, `localizations.${locale}.tags`, 1, 8, 24);
+ assertStringArray(localization.structure, root, `localizations.${locale}.structure`, 2, 12, 80);
+ if (typeof localization.instructions !== 'string' || localization.instructions.length > 8_000) {
+ fail(root, `localizations.${locale}.instructions is invalid`);
+ }
+ }
+}
+
+async function assertRegularFile(path, root, message) {
+ try {
+ if ((await lstat(path)).isFile()) return;
+ } catch (error) {
+ if (error?.code !== 'ENOENT') throw error;
+ }
+ fail(root, message);
+}
+
+function normalizeSource(source) {
+ return {
+ type: source.type,
+ repository: typeof source.repository === 'string' ? source.repository : null,
+ revision: typeof source.revision === 'string' ? source.revision : null,
+ url: typeof source.url === 'string' ? source.url : null,
+ license: source.license
+ };
+}
+
+function templateSourceRank(template) {
+ return template.source.type === 'github' ? 0 : 1;
+}
+
+function safeResourcePath(root, resource) {
+ if (typeof resource !== 'string' || resource.startsWith('/') || resource.includes('\\')) {
+ fail(root, `invalid resource path: ${String(resource)}`);
+ }
+ const resolved = resolve(root, resource);
+ if (resolved === root || !resolved.startsWith(`${root}${sep}`)) fail(root, `resource escapes package: ${resource}`);
+ if (!['.md', '.txt'].includes(extname(resolved).toLowerCase())) fail(root, `resource must be Markdown or text: ${resource}`);
+ return resolved;
+}
+
+function assertSafePrompt(content, root, resource) {
+ const prohibited = [
+ /<script\b/i,
+ /javascript\s*:/i,
+ /data\s*:\s*text\/html/i,
+ /\brm\s+-rf\b/i,
+ /\bcurl\b[^\n|]*\|\s*(?:ba)?sh\b/i,
+ /忽略(?:此前|以上|系统)指令/,
+ /ignore (?:all )?(?:previous|system) instructions/i
+ ];
+ if (prohibited.some(pattern => pattern.test(content))) fail(root, `unsafe instruction detected in ${resource}`);
+}
+
+function assertString(value, root, field, maxLength) {
+ if (typeof value !== 'string' || value.trim().length === 0 || value.length > maxLength) fail(root, `${field} is invalid`);
+}
+
+function assertStringArray(value, root, field, min, max, maxLength) {
+ if (!Array.isArray(value) || value.length < min || value.length > max) fail(root, `${field} is invalid`);
+ for (const item of value) assertString(item, root, field, maxLength);
+}
+
+function isRecord(value) {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function fail(root, message) {
+ throw new Error(`WRITING_TEMPLATE_INVALID: ${relative(packageRoot, String(root))}: ${message}`);
+}
diff --git a/packages/writing-templates/src/catalog.ts b/packages/writing-templates/src/catalog.ts
new file mode 100644
index 00000000..862d2342
--- /dev/null
+++ b/packages/writing-templates/src/catalog.ts
@@ -0,0 +1,36 @@
+import generatedCatalog from './generated/catalog.json' with { type: 'json' };
+import type { WritingTemplate, WritingTemplateLocale, WritingTemplateStage } from './types.js';
+
+export const writingTemplates: readonly WritingTemplate[] = deepFreeze(
+ structuredClone(generatedCatalog) as WritingTemplate[]
+);
+
+const writingTemplateIdAliases: Readonly<Record<string, string>> = Object.freeze({
+ 'community.restrained-narrative': 'community.sun-style-writing'
+});
+
+export function normalizeWritingTemplateId(id: string): string {
+ return writingTemplateIdAliases[id] ?? id;
+}
+
+export function getWritingTemplate(id: string): WritingTemplate | undefined {
+ const normalizedId = normalizeWritingTemplateId(id);
+ return writingTemplates.find(template => template.id === normalizedId);
+}
+
+export function getWritingTemplateStagePrompt(id: string, stage: WritingTemplateStage): string {
+ return getWritingTemplate(id)?.stagePrompts[stage]?.trim() ?? '';
+}
+
+export function localizeWritingTemplate(template: WritingTemplate, locale: WritingTemplateLocale): WritingTemplate {
+ return {
+ ...template,
+ ...template.localizations[locale]
+ };
+}
+
+function deepFreeze<T>(value: T): T {
+ if (value === null || typeof value !== 'object' || Object.isFrozen(value)) return value;
+ for (const nested of Object.values(value)) deepFreeze(nested);
+ return Object.freeze(value);
+}
diff --git a/packages/writing-templates/src/generated/catalog.json b/packages/writing-templates/src/generated/catalog.json
new file mode 100644
index 00000000..f6d6586d
--- /dev/null
+++ b/packages/writing-templates/src/generated/catalog.json
@@ -0,0 +1,536 @@
+[
+ {
+ "schemaVersion": 1,
+ "id": "community.sun-style-writing",
+ "version": "1.0.0",
+ "name": "孙割写作.skill",
+ "description": "用短句、物件、数字和留白承载情绪的非虚构叙事",
+ "localizations": {
+ "zh-CN": {
+ "name": "孙割写作.skill",
+ "description": "用短句、物件、数字和留白承载情绪的非虚构叙事",
+ "tags": [
+ "白描",
+ "短句节奏",
+ "物件叙事",
+ "非虚构"
+ ],
+ "structure": [
+ "反差或悬念开场",
+ "场景与时间锚点",
+ "关系或冲突推进",
+ "物件回响"
+ ],
+ "instructions": "以可观察的动作、物件和真实数字推进叙事,减少直接心理解释。保持短句节奏,让关键场景充分展开,并用来源中真实存在的细节形成照应。"
+ },
+ "en-US": {
+ "name": "Sun-style Writing Skill",
+ "description": "Nonfiction storytelling shaped by short sentences, objects, numbers, and restraint",
+ "tags": [
+ "Plain description",
+ "Short-sentence rhythm",
+ "Object narrative",
+ "Nonfiction"
+ ],
+ "structure": [
+ "Contrast or suspense",
+ "Scene and time anchor",
+ "Relationship or conflict",
+ "Object callback"
+ ],
+ "instructions": "Move the narrative through observable actions, concrete objects, and real numbers while limiting direct explanations of inner states. Maintain a short-sentence rhythm, give key scenes room to unfold, and create callbacks with details that genuinely exist in the sources."
+ }
+ },
+ "categoryId": "story",
+ "domains": [
+ "emotion",
+ "lifestyle"
+ ],
+ "tags": [
+ "白描",
+ "短句节奏",
+ "物件叙事",
+ "非虚构"
+ ],
+ "structure": [
+ "反差或悬念开场",
+ "场景与时间锚点",
+ "关系或冲突推进",
+ "物件回响"
+ ],
+ "instructions": "以可观察的动作、物件和真实数字推进叙事,减少直接心理解释。保持短句节奏,让关键场景充分展开,并用来源中真实存在的细节形成照应。",
+ "author": "数字生命卡兹克 / OpenCreator adapted",
+ "status": "featured",
+ "sortOrder": 100,
+ "source": {
+ "type": "github",
+ "repository": "KKKKhazix/sun-style-writing",
+ "revision": "fe970dc15113ea0c3807f19f1d3118f63f9d9079",
+ "url": "https://github.com/KKKKhazix/sun-style-writing",
+ "license": "MIT"
+ },
+ "contentHash": "290ffd63506d5502c5e83c1b711cb841e355cd924333d4b6926cdbc4416fcd67",
+ "stagePrompts": {
+ "topics": "# 选题规则\n\n优先寻找来源中有明确人物、关系、时间跨度、具体物件或行动冲突的方向。选题应能够由真实场景展开,并具备反差或悬念。不要为追求文学感补造材料中不存在的经历、数字和细节。",
+ "outline": "# 孙学写作法\n\n这是一套来自 `KKKKhazix/sun-style-writing`、经 OpenCreator 接入的非虚构叙事规则。使用写作技法本身,不要求复刻任何现实人物的独特口吻。\n\n## 核心原则\n\n- 只写来源能够支持的动作、对话、物件、数字和环境细节,少解释人物心理。\n- 用具体数字替代模糊形容词,但真实性优先;材料不精确时不得制造假精确。\n- 段落和对话可以短,但一个关键场景要充分展开,形成进入、细节、变化和离开的过程。\n- 从材料中选择一个普通物件、动作或声音作为线索,让它在后文自然回来,不解释其象征意义。\n- 关键转折可以由沉默、称谓变化、动作变化或重复句式的中断承担。\n\n## 大纲方式\n\n开篇三句话内建立材料中真实存在的反差、悬念或关系变化。随后用时间、地点、人物或物件作为锚点推进场景。只在重大阶段转换时使用分隔,不把叙事切成大量碎片。结尾回到开篇出现过的动作、物件或问题,让语境变化产生回响,避免总结式升华。\n\n## 语言边界\n\n保持平静陈述,减少成语堆叠、感叹号、直接情绪标签和排比抒情。能够用动作呈现时不解释心理,能够用物件呈现时不总结感情。所有细节都必须服从来源和用户提供的事实边界。",
+ "article": "# 孙学写作法\n\n这是一套来自 `KKKKhazix/sun-style-writing`、经 OpenCreator 接入的非虚构叙事规则。使用写作技法本身,不要求复刻任何现实人物的独特口吻。\n\n## 核心原则\n\n- 只写来源能够支持的动作、对话、物件、数字和环境细节,少解释人物心理。\n- 用具体数字替代模糊形容词,但真实性优先;材料不精确时不得制造假精确。\n- 段落和对话可以短,但一个关键场景要充分展开,形成进入、细节、变化和离开的过程。\n- 从材料中选择一个普通物件、动作或声音作为线索,让它在后文自然回来,不解释其象征意义。\n- 关键转折可以由沉默、称谓变化、动作变化或重复句式的中断承担。\n\n## 大纲方式\n\n开篇三句话内建立材料中真实存在的反差、悬念或关系变化。随后用时间、地点、人物或物件作为锚点推进场景。只在重大阶段转换时使用分隔,不把叙事切成大量碎片。结尾回到开篇出现过的动作、物件或问题,让语境变化产生回响,避免总结式升华。\n\n## 语言边界\n\n保持平静陈述,减少成语堆叠、感叹号、直接情绪标签和排比抒情。能够用动作呈现时不解释心理,能够用物件呈现时不总结感情。所有细节都必须服从来源和用户提供的事实边界。\n\n# 成稿检查\n\n- 开头是否快速建立了来源真实支持的反差或悬念。\n- 是否删除了无依据的心理描写、精确数字和场景细节。\n- 关键场景是否足够完整,而不是只展示几个技巧就跳走。\n- 重复出现的物件、动作或句式是否自然,并在后文产生新的意义。\n- 结尾是否停留在具体画面或动作上,避免口号、总结和强行升华。\n- 技法是否服务于人物和事实;如果技巧比内容更醒目,应主动削弱。",
+ "review": "# 成稿检查\n\n- 开头是否快速建立了来源真实支持的反差或悬念。\n- 是否删除了无依据的心理描写、精确数字和场景细节。\n- 关键场景是否足够完整,而不是只展示几个技巧就跳走。\n- 重复出现的物件、动作或句式是否自然,并在后文产生新的意义。\n- 结尾是否停留在具体画面或动作上,避免口号、总结和强行升华。\n- 技法是否服务于人物和事实;如果技巧比内容更醒目,应主动削弱。"
+ }
+ },
+ {
+ "schemaVersion": 1,
+ "id": "community.khazix-writer",
+ "version": "1.0.0",
+ "name": "卡兹克公众号长文写作",
+ "description": "用聊天感、真实体验和层层推进写出有判断力的公众号长文",
+ "localizations": {
+ "zh-CN": {
+ "name": "卡兹克公众号长文写作",
+ "description": "用聊天感、真实体验和层层推进写出有判断力的公众号长文",
+ "tags": [
+ "公众号长文",
+ "口语节奏",
+ "真实体验",
+ "观点叙事"
+ ],
+ "structure": [
+ "具体事件开场",
+ "聊天式背景铺垫",
+ "观点与案例推进",
+ "回环或余韵收尾"
+ ],
+ "instructions": "从来源支持的具体事件、体验或好奇心切入,以口语化节奏推进观点,用真实案例、明确判断和自然转场维持阅读心流。只使用用户与来源提供的第一手经历,不冒充原作者,不编造个人体验。"
+ },
+ "en-US": {
+ "name": "Khazix Long-form WeChat Writing",
+ "description": "Conversational long-form writing built on real experience and progressive argument",
+ "tags": [
+ "Long-form article",
+ "Conversational rhythm",
+ "Real experience",
+ "Opinion narrative"
+ ],
+ "structure": [
+ "Concrete event opening",
+ "Conversational context",
+ "Ideas and examples",
+ "Callback or resonant close"
+ ],
+ "instructions": "Begin with a source-supported event, experience, or genuine question. Develop the argument in a conversational rhythm, using real examples, clear judgments, and natural transitions to sustain reading flow. Use first-hand experience only when supplied by the user or sources; do not impersonate the original author or invent personal experience."
+ }
+ },
+ "categoryId": "story",
+ "domains": [
+ "technology",
+ "workplace"
+ ],
+ "tags": [
+ "公众号长文",
+ "口语节奏",
+ "真实体验",
+ "观点叙事"
+ ],
+ "structure": [
+ "具体事件开场",
+ "聊天式背景铺垫",
+ "观点与案例推进",
+ "回环或余韵收尾"
+ ],
+ "instructions": "从来源支持的具体事件、体验或好奇心切入,以口语化节奏推进观点,用真实案例、明确判断和自然转场维持阅读心流。只使用用户与来源提供的第一手经历,不冒充原作者,不编造个人体验。",
+ "author": "数字生命卡兹克",
+ "status": "featured",
+ "sortOrder": 110,
+ "source": {
+ "type": "github",
+ "repository": "KKKKhazix/khazix-skills",
+ "revision": "7a5c4934be4106ac740ffdb95280bb81b3f4b83c",
+ "url": "https://github.com/KKKKhazix/khazix-skills/blob/main/khazix-writer/SKILL.md",
+ "license": "MIT"
+ },
+ "contentHash": "e2c5e7040fe5439e16d9a07746cf429292a94360df03b35ad213c1fc2db0e628",
+ "stagePrompts": {
+ "topics": "# 卡兹克公众号长文写作:选题判断\n\n先吃透内容来源和用户的写作要求,再生成选题。不得用想象补齐来源中不存在的事实、经历、数据或引语。\n\n## HKR 质检\n\n每个候选选题至少满足下面两项,并在角度或摘要中体现其优势:\n\n- Happy:有趣、有反差或有悬念,让读者产生继续了解的好奇心。\n- Knowledge:包含新信息、新方法或能够改变理解的背景知识。\n- Resonance:能连接目标读者真实面对的处境、情绪或争议。\n\n优先提出同时满足三项的选题。多个候选之间要有明显差异,不要只替换标题措辞。\n\n## 文章原型\n\n根据材料选择最合适的原型:调查实验型、产品体验型、现象解读型、工具分享型、方法论分享型。选题必须说明文章从什么具体事件、场景、问题或体验切入,以及核心判断是什么。\n\n如果材料不足以支撑第一人称经历,改用观察者或分析者视角,不得冒充模板作者,也不得虚构作者已经亲自做过某件事。",
+ "outline": "# 卡兹克公众号长文写作\n\n本模板接入自 `KKKKhazix/khazix-skills` 中的 `khazix-writer`。它提取原 Skill 的写作方法用于文章生成,不代表原作者本人发言,也不允许冒充「数字生命卡兹克」或自动添加原账号署名、联系方式和固定推广尾部。\n\n## 核心底色\n\n- 对新事物保持真实好奇,从「这件事哪里有意思」出发,而不是从宏大结论出发。\n- 讲人话,允许明确表达判断和不确定性,避免滴水不漏但没有温度的报告腔。\n- 真诚优先。产品有缺点就写缺点,不懂就承认不懂,不用不存在的细节增强戏剧性。\n- 观点必须是作者真的相信并愿意表达的,不能为了流量强行制造立场。\n\n## 素材边界\n\n先区分来源事实、用户提供的第一手经历、可验证的背景知识和写作者判断。第一手观察、真实经历、情绪节点和核心创意只能来自用户或内容来源。不得替用户编造试用过程、人物对话、精确数字、现场反应或私人关系。\n\n当素材不足时,保留信息缺口,用诚实的限定语表达,或者调整成不依赖虚构经历的观察视角。\n\n## 文章原型\n\n- 调查实验型:围绕「我替读者实际验证了一件事」展开,重点是过程、意外和发现的递进。只有材料明确提供真实实验时才能使用第一人称。\n- 产品体验型:带读者进入真实使用场景,展示操作、结果、感受和限制。\n- 现象解读型:按观察、好奇、研究、判断的路径推进,从表面现象逐层追问。\n- 工具分享型:用一个真实问题引出工具,用具体案例证明价值,同时交代限制和成本。\n- 方法论分享型:每一部分都给出可执行动作,并坦诚说明学习曲线、失败点和适用边界。\n\n## 开头\n\n从内容来源中真实存在的当下事件、具体场景、反常事实或问题切入。前三段就让读者知道发生了什么,以及为什么值得继续看。禁止使用「在当今快速发展的时代」「随着技术不断进步」等教科书式空话。\n\n开头可以直接启动叙事,也可以抛出一个来源支持的荒诞事实、热点变化或好奇心。不要在开头先解释全文结构。\n\n## 推进与节奏\n\n文章像和朋友认真聊天,而不是提交报告。句子长短交替,段落保持轻盈,关键判断可以独立成段。每次展开背景、案例或类比之后,用一句简短的话扣回主线,避免读者为了理解结构而回头。\n\n一个内容板块通常包含:明确观点、具体事实或案例、与读者处境的连接,以及扣回主线的转场。知识要像聊天过程中自然拿出来的补充,不使用「下面科普一下」式的讲义口吻。\n\n涉及多个产品、模型或案例时,逐一展示,不要一次罗列所有结论。顺序从基础发现推进到最有反差的结果,让每一轮比上一轮更深入或更意外。\n\n## 判断与同理心\n\n可以有明确好恶,但不要居高临下。讨论争议观点时,先把另一方的真实处境具体化,承认其合理部分,再给出自己的不同判断。\n\n需要从具体事件连接到文化、历史或哲学背景时,连接必须服务于当前问题,并且由来源或可靠知识支持。不要为了显得深刻强行升华。\n\n## 真实感\n\n优先使用具体产品名、动作、限制、结果和环境细节,避免「某个模型」「相关技术」「非常震撼」等空泛表达。情绪要落在可观察的反应上,但这些反应必须来自真实材料。\n\n可以使用自然口语和少量不完整句制造呼吸感,但不能机械堆砌口头禅、粗口、夸张标点或模板作者的个人习惯。目标是吸收节奏方法,不是复刻某个人的身份特征。\n\n## 结构\n\n典型长文可以采用以下推进关系:\n\n1. 用具体事件或场景快速建立好奇心。\n2. 用聊天式背景补齐非专业读者需要的信息。\n3. 围绕核心判断展开若干板块,每个板块都有事实或案例支撑。\n4. 在必要时连接更大的文化、历史或行业背景。\n5. 回到开头的意象、问题或判断,以回环、余韵或明确行动收尾。\n\n除非文章本身是「N 条方法」等条目型内容,否则不要滥用 Markdown 小标题和列表。优先用自然转场形成连续阅读体验。不要自动添加上游 Skill 中属于原作者账号的固定署名、邮箱或关注引导。\n\n## 语言禁区\n\n- 不使用「首先、其次、最后」「综上所述」「值得注意的是」「不难发现」「让我们来看看」等套话组织文章。\n- 不堆砌加粗、项目符号和形式整齐但内容空泛的排比。\n- 不用假设性第一人称故事替代真实案例。\n- 不把所有观点包装成绝对结论,保留来源和认知边界。\n- 不为了模仿风格而强制使用粗口、特殊标点或原作者口癖。\n\n## 收尾\n\n从文章已经建立的内容自然收束。可以回到开头的物件或问题,可以留下简短判断,也可以给出读者今天能做的一件事。避免总结全文、重复观点和强行拔高。",
+ "article": "# 卡兹克公众号长文写作\n\n本模板接入自 `KKKKhazix/khazix-skills` 中的 `khazix-writer`。它提取原 Skill 的写作方法用于文章生成,不代表原作者本人发言,也不允许冒充「数字生命卡兹克」或自动添加原账号署名、联系方式和固定推广尾部。\n\n## 核心底色\n\n- 对新事物保持真实好奇,从「这件事哪里有意思」出发,而不是从宏大结论出发。\n- 讲人话,允许明确表达判断和不确定性,避免滴水不漏但没有温度的报告腔。\n- 真诚优先。产品有缺点就写缺点,不懂就承认不懂,不用不存在的细节增强戏剧性。\n- 观点必须是作者真的相信并愿意表达的,不能为了流量强行制造立场。\n\n## 素材边界\n\n先区分来源事实、用户提供的第一手经历、可验证的背景知识和写作者判断。第一手观察、真实经历、情绪节点和核心创意只能来自用户或内容来源。不得替用户编造试用过程、人物对话、精确数字、现场反应或私人关系。\n\n当素材不足时,保留信息缺口,用诚实的限定语表达,或者调整成不依赖虚构经历的观察视角。\n\n## 文章原型\n\n- 调查实验型:围绕「我替读者实际验证了一件事」展开,重点是过程、意外和发现的递进。只有材料明确提供真实实验时才能使用第一人称。\n- 产品体验型:带读者进入真实使用场景,展示操作、结果、感受和限制。\n- 现象解读型:按观察、好奇、研究、判断的路径推进,从表面现象逐层追问。\n- 工具分享型:用一个真实问题引出工具,用具体案例证明价值,同时交代限制和成本。\n- 方法论分享型:每一部分都给出可执行动作,并坦诚说明学习曲线、失败点和适用边界。\n\n## 开头\n\n从内容来源中真实存在的当下事件、具体场景、反常事实或问题切入。前三段就让读者知道发生了什么,以及为什么值得继续看。禁止使用「在当今快速发展的时代」「随着技术不断进步」等教科书式空话。\n\n开头可以直接启动叙事,也可以抛出一个来源支持的荒诞事实、热点变化或好奇心。不要在开头先解释全文结构。\n\n## 推进与节奏\n\n文章像和朋友认真聊天,而不是提交报告。句子长短交替,段落保持轻盈,关键判断可以独立成段。每次展开背景、案例或类比之后,用一句简短的话扣回主线,避免读者为了理解结构而回头。\n\n一个内容板块通常包含:明确观点、具体事实或案例、与读者处境的连接,以及扣回主线的转场。知识要像聊天过程中自然拿出来的补充,不使用「下面科普一下」式的讲义口吻。\n\n涉及多个产品、模型或案例时,逐一展示,不要一次罗列所有结论。顺序从基础发现推进到最有反差的结果,让每一轮比上一轮更深入或更意外。\n\n## 判断与同理心\n\n可以有明确好恶,但不要居高临下。讨论争议观点时,先把另一方的真实处境具体化,承认其合理部分,再给出自己的不同判断。\n\n需要从具体事件连接到文化、历史或哲学背景时,连接必须服务于当前问题,并且由来源或可靠知识支持。不要为了显得深刻强行升华。\n\n## 真实感\n\n优先使用具体产品名、动作、限制、结果和环境细节,避免「某个模型」「相关技术」「非常震撼」等空泛表达。情绪要落在可观察的反应上,但这些反应必须来自真实材料。\n\n可以使用自然口语和少量不完整句制造呼吸感,但不能机械堆砌口头禅、粗口、夸张标点或模板作者的个人习惯。目标是吸收节奏方法,不是复刻某个人的身份特征。\n\n## 结构\n\n典型长文可以采用以下推进关系:\n\n1. 用具体事件或场景快速建立好奇心。\n2. 用聊天式背景补齐非专业读者需要的信息。\n3. 围绕核心判断展开若干板块,每个板块都有事实或案例支撑。\n4. 在必要时连接更大的文化、历史或行业背景。\n5. 回到开头的意象、问题或判断,以回环、余韵或明确行动收尾。\n\n除非文章本身是「N 条方法」等条目型内容,否则不要滥用 Markdown 小标题和列表。优先用自然转场形成连续阅读体验。不要自动添加上游 Skill 中属于原作者账号的固定署名、邮箱或关注引导。\n\n## 语言禁区\n\n- 不使用「首先、其次、最后」「综上所述」「值得注意的是」「不难发现」「让我们来看看」等套话组织文章。\n- 不堆砌加粗、项目符号和形式整齐但内容空泛的排比。\n- 不用假设性第一人称故事替代真实案例。\n- 不把所有观点包装成绝对结论,保留来源和认知边界。\n- 不为了模仿风格而强制使用粗口、特殊标点或原作者口癖。\n\n## 收尾\n\n从文章已经建立的内容自然收束。可以回到开头的物件或问题,可以留下简短判断,也可以给出读者今天能做的一件事。避免总结全文、重复观点和强行拔高。\n\n# 卡兹克公众号长文写作:四层质检\n\n成稿后按四层顺序检查并直接修复问题。质检服务于文章质量,不要求在最终文章正文中附带报告。\n\n## L1 硬性规则\n\n- 清除「首先、其次、最后」「综上所述」「值得注意的是」「不难发现」「让我们来看看」等报告腔套话。\n- 检查是否存在大段加粗、连续列表、教科书式开头和空泛工具名。\n- 删除来源不支持的经历、对话、数字、情绪反应和假设性第一人称案例。\n- 确认没有原作者署名、联系方式、账号推广或冒充作者身份的表述。\n\n## L2 风格一致性\n\n- 开头是否来自具体事件、场景、反常事实或真实问题。\n- 长短句、短段落和关键独立句是否形成自然节奏,而不是整齐划一。\n- 展开的背景或案例后是否及时扣回主线。\n- 口语表达是否自然,是否避免机械堆砌口头禅和夸张标点。\n\n## L3 内容质量\n\n- 每个核心观点是否都有来源事实、具体案例或可靠知识支撑。\n- 知识是否自然融入叙述,而不是突然切换成讲义。\n- 对立观点是否得到公平解释,判断是否建立在理解对方处境之后。\n- 调查、体验、解读、工具分享或方法论等文章原型是否采用了对应的推进方式。\n- 多个案例是否逐一展开,并形成由浅入深的发现过程。\n\n## L4 真实感终审\n\n通读全文,判断它像一个有见识的普通人在认真聊一件打动他的事,还是像模型在整理信息。重点检查情绪是否来自材料、细节是否可信、观点是否有作者自己的判断,以及阅读心流是否在某处中断。\n\n如果风格技巧比内容本身更醒目,主动降低模仿痕迹,让文章回到事实、观点和读者体验。",
+ "review": "# 卡兹克公众号长文写作:四层质检\n\n成稿后按四层顺序检查并直接修复问题。质检服务于文章质量,不要求在最终文章正文中附带报告。\n\n## L1 硬性规则\n\n- 清除「首先、其次、最后」「综上所述」「值得注意的是」「不难发现」「让我们来看看」等报告腔套话。\n- 检查是否存在大段加粗、连续列表、教科书式开头和空泛工具名。\n- 删除来源不支持的经历、对话、数字、情绪反应和假设性第一人称案例。\n- 确认没有原作者署名、联系方式、账号推广或冒充作者身份的表述。\n\n## L2 风格一致性\n\n- 开头是否来自具体事件、场景、反常事实或真实问题。\n- 长短句、短段落和关键独立句是否形成自然节奏,而不是整齐划一。\n- 展开的背景或案例后是否及时扣回主线。\n- 口语表达是否自然,是否避免机械堆砌口头禅和夸张标点。\n\n## L3 内容质量\n\n- 每个核心观点是否都有来源事实、具体案例或可靠知识支撑。\n- 知识是否自然融入叙述,而不是突然切换成讲义。\n- 对立观点是否得到公平解释,判断是否建立在理解对方处境之后。\n- 调查、体验、解读、工具分享或方法论等文章原型是否采用了对应的推进方式。\n- 多个案例是否逐一展开,并形成由浅入深的发现过程。\n\n## L4 真实感终审\n\n通读全文,判断它像一个有见识的普通人在认真聊一件打动他的事,还是像模型在整理信息。重点检查情绪是否来自材料、细节是否可信、观点是否有作者自己的判断,以及阅读心流是否在某处中断。\n\n如果风格技巧比内容本身更醒目,主动降低模仿痕迹,让文章回到事实、观点和读者体验。"
+ }
+ },
+ {
+ "schemaVersion": 1,
+ "id": "community.research-paper-writing",
+ "version": "1.0.0",
+ "name": "Research Paper Writing",
+ "description": "用清晰章节、严密论证和审稿人视角组织科研论文与学术内容",
+ "localizations": {
+ "zh-CN": {
+ "name": "科研论文写作",
+ "description": "用清晰章节、严密论证和审稿人视角组织科研论文与学术内容",
+ "tags": [
+ "学术论文",
+ "章节结构",
+ "论点证据",
+ "投稿自审"
+ ],
+ "structure": [
+ "研究任务与问题",
+ "相关工作与技术挑战",
+ "方法与核心贡献",
+ "实验与证据",
+ "结论、局限与未来方向"
+ ],
+ "instructions": "先明确研究故事、技术问题和核心贡献,再按章节组织论证。每段只传递一个信息,首句说明段落作用,术语前后一致;摘要和引言中的重要主张必须由实验或来源证据支持。成稿后使用审稿人视角检查贡献、表达、实验、评估完整性和方法合理性。"
+ },
+ "en-US": {
+ "name": "Research Paper Writing",
+ "description": "Structure research papers with clear sections, rigorous arguments, and a reviewer's perspective",
+ "tags": [
+ "Academic paper",
+ "Section structure",
+ "Claim and evidence",
+ "Pre-submission review"
+ ],
+ "structure": [
+ "Research task and problem",
+ "Related work and challenge",
+ "Method and contribution",
+ "Experiments and evidence",
+ "Conclusion, limits, and future work"
+ ],
+ "instructions": "Clarify the research story, technical problem, and core contribution before organizing the argument by section. Give each paragraph one message, state its role in the opening sentence, and keep terminology consistent. Every major claim in the abstract and introduction must be supported by experiments or source evidence. Review the draft for contribution, clarity, experimental strength, evaluation completeness, and method soundness."
+ }
+ },
+ "categoryId": "analysis",
+ "domains": [
+ "research"
+ ],
+ "tags": [
+ "学术论文",
+ "章节结构",
+ "论点证据",
+ "投稿自审"
+ ],
+ "structure": [
+ "研究任务与问题",
+ "相关工作与技术挑战",
+ "方法与核心贡献",
+ "实验与证据",
+ "结论、局限与未来方向"
+ ],
+ "instructions": "先明确研究故事、技术问题和核心贡献,再按章节组织论证。每段只传递一个信息,首句说明段落作用,术语前后一致;摘要和引言中的重要主张必须由实验或来源证据支持。成稿后使用审稿人视角检查贡献、表达、实验、评估完整性和方法合理性。",
+ "author": "Master-cai / OpenCreator adapted",
+ "status": "featured",
+ "sortOrder": 120,
+ "source": {
+ "type": "github",
+ "repository": "Master-cai/Research-Paper-Writing-Skills",
+ "revision": "77e7c2c1ba06f7d71844873147665437a03aac1b",
+ "url": "https://github.com/Master-cai/Research-Paper-Writing-Skills",
+ "license": "MIT"
+ },
+ "contentHash": "c8ce7ee2b0d4b815ca672ecea3b7a0cc3a646ab03aa9c306b5dcc072b351bb03",
+ "stagePrompts": {
+ "topics": "# Research Paper Writing:科研选题判断\n\n先读取内容来源、研究材料和用户要求,再提出候选选题。选题必须由已有材料支撑,不得虚构实验结果、数据集、基线、引用或研究贡献。\n\n## 候选选题要求\n\n- 明确研究任务、具体技术问题和目标读者,不使用只有领域名的宽泛题目。\n- 说明现有方法的关键局限及其技术原因,且该局限应当正是文章准备讨论或解决的问题。\n- 指出可被材料支持的核心贡献、新见解或实证发现。\n- 给出选题所需的证据基础,例如对比实验、消融实验、案例、论文引用或来源事实。\n- 多个候选应当在研究问题、论证角度或目标章节上真正不同,不只是改写标题。\n\n若材料不足以支持强结论,应缩小范围,改成问题梳理、方法比较、研究综述或待验证假设,并明确证据缺口。",
+ "outline": "# Research Paper Writing\n\n本模板接入自 `Master-cai/Research-Paper-Writing-Skills`,用于提升科研论文和学术内容的章节结构、段落流畅性、论点证据对齐及审稿人可读性。上游说明其大部分写作知识与方法来自彭思达教授公开的学习笔记和 `pengsida/learning_research`;本模板保留该归属,并将方法适配到 OpenCreator 的写作流程。\n\n## 核心工作流\n\n1. 在润色句子前先明确完整的研究故事:任务、技术问题、贡献、为什么有效,以及需要哪些证据。\n2. 为文章建立紧凑提纲,确保每一节都服务于主问题,每一段只传递一个信息。\n3. 每段首句说明该段作用,后续句子通过因果、对比、结果、细化或例子自然衔接。\n4. 新术语先定义再复用,全文保持术语、符号和概念边界一致。\n5. 摘要和引言中的每个重要主张都必须对应实验、数据或来源证据;没有证据时减弱或删除主张。\n6. 完成章节后执行反向提纲,再以怀疑性的审稿人视角做终审。\n\n## 提纲组织\n\n根据写作目标选择需要的章节,不为凑结构强行加入无关部分。\n\n- 摘要:任务,技术挑战,洞见或贡献,贡献带来的优势,实验结果。\n- 引言:任务与应用,已有方法及其真正局限,本文方案与为什么有效,贡献,实验概览。\n- 相关工作:按技术主题分组,概括共同范式,指出与目标问题相关的局限,并说明本文差异。\n- 方法:先给设置和总体方案;每个模块按动机、设计或执行过程、技术优势展开。\n- 实验:用强基线证明效果,用消融验证关键设计,用困难或分布外场景说明泛化和边界。\n- 结论:重述问题与核心洞见,总结最强证据,坦诚说明适用边界,并给出具体未来方向。\n\n## 段落与论证\n\n每段只承担一种角色,例如定义任务、提出挑战、解释技术原因、描述方法、陈述优势、提供证据或说明局限。段首句应让外部读者立刻理解该段要做什么。\n\n写完后做反向提纲:列出全文主张、各段主题句和各段证据,逐项检查“主题句是否支持主张、证据是否支持主题句”。不能清晰对应的段落应修改、移动或删除。\n\n不要把工作写成“先提出一个幼稚方案,再打补丁”的增量叙事,也不要只堆抽象洞见而隐藏实际方法。清楚说明真正的技术挑战、技术原因、解决机制和可验证优势。\n\n## 来源与真实性\n\n只能使用用户或内容来源中存在的论文、数据、实验、基线、指标、引语和结论。无法验证的信息必须标记为待补充,不得自动编造引用或数值。区分事实、作者主张、实验观察和写作者推断。\n\n## 输出要求\n\n成稿应具有清晰章节和稳定术语。对主要论点,在写作过程中维护“论点、证据、状态”的对应关系;证据不足的状态只能是“需要证据”,不能用更强措辞掩盖缺口。最终正文不必附带内部检查过程,除非用户明确要求。",
+ "article": "# Research Paper Writing\n\n本模板接入自 `Master-cai/Research-Paper-Writing-Skills`,用于提升科研论文和学术内容的章节结构、段落流畅性、论点证据对齐及审稿人可读性。上游说明其大部分写作知识与方法来自彭思达教授公开的学习笔记和 `pengsida/learning_research`;本模板保留该归属,并将方法适配到 OpenCreator 的写作流程。\n\n## 核心工作流\n\n1. 在润色句子前先明确完整的研究故事:任务、技术问题、贡献、为什么有效,以及需要哪些证据。\n2. 为文章建立紧凑提纲,确保每一节都服务于主问题,每一段只传递一个信息。\n3. 每段首句说明该段作用,后续句子通过因果、对比、结果、细化或例子自然衔接。\n4. 新术语先定义再复用,全文保持术语、符号和概念边界一致。\n5. 摘要和引言中的每个重要主张都必须对应实验、数据或来源证据;没有证据时减弱或删除主张。\n6. 完成章节后执行反向提纲,再以怀疑性的审稿人视角做终审。\n\n## 提纲组织\n\n根据写作目标选择需要的章节,不为凑结构强行加入无关部分。\n\n- 摘要:任务,技术挑战,洞见或贡献,贡献带来的优势,实验结果。\n- 引言:任务与应用,已有方法及其真正局限,本文方案与为什么有效,贡献,实验概览。\n- 相关工作:按技术主题分组,概括共同范式,指出与目标问题相关的局限,并说明本文差异。\n- 方法:先给设置和总体方案;每个模块按动机、设计或执行过程、技术优势展开。\n- 实验:用强基线证明效果,用消融验证关键设计,用困难或分布外场景说明泛化和边界。\n- 结论:重述问题与核心洞见,总结最强证据,坦诚说明适用边界,并给出具体未来方向。\n\n## 段落与论证\n\n每段只承担一种角色,例如定义任务、提出挑战、解释技术原因、描述方法、陈述优势、提供证据或说明局限。段首句应让外部读者立刻理解该段要做什么。\n\n写完后做反向提纲:列出全文主张、各段主题句和各段证据,逐项检查“主题句是否支持主张、证据是否支持主题句”。不能清晰对应的段落应修改、移动或删除。\n\n不要把工作写成“先提出一个幼稚方案,再打补丁”的增量叙事,也不要只堆抽象洞见而隐藏实际方法。清楚说明真正的技术挑战、技术原因、解决机制和可验证优势。\n\n## 来源与真实性\n\n只能使用用户或内容来源中存在的论文、数据、实验、基线、指标、引语和结论。无法验证的信息必须标记为待补充,不得自动编造引用或数值。区分事实、作者主张、实验观察和写作者推断。\n\n## 输出要求\n\n成稿应具有清晰章节和稳定术语。对主要论点,在写作过程中维护“论点、证据、状态”的对应关系;证据不足的状态只能是“需要证据”,不能用更强措辞掩盖缺口。最终正文不必附带内部检查过程,除非用户明确要求。\n\n# Research Paper Writing:投稿前审稿式检查\n\n成稿后以怀疑性的审稿人视角逐项检查并直接修订。检查过程服务于正文质量,默认不作为正文附录输出。\n\n## 硬性约束\n\n- 摘要和引言中的每个重要主张是否技术上正确,并由正文中的实验、数据或来源证据明确支持。\n- 是否存在虚构引用、数据集、基线、指标、实验结果、实现细节或研究贡献。\n- 关键术语、符号、任务边界和结论强度是否前后一致。\n- 每段是否只有一个中心信息,首句能否说明该段作用,句间关系是否清楚。\n\n## 五个审稿维度\n\n1. 贡献:读者能获得什么新知识;创新属于新任务、流程、模块、设计发现还是洞见;是否超出显而易见的增量改动。\n2. 表达:方法是否足够清楚可复现;每个模块是否有明确动机;术语和段落逻辑是否稳定。\n3. 实验强度:是否与近期强基线公平比较;提升是否有意义;是否同时说明优势、失败案例和限制。\n4. 评估完整性:关键设计是否有消融;指标和数据集是否足够;所有主要主张是否有对应验证。\n5. 方法合理性:设置是否现实;假设是否合理;是否需要逐场景调参;新增复杂度和局限是否超过收益。\n\n## 反向提纲与论点证据表\n\n列出主张、各段主题句和证据,检查每一层是否能够向上支撑。为每个主要主张记录:`论点:... | 证据:... | 状态:已支持/需要证据`。状态为“需要证据”时,只能补充证据、减弱结论或删除主张。\n\n重复审阅和修订,直到不存在未处理的高风险拒稿理由。",
+ "review": "# Research Paper Writing:投稿前审稿式检查\n\n成稿后以怀疑性的审稿人视角逐项检查并直接修订。检查过程服务于正文质量,默认不作为正文附录输出。\n\n## 硬性约束\n\n- 摘要和引言中的每个重要主张是否技术上正确,并由正文中的实验、数据或来源证据明确支持。\n- 是否存在虚构引用、数据集、基线、指标、实验结果、实现细节或研究贡献。\n- 关键术语、符号、任务边界和结论强度是否前后一致。\n- 每段是否只有一个中心信息,首句能否说明该段作用,句间关系是否清楚。\n\n## 五个审稿维度\n\n1. 贡献:读者能获得什么新知识;创新属于新任务、流程、模块、设计发现还是洞见;是否超出显而易见的增量改动。\n2. 表达:方法是否足够清楚可复现;每个模块是否有明确动机;术语和段落逻辑是否稳定。\n3. 实验强度:是否与近期强基线公平比较;提升是否有意义;是否同时说明优势、失败案例和限制。\n4. 评估完整性:关键设计是否有消融;指标和数据集是否足够;所有主要主张是否有对应验证。\n5. 方法合理性:设置是否现实;假设是否合理;是否需要逐场景调参;新增复杂度和局限是否超过收益。\n\n## 反向提纲与论点证据表\n\n列出主张、各段主题句和证据,检查每一层是否能够向上支撑。为每个主要主张记录:`论点:... | 证据:... | 状态:已支持/需要证据`。状态为“需要证据”时,只能补充证据、减弱结论或删除主张。\n\n重复审阅和修订,直到不存在未处理的高风险拒稿理由。"
+ }
+ },
+ {
+ "schemaVersion": 1,
+ "id": "insight",
+ "version": "1.0.0",
+ "name": "深度洞察",
+ "description": "观点鲜明,适合行业观察与趋势分析",
+ "localizations": {
+ "zh-CN": {
+ "name": "深度洞察",
+ "description": "观点鲜明,适合行业观察与趋势分析",
+ "tags": [
+ "观点先行",
+ "行业观察",
+ "层层论证"
+ ],
+ "structure": [
+ "核心判断",
+ "背景与问题",
+ "分层论证",
+ "行动建议"
+ ],
+ "instructions": "以清晰的问题意识开篇,先给结论再展开论证。使用二到四个层次分明的小标题,结合来源中的事实、数据和案例,避免空泛判断。结尾给出可执行的观察或建议。"
+ },
+ "en-US": {
+ "name": "Deep Insight",
+ "description": "Clear points of view for industry observations and trend analysis",
+ "tags": [
+ "Thesis first",
+ "Industry insight",
+ "Layered argument"
+ ],
+ "structure": [
+ "Core judgment",
+ "Context and problem",
+ "Layered argument",
+ "Actionable advice"
+ ],
+ "instructions": "Open with a clearly defined problem and state the conclusion before developing the argument. Use two to four well-structured section headings, grounding each point in facts, data, and examples from the sources. Avoid vague claims and close with actionable observations or recommendations."
+ }
+ },
+ "categoryId": "analysis",
+ "domains": [
+ "technology",
+ "finance",
+ "workplace"
+ ],
+ "tags": [
+ "观点先行",
+ "行业观察",
+ "层层论证"
+ ],
+ "structure": [
+ "核心判断",
+ "背景与问题",
+ "分层论证",
+ "行动建议"
+ ],
+ "instructions": "以清晰的问题意识开篇,先给结论再展开论证。使用二到四个层次分明的小标题,结合来源中的事实、数据和案例,避免空泛判断。结尾给出可执行的观察或建议。",
+ "author": "OpenCreator",
+ "status": "verified",
+ "sortOrder": 10,
+ "source": {
+ "type": "official",
+ "repository": null,
+ "revision": null,
+ "url": null,
+ "license": "OpenCreator project"
+ },
+ "contentHash": "d5918440e881293e62a3eca7f0bedf0f5d1935db725aa769028611b943a291b9",
+ "stagePrompts": {
+ "topics": "# 深度洞察写作规则\n\n- 选题必须包含可验证的问题、明确受众和有信息增量的判断,避免空泛的大词。\n- 大纲先给核心结论,再用事实、数据、案例或来源中的对比逐层论证。\n- 正文区分来源事实与作者判断。二到四个主体章节即可,每个章节回答一个具体问题。\n- 结尾给出可执行建议或后续观察信号,不重复全文摘要。",
+ "outline": "# 深度洞察写作规则\n\n- 选题必须包含可验证的问题、明确受众和有信息增量的判断,避免空泛的大词。\n- 大纲先给核心结论,再用事实、数据、案例或来源中的对比逐层论证。\n- 正文区分来源事实与作者判断。二到四个主体章节即可,每个章节回答一个具体问题。\n- 结尾给出可执行建议或后续观察信号,不重复全文摘要。",
+ "article": "# 深度洞察写作规则\n\n- 选题必须包含可验证的问题、明确受众和有信息增量的判断,避免空泛的大词。\n- 大纲先给核心结论,再用事实、数据、案例或来源中的对比逐层论证。\n- 正文区分来源事实与作者判断。二到四个主体章节即可,每个章节回答一个具体问题。\n- 结尾给出可执行建议或后续观察信号,不重复全文摘要。"
+ }
+ },
+ {
+ "schemaVersion": 1,
+ "id": "story",
+ "version": "1.0.0",
+ "name": "故事叙事",
+ "description": "从人物或场景切入,强调阅读节奏",
+ "localizations": {
+ "zh-CN": {
+ "name": "故事叙事",
+ "description": "从人物或场景切入,强调阅读节奏",
+ "tags": [
+ "场景开篇",
+ "人物叙事",
+ "情绪节奏"
+ ],
+ "structure": [
+ "人物或场景",
+ "矛盾推进",
+ "关键转折",
+ "主题回扣"
+ ],
+ "instructions": "用具体人物、场景或冲突开篇,按故事推进承载核心观点。段落短而有节奏,关键转折处设置小标题,避免编造来源中不存在的细节。结尾回扣开头并留下余味。"
+ },
+ "en-US": {
+ "name": "Narrative Storytelling",
+ "description": "Lead with a person or scene and build a strong reading rhythm",
+ "tags": [
+ "Scene opening",
+ "Character story",
+ "Emotional rhythm"
+ ],
+ "structure": [
+ "Person or scene",
+ "Rising conflict",
+ "Key turn",
+ "Thematic callback"
+ ],
+ "instructions": "Open with a specific person, scene, or conflict, then carry the central idea through the story's progression. Keep paragraphs concise and rhythmic, use headings at meaningful turns, and never invent details absent from the sources. Close by returning to the opening and leave the reader with a lingering thought."
+ }
+ },
+ "categoryId": "story",
+ "domains": [
+ "emotion",
+ "lifestyle"
+ ],
+ "tags": [
+ "场景开篇",
+ "人物叙事",
+ "情绪节奏"
+ ],
+ "structure": [
+ "人物或场景",
+ "矛盾推进",
+ "关键转折",
+ "主题回扣"
+ ],
+ "instructions": "用具体人物、场景或冲突开篇,按故事推进承载核心观点。段落短而有节奏,关键转折处设置小标题,避免编造来源中不存在的细节。结尾回扣开头并留下余味。",
+ "author": "OpenCreator",
+ "status": "verified",
+ "sortOrder": 20,
+ "source": {
+ "type": "official",
+ "repository": null,
+ "revision": null,
+ "url": null,
+ "license": "OpenCreator project"
+ },
+ "contentHash": "63beedb290fd7875ffa552df4f57e58a069fb81cffca488e2bef24b5e952acaa",
+ "stagePrompts": {
+ "topics": "# 故事叙事写作规则\n\n- 选题从一个有行动、关系或冲突的人物切入,而不是先讲抽象道理。\n- 大纲按场景推进组织,每个场景都必须推动人物、冲突或核心观点发生变化。\n- 正文使用具体动作、对话和环境细节,保持段落节奏;没有来源支持的细节不得补写。\n- 结尾回扣开篇的场景、动作或问题,避免直接喊口号和强行升华。",
+ "outline": "# 故事叙事写作规则\n\n- 选题从一个有行动、关系或冲突的人物切入,而不是先讲抽象道理。\n- 大纲按场景推进组织,每个场景都必须推动人物、冲突或核心观点发生变化。\n- 正文使用具体动作、对话和环境细节,保持段落节奏;没有来源支持的细节不得补写。\n- 结尾回扣开篇的场景、动作或问题,避免直接喊口号和强行升华。",
+ "article": "# 故事叙事写作规则\n\n- 选题从一个有行动、关系或冲突的人物切入,而不是先讲抽象道理。\n- 大纲按场景推进组织,每个场景都必须推动人物、冲突或核心观点发生变化。\n- 正文使用具体动作、对话和环境细节,保持段落节奏;没有来源支持的细节不得补写。\n- 结尾回扣开篇的场景、动作或问题,避免直接喊口号和强行升华。"
+ }
+ },
+ {
+ "schemaVersion": 1,
+ "id": "tutorial",
+ "version": "1.0.0",
+ "name": "实用教程",
+ "description": "步骤清楚,适合方法论与操作指南",
+ "localizations": {
+ "zh-CN": {
+ "name": "实用教程",
+ "description": "步骤清楚,适合方法论与操作指南",
+ "tags": [
+ "步骤清晰",
+ "方法拆解",
+ "检查清单"
+ ],
+ "structure": [
+ "问题与收益",
+ "执行步骤",
+ "注意事项",
+ "完成检查"
+ ],
+ "instructions": "先说明读者问题和完成后的收益,再按可执行步骤展开。每一步说明目的、操作和注意事项,必要时使用清单。结尾提供检查表或下一步行动。"
+ },
+ "en-US": {
+ "name": "Practical Tutorial",
+ "description": "Clear steps for methods, workflows, and hands-on guides",
+ "tags": [
+ "Clear steps",
+ "Method breakdown",
+ "Checklist"
+ ],
+ "structure": [
+ "Problem and outcome",
+ "Action steps",
+ "Cautions",
+ "Completion check"
+ ],
+ "instructions": "Start by explaining the reader's problem and the outcome they can achieve, then proceed through executable steps. For each step, state its purpose, action, and cautions, using checklists where useful. End with a completion checklist or a clear next action."
+ }
+ },
+ "categoryId": "practical",
+ "domains": [
+ "technology",
+ "workplace",
+ "education"
+ ],
+ "tags": [
+ "步骤清晰",
+ "方法拆解",
+ "检查清单"
+ ],
+ "structure": [
+ "问题与收益",
+ "执行步骤",
+ "注意事项",
+ "完成检查"
+ ],
+ "instructions": "先说明读者问题和完成后的收益,再按可执行步骤展开。每一步说明目的、操作和注意事项,必要时使用清单。结尾提供检查表或下一步行动。",
+ "author": "OpenCreator",
+ "status": "verified",
+ "sortOrder": 30,
+ "source": {
+ "type": "official",
+ "repository": null,
+ "revision": null,
+ "url": null,
+ "license": "OpenCreator project"
+ },
+ "contentHash": "690727ca030ce7ccf03e7640596e60b34576f917ffc6a4155420d44e60bcb312",
+ "stagePrompts": {
+ "topics": "# 实用教程写作规则\n\n- 选题写清目标读者要解决的问题、完成后的具体结果和适用边界。\n- 大纲按执行顺序排列步骤,每一步都说明目的、动作、输入输出和常见风险。\n- 正文优先使用清单、表格、示例和验证方式;命令、版本、数据不得脱离来源臆造。\n- 结尾给出能够逐项核对的完成检查,而不是泛泛总结。",
+ "outline": "# 实用教程写作规则\n\n- 选题写清目标读者要解决的问题、完成后的具体结果和适用边界。\n- 大纲按执行顺序排列步骤,每一步都说明目的、动作、输入输出和常见风险。\n- 正文优先使用清单、表格、示例和验证方式;命令、版本、数据不得脱离来源臆造。\n- 结尾给出能够逐项核对的完成检查,而不是泛泛总结。",
+ "article": "# 实用教程写作规则\n\n- 选题写清目标读者要解决的问题、完成后的具体结果和适用边界。\n- 大纲按执行顺序排列步骤,每一步都说明目的、动作、输入输出和常见风险。\n- 正文优先使用清单、表格、示例和验证方式;命令、版本、数据不得脱离来源臆造。\n- 结尾给出能够逐项核对的完成检查,而不是泛泛总结。"
+ }
+ },
+ {
+ "schemaVersion": 1,
+ "id": "news-analysis",
+ "version": "1.0.0",
+ "name": "热点解读",
+ "description": "快速交代事件,再解释影响与判断",
+ "localizations": {
+ "zh-CN": {
+ "name": "热点解读",
+ "description": "快速交代事件,再解释影响与判断",
+ "tags": [
+ "事实速览",
+ "影响分析",
+ "趋势判断"
+ ],
+ "structure": [
+ "事件概况",
+ "重要背景",
+ "影响对象",
+ "后续信号"
+ ],
+ "instructions": "开头用最少篇幅交代发生了什么,随后回答为什么重要、影响谁、接下来关注什么。区分来源事实与作者判断,不夸大结论,不制造未经来源支持的数据。"
+ },
+ "en-US": {
+ "name": "News Analysis",
+ "description": "Explain what happened, then assess its impact and significance",
+ "tags": [
+ "Fact summary",
+ "Impact analysis",
+ "Trend outlook"
+ ],
+ "structure": [
+ "What happened",
+ "Essential context",
+ "Who is affected",
+ "Signals to watch"
+ ],
+ "instructions": "Use as little space as possible to establish what happened, then explain why it matters, who it affects, and what to watch next. Clearly separate sourced facts from the author's judgment, avoid overstating conclusions, and never invent unsupported data."
+ }
+ },
+ "categoryId": "news",
+ "domains": [
+ "technology",
+ "finance"
+ ],
+ "tags": [
+ "事实速览",
+ "影响分析",
+ "趋势判断"
+ ],
+ "structure": [
+ "事件概况",
+ "重要背景",
+ "影响对象",
+ "后续信号"
+ ],
+ "instructions": "开头用最少篇幅交代发生了什么,随后回答为什么重要、影响谁、接下来关注什么。区分来源事实与作者判断,不夸大结论,不制造未经来源支持的数据。",
+ "author": "OpenCreator",
+ "status": "verified",
+ "sortOrder": 40,
+ "source": {
+ "type": "official",
+ "repository": null,
+ "revision": null,
+ "url": null,
+ "license": "OpenCreator project"
+ },
+ "contentHash": "80bce82d0081abc8050eec6d610f74eca0b905a06ef5445a527750fbc7ef5cda",
+ "stagePrompts": {
+ "topics": "# 热点解读写作规则\n\n- 选题必须指出已确认的事件、受影响对象和一个值得解释的关键问题。\n- 大纲依次组织事实速览、必要背景、影响分析和后续观察信号。\n- 正文明确标记哪些是来源事实、哪些是作者判断;不把推测写成事实。\n- 避免标题党、夸大因果和来源没有支持的数字,结尾保留不确定性。",
+ "outline": "# 热点解读写作规则\n\n- 选题必须指出已确认的事件、受影响对象和一个值得解释的关键问题。\n- 大纲依次组织事实速览、必要背景、影响分析和后续观察信号。\n- 正文明确标记哪些是来源事实、哪些是作者判断;不把推测写成事实。\n- 避免标题党、夸大因果和来源没有支持的数字,结尾保留不确定性。",
+ "article": "# 热点解读写作规则\n\n- 选题必须指出已确认的事件、受影响对象和一个值得解释的关键问题。\n- 大纲依次组织事实速览、必要背景、影响分析和后续观察信号。\n- 正文明确标记哪些是来源事实、哪些是作者判断;不把推测写成事实。\n- 避免标题党、夸大因果和来源没有支持的数字,结尾保留不确定性。"
+ }
+ }
+]
diff --git a/packages/writing-templates/src/index.ts b/packages/writing-templates/src/index.ts
new file mode 100644
index 00000000..96d368c8
--- /dev/null
+++ b/packages/writing-templates/src/index.ts
@@ -0,0 +1,2 @@
+export * from './types.js';
+export * from './catalog.js';
diff --git a/packages/writing-templates/src/types.ts b/packages/writing-templates/src/types.ts
new file mode 100644
index 00000000..cc427f2f
--- /dev/null
+++ b/packages/writing-templates/src/types.ts
@@ -0,0 +1,48 @@
+export type WritingTemplateCategoryId = 'analysis' | 'story' | 'practical' | 'news';
+
+export type WritingTemplateDomainId = 'technology' | 'finance' | 'emotion' | 'workplace' | 'education' | 'research' | 'lifestyle';
+
+export type WritingTemplateStatus = 'submitted' | 'verified' | 'featured' | 'deprecated';
+
+export type WritingTemplateStage = 'topics' | 'outline' | 'article' | 'review';
+
+export type WritingTemplateLocale = 'zh-CN' | 'en-US';
+
+export type WritingTemplateLocalization = {
+ name: string;
+ description: string;
+ tags: readonly string[];
+ structure: readonly string[];
+ instructions: string;
+};
+
+export type WritingTemplateSource = {
+ type: 'official' | 'github';
+ repository: string | null;
+ revision: string | null;
+ url: string | null;
+ license: string;
+};
+
+export type WritingTemplateManifest = {
+ schemaVersion: 1;
+ id: string;
+ version: string;
+ name: string;
+ description: string;
+ localizations: Readonly<Record<WritingTemplateLocale, WritingTemplateLocalization>>;
+ categoryId: WritingTemplateCategoryId;
+ domains: readonly WritingTemplateDomainId[];
+ tags: readonly string[];
+ structure: readonly string[];
+ instructions: string;
+ author: string;
+ status: WritingTemplateStatus;
+ sortOrder: number;
+ source: WritingTemplateSource;
+};
+
+export type WritingTemplate = WritingTemplateManifest & {
+ contentHash: string;
+ stagePrompts: Readonly<Partial<Record<WritingTemplateStage, string>>>;
+};
diff --git a/packages/writing-templates/templates/community/khazix-writer/LICENSE b/packages/writing-templates/templates/community/khazix-writer/LICENSE
new file mode 100644
index 00000000..2d848c9f
--- /dev/null
+++ b/packages/writing-templates/templates/community/khazix-writer/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 数字生命卡兹克
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/packages/writing-templates/templates/community/khazix-writer/skill/SKILL.md b/packages/writing-templates/templates/community/khazix-writer/skill/SKILL.md
new file mode 100644
index 00000000..f9ee410a
--- /dev/null
+++ b/packages/writing-templates/templates/community/khazix-writer/skill/SKILL.md
@@ -0,0 +1,74 @@
+# 卡兹克公众号长文写作
+
+本模板接入自 `KKKKhazix/khazix-skills` 中的 `khazix-writer`。它提取原 Skill 的写作方法用于文章生成,不代表原作者本人发言,也不允许冒充「数字生命卡兹克」或自动添加原账号署名、联系方式和固定推广尾部。
+
+## 核心底色
+
+- 对新事物保持真实好奇,从「这件事哪里有意思」出发,而不是从宏大结论出发。
+- 讲人话,允许明确表达判断和不确定性,避免滴水不漏但没有温度的报告腔。
+- 真诚优先。产品有缺点就写缺点,不懂就承认不懂,不用不存在的细节增强戏剧性。
+- 观点必须是作者真的相信并愿意表达的,不能为了流量强行制造立场。
+
+## 素材边界
+
+先区分来源事实、用户提供的第一手经历、可验证的背景知识和写作者判断。第一手观察、真实经历、情绪节点和核心创意只能来自用户或内容来源。不得替用户编造试用过程、人物对话、精确数字、现场反应或私人关系。
+
+当素材不足时,保留信息缺口,用诚实的限定语表达,或者调整成不依赖虚构经历的观察视角。
+
+## 文章原型
+
+- 调查实验型:围绕「我替读者实际验证了一件事」展开,重点是过程、意外和发现的递进。只有材料明确提供真实实验时才能使用第一人称。
+- 产品体验型:带读者进入真实使用场景,展示操作、结果、感受和限制。
+- 现象解读型:按观察、好奇、研究、判断的路径推进,从表面现象逐层追问。
+- 工具分享型:用一个真实问题引出工具,用具体案例证明价值,同时交代限制和成本。
+- 方法论分享型:每一部分都给出可执行动作,并坦诚说明学习曲线、失败点和适用边界。
+
+## 开头
+
+从内容来源中真实存在的当下事件、具体场景、反常事实或问题切入。前三段就让读者知道发生了什么,以及为什么值得继续看。禁止使用「在当今快速发展的时代」「随着技术不断进步」等教科书式空话。
+
+开头可以直接启动叙事,也可以抛出一个来源支持的荒诞事实、热点变化或好奇心。不要在开头先解释全文结构。
+
+## 推进与节奏
+
+文章像和朋友认真聊天,而不是提交报告。句子长短交替,段落保持轻盈,关键判断可以独立成段。每次展开背景、案例或类比之后,用一句简短的话扣回主线,避免读者为了理解结构而回头。
+
+一个内容板块通常包含:明确观点、具体事实或案例、与读者处境的连接,以及扣回主线的转场。知识要像聊天过程中自然拿出来的补充,不使用「下面科普一下」式的讲义口吻。
+
+涉及多个产品、模型或案例时,逐一展示,不要一次罗列所有结论。顺序从基础发现推进到最有反差的结果,让每一轮比上一轮更深入或更意外。
+
+## 判断与同理心
+
+可以有明确好恶,但不要居高临下。讨论争议观点时,先把另一方的真实处境具体化,承认其合理部分,再给出自己的不同判断。
+
+需要从具体事件连接到文化、历史或哲学背景时,连接必须服务于当前问题,并且由来源或可靠知识支持。不要为了显得深刻强行升华。
+
+## 真实感
+
+优先使用具体产品名、动作、限制、结果和环境细节,避免「某个模型」「相关技术」「非常震撼」等空泛表达。情绪要落在可观察的反应上,但这些反应必须来自真实材料。
+
+可以使用自然口语和少量不完整句制造呼吸感,但不能机械堆砌口头禅、粗口、夸张标点或模板作者的个人习惯。目标是吸收节奏方法,不是复刻某个人的身份特征。
+
+## 结构
+
+典型长文可以采用以下推进关系:
+
+1. 用具体事件或场景快速建立好奇心。
+2. 用聊天式背景补齐非专业读者需要的信息。
+3. 围绕核心判断展开若干板块,每个板块都有事实或案例支撑。
+4. 在必要时连接更大的文化、历史或行业背景。
+5. 回到开头的意象、问题或判断,以回环、余韵或明确行动收尾。
+
+除非文章本身是「N 条方法」等条目型内容,否则不要滥用 Markdown 小标题和列表。优先用自然转场形成连续阅读体验。不要自动添加上游 Skill 中属于原作者账号的固定署名、邮箱或关注引导。
+
+## 语言禁区
+
+- 不使用「首先、其次、最后」「综上所述」「值得注意的是」「不难发现」「让我们来看看」等套话组织文章。
+- 不堆砌加粗、项目符号和形式整齐但内容空泛的排比。
+- 不用假设性第一人称故事替代真实案例。
+- 不把所有观点包装成绝对结论,保留来源和认知边界。
+- 不为了模仿风格而强制使用粗口、特殊标点或原作者口癖。
+
+## 收尾
+
+从文章已经建立的内容自然收束。可以回到开头的物件或问题,可以留下简短判断,也可以给出读者今天能做的一件事。避免总结全文、重复观点和强行拔高。
diff --git a/packages/writing-templates/templates/community/khazix-writer/skill/review.md b/packages/writing-templates/templates/community/khazix-writer/skill/review.md
new file mode 100644
index 00000000..89233325
--- /dev/null
+++ b/packages/writing-templates/templates/community/khazix-writer/skill/review.md
@@ -0,0 +1,31 @@
+# 卡兹克公众号长文写作:四层质检
+
+成稿后按四层顺序检查并直接修复问题。质检服务于文章质量,不要求在最终文章正文中附带报告。
+
+## L1 硬性规则
+
+- 清除「首先、其次、最后」「综上所述」「值得注意的是」「不难发现」「让我们来看看」等报告腔套话。
+- 检查是否存在大段加粗、连续列表、教科书式开头和空泛工具名。
+- 删除来源不支持的经历、对话、数字、情绪反应和假设性第一人称案例。
+- 确认没有原作者署名、联系方式、账号推广或冒充作者身份的表述。
+
+## L2 风格一致性
+
+- 开头是否来自具体事件、场景、反常事实或真实问题。
+- 长短句、短段落和关键独立句是否形成自然节奏,而不是整齐划一。
+- 展开的背景或案例后是否及时扣回主线。
+- 口语表达是否自然,是否避免机械堆砌口头禅和夸张标点。
+
+## L3 内容质量
+
+- 每个核心观点是否都有来源事实、具体案例或可靠知识支撑。
+- 知识是否自然融入叙述,而不是突然切换成讲义。
+- 对立观点是否得到公平解释,判断是否建立在理解对方处境之后。
+- 调查、体验、解读、工具分享或方法论等文章原型是否采用了对应的推进方式。
+- 多个案例是否逐一展开,并形成由浅入深的发现过程。
+
+## L4 真实感终审
+
+通读全文,判断它像一个有见识的普通人在认真聊一件打动他的事,还是像模型在整理信息。重点检查情绪是否来自材料、细节是否可信、观点是否有作者自己的判断,以及阅读心流是否在某处中断。
+
+如果风格技巧比内容本身更醒目,主动降低模仿痕迹,让文章回到事实、观点和读者体验。
diff --git a/packages/writing-templates/templates/community/khazix-writer/skill/topics.md b/packages/writing-templates/templates/community/khazix-writer/skill/topics.md
new file mode 100644
index 00000000..58f7a3f8
--- /dev/null
+++ b/packages/writing-templates/templates/community/khazix-writer/skill/topics.md
@@ -0,0 +1,19 @@
+# 卡兹克公众号长文写作:选题判断
+
+先吃透内容来源和用户的写作要求,再生成选题。不得用想象补齐来源中不存在的事实、经历、数据或引语。
+
+## HKR 质检
+
+每个候选选题至少满足下面两项,并在角度或摘要中体现其优势:
+
+- Happy:有趣、有反差或有悬念,让读者产生继续了解的好奇心。
+- Knowledge:包含新信息、新方法或能够改变理解的背景知识。
+- Resonance:能连接目标读者真实面对的处境、情绪或争议。
+
+优先提出同时满足三项的选题。多个候选之间要有明显差异,不要只替换标题措辞。
+
+## 文章原型
+
+根据材料选择最合适的原型:调查实验型、产品体验型、现象解读型、工具分享型、方法论分享型。选题必须说明文章从什么具体事件、场景、问题或体验切入,以及核心判断是什么。
+
+如果材料不足以支撑第一人称经历,改用观察者或分析者视角,不得冒充模板作者,也不得虚构作者已经亲自做过某件事。
diff --git a/packages/writing-templates/templates/community/khazix-writer/template.json b/packages/writing-templates/templates/community/khazix-writer/template.json
new file mode 100644
index 00000000..b21da3b4
--- /dev/null
+++ b/packages/writing-templates/templates/community/khazix-writer/template.json
@@ -0,0 +1,46 @@
+{
+ "schemaVersion": 1,
+ "id": "community.khazix-writer",
+ "version": "1.0.0",
+ "name": "卡兹克公众号长文写作",
+ "description": "用聊天感、真实体验和层层推进写出有判断力的公众号长文",
+ "localizations": {
+ "zh-CN": {
+ "name": "卡兹克公众号长文写作",
+ "description": "用聊天感、真实体验和层层推进写出有判断力的公众号长文",
+ "tags": ["公众号长文", "口语节奏", "真实体验", "观点叙事"],
+ "structure": ["具体事件开场", "聊天式背景铺垫", "观点与案例推进", "回环或余韵收尾"],
+ "instructions": "从来源支持的具体事件、体验或好奇心切入,以口语化节奏推进观点,用真实案例、明确判断和自然转场维持阅读心流。只使用用户与来源提供的第一手经历,不冒充原作者,不编造个人体验。"
+ },
+ "en-US": {
+ "name": "Khazix Long-form WeChat Writing",
+ "description": "Conversational long-form writing built on real experience and progressive argument",
+ "tags": ["Long-form article", "Conversational rhythm", "Real experience", "Opinion narrative"],
+ "structure": ["Concrete event opening", "Conversational context", "Ideas and examples", "Callback or resonant close"],
+ "instructions": "Begin with a source-supported event, experience, or genuine question. Develop the argument in a conversational rhythm, using real examples, clear judgments, and natural transitions to sustain reading flow. Use first-hand experience only when supplied by the user or sources; do not impersonate the original author or invent personal experience."
+ }
+ },
+ "categoryId": "story",
+ "domains": ["technology", "workplace"],
+ "tags": ["公众号长文", "口语节奏", "真实体验", "观点叙事"],
+ "structure": ["具体事件开场", "聊天式背景铺垫", "观点与案例推进", "回环或余韵收尾"],
+ "instructions": "从来源支持的具体事件、体验或好奇心切入,以口语化节奏推进观点,用真实案例、明确判断和自然转场维持阅读心流。只使用用户与来源提供的第一手经历,不冒充原作者,不编造个人体验。",
+ "author": "数字生命卡兹克",
+ "status": "featured",
+ "sortOrder": 110,
+ "source": {
+ "type": "github",
+ "repository": "KKKKhazix/khazix-skills",
+ "revision": "7a5c4934be4106ac740ffdb95280bb81b3f4b83c",
+ "url": "https://github.com/KKKKhazix/khazix-skills/blob/main/khazix-writer/SKILL.md",
+ "license": "MIT"
+ },
+ "skill": {
+ "stageResources": {
+ "topics": ["skill/topics.md"],
+ "outline": ["skill/SKILL.md"],
+ "article": ["skill/SKILL.md", "skill/review.md"],
+ "review": ["skill/review.md"]
+ }
+ }
+}
diff --git a/packages/writing-templates/templates/community/research-paper-writing/LICENSE b/packages/writing-templates/templates/community/research-paper-writing/LICENSE
new file mode 100644
index 00000000..5712ae3a
--- /dev/null
+++ b/packages/writing-templates/templates/community/research-paper-writing/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Master-cai
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/packages/writing-templates/templates/community/research-paper-writing/NOTICE b/packages/writing-templates/templates/community/research-paper-writing/NOTICE
new file mode 100644
index 00000000..c4053d66
--- /dev/null
+++ b/packages/writing-templates/templates/community/research-paper-writing/NOTICE
@@ -0,0 +1,13 @@
+This writing template is adapted from Research Paper Writing by Master-cai:
+https://github.com/Master-cai/Research-Paper-Writing-Skills
+
+Upstream revision:
+77e7c2c1ba06f7d71844873147665437a03aac1b
+
+The upstream repository states that most writing knowledge and methodology
+comes from Prof. Peng Sida's public study notes and learning_research project:
+https://pengsida.notion.site/c1a22465a0fa4b15a12985223916048e
+https://github.com/pengsida/learning_research
+
+OpenCreator adapted the upstream material to its topics, outline, article, and
+review stages. The original MIT license is preserved in LICENSE.
diff --git a/packages/writing-templates/templates/community/research-paper-writing/skill/SKILL.md b/packages/writing-templates/templates/community/research-paper-writing/skill/SKILL.md
new file mode 100644
index 00000000..55b35e59
--- /dev/null
+++ b/packages/writing-templates/templates/community/research-paper-writing/skill/SKILL.md
@@ -0,0 +1,39 @@
+# Research Paper Writing
+
+本模板接入自 `Master-cai/Research-Paper-Writing-Skills`,用于提升科研论文和学术内容的章节结构、段落流畅性、论点证据对齐及审稿人可读性。上游说明其大部分写作知识与方法来自彭思达教授公开的学习笔记和 `pengsida/learning_research`;本模板保留该归属,并将方法适配到 OpenCreator 的写作流程。
+
+## 核心工作流
+
+1. 在润色句子前先明确完整的研究故事:任务、技术问题、贡献、为什么有效,以及需要哪些证据。
+2. 为文章建立紧凑提纲,确保每一节都服务于主问题,每一段只传递一个信息。
+3. 每段首句说明该段作用,后续句子通过因果、对比、结果、细化或例子自然衔接。
+4. 新术语先定义再复用,全文保持术语、符号和概念边界一致。
+5. 摘要和引言中的每个重要主张都必须对应实验、数据或来源证据;没有证据时减弱或删除主张。
+6. 完成章节后执行反向提纲,再以怀疑性的审稿人视角做终审。
+
+## 提纲组织
+
+根据写作目标选择需要的章节,不为凑结构强行加入无关部分。
+
+- 摘要:任务,技术挑战,洞见或贡献,贡献带来的优势,实验结果。
+- 引言:任务与应用,已有方法及其真正局限,本文方案与为什么有效,贡献,实验概览。
+- 相关工作:按技术主题分组,概括共同范式,指出与目标问题相关的局限,并说明本文差异。
+- 方法:先给设置和总体方案;每个模块按动机、设计或执行过程、技术优势展开。
+- 实验:用强基线证明效果,用消融验证关键设计,用困难或分布外场景说明泛化和边界。
+- 结论:重述问题与核心洞见,总结最强证据,坦诚说明适用边界,并给出具体未来方向。
+
+## 段落与论证
+
+每段只承担一种角色,例如定义任务、提出挑战、解释技术原因、描述方法、陈述优势、提供证据或说明局限。段首句应让外部读者立刻理解该段要做什么。
+
+写完后做反向提纲:列出全文主张、各段主题句和各段证据,逐项检查“主题句是否支持主张、证据是否支持主题句”。不能清晰对应的段落应修改、移动或删除。
+
+不要把工作写成“先提出一个幼稚方案,再打补丁”的增量叙事,也不要只堆抽象洞见而隐藏实际方法。清楚说明真正的技术挑战、技术原因、解决机制和可验证优势。
+
+## 来源与真实性
+
+只能使用用户或内容来源中存在的论文、数据、实验、基线、指标、引语和结论。无法验证的信息必须标记为待补充,不得自动编造引用或数值。区分事实、作者主张、实验观察和写作者推断。
+
+## 输出要求
+
+成稿应具有清晰章节和稳定术语。对主要论点,在写作过程中维护“论点、证据、状态”的对应关系;证据不足的状态只能是“需要证据”,不能用更强措辞掩盖缺口。最终正文不必附带内部检查过程,除非用户明确要求。
diff --git a/packages/writing-templates/templates/community/research-paper-writing/skill/review.md b/packages/writing-templates/templates/community/research-paper-writing/skill/review.md
new file mode 100644
index 00000000..b6530f88
--- /dev/null
+++ b/packages/writing-templates/templates/community/research-paper-writing/skill/review.md
@@ -0,0 +1,24 @@
+# Research Paper Writing:投稿前审稿式检查
+
+成稿后以怀疑性的审稿人视角逐项检查并直接修订。检查过程服务于正文质量,默认不作为正文附录输出。
+
+## 硬性约束
+
+- 摘要和引言中的每个重要主张是否技术上正确,并由正文中的实验、数据或来源证据明确支持。
+- 是否存在虚构引用、数据集、基线、指标、实验结果、实现细节或研究贡献。
+- 关键术语、符号、任务边界和结论强度是否前后一致。
+- 每段是否只有一个中心信息,首句能否说明该段作用,句间关系是否清楚。
+
+## 五个审稿维度
+
+1. 贡献:读者能获得什么新知识;创新属于新任务、流程、模块、设计发现还是洞见;是否超出显而易见的增量改动。
+2. 表达:方法是否足够清楚可复现;每个模块是否有明确动机;术语和段落逻辑是否稳定。
+3. 实验强度:是否与近期强基线公平比较;提升是否有意义;是否同时说明优势、失败案例和限制。
+4. 评估完整性:关键设计是否有消融;指标和数据集是否足够;所有主要主张是否有对应验证。
+5. 方法合理性:设置是否现实;假设是否合理;是否需要逐场景调参;新增复杂度和局限是否超过收益。
+
+## 反向提纲与论点证据表
+
+列出主张、各段主题句和证据,检查每一层是否能够向上支撑。为每个主要主张记录:`论点:... | 证据:... | 状态:已支持/需要证据`。状态为“需要证据”时,只能补充证据、减弱结论或删除主张。
+
+重复审阅和修订,直到不存在未处理的高风险拒稿理由。
diff --git a/packages/writing-templates/templates/community/research-paper-writing/skill/topics.md b/packages/writing-templates/templates/community/research-paper-writing/skill/topics.md
new file mode 100644
index 00000000..5f827942
--- /dev/null
+++ b/packages/writing-templates/templates/community/research-paper-writing/skill/topics.md
@@ -0,0 +1,13 @@
+# Research Paper Writing:科研选题判断
+
+先读取内容来源、研究材料和用户要求,再提出候选选题。选题必须由已有材料支撑,不得虚构实验结果、数据集、基线、引用或研究贡献。
+
+## 候选选题要求
+
+- 明确研究任务、具体技术问题和目标读者,不使用只有领域名的宽泛题目。
+- 说明现有方法的关键局限及其技术原因,且该局限应当正是文章准备讨论或解决的问题。
+- 指出可被材料支持的核心贡献、新见解或实证发现。
+- 给出选题所需的证据基础,例如对比实验、消融实验、案例、论文引用或来源事实。
+- 多个候选应当在研究问题、论证角度或目标章节上真正不同,不只是改写标题。
+
+若材料不足以支持强结论,应缩小范围,改成问题梳理、方法比较、研究综述或待验证假设,并明确证据缺口。
diff --git a/packages/writing-templates/templates/community/research-paper-writing/template.json b/packages/writing-templates/templates/community/research-paper-writing/template.json
new file mode 100644
index 00000000..0792ce68
--- /dev/null
+++ b/packages/writing-templates/templates/community/research-paper-writing/template.json
@@ -0,0 +1,46 @@
+{
+ "schemaVersion": 1,
+ "id": "community.research-paper-writing",
+ "version": "1.0.0",
+ "name": "Research Paper Writing",
+ "description": "用清晰章节、严密论证和审稿人视角组织科研论文与学术内容",
+ "localizations": {
+ "zh-CN": {
+ "name": "科研论文写作",
+ "description": "用清晰章节、严密论证和审稿人视角组织科研论文与学术内容",
+ "tags": ["学术论文", "章节结构", "论点证据", "投稿自审"],
+ "structure": ["研究任务与问题", "相关工作与技术挑战", "方法与核心贡献", "实验与证据", "结论、局限与未来方向"],
+ "instructions": "先明确研究故事、技术问题和核心贡献,再按章节组织论证。每段只传递一个信息,首句说明段落作用,术语前后一致;摘要和引言中的重要主张必须由实验或来源证据支持。成稿后使用审稿人视角检查贡献、表达、实验、评估完整性和方法合理性。"
+ },
+ "en-US": {
+ "name": "Research Paper Writing",
+ "description": "Structure research papers with clear sections, rigorous arguments, and a reviewer's perspective",
+ "tags": ["Academic paper", "Section structure", "Claim and evidence", "Pre-submission review"],
+ "structure": ["Research task and problem", "Related work and challenge", "Method and contribution", "Experiments and evidence", "Conclusion, limits, and future work"],
+ "instructions": "Clarify the research story, technical problem, and core contribution before organizing the argument by section. Give each paragraph one message, state its role in the opening sentence, and keep terminology consistent. Every major claim in the abstract and introduction must be supported by experiments or source evidence. Review the draft for contribution, clarity, experimental strength, evaluation completeness, and method soundness."
+ }
+ },
+ "categoryId": "analysis",
+ "domains": ["research"],
+ "tags": ["学术论文", "章节结构", "论点证据", "投稿自审"],
+ "structure": ["研究任务与问题", "相关工作与技术挑战", "方法与核心贡献", "实验与证据", "结论、局限与未来方向"],
+ "instructions": "先明确研究故事、技术问题和核心贡献,再按章节组织论证。每段只传递一个信息,首句说明段落作用,术语前后一致;摘要和引言中的重要主张必须由实验或来源证据支持。成稿后使用审稿人视角检查贡献、表达、实验、评估完整性和方法合理性。",
+ "author": "Master-cai / OpenCreator adapted",
+ "status": "featured",
+ "sortOrder": 120,
+ "source": {
+ "type": "github",
+ "repository": "Master-cai/Research-Paper-Writing-Skills",
+ "revision": "77e7c2c1ba06f7d71844873147665437a03aac1b",
+ "url": "https://github.com/Master-cai/Research-Paper-Writing-Skills",
+ "license": "MIT"
+ },
+ "skill": {
+ "stageResources": {
+ "topics": ["skill/topics.md"],
+ "outline": ["skill/SKILL.md"],
+ "article": ["skill/SKILL.md", "skill/review.md"],
+ "review": ["skill/review.md"]
+ }
+ }
+}
diff --git a/packages/writing-templates/templates/community/sun-style-writing/LICENSE b/packages/writing-templates/templates/community/sun-style-writing/LICENSE
new file mode 100644
index 00000000..2d848c9f
--- /dev/null
+++ b/packages/writing-templates/templates/community/sun-style-writing/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 数字生命卡兹克
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/packages/writing-templates/templates/community/sun-style-writing/skill/SKILL.md b/packages/writing-templates/templates/community/sun-style-writing/skill/SKILL.md
new file mode 100644
index 00000000..faa64ab2
--- /dev/null
+++ b/packages/writing-templates/templates/community/sun-style-writing/skill/SKILL.md
@@ -0,0 +1,19 @@
+# 孙学写作法
+
+这是一套来自 `KKKKhazix/sun-style-writing`、经 OpenCreator 接入的非虚构叙事规则。使用写作技法本身,不要求复刻任何现实人物的独特口吻。
+
+## 核心原则
+
+- 只写来源能够支持的动作、对话、物件、数字和环境细节,少解释人物心理。
+- 用具体数字替代模糊形容词,但真实性优先;材料不精确时不得制造假精确。
+- 段落和对话可以短,但一个关键场景要充分展开,形成进入、细节、变化和离开的过程。
+- 从材料中选择一个普通物件、动作或声音作为线索,让它在后文自然回来,不解释其象征意义。
+- 关键转折可以由沉默、称谓变化、动作变化或重复句式的中断承担。
+
+## 大纲方式
+
+开篇三句话内建立材料中真实存在的反差、悬念或关系变化。随后用时间、地点、人物或物件作为锚点推进场景。只在重大阶段转换时使用分隔,不把叙事切成大量碎片。结尾回到开篇出现过的动作、物件或问题,让语境变化产生回响,避免总结式升华。
+
+## 语言边界
+
+保持平静陈述,减少成语堆叠、感叹号、直接情绪标签和排比抒情。能够用动作呈现时不解释心理,能够用物件呈现时不总结感情。所有细节都必须服从来源和用户提供的事实边界。
diff --git a/packages/writing-templates/templates/community/sun-style-writing/skill/review.md b/packages/writing-templates/templates/community/sun-style-writing/skill/review.md
new file mode 100644
index 00000000..7b7ed4eb
--- /dev/null
+++ b/packages/writing-templates/templates/community/sun-style-writing/skill/review.md
@@ -0,0 +1,8 @@
+# 成稿检查
+
+- 开头是否快速建立了来源真实支持的反差或悬念。
+- 是否删除了无依据的心理描写、精确数字和场景细节。
+- 关键场景是否足够完整,而不是只展示几个技巧就跳走。
+- 重复出现的物件、动作或句式是否自然,并在后文产生新的意义。
+- 结尾是否停留在具体画面或动作上,避免口号、总结和强行升华。
+- 技法是否服务于人物和事实;如果技巧比内容更醒目,应主动削弱。
diff --git a/packages/writing-templates/templates/community/sun-style-writing/skill/topics.md b/packages/writing-templates/templates/community/sun-style-writing/skill/topics.md
new file mode 100644
index 00000000..a2a54533
--- /dev/null
+++ b/packages/writing-templates/templates/community/sun-style-writing/skill/topics.md
@@ -0,0 +1,3 @@
+# 选题规则
+
+优先寻找来源中有明确人物、关系、时间跨度、具体物件或行动冲突的方向。选题应能够由真实场景展开,并具备反差或悬念。不要为追求文学感补造材料中不存在的经历、数字和细节。
diff --git a/packages/writing-templates/templates/community/sun-style-writing/template.json b/packages/writing-templates/templates/community/sun-style-writing/template.json
new file mode 100644
index 00000000..b3c9c081
--- /dev/null
+++ b/packages/writing-templates/templates/community/sun-style-writing/template.json
@@ -0,0 +1,46 @@
+{
+ "schemaVersion": 1,
+ "id": "community.sun-style-writing",
+ "version": "1.0.0",
+ "name": "孙割写作.skill",
+ "description": "用短句、物件、数字和留白承载情绪的非虚构叙事",
+ "localizations": {
+ "zh-CN": {
+ "name": "孙割写作.skill",
+ "description": "用短句、物件、数字和留白承载情绪的非虚构叙事",
+ "tags": ["白描", "短句节奏", "物件叙事", "非虚构"],
+ "structure": ["反差或悬念开场", "场景与时间锚点", "关系或冲突推进", "物件回响"],
+ "instructions": "以可观察的动作、物件和真实数字推进叙事,减少直接心理解释。保持短句节奏,让关键场景充分展开,并用来源中真实存在的细节形成照应。"
+ },
+ "en-US": {
+ "name": "Sun-style Writing Skill",
+ "description": "Nonfiction storytelling shaped by short sentences, objects, numbers, and restraint",
+ "tags": ["Plain description", "Short-sentence rhythm", "Object narrative", "Nonfiction"],
+ "structure": ["Contrast or suspense", "Scene and time anchor", "Relationship or conflict", "Object callback"],
+ "instructions": "Move the narrative through observable actions, concrete objects, and real numbers while limiting direct explanations of inner states. Maintain a short-sentence rhythm, give key scenes room to unfold, and create callbacks with details that genuinely exist in the sources."
+ }
+ },
+ "categoryId": "story",
+ "domains": ["emotion", "lifestyle"],
+ "tags": ["白描", "短句节奏", "物件叙事", "非虚构"],
+ "structure": ["反差或悬念开场", "场景与时间锚点", "关系或冲突推进", "物件回响"],
+ "instructions": "以可观察的动作、物件和真实数字推进叙事,减少直接心理解释。保持短句节奏,让关键场景充分展开,并用来源中真实存在的细节形成照应。",
+ "author": "数字生命卡兹克 / OpenCreator adapted",
+ "status": "featured",
+ "sortOrder": 100,
+ "source": {
+ "type": "github",
+ "repository": "KKKKhazix/sun-style-writing",
+ "revision": "fe970dc15113ea0c3807f19f1d3118f63f9d9079",
+ "url": "https://github.com/KKKKhazix/sun-style-writing",
+ "license": "MIT"
+ },
+ "skill": {
+ "stageResources": {
+ "topics": ["skill/topics.md"],
+ "outline": ["skill/SKILL.md"],
+ "article": ["skill/SKILL.md", "skill/review.md"],
+ "review": ["skill/review.md"]
+ }
+ }
+}
diff --git a/packages/writing-templates/templates/official/insight/skill/SKILL.md b/packages/writing-templates/templates/official/insight/skill/SKILL.md
new file mode 100644
index 00000000..c38a92f0
--- /dev/null
+++ b/packages/writing-templates/templates/official/insight/skill/SKILL.md
@@ -0,0 +1,6 @@
+# 深度洞察写作规则
+
+- 选题必须包含可验证的问题、明确受众和有信息增量的判断,避免空泛的大词。
+- 大纲先给核心结论,再用事实、数据、案例或来源中的对比逐层论证。
+- 正文区分来源事实与作者判断。二到四个主体章节即可,每个章节回答一个具体问题。
+- 结尾给出可执行建议或后续观察信号,不重复全文摘要。
diff --git a/packages/writing-templates/templates/official/insight/template.json b/packages/writing-templates/templates/official/insight/template.json
new file mode 100644
index 00000000..826bf694
--- /dev/null
+++ b/packages/writing-templates/templates/official/insight/template.json
@@ -0,0 +1,39 @@
+{
+ "schemaVersion": 1,
+ "id": "insight",
+ "version": "1.0.0",
+ "name": "深度洞察",
+ "description": "观点鲜明,适合行业观察与趋势分析",
+ "localizations": {
+ "zh-CN": {
+ "name": "深度洞察",
+ "description": "观点鲜明,适合行业观察与趋势分析",
+ "tags": ["观点先行", "行业观察", "层层论证"],
+ "structure": ["核心判断", "背景与问题", "分层论证", "行动建议"],
+ "instructions": "以清晰的问题意识开篇,先给结论再展开论证。使用二到四个层次分明的小标题,结合来源中的事实、数据和案例,避免空泛判断。结尾给出可执行的观察或建议。"
+ },
+ "en-US": {
+ "name": "Deep Insight",
+ "description": "Clear points of view for industry observations and trend analysis",
+ "tags": ["Thesis first", "Industry insight", "Layered argument"],
+ "structure": ["Core judgment", "Context and problem", "Layered argument", "Actionable advice"],
+ "instructions": "Open with a clearly defined problem and state the conclusion before developing the argument. Use two to four well-structured section headings, grounding each point in facts, data, and examples from the sources. Avoid vague claims and close with actionable observations or recommendations."
+ }
+ },
+ "categoryId": "analysis",
+ "domains": ["technology", "finance", "workplace"],
+ "tags": ["观点先行", "行业观察", "层层论证"],
+ "structure": ["核心判断", "背景与问题", "分层论证", "行动建议"],
+ "instructions": "以清晰的问题意识开篇,先给结论再展开论证。使用二到四个层次分明的小标题,结合来源中的事实、数据和案例,避免空泛判断。结尾给出可执行的观察或建议。",
+ "author": "OpenCreator",
+ "status": "verified",
+ "sortOrder": 10,
+ "source": { "type": "official", "license": "OpenCreator project" },
+ "skill": {
+ "stageResources": {
+ "topics": ["skill/SKILL.md"],
+ "outline": ["skill/SKILL.md"],
+ "article": ["skill/SKILL.md"]
+ }
+ }
+}
diff --git a/packages/writing-templates/templates/official/news-analysis/skill/SKILL.md b/packages/writing-templates/templates/official/news-analysis/skill/SKILL.md
new file mode 100644
index 00000000..4125840a
--- /dev/null
+++ b/packages/writing-templates/templates/official/news-analysis/skill/SKILL.md
@@ -0,0 +1,6 @@
+# 热点解读写作规则
+
+- 选题必须指出已确认的事件、受影响对象和一个值得解释的关键问题。
+- 大纲依次组织事实速览、必要背景、影响分析和后续观察信号。
+- 正文明确标记哪些是来源事实、哪些是作者判断;不把推测写成事实。
+- 避免标题党、夸大因果和来源没有支持的数字,结尾保留不确定性。
diff --git a/packages/writing-templates/templates/official/news-analysis/template.json b/packages/writing-templates/templates/official/news-analysis/template.json
new file mode 100644
index 00000000..f5f3827c
--- /dev/null
+++ b/packages/writing-templates/templates/official/news-analysis/template.json
@@ -0,0 +1,39 @@
+{
+ "schemaVersion": 1,
+ "id": "news-analysis",
+ "version": "1.0.0",
+ "name": "热点解读",
+ "description": "快速交代事件,再解释影响与判断",
+ "localizations": {
+ "zh-CN": {
+ "name": "热点解读",
+ "description": "快速交代事件,再解释影响与判断",
+ "tags": ["事实速览", "影响分析", "趋势判断"],
+ "structure": ["事件概况", "重要背景", "影响对象", "后续信号"],
+ "instructions": "开头用最少篇幅交代发生了什么,随后回答为什么重要、影响谁、接下来关注什么。区分来源事实与作者判断,不夸大结论,不制造未经来源支持的数据。"
+ },
+ "en-US": {
+ "name": "News Analysis",
+ "description": "Explain what happened, then assess its impact and significance",
+ "tags": ["Fact summary", "Impact analysis", "Trend outlook"],
+ "structure": ["What happened", "Essential context", "Who is affected", "Signals to watch"],
+ "instructions": "Use as little space as possible to establish what happened, then explain why it matters, who it affects, and what to watch next. Clearly separate sourced facts from the author's judgment, avoid overstating conclusions, and never invent unsupported data."
+ }
+ },
+ "categoryId": "news",
+ "domains": ["technology", "finance"],
+ "tags": ["事实速览", "影响分析", "趋势判断"],
+ "structure": ["事件概况", "重要背景", "影响对象", "后续信号"],
+ "instructions": "开头用最少篇幅交代发生了什么,随后回答为什么重要、影响谁、接下来关注什么。区分来源事实与作者判断,不夸大结论,不制造未经来源支持的数据。",
+ "author": "OpenCreator",
+ "status": "verified",
+ "sortOrder": 40,
+ "source": { "type": "official", "license": "OpenCreator project" },
+ "skill": {
+ "stageResources": {
+ "topics": ["skill/SKILL.md"],
+ "outline": ["skill/SKILL.md"],
+ "article": ["skill/SKILL.md"]
+ }
+ }
+}
diff --git a/packages/writing-templates/templates/official/story/skill/SKILL.md b/packages/writing-templates/templates/official/story/skill/SKILL.md
new file mode 100644
index 00000000..39725856
--- /dev/null
+++ b/packages/writing-templates/templates/official/story/skill/SKILL.md
@@ -0,0 +1,6 @@
+# 故事叙事写作规则
+
+- 选题从一个有行动、关系或冲突的人物切入,而不是先讲抽象道理。
+- 大纲按场景推进组织,每个场景都必须推动人物、冲突或核心观点发生变化。
+- 正文使用具体动作、对话和环境细节,保持段落节奏;没有来源支持的细节不得补写。
+- 结尾回扣开篇的场景、动作或问题,避免直接喊口号和强行升华。
diff --git a/packages/writing-templates/templates/official/story/template.json b/packages/writing-templates/templates/official/story/template.json
new file mode 100644
index 00000000..d0192e5c
--- /dev/null
+++ b/packages/writing-templates/templates/official/story/template.json
@@ -0,0 +1,39 @@
+{
+ "schemaVersion": 1,
+ "id": "story",
+ "version": "1.0.0",
+ "name": "故事叙事",
+ "description": "从人物或场景切入,强调阅读节奏",
+ "localizations": {
+ "zh-CN": {
+ "name": "故事叙事",
+ "description": "从人物或场景切入,强调阅读节奏",
+ "tags": ["场景开篇", "人物叙事", "情绪节奏"],
+ "structure": ["人物或场景", "矛盾推进", "关键转折", "主题回扣"],
+ "instructions": "用具体人物、场景或冲突开篇,按故事推进承载核心观点。段落短而有节奏,关键转折处设置小标题,避免编造来源中不存在的细节。结尾回扣开头并留下余味。"
+ },
+ "en-US": {
+ "name": "Narrative Storytelling",
+ "description": "Lead with a person or scene and build a strong reading rhythm",
+ "tags": ["Scene opening", "Character story", "Emotional rhythm"],
+ "structure": ["Person or scene", "Rising conflict", "Key turn", "Thematic callback"],
+ "instructions": "Open with a specific person, scene, or conflict, then carry the central idea through the story's progression. Keep paragraphs concise and rhythmic, use headings at meaningful turns, and never invent details absent from the sources. Close by returning to the opening and leave the reader with a lingering thought."
+ }
+ },
+ "categoryId": "story",
+ "domains": ["emotion", "lifestyle"],
+ "tags": ["场景开篇", "人物叙事", "情绪节奏"],
+ "structure": ["人物或场景", "矛盾推进", "关键转折", "主题回扣"],
+ "instructions": "用具体人物、场景或冲突开篇,按故事推进承载核心观点。段落短而有节奏,关键转折处设置小标题,避免编造来源中不存在的细节。结尾回扣开头并留下余味。",
+ "author": "OpenCreator",
+ "status": "verified",
+ "sortOrder": 20,
+ "source": { "type": "official", "license": "OpenCreator project" },
+ "skill": {
+ "stageResources": {
+ "topics": ["skill/SKILL.md"],
+ "outline": ["skill/SKILL.md"],
+ "article": ["skill/SKILL.md"]
+ }
+ }
+}
diff --git a/packages/writing-templates/templates/official/tutorial/skill/SKILL.md b/packages/writing-templates/templates/official/tutorial/skill/SKILL.md
new file mode 100644
index 00000000..3dda8e62
--- /dev/null
+++ b/packages/writing-templates/templates/official/tutorial/skill/SKILL.md
@@ -0,0 +1,6 @@
+# 实用教程写作规则
+
+- 选题写清目标读者要解决的问题、完成后的具体结果和适用边界。
+- 大纲按执行顺序排列步骤,每一步都说明目的、动作、输入输出和常见风险。
+- 正文优先使用清单、表格、示例和验证方式;命令、版本、数据不得脱离来源臆造。
+- 结尾给出能够逐项核对的完成检查,而不是泛泛总结。
diff --git a/packages/writing-templates/templates/official/tutorial/template.json b/packages/writing-templates/templates/official/tutorial/template.json
new file mode 100644
index 00000000..8c90a688
--- /dev/null
+++ b/packages/writing-templates/templates/official/tutorial/template.json
@@ -0,0 +1,39 @@
+{
+ "schemaVersion": 1,
+ "id": "tutorial",
+ "version": "1.0.0",
+ "name": "实用教程",
+ "description": "步骤清楚,适合方法论与操作指南",
+ "localizations": {
+ "zh-CN": {
+ "name": "实用教程",
+ "description": "步骤清楚,适合方法论与操作指南",
+ "tags": ["步骤清晰", "方法拆解", "检查清单"],
+ "structure": ["问题与收益", "执行步骤", "注意事项", "完成检查"],
+ "instructions": "先说明读者问题和完成后的收益,再按可执行步骤展开。每一步说明目的、操作和注意事项,必要时使用清单。结尾提供检查表或下一步行动。"
+ },
+ "en-US": {
+ "name": "Practical Tutorial",
+ "description": "Clear steps for methods, workflows, and hands-on guides",
+ "tags": ["Clear steps", "Method breakdown", "Checklist"],
+ "structure": ["Problem and outcome", "Action steps", "Cautions", "Completion check"],
+ "instructions": "Start by explaining the reader's problem and the outcome they can achieve, then proceed through executable steps. For each step, state its purpose, action, and cautions, using checklists where useful. End with a completion checklist or a clear next action."
+ }
+ },
+ "categoryId": "practical",
+ "domains": ["technology", "workplace", "education"],
+ "tags": ["步骤清晰", "方法拆解", "检查清单"],
+ "structure": ["问题与收益", "执行步骤", "注意事项", "完成检查"],
+ "instructions": "先说明读者问题和完成后的收益,再按可执行步骤展开。每一步说明目的、操作和注意事项,必要时使用清单。结尾提供检查表或下一步行动。",
+ "author": "OpenCreator",
+ "status": "verified",
+ "sortOrder": 30,
+ "source": { "type": "official", "license": "OpenCreator project" },
+ "skill": {
+ "stageResources": {
+ "topics": ["skill/SKILL.md"],
+ "outline": ["skill/SKILL.md"],
+ "article": ["skill/SKILL.md"]
+ }
+ }
+}
diff --git a/packages/writing-templates/test/catalog.test.ts b/packages/writing-templates/test/catalog.test.ts
new file mode 100644
index 00000000..b6ba3744
--- /dev/null
+++ b/packages/writing-templates/test/catalog.test.ts
@@ -0,0 +1,115 @@
+import { describe, expect, it } from 'vitest';
+import {
+ getWritingTemplate,
+ getWritingTemplateStagePrompt,
+ localizeWritingTemplate,
+ normalizeWritingTemplateId,
+ writingTemplates
+} from '../src/index.js';
+
+describe('writing template catalog', () => {
+ it('publishes official and reviewed community templates with unique ids', () => {
+ expect(writingTemplates).toHaveLength(7);
+ expect(writingTemplates.map(template => template.id)).toEqual([
+ 'community.sun-style-writing',
+ 'community.khazix-writer',
+ 'community.research-paper-writing',
+ 'insight',
+ 'story',
+ 'tutorial',
+ 'news-analysis'
+ ]);
+ expect(new Set(writingTemplates.map(template => template.id)).size).toBe(writingTemplates.length);
+ expect(writingTemplates.every(template => ['verified', 'featured'].includes(template.status))).toBe(true);
+ expect(writingTemplates.filter(template => template.source.type === 'github').every(template => template.status === 'featured')).toBe(true);
+ expect(Object.isFrozen(writingTemplates)).toBe(true);
+ });
+
+ it('pins and attributes the adapted community template', () => {
+ const template = getWritingTemplate('community.sun-style-writing');
+ expect(template).toMatchObject({
+ name: '孙割写作.skill',
+ source: {
+ type: 'github',
+ repository: 'KKKKhazix/sun-style-writing',
+ revision: 'fe970dc15113ea0c3807f19f1d3118f63f9d9079',
+ license: 'MIT'
+ },
+ contentHash: expect.stringMatching(/^[a-f0-9]{64}$/)
+ });
+ });
+
+ it('normalizes renamed community template ids', () => {
+ expect(normalizeWritingTemplateId('community.restrained-narrative')).toBe('community.sun-style-writing');
+ expect(getWritingTemplate('community.restrained-narrative')?.id).toBe('community.sun-style-writing');
+ });
+
+ it('preserves the upstream khazix-writer name and source', () => {
+ const template = getWritingTemplate('community.khazix-writer');
+ expect(template).toMatchObject({
+ name: '卡兹克公众号长文写作',
+ author: '数字生命卡兹克',
+ source: {
+ type: 'github',
+ repository: 'KKKKhazix/khazix-skills',
+ revision: '7a5c4934be4106ac740ffdb95280bb81b3f4b83c',
+ license: 'MIT'
+ },
+ contentHash: expect.stringMatching(/^[a-f0-9]{64}$/)
+ });
+ });
+
+ it('preserves the upstream research paper template name, source, and research domain', () => {
+ const template = getWritingTemplate('community.research-paper-writing');
+ expect(template).toMatchObject({
+ name: 'Research Paper Writing',
+ author: 'Master-cai / OpenCreator adapted',
+ domains: ['research'],
+ source: {
+ type: 'github',
+ repository: 'Master-cai/Research-Paper-Writing-Skills',
+ revision: '77e7c2c1ba06f7d71844873147665437a03aac1b',
+ license: 'MIT'
+ },
+ contentHash: expect.stringMatching(/^[a-f0-9]{64}$/)
+ });
+ expect(localizeWritingTemplate(template!, 'zh-CN')).toMatchObject({
+ name: '科研论文写作',
+ description: '用清晰章节、严密论证和审稿人视角组织科研论文与学术内容'
+ });
+ expect(localizeWritingTemplate(template!, 'en-US')).toMatchObject({
+ name: 'Research Paper Writing',
+ description: 'Structure research papers with clear sections, rigorous arguments, and a reviewer\'s perspective'
+ });
+ });
+
+ it('localizes templates whose canonical names are Chinese', () => {
+ const template = getWritingTemplate('community.khazix-writer');
+ expect(localizeWritingTemplate(template!, 'en-US')).toMatchObject({
+ name: 'Khazix Long-form WeChat Writing',
+ tags: ['Long-form article', 'Conversational rhythm', 'Real experience', 'Opinion narrative']
+ });
+ });
+
+ it('loads only the resources needed by each writing stage', () => {
+ const topicPrompt = getWritingTemplateStagePrompt('community.sun-style-writing', 'topics');
+ const articlePrompt = getWritingTemplateStagePrompt('community.sun-style-writing', 'article');
+
+ expect(topicPrompt).toContain('选题规则');
+ expect(topicPrompt).not.toContain('成稿检查');
+ expect(articlePrompt).toContain('孙学写作法');
+ expect(articlePrompt).toContain('成稿检查');
+
+ const khazixTopicPrompt = getWritingTemplateStagePrompt('community.khazix-writer', 'topics');
+ const khazixArticlePrompt = getWritingTemplateStagePrompt('community.khazix-writer', 'article');
+ expect(khazixTopicPrompt).toContain('HKR 质检');
+ expect(khazixArticlePrompt).toContain('卡兹克公众号长文写作');
+ expect(khazixArticlePrompt).toContain('四层质检');
+
+ const researchTopicPrompt = getWritingTemplateStagePrompt('community.research-paper-writing', 'topics');
+ const researchArticlePrompt = getWritingTemplateStagePrompt('community.research-paper-writing', 'article');
+ expect(researchTopicPrompt).toContain('科研选题判断');
+ expect(researchArticlePrompt).toContain('Research Paper Writing');
+ expect(researchArticlePrompt).toContain('投稿前审稿式检查');
+ });
+});
diff --git a/packages/writing-templates/tsconfig.json b/packages/writing-templates/tsconfig.json
new file mode 100644
index 00000000..2fae345f
--- /dev/null
+++ b/packages/writing-templates/tsconfig.json
@@ -0,0 +1,8 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "rootDir": "src",
+ "outDir": "dist"
+ },
+ "include": ["src/**/*.ts", "src/**/*.json"]
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d967b100..46b260ff 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -58,9 +58,15 @@ importers:
'@opencreator/skill-market':
specifier: workspace:*
version: link:../../packages/skill-market
+ '@opencreator/writing-templates':
+ specifier: workspace:*
+ version: link:../../packages/writing-templates
better-sqlite3:
specifier: ^12.11.1
version: 12.11.1
+ cheerio:
+ specifier: 1.1.2
+ version: 1.1.2
cron-parser:
specifier: ^5.6.1
version: 5.6.1
@@ -73,9 +79,18 @@ importers:
https-proxy-agent:
specifier: ^7.0.6
version: 7.0.6
+ marked:
+ specifier: ^18.0.12
+ version: 18.0.12
nanoid:
specifier: ^5.0.9
version: 5.1.16
+ pdf-parse:
+ specifier: 1.1.1
+ version: 1.1.1
+ pdfkit:
+ specifier: ^0.20.2
+ version: 0.20.2
yaml:
specifier: ^2.8.1
version: 2.9.0
@@ -89,6 +104,12 @@ importers:
'@types/cross-spawn':
specifier: ^6.0.6
version: 6.0.6
+ '@types/pdf-parse':
+ specifier: 1.1.5
+ version: 1.1.5
+ '@types/pdfkit':
+ specifier: ^0.17.6
+ version: 0.17.6
apps/desktop:
dependencies:
@@ -183,6 +204,9 @@ importers:
'@opencreator/skill-market':
specifier: workspace:*
version: link:../../packages/skill-market
+ '@opencreator/writing-templates':
+ specifier: workspace:*
+ version: link:../../packages/writing-templates
lucide-react:
specifier: ^0.468.0
version: 0.468.0([email protected])
@@ -247,6 +271,8 @@ importers:
packages/skill-market: {}
+ packages/writing-templates: {}
+
packages:
@@ -869,10 +895,18 @@ packages:
'@cfworker/json-schema':
optional: true
+ '@noble/[email protected]':
+ resolution: {integrity: sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==}
+ engines: {node: ^14.21.3 || >=16}
+
resolution: {integrity: sha512-V1JJ1WTRUqHHrOSh597hURcMqVKVGL/ea3kv0gSnEdsEZ0/+VyPghM1lMNGc00z7CIQorSvbKpuJkxvuHbvdbg==}
engines: {node: '>= 16'}
+ '@noble/[email protected]':
+ resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==}
+ engines: {node: ^14.21.3 || >=16}
+
resolution: {integrity: sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg==}
engines: {node: '>= 20.19.0'}
@@ -1035,6 +1069,9 @@ packages:
resolution: {integrity: sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==}
+
'@szmarczak/[email protected]':
resolution: {integrity: sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==}
engines: {node: '>=10'}
@@ -1118,6 +1155,12 @@ packages:
resolution: {integrity: sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-kBfrSXsloMnUJOKi25s3+hRmkycHfLK6A09eRGqF/N8BkQoPUmaCr+q8Cli5FnfohEz/rsv82zAiPz/LXtOGhA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-tIwzxk2uWKp0Cq9JIluQXJid77lYhF52EsIOwhsMF4iWLA6YneoBR1xVKYYdAysHuepUB0OX4tdwMiUDdGKmig==}
+
resolution: {integrity: sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==}
@@ -1270,6 +1313,10 @@ packages:
resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==}
engines: {node: 18 || 20 || >=22}
+ resolution: {integrity: sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==}
+ engines: {node: '>= 0.4'}
+
resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}
@@ -1295,6 +1342,9 @@ packages:
resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==}
+
resolution: {integrity: sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==}
deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
@@ -1309,6 +1359,9 @@ packages:
resolution: {integrity: sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==}
engines: {node: 20 || >=22}
+ resolution: {integrity: sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==}
+
resolution: {integrity: sha512-JxV13hNrFxqjOc8alRbq9dK1MM79NEXYpma2B2J4wAtpWS5zIEIKqWPGCl7N4o7Uc7B7itylh7SuDujATRyyTw==}
engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
@@ -1371,6 +1424,13 @@ packages:
resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==}
engines: {node: '>= 16'}
+ resolution: {integrity: sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==}
+
+ resolution: {integrity: sha512-IkxPpb5rS/d1IiLbHMgfPuS0FgiWTtFIm/Nj+2woXDLTZ7fOT2eqzgYbdMlLweqlHbsZjxEChoVK+7iph7jyQg==}
+ engines: {node: '>=20.18.1'}
+
resolution: {integrity: sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==}
@@ -1396,6 +1456,10 @@ packages:
resolution: {integrity: sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA==}
+ resolution: {integrity: sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==}
+ engines: {node: '>=0.8'}
+
resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==}
engines: {node: '>=7.0.0'}
@@ -1470,6 +1534,13 @@ packages:
resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
engines: {node: '>= 8'}
+ resolution: {integrity: sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==}
+
+ resolution: {integrity: sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==}
+ engines: {node: '>= 6'}
+
resolution: {integrity: sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==}
@@ -1484,6 +1555,14 @@ packages:
resolution: {integrity: sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==}
+ peerDependencies:
+ supports-color: '*'
+ peerDependenciesMeta:
+ supports-color:
+ optional: true
+
resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}
engines: {node: '>=6.0'}
@@ -1539,6 +1618,9 @@ packages:
resolution: {integrity: sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==}
+ resolution: {integrity: sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==}
+
resolution: {integrity: sha512-2xMCmOoMrdQIPHdsTawECdNPwlVFB9zGcz3kuhmBO6U3oU+UQjsue0i8ayLKpgBcm+hcXPMVSGUN9d+pvJ6+VQ==}
@@ -1551,6 +1633,19 @@ packages:
resolution: {integrity: sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==}
+ resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==}
+
+ resolution: {integrity: sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==}
+
+ resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==}
+ engines: {node: '>= 4'}
+
+ resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==}
+
resolution: {integrity: sha512-zIHwmZPRshsCdpMDyVsqGmgyP0yT8GAgXUnkdAoJisxvf33k7yO6OuoKmcTGuXPWSsm8Oh88nZicRLA9Y0rUeA==}
engines: {node: '>=12'}
@@ -1607,13 +1702,24 @@ packages:
resolution: {integrity: sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==}
engines: {node: '>= 0.8'}
+ resolution: {integrity: sha512-5gvq20T6vfpekVtqrYQsSCFZ1wEg5+wW0/QaZMWkFr6BqD3NfKs0rLCx4rrVlSWJeZb5NBJgVLswK/w2MWU+Gw==}
+
resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==}
+ resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==}
+ engines: {node: '>=0.12'}
+
resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==}
engines: {node: '>=0.12'}
+ resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==}
+ engines: {node: '>=0.12'}
+
resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==}
engines: {node: '>=6'}
@@ -1741,6 +1847,9 @@ packages:
picomatch:
optional: true
+ resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==}
+
resolution: {integrity: sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==}
@@ -1755,6 +1864,9 @@ packages:
resolution: {integrity: sha512-f2JHn75x2JlwUwLenZypgczR7YWMb/uO9BvUXtus+JMgkbIkLADd38cI4EiV+OQqrGo1Zlq6V8wnqMJ8e62wUQ==}
engines: {node: '>=20'}
+ resolution: {integrity: sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==}
+
resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==}
engines: {node: '>= 6'}
@@ -1887,6 +1999,9 @@ packages:
resolution: {integrity: sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==}
+
resolution: {integrity: sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==}
@@ -2046,6 +2161,9 @@ packages:
resolution: {integrity: sha512-CHYbu8RtboSIoVsHZ6Ye4cj4Aw/yg2oAFimlF7mNvfDV192LR7nDiKtSIfCuLT7KokPSTn/9kfVLm5OGN0A28A==}
+ resolution: {integrity: sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==}
+
resolution: {integrity: sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==}
@@ -2093,6 +2211,11 @@ packages:
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
+ resolution: {integrity: sha512-LEm4ga2YeI2T3GVHj9b0BaDPPk93LLTHMFeMyQbNIzPxc8vCI0y/scy0ZA6z6lXKyT9j9Nhl/OC6ZYKYGuFScA==}
+ engines: {node: '>= 20'}
+ hasBin: true
+
resolution: {integrity: sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==}
engines: {node: '>=10'}
@@ -2206,6 +2329,9 @@ packages:
resolution: {integrity: sha512-2xP/IGGMmmSQpI1+O/k72jF/ykvZ89JeuKX3TLJAYPDVLUalrshrLHkeVcCCZqG/eEa635cr8IBYzgnDvM2O8Q==}
+ resolution: {integrity: sha512-DRI60hzo2oKN1ma0ckc6nQWlHU69RH6xN0sjQTjMpChPfTYvKZdcQFfdYK2RWbJcKyUizSIy/l8OTGxMAM1QDw==}
+
resolution: {integrity: sha512-OMcPNvqTCFUnNaBlmdgq+lfNqY7gTiSmNRDjY3uAXRyudeKZEZxu3CLtjMQrx4zZxCX2b/mpNqTtwuCJgXhHkw==}
engines: {node: ^20.17.0 || >=22.9.0}
@@ -2237,6 +2363,9 @@ packages:
resolution: {integrity: sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==}
+
resolution: {integrity: sha512-7YRhZ3jS45LwmSCT4b2sVFHt/WuovaktDU07QrtOBY2PXskss5a9jfmR9jptyumwXST+rFjrmppMY1KT/yn35A==}
@@ -2271,6 +2400,15 @@ packages:
resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==}
+
+ resolution: {integrity: sha512-ruw5xyKs6lrpo9x9rCZqZZnIUntICjQAd0Wsmp396Ul9lN/h+ifgVV1x1gZHi8euej6wTfpqX8j+BFQxF0NS/g==}
+
+ resolution: {integrity: sha512-JyeQc9iwFLn5TbvvqACIF/VXG6abODeB3Fwmv/TGdLk2LfbWkaySGY72at4+Ty7EkPZj854u4CrICqNk2qIbow==}
+
resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==}
@@ -2296,6 +2434,13 @@ packages:
resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==}
engines: {node: '>= 14.16'}
+ resolution: {integrity: sha512-v6ZJ/efsBpGrGGknjtq9J/oC8tZWq0KWL5vQrk2GlzLEQPUDB1ex+13Rmidl1neNN358Jn9EHZw5y07FFtaC7A==}
+ engines: {node: '>=6.8.1'}
+
+ resolution: {integrity: sha512-Q/w03ICAQyXfHNfTsg1udp0ADerdBN0s7a6XSPL7J7Ro6ABnafoBOCDBstIO9U02mvzHEV8HrvFIw5iV5ejIRA==}
+
resolution: {integrity: sha512-eRWB5LBz7PpDu4PUlwT0PhnQfTQJlDDdPa35urV4Osrm0t0AqQFGn+UIkU3klZvwJ8KPO3VbBFsXquA6p6kqZw==}
engines: {node: '>=12', npm: '>=6'}
@@ -2339,6 +2484,9 @@ packages:
resolution: {integrity: sha512-uysumyrvkUX0rX/dEVqt8gC3sTBzd4zoWfLeS29nb53imdaXVvLINYXTI2GNqzaMuvacNx4uJQ8+b3zXR0pkgQ==}
engines: {node: '>=10.4.0'}
+ resolution: {integrity: sha512-GdzJuUMc6ZSpxFJWVxtOH1bzYHym+TOnveqUjb+VJIbZWbZzyiRGFiKhbiielfpYbgMlhHVhsJ0FTazfuRFkMA==}
+
resolution: {integrity: sha512-xdB1oSLHbz1vRWgCDalrCqEFTWzFlhqFC5tIHLMOSUIjhm3XXQ1qrFy8S/ESr1JYRRXqM3c1QFiMZUJdUTqyMQ==}
engines: {node: ^10 || ^12 || >=14}
@@ -2502,6 +2650,9 @@ packages:
resolution: {integrity: sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw==}
+ resolution: {integrity: sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==}
+
resolution: {integrity: sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw==}
engines: {node: '>=10'}
@@ -2753,6 +2904,9 @@ packages:
resolution: {integrity: sha512-01EAw5EDrcVrdgyCLgoSPvqznC0sVxDSVeiOz09FUpjh71G79VCqneOr+xvt7T1r76CF6ZZfPjHorN2+d+3mqA==}
+ resolution: {integrity: sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==}
+
resolution: {integrity: sha512-qVtvMxeXbVej0cQWKqVSSAHmKZEHAvxdF8HEUBFWts8h+xEo5m/lEiPakuyZ3BnCBjOD8i24kzNOiOLLgsSxhA==}
@@ -2853,6 +3007,12 @@ packages:
resolution: {integrity: sha512-YQ3WlbqjYMmNpdvDH64jAgLjxuAR9+649calDWhbshYaeQGO2bR4nI94ORJmwI3J9YhoKQnpyGOK+0zlWS5N5Q==}
engines: {node: '>=22.19.0'}
+ resolution: {integrity: sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==}
+
+ resolution: {integrity: sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==}
+
resolution: {integrity: sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==}
engines: {node: '>= 4.0.0'}
@@ -3727,8 +3887,12 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ '@noble/[email protected]': {}
+
'@noble/[email protected]': {}
+ '@noble/[email protected]': {}
+
'@noble/[email protected]': {}
'@peculiar/[email protected]':
@@ -3840,6 +4004,10 @@ snapshots:
'@sindresorhus/[email protected]': {}
+ dependencies:
+ tslib: 2.8.1
+
'@szmarczak/[email protected]':
dependencies:
defer-to-connect: 2.0.1
@@ -3949,6 +4117,14 @@ snapshots:
dependencies:
undici-types: 7.18.2
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 22.20.0
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 22.20.0
+
'@types/[email protected]': {}
@@ -4145,6 +4321,8 @@ snapshots:
+
@@ -4180,6 +4358,8 @@ snapshots:
transitivePeerDependencies:
- supports-color
+
optional: true
@@ -4196,6 +4376,10 @@ snapshots:
dependencies:
balanced-match: 4.0.4
+ dependencies:
+ base64-js: 1.5.1
+
dependencies:
baseline-browser-mapping: 2.11.21
@@ -4282,6 +4466,29 @@ snapshots:
+ dependencies:
+ boolbase: 1.0.0
+ css-select: 5.2.2
+ css-what: 6.2.2
+ domelementtype: 2.3.0
+ domhandler: 5.0.3
+ domutils: 3.2.2
+
+ dependencies:
+ cheerio-select: 2.1.0
+ dom-serializer: 2.0.0
+ domhandler: 5.0.3
+ domutils: 3.2.2
+ encoding-sniffer: 0.2.1
+ htmlparser2: 10.1.0
+ parse5: 7.3.0
+ parse5-htmlparser2-tree-adapter: 7.1.0
+ parse5-parser-stream: 7.1.2
+ undici: 7.29.0
+ whatwg-mimetype: 4.0.0
+
@@ -4302,6 +4509,8 @@ snapshots:
dependencies:
mimic-response: 1.0.1
+
dependencies:
color-name: 1.1.4
@@ -4357,6 +4566,16 @@ snapshots:
shebang-command: 2.0.0
which: 2.0.2
+ dependencies:
+ boolbase: 1.0.0
+ css-what: 6.2.2
+ domhandler: 5.0.3
+ domutils: 3.2.2
+ nth-check: 2.1.1
+
+
@@ -4371,6 +4590,10 @@ snapshots:
whatwg-mimetype: 4.0.0
whatwg-url: 14.2.0
+ dependencies:
+ ms: 2.1.3
+
dependencies:
ms: 2.1.3
@@ -4412,6 +4635,8 @@ snapshots:
optional: true
+
dependencies:
minimatch: 3.1.5
@@ -4431,6 +4656,24 @@ snapshots:
+ dependencies:
+ domelementtype: 2.3.0
+ domhandler: 5.0.3
+ entities: 4.5.0
+
+
+ dependencies:
+ domelementtype: 2.3.0
+
+ dependencies:
+ dom-serializer: 2.0.0
+ domelementtype: 2.3.0
+ domhandler: 5.0.3
+
dependencies:
dotenv: 16.6.1
@@ -4531,12 +4774,21 @@ snapshots:
+ dependencies:
+ iconv-lite: 0.6.3
+ whatwg-encoding: 3.1.1
+
dependencies:
once: 1.4.0
+
+
@@ -4733,6 +4985,8 @@ snapshots:
optionalDependencies:
picomatch: 4.0.5
+
@@ -4756,6 +5010,18 @@ snapshots:
fast-querystring: 1.1.2
safe-regex2: 5.1.1
+ dependencies:
+ '@swc/helpers': 0.5.23
+ brotli: 1.3.3
+ clone: 2.1.2
+ dfa: 1.2.0
+ fast-deep-equal: 3.1.3
+ restructure: 3.0.2
+ tiny-inflate: 1.0.3
+ unicode-properties: 1.4.1
+ unicode-trie: 2.0.0
+
dependencies:
asynckit: 0.4.0
@@ -4915,6 +5181,13 @@ snapshots:
dependencies:
whatwg-encoding: 3.1.1
+ dependencies:
+ domelementtype: 2.3.0
+ domhandler: 5.0.3
+ domutils: 3.2.2
+ entities: 7.0.1
+
@@ -5074,6 +5347,11 @@ snapshots:
process-warning: 4.0.1
set-cookie-parser: 2.7.2
+ dependencies:
+ base64-js: 0.0.8
+ unicode-trie: 2.0.0
+
@@ -5110,6 +5388,8 @@ snapshots:
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
+
dependencies:
escape-string-regexp: 4.0.0
@@ -5193,6 +5473,8 @@ snapshots:
dependencies:
semver: 7.8.5
+
dependencies:
env-paths: 2.2.1
@@ -5233,6 +5515,10 @@ snapshots:
+ dependencies:
+ boolbase: 1.0.0
+
@@ -5258,6 +5544,17 @@ snapshots:
dependencies:
yocto-queue: 0.1.0
+
+ dependencies:
+ domhandler: 5.0.3
+ parse5: 7.3.0
+
+ dependencies:
+ parse5: 7.3.0
+
dependencies:
entities: 6.0.1
@@ -5274,6 +5571,22 @@ snapshots:
+ dependencies:
+ debug: 3.2.7
+ node-ensure: 0.0.0
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@noble/ciphers': 1.3.0
+ '@noble/hashes': 1.8.0
+ fflate: 0.8.3
+ fontkit: 2.0.4
+ linebreak: 1.1.0
+ png-js: 2.0.0
+
@@ -5325,6 +5638,10 @@ snapshots:
base64-js: 1.5.1
xmlbuilder: 15.1.1
+ dependencies:
+ fflate: 0.8.3
+
dependencies:
nanoid: 3.3.18
@@ -5499,6 +5816,8 @@ snapshots:
dependencies:
lowercase-keys: 2.0.0
+
@@ -5798,6 +6117,8 @@ snapshots:
dependencies:
semver: 5.7.2
+
@@ -5872,11 +6193,20 @@ snapshots:
- optional: true
+ dependencies:
+ base64-js: 1.5.1
+ unicode-trie: 2.0.0
+
+ dependencies:
+ pako: 0.2.9
+ tiny-inflate: 1.0.3
+