From c6497cccc914e5daa14ce3daad7c53b8f16fccec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=86=8A=E5=85=B5?= Date: Thu, 26 Nov 2026 16:46:21 +0800 Subject: [PATCH 1/4] Add WeChat Official Account Article Studio Mini App Adds plugins/xiaobinger/wechat-mp-article-studio: a workbench that turns an article topic, body, cover and illustration requirements, and a visual style into a cover/illustration plan, a duplication check against the previous article, versioned drafts with publish states, and paste-ready inline-styled HTML. Publishing is gated on account authorisation, material access scope, and an available publish interface. With no WeChat interface connected the app keeps everything as a draft and never claims to have published. --- README.md | 1 + README.zh-CN.md | 1 + .../.minimax-plugin/plugin.json | 18 + .../wechat-mp-article-studio/LICENSE | 21 + .../wechat-mp-article-studio/README.md | 92 ++ .../wechat-mp-article-studio/README.zh-CN.md | 75 + .../wechat-mp-article-studio/icon.png | Bin 0 -> 1574 bytes .../miniapp/client/app.js | 1264 +++++++++++++++++ .../miniapp/client/client-api.ts | 661 +++++++++ .../miniapp/client/index.html | 48 + .../miniapp/client/styles.css | 724 ++++++++++ .../miniapp/miniapp.json | 39 + .../miniapp/node/content.mjs | 520 +++++++ .../miniapp/node/host-connector-value.mjs | 53 + .../miniapp/node/images.mjs | 285 ++++ .../miniapp/node/miniapp-api.ts | 641 +++++++++ .../miniapp/node/polisher.mjs | 225 +++ .../miniapp/node/publishing.mjs | 284 ++++ .../miniapp/node/server.mjs | 802 +++++++++++ .../miniapp/node/store.mjs | 117 ++ .../miniapp/node/styles.mjs | 101 ++ .../wechat-mp-article-studio/package.json | 6 + 22 files changed, 5978 insertions(+) create mode 100644 plugins/xiaobinger/wechat-mp-article-studio/.minimax-plugin/plugin.json create mode 100644 plugins/xiaobinger/wechat-mp-article-studio/LICENSE create mode 100644 plugins/xiaobinger/wechat-mp-article-studio/README.md create mode 100644 plugins/xiaobinger/wechat-mp-article-studio/README.zh-CN.md create mode 100644 plugins/xiaobinger/wechat-mp-article-studio/icon.png create mode 100644 plugins/xiaobinger/wechat-mp-article-studio/miniapp/client/app.js create mode 100644 plugins/xiaobinger/wechat-mp-article-studio/miniapp/client/client-api.ts create mode 100644 plugins/xiaobinger/wechat-mp-article-studio/miniapp/client/index.html create mode 100644 plugins/xiaobinger/wechat-mp-article-studio/miniapp/client/styles.css create mode 100644 plugins/xiaobinger/wechat-mp-article-studio/miniapp/miniapp.json create mode 100644 plugins/xiaobinger/wechat-mp-article-studio/miniapp/node/content.mjs create mode 100644 plugins/xiaobinger/wechat-mp-article-studio/miniapp/node/host-connector-value.mjs create mode 100644 plugins/xiaobinger/wechat-mp-article-studio/miniapp/node/images.mjs create mode 100644 plugins/xiaobinger/wechat-mp-article-studio/miniapp/node/miniapp-api.ts create mode 100644 plugins/xiaobinger/wechat-mp-article-studio/miniapp/node/polisher.mjs create mode 100644 plugins/xiaobinger/wechat-mp-article-studio/miniapp/node/publishing.mjs create mode 100644 plugins/xiaobinger/wechat-mp-article-studio/miniapp/node/server.mjs create mode 100644 plugins/xiaobinger/wechat-mp-article-studio/miniapp/node/store.mjs create mode 100644 plugins/xiaobinger/wechat-mp-article-studio/miniapp/node/styles.mjs create mode 100644 plugins/xiaobinger/wechat-mp-article-studio/package.json diff --git a/README.md b/README.md index 0e543f77..1a78e881 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,7 @@ The MiniMax Code Agent communicates through the host MCP client. Business reques | [FactScribe Paper Workbench](plugins/unclemoc/factscribe/) | A local workbench for writing papers: open your manuscript projects, read the check report, the fact ledger and the knowledge base, and let the assistant propose edits you approve before anything reaches the file. 17 MCP tools, read-mostly by design; every write is gated by your confirmation. Requires MiniMax Code 3.1.2 or later | [UncleMoc (BGISMALL)](https://github.com/UncleMoc) | | [GitHub Star Shelf](plugins/start3208/github-star-shelf/) | Turn your GitHub stars into collections you can search and ask the AI to explain in plain language: from the README alone, or after it has read a shallow clone of the code. One session per project, your own notes, and collections the Agent can arrange | [start3208](https://github.com/start3208) | | [Plugin Listing Workbench](plugins/zhuyankarl/submission-workbench/) | Prepare a plugin submission: fill in the manifest and listing fields, check every required field and cross-file consistency, then download a reviewable listing package that names what is missing; a bundled Skill gives the Agent the same checklist | [zhuyankarl](https://github.com/zhuyankarl) | +| [WeChat Article Studio](plugins/xiaobinger/wechat-mp-article-studio/) | Plan a WeChat Official Account article: cover and illustration slots rendered as real images, a duplication check against your previous piece, versioned drafts with publish states, and paste-ready inline-styled HTML. Publishing stays blocked until account authorisation, material access and a publish interface are confirmed; with no interface connected it only ever saves a draft. Requires MiniMax Code 3.1.6 or later | [xiaobinger](https://github.com/xiaobinger) |
Preview: Cutline diff --git a/README.zh-CN.md b/README.zh-CN.md index e3c9a776..19c1ac99 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -96,6 +96,7 @@ MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求 | [FactScribe 论文工作台](plugins/unclemoc/factscribe/README.zh-CN.md) | 写论文的本地工作台:打开你的稿盘,看检查报告、事实账与知识库,助手给的改动先成提议单,你在页面上点采纳才落盘。17 个 MCP 工具以只读为主,写盘一律由你确认。需要 MiniMax Code 3.1.2 或更高版本 | [UncleMoc (BGISMALL)](https://github.com/UncleMoc) | | [GitHub 收藏夹](plugins/start3208/github-star-shelf/README.zh-CN.md) | 把 GitHub Star 分进收藏夹,按名称、README 和备注搜索;让 AI 用大白话讲清每个项目:只看 README 讲,或读一遍浅克隆的代码再讲。一个项目一个会话,可以写备注,也能让 Agent 整理收藏夹 | [start3208](https://github.com/start3208) | | [插件上架材料工作台](plugins/zhuyankarl/submission-workbench/README.zh-CN.md) | 填写插件清单与上架信息,逐项核对必填字段与内容一致性,生成可审核的上架材料包并标出缺失项;内置 Skill 让 Agent 拿到同一套检查清单 | [zhuyankarl](https://github.com/zhuyankarl) | +| [公众号图文工作台](plugins/xiaobinger/wechat-mp-article-studio/README.zh-CN.md) | 输入主题、正文、封面与插图需求,选一个视觉风格,产出封面与插图方案、与上一篇的查重结论、带版本和发布状态的草稿箱,以及可以直接粘贴进公众号的内联样式 HTML;发布前必须确认账号授权、素材范围与可用发布接口,没接接口时只存草稿。需要 MiniMax Code 3.1.6 或更高版本 | [xiaobinger](https://github.com/xiaobinger) |
预览:Cutline diff --git a/plugins/xiaobinger/wechat-mp-article-studio/.minimax-plugin/plugin.json b/plugins/xiaobinger/wechat-mp-article-studio/.minimax-plugin/plugin.json new file mode 100644 index 00000000..82b3c685 --- /dev/null +++ b/plugins/xiaobinger/wechat-mp-article-studio/.minimax-plugin/plugin.json @@ -0,0 +1,18 @@ +{ + "schemaVersion": 1, + "name": "wechat-mp-article-studio", + "displayName": "公众号图文工作台", + "version": "1.0.0", + "description": "输入公众号文章主题与正文,产出封面与插图方案、查重结论、版本管理与可发布内容;发布前须确认账号授权、素材范围与发布接口。", + "author": "xiaobinger", + "icon": "icon.png", + "category": "Business", + "exampleQueries": [ + "新建一篇公众号文章并生成封面与插图方案", + "看看草稿箱里有没有和上一篇重复的文章", + "为这篇公众号文章生成可发布内容" + ], + "apps": [], + "mcpServers": [], + "skills": [] +} diff --git a/plugins/xiaobinger/wechat-mp-article-studio/LICENSE b/plugins/xiaobinger/wechat-mp-article-studio/LICENSE new file mode 100644 index 00000000..0c69691c --- /dev/null +++ b/plugins/xiaobinger/wechat-mp-article-studio/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 xiaobinger + +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/plugins/xiaobinger/wechat-mp-article-studio/README.md b/plugins/xiaobinger/wechat-mp-article-studio/README.md new file mode 100644 index 00000000..a4edc338 --- /dev/null +++ b/plugins/xiaobinger/wechat-mp-article-studio/README.md @@ -0,0 +1,92 @@ +# 公众号图文工作台 (WeChat Official Account Article Studio) + +Turns an article topic, body text, cover and illustration requirements, and a visual style into a +cover/illustration plan, a duplication check against your previous article, a versioned draft list, +and a paste-ready WeChat Official Account (公众号) body. + +## What it does + +- **Plan** — enter a topic, the body, a cover requirement, an illustration requirement, and pick one + of the built-in visual styles or create your own. The app derives a cover slot (2.35:1 or 1:1) and + one illustration slot per `##` section, each with its ratio, pixel target, generation prompt, and a + short checklist. +- **Render** — every slot can be rendered as a real image through the `matrix` Connector + (`connector__matrix__generate_image`). Each slot is a separate call at 1K, so one slow image + cannot cancel the rest. +- **Duplication check** — the draft is compared with the previous draft and with the previous + published article (title, body, and key-point overlap) and reports a percentage plus a verdict. +- **Versions and states** — editing the body creates a new version of the same article and keeps the + older ones. A version is `草稿`, `待发布`, `已发布(接口)`, or `已发布(手动)`. +- **Cleanup** — select several versions and delete them together. A published record is protected + unless you confirm the deletion. +- **Publish gate** — before anything is published the app checks account authorisation, material + access scope, and an available publish interface. It reports only what it actually detects: with no + WeChat interface connected it keeps everything as a draft and never claims to have published. +- **Publish-ready content** — the body becomes inline-styled HTML that 公众号 accepts (no class + selectors, no `${data.html}`; + render(); + return; + } + + if (action === 'download-export') { + const response = await fetch(`/api/export/${encodeURIComponent(id)}?download=1`); + if (!response.ok) { + toast('下载失败', 'error'); + return; + } + const blob = await response.blob(); + const url = URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = url; + link.download = `公众号-${id.slice(0, 6)}.html`; + document.body.appendChild(link); + link.click(); + link.remove(); + URL.revokeObjectURL(url); + toast('已下载可发布 HTML', 'ok'); + return; + } + + if (action === 'start-polish') { + state.busy = true; + render(); + try { + const noteInput = document.getElementById('polish-note'); + state.polishNote = noteInput ? noteInput.value : state.polishNote; + const result = await api('/api/polish', { method: 'POST', body: JSON.stringify({ draftId: id, note: state.polishNote }) }); + state.polish = { draftId: id, status: 'running', message: 'Agent 正在润色…', permission: null, question: null }; + startPolishPolling(result.callId, id); + toast('已交给 Agent 润色'); + } finally { + state.busy = false; + render(); + } + return; + } + + if (action === 'cancel-polish') { + const callId = state.polish?.callId; + if (!callId) return; + await api(`/api/polish/${encodeURIComponent(callId)}/cancel`, { method: 'POST', body: '{}' }); + clearInterval(polishTimer); + polishTimer = null; + state.polish = null; + render(); + toast('已请求取消'); + return; + } + + if (action === 'polish-permission') { + const callId = state.polish?.callId; + if (!callId) return; + const result = await api(`/api/polish/${encodeURIComponent(callId)}/permission`, { + method: 'POST', + body: JSON.stringify({ decision: actionEl.dataset.decision }), + }); + state.polish.permission = null; + render(); + toast(result.message, result.ok ? 'ok' : 'error'); + return; + } + + if (action === 'polish-answer') { + const callId = state.polish?.callId; + if (!callId) return; + const stepId = actionEl.dataset.step; + const optionId = actionEl.dataset.option; + const question = state.polish.question; + const answers = (question?.steps || []).map((step) => ({ + stepId: step.id, + selectedOptionIds: step.id === stepId ? [optionId] : [], + selectedOther: false, + skipped: step.id !== stepId, + })); + const result = await api(`/api/polish/${encodeURIComponent(callId)}/answer`, { + method: 'POST', + body: JSON.stringify({ answers }), + }); + state.polish.question = null; + render(); + toast(result.message, result.ok ? 'ok' : 'error'); + return; + } + } catch (error) { + reportError('操作失败', error); + } +}); + +/** + * Compose form field -> state key. The live DOM is mirrored into state on + * every input so a re-render can never discard what the user has typed or + * selected. + */ +const COMPOSE_FIELDS = { + 'f-topic': 'topic', + 'f-title': 'title', + 'f-body': 'body', + 'f-cover-req': 'coverRequirement', + 'f-illus-req': 'illustrationRequirement', + 'f-style': 'styleId', + 'f-ratio': 'coverRatio', + 'f-cover-text': 'coverWithTitle', +}; + +document.addEventListener('input', (event) => { + const target = event.target; + const key = COMPOSE_FIELDS[target.id]; + if (key) state.form[key] = target.type === 'checkbox' ? target.checked : target.value; + if (target.id === 'draft-search') { + state.query = target.value; + render(); + const input = document.getElementById('draft-search'); + if (input) { + input.focus(); + input.setSelectionRange(input.value.length, input.value.length); + } + return; + } + if (target.id === 'polish-note') state.polishNote = target.value; +}); + +document.addEventListener('change', (event) => { + const target = event.target; + const key = COMPOSE_FIELDS[target.id]; + if (key) state.form[key] = target.type === 'checkbox' ? target.checked : target.value; + if (target.dataset && target.dataset.check) { + if (target.checked) state.checked.add(target.dataset.check); + else state.checked.delete(target.dataset.check); + render(); + return; + } + if (target.id === 'draft-filter') { + state.filter = target.value; + render(); + } +}); + +document.addEventListener('submit', async (event) => { + event.preventDefault(); + const form = event.target; + + if (form.id === 'compose-form') { + // Read every field before anything re-renders the form. + const payload = { + topic: document.getElementById('f-topic').value.trim(), + title: document.getElementById('f-title').value.trim(), + body: document.getElementById('f-body').value.trim(), + coverRequirement: document.getElementById('f-cover-req').value.trim(), + illustrationRequirement: document.getElementById('f-illus-req').value.trim(), + styleId: document.getElementById('f-style').value, + coverRatio: document.getElementById('f-ratio').value, + coverWithTitle: document.getElementById('f-cover-text').checked, + }; + if (!payload.topic || !payload.body) { + toast('文章主题与正文都不能为空', 'error'); + return; + } + Object.assign(state.form, payload); + try { + state.busy = true; + render(); + const result = await api('/api/drafts', { method: 'POST', body: JSON.stringify(payload) }); + state.snapshot = result.snapshot; + state.form = { + topic: '', + title: '', + body: '', + coverRequirement: '', + illustrationRequirement: '', + styleId: payload.styleId, + coverRatio: payload.coverRatio, + coverWithTitle: false, + }; + state.selectedId = result.draft.id; + state.view = 'detail'; + await refresh(); + toast('草稿已保存', 'ok'); + } catch (error) { + reportError('保存草稿失败', error); + } finally { + state.busy = false; + render(); + } + return; + } + + if (form.id === 'detail-form') { + const id = state.selectedId; + // Read every field before anything re-renders the detail view. + const payload = { + title: document.getElementById('d-title').value.trim(), + topic: document.getElementById('d-topic').value.trim(), + body: document.getElementById('d-body').value, + coverRequirement: document.getElementById('d-cover-req').value.trim(), + illustrationRequirement: document.getElementById('d-illus-req').value.trim(), + }; + try { + state.busy = true; + render(); + const result = await api(`/api/drafts/${encodeURIComponent(id)}`, { + method: 'PATCH', + body: JSON.stringify(payload), + }); + state.snapshot = result.snapshot; + if (result.draft && result.draft.id !== id) { + state.selectedId = result.draft.id; + } + await refresh(); + const previousVersion = (state.snapshot.drafts || []).find((draft) => draft.id === id)?.version; + toast( + previousVersion && result.draft.version > previousVersion ? '已保存为新版本' : '已保存', + 'ok', + ); + } catch (error) { + reportError('保存失败', error); + } finally { + state.busy = false; + render(); + } + } +}); + +/* ------------------------------------------------------------------ * + * Host appearance + * ------------------------------------------------------------------ */ + +// Follow the Host's effective theme when the bridge is available; fall back +// to prefers-color-scheme otherwise (the stylesheet owns that default). +function subscribeHostAppearance() { + const miniAppHost = window.mcode?.miniapp?.host; + if (!miniAppHost?.ui?.subscribe) return; + const subscription = miniAppHost.ui.subscribe( + ({ theme, language }) => { + if (theme === 'light' || theme === 'dark') { + document.documentElement.dataset.theme = theme; + } + if (language) document.documentElement.lang = language; + }, + { + onError: ({ code }) => { + console.warn('Host appearance unavailable:', code); + }, + }, + ); + window.addEventListener('pagehide', () => subscription?.dispose(), { once: true }); +} + +/* ------------------------------------------------------------------ * + * Boot + * ------------------------------------------------------------------ */ + +async function boot() { + try { + subscribeHostAppearance(); + await loadTools(); + await refresh(); + } catch (error) { + main.innerHTML = `
工作台载入失败:${esc(error.message)}
`; + } +} + +void boot(); diff --git a/plugins/xiaobinger/wechat-mp-article-studio/miniapp/client/client-api.ts b/plugins/xiaobinger/wechat-mp-article-studio/miniapp/client/client-api.ts new file mode 100644 index 00000000..1703018b --- /dev/null +++ b/plugins/xiaobinger/wechat-mp-article-studio/miniapp/client/client-api.ts @@ -0,0 +1,661 @@ +/** + * Copyable Mini App Client declarations for TypeScript and JavaScript/JSDoc authoring. + * No Host implementation or runtime import: Electron preload provides window.mcode. + * Keep the .ts filename because Electron dependency packaging filters out .d.ts assets. + * Node start(context) uses miniapp-api.ts instead. See client-api.md for usage and errors. + */ +export interface MiniAppMessageAPI { + /** + * Ask the user to append plain text to this Mini App's conversation input. + * Accepts at most 100,000 UTF-16 code units and preserves spaces, tabs, and newlines. + * An empty string still requires confirmation and leaves the draft unchanged. + * Resolves after the confirmed append; rejects on cancellation or failure. + * Does not send a message or insert, edit, or delete sent chat history. + */ + append(text: string): Promise; +} + +export type MiniAppAgentQuestionMode = 'questionnaire' | 'feature-enable' | 'plan'; + +export interface MiniAppAgentQuestionOption { + readonly id: string; + readonly label: string; + readonly description?: string; +} + +export interface MiniAppAgentQuestionStep { + readonly id: string; + readonly header?: string; + readonly question: string; + readonly description?: string; + readonly selectionMode: 'single' | 'multiple'; + readonly options: readonly MiniAppAgentQuestionOption[]; + /** Free-text "other" is always accepted; see `MiniAppAgentQuestionAnswer.otherText`. */ + readonly allowOther: true; +} + +/** Same questionnaire the Host chat renders; render every step and answer each one. */ +export interface MiniAppAgentQuestionnaire { + readonly schemaVersion: 2; + readonly id: string; + readonly title?: string; + readonly steps: readonly MiniAppAgentQuestionStep[]; + readonly mode?: MiniAppAgentQuestionMode; + /** Plan review Markdown and other mode-specific data. */ + readonly modePayload?: { readonly [key: string]: unknown }; + /** Unix ms; the request is withdrawn after this. */ + readonly expiresAt?: number; +} + +export interface MiniAppAgentQuestionAnswer { + readonly stepId: string; + readonly selectedOptionIds: readonly string[]; + readonly selectedOther: boolean; + readonly otherText?: string; + readonly skipped?: boolean; +} + +/** A model as the Host's composer selects it; take the values from `models()`. */ +export interface MiniAppAgentModelSelection { + readonly providerId: string; + readonly modelId: string; + /** `''` means thinking is off; it is preserved, distinct from an absent `variant`. */ + readonly variant?: string; + readonly thinking?: { readonly effort: string }; +} + +/** One model this user can use. */ +export interface MiniAppAgentModelOption { + readonly providerId: string; + readonly modelId: string; + readonly displayName: string; + readonly variants?: readonly string[]; + readonly thinking?: { readonly efforts: readonly string[]; readonly default?: string }; +} + +export interface MiniAppAgentModels { + readonly models: readonly MiniAppAgentModelOption[]; + /** What a session without a host chat model starts with. */ + readonly default: MiniAppAgentModelSelection; + /** The host chat's current model (the default when the chat has none); only when opened from a chat. */ + readonly host?: MiniAppAgentModelSelection; +} + +export interface MiniAppAgentAgentOption { + /** Canonical name; what `agent` takes. */ + readonly name: string; + readonly displayName: string; + /** The default agent. */ + readonly primary: boolean; +} + +export interface MiniAppAgentAgents { + readonly agents: readonly MiniAppAgentAgentOption[]; +} + +/** Final outcome of one Agent turn. */ +export interface MiniAppAgentRunResult { + /** Pass back in `run({ sessionId })` to continue the same conversation. */ + readonly sessionId: string; + /** Absent when no turn ran: an `answer` accepted without starting a continuation. */ + readonly turnId?: string; + /** The model the turn was dispatched with; absent when no turn ran or the text was steered. */ + readonly model?: MiniAppAgentModelSelection; + /** + * `aborted` only when the Host confirmed the abort; an unconfirmed cancel rejects with + * `result_unknown`. `steered` (only with `whenBusy`): the text joined the running turn + * `turnId`, whose own call gets the reply, so there is no `text`. + */ + readonly status: 'finished' | 'error' | 'aborted' | 'steered'; + /** Final assistant reply; absent when the turn produced none or did not finish. */ + readonly text?: string; + readonly error?: { readonly code: string; readonly message: string }; + /** Set when the turn ended waiting on a questionnaire; render `request` and continue with `agent.answer`. */ + readonly pendingQuestion?: { + readonly requestId: string; + readonly mode: MiniAppAgentQuestionMode; + readonly request: MiniAppAgentQuestionnaire; + }; +} + +/** + * Progress of one run. `turnId` matches the result's, except that a `permission.requested` raised + * by a delegated child session carries that child's own `sessionId` and `turnId`; `reply` with + * those, and do not filter events by the root turn. Ignore unknown `type` values: new event + * types may be added without notice. + * - `run.queued`: the call waits at 1-based `position`, for a run slot or, with + * `whenBusy: 'queue'`, in the session queue (a `whenBusy` call can get both); sent before the + * turn starts, so it has no `turnId` and names a session only when continuing one. + * - `message.pending` / `message.steered`: with `whenBusy: 'steer'`, the text was handed to the + * running turn, then read by it; `message.steered` is the call's last event. + * - `turn.started`: the Agent began the turn; `model` is the model it was dispatched with. + * - `text.delta`: a piece of the reply as it streams. + * - `message.committed`: one complete assistant message (a turn can have several). + * - `tool.started` / `tool.finished`: a tool call by name; `ok` is false when it failed. + * - `permission.requested`: a tool call waits for approval; decide it with `agent.reply`. + * - `question.requested`: the turn paused on a questionnaire; continue with `agent.answer`. + * - `turn.finished`: last unless the call ended `steered`; same `status`, `text`, and `error` + * as the run result. + * Every event except `run.queued` names its `sessionId`, so `reply` works before the `run` that + * created the session has returned. `answer` does not: call it after the paused `run` resolves, + * or it rejects as busy. + */ +export type MiniAppAgentRunEvent = + | { readonly type: 'run.queued'; readonly sessionId?: string; readonly position: number } + | { + readonly type: 'message.pending' | 'message.steered'; + readonly sessionId: string; + readonly turnId: string; + } + | { + readonly type: 'turn.started'; + readonly sessionId: string; + readonly turnId: string; + readonly model: MiniAppAgentModelSelection; + } + | { + readonly type: 'text.delta'; + readonly sessionId: string; + readonly turnId: string; + readonly text: string; + } + | { + readonly type: 'message.committed'; + readonly sessionId: string; + readonly turnId: string; + readonly text: string; + } + | { + readonly type: 'tool.started'; + readonly sessionId: string; + readonly turnId: string; + readonly name: string; + } + | { + readonly type: 'tool.finished'; + readonly sessionId: string; + readonly turnId: string; + readonly name: string; + readonly ok: boolean; + } + | { + readonly type: 'permission.requested'; + readonly sessionId: string; + /** Absent when the runtime did not attribute the ask to a turn. */ + readonly turnId?: string; + readonly requestId: string; + readonly toolName: string; + readonly toolInput?: string; + readonly reason: string; + } + | { + readonly type: 'question.requested'; + readonly sessionId: string; + readonly turnId?: string; + readonly requestId: string; + readonly mode: MiniAppAgentQuestionMode; + readonly request: MiniAppAgentQuestionnaire; + } + | { + readonly type: 'turn.finished'; + readonly sessionId: string; + readonly turnId: string; + readonly status: 'finished' | 'error' | 'aborted'; + readonly text?: string; + readonly error?: { readonly code: string; readonly message: string }; + }; + +/** `observe({ all: true })` only: the conversation's title, when it has one. */ +interface MiniAppAgentObservedTitle { + readonly title?: string; +} + +type MiniAppAgentRunEventOf = Extract< + MiniAppAgentRunEvent, + { readonly type: T } +>; + +/** + * What an observer receives: the run events without `run.queued` and without asks, which reach + * only the run that owns them. `turn.started.model` is present only when the Host could read it. + * Ignore unknown `type` values. + */ +export type MiniAppAgentObservedEvent = + | (Omit, 'model'> & { + readonly model?: MiniAppAgentModelSelection; + } & MiniAppAgentObservedTitle) + | MiniAppAgentRunEventOf<'text.delta' | 'tool.started' | 'tool.finished'> + | (MiniAppAgentRunEventOf<'message.committed'> & MiniAppAgentObservedTitle) + | (MiniAppAgentRunEventOf<'turn.finished'> & MiniAppAgentObservedTitle); + +/** + * `{ all: true }`: `turn.started`, `message.committed` (the final reply) and `turn.finished` of + * every user conversation, with its `title`. `{ sessionId }`: every progress event of that + * session, turn after turn. Exactly one of the two. + */ +export type MiniAppAgentObserveTarget = { readonly sessionId: string } | { readonly all: true }; + +/** One of the user's conversations; `running` while a turn is in flight. */ +export interface MiniAppAgentSessionSummary { + readonly sessionId: string; + readonly title?: string; + /** The Agent the session runs. */ + readonly agent: string; + readonly status: 'idle' | 'running' | 'error' | 'aborted'; + /** The conversation's project directory (absolute) as recorded; it may no longer exist. */ + readonly workspaceDir: string; + /** True when the conversation has no project and runs in the default workspace. */ + readonly isDefaultWorkspace: boolean; + /** Unix ms. */ + readonly createdAtMs: number; + /** Unix ms. */ + readonly updatedAtMs: number; +} + +export interface MiniAppAgentSessionDetail extends MiniAppAgentSessionSummary { + /** The conversation's current model; absent when the Host has none recorded. */ + readonly model?: MiniAppAgentModelSelection; + /** Only while `status` is `error` and the Host recorded a message. */ + readonly error?: { readonly message: string }; + /** Final text of the latest Agent reply, if any. */ + readonly lastAssistantText?: string; +} + +export interface MiniAppAgentSessions { + /** The 50 most recently updated user conversations (no Mini App, scheduled or sub-Agent ones). */ + readonly sessions: readonly MiniAppAgentSessionSummary[]; +} + +export interface MiniAppAgentRunInput { + /** Plain text, at most 100,000 UTF-16 code units. */ + readonly text: string; + /** Continue a session this Mini App created earlier; omit to start a new one. */ + readonly sessionId?: string; + /** + * Switch the session to this model before the turn (validated like the composer validates a new + * session's model: it must be one `models()` lists; unusable is `invalid_request`, missing BYOK + * credentials end the turn with `status: 'error'`); the session keeps it. Omit to use the session's current model. + */ + readonly model?: MiniAppAgentModelSelection; + /** + * Only when starting a session (no `sessionId`): an agent `name` from `agents()`. A session + * never changes its agent, so passing it with `sessionId` is `invalid_request`. + */ + readonly agent?: string; + /** + * Only with `sessionId`, when that session is already running a turn (otherwise it starts one as + * usual). `queue`: the text runs as the next turn and this call follows it. `steer`: the + * running turn reads the text at its next input point; the call resolves `steered`, or follows + * the next turn when the running one answered before reading it. Omit to reject as `busy`. + */ + readonly whenBusy?: 'queue' | 'steer'; + /** Your id for `cancel(requestId)`; 1-128 characters, unique among this page's active runs. */ + readonly requestId?: string; +} + +export interface MiniAppAgentReplyInput { + readonly sessionId: string; + /** `requestId` of the `permission.requested` event. */ + readonly requestId: string; + /** No `allowAlways`: a Mini App never writes the user's global rules. */ + readonly decision: 'allowOnce' | 'deny'; +} + +export interface MiniAppAgentAnswerInput { + readonly sessionId: string; + /** `requestId` of the `question.requested` event or of `result.pendingQuestion`. */ + readonly questionId: string; + /** One answer per questionnaire step. */ + readonly answers: readonly MiniAppAgentQuestionAnswer[]; + /** Same as `MiniAppAgentRunInput.model`, applied before the continuation turn. */ + readonly model?: MiniAppAgentModelSelection; + /** Your id for `cancel(requestId)`, as in `run`. */ + readonly requestId?: string; +} + +export interface MiniAppAgentRunOptions { + readonly onEvent?: (event: MiniAppAgentRunEvent) => void; +} + +/** + * Absent on older Hosts. `run` / `reply` / `answer` / `open` / `models` / `agents` / `create` reject + * with `not_permitted` unless the manifest declares `agentAccess: ["session.run"]`; `observe` / + * `sessions` need `"session.read"` for anything but this Mini App's own sessions (see + * agent-interaction.md). A new session uses the Agent of the chat this page is open in; + * a page without a host chat uses the primary Agent unless `run({ agent })` / `create({ agent })` + * names one from `agents()`. Continuing a session keeps its Agent. + * The Agent works in the host chat's project directory when it has one, otherwise in this Mini + * App's own Agent directory; a continued session keeps its directory. A new session takes the + * model and thinking level of the host chat (the runtime default when the chat has none) and keeps + * them; `run` / `answer` with `model` switch the session's model first. + * It runs one turn with that Agent's full capabilities (files, shell, Skills, MCP including this + * Mini App's own), and resolves when it ends. + * + * Interaction is yours to render: handle `permission.requested` with `reply` and + * `question.requested` with `answer`. A permission request waits only while this run passed + * `onEvent` or the session is open in a chat side panel through `open`; otherwise it is denied + * and the model is told why. A run with `onEvent` that does not handle the request waits until + * `cancel` or the page closes; there is no timeout. Up to `agentConcurrency` runs (default 4) per + * Mini App run at once, one per session; further `run` / `answer` calls wait in order (up to four + * times that many, see `run.queued`), and `cancel` on a waiting call rejects it with `cancelled`. + * `busy` means the session is running a turn, compacting, or has messages queued ahead (never with + * `whenBusy`; the text reached no turn) or the wait queue is full. + * Failures reject with an `Error` whose `message` is `invalid_request`, `not_permitted`, `busy`, + * `session_not_found`, `runtime_unavailable`, `cancelled`, `result_unknown`, or + * `request_not_found`. `runtime_unavailable` means nothing was started; `result_unknown` means + * the turn may have run (or ended without the Host knowing whether a question is pending), so + * never repeat it automatically. + */ +export interface MiniAppAgentAPI { + run( + input: MiniAppAgentRunInput, + options?: MiniAppAgentRunOptions, + ): Promise; + /** Decide a pending permission request; `request_not_found` when it is unknown or settled. */ + reply(input: MiniAppAgentReplyInput): Promise; + /** + * Answer a questionnaire; the continuation turn is observed like `run`. Rejects with + * `result_unknown` when the answer was recorded but the continuation turn was not observed. + */ + answer( + input: MiniAppAgentAnswerInput, + options?: MiniAppAgentRunOptions, + ): Promise; + /** Ask the Host to stop an active run or answer; unknown or finished ids are ignored. */ + cancel(requestId: string): void; + /** + * Show one of this Mini App's sessions as a tab in the side panel of the chat the + * Mini App is open in, where the user can read the conversation and answer + * permission and question cards themselves. Permission requests wait for the tab only + * while it stays open; once the user closes it, handle `permission.requested` yourself + * or call `open` again. Any session this Mini App owns can be opened, whichever chat + * created it; `session_not_found` otherwise. + */ + open(sessionId: string): Promise; + /** + * Returns the model catalog, runtime `default` and optional chat `host`. Pass `default` / `host` + * directly as `model` to `run` / `answer`. For a catalog entry, extract `providerId` / `modelId`, + * add a selected `variant` if needed and preserve `variant: ''`. If thinking is supported, + * select an effort from `thinking.efforts` and pass `thinking: { effort }`. + */ + models(): Promise; + /** The agents the user has configured; `agent` of `create` / a first `run` must be one of them. */ + agents(): Promise; + /** + * Create a session bound to this chat (agent, project directory, model) without running a + * turn, and return its `sessionId`; continue it with `run({ sessionId })` here or hand it to + * Node code. `agent` picks the session's agent from `agents()`; a session never changes it. + * Takes no run slot. If the Host's 60 s deadline passes it rejects with `runtime_unavailable` + * although the session may already exist. + */ + create(input?: { readonly agent?: string }): Promise<{ readonly sessionId: string }>; + /** + * Watch the user's Agent at work (see `MiniAppAgentObserveTarget`). Pass a `requestId` to be + * able to stop it with `cancel(requestId)`. Resolves when the subscription ended: cancelled, the + * session was deleted, the page or Mini App stopped, or `session.read` was switched off. Rejects + * with `invalid_request` (not exactly one target), `not_permitted`, `session_not_found`, or + * `busy` past 4 observers per Mini App; observers use no run slots. Check + * `capabilities?.has('agent.observe')` first: older Hosts lack it. + */ + observe( + target: MiniAppAgentObserveTarget & { readonly requestId?: string }, + options: { readonly onEvent: (event: MiniAppAgentObservedEvent) => void }, + ): Promise; + /** Check `capabilities?.has('agent.sessions')` first: older Hosts lack it. */ + sessions(): Promise; + /** + * The chat this page is open in (needs `session.read`: it is the user's conversation, not this + * Mini App's); undefined when the page is not in a chat tab. Check + * `capabilities?.has('agent.session')` first. + */ + session(): Promise; + /** One conversation with its model and latest reply. */ + session(sessionId: string): Promise; +} + +/** + * Page entry for asking "always allow" ahead of time, while the user is present, so later Node + * calls need no prompt. Listing and calling tools is Node `context.tool` only. Needs + * `"toolAccess": ["call"]` and a running Node process; check + * `capabilities.has('tool.request')`. + */ +export interface MiniAppToolRequestAPI { + /** + * Shows one Host prompt for the named tools (runtime names from Node `context.tool.list()`) + * that are still `ask`; the user ticks which to always allow. Resolves each name's state + * afterwards; the Host never trusts this map back. Only inside a user gesture + * (`navigator.userActivation.isActive`), 1–10 distinct names, else `invalid_request`. + * Other rejections: `not_permitted` (no `toolAccess`), `approval_required` (no Host window + * can show the prompt), `runtime_unavailable` (Node process not running), `result_unknown`. + */ + request(names: readonly string[]): Promise>; +} + +export interface MiniAppOpenedFile { + readonly path: string; + readonly name: string; + readonly extension: string; +} + +export interface MiniAppFileOpen { + readonly handlerId: string; + readonly files: readonly MiniAppOpenedFile[]; +} + +export interface MiniAppFilesAPI { + subscribe( + listener: (open: MiniAppFileOpen) => void, + options?: MiniAppHostSubscribeOptions, + ): MiniAppHostDisposable; +} + +export interface MiniAppClientAPI { + readonly message: MiniAppMessageAPI; + readonly agent?: MiniAppAgentAPI; + /** Absent on Hosts without `tool.request`. */ + readonly tool?: MiniAppToolRequestAPI; + /** + * Proposed: shape may still change. Feature-detect with + * `window.mcode?.miniapp?.window` before use. + */ + readonly window?: MiniAppWindowHandle; + /** Absent on older Hosts; check `capabilities.has('speech.transcribe')`. */ + readonly speech?: MiniAppSpeechAPI; + /** Effective Host preferences and bounded navigation; absent on older Hosts. */ + readonly host?: MiniAppHostAPI; + /** Absent on older Hosts; check `capabilities.has('files.subscribe')`. */ + readonly files?: MiniAppFilesAPI; + /** + * Synchronous probe of Host features, fixed per Host version; independent of this Mini App's + * manifest or grants. Absent on older Hosts: check `window.mcode?.miniapp?.capabilities?.has`. + */ + readonly capabilities?: MiniAppHostCapabilities; +} + +export interface MiniAppHostCapabilities { + has(name: string): boolean; +} + +/** + * The only PCM the Host transcribes. Capture at exactly this (an `AudioContext` created with + * `sampleRate: 16000`, one channel, samples converted to `Int16Array`) and pass the object + * verbatim; any other value is `invalid_request`. See `audio-capture.ts` for a capture helper. + */ +export interface MiniAppSpeechAudioFormat { + readonly sampleRate: 16000; + readonly channelCount: 1; + readonly sampleFormat: 's16'; +} + +export interface MiniAppSpeechTranscribeInput { + /** + * One utterance of samples: an `Int16Array`, or the `ArrayBuffer` / view behind one. At least + * one sample, at most 16,000,000 bytes (500 s). Not an encoded file: WAV, WebM, Ogg, FLAC and + * MP3 are refused as `invalid_request`. + */ + readonly audio: ArrayBuffer | ArrayBufferView; + readonly format: MiniAppSpeechAudioFormat; +} + +export interface MiniAppSpeechTranscribeOptions { + /** The transcript so far while the Host is still transcribing; the final text is the result. */ + readonly onPartial?: (text: string) => void; +} + +/** + * Speech recognition of audio the page captured. Requires the manifest to declare + * `deviceAccess: ["microphone"]` and the user's "Use the microphone" switch to be on (the same + * switch that lets `getUserMedia` succeed); otherwise calls reject with `not_permitted`. + * The Host transcribes after it has the whole utterance: decide the utterance boundary in the + * page (release of a push-to-talk button, a stop button, a silence detector), then call once + * per utterance. One call per Mini App runs at a time; a second is `busy`. + * Failures reject with an `Error` whose `message` is `invalid_request`, `not_permitted`, + * `audio_too_large`, `busy`, `runtime_unavailable` (speech recognition is disabled or the user + * is signed out), `transcription_failed`, or `result_unknown`. + */ +export interface MiniAppSpeechAPI { + transcribe( + input: MiniAppSpeechTranscribeInput, + options?: MiniAppSpeechTranscribeOptions, + ): Promise<{ readonly text: string }>; +} + +/** Live state of the popped-out window: current position, size, and flags — not the manifest declaration. */ +export interface MiniAppWindowOptions { + readonly width: number; + readonly height: number; + readonly minWidth: number; + readonly minHeight: number; + readonly x: number; + readonly y: number; + readonly visible: boolean; + readonly resizable: boolean; + readonly frame: boolean; + readonly transparent: boolean; + readonly alwaysOnTop: boolean; + readonly clickThrough: boolean; + readonly skipTaskbar: boolean; +} + +export type MiniAppWindowState = + | { readonly mode: 'inline'; readonly modeChangeReloadsPage?: boolean } + | { + readonly mode: 'window'; + readonly window: MiniAppWindowOptions; + readonly modeChangeReloadsPage?: boolean; + }; + +/** Every field is optional; omitted fields are left unchanged. */ +export type MiniAppWindowPatch = Partial<{ + mode: 'inline' | 'window'; + width: number; + height: number; + x: number; + y: number; + visible: boolean; + resizable: boolean; + alwaysOnTop: boolean; + clickThrough: boolean; + skipTaskbar: boolean; +}>; + +export interface MiniAppWindowDisposable { + dispose(): void; +} + +/** + * Page-side handle for this Mini App's own window (proposed). Separate from + * `message`; the Host injects both under the same `mcode.miniapp` namespace. + */ +export interface MiniAppWindowHandle { + /** Opaque and stable across pop-out and return; never a Session or launch identifier. */ + readonly id: string; + getState(): Promise; + /** + * `update({ mode: ... })` or `focus()` require the call to originate from a + * user gesture (`navigator.userActivation.isActive`); otherwise they reject + * with `not_permitted` before any Host round trip. The `click` handler of a + * `Notification` the page created counts as one. + * When getState().modeChangeReloadsPage is true, mode changes end this document. + * Do not rely on the old Promise continuation; read state on the destination page. + */ + update(patch: MiniAppWindowPatch): Promise; + focus(): Promise; + /** Returns a disposable; call `dispose()` to stop receiving updates. */ + onDidChangeState(listener: (state: MiniAppWindowState) => void): MiniAppWindowDisposable; +} + +/** Page-visible Host state. Resource identities and pending preferences never enter these values. */ +export interface MiniAppHostUIState { + readonly theme: 'light' | 'dark'; + readonly language: string; +} + +export type MiniAppHostView = 'home' | 'conversation' | 'plugins' | 'schedule' | 'other'; +export type MiniAppHostOverlay = { readonly type: 'settings' } | null; + +export interface MiniAppHostNavigationState { + /** Short-lived opaque value scoped to this page and its observation authorization. */ + readonly key: string; + readonly view: MiniAppHostView; + readonly overlay: MiniAppHostOverlay; +} + +export type MiniAppHostOpenTarget = + | { readonly id: 'home' } + | { readonly id: 'plugins' } + | { readonly id: 'schedule' } + | { readonly id: 'settings'; readonly section?: 'appearance' | 'language' } + | { readonly id: 'session'; readonly sessionId: string; readonly source: 'local' }; + +export type MiniAppHostOpenResult = + | { readonly status: 'opened' } + | { readonly status: 'cancelled'; readonly reason: 'user_cancelled' | 'superseded' }; + +export type MiniAppHostErrorCode = + | 'invalid_request' + | 'not_permitted' + | 'host_unavailable' + | 'unsupported_source' + | 'unsupported_target' + | 'target_unavailable' + | 'result_unknown'; +export interface MiniAppHostError { + readonly code: MiniAppHostErrorCode; + readonly message: string; +} +export interface MiniAppHostDisposable { + dispose(): void; +} +export interface MiniAppHostSubscribeOptions { + readonly onError?: (error: MiniAppHostError) => void; +} + +export interface MiniAppHostAPI { + readonly ui: { + getState(): Promise; + subscribe( + listener: (state: MiniAppHostUIState) => void, + options?: MiniAppHostSubscribeOptions, + ): MiniAppHostDisposable; + }; + readonly navigation: { + getState(): Promise; + subscribe( + listener: (state: MiniAppHostNavigationState) => void, + options?: MiniAppHostSubscribeOptions, + ): MiniAppHostDisposable; + open(target: MiniAppHostOpenTarget): Promise; + }; +} + +export interface McodeClientAPI { + readonly miniapp: MiniAppClientAPI; +} + +declare global { + interface Window { + /** Absent outside a supported managed Mini App main page. Check before use. */ + readonly mcode?: McodeClientAPI; + } +} diff --git a/plugins/xiaobinger/wechat-mp-article-studio/miniapp/client/index.html b/plugins/xiaobinger/wechat-mp-article-studio/miniapp/client/index.html new file mode 100644 index 00000000..c68040e8 --- /dev/null +++ b/plugins/xiaobinger/wechat-mp-article-studio/miniapp/client/index.html @@ -0,0 +1,48 @@ + + + + + + 公众号图文工作台 + + + +
+
+
+

公众号图文工作台

+

输入主题与正文,产出封面与插图方案、查重结论和可发布内容

+
+
+ 正在读取工作台状态… +
+
+ +
+ + +
+

正在载入工作台…

+
+
+
+ + + + + + diff --git a/plugins/xiaobinger/wechat-mp-article-studio/miniapp/client/styles.css b/plugins/xiaobinger/wechat-mp-article-studio/miniapp/client/styles.css new file mode 100644 index 00000000..6a8a6d7a --- /dev/null +++ b/plugins/xiaobinger/wechat-mp-article-studio/miniapp/client/styles.css @@ -0,0 +1,724 @@ +/* 公众号图文工作台 — Mini App Client + Visual baseline: minimax-code-visual-ui.md (--mcode-* semantic variables). */ + +:root, +[data-theme='light'] { + --mcode-bg: #ffffff; + --mcode-bg-secondary: #f5f5f5; + --mcode-surface: #ffffff; + --mcode-surface-muted: #fafafa; + --mcode-text: #171717; + --mcode-text-muted: #666666; + --mcode-text-subtle: #adadad; + --mcode-border: #0a0a0a14; + --mcode-border-strong: #0a0a0af2; + --mcode-accent: #0094fc; + --mcode-success: #04b54b; + --mcode-warning: #f56811; + --mcode-danger: #f73646; + --mcode-primary-action-bg: #171717; + --mcode-primary-action-text: #ffffff; + --mcode-radius-card: 12px; + --mcode-radius-control: 8px; + --mcode-shadow: 0 0 20px rgb(10 10 10 / 8%); +} + +[data-theme='dark'] { + --mcode-bg: #171717; + --mcode-bg-secondary: #1c1c1c; + --mcode-surface: #262626; + --mcode-surface-muted: #262626; + --mcode-text: #ededed; + --mcode-text-muted: #949494; + --mcode-text-subtle: #666666; + --mcode-border: #ffffff14; + --mcode-border-strong: #fffffff2; + --mcode-accent: #0077d9; + --mcode-success: #009c3d; + --mcode-warning: #e25507; + --mcode-danger: #e31937; + --mcode-primary-action-bg: #ffffff; + --mcode-primary-action-text: #171717; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme='light']) { + --mcode-bg: #171717; + --mcode-bg-secondary: #1c1c1c; + --mcode-surface: #262626; + --mcode-surface-muted: #262626; + --mcode-text: #ededed; + --mcode-text-muted: #949494; + --mcode-text-subtle: #666666; + --mcode-border: #ffffff14; + --mcode-border-strong: #fffffff2; + --mcode-accent: #0077d9; + --mcode-success: #009c3d; + --mcode-warning: #e25507; + --mcode-danger: #e31937; + --mcode-primary-action-bg: #ffffff; + --mcode-primary-action-text: #171717; + } +} + +* { + box-sizing: border-box; +} + +[hidden] { + display: none !important; +} + +body { + margin: 0; + background: var(--mcode-bg-secondary); + color: var(--mcode-text); + font-family: ui-sans-serif, -apple-system, system-ui, 'Segoe UI', Helvetica, Arial, sans-serif; + font-size: 14px; + line-height: 1.6; +} + +.app-shell { + min-height: 100vh; + display: flex; + flex-direction: column; +} + +.app-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + padding: 16px 24px; + background: var(--mcode-surface); + border-bottom: 1px solid var(--mcode-border); +} + +.app-title { + margin: 0; + font-size: 18px; + line-height: 28px; + font-weight: 600; +} + +.app-subtitle { + margin: 2px 0 0; + font-size: 12px; + line-height: 18px; + color: var(--mcode-text-muted); +} + +.gate-note { + font-size: 12px; + color: var(--mcode-text-muted); + text-align: right; + max-width: 360px; + display: inline-block; +} + +.app-body { + flex: 1; + display: flex; + align-items: flex-start; + gap: 24px; + padding: 24px; +} + +.app-nav { + flex: 0 0 216px; + display: flex; + flex-direction: column; + gap: 4px; + position: sticky; + top: 24px; +} + +.nav-item { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + width: 100%; + padding: 9px 12px; + border: 1px solid transparent; + border-radius: var(--mcode-radius-control); + background: transparent; + color: var(--mcode-text); + font: inherit; + text-align: left; + cursor: pointer; + transition: background 150ms ease-out, color 150ms ease-out; +} + +.nav-item:hover { + background: var(--mcode-surface-muted); +} + +.nav-item[aria-current='page'] { + background: var(--mcode-surface); + border-color: var(--mcode-border); + font-weight: 600; +} + +.nav-item__count { + font-size: 12px; + color: var(--mcode-text-muted); + background: var(--mcode-bg-secondary); + border-radius: 999px; + padding: 1px 8px; +} + +.nav-footnote { + margin: 12px 4px 0; + font-size: 12px; + line-height: 1.6; + color: var(--mcode-text-subtle); + border-top: 1px solid var(--mcode-border); + padding-top: 12px; +} + +.app-main { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 16px; +} + +.card { + background: var(--mcode-surface); + border: 1px solid var(--mcode-border); + border-radius: var(--mcode-radius-card); + padding: 20px; +} + +.card__header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + flex-wrap: wrap; + margin-bottom: 12px; +} + +.section-title { + margin: 0; + font-size: 16px; + line-height: 24px; + font-weight: 500; +} + +.section-desc { + margin: 4px 0 0; + font-size: 12px; + line-height: 18px; + color: var(--mcode-text-muted); +} + +.toolbar { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} + +.field { + display: flex; + flex-direction: column; + gap: 6px; + margin-bottom: 14px; +} + +.field__label { + font-size: 13px; + font-weight: 500; +} + +.field__hint { + font-size: 12px; + color: var(--mcode-text-muted); +} + +.field__error { + font-size: 12px; + color: var(--mcode-danger); +} + +input[type='text'], +input[type='number'], +textarea, +select { + width: 100%; + min-height: 36px; + padding: 8px 10px; + border: 1px solid var(--mcode-border); + border-radius: var(--mcode-radius-control); + background: var(--mcode-surface); + color: var(--mcode-text); + font: inherit; + transition: border-color 150ms ease-out; +} + +textarea { + min-height: 200px; + resize: vertical; + line-height: 1.7; +} + +input:focus-visible, +textarea:focus-visible, +select:focus-visible, +button:focus-visible { + outline: 2px solid var(--mcode-accent); + outline-offset: 1px; +} + +input:focus, +textarea:focus, +select:focus { + border-color: var(--mcode-accent); +} + +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + height: 34px; + padding: 0 14px; + border-radius: var(--mcode-radius-control); + border: 1px solid var(--mcode-border); + background: var(--mcode-surface); + color: var(--mcode-text); + font: inherit; + font-size: 13px; + cursor: pointer; + transition: background 150ms ease-out, opacity 150ms ease-out; +} + +.btn:hover:not(:disabled) { + background: var(--mcode-surface-muted); +} + +.btn:disabled { + opacity: 0.45; + cursor: not-allowed; +} + +.btn--primary { + background: var(--mcode-primary-action-bg); + color: var(--mcode-primary-action-text); + border-color: transparent; + font-weight: 500; +} + +.btn--primary:hover:not(:disabled) { + opacity: 0.88; + background: var(--mcode-primary-action-bg); +} + +.btn--danger { + color: var(--mcode-danger); + border-color: var(--mcode-border); +} + +.btn--danger:hover:not(:disabled) { + background: var(--mcode-danger); + color: #ffffff; + border-color: var(--mcode-danger); +} + +.btn--link { + border-color: transparent; + background: transparent; + color: var(--mcode-accent); + padding: 0 6px; + height: 28px; +} + +.btn--link:hover:not(:disabled) { + background: var(--mcode-surface-muted); +} + +.grid-2 { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); + gap: 16px; +} + +.stack { + display: flex; + flex-direction: column; + gap: 12px; +} + +.row { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} + +.pill { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 1px 9px; + border-radius: 999px; + font-size: 12px; + line-height: 18px; + border: 1px solid var(--mcode-border); + color: var(--mcode-text-muted); + background: var(--mcode-surface-muted); + white-space: nowrap; +} + +.pill--ok { + color: var(--mcode-success); + border-color: color-mix(in srgb, var(--mcode-success) 40%, transparent); +} + +.pill--warn { + color: var(--mcode-warning); + border-color: color-mix(in srgb, var(--mcode-warning) 40%, transparent); +} + +.pill--danger { + color: var(--mcode-danger); + border-color: color-mix(in srgb, var(--mcode-danger) 40%, transparent); +} + +.pill--accent { + color: var(--mcode-accent); + border-color: color-mix(in srgb, var(--mcode-accent) 40%, transparent); +} + +.draft-list { + display: flex; + flex-direction: column; + gap: 8px; +} + +.draft-row { + display: grid; + grid-template-columns: 28px 1fr auto; + align-items: start; + gap: 12px; + padding: 12px 14px; + border: 1px solid var(--mcode-border); + border-radius: var(--mcode-radius-control); + background: var(--mcode-surface); +} + +.draft-row:hover { + background: var(--mcode-surface-muted); +} + +.draft-row__main { + min-width: 0; + display: flex; + flex-direction: column; + gap: 4px; +} + +.draft-row__title { + font-weight: 500; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.draft-row__meta { + display: flex; + gap: 6px; + flex-wrap: wrap; + align-items: center; + font-size: 12px; + color: var(--mcode-text-muted); +} + +.draft-row__actions { + display: flex; + align-items: center; + gap: 4px; +} + +.plan-slot { + border: 1px solid var(--mcode-border); + border-radius: var(--mcode-radius-control); + overflow: hidden; + background: var(--mcode-surface); +} + +.plan-slot__media { + aspect-ratio: 16 / 9; + background: var(--mcode-surface-muted); + display: flex; + align-items: center; + justify-content: center; + border-bottom: 1px solid var(--mcode-border); + overflow: hidden; +} + +.plan-slot__media img { + width: 100%; + height: 100%; + object-fit: cover; + display: block; +} + +.plan-slot__placeholder { + font-size: 12px; + color: var(--mcode-text-subtle); + padding: 12px; + text-align: center; +} + +.plan-slot__body { + padding: 12px; + display: flex; + flex-direction: column; + gap: 8px; +} + +.prompt-box { + margin: 0; + padding: 10px; + background: var(--mcode-bg-secondary); + border: 1px solid var(--mcode-border); + border-radius: 6px; + font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; + font-size: 12px; + line-height: 1.6; + color: var(--mcode-text-muted); + white-space: pre-wrap; + word-break: break-word; + max-height: 150px; + overflow: auto; +} + +.check-list { + margin: 0; + padding-left: 18px; + font-size: 12px; + color: var(--mcode-text-muted); +} + +.gate-item { + display: grid; + grid-template-columns: 1fr auto; + gap: 10px; + align-items: start; + padding: 12px 0; + border-bottom: 1px solid var(--mcode-border); +} + +.gate-item:last-child { + border-bottom: none; +} + +.gate-item__label { + font-weight: 500; +} + +.gate-item__note { + font-size: 12px; + color: var(--mcode-text-muted); + margin-top: 2px; +} + +.notice { + padding: 10px 12px; + border-radius: var(--mcode-radius-control); + font-size: 13px; + line-height: 1.6; + border: 1px solid var(--mcode-border); + background: var(--mcode-surface-muted); + color: var(--mcode-text-muted); +} + +.notice--warn { + border-color: color-mix(in srgb, var(--mcode-warning) 40%, transparent); + color: var(--mcode-warning); +} + +.notice--danger { + border-color: color-mix(in srgb, var(--mcode-danger) 40%, transparent); + color: var(--mcode-danger); +} + +.notice--ok { + border-color: color-mix(in srgb, var(--mcode-success) 40%, transparent); + color: var(--mcode-success); +} + +.state-message { + color: var(--mcode-text-muted); + font-size: 13px; + padding: 24px 0; +} + +.empty-state { + text-align: center; + padding: 40px 16px; + color: var(--mcode-text-muted); + border: 1px dashed var(--mcode-border); + border-radius: var(--mcode-radius-card); +} + +.empty-state h3 { + margin: 0 0 6px; + font-size: 15px; + font-weight: 500; + color: var(--mcode-text); +} + +.style-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); + gap: 12px; +} + +.style-card { + border: 1px solid var(--mcode-border); + border-radius: var(--mcode-radius-card); + padding: 14px; + background: var(--mcode-surface); + display: flex; + flex-direction: column; + gap: 8px; +} + +.style-card__swatches { + display: flex; + gap: 4px; +} + +.style-swatch { + width: 22px; + height: 22px; + border-radius: 6px; + border: 1px solid var(--mcode-border); +} + +.export-preview { + border: 1px solid var(--mcode-border); + border-radius: var(--mcode-radius-control); + background: #ffffff; + overflow: auto; + max-height: 520px; +} + +.export-preview iframe { + width: 100%; + min-height: 420px; + border: 0; +} + +.toast { + position: fixed; + right: 24px; + bottom: 24px; + max-width: 380px; + padding: 10px 14px; + border-radius: var(--mcode-radius-control); + background: var(--mcode-surface); + border: 1px solid var(--mcode-border); + box-shadow: var(--mcode-shadow); + font-size: 13px; + z-index: 20; +} + +.toast--error { + border-color: color-mix(in srgb, var(--mcode-danger) 45%, transparent); + color: var(--mcode-danger); +} + +.toast--ok { + border-color: color-mix(in srgb, var(--mcode-success) 45%, transparent); + color: var(--mcode-success); +} + +.checkbox { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 13px; + cursor: pointer; +} + +.checkbox input { + width: 15px; + height: 15px; + accent-color: var(--mcode-accent); +} + +.mono { + font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; + font-size: 12px; +} + +.meta-list { + margin: 0; + display: grid; + grid-template-columns: max-content 1fr; + gap: 4px 16px; + font-size: 13px; +} + +.meta-list dt { + color: var(--mcode-text-muted); +} + +.meta-list dd { + margin: 0; +} + +@media (max-width: 768px) { + .app-body { + flex-direction: column; + padding: 16px; + gap: 16px; + } + + .app-nav { + flex: 1 1 auto; + width: 100%; + position: static; + flex-direction: row; + flex-wrap: wrap; + } + + .nav-item { + width: auto; + } + + .nav-footnote { + flex-basis: 100%; + } + + .app-header { + flex-direction: column; + padding: 16px; + } + + .gate-note { + text-align: left; + max-width: none; + } + + .draft-row { + grid-template-columns: 28px 1fr; + } + + .draft-row__actions { + grid-column: 2; + } +} + +@media (prefers-reduced-motion: reduce) { + * { + transition: none !important; + animation: none !important; + } +} diff --git a/plugins/xiaobinger/wechat-mp-article-studio/miniapp/miniapp.json b/plugins/xiaobinger/wechat-mp-article-studio/miniapp/miniapp.json new file mode 100644 index 00000000..f0bb484c --- /dev/null +++ b/plugins/xiaobinger/wechat-mp-article-studio/miniapp/miniapp.json @@ -0,0 +1,39 @@ +{ + "schemaVersion": 1, + "artifacts": { + "client": [ + "./miniapp/client" + ], + "node": [ + "./miniapp/node" + ] + }, + "runtime": { + "kind": "process", + "entry": "./miniapp/node/server.mjs", + "lifecycle": "on-demand" + }, + "surface": { + "path": "/dashboard", + "window": { + "width": 1280, + "height": 860, + "minWidth": 760, + "minHeight": 520, + "resizable": true, + "frame": true, + "transparent": false, + "alwaysOnTop": false, + "skipTaskbar": false, + "clickThrough": false + } + }, + "mcpEndpoints": [], + "toolAccess": [ + "call" + ], + "agentAccess": [ + "session.run" + ], + "agentConcurrency": 2 +} diff --git a/plugins/xiaobinger/wechat-mp-article-studio/miniapp/node/content.mjs b/plugins/xiaobinger/wechat-mp-article-studio/miniapp/node/content.mjs new file mode 100644 index 00000000..0c097274 --- /dev/null +++ b/plugins/xiaobinger/wechat-mp-article-studio/miniapp/node/content.mjs @@ -0,0 +1,520 @@ +// @ts-check + +/** + * Content domain logic for the 公众号图文工作台. + * + * This module is deliberately deterministic: everything it produces is + * derived from the user's own topic, body and requirements by rule. Nothing + * here invents prose or claims an AI wrote it — derived fields are labelled + * as 规则提取 in the UI. + */ + +/** @typedef {{ type: string, text: string, items: string[] }} Block */ +/** @typedef {{ id: string, role: string, ratio: string, pixels: string, anchor: string, prompt: string, checklist: string[], status: string }} PlanSlot */ + +export const COVER_RATIOS = { + wide: { ratio: '47:20', pixels: '900×383', label: '2.35:1 主封面' }, + square: { ratio: '1:1', pixels: '900×900', label: '1:1 分享缩略图' }, +}; + +const MAX_ILLUSTRATIONS = 4; +const DIGEST_LIMIT = 120; + +/* ------------------------------------------------------------------ * + * Body parsing — a deliberately small markdown subset + * ------------------------------------------------------------------ */ + +/** + * @param {string} body + * @returns {Block[]} + */ +export function parseBlocks(body) { + const text = String(body ?? '').replace(/\r\n/g, '\n'); + /** @type {Block[]} */ + const blocks = []; + /** @type {string[]} */ + const paragraph = []; + + const flushParagraph = () => { + const joined = paragraph.join('').trim(); + paragraph.length = 0; + if (joined) blocks.push({ type: 'p', text: joined, items: [] }); + }; + + for (const rawLine of text.split('\n')) { + const line = rawLine.trim(); + if (!line) { + flushParagraph(); + continue; + } + if (line.startsWith('### ')) { + flushParagraph(); + blocks.push({ type: 'h3', text: line.slice(4).trim(), items: [] }); + continue; + } + if (line.startsWith('## ')) { + flushParagraph(); + blocks.push({ type: 'h2', text: line.slice(3).trim(), items: [] }); + continue; + } + if (line.startsWith('# ')) { + flushParagraph(); + blocks.push({ type: 'h1', text: line.slice(2).trim(), items: [] }); + continue; + } + if (line.startsWith('> ')) { + flushParagraph(); + blocks.push({ type: 'quote', text: line.slice(2).trim(), items: [] }); + continue; + } + if (/^[-*]\s+/.test(line)) { + flushParagraph(); + blocks.push({ type: 'li', text: '', items: [line.replace(/^[-*]\s+/, '').trim()] }); + continue; + } + paragraph.push(line); + } + flushParagraph(); + return blocks; +} + +/** + * @param {string} body + * @returns {string[]} + */ +export function headings(body) { + return parseBlocks(body) + .filter((block) => block.type === 'h2' || block.type === 'h3') + .map((block) => block.text); +} + +/* ------------------------------------------------------------------ * + * Derivation — digest, title candidates, outline, key points + * ------------------------------------------------------------------ */ + +/** + * @param {string} body + * @returns {string[]} + */ +export function sentences(body) { + return String(body ?? '') + .split(/\n+/) + .flatMap((line) => line.replace(/^[#>\-*\s]+/, '').split(/[。!?!?;;]/)) + .map((s) => s.trim()) + .filter((s) => s.length >= 6); +} + +/** + * @param {string} body + * @returns {string[]} + */ +export function keyPoints(body, limit = 4) { + const scored = sentences(body).map((text, index) => ({ + text, + score: Math.min(text.length, 42) + Math.max(0, 24 - index * 2), + })); + scored.sort((a, b) => b.score - a.score); + const picked = []; + for (const item of scored) { + if (picked.length >= limit) break; + if (picked.some((other) => other.includes(item.text) || item.text.includes(other))) continue; + picked.push(item.text); + } + return picked; +} + +/** + * @param {any} draft + * @returns {{ digest: string, titleCandidates: string[], outline: string[], keyPoints: string[] }} + */ +export function deriveContent(draft) { + const body = String(draft.body ?? ''); + const blocks = parseBlocks(body); + const firstParagraph = blocks.find((block) => block.type === 'p'); + const digestSource = firstParagraph ? firstParagraph.text : sentences(body)[0] || ''; + const digest = digestSource.length > DIGEST_LIMIT + ? `${digestSource.slice(0, DIGEST_LIMIT - 1)}…` + : digestSource; + + const topic = String(draft.topic ?? '').trim(); + const points = keyPoints(body); + const sectionTitles = blocks.filter((b) => b.type === 'h2').map((b) => b.text); + + /** @type {string[]} */ + const titleCandidates = []; + if (topic) titleCandidates.push(topic); + const lead = sentences(body)[0] || ''; + if (lead && lead !== topic) { + titleCandidates.push(lead.length > 26 ? `${lead.slice(0, 26)}…` : lead); + } + if (sectionTitles.length >= 2) { + titleCandidates.push(`${sectionTitles[0]}|${sectionTitles[1]}`); + } + if (sectionTitles.length === 1) { + titleCandidates.push(`${sectionTitles[0]}:${topic}`); + } + + return { + digest, + titleCandidates: [...new Set(titleCandidates)].slice(0, 3), + outline: blocks + .filter((block) => block.type === 'h2' || block.type === 'h3') + .map((block) => `${block.type === 'h2' ? '' : ' '}${block.text}`), + keyPoints: points, + }; +} + +/* ------------------------------------------------------------------ * + * Cover / illustration plan + * ------------------------------------------------------------------ */ + +/** + * @param {any} draft + * @param {any} style + * @returns {{ cover: PlanSlot, illustrations: PlanSlot[], styleName: string }} + */ +export function buildPlan(draft, style) { + const body = String(draft.body ?? ''); + const topic = String(draft.topic ?? '').trim(); + const coverRequirement = String(draft.coverRequirement ?? '').trim(); + const illustrationRequirement = String(draft.illustrationRequirement ?? '').trim(); + const points = keyPoints(body, 4); + const coverSpec = COVER_RATIOS[draft.coverRatio === 'square' ? 'square' : 'wide']; + + const coverPrompt = [ + `公众号文章封面主视觉。`, + `视觉风格:${style.coverPrompt}。`, + `文章主题:${topic || '(未填写主题)'}。`, + points.length ? `正文要点:${points.join(';')}。` : '', + coverRequirement ? `封面需求:${coverRequirement}。` : '', + `画面比例 ${coverSpec.ratio} 横向构图(公众号推荐 ${specPixels(coverSpec)}),主体明确、四周留出安全边距。`, + draft.coverWithTitle + ? `画面中排版中文主标题文字「${(draft.title || topic).slice(0, 16)}」,字形端正清晰,不错字。` + : `画面中不要出现任何文字、水印、logo 或二维码。`, + ] + .filter(Boolean) + .join(''); + + const cover = { + id: 'cover', + role: '封面主图', + ratio: coverSpec.ratio, + pixels: coverSpec.pixels, + anchor: '文章首图(公众号列表与正文顶部)', + prompt: coverPrompt, + checklist: [ + `比例 ${coverSpec.ratio},目标 ${coverSpec.pixels}`, + draft.coverWithTitle ? '含中文标题文字,无错字' : '不含任何文字,避免和文章标题重复', + '主体清晰,缩略图尺寸下仍可辨识', + ], + status: draft.assets?.cover ? 'rendered' : 'pending', + }; + + /** @type {PlanSlot[]} */ + const illustrations = []; + const blocks = parseBlocks(body); + const anchors = []; + blocks.forEach((block, index) => { + if (block.type === 'h2' && anchors.length < MAX_ILLUSTRATIONS) { + anchors.push({ title: block.text, index }); + } + }); + if (anchors.length === 0) { + const lead = blocks.find((block) => block.type === 'p'); + if (lead) anchors.push({ title: '开篇', index: blocks.indexOf(lead) }); + } + + anchors.forEach((anchor, position) => { + const related = points[position % Math.max(points.length, 1)] || topic; + illustrations.push({ + id: `illustration-${position + 1}`, + role: `插图 ${position + 1}`, + ratio: '16:9', + pixels: '1080×608', + anchor: `小节「${anchor.title}」之后`, + prompt: [ + `公众号正文插图。`, + `视觉风格:${style.illustrationPrompt}。`, + `对应小节:${anchor.title}。`, + `该段要点:${related}。`, + illustrationRequirement ? `插图需求:${illustrationRequirement}。` : '', + `画面比例 16:9 横向,主体居中偏一侧,为正文文字留出空间,不含文字。`, + ] + .filter(Boolean) + .join(''), + checklist: ['比例 16:9', '不含文字', '与封面同一视觉语言'], + status: draft.assets?.illustrations?.[`illustration-${position + 1}`] ? 'rendered' : 'pending', + }); + }); + + return { cover, illustrations, styleName: style.name }; +} + +/** + * @param {{ ratio: string, pixels: string }} spec + * @returns {string} + */ +function specPixels(spec) { + return spec.pixels; +} + +/* ------------------------------------------------------------------ * + * Duplicate detection against the previous article + * ------------------------------------------------------------------ */ + +/** + * @param {string} text + * @returns {Set} + */ +function shingles(text, size) { + const normalized = String(text ?? '') + .toLowerCase() + .replace(/[\s\p{P}\p{S}]+/gu, ''); + const set = new Set(); + if (normalized.length === 0) return set; + if (normalized.length < size) { + set.add(normalized); + return set; + } + for (let i = 0; i <= normalized.length - size; i += 1) { + set.add(normalized.slice(i, i + size)); + } + return set; +} + +/** + * @param {Set} a + * @param {Set} b + * @returns {number} + */ +function jaccard(a, b) { + if (a.size === 0 || b.size === 0) return 0; + let intersection = 0; + for (const item of a) if (b.has(item)) intersection += 1; + const union = a.size + b.size - intersection; + return union === 0 ? 0 : intersection / union; +} + +/** + * @param {any} left + * @param {any} right + * @returns {{ score: number, title: number, body: number, key: number }} + */ +function similarity(left, right) { + const title = jaccard(shingles(`${left.title ?? ''} ${left.topic ?? ''}`, 2), shingles(`${right.title ?? ''} ${right.topic ?? ''}`, 2)); + const body = jaccard(shingles(left.body ?? '', 3), shingles(right.body ?? '', 3)); + const leftKey = new Set(keyPoints(left.body ?? '', 4)); + const rightKey = new Set(keyPoints(right.body ?? '', 4)); + let shared = 0; + for (const item of leftKey) if (rightKey.has(item)) shared += 1; + const key = leftKey.size === 0 || rightKey.size === 0 ? 0 : shared / Math.min(leftKey.size, rightKey.size); + const score = title * 0.35 + body * 0.5 + key * 0.15; + return { score: Math.round(score * 1000) / 10, title: Math.round(title * 100), body: Math.round(body * 100), key: Math.round(key * 100) }; +} + +/** + * @param {any} draft + * @param {any[]} allDrafts + * @returns {{ score: number, verdict: string, tone: string, compared: any[] }} + */ +export function checkDuplicate(draft, allDrafts) { + const others = allDrafts.filter( + (item) => item.id !== draft.id && item.articleId !== draft.articleId && String(item.body ?? '').trim(), + ); + const published = others + .filter((item) => item.status === 'published_api' || item.status === 'published_manual') + .sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt))); + const recentDrafts = others + .filter((item) => item.status !== 'published_api' && item.status !== 'published_manual') + .sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt))); + + /** @type {any[]} */ + const compared = []; + const push = (/** @type {any} */ item, /** @type {string} */ relation) => { + if (!item) return; + const sim = similarity(draft, item); + compared.push({ + id: item.id, + articleId: item.articleId, + version: item.version, + title: item.title || item.topic || '(未命名)', + status: item.status, + relation, + score: sim.score, + detail: `标题重合 ${sim.title}% · 正文重合 ${sim.body}% · 要点重合 ${sim.key}%`, + }); + }; + + push(published[0], '上一篇已发布文章'); + push(recentDrafts[0], '上一条草稿'); + + if (compared.length === 0) { + return { + score: 0, + verdict: '没有可比对的历史文章', + tone: 'neutral', + compared: [], + }; + } + + const top = compared.slice().sort((a, b) => b.score - a.score)[0]; + const score = top.score; + let verdict = '与上一篇基本不重复'; + let tone = 'ok'; + if (score >= 65) { + verdict = '与上一篇高度重复,建议更换切入点或素材'; + tone = 'danger'; + } else if (score >= 35) { + verdict = '与上一篇存在部分重合,建议补充新内容'; + tone = 'warn'; + } + return { score, verdict, tone, compared: compared.sort((a, b) => b.score - a.score) }; +} + +/* ------------------------------------------------------------------ * + * Publish-ready export (公众号 editor friendly, inline styles only) + * ------------------------------------------------------------------ */ + +/** + * @param {string} text + * @returns {string} + */ +function escapeHtml(text) { + return String(text ?? '') + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"'); +} + +/** + * @param {string} text + * @returns {string} + */ +function inlineEmphasis(text) { + return escapeHtml(text).replace(/\*\*([^*]+)\*\*/g, '$1'); +} + +/** + * @param {any} style + * @returns {Record} + */ +function bodyTokens(style) { + const palette = style.palette || ['#1f2328', '#5b6470', '#e8eaed']; + const accent = palette[1] || '#2563eb'; + const text = palette[0] || '#1f2328'; + const muted = palette[2] || '#e8eaed'; + const density = style.bodyStyle === 'dense' + ? { size: '15px', line: '1.8', gap: '20px' } + : style.bodyStyle === 'airy' + ? { size: '16px', line: '1.9', gap: '26px' } + : { size: '16px', line: '1.75', gap: '22px' }; + return { + ACCENT: accent, + TEXT: text, + MUTED: muted, + size: density.size, + line: density.line, + gap: density.gap, + }; +} + +/** + * Build the standalone, copy-pasteable 公众号 body HTML. + * + * 公众号 strips