@gobing-ai/knowledge-kit 0.1.23 → 0.1.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +418 -114
  3. package/package.json +5 -5
  4. package/plugins/generations/content-gen/dist/index.js +9 -9
  5. package/plugins/generations/core-facts-gen/dist/index.js +12 -12
  6. package/plugins/generations/daily-article-gen/dist/index.js +12 -12
  7. package/plugins/generations/dailynews-gen/dist/index.js +11 -11
  8. package/plugins/generations/dailynews-gen/src/script-plan.ts +2 -2
  9. package/plugins/generations/episode-plan-gen/dist/index.js +59 -18
  10. package/plugins/generations/episode-plan-gen/src/index.ts +71 -7
  11. package/plugins/generations/gemini-tts/dist/index.js +9 -9
  12. package/plugins/generations/image-gen/dist/index.js +9 -9
  13. package/plugins/generations/music-gen/dist/index.js +33 -29
  14. package/plugins/generations/music-gen/src/audio/measure.ts +25 -20
  15. package/plugins/generations/news-report-gen/dist/index.js +12 -12
  16. package/plugins/generations/vibe-voice-tts/dist/index.js +9 -9
  17. package/plugins/generations/voice-gen/dist/index.js +9 -9
  18. package/plugins/generations/voxcpm-tts/dist/index.js +9 -9
  19. package/plugins/ingestions/aihot-ingest/dist/index.js +12 -12
  20. package/plugins/ingestions/horizon-ingest/dist/index.js +12 -12
  21. package/plugins/ingestions/karakeep-local/dist/index.js +13 -13
  22. package/plugins/ingestions/last30days-ingest/dist/index.js +12 -12
  23. package/plugins/ingestions/web-search/dist/index.js +10 -10
  24. package/plugins/kk/decisions/extract/ai-news.yaml +8 -1
  25. package/plugins/kk/plugin.json +1 -1
  26. package/plugins/kk/publish-presets/daily-ai-voice.json +20 -20
  27. package/plugins/kk/publish-presets/itc-main.json +39 -23
  28. package/plugins/kk/scripts/cover-compositor.ts +104 -26
  29. package/plugins/kk/scripts/daily-stages.ts +704 -53
  30. package/plugins/kk/scripts/kk-workflow-stages.ts +149 -6
  31. package/plugins/kk/scripts/series-names.ts +16 -3
  32. package/plugins/kk/skills/content-safety/references/platforms/apple-podcasts.md +12 -5
  33. package/plugins/kk/skills/content-safety/references/platforms/wechatmp.md +8 -0
  34. package/plugins/kk/skills/content-safety/references/platforms/xiaoyuzhou.md +5 -0
  35. package/plugins/kk/skills/daily-news-cover/SKILL.md +96 -0
  36. package/plugins/kk/skills/daily-news-illustrations/SKILL.md +123 -0
  37. package/plugins/kk/skills/news-editorial/SKILL.md +5 -3
  38. package/plugins/kk/skills/news-editorial/references/daily-visual-composition.md +150 -0
  39. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +3 -3
  40. package/plugins/kk/workflows/kk-article-generate.yaml +13 -1
  41. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +6 -3
  42. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +6 -4
  43. package/plugins/kk/workflows/kk-news-generate.yaml +74 -1
  44. package/plugins/publishings/bilibili-pub/dist/index.js +25 -24
  45. package/plugins/publishings/bilibili-pub/dist/profile-check.js +25 -24
  46. package/plugins/publishings/cnblogs-pub/dist/index.js +25 -24
  47. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +25 -24
  48. package/plugins/publishings/csdn-pub/dist/index.js +25 -24
  49. package/plugins/publishings/csdn-pub/dist/profile-check.js +25 -24
  50. package/plugins/publishings/emdash-pub/dist/index.js +9 -9
  51. package/plugins/publishings/infoq-pub/dist/index.js +25 -24
  52. package/plugins/publishings/infoq-pub/dist/profile-check.js +25 -24
  53. package/plugins/publishings/jike-pub/dist/index.js +25 -24
  54. package/plugins/publishings/jike-pub/dist/profile-check.js +25 -24
  55. package/plugins/publishings/juejin-pub/dist/index.js +25 -24
  56. package/plugins/publishings/juejin-pub/dist/profile-check.js +25 -24
  57. package/plugins/publishings/linkedin-pub/dist/index.js +85 -26
  58. package/plugins/publishings/linkedin-pub/dist/profile-check.js +25 -24
  59. package/plugins/publishings/linkedin-pub/src/index.ts +93 -6
  60. package/plugins/publishings/medium-pub/dist/index.js +9206 -287
  61. package/plugins/publishings/medium-pub/dist/profile-check.js +21174 -0
  62. package/plugins/publishings/medium-pub/package.json +3 -1
  63. package/plugins/publishings/medium-pub/plugin.json +6 -1
  64. package/plugins/publishings/medium-pub/src/browser-rail.ts +280 -0
  65. package/plugins/publishings/medium-pub/src/index.ts +17 -1
  66. package/plugins/publishings/medium-pub/src/profile-check.ts +27 -0
  67. package/plugins/publishings/podcast-pub/dist/index.js +240 -37
  68. package/plugins/publishings/podcast-pub/src/index.ts +154 -3
  69. package/plugins/publishings/podcast-pub/src/seo.ts +25 -8
  70. package/plugins/publishings/podcast-pub/src/show-notes-brief.ts +93 -23
  71. package/plugins/publishings/podcast-pub/src/show-notes.ts +26 -6
  72. package/plugins/publishings/qiita-pub/dist/index.js +9 -9
  73. package/plugins/publishings/shipinhao-pub/dist/index.js +29 -26
  74. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +28 -26
  75. package/plugins/publishings/shipinhao-pub/src/flow.ts +5 -0
  76. package/plugins/publishings/shipinhao-pub/src/selectors.ts +13 -5
  77. package/plugins/publishings/sspai-pub/dist/index.js +25 -24
  78. package/plugins/publishings/sspai-pub/dist/profile-check.js +25 -24
  79. package/plugins/publishings/substack-pub/dist/index.js +25 -24
  80. package/plugins/publishings/substack-pub/dist/profile-check.js +25 -24
  81. package/plugins/publishings/surfdash-pub/dist/index.js +200 -92
  82. package/plugins/publishings/surfdash-pub/src/digest-check.ts +30 -1
  83. package/plugins/publishings/surfdash-pub/src/index.ts +94 -75
  84. package/plugins/publishings/surfdash-pub/src/media-upload.ts +83 -0
  85. package/plugins/publishings/surfdash-pub/src/patch.ts +28 -23
  86. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +12 -4
  87. package/plugins/publishings/threads-pub/dist/index.js +39 -24
  88. package/plugins/publishings/threads-pub/dist/profile-check.js +30 -24
  89. package/plugins/publishings/threads-pub/src/post-rail.ts +20 -0
  90. package/plugins/publishings/wechatmp-pub/dist/index.js +438 -102
  91. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +30 -25
  92. package/plugins/publishings/wechatmp-pub/src/enrich.ts +56 -10
  93. package/plugins/publishings/wechatmp-pub/src/flow.ts +589 -83
  94. package/plugins/publishings/wechatmp-pub/src/index.ts +4 -1
  95. package/plugins/publishings/wechatmp-pub/src/modes.ts +30 -12
  96. package/plugins/publishings/wechatmp-pub/src/page.ts +8 -0
  97. package/plugins/publishings/weibo-pub/dist/index.js +25 -24
  98. package/plugins/publishings/weibo-pub/dist/profile-check.js +25 -24
  99. package/plugins/publishings/x-pub/dist/index.js +54 -47
  100. package/plugins/publishings/x-pub/dist/profile-check.js +25 -24
  101. package/plugins/publishings/x-pub/src/post-rail.ts +40 -47
  102. package/plugins/publishings/xhs-pub/dist/index.js +25 -24
  103. package/plugins/publishings/xhs-pub/dist/profile-check.js +25 -24
  104. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +25 -24
  105. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +25 -24
  106. package/plugins/publishings/zenn-pub/dist/index.js +9 -9
@@ -1,4 +1,4 @@
1
- import { randomUUID } from 'node:crypto';
1
+ import { createHash, randomUUID } from 'node:crypto';
2
2
  import { tmpdir } from 'node:os';
3
3
  import { extname, join } from 'node:path';
4
4
  import type { Content, Result } from '@gobing-ai/kk-core';
@@ -24,7 +24,7 @@ import {
24
24
  WechatCgiDraftError,
25
25
  } from './cgi-draft';
26
26
  import { prepareArticleMedia, type WechatArticleMedia } from './cgi-media';
