dsh-fish-soul 0.18.1 → 0.18.3

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.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  让一个 QQ 小号背后有"同一个人":固定人格、按人记记忆、有自己的生活节奏、会主动开口;同一个"她"同时出现在 QQ、B站、抖音。
4
4
 
5
- DSH 插件(单角色 `feiyu`)。版本 **0.18.1**。
5
+ DSH 插件(单角色 `feiyu`)。版本 **0.18.3**。
6
6
 
7
7
  QQ 交流群:**1125962189**
8
8
 
package/lib/browse.js CHANGED
@@ -439,7 +439,8 @@ export class BiliBrowser {
439
439
  const text = oneLine(m[2].replace(/^[「“"']|[」”"']$/g, ''), 60);
440
440
  if (!pick || text === '') return '';
441
441
  try {
442
- await this.client.replyComment({ type: 1, oid: v.aid, root: pick.rpid, parent: 0, message: text });
442
+ // 二级评论:B站要求 root 与 parent 同为被回那条的 rpid(parent: 0 会发成顶层评论,#124)
443
+ await this.client.replyComment({ type: 1, oid: v.aid, root: pick.rpid, parent: pick.rpid, message: text });
443
444
  setKv(this.db, this.replyDayKey(), this.repliedToday() + 1);
444
445
  setKv(this.db, 'bili.reply.last', { bvid: v.bvid, title: oneLine(v.title, 40), name: pick.name, text, root: pick.rpid, at: Date.now() });
445
446
  this.log('info', `[fish-soul] 回了 @${pick.name} 的评论:${text}`);
@@ -254,7 +254,10 @@ window.__ModuleLoader__.load({
254
254
  setBusy(false);
255
255
  if (!r?.ok) { notify(r?.error ?? "导入失败"); return; }
256
256
  setMx(null);
257
- notify(`导入了 ${r.emojis} 张表情、${r.expressions} 种说话方式、${r.terms} 个梗` + (r.emojiDup ? `(${r.emojiDup} 张已经有了)` : "") + ((r.warnings ?? []).length ? `;${r.warnings.join(";")}` : ""));
257
+ notify(`导入了 ${r.emojis} 张表情、${r.expressions} 种说话方式、${r.terms} 个梗`
258
+ + (r.emojiTagged ? `(${r.emojiTagged} 张看图打上了标签)` : "")
259
+ + (r.emojiDup ? `(${r.emojiDup} 张已经有了)` : "")
260
+ + ((r.warnings ?? []).length ? `;${r.warnings.join(";")}` : ""));
258
261
  }
259
262
  async function backupNow() {
260
263
  setBusy(true);
@@ -485,41 +488,48 @@ window.__ModuleLoader__.load({
485
488
  const [q, setQ] = react.useState("");
486
489
  const [qApplied, setQApplied] = react.useState("");
487
490
  const [source, setSource] = react.useState("");
491
+ const [kind, setKind] = react.useState("");
492
+ const [from, setFrom] = react.useState("");
493
+ const [to, setTo] = react.useState("");
488
494
  const [bulk, setBulk] = react.useState(false);
489
495
  const [sel, setSel] = react.useState(() => new Set());
490
496
  const [page, setPage] = react.useState(0);
491
497
  const [dateValue, setDateValue] = react.useState("");
498
+ const [moveTo, setMoveTo] = react.useState("");
492
499
  const [confirm, confirmNode] = useConfirm();
493
500
  const pageSize = bulk ? 100 : 100;
494
- const qs = new URLSearchParams({ ...(owner !== "all" ? { ownerId: owner } : {}), ...(qApplied ? { q: qApplied } : {}), ...(source ? { source } : {}), limit: String(pageSize), offset: String(page * pageSize) }).toString();
501
+ const qs = new URLSearchParams({ ...(owner !== "all" ? { ownerId: owner } : {}), ...(qApplied ? { q: qApplied } : {}), ...(source ? { source } : {}), ...(kind ? { kind } : {}), ...(from ? { from } : {}), ...(to ? { to } : {}), limit: String(pageSize), offset: String(page * pageSize) }).toString();
495
502
  const [data, load] = usePoll(api, `/inspector/overview${qs ? `?${qs}` : ""}`, 0);
496
503
  async function dropPending(id) {
497
504
  const r = await api("POST", "/inspector/forget", { targetType: "pending", id });
498
505
  if (r?.ok) { notify("已删掉这条待办"); load(); } else notify(r?.error ?? "删除失败");
499
506
  }
500
507
  const [adding, setAdding] = react.useState("");
501
- react.useEffect(() => { setSel(new Set()); setPage(0); }, [owner, qApplied, source, bulk]);
508
+ react.useEffect(() => { setSel(new Set()); setPage(0); }, [owner, qApplied, source, kind, from, to, bulk]);
502
509
  if (!data) return null;
503
510
  const persons = data.persons ?? [];
504
511
  const memories = data.memories ?? [];
505
512
  const pendings = data.pendings ?? [];
506
513
  const pill = (ownerId, label, title) => ui.Pill({ key: ownerId, active: owner === ownerId, className: "fs-pill", "aria-pressed": owner === ownerId, title, onClick: () => setOwner(ownerId), children: label });
507
514
  const onSelect = (id, on) => setSel((prev) => { const next = new Set(prev); if (on) next.add(id); else next.delete(id); return next; });
508
- const filter = { ownerId: owner, q: qApplied, source };
509
- const narrowed = owner !== "all" || qApplied !== "" || source !== "";
515
+ const filter = { ownerId: owner, q: qApplied, source, kind, from, to };
516
+ const narrowed = owner !== "all" || qApplied !== "" || source !== "" || kind !== "" || from !== "" || to !== "";
510
517
  async function runBulk(action, value, label, byFilter = false) {
511
518
  const target = byFilter ? { filter } : { ids: [...sel] };
512
- if (byFilter) {
519
+ if (byFilter || action === "owner") {
513
520
  const dry = await api("POST", "/inspector/bulk", { ...target, action, value, dryRun: true });
514
521
  if (!dry?.ok) { notify(dry?.error ?? "操作失败"); return; }
515
522
  if (dry.matched === 0) { notify("没有符合条件的"); return; }
516
- if (!(await confirm({ title: label, description: `符合当前筛选的 ${dry.matched} 条,确定?`, danger: action === "forget" }))) return;
523
+ const desc = byFilter ? `符合当前筛选的 ${dry.matched} 条,确定?` : `把选中的 ${dry.matched} 条${label},确定?`;
524
+ if (!(await confirm({ title: label, description: desc, danger: action === "forget" }))) return;
517
525
  } else if (action === "forget" && !(await confirm({ title: "删除记忆", description: `删掉选中的 ${sel.size} 条?(能在人物卡里恢复)`, danger: true }))) return;
518
526
  const r = await api("POST", "/inspector/bulk", { ...target, action, value });
519
527
  if (r?.ok) { notify(`${label}:${r.changed} 条`); setSel(new Set()); load(); } else notify(r?.error ?? "操作失败");
520
528
  }
521
529
  const SOURCES = [["", "所有来源"], ["chat", "聊天里记的"], ["history-import", "导入(聊天记录)"], ["import", "导入(记忆文件)"], ["manual", "主人手动加的"], ["weekly", "周记"]];
530
+ const KIND_OPTIONS = [["", "所有类型"], ...Object.entries(KIND).filter(([k]) => k !== "weekly" && k !== "diary")];
522
531
  const n = sel.size;
532
+ const moveName = moveTo === "" ? "" : moveTo === "self" ? "她自己" : persons.find((p) => p.ownerId === moveTo)?.displayName ?? moveTo;
523
533
  const bulkBar = !bulk ? null : h("div", { className: "fs-row" },
524
534
  h("div", { className: "fs-ctl", style: { flexWrap: "wrap", gap: "6px" } },
525
535
  Button({ variant: "ghost", onClick: () => setSel(n === memories.length ? new Set() : new Set(memories.map((m) => m.id))) }, n === memories.length && n > 0 ? "全不选" : `全选这 ${memories.length} 条`),
@@ -531,8 +541,14 @@ window.__ModuleLoader__.load({
531
541
  Input({ type: "date", value: dateValue, "aria-label": "批量事件日期", onChange: (e) => setDateValue(e.target.value) }),
532
542
  Button({ variant: "ghost", disabled: n === 0 || dateValue === "", onClick: () => runBulk("sortDate", dateValue, "事件日期已改") }, "设日期"),
533
543
  Button({ variant: "ghost", disabled: n === 0, onClick: () => runBulk("sortDate", null, "事件日期已清空") }, "清日期"),
544
+ ui.Select({ value: moveTo, "aria-label": "搬到谁", onChange: (e) => setMoveTo(e.target.value) },
545
+ h("option", { value: "" }, "选择目标"),
546
+ ...persons.map((p) => h("option", { key: p.ownerId, value: p.ownerId }, p.ownerId === "self" ? "她自己" : p.displayName))),
547
+ Button({ variant: "ghost", disabled: n === 0 || moveTo === "", onClick: () => runBulk("owner", moveTo, `搬给${moveName}`) }, "搬给"),
534
548
  h("span", { className: "fs-fill-gap" }),
535
- Button({ variant: "ghost", disabled: !narrowed, title: narrowed ? "删掉符合当前筛选(人 / 来源 / 包含的字)的全部记忆,不只是这页显示的" : "先选一个人、来源或输入要包含的字", onClick: () => runBulk("forget", null, "按筛选删除", true) },
549
+ Button({ variant: "ghost", disabled: !narrowed || moveTo === "", title: narrowed ? "把符合当前筛选(人 / 来源 / 类型 / 日期 / 包含的字)的记忆全部搬给这个人,不只是这页显示的" : "先选一个人、来源、类型、日期或输入要包含的字", onClick: () => runBulk("owner", moveTo, `搬给${moveName}`, true) },
550
+ `符合筛选的都搬给${moveName || "…"}`),
551
+ Button({ variant: "ghost", disabled: !narrowed, title: narrowed ? "删掉符合当前筛选(人 / 来源 / 类型 / 日期 / 包含的字)的全部记忆,不只是这页显示的" : "先选一个人、来源、类型、日期或输入要包含的字", onClick: () => runBulk("forget", null, "按筛选删除", true) },
536
552
  `删掉符合筛选的全部${data.matchedTotal != null ? ` ${data.matchedTotal} 条` : ""}`)));
537
553
  async function add() {
538
554
  const r = await api("POST", "/inspector/memory-add", { ownerId: owner, content: adding, importance: 3 });
@@ -557,7 +573,14 @@ window.__ModuleLoader__.load({
557
573
  ...persons.map((p) => pill(p.ownerId, p.ownerId === "self" ? "她自己" : p.displayName, p.ownerId === "self" ? undefined : `${stageLabel(p.relationStage)} · ${p.memoryCount} 条`))),
558
574
  h("div", { className: "fs-row" },
559
575
  Input({ value: q, className: "wide", placeholder: "搜记忆内容(回车)", "aria-label": "搜记忆内容", onChange: (e) => setQ(e.target.value), onKeyDown: (e) => { if (e.key === "Enter") setQApplied(q.trim()); }, onBlur: () => setQApplied(q.trim()) }),
560
- ui.Select({ value: source, "aria-label": "来源", onChange: (e) => setSource(e.target.value) }, ...SOURCES.map(([v, l]) => h("option", { key: v, value: v }, l)))),
576
+ ui.Select({ value: source, "aria-label": "来源", onChange: (e) => setSource(e.target.value) }, ...SOURCES.map(([v, l]) => h("option", { key: v, value: v }, l))),
577
+ ui.Select({ value: kind, "aria-label": "类型", onChange: (e) => setKind(e.target.value) }, ...KIND_OPTIONS.map(([v, l]) => h("option", { key: v, value: v }, l)))),
578
+ h("div", { className: "fs-row" },
579
+ h("div", { className: "fs-ctl" },
580
+ h("span", { className: "fs-unit" }, "日期"),
581
+ Input({ type: "date", value: from, "aria-label": "日期从", onChange: (e) => setFrom(e.target.value) }),
582
+ h("span", { className: "fs-unit" }, "到"),
583
+ Input({ type: "date", value: to, "aria-label": "日期到", onChange: (e) => setTo(e.target.value) }))),
561
584
  bulkBar,
562
585
  owner !== "all" ? h("div", { className: "fs-row" },
563
586
  Input({ value: adding, className: "wide", placeholder: "手动记一条(比如:她不吃香菜)", onChange: (e) => setAdding(e.target.value), onKeyDown: (e) => { if (e.key === "Enter" && adding.trim()) add(); } }),
@@ -694,7 +717,8 @@ window.__ModuleLoader__.load({
694
717
  load();
695
718
  }
696
719
  // 没标签的进不了「按感觉挑」的池子(pickByFeel 只认有标签的),所以这个数字是问题的入口
697
- const untaggedCount = items.filter((x) => (x.tags ?? []).length === 0).length;
720
+ // 文件已经没了的记录不算:它永远打不上标签,留在数字里只会让人一直点「补标签」(#118)
721
+ const untaggedCount = items.filter((x) => (x.tags ?? []).length === 0 && x.exists !== false).length;
698
722
  async function backfill() {
699
723
  setBusy(true);
700
724
  const r = await api("POST", "/stickers/backfill", { workspacePath: data.workspacePath ?? "" });
package/lib/db.js CHANGED
@@ -226,7 +226,11 @@ const MIGRATIONS = [
226
226
  'ALTER TABLE chat_session ADD COLUMN merged_into TEXT',
227
227
  // #80:待办被「顺口提起」过(status='surfaced')的时间。
228
228
  // 提起不等于说到——那轮她没提,这条以前就永远消失了;现在过一阵能退回 pending 重来
229
- 'ALTER TABLE pending ADD COLUMN surfaced_at INTEGER'
229
+ 'ALTER TABLE pending ADD COLUMN surfaced_at INTEGER',
230
+ // #126:weekly_source_changed 的定义改了(owner_id 不再算「来源变了」)。
231
+ // 触发器是 CREATE TRIGGER IF NOT EXISTS 建的,老库不会自己换定义 —— 先摘掉,
232
+ // 后面建触发器那段按新定义重建(每次启动收敛一次)。
233
+ 'DROP TRIGGER IF EXISTS weekly_source_changed'
230
234
  ];
231
235
 
232
236
  /**
@@ -254,8 +258,10 @@ export function openDatabase() {
254
258
  try { db.exec(sql); } catch { /* 已迁移 */ }
255
259
  }
256
260
  db.exec(`
257
- CREATE TRIGGER IF NOT EXISTS weekly_source_changed AFTER UPDATE OF content,status,valid_to,visibility,owner_id,channel,channel_id,kind,about ON memory
258
- WHEN OLD.content IS NOT NEW.content OR OLD.status IS NOT NEW.status OR OLD.valid_to IS NOT NEW.valid_to OR OLD.visibility IS NOT NEW.visibility OR OLD.owner_id IS NOT NEW.owner_id OR OLD.channel IS NOT NEW.channel OR OLD.channel_id IS NOT NEW.channel_id OR OLD.kind IS NOT NEW.kind OR OLD.about IS NOT NEW.about
261
+ -- 周记的失效条件是「来源内容变了」。owner_id 变了只说明这条记忆归谁,内容没变,
262
+ -- 周记照样是有效的 —— 所以 owner_id 不在 OF 列表里(#126:搬主人不该把周记标废)。
263
+ CREATE TRIGGER IF NOT EXISTS weekly_source_changed AFTER UPDATE OF content,status,valid_to,visibility,channel,channel_id,kind,about ON memory
264
+ WHEN OLD.content IS NOT NEW.content OR OLD.status IS NOT NEW.status OR OLD.valid_to IS NOT NEW.valid_to OR OLD.visibility IS NOT NEW.visibility OR OLD.channel IS NOT NEW.channel OR OLD.channel_id IS NOT NEW.channel_id OR OLD.kind IS NOT NEW.kind OR OLD.about IS NOT NEW.about
259
265
  BEGIN
260
266
  UPDATE memory SET status='outdated', valid_to=NEW.updated_at, updated_at=NEW.updated_at WHERE id IN (SELECT summary_id FROM weekly_source WHERE source_id=OLD.id) AND status='active';
261
267
  DELETE FROM vec WHERE memory_id IN (SELECT summary_id FROM weekly_source WHERE source_id=OLD.id);
@@ -270,6 +276,23 @@ export function openDatabase() {
270
276
  return db;
271
277
  }
272
278
 
279
+ /**
280
+ * 搬主人时的周记触发器安全路径:搬之前摘掉 `weekly_protect`,搬完(含抛错)按原定义重建。
281
+ *
282
+ * 不改触发器语义(周记照样不能被编辑 / 不能被恢复),只放行「换主人」这一种操作。
283
+ * 用共享的常量重建,保证重建出来的和 openDatabase 建库时的定义是同一份。
284
+ * @template T @param {DatabaseSync} db @param {() => T} fn @returns {T}
285
+ */
286
+ export function withoutWeeklyProtect(db, fn) {
287
+ db.exec('DROP TRIGGER IF EXISTS weekly_protect');
288
+ try {
289
+ return fn();
290
+ } finally {
291
+ // 无论搬成功还是抛错,触发器都要回来(它守的是周记不被篡改)。
292
+ db.exec(WEEKLY_PROTECT_SQL);
293
+ }
294
+ }
295
+
273
296
  /**
274
297
  * 把一个人的记忆搬给另一个人(认人合并 / 主人换号时用)。
275
298
  *
@@ -279,20 +302,14 @@ export function openDatabase() {
279
302
  * 认人阶段就断,整条通道不回话(而报错信息是「derived weekly summary cannot be
280
303
  * edited or restored」,根本指不到真正的操作上)。
281
304
  *
282
- * 修法:搬之前临时摘掉触发器,搬完立刻按原定义重建 —— **不改触发器语义**
283
- * (周记照样不能被编辑 / 不能被恢复),只是放行「换主人」这一种操作。
284
- * 用 try/finally 保证触发器一定重建,哪怕搬的过程抛错。
305
+ * 修法:走 withoutWeeklyProtect —— 搬之前临时摘掉触发器,搬完立刻按原定义重建。
306
+ * try/finally 保证触发器一定重建,哪怕搬的过程抛错。
285
307
  */
286
308
  export function reassignMemoryOwner(db, from, to) {
287
- db.exec('DROP TRIGGER IF EXISTS weekly_protect');
288
- try {
309
+ withoutWeeklyProtect(db, () => {
289
310
  db.prepare('UPDATE memory SET owner_id = ? WHERE owner_id = ?').run(to, from);
290
311
  db.prepare('UPDATE pending SET owner_id = ? WHERE owner_id = ?').run(to, from);
291
- } finally {
292
- // 无论搬成功还是抛错,触发器都要回来(它守的是周记不被篡改)。
293
- // 用共享的常量:保证重建出来的和 openDatabase 建库时的定义是同一份
294
- db.exec(WEEKLY_PROTECT_SQL);
295
- }
312
+ });
296
313
  }
297
314
 
298
315
  /** kv 读写(虚拟钟快照、重建游标、Dream 水位等跨重启状态)。 */
@@ -103,8 +103,9 @@ export class DouyinBrowser {
103
103
  * @param {[number, number]} [deps.dwellMs] 推荐页每条看多久(真实毫秒)
104
104
  * @param {(opts: {browser: object, id: string, commentLimit?: number}) => Promise<object>} [deps.readDetail]
105
105
  * @param {import('./douyin-http.js').DouyinHttp} [deps.http] 纯 HTTP 客户端(http 模式用)
106
+ * @param {object} [deps.timing] 页面操作的时间上限(eval / send / next 的总预算)
106
107
  */
107
- constructor({ db, clock, host, getConfig, callLlm, persona, worker, log, dwellMs = [5000, 20000], readDetail = detail, settleMs = 8000, fetchImpl, share, note, http, frames }) {
108
+ constructor({ db, clock, host, getConfig, callLlm, persona, worker, log, dwellMs = [5000, 20000], readDetail = detail, settleMs = 8000, fetchImpl, share, note, http, frames, timing = {} }) {
108
109
  this.share = share ?? null;
109
110
  this.note = note ?? null;
110
111
  this.framesOf = frames ?? null; // 抽九宫格看画面(可缺:没有就只读文字)
@@ -124,6 +125,7 @@ export class DouyinBrowser {
124
125
  this.running = false;
125
126
  this.httpBroken = false; // 这轮试过纯 HTTP 不行 → 退回浏览器
126
127
  this.described = new Map();
128
+ this.tm = { evalTimeoutMs: 12_000, nextBudgetMs: 30_000, ...timing }; // 页面卡死时不能挂死或霸住浏览器锁
127
129
  }
128
130
 
129
131
  cfg() {
@@ -215,32 +217,47 @@ export class DouyinBrowser {
215
217
  return lo + Math.floor(Math.random() * Math.max(0, hi - lo));
216
218
  }
217
219
 
218
- async activeVideo(b) {
219
- const r = await b.eval(ACTIVE_VIDEO_JS).catch(() => null);
220
+ async activeVideo(b, timeoutMs = this.tm.evalTimeoutMs) {
221
+ const r = await b.eval(ACTIVE_VIDEO_JS, { timeoutMs }).catch(() => null);
220
222
  return r && r.ok ? r : null;
221
223
  }
222
224
 
223
225
  /** 划到下一条:先点"下一条"箭头,不行按 ↓,再不行滚轮;确认 id 变了。 */
224
226
  async next(b, prevId) {
227
+ // 页面卡死时 eval 永不回包 ⇒ 每次 eval 都有短超时,整轮还有总预算
228
+ //(只给单次超时不够:8 轮 × 60 秒照样霸着浏览器独占锁)。
229
+ const end = Date.now() + this.tm.nextBudgetMs;
230
+ const left = () => end - Date.now();
231
+ const timeout = () => Math.max(1, Math.min(this.tm.evalTimeoutMs, left()));
232
+ // 预算耗尽后**不能再发起** eval / send / 睡眠:max(1,…) 只防 0,不是通行证。
233
+ // 否则点「下一条」失败后,键盘 / 滚轮分支会各在预算之外再等一次超时,照样霸锁。
234
+ const expired = () => left() <= 0;
225
235
  const changed = async () => {
226
236
  for (let i = 0; i < 8; i++) {
227
- await sleep(400);
228
- const v = await this.activeVideo(b);
237
+ if (expired()) return false;
238
+ await sleep(Math.min(400, Math.max(0, left())));
239
+ if (expired()) return false;
240
+ const v = await this.activeVideo(b, timeout());
229
241
  if (v && v.id && v.id !== prevId) return true;
230
242
  }
231
243
  return false;
232
244
  };
233
- if (await b.eval(CLICK_NEXT_JS).catch(() => false) && await changed()) return true;
245
+ if (expired()) return false;
246
+ if (await b.eval(CLICK_NEXT_JS, { timeoutMs: timeout() }).catch(() => false) && await changed()) return true;
247
+ if (expired()) return false;
234
248
  try {
235
249
  for (const type of ['keyDown', 'keyUp']) {
236
- await b.send('Input.dispatchKeyEvent', { type, key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40 }, b.sessionId);
250
+ if (expired()) return false;
251
+ await b.send('Input.dispatchKeyEvent', { type, key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40 }, b.sessionId, timeout());
237
252
  }
238
253
  if (await changed()) return true;
239
254
  } catch { /* 换滚轮 */ }
255
+ if (expired()) return false;
240
256
  try {
241
- const m = await b.send('Page.getLayoutMetrics', {}, b.sessionId);
257
+ const m = await b.send('Page.getLayoutMetrics', {}, b.sessionId, timeout());
242
258
  const vp = m?.cssVisualViewport ?? {};
243
- await b.send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: Math.round((vp.clientWidth ?? 800) / 2), y: Math.round((vp.clientHeight ?? 600) / 2), deltaX: 0, deltaY: 600 }, b.sessionId);
259
+ if (expired()) return false;
260
+ await b.send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: Math.round((vp.clientWidth ?? 800) / 2), y: Math.round((vp.clientHeight ?? 600) / 2), deltaX: 0, deltaY: 600 }, b.sessionId, timeout());
244
261
  if (await changed()) return true;
245
262
  } catch { /* 划不动 */ }
246
263
  return false;
@@ -257,13 +274,13 @@ export class DouyinBrowser {
257
274
  const r = el.getBoundingClientRect();
258
275
  if (r.width < 2 || r.height < 2) return null;
259
276
  return { x: r.x + r.width / 2, y: r.y + r.height / 2, w: r.width, h: r.height };
260
- })()`).catch(() => null);
277
+ })()`, { timeoutMs: this.tm.evalTimeoutMs }).catch(() => null);
261
278
  if (!pos || typeof pos.x !== 'number') return false;
262
- const m = await b.send('Page.getLayoutMetrics', {}, b.sessionId).catch(() => null);
279
+ const m = await b.send('Page.getLayoutMetrics', {}, b.sessionId, this.tm.evalTimeoutMs).catch(() => null);
263
280
  const vp = m?.cssVisualViewport ?? m?.cssLayoutViewport ?? {};
264
281
  if (pos.x < 0 || pos.y < 0 || pos.x > (vp.clientWidth ?? 0) || pos.y > (vp.clientHeight ?? 0)) return false;
265
282
  for (const type of ['mouseMoved', 'mousePressed', 'mouseReleased']) {
266
- await b.send('Input.dispatchMouseEvent', { type, x: Math.round(pos.x), y: Math.round(pos.y), button: 'left', clickCount: type === 'mouseMoved' ? 0 : 1 }, b.sessionId);
283
+ await b.send('Input.dispatchMouseEvent', { type, x: Math.round(pos.x), y: Math.round(pos.y), button: 'left', clickCount: type === 'mouseMoved' ? 0 : 1 }, b.sessionId, this.tm.evalTimeoutMs);
267
284
  }
268
285
  await sleep(3000);
269
286
  return await this.activeVideo(b) !== null;
@@ -445,8 +462,8 @@ export class DouyinBrowser {
445
462
  const b = this.host?.running === true ? this.host?.browser : null;
446
463
  if (b && typeof b.eval === 'function') {
447
464
  try {
448
- if (!(await commentBridgeReady(b))) await installCommentBridge(b);
449
- const r = await callBridge(b, 'collect', { awemeId: v.id, collect: true });
465
+ if (!(await commentBridgeReady(b, { timeoutMs: this.tm.evalTimeoutMs }))) await installCommentBridge(b, { timeoutMs: this.tm.evalTimeoutMs });
466
+ const r = await callBridge(b, 'collect', { awemeId: v.id, collect: true }, { timeoutMs: this.tm.evalTimeoutMs });
450
467
  if (r?.ok === true) {
451
468
  collected = r.collected !== false;
452
469
  done = true;
@@ -520,8 +537,8 @@ export class DouyinBrowser {
520
537
  // 两条都走会让同一条视频被赞两次(一个走接口、一个走 UI)。
521
538
  let bridgeRan = false;
522
539
  try {
523
- if (!(await commentBridgeReady(b))) await installCommentBridge(b);
524
- const r = await callBridge(b, 'digg', { awemeId: v.id, diggType: 1 });
540
+ if (!(await commentBridgeReady(b, { timeoutMs: this.tm.evalTimeoutMs }))) await installCommentBridge(b, { timeoutMs: this.tm.evalTimeoutMs });
541
+ const r = await callBridge(b, 'digg', { awemeId: v.id, diggType: 1 }, { timeoutMs: this.tm.evalTimeoutMs });
525
542
  // 这两种「失败」说明的是**这个页面用不了桥**(不是"没赞上"),要退回点按钮:
526
543
  // - 桥没装上(window.__fishComment 不存在)
527
544
  // - 桥发出了请求但拿回的不是 JSON(页面不是真抖音,比如测试用的本地假站)
@@ -540,7 +557,7 @@ export class DouyinBrowser {
540
557
  this.log('warn', `[fish-soul] 抖音点赞接口桥失败:${errText(error)},退回点按钮`);
541
558
  }
542
559
  if (!bridgeRan) {
543
- try { liked = await b.eval(CLICK_LIKE_JS) === true; } catch { liked = false; }
560
+ try { liked = await b.eval(CLICK_LIKE_JS, { timeoutMs: this.tm.evalTimeoutMs }) === true; } catch { liked = false; }
544
561
  }
545
562
  }
546
563
  // 收藏:和点赞同一族(commit/* 写接口,必须页面内发)。
@@ -548,8 +565,8 @@ export class DouyinBrowser {
548
565
  let collected = false;
549
566
  if (wantCollect) {
550
567
  try {
551
- if (!(await commentBridgeReady(b))) await installCommentBridge(b);
552
- const r = await callBridge(b, 'collect', { awemeId: v.id, collect: true });
568
+ if (!(await commentBridgeReady(b, { timeoutMs: this.tm.evalTimeoutMs }))) await installCommentBridge(b, { timeoutMs: this.tm.evalTimeoutMs });
569
+ const r = await callBridge(b, 'collect', { awemeId: v.id, collect: true }, { timeoutMs: this.tm.evalTimeoutMs });
553
570
  if (r?.ok === true) {
554
571
  collected = r.collected !== false;
555
572
  if (r.confirmed === false) this.log('info', '[fish-soul] 抖音收藏提交了(返回里没有 collect_stat,按成功算)');
@@ -652,8 +652,8 @@ export function douyinSocialDriver(host, timing = {}) {
652
652
  async emojiCodes() {
653
653
  const br = b();
654
654
  if (!this._emojiCodes) {
655
- if (!(await commentBridgeReady(br))) await installCommentBridge(br);
656
- const r = await callBridge(br, 'emojiList', {});
655
+ if (!(await commentBridgeReady(br, { timeoutMs: tm.evalTimeoutMs }))) await installCommentBridge(br, { timeoutMs: tm.evalTimeoutMs });
656
+ const r = await callBridge(br, 'emojiList', {}, { timeoutMs: tm.evalTimeoutMs });
657
657
  this._emojiCodes = r.ok ? (r.list || []).map((e) => e.name).filter(Boolean) : [];
658
658
  this._emojiCodesAt = Date.now();
659
659
  }
@@ -185,12 +185,16 @@ export function previewMaiBotExtras(dbPath, { titleOf = (c) => c } = {}) {
185
185
 
186
186
  /**
187
187
  * 导入。
188
- * @param {{dbPath: string, slang: {importEntries: Function}, stickers: {importImage: Function}|null, workspacePath: string|null,
189
- * emojis?: boolean, expressions?: boolean, jargons?: boolean, maxEmojis?: number}} opts
188
+ *
189
+ * `vision` 给了 → 导入的表情顺手看图打标签(没标签的表情进不了「按感觉挑」的池子,#118)。
190
+ * 不给 → 只导入不打标(跟以前一样)。
191
+ *
192
+ * @param {{dbPath: string, slang: {importEntries: Function}, stickers: {importImage: Function, collected?: Function}|null, workspacePath: string|null,
193
+ * vision?: Function|null, emojis?: boolean, expressions?: boolean, jargons?: boolean, maxEmojis?: number}} opts
190
194
  */
191
- export function importMaiBotExtras({ dbPath, slang, stickers, workspacePath, emojis = true, expressions = true, jargons = true, maxEmojis = DEFAULT_MAX_EMOJIS }) {
195
+ export async function importMaiBotExtras({ dbPath, slang, stickers, workspacePath, vision = null, emojis = true, expressions = true, jargons = true, maxEmojis = DEFAULT_MAX_EMOJIS }) {
192
196
  const x = readMaiBotExtras(dbPath);
193
- const out = { emojis: 0, emojiDup: 0, emojiFailed: 0, expressions: 0, terms: 0, skipped: 0, chats: 0, warnings: [...x.warnings] };
197
+ const out = { emojis: 0, emojiDup: 0, emojiFailed: 0, emojiTagged: 0, expressions: 0, terms: 0, skipped: 0, chats: 0, warnings: [...x.warnings] };
194
198
  if (expressions || jargons) {
195
199
  const per = new Map();
196
200
  const bucket = (c) => { if (!per.has(c)) per.set(c, { terms: [], expressions: [] }); return per.get(c); };
@@ -206,6 +210,21 @@ export function importMaiBotExtras({ dbPath, slang, stickers, workspacePath, emo
206
210
  if (!stickers || !workspacePath) out.warnings.push('表情包没导:QQ 工作区还没准备好(先连一次 QQ)');
207
211
  else {
208
212
  const cap = Math.min(100, Math.max(0, Math.floor(Number(maxEmojis)) || DEFAULT_MAX_EMOJIS));
213
+ // 打标签也限量:一次别把模型打爆 —— 只在「真会问模型」的那一次扣额度
214
+ let tagBudget = cap;
215
+ // 这一轮开始时每张图有没有标签:已经有标签的(重复的老表情、summary 捡出来的)不算
216
+ // 「这次看图打上的」—— 面板报的是真的被看图补上标签的张数,不然用户以为修好了其实没有。
217
+ const hadTags = new Map();
218
+ // 每张图「现在」有没有标签:导入 / 打标之后随时更新。
219
+ // tagByVision 遇到有标签的直接返回旧标签(根本不问模型)—— 这种不算「要问模型」。
220
+ const hasTags = new Map();
221
+ for (const row of stickers.collected?.() ?? []) {
222
+ if (row.workspacePath !== workspacePath) continue;
223
+ hadTags.set(row.file, (row.tags ?? []).length > 0);
224
+ hasTags.set(row.file, (row.tags ?? []).length > 0);
225
+ }
226
+ // 同一个文件可能有多条记录(导入一条 + 重复一条):报的张数按文件算,不按记录算
227
+ const taggedFiles = new Set();
209
228
  for (const e of x.emojis) {
210
229
  if (out.emojis >= cap) break;
211
230
  let bytes;
@@ -220,6 +239,25 @@ export function importMaiBotExtras({ dbPath, slang, stickers, workspacePath, emo
220
239
  else if (r.dup) out.emojiDup++;
221
240
  else if (r.full) { out.warnings.push('_stickers 满了(300 张),剩下的没导'); break; }
222
241
  else out.emojiFailed++;
242
+ // 看图打标:导进来的表情没标签就进不了「按感觉挑」的池子(#118)
243
+ // 重复导入的老表情也接着打 —— 它可能一直都没标签
244
+ if (!r.file) continue;
245
+ if (r.ok !== true && r.dup !== true) continue;
246
+ if (typeof vision !== 'function') continue;
247
+ // 已经有标签的:看图那步会直接返回旧标签(不重复问模型),不算「这次打上的」
248
+ const had = r.ok === true ? (r.tags ?? []).length > 0 : hadTags.get(r.file) === true;
249
+ // 刚导进来的那张:现在有没有标签就是 summary 捡出来的那几个
250
+ if (r.ok === true) hasTags.set(r.file, had);
251
+ // 额度用完了 → 这次不打标
252
+ if (tagBudget <= 0) continue;
253
+ // 额度只在「真会问模型」的那一次扣:已经有标签的老表情 tagByVision 会早退,
254
+ // 一分额度都不该吃(不然额度被老表情吃光,真正要打标的新图一张都轮不上,
255
+ // 导多少遍都不收敛 —— 跟 #118 修的是同一个症状)
256
+ if (hasTags.get(r.file) !== true) tagBudget--;
257
+ const tags = await stickers.tagByVision?.({ file: r.file, bytes, mediaType, workspacePath }, vision) ?? [];
258
+ if (tags.length > 0) hasTags.set(r.file, true);
259
+ // 同一个文件可能有多条记录:报的张数按文件算,不按记录算
260
+ if (tags.length > 0 && !had && !taggedFiles.has(r.file)) { taggedFiles.add(r.file); out.emojiTagged++; }
223
261
  }
224
262
  }
225
263
  }
@@ -1,10 +1,12 @@
1
1
  import { isCalendarDate } from './time-util.js';
2
+ import { withoutWeeklyProtect } from './db.js';
2
3
  /**
3
4
  * memory-bulk.js —— 记忆批量操作(设置页「记忆」里勾选多条 / 按筛选条件一次处理)。
4
5
  *
5
6
  * 选法:ids(勾的那几条)或 filter(某个人 / 内容包含 / 来源),二选一;按筛选最多一次 5000 条。
6
7
  * 动作:forget(删 = 标 archived + 清向量,能在人物卡「改掉 / 过时的」里恢复)、restore(恢复删掉 / 过时的)、
7
- * importance(1~5)、kind(事实 / 事件 / 感受 / 聊过)、visibility(normal / private)。
8
+ * importance(1~5)、kind(事实 / 事件 / 感受 / 聊过)、visibility(normal / private)、
9
+ * owner(换主人:把勾选的那几条搬到另一个人名下,含「她自己」)。
8
10
  * dryRun 只数会动到几条,不改。
9
11
  */
10
12
  export const KINDS = ['fact', 'event', 'feeling', 'episode'];
@@ -18,16 +20,26 @@ export const SOURCES = {
18
20
  const MAX_IDS = 1000;
19
21
  const MAX_FILTER = 5000;
20
22
 
23
+ /** 记忆的日历日期口径:事件日期优先,没有就按创建时间落本地日历日(列表排序、日期筛选同口径)。 */
24
+ export const MEMORY_DATE = "COALESCE(sort_date, date(created_at / 1000, 'unixepoch', 'localtime'))";
25
+
21
26
  /** 筛选条件 → WHERE(只认白名单字段;内容包含用 instr,不拼用户输入)。 */
22
27
  export function filterWhere(filter = {}, { archived = false } = {}) {
23
28
  const where = ["character_id = 'feiyu'", archived ? "status IN ('archived', 'outdated', 'superseded')" : "status = 'active' AND valid_to IS NULL"];
24
29
  const params = [];
25
- if (filter.ownerId && filter.ownerId !== 'all') { where.push('owner_id = ?'); params.push(String(filter.ownerId)); }
30
+ // 够不够窄(防误删全部):光有角色 / 状态不算,真筛了东西才算
31
+ let narrowed = false;
32
+ if (filter.ownerId && filter.ownerId !== 'all') { where.push('owner_id = ?'); params.push(String(filter.ownerId)); narrowed = true; }
26
33
  const q = String(filter.q ?? '').trim();
27
- if (q !== '') { where.push('instr(content, ?) > 0'); params.push(q.slice(0, 100)); }
28
- if (filter.source && SOURCES[filter.source]) where.push(`(${SOURCES[filter.source]})`);
29
- if (filter.visibility === 'private' || filter.visibility === 'normal') { where.push('visibility = ?'); params.push(filter.visibility); }
30
- return { sql: where.join(' AND '), params, narrowed: where.length > 2 };
34
+ if (q !== '') { where.push('instr(content, ?) > 0'); params.push(q.slice(0, 100)); narrowed = true; }
35
+ if (filter.source && SOURCES[filter.source]) { where.push(`(${SOURCES[filter.source]})`); narrowed = true; }
36
+ if (filter.visibility === 'private' || filter.visibility === 'normal') { where.push('visibility = ?'); params.push(filter.visibility); narrowed = true; }
37
+ if (KINDS.includes(filter.kind)) { where.push('kind = ?'); params.push(filter.kind); narrowed = true; }
38
+ const from = String(filter.from ?? '').trim();
39
+ if (isCalendarDate(from)) { where.push(`${MEMORY_DATE} >= ?`); params.push(from); narrowed = true; }
40
+ const to = String(filter.to ?? '').trim();
41
+ if (isCalendarDate(to)) { where.push(`${MEMORY_DATE} <= ?`); params.push(to); narrowed = true; }
42
+ return { sql: where.join(' AND '), params, narrowed };
31
43
  }
32
44
 
33
45
  /**
@@ -46,12 +58,13 @@ export function bulkMemory({ db, clock, worker, ids, filter, action, value, dryR
46
58
  rows = db.prepare(`SELECT id, content, kind FROM memory WHERE character_id = 'feiyu' AND ${status} AND id IN (${list.map(() => '?').join(',')})`).all(...list);
47
59
  } else if (filter && typeof filter === 'object') {
48
60
  const { sql, params, narrowed } = filterWhere(filter, { archived: restore });
49
- if (!narrowed) return { ok: false, error: '按条件批量至少要选一个人、来源或输入要包含的字(防止误删全部)' };
61
+ if (!narrowed) return { ok: false, error: '按条件批量至少要选一个人、来源、类型、日期或输入要包含的字(防止误删全部)' };
50
62
  rows = db.prepare(`SELECT id, content, kind FROM memory WHERE ${sql} ORDER BY id DESC LIMIT ${MAX_FILTER + 1}`).all(...params);
51
63
  if (rows.length > MAX_FILTER) return { ok: false, error: `符合条件的超过 ${MAX_FILTER} 条,条件再收窄一点` };
52
64
  } else return { ok: false, error: '要么勾选几条,要么给筛选条件' };
53
65
 
54
66
  let set = null;
67
+ let moveTo = null;
55
68
  if (action === 'importance') {
56
69
  const n = Math.round(Number(value));
57
70
  if (!(n >= 1 && n <= 5)) return { ok: false, error: '重要度是 1~5' };
@@ -65,11 +78,43 @@ export function bulkMemory({ db, clock, worker, ids, filter, action, value, dryR
65
78
  } else if (action === 'sortDate') {
66
79
  if (value !== null && !isCalendarDate(value)) return { ok: false, error: '日期无效' };
67
80
  set = ['sort_date = ?', value];
81
+ } else if (action === 'owner') {
82
+ // 目标主人:只认「她自己」或库里真实存在的人(owner_id 形如 user:<canonical_id>)。
83
+ // 裸 canonical_id 一律拒 —— 那种 owner_id 谁都匹配不上,搬过去等于把记忆藏起来。
84
+ const to = String(value ?? '').trim();
85
+ if (to === '' || to.length > 64) return { ok: false, error: '要搬给谁?' };
86
+ if (to !== 'self') {
87
+ const cid = to.startsWith('user:') ? to.slice(5) : '';
88
+ if (cid === '' || cid.length > 58 || /[\s\x00-\x1f]/.test(cid)) return { ok: false, error: '要搬给谁?' };
89
+ if (!db.prepare('SELECT 1 FROM person WHERE canonical_id = ?').get(cid)) return { ok: false, error: '没有这个人' };
90
+ }
91
+ moveTo = to;
68
92
  } else if (action !== 'forget' && action !== 'restore') return { ok: false, error: `不认识的操作:${action}` };
69
93
 
70
94
  if (action !== 'forget') rows = rows.filter((r) => r.kind !== 'weekly'); // 派生周记不允许更改范围、类型或恢复
71
95
  const matched = rows.map((r) => r.id);
72
96
  if (dryRun || rows.length === 0) return { ok: true, matched: rows.length, changed: 0, ids: matched.slice(0, 50) };
97
+ if (action === 'owner') {
98
+ // 搬主人必须走周记触发器安全路径:weekly_protect 把 owner_id 变化也算「周记被编辑」→ ABORT。
99
+ // 摘掉 → 搬 → 按原定义重建(和 db.js 的 reassignMemoryOwner 同一套手法)。
100
+ // 不动 updated_at:内容没变,搬主人不该把遗忘曲线的起点重置。
101
+ //
102
+ // 「摘触发器 + 搬 + 重建」整段在一个事务里:SQLite 的 DDL 是事务性的,
103
+ // 进程在「摘了还没建回来」的当口崩掉,也不会留下一个缺席的 weekly_protect
104
+ // (那一刻谁都能改周记)。出错时 ROLLBACK,触发器和搬动一起回去。
105
+ db.exec('BEGIN');
106
+ try {
107
+ withoutWeeklyProtect(db, () => {
108
+ db.prepare(`UPDATE memory SET owner_id = ? WHERE id IN (${matched.map(() => '?').join(',')})`).run(moveTo, ...matched);
109
+ });
110
+ db.exec('COMMIT');
111
+ } catch (error) {
112
+ db.exec('ROLLBACK');
113
+ throw error;
114
+ }
115
+ // 向量不用重算:vec 表只有 memory_id,检索时按 memory.owner_id 现筛(见 lib/retrieval.js)。
116
+ return { ok: true, matched: rows.length, changed: rows.length, ids: matched.slice(0, 50) };
117
+ }
73
118
  const now = clock.now();
74
119
  db.exec('BEGIN');
75
120
  try {
@@ -316,7 +316,7 @@ export async function handleSoulRoute({ method, path, url, req, res, send, readB
316
316
  send(200, { ok: true, id: Number(r.lastInsertRowid) });
317
317
  return true;
318
318
  }
319
- // 批量:{ ids[] | filter{ownerId,q,source,visibility}, action, value, dryRun }
319
+ // 批量:{ ids[] | filter{ownerId,q,source,visibility,kind,from,to}, action, value, dryRun }
320
320
  if (path === '/inspector/bulk' && post) {
321
321
  if (!guard()) return true;
322
322
  const b = await body();
package/lib/routes-v07.js CHANGED
@@ -453,8 +453,10 @@ export async function handleV07Route({ method, path, url, req, res, send, readBo
453
453
  if (!guard()) return true;
454
454
  const b = await body();
455
455
  if (!slang) { send(200, { ok: false, error: '学说法没起来' }); return true; }
456
- const r = importMaiBotExtras({
456
+ // 要 await:导入现在会看图打标,不等就回一个 ok,面板显示「导入了 undefined 张」
457
+ const r = await importMaiBotExtras({
457
458
  dbPath: String(b.dbPath ?? ''), slang, stickers, workspacePath: gateway?.workspacePath?.() ?? null,
459
+ vision,
458
460
  emojis: b.emojis !== false, expressions: b.expressions !== false, jargons: b.jargons !== false, maxEmojis: b.maxEmojis
459
461
  });
460
462
  send(200, { ok: true, ...r });
package/lib/routes.js CHANGED
@@ -21,7 +21,7 @@ import { pluginVersion } from './update-check.js';
21
21
  import { stickerConfig } from './stickers.js';
22
22
  import { slangConfig } from './slang.js';
23
23
  import { importMemories } from './importer.js';
24
- import { bulkMemory, filterWhere } from './memory-bulk.js';
24
+ import { bulkMemory, filterWhere, MEMORY_DATE } from './memory-bulk.js';
25
25
  import { dedicatedWorkspacePath, interjectConfig, clampReplyWindow } from './gateway.js';
26
26
  import { DEFAULT_DAILY_MAX, DEFAULT_IDLE_REAL_GAP_MIN } from './life.js';
27
27
  import { qrSvg } from './channels/qrcode.js';
@@ -387,8 +387,16 @@ export function registerRoutes(ctx, deps) {
387
387
  // ── 契约 7:记忆与人物检视 ──
388
388
  if (method === 'GET' && path === '/inspector/overview') {
389
389
  const ownerFilter = url.searchParams.get('ownerId');
390
- // 筛选:内容包含 q、来源 source、私密 visibility;limit 最多 500(批量操作要看得到更多)
391
- const listFilter = filterWhere({ ownerId: ownerFilter, q: url.searchParams.get('q') ?? '', source: url.searchParams.get('source') ?? '', visibility: url.searchParams.get('visibility') ?? '' });
390
+ // 筛选:内容包含 q、来源 source、私密 visibility、类型 kind、日期 from/to;limit 最多 500(批量操作要看得到更多)
391
+ const listFilter = filterWhere({
392
+ ownerId: ownerFilter,
393
+ q: url.searchParams.get('q') ?? '',
394
+ source: url.searchParams.get('source') ?? '',
395
+ visibility: url.searchParams.get('visibility') ?? '',
396
+ kind: url.searchParams.get('kind') ?? '',
397
+ from: url.searchParams.get('from') ?? '',
398
+ to: url.searchParams.get('to') ?? ''
399
+ });
392
400
  const listLimit = Math.min(500, Math.max(1, Math.floor(Number(url.searchParams.get('limit') ?? 100)) || 100));
393
401
  const listOffset = Math.min(100_000, Math.max(0, Math.floor(Number(url.searchParams.get('offset') ?? 0)) || 0));
394
402
  const meta = readVecMeta(db);
@@ -406,7 +414,7 @@ export function registerRoutes(ctx, deps) {
406
414
  );
407
415
  // 同一创建时间的记忆按最早版本的 id 排序:编辑会新建 id,不能因此换位置。
408
416
  // UNION 防止旧数据中的异常环造成递归不结束;索引支持按 superseded_by 反查。
409
- const memRows = db.prepare(`SELECT * FROM memory WHERE ${listFilter.sql} ORDER BY COALESCE(sort_date, date(created_at / 1000, 'unixepoch', 'localtime')) DESC, created_at DESC,
417
+ const memRows = db.prepare(`SELECT * FROM memory WHERE ${listFilter.sql} ORDER BY ${MEMORY_DATE} DESC, created_at DESC,
410
418
  (WITH RECURSIVE ancestors(id) AS (
411
419
  SELECT memory.id UNION SELECT old.id FROM memory old JOIN ancestors a ON old.superseded_by = a.id
412
420
  ) SELECT MIN(id) FROM ancestors) ASC, id ASC LIMIT ${listLimit} OFFSET ${listOffset}`).all(...listFilter.params);
package/lib/stickers.js CHANGED
@@ -637,7 +637,10 @@ export class StickerBox {
637
637
  const limit = Math.max(1, Math.round(Number(opts.limit) || 40));
638
638
  const all = this.collected();
639
639
  const want = (x) => (workspacePath === '' || sameWs(x.workspacePath, workspacePath));
640
- const todo = all.filter((x) => want(x) && (x.tags ?? []).length === 0).slice(0, limit);
640
+ const todo = all.filter((x) => want(x) && (x.tags ?? []).length === 0)
641
+ // 文件已经没了的记录不算待办:打不上标签,还占着 limit(#118)
642
+ .filter((x) => this.stickerAlive(x))
643
+ .slice(0, limit);
641
644
  const result = { tagged: 0, skipped: 0, embedded: 0, total: todo.length, failures: {} };
642
645
  const failed = (reason) => { result.failures[reason] = (result.failures[reason] ?? 0) + 1; };
643
646
  for (const [i, hit] of todo.entries()) {
@@ -656,6 +659,25 @@ export class StickerBox {
656
659
  return result;
657
660
  }
658
661
 
662
+ /**
663
+ * 收藏记录 → _stickers 里的真文件路径。
664
+ */
665
+ stickerPath(hit) {
666
+ return join(String(hit?.workspacePath ?? ''), '_stickers', basename(String(hit?.file ?? '')));
667
+ }
668
+
669
+ /**
670
+ * 记录指向的文件还在不在。
671
+ *
672
+ * 文件已经没了的记录永远打不上标签(读回来是空的)—— 让它占着待办只会把「补标签」的
673
+ * 额度(limit)吃光,而且每次都报同一批「文件读不到」,永远不收敛(#118)。
674
+ * **记录本身不动**(主人的数据,删不删由面板决定)。
675
+ */
676
+ stickerAlive(hit) {
677
+ if (String(hit?.file ?? '') === '') return false;
678
+ try { return statSync(this.stickerPath(hit)).isFile(); } catch { return false; }
679
+ }
680
+
659
681
  /**
660
682
  * 从收藏记录读回图片字节 + 推断 mediaType(面板补打标要原图)。
661
683
  * 收藏记录里**没存 mediaType**(只有文件名),所以从扩展名反推 —— 反推不出就是读不到。
@@ -668,7 +690,7 @@ export class StickerBox {
668
690
  if (!IMAGE_EXT.has(ext)) return { error: 'unsupported_format' };
669
691
  const mediaType = `image/${ext === 'jpg' ? 'jpeg' : ext}`;
670
692
  try {
671
- const path = join(hit.workspacePath, '_stickers', basename(file));
693
+ const path = this.stickerPath(hit);
672
694
  if (statSync(path).size > VISION_MAX_BYTES) return { error: 'file_too_large' };
673
695
  const bytes = readFileSync(path);
674
696
  return bytes.length > VISION_MAX_BYTES ? { error: 'file_too_large' } : { bytes, mediaType };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-fish-soul",
3
- "version": "0.18.1",
3
+ "version": "0.18.3",
4
4
  "description": "鱼 · 人格、按人记忆(可纠正、有印象、能导入旧聊天记录)、日程自走与主动开口,直连 SnowLuma 收发 QQ(群里会自己插话),B站 / 抖音小号私信与自己刷视频;按功能选模型并统计用量花费,能听会说 QQ 语音、收藏表情包、学群里的梗,可选上网查;心情影响说话、去 AI 味、每个群的设定、按聊天选模型、每晚写日记、每周记忆存档与可选周记(DSH 插件,单角色 feiyu ,v0.15.37)",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -64,7 +64,6 @@
64
64
  }
65
65
  },
66
66
  "scripts": {
67
- "test": "node test/safe-download.mjs && node test/douyin-exact-id.mjs && node test/douyin-pb-init.mjs && node test/douyin-conversation.mjs && node test/douyin-inbox.mjs && node test/douyin-quarantine.mjs && node test/douyin-send-target.mjs && node test/douyin-send-exclusive.mjs && node test/douyin-gap-dedupe.mjs && node test/douyin-message-id-dedupe.mjs && node test/douyin-read-fail-retry.mjs && node test/douyin-read-cache.mjs && node test/douyin-dm-media-conv.mjs && node test/douyin-read-fail-retry-poll.mjs && node test/douyin-inbox-contract.mjs && node test/person-attribution.mjs && node test/memory-owner-reassign.mjs && node test/douyin-poll-and-timer-safety.mjs && node test/p2-limits.mjs && node test/resource-safety.mjs && node test/leftover-edge-cases.mjs && node test/douyin-master-person-merge.mjs && node test/douyin-master-uid.mjs && node test/douyin-identity-e2e.mjs && node test/douyin-post-jobs.mjs && node test/retrieval-filtered-vectors.mjs && node test/security-boundaries.mjs && node test/douyin-cdp-cursor.mjs && node test/douyin-nav-timeout.mjs && node test/persona-isolation.mjs && node test/smoke.mjs && node test/douyin-browser.mjs && node test/douyin-page-alive.mjs && node test/douyin-eval-timeout.mjs && node test/douyin-goto-budget.mjs && node test/douyin-music.mjs && node test/startup-gate.mjs && node test/outbox.mjs && node test/import-coverage.mjs && node test/update-check.mjs && node test/issue-fixes.mjs && node test/import-resume.mjs && node test/maibot-extras.mjs && node test/worldinfo.mjs && node test/memory-bulk.mjs && node test/memory-tiers.mjs && node test/memory-weekly.mjs && node test/issue-98-self-archive.mjs && node test/issue-99-memory-order.mjs && node test/issue-115-memory-date.mjs && node test/issue-119-memory-page.mjs && node test/issue-78-diagnostic.mjs && node test/memory-storage.mjs && node test/memory-storage-restore.mjs && node test/backup-restore.mjs && node test/douyin-group.mjs && node test/review-fixes.mjs && node test/at-reads-video.mjs && node test/search-source.mjs && node test/followups.mjs && node test/detail-config.mjs && node test/qq-send-any-image.mjs && node test/qq-read-attachment.mjs && node test/qq-batch-window.mjs && node test/comment-video.mjs && node test/frames.mjs && node test/face-name.mjs && node test/comment-reply.mjs && node test/chat-comment.mjs && node test/at-target.mjs && node test/quota-caps.mjs && node test/client-lint.mjs && node test/client-panels.mjs && node test/dsh-desktop.mjs && node test/group-mention-only.mjs && node test/qq-private-allowlist.mjs && node test/issue-59-interject.mjs && node test/issue-59-diagnose.mjs && node test/sticker-backfill.mjs && node test/issue-118-sticker-diagnostics.mjs && node test/sticker-manage.mjs && node test/bili-emotes.mjs && node test/qq-outbound-sanitize.mjs && node test/person-delete.mjs && node test/qq-group-admin.mjs && node test/douyin-recovery.mjs && node test/session-preset.mjs && node test/qq-connect-error.mjs && node test/douyin-comment-bridge.mjs && node test/douyin-comment-write-unknown.mjs && node test/douyin-reply-verify-status.mjs && node test/bili-comment-emoji.mjs && node test/douyin-state-echo.mjs && node test/issue-75-proactive.mjs && node test/issue-76-capability.mjs && node test/douyin-http-browse.mjs && node test/douyin-verify-backoff.mjs && node test/douyin-digg-bridge.mjs && node test/memory-evidence-transcript.mjs && node test/chat-archive-default.mjs && node test/issue-113-desktop-archive.mjs && node test/dream-transcript-wire.mjs && node test/douyin-frames-collect.mjs && node test/master-qq-uin-rebind.mjs && node test/douyin-session-health.mjs && node test/douyin-delivered.mjs && node test/douyin-card-share.mjs && node test/douyin-push-drop.mjs && node test/douyin-stranger-dm.mjs && node test/douyin-uid-binding.mjs && node test/image-webp-fallback.mjs && node test/douyin-emoji-fallback.mjs && node test/relay-other-platform.mjs && node test/issue-101-voice-files.mjs && node test/voice-volcengine.mjs && node test/voice-minimax-dashscope.mjs && node test/bili-switch-persist.mjs && node test/cross-channel-context.mjs && node test/reply-target.mjs && node test/shared-session.mjs && node test/memory-source-label.mjs && node test/pending-delivery.mjs && node test/recall-window-78.mjs && node test/client-syntax.mjs && node test/diag-log.mjs && node test/check-rings.mjs && node test/release-workflow.mjs && node test/sticker-import-gif.mjs && node test/sticker-real-gif.mjs && node test/sticker-upload-binary.mjs && node test/sticker-vision-tags.mjs && node test/sticker-manual-tags.mjs && node test/sticker-auto-name.mjs && node test/self-update.mjs && node test/group-list.mjs && node test/douyin-inbox-noise.mjs && node test/douyin-inbox-diag.mjs && node test/douyin-inbox-stuck.mjs && node test/reply-window.mjs && node test/douyin-sticker-heuristic.mjs && node test/douyin-image-boundary.mjs && node test/media-image-boundary.mjs && node test/douyin-comment-identity-cid.mjs",
68
- "eval": "node test/eval/persona-eval.mjs"
67
+ "test": "node test/memory-bulk-move.mjs && node test/safe-download.mjs && node test/douyin-exact-id.mjs && node test/douyin-pb-init.mjs && node test/douyin-conversation.mjs && node test/douyin-inbox.mjs && node test/douyin-quarantine.mjs && node test/douyin-send-target.mjs && node test/douyin-send-exclusive.mjs && node test/douyin-gap-dedupe.mjs && node test/douyin-message-id-dedupe.mjs && node test/douyin-read-fail-retry.mjs && node test/douyin-read-cache.mjs && node test/douyin-dm-media-conv.mjs && node test/douyin-read-fail-retry-poll.mjs && node test/douyin-inbox-contract.mjs && node test/person-attribution.mjs && node test/memory-owner-reassign.mjs && node test/douyin-poll-and-timer-safety.mjs && node test/p2-limits.mjs && node test/resource-safety.mjs && node test/leftover-edge-cases.mjs && node test/douyin-master-person-merge.mjs && node test/douyin-master-uid.mjs && node test/douyin-identity-e2e.mjs && node test/douyin-post-jobs.mjs && node test/retrieval-filtered-vectors.mjs && node test/security-boundaries.mjs && node test/douyin-cdp-cursor.mjs && node test/douyin-nav-timeout.mjs && node test/persona-isolation.mjs && node test/smoke.mjs && node test/douyin-browser.mjs && node test/douyin-page-alive.mjs && node test/douyin-eval-timeout.mjs && node test/douyin-bridge-timeout.mjs && node test/douyin-goto-budget.mjs && node test/douyin-music.mjs && node test/startup-gate.mjs && node test/outbox.mjs && node test/import-coverage.mjs && node test/update-check.mjs && node test/issue-fixes.mjs && node test/import-resume.mjs && node test/maibot-extras.mjs && node test/worldinfo.mjs && node test/memory-bulk.mjs && node test/memory-tiers.mjs && node test/memory-weekly.mjs && node test/issue-98-self-archive.mjs && node test/issue-99-memory-order.mjs && node test/issue-115-memory-date.mjs && node test/issue-119-memory-page.mjs && node test/issue-125-memory-filter.mjs && node test/issue-78-diagnostic.mjs && node test/memory-storage.mjs && node test/memory-storage-restore.mjs && node test/backup-restore.mjs && node test/douyin-group.mjs && node test/review-fixes.mjs && node test/at-reads-video.mjs && node test/search-source.mjs && node test/followups.mjs && node test/detail-config.mjs && node test/qq-send-any-image.mjs && node test/qq-read-attachment.mjs && node test/qq-batch-window.mjs && node test/comment-video.mjs && node test/frames.mjs && node test/face-name.mjs && node test/comment-reply.mjs && node test/chat-comment.mjs && node test/at-target.mjs && node test/quota-caps.mjs && node test/client-lint.mjs && node test/client-panels.mjs && node test/dsh-desktop.mjs && node test/group-mention-only.mjs && node test/qq-private-allowlist.mjs && node test/issue-59-interject.mjs && node test/issue-59-diagnose.mjs && node test/sticker-backfill.mjs && node test/issue-118-sticker-diagnostics.mjs && node test/sticker-manage.mjs && node test/bili-emotes.mjs && node test/qq-outbound-sanitize.mjs && node test/person-delete.mjs && node test/qq-group-admin.mjs && node test/douyin-recovery.mjs && node test/session-preset.mjs && node test/qq-connect-error.mjs && node test/douyin-comment-bridge.mjs && node test/douyin-comment-write-unknown.mjs && node test/douyin-reply-verify-status.mjs && node test/bili-comment-emoji.mjs && node test/douyin-state-echo.mjs && node test/issue-75-proactive.mjs && node test/issue-76-capability.mjs && node test/douyin-http-browse.mjs && node test/douyin-verify-backoff.mjs && node test/douyin-digg-bridge.mjs && node test/memory-evidence-transcript.mjs && node test/chat-archive-default.mjs && node test/issue-113-desktop-archive.mjs && node test/dream-transcript-wire.mjs && node test/douyin-frames-collect.mjs && node test/master-qq-uin-rebind.mjs && node test/douyin-session-health.mjs && node test/douyin-delivered.mjs && node test/douyin-card-share.mjs && node test/douyin-push-drop.mjs && node test/douyin-stranger-dm.mjs && node test/douyin-uid-binding.mjs && node test/image-webp-fallback.mjs && node test/douyin-emoji-fallback.mjs && node test/relay-other-platform.mjs && node test/issue-101-voice-files.mjs && node test/voice-volcengine.mjs && node test/voice-minimax-dashscope.mjs && node test/bili-switch-persist.mjs && node test/cross-channel-context.mjs && node test/reply-target.mjs && node test/shared-session.mjs && node test/memory-source-label.mjs && node test/pending-delivery.mjs && node test/recall-window-78.mjs && node test/client-syntax.mjs && node test/diag-log.mjs && node test/check-rings.mjs && node test/release-workflow.mjs && node test/sticker-import-gif.mjs && node test/sticker-real-gif.mjs && node test/sticker-upload-binary.mjs && node test/sticker-vision-tags.mjs && node test/sticker-manual-tags.mjs && node test/sticker-auto-name.mjs && node test/self-update.mjs && node test/group-list.mjs && node test/douyin-inbox-noise.mjs && node test/douyin-inbox-diag.mjs && node test/douyin-inbox-stuck.mjs && node test/reply-window.mjs && node test/douyin-sticker-heuristic.mjs && node test/douyin-image-boundary.mjs && node test/media-image-boundary.mjs && node test/douyin-comment-identity-cid.mjs"
69
68
  }
70
69
  }