a4phone 1.2.0 → 1.2.1

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
@@ -98,6 +98,8 @@ a4p status # 查看当前模式
98
98
  ```
99
99
 
100
100
  > 续聊完全 headless 运行(无需窗口标题匹配、前台焦点或剪贴板,也不依赖你当前是否开着终端),支持 Claude Code、Codex 与 DSH 会话(按最近会话的 agent 自动选择续聊方式)。续聊回合内若再次触发提问/权限请求,仍会推送手机,形成完整的远程对话闭环。
101
+ >
102
+ > **积压合并**:一轮续聊最长可达 `resumeTimeout`(默认 30 分钟),期间手机连续发来的消息会自动**合并为一个批次**一次性续聊(不再逐条排队、每条一个独立轮次),保证手机内容一定能送达 AI;积压批次持久化到 `~/.a4phone/pending-batch.json`,守护进程重启/崩溃后自动恢复,不丢消息。
101
103
 
102
104
  ## Codex
103
105
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "a4phone",
3
- "version": "1.2.0",
3
+ "version": "1.2.1",
4
4
  "description": "Claude Code / Codex / DSH 远程手机交互:任务完成通知(含 AI 最后输出)、提问/权限请求手机点选或文字作答、远程续聊(ntfy.sh,含 DSH 会话续聊)",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,75 @@
1
+ // batcher.mjs — 串行批处理器
2
+ //
3
+ // 解决续聊守护进程的积压问题:一轮续聊最长可达 resumeTimeout(默认 1800 秒),
4
+ // 期间手机发来的消息若逐条排队,每条都会触发一个独立的续聊轮次(N 条 = N 轮),
5
+ // 手机内容会被无限期延迟。本模块把忙时到达的消息**合并为一个批次**,
6
+ // 当前轮结束后一次处理整批——任意数量积压最多只产生一条额外续聊轮次,
7
+ // 保证手机内容一定能送达 AI(顺序保留、串行执行、有界延迟)。
8
+ //
9
+ // 用法:
10
+ // const batcher = createBatcher({
11
+ // run: async ({ text, count, msgTime }) => { ...; return true }, // false=丢弃该批
12
+ // log: (msg) => ...,
13
+ // });
14
+ // batcher.submit(text, msgTime); // 立即返回 drain 的 promise(fire-and-forget 也行)
15
+ // batcher.restore(texts, msgTime); // 启动时恢复上次未处理的批次
16
+ // batcher.pendingCount / batcher.pendingSnapshot() // 持久化与检查用
17
+ export function createBatcher({ run, log = () => {} }) {
18
+ let draining = null; // 正在执行的 drain 循环(防止并发)
19
+ const pending = { texts: [], msgTime: null };
20
+
21
+ function enqueue(text, msgTime) {
22
+ pending.texts.push(text);
23
+ pending.msgTime = pending.msgTime == null ? msgTime : Math.min(pending.msgTime, msgTime);
24
+ if (pending.texts.length === 2) {
25
+ log('当前续聊进行中,后续消息将合并为一条续聊请求');
26
+ }
27
+ }
28
+
29
+ // 串行排空循环:一次处理一批,过时/被拒批次丢弃后继续下一批(不会停顿)
30
+ function drain() {
31
+ if (!draining) {
32
+ draining = (async () => {
33
+ try {
34
+ while (pending.texts.length) {
35
+ const texts = pending.texts;
36
+ const msgTime = pending.msgTime;
37
+ pending.texts = [];
38
+ pending.msgTime = null;
39
+ try {
40
+ await run({ text: texts.join('\n\n'), count: texts.length, msgTime });
41
+ } catch (error) {
42
+ log(`批次处理异常(已跳过该批): ${String(error?.message ?? error)}`);
43
+ }
44
+ }
45
+ } finally {
46
+ draining = null;
47
+ }
48
+ })();
49
+ }
50
+ return draining;
51
+ }
52
+
53
+ return {
54
+ /** 提交一条消息;忙时自动合并进当前批次 */
55
+ submit(text, msgTime) {
56
+ enqueue(text, msgTime);
57
+ return drain();
58
+ },
59
+ /** 启动时恢复上次未处理完的批次(触发排空) */
60
+ restore(texts, msgTime) {
61
+ if (!Array.isArray(texts) || !texts.length) return;
62
+ for (const t of texts) pending.texts.push(String(t));
63
+ pending.msgTime = msgTime ?? null;
64
+ drain();
65
+ },
66
+ /** 当前积压条数(0 = 无积压) */
67
+ get pendingCount() {
68
+ return pending.texts.length;
69
+ },
70
+ /** 当前批次快照(供持久化) */
71
+ pendingSnapshot() {
72
+ return { texts: [...pending.texts], msgTime: pending.msgTime };
73
+ },
74
+ };
75
+ }
package/src/listen.mjs CHANGED
@@ -1,12 +1,17 @@
1
1
  // 续聊守护进程:订阅主话题,手机向主话题发送文字即触发一次续聊。
2
2
  // 断线自动重连(since 从上次消息之后继续),续聊请求串行处理(避免并发会话冲突)。
3
+ // 积压合并:一轮续聊最长 resumeTimeout(默认 1800 秒),忙时到达的手机消息
4
+ // 合并为一个批次,当前轮结束后一次续聊处理整批(任意数量积压最多只多一轮),
5
+ // 保证手机内容一定能送达 AI;批次持久化到 ~/.a4phone/pending-batch.json,
6
+ // 守护进程重启后自动恢复,避免积压消息丢失。
3
7
  // 按消息时间戳过滤:如果新会话开启时间晚于用户的消息时间,则跳过该消息,
4
8
  // 避免旧消息被注入到新会话中。
5
9
  import fs from 'fs';
6
10
  import path from 'path';
7
- import os from 'os';
8
11
  import { loadConfig, loadLastSession } from './config.mjs';
9
12
  import { runResume } from './resume.mjs';
13
+ import { createBatcher } from './batcher.mjs';
14
+ import { PENDING_PATH, ensureDir } from './paths.mjs';
10
15
 
11
16
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
12
17
  const RETRY_DELAY = 5000;
@@ -19,6 +24,13 @@ export function createLogWriter(logPath) {
19
24
  };
20
25
  }
21
26
 
27
+ // 原子写 JSON(临时文件 + rename,避免读者读到半个文件)
28
+ function atomicWriteJson(filePath, data) {
29
+ const tmp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
30
+ fs.writeFileSync(tmp, JSON.stringify(data));
31
+ fs.renameSync(tmp, filePath);
32
+ }
33
+
22
34
  export async function runListen({ onLog = (s) => console.log(s) } = {}) {
23
35
  const config = loadConfig();
24
36
  if (!config.topic) {
@@ -31,8 +43,6 @@ export async function runListen({ onLog = (s) => console.log(s) } = {}) {
31
43
 
32
44
  // ntfy 的 since 参数只接受 Unix 秒时间戳/时长/all,不接受 "now" 或消息 ID
33
45
  let lastTime = Math.floor(Date.now() / 1000); // 首次只收连接之后的新消息
34
- let busy = false;
35
- const queue = [];
36
46
  let knownSessionId = null; // 记录已处理过的会话 ID,用于检测会话切换
37
47
 
38
48
  // 判断消息是否仍应被处理:如果新会话在消息发送之后才创建,则丢弃
@@ -52,24 +62,48 @@ export async function runListen({ onLog = (s) => console.log(s) } = {}) {
52
62
  return false;
53
63
  }
54
64
 
55
- const processMessage = async (text, msgTime) => {
56
- if (busy) {
57
- queue.push({ text, msgTime });
58
- return;
59
- }
60
- if (msgTime != null && isMessageStale(msgTime)) return; // 旧消息,丢弃
61
- busy = true;
62
- onLog(`收到续聊请求:${text.slice(0, 60)}`);
63
- const result = await runResume(text, { config, onLog });
64
- onLog(result.ok
65
- ? `消息已处理(resume 续聊${result.code != null ? `,退出码 ${result.code}` : ''}),结果已推送手机。`
66
- : `续聊失败:${result.reason}`);
67
- busy = false;
68
- if (queue.length) {
69
- const next = queue.shift();
70
- processMessage(next.text, next.msgTime);
65
+ // 批次持久化:积压非空写文件,排空后删除(守护进程重启后恢复)
66
+ function persistSnapshot() {
67
+ try {
68
+ ensureDir();
69
+ const snapshot = batcher.pendingSnapshot();
70
+ if (snapshot.texts.length) {
71
+ atomicWriteJson(PENDING_PATH, snapshot);
72
+ } else {
73
+ try { fs.unlinkSync(PENDING_PATH); } catch {}
74
+ }
75
+ } catch {}
76
+ }
77
+
78
+ const batcher = createBatcher({
79
+ log: onLog,
80
+ run: async ({ text, count, msgTime }) => {
81
+ try {
82
+ if (msgTime != null && isMessageStale(msgTime)) return false; // 旧消息,丢弃
83
+ if (count > 1) onLog(`合并 ${count} 条积压消息为一条续聊请求`);
84
+ onLog(`收到续聊请求:${text.slice(0, 60)}`);
85
+ const result = await runResume(text, { config, onLog });
86
+ onLog(result.ok
87
+ ? `消息已处理(resume 续聊${result.code != null ? `,退出码 ${result.code}` : ''}),结果已推送手机。`
88
+ : `续聊失败:${result.reason}`);
89
+ return true;
90
+ } finally {
91
+ // 批次处理完成(或已丢弃)后刷新持久化:
92
+ // 期间若有新积压则保留到文件,否则清空,避免重启后重复处理已完成批次
93
+ persistSnapshot();
94
+ }
95
+ },
96
+ });
97
+
98
+ // 启动恢复:上次未处理完的积压批次(守护进程重启/崩溃不丢消息)
99
+ try {
100
+ const raw = fs.readFileSync(PENDING_PATH, 'utf-8');
101
+ const saved = JSON.parse(raw);
102
+ if (Array.isArray(saved?.texts) && saved.texts.length) {
103
+ onLog(`恢复 ${saved.texts.length} 条重启前未处理的续聊消息,继续处理...`);
104
+ batcher.restore(saved.texts, saved.msgTime ?? null);
71
105
  }
72
- };
106
+ } catch {}
73
107
 
74
108
  while (true) {
75
109
  try {
@@ -107,7 +141,8 @@ export async function runListen({ onLog = (s) => console.log(s) } = {}) {
107
141
  msg = event.message; // 纯文本:手机发来的续聊内容
108
142
  }
109
143
  if (typeof msg === 'string' && msg.trim()) {
110
- processMessage(msg.trim(), event.time ? Number(event.time) : null);
144
+ batcher.submit(msg.trim(), event.time ? Number(event.time) : null);
145
+ persistSnapshot();
111
146
  }
112
147
  }
113
148
  }
package/src/paths.mjs CHANGED
@@ -20,6 +20,9 @@ export const LOG_PATH = path.join(A4P_DIR, 'daemon.log');
20
20
  export const DSH_JOB_DIR = path.join(A4P_DIR, 'dsh-jobs');
21
21
  // DSH 插件心跳:dsh web 每次轮询刷新,a4p 据此判断 dsh web 是否在运行
22
22
  export const DSH_HEARTBEAT = path.join(A4P_DIR, 'dsh-heartbeat.json');
23
+ // 续聊积压批次持久化:长轮次期间到达的消息写入该文件,守护进程重启后恢复,
24
+ // 避免积压消息在重启时丢失
25
+ export const PENDING_PATH = path.join(A4P_DIR, 'pending-batch.json');
23
26
 
24
27
  // 旧版散落在家目录的单文件 → 迁移到 ~/.a4phone/(新路径不存在时才移动)
25
28
  const LEGACY_PATHS = {