xinghe-muse 0.0.0-stage → 2.3.0

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.
@@ -0,0 +1,565 @@
1
+ /**
2
+ * xinghe-muse 浏览器驱动 —— 在 ego lite 里操作 muse.ai 出图 / 出视频。
3
+ *
4
+ * 作者:星禾
5
+ *
6
+ * 由 lib/drive.mjs 从 stdin 喂给 `ego-browser nodejs` 执行,因此这里拿不到 argv,
7
+ * 也读不到 shell 环境变量:所有输入都在 globalThis.__museArgv 里。
8
+ *
9
+ * argv: <指令> <保存目录> <超时秒> <文件名提示> <任务空间名> <类型 image|video> <参考素材JSON>
10
+ *
11
+ * 参考素材(v2.3.0 起):第 7 项是 JSON 数组的绝对路径,图片和视频都能挂,
12
+ * 可以挂多个。挂载走页面上那个可见的 input[type=file],走 setInputFiles,
13
+ * 不点屏幕、不弹系统对话框,所以窗口不可见也照样能挂上去。
14
+ *
15
+ * stdout 只打一行 JSON 作为结果,诊断信息一律走 stderr,调用方靠这个分界。
16
+ *
17
+ * 三条实测教训,改这里之前先看:
18
+ * 1. 图片产物是 <button aria-label="打开生成的图片…">,视频产物是
19
+ * <div role="button" aria-label="打开动画视频 ….mp4">。只查 button 会漏掉视频。
20
+ * 2. ego 的 loc=css 对 [role="button"] 这类属性选择器不稳,点不动。
21
+ * 所以产物一律先 evaluate 取包围盒,再用 mouse.click 按坐标点。
22
+ * 3. 直接 goto /thread/new 时好时坏,第二次常拿到空白页。
23
+ * 先进首页、点「新旁聊」,拿不到再退回直接开。
24
+ */
25
+
26
+ const [prompt, outDir, timeoutSec, nameHint, spaceName, kindRaw, refsRaw] = globalThis.__museArgv ?? []
27
+ const KIND = kindRaw === 'video' ? 'video' : 'image'
28
+ const IS_VIDEO = KIND === 'video'
29
+
30
+ /**
31
+ * 参考素材:图、视频都收,绝对路径数组。
32
+ *
33
+ * 传进来是 JSON 字符串而不是数组对象——drive.mjs 那边只做一次 JSON.stringify,
34
+ * 这里解析失败就当没给,不让它炸掉整轮。
35
+ */
36
+ const REFS = (() => {
37
+ try {
38
+ const value = JSON.parse(refsRaw ?? '[]')
39
+ return Array.isArray(value)
40
+ ? value.filter((p) => typeof p === 'string' && p.trim() !== '')
41
+ : []
42
+ } catch {
43
+ return []
44
+ }
45
+ })()
46
+
47
+ /** 视频比图片慢得多,同一套轮询逻辑给更宽的上限。 */
48
+ const GEN_TIMEOUT = (IS_VIDEO
49
+ ? Math.max(60, Math.min(Number(timeoutSec) || 420, 1800))
50
+ : Math.max(60, Math.min(Number(timeoutSec) || 180, 600))) * 1000
51
+
52
+ const COMPOSER = 'loc=css:textarea[placeholder="消息"]'
53
+ const SEND = 'loc=css:button[aria-label="发送"]'
54
+ const STOP = 'button[aria-label="停止"]'
55
+ const NEW_THREAD = 'https://muse.ai/thread/new'
56
+ const HOME = 'https://muse.ai/'
57
+
58
+ const say = (msg) => process.stderr.write(`${msg}\n`)
59
+
60
+ /** 生成中 Chrome 会挂一个停止按钮,它消失就是这轮结束。 */
61
+ const stillGenerating = `() => !!document.querySelector('${STOP}, button[aria-label*="中断"]')`
62
+
63
+ /**
64
+ * 找最新那条产物的可点元素,返回它的中心坐标。
65
+ *
66
+ * 先按 aria 文案挑(图片含「图片」,视频含「视频/动画视频」或 .mp4),
67
+ * 挑不到再按结构兜底:页面里最后一个够大的 video / img 的可点祖先。
68
+ * 返回矩形是给 mouse.click 用的,不走 CSS 选择器。
69
+ */
70
+ const findMedia = `(kind) => {
71
+ const nodes = [...document.querySelectorAll('[role="button"], button, a')];
72
+ const isVideo = (a) => /(动画视频|视频|影片|video)/i.test(a) || /\\.(mp4|webm|mov)\\b/i.test(a);
73
+ const isImage = (a) => /(图片|图像|照片|image)/i.test(a) || /\\.(png|jpe?g|webp|gif)\\b/i.test(a);
74
+ const wanted = kind === 'video' ? isVideo : isImage;
75
+ // 挂了参考素材的轮次,用户消息里也有一份视频/图预览,不排掉就会把**输入**当产物下载。
76
+ const isRef = (a) => /参考|附件|reference|attach/i.test(a);
77
+
78
+ const boxOf = (el) => {
79
+ const r = el.getBoundingClientRect();
80
+ return { x: Math.round(r.x), y: Math.round(r.y), w: Math.round(r.width), h: Math.round(r.height) };
81
+ };
82
+
83
+ // 一:按文案,从后往前(最新的在后面)。先只认「打开…产物」这一路文案,
84
+ // 认不到再放宽——产物和参考素材的文案差别就在这里。
85
+ const passes = [/打开/, null];
86
+ for (const gate of passes) {
87
+ for (let i = nodes.length - 1; i >= 0; i -= 1) {
88
+ const el = nodes[i];
89
+ const aria = (el.getAttribute('aria-label') || '') + ' ' + (el.getAttribute('title') || '');
90
+ if (!aria.trim()) continue;
91
+ if (isRef(aria)) continue;
92
+ if (!wanted(aria)) continue;
93
+ if (gate && !gate.test(aria)) continue;
94
+ const b = boxOf(el);
95
+ if (b.w < 80 || b.h < 80) continue;
96
+ return { aria: el.getAttribute('aria-label') || '', ...b, how: gate ? 'aria' : 'aria-loose' };
97
+ }
98
+ }
99
+
100
+ // 二:按结构兜底
101
+ const media = [...document.querySelectorAll(kind === 'video' ? 'video' : 'img')];
102
+ for (let i = media.length - 1; i >= 0; i -= 1) {
103
+ const host = media[i].closest('[role="button"], button, a');
104
+ if (!host) continue;
105
+ if (isRef(host.getAttribute('aria-label') || '')) continue;
106
+ const b = boxOf(host);
107
+ if (b.w < 80 || b.h < 80) continue;
108
+ return { aria: host.getAttribute('aria-label') || '', ...b, how: 'dom' };
109
+ }
110
+ return null;
111
+ }`
112
+
113
+ /** 弹层里所有可点项的文字与 aria,用来找下载入口。 */
114
+ const dialogItems = `() => {
115
+ const scope = document.querySelector('[role="dialog"]') || document.body;
116
+ const items = [...scope.querySelectorAll('button, [role="button"], a')]
117
+ .map((el) => {
118
+ const r = el.getBoundingClientRect();
119
+ if (!r.width || !r.height) return null;
120
+ return {
121
+ label: (el.getAttribute('aria-label') || '').trim(),
122
+ text: (el.textContent || '').trim().slice(0, 24),
123
+ x: Math.round(r.x + r.width / 2),
124
+ y: Math.round(r.y + r.height / 2),
125
+ };
126
+ })
127
+ .filter(Boolean);
128
+ const dlgText = scope === document.body ? '' : (scope.textContent || '').trim().slice(0, 120);
129
+ return { items, dlgText };
130
+ }`
131
+
132
+ /** Muse 自己说的话,取最新的几条。 */
133
+ const replies = `() => {
134
+ const nodes = [...document.querySelectorAll('p, div')]
135
+ .map((n) => (n.textContent || '').trim())
136
+ .filter((t) => t.length > 8 && t.length < 400);
137
+ return [...new Set(nodes)].slice(-6);
138
+ }`
139
+
140
+ /** 文件名安全化:去掉路径分隔符与 Windows 保留字符。 */
141
+ const slug = (text) => text
142
+ .replace(/[\\/:*?"<>|\\s]+/g, '')
143
+ .replace(/^[.]+/, '')
144
+ .slice(0, 40) || (IS_VIDEO ? '视频' : '图片')
145
+
146
+ /** 把 aria 里那串机器名换成人能看的名,剥不掉就用兜底名。 */
147
+ const niceName = (aria) => {
148
+ const stripped = (aria || '')
149
+ .replace(/^打开/, '')
150
+ .replace(/^动画/, '')
151
+ .replace(/^生成的?/, '')
152
+ .replace(/^(图片|视频|影像|影片)/, '')
153
+ .replace(/^[\s::-]+/, '')
154
+ .replace(/\.(png|jpe?g|webp|gif|mp4|webm|mov)$/i, '')
155
+ .replace(/^media-generation[\w-]*$/i, '')
156
+ .trim()
157
+ return stripped && !/^media-generation/i.test(stripped) ? stripped : ''
158
+ }
159
+
160
+ const stampOf = (date) => {
161
+ const p = (n) => String(n).padStart(2, '0')
162
+ return `${date.getFullYear()}${p(date.getMonth() + 1)}${p(date.getDate())}_${p(date.getHours())}${p(date.getMinutes())}${p(date.getSeconds())}`
163
+ }
164
+
165
+ /** 图片与视频各认一套扩展名,取下载文件名里真实的那个。 */
166
+ const EXT_RE = IS_VIDEO
167
+ ? /\.(mp4|webm|mov|m4v)$/i
168
+ : /\.(png|jpe?g|webp|gif)$/i
169
+ const DEFAULT_EXT = IS_VIDEO ? '.mp4' : '.webp'
170
+
171
+ /** 产物 aria 里写的扩展名,任何一套都认——用来纠正下载按钮给错的名字。 */
172
+ const ANY_EXT = /\.(mp4|webm|mov|m4v|png|jpe?g|webp|gif)\b/i
173
+
174
+ /**
175
+ * 按文件头推真实扩展名。
176
+ *
177
+ * 实测:视频产物经下载按钮落地,建议名是 .webp,字节里却是 mp4——
178
+ * 名字错了外面双击打不开,所以落地后一律按头改一次。
179
+ */
180
+ async function matchExt(file) {
181
+ const probe = await (await import('node:fs/promises')).open(file, 'r')
182
+ try {
183
+ const head = Buffer.alloc(16)
184
+ await probe.read(head, 0, 16, 0)
185
+ const ascii = head.toString('latin1')
186
+ if (ascii.startsWith('\x89PNG')) return '.png'
187
+ if (ascii.startsWith('\xFF\xD8\xFF')) return '.jpg'
188
+ if (ascii.startsWith('GIF8')) return '.gif'
189
+ if (ascii.startsWith('RIFF') && ascii.slice(8, 12) === 'WEBP') return '.webp'
190
+ if (ascii.slice(4, 8) === 'ftyp') return '.mp4'
191
+ if (head[0] === 0x1a && head[1] === 0x45 && head[2] === 0xdf && head[3] === 0xa3) return '.webm'
192
+ return ''
193
+ } finally {
194
+ await probe.close()
195
+ }
196
+ }
197
+
198
+ /** 这一轮可能落地的产物:按「目录 + 文件名前缀」扫最近的几个,异常时用它兜底。 */
199
+ let OUT_DIR_NOW = ''
200
+ let BASE_NOW = ''
201
+ async function landedFile() {
202
+ if (!OUT_DIR_NOW || !BASE_NOW) return ''
203
+ const fs = await import('node:fs/promises')
204
+ const { join } = await import('node:path')
205
+ const names = await fs.readdir(OUT_DIR_NOW).catch(() => [])
206
+ const hits = names
207
+ .filter((n) => n.startsWith(`${BASE_NOW}_`))
208
+ .map((n) => join(OUT_DIR_NOW, n))
209
+ if (!hits.length) return ''
210
+ const stats = await Promise.all(hits.map(async (p) => ({ p, m: (await fs.stat(p)).mtimeMs })))
211
+ stats.sort((a, b) => b.m - a.m)
212
+ return stats[0].p
213
+ }
214
+
215
+ const empty = {
216
+ ok: false, threadUrl: '', media: null, kind: KIND, reply: '', caption: '', detail: '',
217
+ references: REFS,
218
+ }
219
+
220
+ function emit(value) {
221
+ process.stdout.write(`${JSON.stringify({ ...empty, ...value })}\n`)
222
+ }
223
+
224
+ /**
225
+ * 一条真正的旁聊地址长什么样。
226
+ *
227
+ * 只判 `includes('/thread/')` 是不够的:占位页 `/thread/new` 本身就含 `/thread/`,
228
+ * 会把它当成功。所以要求 `/thread/` 后面还跟着一段 id。
229
+ */
230
+ const THREAD_RE = /\/thread\/(?!new(\/|$|\?|#))[^/?#]+/
231
+
232
+ const isThread = (url) => THREAD_RE.test(url ?? '')
233
+
234
+ /**
235
+ * 进一条新旁聊。
236
+ *
237
+ * 直开 /thread/new 最快,偶尔会停在空白页,所以第一次不成时退到首页点入口。
238
+ * 首页那个入口在侧栏,是 <button>旁聊</button>(纯文字、没有 aria-label),
239
+ * 不是「新旁聊」几个字,所以 loc=text 只对「旁聊」才有戏。
240
+ * 无论走哪条路,最后都以 URL 变成真旁聊地址为成功判据。
241
+ */
242
+ async function openNewThread(page) {
243
+ const landed = () => page.url().then(isThread)
244
+
245
+ const waitLanding = async (rounds) => {
246
+ for (let i = 0; i < rounds; i += 1) {
247
+ if (await landed()) return true
248
+ await page.waitForTimeout(700)
249
+ }
250
+ return landed()
251
+ }
252
+
253
+ await page.goto(NEW_THREAD, { waitUntil: 'domcontentloaded', timeout: 60_000 })
254
+ if (await waitLanding(12)) return page.url()
255
+
256
+ say('/thread/new 没跳成真旁聊,退到首页点入口')
257
+ await page.goto(HOME, { waitUntil: 'domcontentloaded', timeout: 60_000 })
258
+ await page.waitForTimeout(2000)
259
+ for (const label of ['旁聊', '新旁聊', '新建对话']) {
260
+ try {
261
+ await page.click(`loc=text=${label}`, { label, timeout: 4000 })
262
+ if (await waitLanding(12)) return page.url()
263
+ } catch {
264
+ // 试下一个文案
265
+ }
266
+ }
267
+ await page.goto(NEW_THREAD, { waitUntil: 'domcontentloaded', timeout: 60_000 })
268
+ await waitLanding(12)
269
+ return page.url()
270
+ }
271
+
272
+ async function main() {
273
+ const fs = await import('node:fs/promises')
274
+ const { join } = await import('node:path')
275
+
276
+ if (!prompt || prompt.trim() === '') {
277
+ emit({ detail: '指令是空的。填一句想让它做的事再调一次。' })
278
+ return
279
+ }
280
+
281
+ await fs.mkdir(outDir, { recursive: true })
282
+
283
+ // 每轮开一个独立空间,免得继承上一个任务的标签页;同名残留说明是上一轮,
284
+ // 直接接管而不是报错。
285
+ let task
286
+ try {
287
+ task = await taskSpace(spaceName)
288
+ } catch (error) {
289
+ if (!String(error?.message ?? error).includes('IN_USE')) throw error
290
+ task = await takeOverTaskSpace(spaceName)
291
+ }
292
+
293
+ try {
294
+ const page = task.page('p1')
295
+
296
+ await openNewThread(page)
297
+ await page.waitForSelector(COMPOSER, { state: 'visible', timeout: 30_000 })
298
+ await page.waitForTimeout(800)
299
+
300
+ // 参考素材先挂,再填指令:顺序反了会被当成两次输入,附件挂上来时输入框被清空过。
301
+ if (REFS.length > 0) {
302
+ const missing = []
303
+ for (const file of REFS) {
304
+ try {
305
+ await fs.access(file)
306
+ } catch {
307
+ missing.push(file)
308
+ }
309
+ }
310
+ if (missing.length > 0) {
311
+ emit({
312
+ threadUrl: await page.url(),
313
+ detail: `参考素材打不开:${missing.join(';')}。给绝对路径,图片或视频都行。`,
314
+ })
315
+ return
316
+ }
317
+
318
+ // 页面上那个 input[type=file] 直接灌文件,不点屏幕、不弹系统对话框。
319
+ await page.setInputFiles('input[type=file]', REFS)
320
+ say(`已在灌 ${REFS.length} 个参考素材`)
321
+
322
+ // 等它真挂上。判据按可靠度排:blob 预览 > 移除按钮 > 文件名/参考字样。
323
+ // 本地文件上传后预览是 blob: URL,这个信号最不会误判——中文长文件名经常被页面截断或改写。
324
+ const attachState = `() => {
325
+ const thumbs = [...document.querySelectorAll('img, video')]
326
+ .filter((m) => ((m.currentSrc || m.src || '').startsWith('blob:'))).length;
327
+ const removable = [...document.querySelectorAll('button, [role="button"]')]
328
+ .some((b) => /移除|删除|remove|clear|撤销/i.test(b.getAttribute('aria-label') || ''));
329
+ return { thumbs, removable, text: document.body.innerText.slice(0, 6000) };
330
+ }`
331
+ const stems = REFS.map((p) => p.split(/[\\/]/).pop()?.replace(/\.[^.]+$/, '') ?? '')
332
+ let attached = false
333
+ for (let i = 0; i < 120; i += 1) {
334
+ await page.waitForTimeout(1000)
335
+ const state = await page.evaluate(new Function(`return (${attachState})()`))
336
+ const byName = stems.some((s) => s && state.text.includes(s))
337
+ const byBlob = state.thumbs > 0 || state.removable
338
+ if (byBlob || byName) {
339
+ attached = true
340
+ say(`参考素材已挂上(${byBlob ? '预览/移除按钮' : '文件名'}信号)`)
341
+ break
342
+ }
343
+ }
344
+ if (!attached) say('没确认到附件挂载信号,继续发送(照发,不拿它当失败)')
345
+
346
+ // 预览是 blob: 的本地对象地址,一选完就在,**不代表传完**。
347
+ // 传完的判据:发送按钮可用 + 页面上没有「上传中/百分比」。
348
+ // 上传没完就点发送,那一下是空点,地址永远停在 /thread/new——实测踩过。
349
+ const uploadState = `() => {
350
+ const send = document.querySelector('button[aria-label="发送"]');
351
+ const disabled = !send || send.disabled === true
352
+ || send.getAttribute('aria-disabled') === 'true';
353
+ const text = document.body.innerText;
354
+ const busy = /上传中|正在上传|uploading|处理中/i.test(text);
355
+ return { disabled, busy };
356
+ }`
357
+ let settled = false
358
+ for (let i = 0; i < 120; i += 1) {
359
+ const state = await page.evaluate(new Function(`return (${uploadState})()`))
360
+ if (!state.busy && !state.disabled) {
361
+ settled = true
362
+ break
363
+ }
364
+ await page.waitForTimeout(1000)
365
+ }
366
+ say(settled ? '上传收尾,可以发了' : '等不到上传结束的信号,仍然照发一次')
367
+ await page.waitForTimeout(800)
368
+ }
369
+
370
+ // 写死:prompt 原样递交 Muse,不 trim、不扩写、不改一个字(上面的 trim 只用来判空)。
371
+ await page.fill(COMPOSER, prompt)
372
+ await page.waitForTimeout(500)
373
+ await page.click(SEND, { label: IS_VIDEO ? '发送视频指令' : '发送生成指令' })
374
+
375
+ // 发送后地址不是立刻变的。实测:纯文字 2–4 秒;**带参考视频要 15–20 秒**
376
+ // (Muse 先把它排进队列才换页)。所以窗口给到 60 秒,中间只看两件事:
377
+ // 地址变了没有;输入框里那串字还在不在(还在就说明没发出去,可以补点一下)。
378
+ let threadUrl = ''
379
+ let clicks = 0
380
+ const sendDeadline = Date.now() + 60_000
381
+ while (Date.now() < sendDeadline) {
382
+ await page.waitForTimeout(1500)
383
+ threadUrl = await page.url()
384
+ if (isThread(threadUrl)) break
385
+ if (clicks >= 2) continue
386
+ const pending = await page.evaluate(() => {
387
+ const ta = document.querySelector('textarea[placeholder="消息"]')
388
+ return {
389
+ hasSend: !!document.querySelector('button[aria-label="发送"]'),
390
+ draft: ta ? (ta.value || '').length : -1,
391
+ }
392
+ })
393
+ // 输入框空了 = 已经发出去了,只是还没换页,别重复点。
394
+ if (pending.hasSend && pending.draft > 0) {
395
+ clicks += 1
396
+ say(`指令还压着没发出去,补点第 ${clicks} 次`)
397
+ try {
398
+ await page.click(SEND, { label: IS_VIDEO ? '发送视频指令' : '发送生成指令' })
399
+ } catch (error) {
400
+ say(`补点没点上:${String(error?.message ?? error).split('\n')[0]}`)
401
+ }
402
+ }
403
+ }
404
+
405
+ // 没登录会被打回落地页,那里没有 thread id。在这里就判掉,不等满超时。
406
+ if (!isThread(threadUrl)) {
407
+ say('当前页面不是一条旁聊')
408
+ emit({
409
+ threadUrl,
410
+ detail: REFS.length > 0
411
+ ? '素材挂上了但指令没发出去(发送按钮还没解禁时点的那一下是空点)。'
412
+ + '重调一次;仍然发不出去就打开 ego lite 看那一页卡在哪。'
413
+ : '多半是登录态过期:先在 ego lite 里登录 muse.ai,再调一次就好。',
414
+ })
415
+ return
416
+ }
417
+
418
+ // 等这一轮结束。**不能只看停止按钮**:带参考素材时 Muse 要先排队十几秒才起跑,
419
+ // 停止按钮又出现得晚、点得短,只看它会提前收手,产物还没挂上 DOM 就判结束了——
420
+ // 实测踩过:thread 有了、回复有了、media 却是 null。
421
+ // 所以判据改成「产物挂上了,并且停止按钮不在」,两条都满足才算这一轮真完。
422
+ // 写死(用户 2026-11-28 明确要求):
423
+ // 产物没生成出来、没下载落地,这一轮不许退出。
424
+ // 所以这里**没有**「等超时就算了」的分支。timeoutSec 只当上报间隔用,不当退出判据。
425
+ // 只要还在生成就一直等;停止按钮消失后再给收尾动画留时间;等不到就继续等,
426
+ // 每满一个上报间隔往 stderr 打一次现场,好让外面看得见它还活着。
427
+ const peek = () => page.evaluate(new Function(`return (${findMedia})(${JSON.stringify(KIND)})`))
428
+ const TICK = IS_VIDEO ? 4000 : 2500
429
+ let found = null
430
+ let waited = 0
431
+ let lastReport = 0
432
+ for (;;) {
433
+ found = await peek()
434
+ if (found) break
435
+ const generating = await page.evaluate(new Function(`return (${stillGenerating})()`))
436
+ waited += TICK
437
+ if (waited - lastReport >= GEN_TIMEOUT) {
438
+ lastReport = waited
439
+ const text = await page.evaluate(new Function(`return (${replies})()`))
440
+ say(`还在等产物:已等 ${Math.round(waited / 1000)}s,生成中=${generating},`
441
+ + `最近回复:${(text || []).slice(-1)[0] || '(无)'}`)
442
+ }
443
+ await page.waitForTimeout(TICK)
444
+ }
445
+ say(`产物已挂上,等了 ${Math.round(waited / 1000)}s:${found.how}`)
446
+ say(`命中产物(${found.how}):${found.aria} @ ${found.x},${found.y} ${found.w}x${found.h}`)
447
+
448
+ // 走坐标点,不用 CSS 选择器:role=button 的选择器 ego 解析不了
449
+ await page.mouse.click(found.x + Math.round(found.w / 2), found.y + Math.round(found.h / 2))
450
+ await page.waitForTimeout(IS_VIDEO ? 4000 : 2500)
451
+
452
+ // 弹层里找下载入口:图片是「下载」,视频预览也是「下载」。
453
+ // 弹层偶尔要一两秒才渲染完,取不到就再点一次产物,最多 8 轮——期间照样不退出。
454
+ let dl = null
455
+ for (let i = 0; i < 8; i += 1) {
456
+ const dialog = await page.evaluate(new Function(`return (${dialogItems})()`))
457
+ dl = dialog.items.find((it) => /下载|保存|download/i.test(it.label + it.text))
458
+ if (dl) break
459
+ const list = dialog.items.map((it) => it.label || it.text).filter(Boolean).slice(0, 8)
460
+ say(`弹层还没出下载入口(第 ${i + 1} 轮):${list.join('、') || '(无)'},再点一次产物`)
461
+ await page.mouse.click(found.x + Math.round(found.w / 2), found.y + Math.round(found.h / 2))
462
+ await page.waitForTimeout(IS_VIDEO ? 4000 : 2500)
463
+ }
464
+
465
+ // 产物落地这一关也不许退:下载按钮点不出来,就退回「在页面里把字节抓回来」。
466
+ let saved = null
467
+ if (dl) {
468
+ say(`下载入口:${dl.label || dl.text} @ ${dl.x},${dl.y}`)
469
+ const download = page.waitForEvent('download', { timeout: IS_VIDEO ? 240_000 : 120_000 })
470
+ await page.mouse.click(dl.x, dl.y)
471
+ saved = await download
472
+ } else {
473
+ say('没有下载入口,改成直接从页面抓产物字节')
474
+ }
475
+
476
+ const caption = niceName(found.aria)
477
+ const base = slug(nameHint || caption || (IS_VIDEO ? 'muse生成视频' : 'muse生成图片'))
478
+ const stamp = stampOf(new Date())
479
+ OUT_DIR_NOW = outDir
480
+ BASE_NOW = base
481
+ const pick = async (ext) => {
482
+ let p = join(outDir, `${base}_${stamp}${ext}`)
483
+ for (let i = 2; ; i += 1) {
484
+ try {
485
+ // 不覆盖已有文件:同一秒跑两次就加序号。
486
+ await fs.access(p)
487
+ p = join(outDir, `${base}_${stamp}_${i}${ext}`)
488
+ } catch {
489
+ return p
490
+ }
491
+ }
492
+ }
493
+
494
+ let target
495
+ if (dl) {
496
+ const suggested = saved.suggestedFilename() || ''
497
+ // 建议名里的扩展名常常是 webp(产物其实是 mp4),所以先存下来,落地后再按文件头改。
498
+ const ext = EXT_RE.exec(suggested)?.[0] ?? ANY_EXT.exec(found.aria)?.[0] ?? DEFAULT_EXT
499
+ target = await pick(ext)
500
+ await saved.saveAs(target)
501
+ } else {
502
+ const grabbed = await page.evaluate(`async () => {
503
+ const nodes = [...document.querySelectorAll('video, img')];
504
+ const last = nodes[nodes.length - 1];
505
+ const src = (last && (last.currentSrc || last.src)) || '';
506
+ if (!src) return { ok: false, why: '没找到带 src 的产物' };
507
+ const res = await fetch(src);
508
+ const buf = new Uint8Array(await res.arrayBuffer());
509
+ let s = '';
510
+ const CH = 0x8000;
511
+ for (let i = 0; i < buf.length; i += CH) s += String.fromCharCode(...buf.subarray(i, i + CH));
512
+ return { ok: true, b64: btoa(s), bytes: buf.length, type: res.headers.get('content-type') || '' };
513
+ }`)
514
+ if (!grabbed?.ok) throw new Error(`抓产物字节失败:${grabbed?.why ?? '未知原因'}`)
515
+ target = await pick(ANY_EXT.exec(found.aria)?.[0] ?? DEFAULT_EXT)
516
+ await fs.writeFile(target, Buffer.from(grabbed.b64, 'base64'))
517
+ say(`已从页面抓回 ${grabbed.bytes} 字节(${grabbed.type || '无 content-type'})`)
518
+ }
519
+
520
+ // 按文件头纠正扩展名:下载按钮给的名字与实际编码经常不一致,名字错了外面播不了。
521
+ const fixed = await matchExt(target)
522
+ if (fixed && fixed !== target) {
523
+ const renamed = target.replace(/\.[^.]+$/, fixed)
524
+ await fs.rename(target, renamed)
525
+ target = renamed
526
+ }
527
+
528
+ const stat = await fs.stat(target)
529
+ if (!stat.size) throw new Error('产物落地了但大小是 0,等同没生成')
530
+ const text = await page.evaluate(new Function(`return (${replies})()`))
531
+
532
+ emit({
533
+ ok: true,
534
+ threadUrl,
535
+ media: target,
536
+ bytes: stat.size,
537
+ caption,
538
+ reply: (text || []).slice(-2).join(' | '),
539
+ detail: '',
540
+ })
541
+ } catch (error) {
542
+ const why = String(error?.message ?? error).split('\n')[0]
543
+ // 主管写死的规矩:产物已经落地就不许报失败。走到异常也要先回看一遍磁盘。
544
+ const landed = await landedFile().catch(() => '')
545
+ if (landed) {
546
+ const size = await fs.stat(landed).then((s) => s.size).catch(() => 0)
547
+ if (size > 0) {
548
+ emit({
549
+ ok: true,
550
+ threadUrl,
551
+ media: landed,
552
+ bytes: size,
553
+ detail: `这一步报了「${why}」,但产物已经落地,按成功算。`,
554
+ })
555
+ return
556
+ }
557
+ }
558
+ emit({ detail: `驱动这一步没走完:${why}。产物还没落地,按规矩继续跑,不当作完成。` })
559
+ } finally {
560
+ // 失败的轮次什么都不留;成功的已经把文件拷出来了。
561
+ await task.finish({ keep: [] }).catch(() => {})
562
+ }
563
+ }
564
+
565
+ await main()