dsh-fishpal 0.9.32 → 0.10.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.
package/lib/index.js CHANGED
@@ -41,6 +41,7 @@ import * as recall from './recall.js';
41
41
  import * as backup from './backup.js';
42
42
  import * as router from './router.js';
43
43
  import * as deliveryMap from './delivery-map.js';
44
+ import * as pendingQ from './pending-questions.js';
44
45
  import * as friends from './friends.js';
45
46
  import * as exportMod from './export.js';
46
47
  import * as configPack from './config-pack.js';
@@ -62,6 +63,35 @@ import {
62
63
  } from './privacy.js';
63
64
  import * as P from './protocol.js';
64
65
  import { applyBlocklist } from './charfilter.js';
66
+
67
+ /**
68
+ * 「最近投递」环形缓冲(H5,2026-12-04)。
69
+ *
70
+ * ★ 为什么要有它:现在想知道「刚才那条到底送没送到」只能翻日志、grep 时间戳。
71
+ * 而这件事在状态页上一眼就该看得见 —— 尤其「已排队等投」和「投递失败」
72
+ * 这两种结果长得像但意思完全不同(一个没丢、一个真丢了)。
73
+ *
74
+ * 只记**结果和元数据**,不记正文:这条记录会出现在界面上,也会进诊断工具,
75
+ * 正文没必要跟着走。
76
+ */
77
+ const RECENT_DELIVERY_MAX = 50;
78
+ const recentDeliveries = [];
79
+
80
+ /**
81
+ * @param {{type:string, from:string, id:string, outcome:'delivered'|'queued'|'failed',
82
+ * reason?:string, suspicious?:boolean}} rec
83
+ */
84
+ export function recordDelivery(rec) {
85
+ recentDeliveries.push({ ...rec, at: new Date().toISOString() });
86
+ if (recentDeliveries.length > RECENT_DELIVERY_MAX) {
87
+ recentDeliveries.splice(0, recentDeliveries.length - RECENT_DELIVERY_MAX);
88
+ }
89
+ }
90
+
91
+ /** 最近投递(新的在前)。n 不给就全给。 */
92
+ export function recentDeliveryList(n = RECENT_DELIVERY_MAX) {
93
+ return recentDeliveries.slice(-n).reverse();
94
+ }
65
95
  import { createTransport } from './transport.js';
66
96
  import { createPresence, STATE as PRESENCE_STATE } from './presence.js';
67
97
  import { renderUi, normalizeAvatar } from './ui.js';
@@ -71,6 +101,15 @@ import * as stateMod from './state.js';
71
101
  // ★ 消息按好友分组(纯函数,测试和产品用同一份)
72
102
  import { groupMessagesByPeer } from './mailbox-group.js';
73
103
  import * as room from './room.js';
104
+ // ★ 2026-12-04:统一异常隔离。DSH 对插件里的 uncaught exception / unhandled rejection
105
+ // 是 exit(1),一个没接住的定时器能带走整个进程(11-30、12-03 两次都是这么崩的)。
106
+ import { safeInterval as safeIntervalRaw, safeOn as safeOnRaw } from './safe.js';
107
+
108
+ /** 统一带上 log 的 safeInterval —— 每个定时器一个名字,日志里能看出是谁 */
109
+ const safeInterval = (fn, ms, name) =>
110
+ safeIntervalRaw(fn, ms, { name, log: (s) => log(s) });
111
+ const safeOn = (emitter, event, fn, name) =>
112
+ safeOnRaw(emitter, event, fn, { name, log: (s) => log(s) });
74
113
  import { startHeartbeat } from './heartbeat.js';
75
114
  import { buildDaily, saveNote, noteOf, dayKey, promptedDay, markPrompted } from './daily.js';
76
115
  import * as bottle from './bottle.js';