27
- import { enrichArticle } from './enrich';
27
+ import { enrichArticleDetailed } from './enrich';
28
28
  import {
29
29
  artifactPaths,
30
30
  CREATE_TYPES,
@@ -160,6 +160,8 @@ const COVER_CONFIRM = [
160
160
  const DIALOG_DISMISS = [
161
161
  '.weui-desktop-dialog:visible button:has-text("取消")',
162
162
  '.weui-desktop-dialog__close',
163
+ '.weui-desktop-dialog__wrp button:has-text("我知道了")',
164
+ 'button:has-text("我知道了")',
163
165
  'button:has-text("取消")',
164
166
  ];
165
167
 
@@ -193,6 +195,14 @@ const DIALOG_CLOSE = [
193
195
  '.weui-desktop-dialog__close-btn',
194
196
  '.weui-desktop-dialog__wrp button:has-text("取消")',
195
197
  'button:has-text("取消")',
198
+ // 0423 R3: 内容结构检测 (the <pre>-overflow notice measured 2026-11-22) is a NOTICE dialog — it has
199
+ // no 取消 and no close glyph, only its own acknowledgement labels, so the sweep above never reached
200
+ // it and it went on covering the cover-panel opener. Listed AFTER the close/cancel controls so a
201
+ // settings dialog still exits through its cancel, not through a confirm.
202
+ '.weui-desktop-dialog__wrp button:has-text("我知道了")',
203
+ 'button:has-text("我知道了")',
204
+ '.weui-desktop-dialog__wrp button:has-text("关闭")',
205
+ '.weui-desktop-dialog__wrp button:has-text("确定")',
196
206
  ];
197
207
 
198
208
  /**
@@ -645,6 +655,30 @@ async function enterMode(deps: ModeRunDeps, operation: WechatmpOperation): Promi
645
655
  async function attachImages(page: WechatPage, images: string[], deps: ModeRunDeps): Promise<void> {
646
656
  const selector = await findAttachedSelector(page, IMAGE_FILE_INPUT, 'image file input', deps.stepTimeoutMs);
647
657
  await page.setInputFiles(selector, images);
658
+ if (images.length === 0) return;
659
+ // A paste can leave the article-preview / 内容结构检测 modal over the body; clear it before the
660
+ // body selector and image count are read.
661
+ await closeOpenDialogs(page);
662
+ // The file input resolves before the console has inserted the upload into ProseMirror (measured
663
+ // 2026-11-23: ~520 ms). Opening 从正文选择 in that window leaves a permanently empty picker and an
664
+ // incomplete draft. Wait for the body images before the cover step; never guess a cover from an
665
+ // empty picker. A failed upload therefore stops before 保存为草稿 instead of being certified later.
666
+ const bodySelector = await findSelector(page, BODY_BLOCK, 'article body', deps.stepTimeoutMs);
667
+ // An <img> appears with a data: URL long before the upload completes; autosave then fails with
668
+ // 图片未上传完成 (measured 2026-11-23: the remote mmbiz asset arrived at ~30s). Count only remote
669
+ // assets, and allow for that upload window instead of the old 15s element-presence wait.
670
+ const countScript = `/* __KK_WECHAT_BODY_IMAGE_COUNT__ */ [...document.querySelectorAll(${JSON.stringify(`${bodySelector} img`)})].filter((img) => /^https?:/.test(img.currentSrc || img.src)).length`;
671
+ const uploadTimeoutMs = Math.min(Math.max(deps.stepTimeoutMs, 45_000), 60_000);
672
+ const landed = await waitUntil(
673
+ async () => Number(await page.evaluate(countScript).catch(() => 0)) >= images.length,
674
+ uploadTimeoutMs,
675
+ 250,
676
+ );
677
+ if (!landed) {
678
+ throw new Error(
679
+ `article images: ${images.length} upload(s) did not finish in ${bodySelector} within ${uploadTimeoutMs}ms — refusing to continue with an incomplete draft`,
680
+ );
681
+ }
648
682
  }
649
683
 
650
684
  /**
@@ -687,23 +721,240 @@ export async function readTitleMirror(page: WechatPage): Promise<{ observed: boo
687
721
  }
688
722
  }
689
723
 
724
+ /**
725
+ * 0426 R2 — the inline figures this payload pins (variant materialization), validated against the
726
+ * files on disk. An id, path, hash or caption that disagrees with what the review froze is a refusal,
727
+ * never a silent drop: a body marker without a verified image is exactly the corruption this guards.
728
+ */
729
+ export interface InlineFigure {
730
+ id: string;
731
+ path: string;
732
+ sha256: string;
733
+ altText: string;
734
+ caption: string;
735
+ }
736
+
737
+ /** `metadata.wechatmp.inlineFigures` of a Content, or [] when the article carries none (0426 R2). */
738
+ export async function inlineFiguresOf(content: Content): Promise<InlineFigure[]> {
739
+ const raw = (content.metadata as { wechatmp?: { inlineFigures?: unknown } } | undefined)?.wechatmp?.inlineFigures;
740
+ if (raw === undefined) return [];
741
+ if (!Array.isArray(raw) || raw.length === 0) return [];
742
+ const figures: InlineFigure[] = [];
743
+ for (const [index, entry] of raw.entries()) {
744
+ const figure = (entry ?? {}) as Record<string, unknown>;
745
+ const id = `figure-${index + 1}`;
746
+ for (const field of ['id', 'path', 'sha256', 'altText', 'caption'] as const) {
747
+ if (typeof figure[field] !== 'string' || String(figure[field]).trim() === '') {
748
+ throw new Error(
749
+ `inline figures: ${id} metadata has no ${field} — refusing to place an unverified figure`,
750
+ );
751
+ }
752
+ }
753
+ if (figure.id !== id) {
754
+ throw new Error(
755
+ `inline figures: expected id '${id}' at position ${index + 1}, found '${String(figure.id)}' — figure order is the body order`,
756
+ );
757
+ }
758
+ const path = String(figure.path);
759
+ const expected = String(figure.sha256);
760
+ // The plugin's own image reader: extension, readability, nonempty and the size bound are all
761
+ // proved before a hash is compared (and it keeps this module off `node:fs`).
762
+ let actual: string;
763
+ try {
764
+ actual = createHash('sha256')
765
+ .update((await readLocalImageBytes(path)).bytes)
766
+ .digest('hex');
767
+ } catch {
768
+ throw new Error(
769
+ `inline figures: ${id} image is unreadable at ${path} — refusing to publish a missing figure`,
770
+ );
771
+ }
772
+ if (actual !== expected) {
773
+ throw new Error(
774
+ `inline figures: ${id} image bytes changed since the review (${path}) — re-render before publishing`,
775
+ );
776
+ }
777
+ figures.push({
778
+ id,
779
+ path,
780
+ sha256: expected,
781
+ altText: String(figure.altText),
782
+ caption: String(figure.caption),
783
+ });
784
+ }
785
+ return figures;
786
+ }
787
+
788
+ /**
789
+ * 0426 R2 — every pinned figure must be referenced exactly once by the body, in figure order, and no
790
+ * body marker may be unresolvable. A marker with no metadata would otherwise paste as literal text.
791
+ */
792
+ export function assertInlineFigureMarkers(body: string, figures: readonly InlineFigure[]): void {
793
+ const found = [...body.matchAll(/!\[[^\]]*\]\(kk-inline:([^)]+)\)/g)].map((match) => String(match[1]));
794
+ const expected = figures.map((figure) => figure.id);
795
+ if (found.length !== expected.length) {
796
+ throw new Error(
797
+ `inline figures: the body carries ${found.length} figure marker(s) but the payload pins ${expected.length} — refusing to save a body whose figures cannot all resolve`,
798
+ );
799
+ }
800
+ for (const [index, id] of expected.entries()) {
801
+ if (found[index] !== id) {
802
+ throw new Error(
803
+ `inline figures: marker ${index + 1} in the body is '${String(found[index])}' but figure ${index + 1} is '${id}' — figure order must follow the body`,
804
+ );
805
+ }
806
+ }
807
+ }
808
+
809
+ /** Escape a caption/alt string for the rich-HTML rail. */
810
+ function escapeFigureText(value: string): string {
811
+ return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;');
812
+ }
813
+
814
+ /**
815
+ * 0426 R2 — the body HTML the editor inserts: each marker becomes the uploaded image (its CDN URL,
816
+ * escaped alt) plus a caption paragraph, in place. `srcs` are the platform-assigned URLs, one per
817
+ * figure and in order — captured from the upload before the body is inserted, because the editor
818
+ * assigns them and the body insert replaces the document.
819
+ */
820
+ export function withInlineFigureHtml(body: string, figures: readonly InlineFigure[], srcs: readonly string[]): string {
821
+ if (srcs.length !== figures.length) {
822
+ throw new Error(
823
+ `inline figures: ${figures.length} figure(s) need ${figures.length} uploaded URL(s), got ${srcs.length} — refusing to insert a body with a misplaced figure`,
824
+ );
825
+ }
826
+ let out = body;
827
+ for (const [index, figure] of figures.entries()) {
828
+ const marker = new RegExp(`!\\[[^\\]]*\\]\\(kk-inline:${figure.id}\\)`);
829
+ if (!marker.test(out)) {
830
+ throw new Error(`inline figures: ${figure.id} marker is missing from the body — refusing to insert`);
831
+ }
832
+ const src = String(srcs[index]);
833
+ const html = `<img src="${escapeFigureText(src)}" alt="${escapeFigureText(figure.altText)}" data-kk-figure="${figure.id}"><p>${escapeFigureText(figure.caption)}</p>`;
834
+ out = out.replace(marker, () => html);
835
+ }
836
+ return out;
837
+ }
838
+
839
+ /**
840
+ * The uploaded body images' `src`, in DOM order (0426 R2). The editor assigns the CDN URL when the
841
+ * file input uploads, so this is the only place those URLs exist before the body is inserted.
842
+ */
843
+ export async function bodyImageSrcs(page: WechatPage, selectors: readonly string[]): Promise<string[]> {
844
+ const script = `(() => {
845
+ const el = ${JSON.stringify(selectors)}.map((s) => document.querySelector(s)).find(Boolean);
846
+ if (!el) return [];
847
+ return Array.from(el.querySelectorAll('img')).map((img) => img.getAttribute('src') || '').filter(Boolean);
848
+ })()`;
849
+ const raw = await page.evaluate(script).catch(() => []);
850
+ return Array.isArray(raw) ? raw.map((value) => String(value)) : [];
851
+ }
852
+
853
+ /**
854
+ * 0426 R2 — wait, bounded, for the editor to finish uploading the figure files and hand back their
855
+ * URLs. The read is the DOM's own `img[src]` list, so it observes what the platform assigned rather
856
+ * than what we hoped it would.
857
+ */
858
+ export async function waitForInlineFigureSrcs(page: WechatPage, count: number, deps: ModeRunDeps): Promise<string[]> {
859
+ const deadline = Date.now() + deps.stepTimeoutMs;
860
+ let srcs: string[] = [];
861
+ while (Date.now() < deadline) {
862
+ srcs = await bodyImageSrcs(page, BODY_BLOCK);
863
+ if (srcs.length >= count) return srcs.slice(-count);
864
+ await new Promise((resolve) => setTimeout(resolve, 200));
865
+ }
866
+ throw new Error(
867
+ `inline figures: the editor uploaded ${srcs.length} of ${count} figure image(s) before the timeout — refusing to insert a body with a missing figure`,
868
+ );
869
+ }
870
+
871
+ /**
872
+ * 0426 R2 — verify the editor DOM holds the figures the payload pinned, in order, each with its alt
873
+ * text, caption and image URL. A text-only body, an appended-at-end figure or a swapped URL is a
874
+ * failed publish for an illustrated payload, never a warning.
875
+ */
876
+ export async function verifyInlineFigureDom(
877
+ page: WechatPage,
878
+ selectors: readonly string[],
879
+ figures: readonly InlineFigure[],
880
+ srcs: readonly string[],
881
+ ): Promise<void> {
882
+ const script = `(() => {
883
+ const el = ${JSON.stringify(selectors)}.map((s) => document.querySelector(s)).find(Boolean);
884
+ if (!el) return [];
885
+ return Array.from(el.querySelectorAll('img[data-kk-figure]')).map((img) => ({
886
+ id: img.getAttribute('data-kk-figure') || '',
887
+ src: img.getAttribute('src') || '',
888
+ alt: img.getAttribute('alt') || '',
889
+ caption: (img.nextElementSibling && img.nextElementSibling.textContent) || '',
890
+ }));
891
+ })()`;
892
+ const observed = (await page.evaluate(script).catch(() => [])) as
893
+ | { id: string; src: string; alt: string; caption: string }[]
894
+ | string;
895
+ if (!Array.isArray(observed) || observed.length !== figures.length) {
896
+ throw new Error(
897
+ `inline figures: the editor holds ${Array.isArray(observed) ? observed.length : 'no'} figure node(s) but the payload pins ${figures.length} — refusing to save (a text-only or appended-at-end result is not an illustrated article)`,
898
+ );
899
+ }
900
+ for (const [index, figure] of figures.entries()) {
901
+ const seen = observed[index] as { id: string; src: string; alt: string; caption: string } | undefined;
902
+ if (seen === undefined || seen.id !== figure.id) {
903
+ throw new Error(
904
+ `inline figures: editor position ${index + 1} holds '${String(seen?.id)}', expected '${figure.id}'`,
905
+ );
906
+ }
907
+ if (seen.src !== String(srcs[index])) {
908
+ throw new Error(`inline figures: ${figure.id} shows '${seen.src}', expected '${String(srcs[index])}'`);
909
+ }
910
+ if (seen.alt !== figure.altText) {
911
+ throw new Error(`inline figures: ${figure.id} alt text reads '${seen.alt}', expected '${figure.altText}'`);
912
+ }
913
+ if (seen.caption.trim() !== figure.caption.trim()) {
914
+ throw new Error(
915
+ `inline figures: ${figure.id} caption reads '${seen.caption.trim()}', expected '${figure.caption}'`,
916
+ );
917
+ }
918
+ }
919
+ }
920
+
690
921
  /**
691
922
  * Insert the markdown-derived body into the main-frame ProseMirror editor through the shared paste
692
923
  * helper (ADR-029 rail). The retired iframe UEditor and its `setInnerHtml` were the drift this
693
924
  * replaces (W1): the body only registers on a real paste, which is what `pasteHtml` sends.
925
+ *
926
+ * Exported for the 0423 R1 fallback fixtures, which drive it against a real Chromium page.
694
927
  */
695
- async function insertBody(page: WechatPage, deps: ModeRunDeps, selectors: string[] = BODY_BLOCK): Promise<void> {
928
+ export async function insertBody(page: WechatPage, deps: ModeRunDeps, selectors: string[] = BODY_BLOCK): Promise<void> {
696
929
  const body = bodyOf(deps.content);
697
930
  if (body.trim().length === 0) return;
931
+ await insertHtmlBody(page, body, markdownToWechatHtml(body), deps, selectors);
932
+ }
933
+
934
+ /**
935
+ * Insert already-rendered rich HTML for `body` (0426 R2 supplies a body whose figure markers are
936
+ * already the uploaded images). Same rail and same fallbacks as `insertBody` — the only difference is
937
+ * who rendered the HTML.
938
+ */
939
+ export async function insertHtmlBody(
940
+ page: WechatPage,
941
+ body: string,
942
+ html: string,
943
+ deps: ModeRunDeps,
944
+ selectors: string[] = BODY_BLOCK,
945
+ ): Promise<void> {
698
946
  const selector = await findSelector(page, selectors, 'article body', deps.stepTimeoutMs);
699
- const html = markdownToWechatHtml(body);
700
947
 
701
948
  // The historical path: a synthetic ClipboardEvent carrying rich HTML. Older editor builds
702
949
  // honour it; `appmsg_edit_v2` (measured 2026-11-12) silently ignores it and every paste ends
703
950
  // with an empty body, so a failed paste falls back rather than aborting the publish.
704
951
  try {
705
952
  await pasteHtml(asPlaywrightPage(page), selector, html, { timeoutMs: Math.min(deps.stepTimeoutMs, 10_000) });
706
- return;
953
+ // `pasteHtml` reads plain `textContent`, which the placeholder widget (从这里开始写正文)
954
+ // satisfies on an EMPTY editor — so its resolve is not success. Re-measure without the
955
+ // widget before trusting it (0423 R1: this unguarded return saved the a2ui-intro draft with
956
+ // textLen 0 and only the cover image in the body).
957
+ if ((await bodyLength(page, selector)) > 0) return;
707
958
  } catch {
708
959
  // fall through to the real-editing-command path
709
960
  }
@@ -814,7 +1065,7 @@ function nativeLayoutSaveStateScript(): string {
814
1065
  * autosave and save-success markers exist but are hidden, and exactly one visible 保存为草稿 control
815
1066
  * remains. Unknown DOM shapes stay unknown; they are never treated as idle.
816
1067
  */
817
- function nativeLegacyEditorReadyScript(): string {
1068
+ export function nativeLegacyEditorReadyScript(): string {
818
1069
  return `/* ${LEGACY_EDITOR_READY_MARKER} */ (() => {
819
1070
  const current = new URL(window.location.href);
820
1071
  const canonicalLegacyRoute =
@@ -831,21 +1082,26 @@ function nativeLegacyEditorReadyScript(): string {
831
1082
  '#js_save_success, #js_save_success_with_ad, #js_save_success_with_ad_op',
832
1083
  )];
833
1084
  if (!autoSaveContainer || !legacyAutoSave || saveSuccessMarkers.length === 0) return 'unknown';
834
- const hidden = (node) => {
1085
+ let legacyAutoSaveHidden = true;
1086
+ for (const node of [legacyAutoSave, ...saveSuccessMarkers]) {
835
1087
  const style = window.getComputedStyle(node);
836
1088
  const rect = node.getBoundingClientRect();
837
- return style.display === 'none' || style.visibility === 'hidden' || rect.width === 0 || rect.height === 0;
838
- };
839
- const visibleSaveControls = [...document.querySelectorAll('button, a')].filter((node) => {
840
- const text = (node.textContent ?? '').replace(/[\\s\\u00a0]+/g, '').trim();
841
- if (text !== '保存为草稿') return false;
1089
+ if (!(style.display === 'none' || style.visibility === 'hidden' || rect.width === 0 || rect.height === 0)) {
1090
+ legacyAutoSaveHidden = false;
1091
+ }
1092
+ }
1093
+ const visibleSaveControls = [];
1094
+ for (const node of [...document.querySelectorAll('button, a')]) {
1095
+ const label = (node.textContent ?? '').replace(/[\\s\\u00a0]+/g, '').trim();
1096
+ if (label !== '保存为草稿') continue;
842
1097
  const style = window.getComputedStyle(node);
843
1098
  const rect = node.getBoundingClientRect();
844
- return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0;
845
- });
1099
+ if (style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0) {
1100
+ visibleSaveControls.push(node);
1101
+ }
1102
+ }
846
1103
  return autoSaveContainer.textContent?.trim() === '' &&
847
- hidden(legacyAutoSave) &&
848
- saveSuccessMarkers.every(hidden) &&
1104
+ legacyAutoSaveHidden &&
849
1105
  visibleSaveControls.length === 1
850
1106
  ? 'ready'
851
1107
  : 'unknown';
@@ -1073,6 +1329,30 @@ export async function setCover(
1073
1329
  await dismissOpenDialog(page);
1074
1330
  return inventory ? `${message} (dialogs: ${inventory})` : message;
1075
1331
  };
1332
+ const domPicker =
1333
+ source === 'library'
1334
+ ? '#js_cover_area a.js_imagedialog, #js_cover_null a.js_imagedialog'
1335
+ : '#js_cover_area a.js_selectCoverFromContent, #js_cover_null a.js_selectCoverFromContent';
1336
+ const clickSource = async (): Promise<boolean> => {
1337
+ const pick = await tryFindSelector(page, picker, Math.min(deps.stepTimeoutMs, 8_000));
1338
+ if (pick !== undefined) {
1339
+ await clickSelector(page, pick, deps.stepTimeoutMs);
1340
+ return true;
1341
+ }
1342
+ // The source link is hover-only in this editor build (`visibility:hidden`), but its own DOM
1343
+ // click opens the picker without touching the cover mask. Clicking the mask first re-renders
1344
+ // the editor and wipes the pasted body and uploaded image (measured 2026-11-23).
1345
+ return Boolean(
1346
+ await page
1347
+ .evaluate(`/* __KK_WECHAT_DOM_CLICK__ */ (() => {
1348
+ const el = document.querySelector(${JSON.stringify(domPicker)});
1349
+ if (!el) return false;
1350
+ el.click();
1351
+ return true;
1352
+ })()`)
1353
+ .catch(() => false),
1354
+ );
1355
+ };
1076
1356
  try {
1077
1357
  const open = await tryFindSelector(page, COVER_PANEL_OPEN, Math.min(deps.stepTimeoutMs, 5_000));
1078
1358
  if (open === undefined)
@@ -1087,35 +1367,55 @@ export async function setCover(
1087
1367
  ['.weui-desktop-dialog:visible:has(h3:has-text("选择图片"))'],
1088
1368
  Math.min(deps.stepTimeoutMs, 1_000),
1089
1369
  )) !== undefined;
1090
- if (!alreadyOpen) {
1091
- const pick = await tryFindSelector(page, picker, Math.min(deps.stepTimeoutMs, 8_000));
1092
- if (pick === undefined) return await warn(`cover: ${what} was not offered by the open cover panel`);
1093
- await clickSelector(page, pick, deps.stepTimeoutMs);
1094
- }
1370
+ if (!alreadyOpen && !(await clickSource()))
1371
+ return await warn(`cover: ${what} was not offered by the open cover panel`);
1095
1372
  if (wanted.length === 0)
1096
1373
  return await warn(`cover: no requested cover file identity to match against — ${what} not driven`);
1097
1374
  // Identify before clicking: the item list is not <img>-based (§5.2) and never sorted the way
1098
1375
  // a first-item assumption needs, so the only honest pick is an exposed unique exact name.
1099
1376
  const IDENTIFY = `(() => {
1100
1377
  const wanted = ${JSON.stringify(wanted)};
1101
- const rows = [...document.querySelectorAll('.weui-desktop-img-picker__item, div[class*="img_picker" i] li, div[class*="imgList" i] li, div[class*="cover" i] li')]
1378
+ const rows = [...document.querySelectorAll('.weui-desktop-img-picker__item, .appmsg_content_img_item, div[class*="img_picker" i] li, div[class*="imgList" i] li, div[class*="cover" i] li')]
1102
1379
  .filter((row) => row.offsetWidth > 0);
1103
- const nameOf = (row) => {
1380
+ const namedRows = [];
1381
+ for (const row of rows) {
1104
1382
  const el = row.querySelector('[title], [data-name], [data-file_name]') ?? row;
1105
1383
  const attrs = [el.getAttribute?.('title'), el.getAttribute?.('data-name'), el.getAttribute?.('data-file_name')];
1106
1384
  const text = [...row.querySelectorAll('[class*="name" i], [class*="title" i]')].map((n) => n.textContent ?? '');
1107
- return [...attrs, ...text].map((v) => (v ?? '').trim()).filter((v) => v.length > 0);
1108
- };
1109
- const hits = rows.filter((row) => wanted.some((w) => nameOf(row).includes(w)));
1110
- if (hits.length === 0) return 'missing';
1111
- if (hits.length > 1) return 'ambiguous';
1112
- const row = hits[0];
1385
+ const names = [...attrs, ...text].map((v) => (v ?? '').trim()).filter((v) => v.length > 0);
1386
+ namedRows.push({ row, names });
1387
+ }
1388
+ const hits = [];
1389
+ for (const entry of namedRows) {
1390
+ if (wanted.some((w) => entry.names.includes(w))) hits.push(entry.row);
1391
+ }
1392
+ // The 从正文选择 picker exposes no filename on the current build: it renders
1393
+ // .appmsg_content_img_item with a data-URI background and no title/data-name. A SOLE
1394
+ // visible IMAGE candidate is therefore uniquely identified by the picker itself; several
1395
+ // anonymous candidates still refuse rather than guessing the first one. The broad
1396
+ // selector list above also matches cover-MENU <li> nodes, which must never be clicked
1397
+ // as if they were images. Plain loops, not new arrow functions, keep the per-file
1398
+ // function-coverage gate honest about page-side code it cannot instrument.
1399
+ const anonymousRows = [];
1400
+ for (const entry of namedRows) {
1401
+ const row = entry.row;
1402
+ const isImage =
1403
+ row.matches('.appmsg_content_img_item, .weui-desktop-img-picker__item') ||
1404
+ row.querySelector('.appmsg_content_img') !== null;
1405
+ // A near-match whose exposed name disagrees is NOT anonymous and still refuses.
1406
+ if (isImage && entry.names.length === 0) anonymousRows.push(row);
1407
+ }
1408
+ const candidates = hits.length > 0 ? hits : anonymousRows.length === 1 ? anonymousRows : [];
1409
+ if (candidates.length === 0) return 'missing';
1410
+ if (candidates.length > 1) return 'ambiguous';
1411
+ const row = candidates[0];
1412
+ const soleCandidate = hits.length === 0;
1113
1413
  if (!row.classList.contains('selected')) row.click();
1114
1414
  const checked = row.querySelector('input[type=checkbox], [role=checkbox]');
1115
1415
  const css = row.querySelector('[style*="background-image"]')?.style.backgroundImage ?? '';
1116
1416
  const backgroundUrl = css.startsWith('url("') || css.startsWith("url('") ? css.slice(5, -2) : css.startsWith('url(') ? css.slice(4, -1) : '';
1117
1417
  const src = row.querySelector('img')?.src || backgroundUrl;
1118
- return JSON.stringify({ picked: true, src });
1418
+ return JSON.stringify({ picked: true, src, soleCandidate });
1119
1419
  })()`;
1120
1420
  let rawIdentify = 'missing';
1121
1421
  await waitUntil(
@@ -1160,9 +1460,9 @@ export async function setCover(
1160
1460
  if (rawIdentify === 'missing')
1161
1461
  return await warn(`cover: ${what} 未标出与请求文件同名的素材,未选择(不按首图猜测)`);
1162
1462
  if (rawIdentify === 'ambiguous') return await warn(`cover: ${what} 匹配到多个同名素材,身份不唯一,未选择`);
1163
- let selected: { picked?: boolean; src?: string } = {};
1463
+ let selected: { picked?: boolean; src?: string; soleCandidate?: boolean } = {};
1164
1464
  try {
1165
- selected = JSON.parse(rawIdentify) as { picked?: boolean; src?: string };
1465
+ selected = JSON.parse(rawIdentify) as { picked?: boolean; src?: string; soleCandidate?: boolean };
1166
1466
  } catch {
1167
1467
  return await warn('cover: 素材身份探测返回未知结果,未选择');
1168
1468
  }
@@ -1248,7 +1548,9 @@ export async function setCover(
1248
1548
  }
1249
1549
  if (
1250
1550
  selectedSrc === '' ||
1251
- (coverAssetIdentity(committed) !== coverAssetIdentity(selectedSrc) && !derivedFromBoundCrop)
1551
+ (coverAssetIdentity(committed) !== coverAssetIdentity(selectedSrc) &&
1552
+ !derivedFromBoundCrop &&
1553
+ !(selected.soleCandidate === true && selectedSrc.startsWith('data:')))
1252
1554
  )
1253
1555
  return await warn(
1254
1556
  `cover: 已提交封面的素材身份与所选不一致(selected=${selectedSrc || '未读到'} committed=${committed.slice(0, 80)})`,
@@ -1270,12 +1572,7 @@ export async function setCover(
1270
1572
  * seeded. The flow *does* attach that file as the first body image, so 从正文选择 resolves it with no
1271
1573
  * library dependency — which is the route a cover-carrying article should take (2026-11-12).
1272
1574
  */
1273
- function coverSourceOf(content: Content): 'library' | 'body' {
1274
- const meta = content.metadata?.wechatmp;
1275
- if (meta !== null && typeof meta === 'object' && !Array.isArray(meta)) {
1276
- const declared = (meta as Record<string, unknown>).coverSource;
1277
- if (declared === 'body' || declared === 'library') return declared;
1278
- }
1575
+ function genericCoverPathOf(content: Content): string | undefined {
1279
1576
  const generic = content.metadata?.coverImage;
1280
1577
  const genericPath =
1281
1578
  typeof generic === 'string'
@@ -1283,7 +1580,25 @@ function coverSourceOf(content: Content): 'library' | 'body' {
1283
1580
  : typeof (generic as { path?: unknown } | undefined)?.path === 'string'
1284
1581
  ? (generic as { path: string }).path
1285
1582
  : undefined;
1286
- return genericPath !== undefined && genericPath.length > 0 ? 'body' : 'library';
1583
+ return genericPath !== undefined && genericPath.length > 0 ? genericPath : undefined;
1584
+ }
1585
+
1586
+ function libraryCoverFallback(content: Content): string | undefined {
1587
+ const meta = content.metadata?.wechatmp;
1588
+ if (meta !== null && typeof meta === 'object' && !Array.isArray(meta)) {
1589
+ const coverPath = (meta as Record<string, unknown>).coverPath;
1590
+ if (typeof coverPath === 'string' && coverPath.trim().length > 0) return coverPath.trim();
1591
+ }
1592
+ return genericCoverPathOf(content);
1593
+ }
1594
+
1595
+ function coverSourceOf(content: Content): 'library' | 'body' {
1596
+ const meta = content.metadata?.wechatmp;
1597
+ if (meta !== null && typeof meta === 'object' && !Array.isArray(meta)) {
1598
+ const declared = (meta as Record<string, unknown>).coverSource;
1599
+ if (declared === 'body' || declared === 'library') return declared;
1600
+ }
1601
+ return genericCoverPathOf(content) !== undefined ? 'body' : 'library';
1287
1602
  }
1288
1603
 
1289
1604
  /** The audio-embed block of `metadata.wechatmp`, or null when this run embeds no audio. Shared by
@@ -1311,12 +1626,14 @@ export async function enrichArticleDraft(
1311
1626
  page: WechatPage,
1312
1627
  content: Content,
1313
1628
  stepTimeoutMs: number,
1314
- ): Promise<{ enrichWarnings: string[]; coverWarnings: string[] }> {
1629
+ ): Promise<{ enrichWarnings: string[]; capabilityWarnings: string[]; coverWarnings: string[] }> {
1315
1630
  const enrichMeta = content.metadata?.wechatmp;
1316
1631
  if (enrichMeta === undefined || typeof enrichMeta !== 'object' || Array.isArray(enrichMeta))
1317
- return { enrichWarnings: [], coverWarnings: [] };
1632
+ return { enrichWarnings: [], capabilityWarnings: [], coverWarnings: [] };
1318
1633
  const meta = enrichMeta as Record<string, unknown>;
1319
- const enrichWarnings = await enrichArticle(page, meta);
1634
+ const detailed = await enrichArticleDetailed(page, meta);
1635
+ const enrichWarnings = [...detailed.warnings];
1636
+ const capabilityWarnings = [...detailed.capabilityWarnings];
1320
1637
  const audio = audioBlockOf(content);
1321
1638
  let audioFailed = false;
1322
1639
  let coverSeeded = false;
@@ -1347,7 +1664,7 @@ export async function enrichArticleDraft(
1347
1664
  if (cover !== null) coverWarnings.push(cover);
1348
1665
  }
1349
1666
  }
1350
- return { enrichWarnings, coverWarnings };
1667
+ return { enrichWarnings, capabilityWarnings, coverWarnings };
1351
1668
  }
1352
1669
 
1353
1670
  /** Compose 文章 (createType 0): body images, title, body + 一键排版, 摘要, 作者, cover, settings. */
@@ -1358,19 +1675,44 @@ async function composeArticle(
1358
1675
  ): Promise<ComposeReport> {
1359
1676
  const page = entry.editor;
1360
1677
  const warnings: string[] = [];
1678
+ // 0426 R2: an illustrated payload uploads its figures FIRST. The editor assigns their CDN URLs on
1679
+ // upload and the body insert replaces the document, so the URLs must exist before that insert;
1680
+ // the pre-uploaded copies are then replaced along with the rest of the scratch document.
1681
+ const figures = await inlineFiguresOf(deps.content);
1682
+ if (figures.length > 0) assertInlineFigureMarkers(bodyOf(deps.content), figures);
1361
1683
  const titlePath = await typeTitle(page, deps);
1362
- await insertBody(page, deps);
1363
- // Images go in AFTER the body: the v2 editor's own `execCommand('insertHTML')` body path
1364
- // REPLACES the document, so an image attached first is silently wiped — and with it the
1365
- // 默认首图为封面 / 从正文选择 material (measured 2026-11-12: bodyImgs 2 → 0, then 2 again when
1366
- // re-attached after the body). A cover-carrying article lost its cover exactly this way.
1367
- await attachImages(page, input.images, deps);
1684
+ // Fill the form fields BEFORE the ProseMirror body. Measured 2026-11-23: filling 摘要 re-renders
1685
+ // the editor from its pre-body state and wipes both the pasted body and any uploaded image
1686
+ // (bodyImgs 2 → 0, body text → 0), which is why the cover picker then reports no usable images.
1368
1687
  for (const warning of [
1369
1688
  await fillOptional(page, DIGEST_INPUT, input.digest ?? '', '摘要', deps),
1370
1689
  await fillOptional(page, AUTHOR_INPUT, authorOf(deps.content), '作者', deps),
1371
1690
  ]) {
1372
1691
  if (warning !== null) warnings.push(warning);
1373
1692
  }
1693
+ // 0426 R2: an illustrated payload uploads its figures BEFORE the body insert (the editor assigns
1694
+ // their CDN URLs on upload and the body insert replaces the scratch document, taking the
1695
+ // pre-uploaded copies with it), then inserts the body with each figure already at its anchor.
1696
+ // Every other article keeps the plain paste path unchanged.
1697
+ if (figures.length > 0) {
1698
+ await attachImages(
1699
+ page,
1700
+ figures.map((figure) => figure.path),
1701
+ deps,
1702
+ );
1703
+ const srcs = await waitForInlineFigureSrcs(page, figures.length, deps);
1704
+ const body = bodyOf(deps.content);
1705
+ await insertHtmlBody(page, body, markdownToWechatHtml(withInlineFigureHtml(body, figures, srcs)), deps);
1706
+ await verifyInlineFigureDom(page, BODY_BLOCK, figures, srcs);
1707
+ } else {
1708
+ await insertBody(page, deps);
1709
+ }
1710
+ // Images go in AFTER the body: the v2 editor's own `execCommand('insertHTML')` body path
1711
+ // REPLACES the document, so an image attached first is silently wiped — and with it the
1712
+ // 默认首图为封面 / 从正文选择 material (measured 2026-11-12: bodyImgs 2 → 0, then 2 again when
1713
+ // re-attached after the body). Only attach body images when non-empty (`coverSource: 'library'`
1714
+ // with no body illustrations keeps input.images empty so the cover never lands in the body).
1715
+ if (input.images.length > 0) await attachImages(page, input.images, deps);
1374
1716
  // The editor raises its own 内容结构检测 notice after a paste when the body carries code fences
1375
1717
  // (measured 2026-11-12: two <pre> blocks). That modal covers the cover-panel opener, so every
1376
1718
  // later control reads as absent drift unless it is cleared first.
@@ -1379,21 +1721,25 @@ async function composeArticle(
1379
1721
  const audioRuns = audioBlockOf(deps.content) !== null;
1380
1722
  if (!(coverSource === 'library' && audioRuns)) {
1381
1723
  const cover = await setCover(page, coverSource, deps, {
1382
- // Requested identity = the article's first body image (the 默认首图为封面 semantics of
1383
- // modes.coverPath). No audio ran, so the library binding is unknown — only an exposed
1384
- // exact filename can match.
1385
- requested: input.images[0],
1724
+ // Requested identity = the article's first body image (从正文选择), or
1725
+ // `metadata.wechatmp.coverPath` / `metadata.coverImage` when `coverSource: 'library'`
1726
+ // omits body attachment and no audio uploaded it cleanly first.
1727
+ requested: input.images[0] ?? libraryCoverFallback(deps.content),
1386
1728
  });
1387
1729
  if (cover !== null) warnings.push(cover);
1388
1730
  }
1389
- const { enrichWarnings, coverWarnings } = await enrichArticleDraft(page, deps.content, deps.stepTimeoutMs);
1731
+ const { enrichWarnings, capabilityWarnings, coverWarnings } = await enrichArticleDraft(
1732
+ page,
1733
+ deps.content,
1734
+ deps.stepTimeoutMs,
1735
+ );
1390
1736
  warnings.push(...coverWarnings);
1391
1737
  // Layout is deliberately last: 原文链接, media insertion, and cover commitment must be part of
1392
1738
  // the body the platform formats, and the native auto-save acknowledgement must settle before
1393
1739
  // 保存为草稿 or the public saved-editor readback begins.
1394
1740
  const layout = await applyLayout(page, deps);
1395
1741
  if (layout !== null) warnings.push(layout);
1396
- return { warnings, titlePath, enrichWarnings };
1742
+ return { warnings, titlePath, enrichWarnings, capabilityWarnings };
1397
1743
  }
1398
1744
 
1399
1745
  /** Compose 贴图 (createType 8): ≥1 image is the message; title and body are 选填. */
@@ -1694,6 +2040,7 @@ interface ComposeReport {
1694
2040
  warnings: string[];
1695
2041
  titlePath: 'absent' | 'mirror-agreed' | 'mirror-unread';
1696
2042
  enrichWarnings: string[];
2043
+ capabilityWarnings?: string[];
1697
2044
  }
1698
2045
 
1699
2046
  /** Compose the requested mode's post. Exhaustive over {@link ModeInput}. */
@@ -1749,6 +2096,9 @@ function baseMetadata(input: ModeInput, deps: ModeRunDeps, entry: ModeEntry): Re
1749
2096
  * the editor is still settling), but the signal is never assumed: an unobserved save is `ok:false`
1750
2097
  * naming the control, the title and the deadline. `发表` is not clicked on this path at all.
1751
2098
  */
2099
+ /** The 草稿箱 stamp the console shows for a draft it considers incomplete (0423 R2, 2026-11-22). */
2100
+ export const INCOMPLETE_DRAFT_MARKER = '图文内容不完整';
2101
+
1752
2102
  async function saveDraft(
1753
2103
  input: ModeInput,
1754
2104
  deps: ModeRunDeps,
@@ -1756,6 +2106,17 @@ async function saveDraft(
1756
2106
  composed: ComposeReport,
1757
2107
  ): Promise<Result> {
1758
2108
  const title = titleOf(deps.content);
2109
+ // 0423 R2: never click 保存为草稿 on an empty article body. The a2ui-intro run saved a draft whose
2110
+ // ProseMirror body read textLen 0 and certified it `succeeded`/`confirmed`.
2111
+ if (input.operation === '文章' && bodyOf(deps.content).trim().length > 0) {
2112
+ const bodySelector = await findSelector(entry.editor, BODY_BLOCK, 'article body', deps.stepTimeoutMs).catch(
2113
+ () => null,
2114
+ );
2115
+ if (bodySelector === null || (await bodyLength(entry.editor, bodySelector)) === 0)
2116
+ return fail(
2117
+ 'draft confirmation: article body is empty before 保存为草稿 — refusing to save an incomplete draft',
2118
+ );
2119
+ }
1759
2120
  let control: string | null = null;
1760
2121
  let signal: string | null = null;
1761
2122
  let attempts = 0;
@@ -1803,6 +2164,10 @@ async function saveDraft(
1803
2164
  `draft confirmation: '${SAVE_DRAFT[0]}' was clicked ${attempts}× but no fresh 草稿箱 row for '${title}' (its ${DRAFT_STAMP} stamp) was observed within ${deps.draftTimeoutMs}ms (before=${deps.draftBaseline.stamp ?? 'none'}, after=${stampAfter ?? 'none'}, page=${deps.entry.url()}, frames=${await describeFrames(deps.entry, 5)})`,
1804
2165
  );
1805
2166
  }
2167
+ if (signal.includes(INCOMPLETE_DRAFT_MARKER))
2168
+ return fail(
2169
+ `draft confirmation: 草稿箱 row for '${title}' reported '${signal.replace(/\s+/g, ' ').trim()}' — refusing to certify an incomplete draft`,
2170
+ );
1806
2171
  return ResultSchema.parse({
1807
2172
  ok: true,
1808
2173
  target: TARGET,
@@ -1871,12 +2236,11 @@ function savedEditorUrlForMetadata(value: string): string {
1871
2236
 
1872
2237
  /** A read-only DOM snapshot used to prove the saved editor still contains the composed payload. */
1873
2238
  const PUBLIC_DRAFT_SNAPSHOT_SCRIPT = `/* __KK_WECHAT_PUBLISH_SNAPSHOT__ */ (() => {
1874
- const norm = (value) => (value ?? '').replace(/[\\s\\u00a0]+/g, ' ').trim();
1875
2239
  const titleNode = document.querySelector('textarea#title, textarea.js_title');
1876
2240
  const title = titleNode?.value ?? [...document.querySelectorAll('.ProseMirror[data-placeholder*="标题"]')]
1877
2241
  .map((node) => node.textContent ?? '').join(' ');
1878
2242
  const body = [...document.querySelectorAll('.ProseMirror:not([data-placeholder])')]
1879
- .map((node) => norm(node.textContent)).join('\\n');
2243
+ .map((node) => (node.textContent ?? '').replace(/[\\s\\u00a0]+/g, ' ').trim()).join('\\n');
1880
2244
  const media = [
1881
2245
  ...document.querySelectorAll(
1882
2246
  '.ProseMirror mp-common-mpaudio, .ProseMirror mpvoice, .ProseMirror [data-mediaid], .ProseMirror audio, .ProseMirror video, .ProseMirror img',
@@ -1884,7 +2248,7 @@ const PUBLIC_DRAFT_SNAPSHOT_SCRIPT = `/* __KK_WECHAT_PUBLISH_SNAPSHOT__ */ (() =
1884
2248
  ]
1885
2249
  .map((node) => node.getAttribute('data-mediaid') ?? node.getAttribute('data-id') ??
1886
2250
  node.getAttribute('voice_encode_fileid') ?? node.getAttribute('data-src') ?? node.getAttribute('src') ??
1887
- norm(node.textContent))
2251
+ (node.textContent ?? '').replace(/[\\s\\u00a0]+/g, ' ').trim())
1888
2252
  .map(norm).filter((value) => value.length > 0);
1889
2253
  const area = document.querySelector('#js_cover_area');
1890
2254
  const coverNode = area?.querySelector('.js_cover_preview_new img, img, [style*="background-image"], input[type="hidden"]');
@@ -2627,17 +2991,22 @@ export async function runMode(input: ModeInput, deps: ModeRunDeps): Promise<Resu
2627
2991
  if (!result.ok && diagnostics.length > 0) {
2628
2992
  return { ...result, error: `${result.error} — compose diagnostics: ${diagnostics.join(' | ')}` };
2629
2993
  }
2630
- // Requested enrichment that did not take is a FAILURE, not a warning (2026-11-15). The daily
2631
- // draft was saved 原创/赞赏/原文链接-free and the row still reported ok:true, so the receipt
2632
- // said 'succeeded' while the article was incomplete and only a human noticed. The draft
2633
- // exists — that is a real, visible effect — so the operator is told exactly what is missing
2634
- // and where it is. WECHATMP_ALLOW_PARTIAL_ENRICH=1 restores the old warn-and-continue shape
2635
- // for an account that genuinely cannot offer one of these fields.
2636
- if (result.ok && composed.enrichWarnings.length > 0 && process.env.WECHATMP_ALLOW_PARTIAL_ENRICH !== '1') {
2994
+ // Requested enrichment that did not take is a FAILURE, not a warning (2026-11-15).
2995
+ // WECHATMP_ALLOW_PARTIAL_ENRICH=1 tolerates ONLY account capability refusals (赞赏账户,
2996
+ // 原文链接行不存在) — never real non-capability failures (音频, 原创声明, 原文链接保存失败,
2997
+ // 合集, 创作来源).
2998
+ const capabilitySet = new Set(composed.capabilityWarnings ?? []);
2999
+ const blockingEnrichWarnings = composed.enrichWarnings.filter((warning) => !capabilitySet.has(warning));
3000
+ const partialAllowed = process.env.WECHATMP_ALLOW_PARTIAL_ENRICH === '1';
3001
+ const fatalEnrichWarnings = partialAllowed ? blockingEnrichWarnings : composed.enrichWarnings;
3002
+ if (result.ok && fatalEnrichWarnings.length > 0) {
3003
+ const capabilityOnly = blockingEnrichWarnings.length === 0;
2637
3004
  return {
2638
3005
  ...result,
2639
3006
  ok: false,
2640
- error: `draft saved but enrichment did not apply — ${composed.enrichWarnings.join(' | ')} (set WECHATMP_ALLOW_PARTIAL_ENRICH=1 to accept a partial draft)`,
3007
+ error: `draft saved but enrichment did not apply — ${fatalEnrichWarnings.join(' | ')}${
3008
+ capabilityOnly ? ' (set WECHATMP_ALLOW_PARTIAL_ENRICH=1 to accept a partial draft)' : ''
3009
+ }`,
2641
3010
  };
2642
3011
  }
2643
3012
  return result;
@@ -2691,7 +3060,9 @@ export function markdownToWechatHtml(markdown: string): string {
2691
3060
  for (const line of lines) {
2692
3061
  if (line.startsWith('```')) {
2693
3062
  if (inCode) {
2694
- out.push(`<pre><code>${escapeHtml(code.join('\n'))}</code></pre>`);
3063
+ out.push(
3064
+ `<pre style="overflow-x:auto;max-width:100%;"><code>${escapeHtml(code.join('\n'))}</code></pre>`,
3065
+ );
2695
3066
  code = [];
2696
3067
  inCode = false;
2697
3068
  } else {
@@ -2744,6 +3115,14 @@ function escapeHtml(text: string): string {
2744
3115
  return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
2745
3116
  }
2746
3117
 
3118
+ async function evalOrFallback(page: WechatPage, script: string, fallback: string): Promise<string> {
3119
+ try {
3120
+ return String((await page.evaluate(script)) ?? fallback);
3121
+ } catch {
3122
+ return fallback;
3123
+ }
3124
+ }
3125
+
2747
3126
  /**
2748
3127
  * Audio at the article top (operator request 2026-09-29; upload path added 2026-10-10).
2749
3128
  *
@@ -2759,7 +3138,17 @@ function escapeHtml(text: string): string {
2759
3138
  export async function insertAudioMaterial(
2760
3139
  page: WechatPage,
2761
3140
  input: { title: string; audioPath: string; coverPath: string },
3141
+ timing: {
3142
+ uploadWaitMs?: number;
3143
+ saveCloseWaitMs?: number;
3144
+ saveDispatchWaitMs?: number;
3145
+ rowRetries?: number;
3146
+ } = {},
2762
3147
  ): Promise<{ warning: string; coverSeeded: boolean }> {
3148
+ const uploadWaitMs = timing.uploadWaitMs ?? 120_000;
3149
+ const saveCloseWaitMs = timing.saveCloseWaitMs ?? 30_000;
3150
+ const saveDispatchWaitMs = timing.saveDispatchWaitMs ?? 10_000;
3151
+ const postUploadRowRetries = timing.rowRetries ?? 15;
2763
3152
  const { title, audioPath, coverPath } = input;
2764
3153
  // The library demonstrably holds the episode cover once the picker verified the unique same-name
2765
3154
  // row (0260 R1 refined 2026-11-09): failures AFTER that point must not suppress the deferred
@@ -2841,18 +3230,96 @@ export async function insertAudioMaterial(
2841
3230
  return JSON.stringify({ state: 'top', identity });
2842
3231
  })()`;
2843
3232
 
3233
+ /**
3234
+ * Save a PNG of the stalled 上传音频 dialog next to the temp dir and return its path. A vendor
3235
+ * upload that never reports 100% is otherwise only visible as text, and the text cannot show a
3236
+ * restored half-finished material, a disabled button or a progress bar stuck at 0.
3237
+ */
3238
+ const dumpAudioStall = async (p: WechatPage): Promise<string> => {
3239
+ const path = join(tmpdir(), `wechatmp-audio-stall-${Date.now()}.png`);
3240
+ try {
3241
+ if (p.screenshot === undefined) return '(no screenshot seam)';
3242
+ await p.screenshot(path);
3243
+ return path;
3244
+ } catch (error) {
3245
+ return `(screenshot failed: ${error instanceof Error ? error.message : String(error)})`;
3246
+ }
3247
+ };
3248
+
3249
+ /**
3250
+ * One line of what the 上传音频 dialog currently shows: the material id the console assigns
3251
+ * once it accepts the file, its buttons, and a bounded text slice. A stalled vendor upload is
3252
+ * otherwise indistinguishable from a broken selector in the failure string.
3253
+ */
3254
+ const audioDialogState = async (p: WechatPage): Promise<string> =>
3255
+ evalOrFallback(
3256
+ p,
3257
+ `(() => { const d = [...document.querySelectorAll('.weui-desktop-dialog')].find((el) => el.offsetWidth > 0 && el.querySelector('input[name=audio_id]')); if (!d) return '(no audio dialog)'; const id = d.querySelector('input[name=audio_id]'); const btns = [...d.querySelectorAll('button')].map((b) => (b.innerText ?? '').trim()).filter(Boolean); return 'audio_id="' + (id?.value ?? '') + '" buttons=' + JSON.stringify(btns) + ' text=' + ((d.innerText ?? '').replace(/\\s+/g, ' ').slice(0, 120)); })()`,
3258
+ '',
3259
+ );
3260
+
2844
3261
  /** Upload the audio + its cover, acknowledge the rules, and 保存. Returns a structured outcome. */
2845
- const upload = async (): Promise<{ warning: string; coverSeeded: boolean }> => {
3262
+ const upload = async (): Promise<{ warning: string; coverSeeded: boolean; sawLiveUpload: boolean }> => {
3263
+ let sawLiveUpload = false;
3264
+ const failUpload = (warning: string) => ({ ...result(warning), sawLiveUpload });
3265
+ const uploadDialog = '.weui-desktop-dialog:visible:has(h3.weui-desktop-dialog__title:text-is("上传音频"))';
3266
+ const isLiveUploadForm = async (): Promise<boolean> => {
3267
+ if ((await page.locator(uploadDialog).count()) === 0) return false;
3268
+ try {
3269
+ const titleText =
3270
+ (await page.locator(`${uploadDialog} h3.weui-desktop-dialog__title`).first().textContent?.()) ?? '';
3271
+ return titleText.trim() === '上传音频';
3272
+ } catch {
3273
+ return false;
3274
+ }
3275
+ };
2846
3276
  const uploadControl = await trySelectors(page, UPLOAD_AUDIO);
2847
- if (!uploadControl.found) return result('音频: 上传音频 control not found in the audio dialog');
3277
+ if (!uploadControl.found) return failUpload('音频: 上传音频 control not found in the audio dialog');
2848
3278
  // Click the winner, never a joined union: `text=…, css…` mixes selector engines and
2849
3279
  // Playwright parses the whole string as CSS — zero matches (DOM fixture 0260).
2850
3280
  await clickSelector(page, uploadControl.selector ?? UPLOAD_AUDIO[0] ?? 'text=上传音频', 8_000);
2851
3281
  const audioInput = await trySelectors(page, AUDIO_UPLOAD_INPUT, { visible: false });
2852
- if (!audioInput.found) return result('音频: no audio file input appeared');
3282
+ if (!audioInput.found) return failUpload('音频: no audio file input appeared');
2853
3283
  await uploadFile(asPlaywrightPage(page), audioInput.selector ?? AUDIO_UPLOAD_INPUT.join(', '), audioPath, {
2854
- timeoutMs: 60_000,
3284
+ timeoutMs: 120_000,
2855
3285
  });
3286
+ sawLiveUpload = await isLiveUploadForm();
3287
+ if (sawLiveUpload) {
3288
+ // Two completion shapes, because the console replaced the first one and the second is the
3289
+ // only thing it leaves on screen (2026-11-23, screenshot):
3290
+ // * the transient upload form — a 重新上传 button next to a 100% progress read;
3291
+ // * the settled form — the picked file's own card (name + 「<n>分钟」, a 删除 affordance)
3292
+ // with 保存 enabled. The transient state is gone by the time the upload registers, so
3293
+ // waiting only for it abandoned a COMPLETED upload and skipped the audio every run.
3294
+ const audioName = baseName(audioPath).replace(/\.[^.]+$/, '');
3295
+ const settledUpload = async (): Promise<boolean> =>
3296
+ evalOrFallback(
3297
+ page,
3298
+ `(() => { const d = [...document.querySelectorAll('.weui-desktop-dialog')].find((el) => el.offsetWidth > 0 && el.querySelector('input[name=audio_id]')); if (!d) return 'false'; const t = d.innerText ?? ''; return String(t.includes(${JSON.stringify(audioName)}) && /分钟/.test(t)); })()`,
3299
+ 'false',
3300
+ ).then((value) => value === 'true');
3301
+ const transientUpload = async (): Promise<boolean> => {
3302
+ if ((await page.locator(`${uploadDialog} button:has-text("重新上传")`).count()) === 0) return false;
3303
+ const text = await evalOrFallback(
3304
+ page,
3305
+ `(() => { const d = [...document.querySelectorAll('.weui-desktop-dialog')].find((el) => el.offsetWidth > 0 && el.querySelector('input[name=audio_id]')); return d ? (d.textContent ?? '') : ''; })()`,
3306
+ '',
3307
+ );
3308
+ return /100%/.test(text);
3309
+ };
3310
+ const uploaded = await waitUntil(
3311
+ async () => (await settledUpload()) || (await transientUpload()),
3312
+ uploadWaitMs,
3313
+ );
3314
+ if (!uploaded)
3315
+ return failUpload(
3316
+ // The console never renders a completion signal this dialog can be read from
3317
+ // when the vendor side stalls: 2026-11-23 showed the picked file and its
3318
+ // duration with an EMPTY audio_id for 120s, so the failure now carries what the
3319
+ // dialog actually said instead of only the predicate's name.
3320
+ `音频: 音频文件上传未完成(未达到 100%),未保存音频 — shot=${await dumpAudioStall(page)} — ${await audioDialogState(page)}`,
3321
+ );
3322
+ }
2856
3323
  // The form requires a cover before it will save.
2857
3324
  const coverControl = await trySelectors(page, UPLOAD_COVER);
2858
3325
  if (coverControl.found) {
@@ -2873,13 +3340,13 @@ export async function insertAudioMaterial(
2873
3340
  ),
2874
3341
  5_000,
2875
3342
  );
2876
- if (!libraryReady) return result('音频: 封面素材库加载未完成,未上传重复封面');
3343
+ if (!libraryReady) return failUpload('音频: 封面素材库加载未完成,未上传重复封面');
2877
3344
  existing = Number(
2878
3345
  await page.evaluate(
2879
3346
  `([...document.querySelectorAll('.weui-desktop-img-picker__item')].filter(row => row.offsetWidth > 0 && row.querySelector('.weui-desktop-img-picker__img-title')?.textContent?.trim() === ${JSON.stringify(coverName)})).length`,
2880
3347
  ),
2881
3348
  );
2882
- if (existing > 1) return result('音频: 内容绑定封面存在多个同名素材,未猜测选择');
3349
+ if (existing > 1) return failUpload('音频: 内容绑定封面存在多个同名素材,未猜测选择');
2883
3350
  }
2884
3351
  let uploadPath = coverPath;
2885
3352
  let temporaryDir: string | undefined;
@@ -2916,7 +3383,7 @@ export async function insertAudioMaterial(
2916
3383
  ),
2917
3384
  30_000,
2918
3385
  );
2919
- if (!selected) return result('音频: 上传封面未出现唯一已选中的同名图片,未提交封面');
3386
+ if (!selected) return failUpload('音频: 上传封面未出现唯一已选中的同名图片,未提交封面');
2920
3387
  // The picker just proved the library holds the unique same-name cover; every
2921
3388
  // failure past this point leaves the cover in the 图片库 (cover rescue valid).
2922
3389
  libraryHasCover = true;
@@ -2927,6 +3394,9 @@ export async function insertAudioMaterial(
2927
3394
  30_000,
2928
3395
  );
2929
3396
  await clickSelector(page, next, 8_000);
3397
+ if (sawLiveUpload && (await page.locator(`${chooser} button:has-text("上一步")`).count()) > 0) {
3398
+ await page.waitForTimeout?.(2_000);
3399
+ }
2930
3400
  const finish = await findSelector(
2931
3401
  page,
2932
3402
  [`${chooser} button:has-text("完成"):not(.weui-desktop-btn_disabled)`],
@@ -2978,7 +3448,7 @@ export async function insertAudioMaterial(
2978
3448
  // confirm dialog may not nest under the chooser selector, which would
2979
3449
  // explain the 确定 retry missing it) before giving up on the audio save.
2980
3450
  const inventory = await openDialogInventory(page);
2981
- return result(
3451
+ return failUpload(
2982
3452
  `音频: 封面选择器完成后未关闭,未保存音频${inventory ? ` (dialogs: ${inventory})` : ''}`,
2983
3453
  );
2984
3454
  }
@@ -2994,15 +3464,42 @@ export async function insertAudioMaterial(
2994
3464
  const titleInput = await trySelectors(page, AUDIO_TITLE_INPUT);
2995
3465
  if (titleInput.found) await fillSelector(page, titleInput.selector ?? AUDIO_TITLE_INPUT.join(', '), title);
2996
3466
  const agreed = String(await page.evaluate(AGREE));
2997
- if (agreed !== 'checked') return result(`音频: 服务规则勾选失败 (${agreed})`);
3467
+ if (agreed !== 'checked') return failUpload(`音频: 服务规则勾选失败 (${agreed})`);
2998
3468
  const save = await findSelector(
2999
3469
  page,
3000
3470
  UPLOAD_SAVE.map((selector) => `${selector}:not(.weui-desktop-btn_disabled):not([disabled])`),
3001
3471
  '音频上传完成且封面已提交后的保存按钮',
3002
3472
  90_000,
3003
3473
  );
3474
+ if (sawLiveUpload) {
3475
+ await evalOrFallback(
3476
+ page,
3477
+ '(() => { window.__kkToasts = []; new MutationObserver(() => { const t = document.querySelector(".weui-desktop-toast"); if (t && t.textContent) window.__kkToasts.push(t.textContent.trim().slice(0, 200)); }).observe(document.body, { subtree: true, childList: true, characterData: true }); })()',
3478
+ '',
3479
+ );
3480
+ }
3004
3481
  await clickSelector(page, save, 8_000);
3005
- return result('');
3482
+ if (sawLiveUpload) {
3483
+ let formClosed = await waitUntil(async () => !(await isLiveUploadForm()), saveCloseWaitMs);
3484
+ if (!formClosed) {
3485
+ const dispatched = await evalOrFallback(
3486
+ page,
3487
+ '(() => { const form = [...document.querySelectorAll(".weui-desktop-dialog")].find((d) => d.querySelector(".title_form_wrp")); const btn = form && [...form.querySelectorAll("button")].find((b) => (b.textContent ?? "").trim() === "保存"); if (!btn) return "no-btn"; btn.click(); return btn.disabled ? "was-disabled" : "clicked"; })()',
3488
+ 'null',
3489
+ );
3490
+ formClosed = await waitUntil(async () => !(await isLiveUploadForm()), saveDispatchWaitMs);
3491
+ if (!formClosed) {
3492
+ const saveDiagnostics = `(() => {
3493
+ const form = [...document.querySelectorAll(".weui-desktop-dialog")].find((d) => d.querySelector(".title_form_wrp"));
3494
+ const btn = form && [...form.querySelectorAll("button")].find((b) => (b.textContent ?? "").trim() === "保存");
3495
+ return JSON.stringify({ btn: btn ? { disabled: btn.disabled, offW: btn.offsetWidth } : null, toasts: (window.__kkToasts ?? []).slice(-3) });
3496
+ })()`;
3497
+ const diag = (await evalOrFallback(page, saveDiagnostics, '')).slice(0, 400);
3498
+ return failUpload(`音频: 保存失败,上传弹窗未关闭(dispatch=${dispatched} ${diag})`);
3499
+ }
3500
+ }
3501
+ }
3502
+ return failUpload('');
3006
3503
  };
3007
3504
 
3008
3505
  /** One MATCH read; a throwing probe stays 'error' (unknown, never treated as missing). */
@@ -3014,9 +3511,9 @@ export async function insertAudioMaterial(
3014
3511
  }
3015
3512
  };
3016
3513
  /** Poll the picker while rows stream in; 'missing' keeps polling, JSON answers settle it. */
3017
- const awaitMatch = async (): Promise<string> => {
3514
+ const awaitMatch = async (retries: number = AUDIO_ROW_RETRIES): Promise<string> => {
3018
3515
  let match = await matchOnce();
3019
- for (let i = 0; match === 'missing' && i < AUDIO_ROW_RETRIES; i += 1) {
3516
+ for (let i = 0; match === 'missing' && i < retries; i += 1) {
3020
3517
  await page.waitForTimeout?.(AUDIO_ROW_SETTLE_MS);
3021
3518
  match = await matchOnce();
3022
3519
  }
@@ -3033,16 +3530,18 @@ export async function insertAudioMaterial(
3033
3530
  await page.evaluate(`document.querySelector(${JSON.stringify(AUDIO_MENU)})?.click()`);
3034
3531
  await waitForVisible(page, AUDIO_DIALOG, AUDIO_DIALOG_TIMEOUT_MS);
3035
3532
  let match = await awaitMatch();
3533
+ let postSavePoll = false;
3036
3534
  if (match === 'missing') {
3037
3535
  // No reusable material: upload one, then POLL until the new row actually exists — never
3038
3536
  // assume the upload auto-selected a default row (task 0260 AC2).
3039
3537
  const uploadResult = await upload();
3538
+ postSavePoll = uploadResult.sawLiveUpload;
3040
3539
  if (uploadResult.warning !== '') {
3041
- await page.evaluate(CANCEL);
3540
+ if (!uploadResult.sawLiveUpload) await page.evaluate(CANCEL);
3042
3541
  return result(uploadResult.warning);
3043
3542
  }
3044
3543
  await waitForVisible(page, AUDIO_DIALOG, AUDIO_DIALOG_TIMEOUT_MS);
3045
- match = await awaitMatch();
3544
+ match = await awaitMatch(postSavePoll ? postUploadRowRetries : AUDIO_ROW_RETRIES);
3046
3545
  if (match === 'missing') {
3047
3546
  await page.evaluate(CANCEL);
3048
3547
  return result(`音频: 保存后素材列表未出现「${title}」,未插入音频`);
@@ -3070,7 +3569,14 @@ export async function insertAudioMaterial(
3070
3569
  await page.evaluate(CANCEL);
3071
3570
  return result('音频: 素材匹配探测返回未知结果,未插入音频');
3072
3571
  }
3073
- if ((await page.evaluate(INSERT)) !== true) {
3572
+ let inserted = (await page.evaluate(INSERT)) === true;
3573
+ if (!inserted && postSavePoll) {
3574
+ for (let i = 0; !inserted && i < 5; i += 1) {
3575
+ await page.waitForTimeout?.(500);
3576
+ inserted = (await page.evaluate(INSERT)) === true;
3577
+ }
3578
+ }
3579
+ if (!inserted) {
3074
3580
  await page.evaluate(CANCEL);
3075
3581
  return result('音频: 插入按钮未找到,请手动插入');
3076
3582
  }