@@ -714,36 +753,66 @@ function applyInner(ctx, config = {}) {
714
753
  * 醒了立刻补投。只在队列非空时跑,空队列一个字节都不动。
715
754
  */
716
755
  let pendingRetryTimer = null;
756
+ /**
757
+ * ★ 2026-12-03 修「鱼突然掉线」(实际是整个 DSH 被带走):
758
+ *
759
+ * 原来这个定时器的回调里写的是 `if (stopped) return;`,
760
+ * 但 `stopped` 只在下面心跳那个 ctx.effect 里 `let stopped = false` 声明过,
761
+ * 那是**另一个闭包**,这里根本看不见 —— 于是每次走到这行就抛
762
+ * `ReferenceError: stopped is not defined`。
763
+ * setInterval 回调里抛出的异常没人接,Node 按 uncaught exception 处理,
764
+ * **整个进程 fatal 退出**,日志尾巴就是:
765
+ * `dsh: fatal uncaught exception: ReferenceError: stopped is not defined`
766
+ * 表现成「鱼用着用着突然掉线」,其实连 DSH 一起没了。
767
+ *
768
+ * 修法两层:
769
+ * ① 用自己作用域里的 retryStopped,并在插件卸载时清掉定时器;
770
+ * ② 整个回调体包 try/catch —— 定时器里以后不管再出什么事,
771
+ * 最多丢一个 20s 周期,绝不可能再把 DSH 带走。
772
+ */
773
+ let retryStopped = false;
774
+ function stopPendingRetry() {
775
+ retryStopped = true;
776
+ if (pendingRetryTimer) {
777
+ clearInterval(pendingRetryTimer);
778
+ pendingRetryTimer = null;
779
+ }
780
+ }
781
+ ctx.effect(() => () => stopPendingRetry(), 'fishpal.pending-retry');
782
+
717
783
  function schedulePendingRetry() {
718
- if (pendingRetryTimer) return;
784
+ if (retryStopped || pendingRetryTimer) return;
719
785
  pendingRetryTimer = setInterval(() => {
720
- if (!pendingInjects.length) {
721
- clearInterval(pendingRetryTimer);
722
- pendingRetryTimer = null;
723
- return;
724
- }
725
- if (stopped) return;
726
- void (async () => {
727
- try {
728
- if (!room.hasHost(ctx)) return;
729
- // agentFor 会 await resolveAgent —— 这一步才是真正「叫醒」休眠会话的地方
730
- const got = await room.agentFor(ctx, {
731
- state: roomState || room.loadRoomState(dataDir()),
732
- dataDir: dataDir(),
733
- roomDir: roomDir(),
734
- title: '鱼和鱼 · 社交',
735
- log,
736
- allowNew: true,
737
- });
738
- if (got?.sid) {
739
- roomState = got.state || roomState;
740
- log(`房间会话已醒 …${String(got.sid).slice(-8)},补投队列 ${pendingInjects.length} 条`);
741
- flushPendingInjects();
742
- }
743
- } catch (e) {
744
- log(`补投重试失败(${e?.message ?? e})—— 下个周期再试`);
786
+ try {
787
+ if (!pendingInjects.length || retryStopped) {
788
+ clearInterval(pendingRetryTimer);
789
+ pendingRetryTimer = null;
790
+ return;
745
791
  }
746
- })();
792
+ void (async () => {
793
+ try {
794
+ if (!room.hasHost(ctx)) return;
795
+ // agentFor 会 await resolveAgent —— 这一步才是真正「叫醒」休眠会话的地方
796
+ const got = await room.agentFor(ctx, {
797
+ state: roomState || room.loadRoomState(dataDir()),
798
+ dataDir: dataDir(),
799
+ roomDir: roomDir(),
800
+ title: '鱼和鱼 · 社交',
801
+ log,
802
+ allowNew: true,
803
+ });
804
+ if (got?.sid) {
805
+ roomState = got.state || roomState;
806
+ log(`房间会话已醒 …${String(got.sid).slice(-8)},补投队列 ${pendingInjects.length} 条`);
807
+ flushPendingInjects();
808
+ }
809
+ } catch (e) {
810
+ log(`补投重试失败(${e?.message ?? e})—— 下个周期再试`);
811
+ }
812
+ })();
813
+ } catch (e) {
814
+ log(`补投重试定时器异常(${e?.message ?? e})—— 忽略,下个周期再试`);
815
+ }
747
816
  }, 20_000);
748
817
  // 不许这个定时器把进程钉住不退出
749
818
  if (typeof pendingRetryTimer.unref === 'function') pendingRetryTimer.unref();
@@ -758,7 +827,7 @@ function applyInner(ctx, config = {}) {
758
827
  for (const item of batch) {
759
828
  try {
760
829
  // ★ 直接复用 inject,它内部会再判一次 pickAgent —— 拿不到就重新入队
761
- if (inject(item.m, item.suspicious)) ok += 1;
830
+ if (deliver(item.m, item.suspicious)) ok += 1;
762
831
  else keep.push(item);
763
832
  } catch {
764
833
  keep.push(item);
@@ -1606,6 +1675,22 @@ function applyInner(ctx, config = {}) {
1606
1675
  return { ok: true, sessionId: got.sid || null };
1607
1676
  },
1608
1677
  onGlobalPatch: (patch) => {
1678
+ // ★ 2026-12-04(H2 + H1 方案 C):回信昵称的全局默认。
1679
+ // ★ 这里必须先 loadConfig 再 saveConfig —— 直接写内存里那份 cfg
1680
+ // 会把别处刚改的值冲掉(index.js:1723 那条教训)。
1681
+ if ('replyNick' in patch) {
1682
+ const fresh = loadConfig();
1683
+ if (!fresh) throw new Error('还没有配置');
1684
+ const raw = String(patch.replyNick ?? '').trim();
1685
+ if (raw.length > 40) throw new Error('回信昵称最多 40 字');
1686
+ if (/[\u0000-\u001f\u007f]/.test(raw)) throw new Error('回信昵称不能含控制字符');
1687
+ const next = { ...fresh };
1688
+ if (raw) next.replyNick = raw;
1689
+ else delete next.replyNick;
1690
+ saveConfig(next);
1691
+ cfg.replyNick = raw || undefined;
1692
+ log(raw ? `回信昵称改成:${raw}` : '回信昵称已清掉');
1693
+ }
1609
1694
  if ('interactionLevel' in patch) {
1610
1695
  const v = patch.interactionLevel;
1611
1696
  if (v !== 'chat-only' && v !== 'advise') {
@@ -1783,7 +1868,15 @@ function applyInner(ctx, config = {}) {
1783
1868
  }
1784
1869
 
1785
1870
  /** 把一条通过全部校验的消息投进会话。 */
1786
- function inject(m, suspicious) {
1871
+ /**
1872
+ * 投递一条入站消息。
1873
+ *
1874
+ * ★ 2026-12-04 改名:原来叫 inject —— 但 `inject` 在这个文件里有两个身份:
1875
+ * 136 行 `export const inject = [...]` 是 Cordis 的依赖声明,
1876
+ * 这里是同名局部函数。读代码时容易看串(「改 inject 是不是要动依赖?」)。
1877
+ * 现在叫 deliver,一眼能分出「投递动作」和「宿主依赖」。
1878
+ */
1879
+ function deliver(m, suspicious) {
1787
1880
  // ★ 2026-11-29:分两种情况,别混为一谈 ——
1788
1881
  // ① 宿主**根本没有**会话注入能力(老版本 DSH):只能退回老逻辑,
1789
1882
  // 否则这条消息永远发不出去,等于把功能阉了。
@@ -1812,6 +1905,9 @@ function applyInner(ctx, config = {}) {
1812
1905
  const backSid = deliveryMap.sessionFor(dataDir(), {
1813
1906
  replyTo: m.reply_to ?? m.replyTo ?? null,
1814
1907
  threadId: m.thread_id ?? m.threadId ?? null,
1908
+ // ★ 2026-12-04(A3)第三线索:前两条都查不到时,按「这个 peer 最近落哪个屋」兜底。
1909
+ // 只在该 peer 唯一对应一个会话时才认(见 delivery-map.sessionFor 的注释)。
1910
+ peer: m.from ?? null,
1815
1911
  });
1816
1912
  if (backSid) {
1817
1913
  const a = ctx.agents?.get?.(backSid);
@@ -1908,6 +2004,10 @@ function applyInner(ctx, config = {}) {
1908
2004
  // 别的类型别为了一个用不上的判断去翻历史(这是热路径)。
1909
2005
  const prim = P.primitiveFor(m.type, {
1910
2006
  isAnswerToMyQuestion: m.type === 'answer' ? isSelfInvitedAnswer(m) : false,
2007
+ // ★ 2026-12-04:chat/share 的正文也传进去 —— 发送方标 chat、内容却像在问事
2008
+ // (「你在吗?」「帮我看看这个」),按「只抬不降」升成 followup 叫醒。
2009
+ // 不传的话 primitiveFor 就照旧只投 —— 对面等了半天鱼都没醒。
2010
+ text: m.text,
1911
2011
  });
1912
2012
  if (prim === 'followup') agent.followup(msg);
1913
2013
  else if (prim === 'steer') agent.steer(msg);
@@ -1924,11 +2024,29 @@ function applyInner(ctx, config = {}) {
1924
2024
  id: m.id,
1925
2025
  threadId: m.thread_id ?? m.threadId ?? null,
1926
2026
  sessionId: landedSid,
2027
+ // ★ 2026-12-04(A3):记下发送方,供下次反查兜底用
2028
+ from: m.from ?? null,
1927
2029
  });
1928
2030
  }
1929
2031
  } catch {
1930
2032
  /* 记账失败不影响投递本身 */
1931
2033
  }
2034
+ // ★ 2026-12-04(A4):有人问了我一个问题 —— 记下来,免得会话一轮换就再也翻不到。
2035
+ // 岸的原话:「能知道有会话去问的问题」。只有 question 类型才记;
2036
+ // chat 里带问号的不算(那是闲聊,A1/A2 会把它升成 followup 去叫醒,但不该占「欠着谁」的账)。
2037
+ if (m.type === 'question' && m.id && m.text) {
2038
+ try {
2039
+ pendingQ.note(dataDir(), {
2040
+ id: m.id,
2041
+ from: m.from ?? null,
2042
+ fromName: peerName ?? null,
2043
+ text: m.text,
2044
+ threadId: m.thread_id ?? m.threadId ?? null,
2045
+ });
2046
+ } catch (e) {
2047
+ log(`⚠️ 问题没记进待答清单(这条问题照常投递):${e?.message ?? e}`);
2048
+ }
2049
+ }
1932
2050
  // ★ 2026-12-01(用户选的方案 C:「只在房间里生成一条提示 ——
1933
2051
  // 房间显示『A 会话问了 xin 一句,回答已送回 A 会话』,正文不进房间」)
1934
2052
  //
@@ -1963,13 +2081,18 @@ function applyInner(ctx, config = {}) {
1963
2081
  /* 提示失败绝不影响投递本身 */
1964
2082
  }
1965
2083
 
2084
+ // ★ 2026-12-04 修(lint-dead 扫出来的空 try,里面一行代码都没有)
2085
+ // 注释写着「会话轮转计数失败」,可计数**根本没接上**:`bumpTurns` 在全库
2086
+ // 只在这一行注释里出现过,从来没有被调用过。于是 state.turns 永远是 0,
2087
+ // room.agentFor 里 `state.turns >= ROTATE.turnsPerSession`(20)永远不成立,
2088
+ // 会话永远不换、也永远不交接;日志里一个字都没有,因为 try 里本来就是空的。
2089
+ // 「看起来做了、其实没做」—— 和 11-30 那次空 catch 是同一个形状。
2090
+ // 现在接上:投递成功就 +1;到 20 轮由 room.agentFor 那边 retire 换新会话。
1966
2091
  try {
2092
+ const d = dataDir();
2093
+ room.bumpTurns(room.loadRoomState(d), d);
1967
2094
  } catch (e) {
1968
- // ★ 2026-12-01 优化:这里以前是**纯空 catch**,注释写「计数失败不影响投递」——
1969
- // 投递确实不受影响,但**计数器是轮换的唯一开关**:它悄悄不涨,
1970
- // 外面看到的现象就是「会话永远不换、也永远不交接」,而日志里一个字都没有。
1971
- // 静默失败最难查的地方不在「失败了」,在「你连它失败过都不知道」。
1972
- // 所以这里必须留痕;只在这条路真出错时写,正常投递一个字节都不多。
2095
+ // 只在真出错时写。正常投递一个字节都不多。
1973
2096
  log(`⚠️ 会话轮转计数失败(这条消息照常投递,但会话可能因此不换):${e?.message ?? e}`);
1974
2097
  }
1975
2098
  // ★ 2026-12-01(用户:「投递到哪、成没成,一条记录都没有」):
@@ -2508,7 +2631,7 @@ function applyInner(ctx, config = {}) {
2508
2631
  return;
2509
2632
  }
2510
2633
 
2511
- const ok = inject(r.message, r.suspicious);
2634
+ const ok = deliver(r.message, r.suspicious);
2512
2635
 
2513
2636
  // ── 自适配观测(规格 9.1):只记类型和时间,不记正文 ────────────
2514
2637
  try {
@@ -2539,7 +2662,30 @@ function applyInner(ctx, config = {}) {
2539
2662
  /* adapter 内部已经兜过,这里只是保险 */
2540
2663
  });
2541
2664
 
2542
- log(`收到 ${r.message.type} #${received}${r.suspicious ? '(可疑,已标记)' : ''}${ok ? ',已投递' : ',投递失败'}`);
2665
+ // ★ 2026-12-04 修(用户:「有些是打招呼的消息…还以为是去问工作区的」+
2666
+ // 「投递失败到底丢没丢」):以前这里只有「已投递 / 投递失败」两个词,
2667
+ // 但 ok=false 其实有两种:① 真的失败了 ② **消息已经攒进队列、只是房间没就绪**。
2668
+ // ②这种一条都没丢,日志却写「投递失败」—— 看日志的人会以为消息没了。
2669
+ // 现在分开写,并且把原因带出来(lastProblem 是 inject 刚设的)。
2670
+ const queued = !ok && /攒着|排队|待投/.test(String(lastProblem ?? ''));
2671
+ const okText = ok
2672
+ ? ',已投递'
2673
+ : queued
2674
+ ? `,已排队等投(${pendingInjects.length}/${PENDING_INJECT_MAX})`
2675
+ : `,投递失败(${lastProblem ?? '未知原因'})`;
2676
+
2677
+ // ★ H5:记进「最近投递」,状态页和诊断工具直接看这一份。
2678
+ // 三种结果分开记 —— 「已排队」和「投递失败」不能混成一个 ok=false。
2679
+ recordDelivery({
2680
+ type: r.message.type,
2681
+ from: r.message.from,
2682
+ id: r.message.id,
2683
+ outcome: ok ? 'delivered' : queued ? 'queued' : 'failed',
2684
+ reason: ok || queued ? '' : String(lastProblem ?? '未知原因'),
2685
+ suspicious: r.suspicious === true,
2686
+ });
2687
+
2688
+ log(`收到 ${r.message.type} #${received}${r.suspicious ? '(可疑,已标记)' : ''}${okText}`);
2543
2689
  },
2544
2690
  });
2545
2691
  // ② transport 有了,给每个人建对端把 publish 接上
@@ -2581,8 +2727,14 @@ function applyInner(ctx, config = {}) {
2581
2727
  // ★ 走 ctx.effect 托管:插件被禁用或热重载时,这个定时器必须停掉,
2582
2728
  // 否则旧插件留下的计时器还在跑,新的又起一个,越重载越漏。
2583
2729
  ctx.effect(() => {
2584
- const retryTimer = setInterval(() => {
2585
- peer?.retryOutbox?.().catch((err) => log(`outbox 扫描失败:${err?.message ?? err}`));
2730
+ // ★ 2026-12-04:改用 safeInterval。peer?.retryOutbox?.() 如果同步抛,
2731
+ // 以前会直接冒到事件循环顶层(async IIFE 自带 catch,但这一行不在里面)。
2732
+ return safeInterval(() => {
2733
+ try {
2734
+ peer?.retryOutbox?.().catch((err) => log(`outbox 扫描失败:${err?.message ?? err}`));
2735
+ } catch (e) {
2736
+ log(`outbox 扫描启动失败:${e?.message ?? e}`);
2737
+ }
2586
2738
 
2587
2739
  // ★ 2026-11-29(用户:「隔一段时间再发一次,看有没有收到,有点试探的感觉就行」):
2588
2740
  // 漂流瓶回信没收到 ACK 就按档位补发 —— 60 分钟 → 120 分钟,最多 3 次尝试。
@@ -2619,9 +2771,7 @@ function applyInner(ctx, config = {}) {
2619
2771
  log(`漂流瓶回信重试扫描出错:${e?.message ?? e}`);
2620
2772
  }
2621
2773
  })();
2622
- }, 15_000);
2623
- if (typeof retryTimer.unref === 'function') retryTimer.unref();
2624
- return () => clearInterval(retryTimer);
2774
+ }, 15_000, 'outbox-retry');
2625
2775
  }, 'fishpal.outbox-retry');
2626
2776
 
2627
2777
  // ★ 漂流瓶循环广播的扫描器(2026-12-01 用户:「我估计重起了也会断」)。
@@ -2656,16 +2806,19 @@ function applyInner(ctx, config = {}) {
2656
2806
  };
2657
2807
  // 启动补漏:先把错过的排期发掉
2658
2808
  void scan();
2659
- const timer = setInterval(() => void scan(), 60_000);
2660
- if (typeof timer.unref === 'function') timer.unref();
2661
- return () => clearInterval(timer);
2809
+ // ★ 2026-12-04:改用 safeInterval —— scan 是 async,以前 `void scan()`
2810
+ // 把 reject 吞成了 unhandled rejection,一个扫描出错就能带走整个 DSH。
2811
+ // safeInterval 内部已经 unref,也自带清理函数,不用再手写 clearInterval。
2812
+ return safeInterval(scan, 60_000, 'bottle-loop-scan');
2662
2813
  }, 'fishpal.bottle-loop');
2663
2814
 
2664
2815
  // ★ 在线状态:惰性探测(用户 2026-11-30 晚定的方案)。
2665
2816
  // 平时一条都不发 —— 用户原话「不要这么频繁」。每 30 秒看一眼有没有「该探的」,
2666
2817
  // 没有就什么也不做(due() 会直接告诉你 false)。
2667
2818
  ctx.effect(() => {
2668
- const probeTimer = setInterval(() => {
2819
+ // ★ 2026-12-04:改用 safeInterval —— 这里面的 presence.tick / pe.send 都可能抛,
2820
+ // 以前没有任何保护,一次抛出去就是 uncaught exception。
2821
+ return safeInterval(() => {
2669
2822
  if (!presence || !transport?.connected) return;
2670
2823
  const at = Date.now();
2671
2824
  // ① 先结算发出去的探测:超时没回执的,按「认不认 ping」分两种结论
@@ -2682,11 +2835,32 @@ function applyInner(ctx, config = {}) {
2682
2835
  log(`⚠️ 发在线探测失败(不影响收发):${e?.message ?? e}`);
2683
2836
  });
2684
2837
  }
2685
- }, 30_000);
2686
- if (typeof probeTimer.unref === 'function') probeTimer.unref();
2687
- return () => clearInterval(probeTimer);
2838
+ }, 30_000, 'presence-probe');
2688
2839
  }, 'fishpal.presence-probe');
2689
2840
 
2841
+ // ★ 2026-12-04(B7):thread 静默 24 小时自动过期。
2842
+ // 以前只能靠 fishpal_thread archive 手动挡 —— 手动挡等于永远不会发生。
2843
+ // 老 thread 不清会一直占着「同 peer 唯一活跃 thread」那个判定位,
2844
+ // 把本该投房间的新来信拽进一间早就没人看的屋。
2845
+ // 一小时扫一次够了(过期窗口是 24 小时,扫太勤没意义还费 IO)。
2846
+ ctx.effect(() => {
2847
+ return safeInterval(
2848
+ () => {
2849
+ try {
2850
+ const r = router.expireThreads();
2851
+ if (r.expired?.length) {
2852
+ log(`thread 过期 ${r.expired.length} 条(静默超 24 小时):${r.expired.map((t) => String(t).slice(0, 14)).join(', ')}`);
2853
+ }
2854
+ } catch (e) {
2855
+ // ★ 过期满掉不该影响收发 —— 但也不能静默,否则这个定时器坏了没人知道
2856
+ log(`⚠️ thread 过期清理没跑成:${e?.message ?? e}`);
2857
+ }
2858
+ },
2859
+ 60 * 60_000,
2860
+ 'thread-expiry'
2861
+ );
2862
+ }, 'fishpal.thread-expiry');
2863
+
2690
2864
  // ── 出站隐私防护(规格 7.1)──────────────────────────────────────────────
2691
2865
  // 挂在 tools/pre-execute 上:任何调用 fishpal_send 的路径都被拦。
2692
2866
  // 硬拦截凭据 / 拒发主人录入的隐私条目 / 个人信息脱敏。
@@ -3317,6 +3491,14 @@ function applyInner(ctx, config = {}) {
3317
3491
  '对面回的 answer 会精确投回你这扇窗。' +
3318
3492
  '只有想故意冒充别的会话时才显式传,它会覆盖自动取得的值。',
3319
3493
  },
3494
+ // ★ 2026-12-04(H1,方案 C:全局默认 + 单封可改):
3495
+ // 对面看到的「谁在说话」。全局默认在配置里(replyNick),这里只做单封覆盖。
3496
+ nick: {
3497
+ type: 'string',
3498
+ description:
3499
+ '可选:这一封的回信昵称(对面看到的名字)。不填就用配置里的全局默认;' +
3500
+ '全局也没设就不带,对面按它本地给你起的备注显示。只是「自称」,不改身份。',
3501
+ },
3320
3502
  },
3321
3503
  output: {
3322
3504
  schema: { type: 'object', additionalProperties: false, properties: { ok: { type: 'boolean', required: true }, text: { type: 'string', required: true } } },
@@ -3482,7 +3664,7 @@ function applyInner(ctx, config = {}) {
3482
3664
  // 分不出「这是哪扇窗说的」。带上会话短标识,对端一眼能认。
3483
3665
  const shownOrigin = fromSid ? `${origin}·${fromSid.slice(-8)}` : origin;
3484
3666
 
3485
- const m = await targetPeer.send({ type, text, threadId: routeKey, replyTo: args.reply_to ?? null, origin: shownOrigin });
3667
+ const m = await targetPeer.send({ type, text, threadId: routeKey, replyTo: args.reply_to ?? null, origin: shownOrigin, nick: args.nick ?? null });
3486
3668
 
3487
3669
  // ★ 2026-12-01 修(用户:「问问题那个会话只能看到问的问题,然后回来的回答」)
3488
3670
  // 投递路由原来只记**入站**:消息进来投进哪个会话,就记哪个会话。
@@ -3504,6 +3686,15 @@ function applyInner(ctx, config = {}) {
3504
3686
  }
3505
3687
  } catch {
3506
3688
  /* 记账失败不影响发送 */
3689
+ }
3690
+ // ★ 2026-12-04(A4):如果我发的是一条 answer,而它在回某条问题 —— 那就把那条问题标成「答了」。
3691
+ // 判定依据只有 reply_to:投出去一条 answer 才算答,别处顺口提一句不算。
3692
+ if (type === 'answer' && args.reply_to) {
3693
+ try {
3694
+ pendingQ.markAnswered(dataDir(), args.reply_to);
3695
+ } catch (e) {
3696
+ log(`⚠️ 答完没销账(这条回答照常发出):${e?.message ?? e}`);
3697
+ }
3507
3698
  }
3508
3699
  budget.commit({ reserveId: rsv.id, peerFp: targetFp, pool, tokens: toks });
3509
3700
  // ── 记忆适配(规格 8.3):出站也记一条,不然记忆里只有对面说的话 ──
@@ -3672,8 +3863,14 @@ function applyInner(ctx, config = {}) {
3672
3863
  `对面:${getPeer(cfg, cfg.peerFp)?.name || cfg.peer || '—'}${cfg.peerFp ? `(${cfg.peerFp})` : '(未配对)'}`,
3673
3864
  ...(listPeers(cfg).length > 1 ? [`好友:共 ${listPeers(cfg).length} 位`] : []),,
3674
3865
  `broker:${cfg.broker}`,
3675
- `连接:${transport?.connected ? '已连上' : '没连上'}`,
3866
+ // ★ 2026-12-04(D1):从布尔改成状态机。
3867
+ // 以前只有「已连上 / 没连上」—— 「还没启动」和「断了在重连」长得一模一样,
3868
+ // 人看到「没连上」不知道该等还是该查。现在分五档,说得出是哪一档。
3869
+ `连接:${transport?.stateText ?? '未知'}` + (transport?.stateText === '断线重连中' ? '(会自动重试,不用管)' : ''),
3676
3870
  `档位:${DEFAULT_LEVEL}`,
3871
+ // ★ 2026-12-04(H2):回信昵称当前值 —— 设了没设一眼看得出。
3872
+ // 设置入口现在只有 fishpal_config action=set(页面上的入口还没做)。
3873
+ `回信昵称:${cfg.replyNick ? JSON.stringify(cfg.replyNick) : '(没设 —— 对面按它本地备注显示你)'}` + (cfg.replyNick ? '(单封要改在 fishpal_send 传 nick)' : ''),
3677
3874
  // ★ 2026-12-02:以前是 `peer?.sas ?? '(未配对)'` —— peer 没这个字段,
3678
3875
  // 配对成功的人也永远看到「(未配对)」。改成从 peers 目录读存下来的确认码。
3679
3876
  `确认码:${getPeer(cfg, cfg.peerFp)?.sas || cfg.pairingSas || '(未配对)'}${(getPeer(cfg, cfg.peerFp)?.sas || cfg.pairingSas) ? '(手填配对的确认码,不是 SAS——防不住中途换公钥)' : ''}`,
@@ -3682,6 +3879,29 @@ function applyInner(ctx, config = {}) {
3682
3879
  `限流丢弃:${ps.rateDropped ?? 0} 条`,
3683
3880
  `收到:${received} 条 · 拒收:${stats.rejected} 条`,
3684
3881
  ];
3882
+
3883
+ // ★ 2026-12-04(H5):「最近投递」—— 以前想知道刚才那条送没送到只能翻日志。
3884
+ // 三种结果分开数:「已排队」和「投递失败」以前都只是一个 ok=false。
3885
+ try {
3886
+ const recent = recentDeliveryList(5);
3887
+ if (recent.length) {
3888
+ const tally = { delivered: 0, queued: 0, failed: 0 };
3889
+ for (const r of recentDeliveryList(50)) tally[r.outcome] = (tally[r.outcome] ?? 0) + 1;
3890
+ lines.push(
3891
+ `最近投递:已送达 ${tally.delivered} · 已排队 ${tally.queued} · 失败 ${tally.failed}(最近 50 条)`
3892
+ );
3893
+ for (const r of recent) {
3894
+ const mark = r.outcome === 'delivered' ? '✅' : r.outcome === 'queued' ? '⏳' : '❌';
3895
+ const when = String(r.at ?? '').slice(11, 19);
3896
+ const why = r.outcome === 'failed' ? ` — ${r.reason}` : '';
3897
+ lines.push(` ${mark} ${when} ${r.type}(${String(r.from ?? '').slice(0, 10)})${why}`);
3898
+ }
3899
+ } else {
3900
+ lines.push('最近投递:(还没有记录)');
3901
+ }
3902
+ } catch {
3903
+ lines.push('最近投递:读不出来');
3904
+ }
3685
3905
  // 预算(规格 10.4):状态一眼看得到,别让人猜为什么发不出去
3686
3906
  try {
3687
3907
  const rep = budget.report({ cfg });
@@ -4442,6 +4662,66 @@ function applyInner(ctx, config = {}) {
4442
4662
  },
4443
4663
  }));
4444
4664
 
4665
+ // ── 待回答的问题(A4)─────────────────────────────────────────────────
4666
+ // ★ 2026-12-04 立。岸的原话:「能知道有会话去问的问题」。
4667
+ // 一条 question 投进某个会话就完事了 —— 会话一轮换(每 20 轮一个新会话),
4668
+ // 或者那一轮没顾上答,这条问题就沉进历史,翻都翻不出来。
4669
+ // 这里把「谁问了、问了什么、答了没有」摆出来,让「还欠着谁一句回答」看得见。
4670
+ tools.register(defineTool({
4671
+ name: 'fishpal_questions',
4672
+ description:
4673
+ '看还欠着谁的回答。list(默认)列出没答过的问题,按时间从新到旧;answered 看最近答过的。' +
4674
+ '「答了」的判定只有一条:你发过一条 answer,而它的 reply_to 等于那条问题的 id。' +
4675
+ '在别处顺口提一句不算答。',
4676
+ parameters: {
4677
+ action: { type: 'string', description: 'list(没答的,默认)/ answered(答过的)/ stats(统计)' },
4678
+ limit: { type: 'number', description: '最多几条,默认 20' },
4679
+ days: { type: 'number', description: '只看最近几天内问的,默认 7' },
4680
+ },
4681
+ output: {
4682
+ schema: { type: 'object', additionalProperties: false, properties: { ok: { type: 'boolean', required: true }, text: { type: 'string', required: true } } },
4683
+ render: (_a, v) => [{ type: 'text', text: v.text }],
4684
+ },
4685
+ async execute(args) {
4686
+ const action = String(args.action ?? 'list').toLowerCase();
4687
+ const limit = Math.max(1, Math.min(200, Number(args.limit) || 20));
4688
+ const days = Math.max(1, Math.min(365, Number(args.days) || 7));
4689
+ const dir = dataDir();
4690
+
4691
+ if (action === 'stats') {
4692
+ const s = pendingQ.inspect(dir);
4693
+ return {
4694
+ ok: true,
4695
+ text: `待答清单共 ${s.count} 条:还欠着 ${s.open} 条,已答 ${s.answered} 条。`,
4696
+ };
4697
+ }
4698
+
4699
+ if (action === 'answered') {
4700
+ const rows = pendingQ.listAnswered(dir, { limit });
4701
+ if (!rows.length) return { ok: true, text: '还没有答过的问题记录。' };
4702
+ const lines = rows.map((r) => {
4703
+ const who = r.fromName || String(r.from ?? '?').slice(0, 12);
4704
+ return `${who} · 答于 ${new Date(r.answeredAt).toLocaleString('zh-CN')}\n ${r.text.slice(0, 120)}`;
4705
+ });
4706
+ return { ok: true, text: `最近答过的 ${rows.length} 条:\n\n${lines.join('\n\n')}` };
4707
+ }
4708
+
4709
+ const rows = pendingQ.listOpen(dir, { limit, maxAgeMs: days * 24 * 3600_000 });
4710
+ if (!rows.length) {
4711
+ return { ok: true, text: `最近 ${days} 天没有欠着的问题 —— 谁问的都答完了。` };
4712
+ }
4713
+ const lines = rows.map((r) => {
4714
+ const who = r.fromName || String(r.from ?? '?').slice(0, 12);
4715
+ const when = new Date(r.at).toLocaleString('zh-CN');
4716
+ return `${who} · ${when}\n ${r.text.slice(0, 160)}\n id=${String(r.id).slice(0, 8)}${r.threadId ? ` thread=${r.threadId}` : ''}`;
4717
+ });
4718
+ return {
4719
+ ok: true,
4720
+ text: `还欠着 ${rows.length} 条回答(最近 ${days} 天内):\n\n${lines.join('\n\n')}\n\n回的时候用 fishpal_send,type=answer、reply_to 填那条 id —— 发出去才会自动销账。`,
4721
+ };
4722
+ },
4723
+ }));
4724
+
4445
4725
  /**
4446
4726
  * 走 room.agentFor 把一条投进「鱼和鱼」那个会话。
4447
4727
  *
@@ -4619,7 +4899,7 @@ function applyInner(ctx, config = {}) {
4619
4899
  let why = viaRoom.reason || '';
4620
4900
  // 只有这台宿主压根没有工作区能力时,才退回老的多窗口投递。
4621
4901
  if (!ok && (viaRoom.fallback || isQuestion)) {
4622
- ok = inject(payload, true);
4902
+ ok = deliver(payload, true);
4623
4903
  why = ok ? '' : lastProblem || (isQuestion ? '问题没投进任何会话' : '老投递也失败了');
4624
4904
  }
4625
4905
  if (!ok) {
@@ -5118,6 +5398,18 @@ function applyInner(ctx, config = {}) {
5118
5398
  friends: friendList,
5119
5399
  // ★ 哪几条能撤回(一次算好,不是每条消息问一遍 —— canRecall 每次读整个 mailbox)
5120
5400
  recallable: [...recall.recallableIds()],
5401
+ // ★ 2026-12-04(A4):还欠着谁的回答。岸的原话:「能知道有会话去问的问题」。
5402
+ // ★ 必须传 —— 不传 ui.js 那边就是 null,那一行永远不出现(静默降级这一类)。
5403
+ // 只取最近 5 条给面板做 tooltip;总数是**全部**未答的,不只是这 5 条。
5404
+ questions: (() => {
5405
+ try {
5406
+ const open = pendingQ.listOpen(dataDir(), { limit: 5 });
5407
+ const all = pendingQ.inspect(dataDir());
5408
+ return { open, total: all.open };
5409
+ } catch {
5410
+ return null; // 读表失败就当没有 —— 不能因为这条面板坏了挡住整页
5411
+ }
5412
+ })(),
5121
5413
  // ★ 点谁看谁:wantSelected 来自 /ui?sel=fp;没点就还是当前配对的那个。
5122
5414
  // ui.js 那边会校验这个 fp 在不在好友列表里,不在就回退第一个 —— 所以不用在这防。
5123
5415
  // ★ 2026-12-01(用户:「还是退不出不了」「你有没有做那个退出的UI呀?」):
@@ -5127,6 +5419,10 @@ function applyInner(ctx, config = {}) {
5127
5419
  // undefined / null = 调用方没表态(比如 fishpal_ui 工具生成网页)→ 照旧回落主好友;
5128
5420
  // '' = 明确要空会话(GET /ui 不带 sel、或点了 ✕)→ 就给空会话。
5129
5421
  selected: wantSelected === '' ? '' : (wantSelected || cfg.peerFp),
5422
+ // ★ 2026-12-04(H2 + H1 方案 C):全局回信昵称的当前值。
5423
+ // 页面顶部设置区那个输入框靠它回填 —— 不传的话输入框永远是空的,
5424
+ // 用户设过了再打开还以为没设(「读和写对不上」那一类)。
5425
+ replyNick: cfg.replyNick || '',
5130
5426
  quarantine,
5131
5427
  budget: budgetView,
5132
5428
  loop: loopView,
@@ -5659,8 +5955,9 @@ function applyInner(ctx, config = {}) {
5659
5955
  parameters: {
5660
5956
  action: {
5661
5957
  type: 'string',
5662
- enum: ['export', 'inspect', 'import'],
5663
- description: 'export / inspect / import(默认 export)',
5958
+ enum: ['export', 'inspect', 'import', 'set'],
5959
+ description:
5960
+ 'export / inspect / import(默认 export)/ set(改全局设置,目前能改 replyNick 回信昵称)',
5664
5961
  required: true,
5665
5962
  },
5666
5963
  out: { type: 'string', description: 'export 时写到哪,默认 <fishpal>/fishpal-config.json', required: false },
@@ -5672,6 +5969,15 @@ function applyInner(ctx, config = {}) {
5672
5969
  'import 时:merge(只补本地没有的好友,全局设置本地为空才覆盖,默认)/ replace(好友按包里覆盖,本地多出来的保留)/ skip(一个已存在的都不碰:只补缺的好友,全局设置一律不动)',
5673
5970
  required: false,
5674
5971
  },
5972
+ // ★ 2026-12-04(H2,配合 H1 方案 C):全局回信昵称。
5973
+ // 这是「全局默认」,单封要改走 fishpal_send 的 nick 参数。
5974
+ replyNick: {
5975
+ type: 'string',
5976
+ description:
5977
+ 'set 时用:回信昵称(对面看到你叫什么)。空字符串 = 清掉,退回「不带昵称」。' +
5978
+ '只影响**之后**发出的消息,改不了已经发出去的。',
5979
+ required: false,
5980
+ },
5675
5981
  yes: {
5676
5982
  type: 'boolean',
5677
5983
  description: 'import 的二次确认。不带 true 只回报「将会改什么」,不落地',
@@ -5685,6 +5991,46 @@ function applyInner(ctx, config = {}) {
5685
5991
  async execute(args = {}) {
5686
5992
  const action = args.action ?? 'export';
5687
5993
 
5994
+ // ★ 2026-12-04(H2):改全局设置。
5995
+ // 现在只有 replyNick 一项 —— 先做这一个能用的,别铺开成「设置中心」。
5996
+ if (action === 'set') {
5997
+ // ★ 必须先 loadConfig 再 saveConfig(index.js:1723 那条教训):
5998
+ // 用内存里那份 cfg 直接写回去,会把别处刚改的值冲掉。
5999
+ const fresh = loadConfig();
6000
+ if (!fresh) return { text: '还没有配置:先 fishpal_pair 配对。' };
6001
+ const next = { ...fresh };
6002
+
6003
+ if (args.replyNick === undefined) {
6004
+ return {
6005
+ text: [
6006
+ 'set 要指定改什么。现在能改的只有一项:',
6007
+ ` replyNick —— 当前:${next.replyNick ? JSON.stringify(next.replyNick) : '(没设)'}`,
6008
+ '',
6009
+ '用法:fishpal_config action=set replyNick=阿汐',
6010
+ '清掉:fishpal_config action=set replyNick=(空字符串)',
6011
+ ].join('\n'),
6012
+ };
6013
+ }
6014
+
6015
+ const raw = String(args.replyNick ?? '').trim();
6016
+ if (raw.length > 40) return { text: `昵称最多 40 字,你这个 ${raw.length} 字。` };
6017
+ // 控制字符会让对面的界面显示错乱(也会被 wrapForInjection 剥掉),这里先拒
6018
+ if (/[\u0000-\u001f\u007f]/.test(raw)) return { text: '昵称里不能有控制字符。' };
6019
+
6020
+ if (raw) next.replyNick = raw;
6021
+ else delete next.replyNick;
6022
+ try {
6023
+ saveConfig(next);
6024
+ } catch (e) {
6025
+ return { text: '写配置失败:' + (e?.message ?? e) };
6026
+ }
6027
+ return {
6028
+ text: raw
6029
+ ? `已设回信昵称:${JSON.stringify(raw)}\n(只影响之后发出的消息;单封要改就在 fishpal_send 里传 nick。)`
6030
+ : '已清掉回信昵称:之后发出的消息不再带名字,对面按它本地备注显示。',
6031
+ };
6032
+ }
6033
+
5688
6034
  if (action === 'export') {
5689
6035
  const r = configPack.packConfig({
5690
6036
  out: typeof args.out === 'string' && args.out.trim() ? args.out.trim() : null,