cortico-world-wechat-claw 0.1.0 → 0.1.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/CHANGELOG.md +15 -1
- package/dist/webui.js +28 -2
- package/package.json +1 -1
- package/src/driver.ts +63 -10
- package/src/webui/client.ts +34 -5
- package/src/world.ts +117 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,4 +1,18 @@
|
|
|
1
|
-
# Changelog
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.1
|
|
4
|
+
|
|
5
|
+
修三个线上问题。
|
|
6
|
+
|
|
7
|
+
- **收不到消息(严重)**:服务端返回空 `get_updates_buf` 时被当成「没有新游标」而忽略,
|
|
8
|
+
于是永远带着旧游标去问,从此收不到任何新消息,但发送仍然正常。现在区分「字段缺失」(保留旧游标)
|
|
9
|
+
与「字段为空串」(真的重置)。
|
|
10
|
+
- **重连可能并存两个驱动**:`#startDriver` 没有等待旧驱动退出,连续点几次重连会短暂出现两个
|
|
11
|
+
驱动各带游标抢消息。现在先 await 旧驱动停止。
|
|
12
|
+
- **面板时间显示成 UTC**:最近消息时间直接截了 ISO 字符串,北京时间 05:11 会显示成 21:11。
|
|
13
|
+
现在按部署时区格式化。
|
|
14
|
+
- 连续 3 轮拿不到服务端响应时主动重建连接,并在界面写明「长轮询长时间没有响应」。
|
|
15
|
+
- 新增**解绑**按钮:清掉本机保存的凭据与游标,回到未绑定状态。微信里的对话不受影响。
|
|
2
16
|
|
|
3
17
|
## 0.1.0
|
|
4
18
|
|
package/dist/webui.js
CHANGED
|
@@ -169,6 +169,9 @@ var TEXT2 = {
|
|
|
169
169
|
refresh: "\u91CD\u65B0\u751F\u6210",
|
|
170
170
|
cancel: "\u53D6\u6D88\u626B\u7801",
|
|
171
171
|
reconnect: "\u91CD\u65B0\u8FDE\u63A5",
|
|
172
|
+
unbind: "\u89E3\u7ED1",
|
|
173
|
+
unbindConfirm: "\u89E3\u7ED1\u4F1A\u6E05\u6389\u672C\u673A\u4FDD\u5B58\u7684\u5FAE\u4FE1\u51ED\u636E\uFF0C\u4E4B\u540E\u8981\u91CD\u65B0\u626B\u7801\u624D\u80FD\u6536\u6D88\u606F\u3002\u5FAE\u4FE1\u91CC\u7684\u90A3\u4E2A\u5BF9\u8BDD\u4E0D\u4F1A\u6D88\u5931\u3002\u786E\u5B9A\u89E3\u7ED1\uFF1F",
|
|
174
|
+
unbindDone: "\u5DF2\u89E3\u7ED1\uFF0C\u672C\u673A\u4E0D\u518D\u6536\u53D1\u5FAE\u4FE1\u6D88\u606F\u3002",
|
|
172
175
|
verifyLabel: "\u624B\u673A\u5FAE\u4FE1\u663E\u793A\u7684\u6570\u5B57",
|
|
173
176
|
verifyPlaceholder: "\u4F8B\u5982 123456",
|
|
174
177
|
verifySubmit: "\u63D0\u4EA4\u9A8C\u8BC1\u7801",
|
|
@@ -192,6 +195,9 @@ var TEXT2 = {
|
|
|
192
195
|
refresh: "New QR code",
|
|
193
196
|
cancel: "Cancel",
|
|
194
197
|
reconnect: "Reconnect",
|
|
198
|
+
unbind: "Unbind",
|
|
199
|
+
unbindConfirm: "Unbinding clears the WeChat credentials saved on this machine; you will need to scan again to receive messages. The chat in WeChat itself stays. Continue?",
|
|
200
|
+
unbindDone: "Unbound. This machine no longer sends or receives WeChat messages.",
|
|
195
201
|
verifyLabel: "The number shown in WeChat",
|
|
196
202
|
verifyPlaceholder: "for example 123456",
|
|
197
203
|
verifySubmit: "Submit",
|
|
@@ -241,9 +247,11 @@ async function mountBinding(ctx) {
|
|
|
241
247
|
const generateButton = ui.button(t.generate, { variant: "primary" });
|
|
242
248
|
const cancelButton = ui.button(t.cancel, { size: "sm" });
|
|
243
249
|
const reconnectButton = ui.button(t.reconnect, { size: "sm" });
|
|
250
|
+
const unbindButton = ui.button(t.unbind, { variant: "danger", size: "sm" });
|
|
244
251
|
cancelButton.style.display = "none";
|
|
245
252
|
reconnectButton.style.display = "none";
|
|
246
|
-
|
|
253
|
+
unbindButton.style.display = "none";
|
|
254
|
+
actions.append(generateButton, cancelButton, reconnectButton, unbindButton);
|
|
247
255
|
sheet.body.append(stateLine, whoLine, tokenLine, messageLine, qrBox, linkRow, verifyRow, actions);
|
|
248
256
|
let currentState = {
|
|
249
257
|
bound: false,
|
|
@@ -252,6 +260,7 @@ async function mountBinding(ctx) {
|
|
|
252
260
|
accountId: "",
|
|
253
261
|
userId: "",
|
|
254
262
|
lastMessageAt: "",
|
|
263
|
+
lastMessageLocal: "",
|
|
255
264
|
lastError: "",
|
|
256
265
|
contextTokens: 0,
|
|
257
266
|
qrDataUrl: "",
|
|
@@ -269,7 +278,8 @@ async function mountBinding(ctx) {
|
|
|
269
278
|
whoLine.style.display = next.bound ? "" : "none";
|
|
270
279
|
tokenLine.textContent = next.bound ? t.tokenCount(next.contextTokens) : "";
|
|
271
280
|
tokenLine.style.display = next.bound ? "" : "none";
|
|
272
|
-
|
|
281
|
+
const stamp = next.lastMessageLocal || (next.lastMessageAt ? next.lastMessageAt.replace("T", " ").slice(0, 19) : "");
|
|
282
|
+
messageLine.textContent = stamp ? t.lastMessage(stamp) : next.bound ? t.noMessage : "";
|
|
273
283
|
messageLine.style.display = next.bound ? "" : "none";
|
|
274
284
|
if (next.loginError) {
|
|
275
285
|
stateLine.textContent = next.loginError;
|
|
@@ -289,6 +299,7 @@ async function mountBinding(ctx) {
|
|
|
289
299
|
generateButton.style.display = next.bound ? "none" : "";
|
|
290
300
|
cancelButton.style.display = binding && !next.bound ? "" : "none";
|
|
291
301
|
reconnectButton.style.display = next.bound ? "" : "none";
|
|
302
|
+
unbindButton.style.display = next.bound ? "" : "none";
|
|
292
303
|
};
|
|
293
304
|
const readState = async () => {
|
|
294
305
|
try {
|
|
@@ -328,6 +339,21 @@ async function mountBinding(ctx) {
|
|
|
328
339
|
}
|
|
329
340
|
})();
|
|
330
341
|
});
|
|
342
|
+
unbindButton.addEventListener("click", () => {
|
|
343
|
+
void (async () => {
|
|
344
|
+
const ok = await ui.confirm({ title: t.unbind, body: t.unbindConfirm, danger: true });
|
|
345
|
+
if (!ok) return;
|
|
346
|
+
unbindButton.disabled = true;
|
|
347
|
+
try {
|
|
348
|
+
paint(await ctx.invoke("unbind"));
|
|
349
|
+
ui.toast(t.unbindDone, "ok");
|
|
350
|
+
} catch (err) {
|
|
351
|
+
ui.toast(err instanceof Error ? err.message : String(err), "bad");
|
|
352
|
+
} finally {
|
|
353
|
+
unbindButton.disabled = false;
|
|
354
|
+
}
|
|
355
|
+
})();
|
|
356
|
+
});
|
|
331
357
|
const submitVerify = () => {
|
|
332
358
|
const code = verifyInput.value.trim();
|
|
333
359
|
if (!code) return;
|
package/package.json
CHANGED
package/src/driver.ts
CHANGED
|
@@ -6,6 +6,17 @@
|
|
|
6
6
|
* 上层只看到「连上了 / 断了 / 过期了 / 收到一条」。
|
|
7
7
|
*
|
|
8
8
|
* 令牌失效(-14)后暂停一小时再试,这是官方通道的约定:短时间内重复用旧令牌请求会被拒得更久。
|
|
9
|
+
*
|
|
10
|
+
* ## 两条容易出事的路径
|
|
11
|
+
*
|
|
12
|
+
* **长轮询超时是正常路径。** 服务端 hold 住请求,到点没消息就断开;`getUpdates` 把超时
|
|
13
|
+
* 折算成空批次返回。这不能算「连接成功」——否则界面一直显示已连接,而实际可能早就收不到了。
|
|
14
|
+
* 所以 `connected` 只在**真正拿到响应**(哪怕空)时置真,并且每轮都刷新 `lastPollAt`。
|
|
15
|
+
*
|
|
16
|
+
* **游标必须能被清空。** 服务端偶尔会返回空 `get_updates_buf`(重置信号)。早先的实现用
|
|
17
|
+
* `if (buf)` 判断,空串会被忽略,于是永远带着旧游标去问,服务端认为「你还在那个位置之前」,
|
|
18
|
+
* 从此再也推不出新消息——现象就是「能发不能收」。这里区分「字段缺失」(保留旧游标)与
|
|
19
|
+
* 「字段是空串」(真的重置)。
|
|
9
20
|
*/
|
|
10
21
|
import type { ILinkApi } from './protocol/api.ts';
|
|
11
22
|
import { ILinkError, errorText } from './protocol/api.ts';
|
|
@@ -17,6 +28,8 @@ import type { WeixinMessage } from './protocol/types.ts';
|
|
|
17
28
|
export const STALE_TOKEN_ERRCODE = -14;
|
|
18
29
|
/** 令牌失效后的暂停时长。 */
|
|
19
30
|
export const STALE_TOKEN_PAUSE_MS = 60 * 60 * 1000;
|
|
31
|
+
/** 连续这么多轮拿不到任何响应,就判定链路已死并强制重建。 */
|
|
32
|
+
export const DEAD_AFTER_SILENT_ROUNDS = 3;
|
|
20
33
|
|
|
21
34
|
export interface DriverStatus {
|
|
22
35
|
connected: boolean;
|
|
@@ -25,6 +38,8 @@ export interface DriverStatus {
|
|
|
25
38
|
error: string;
|
|
26
39
|
/** 令牌失效后的冷却截止时刻(毫秒)。 */
|
|
27
40
|
pausedUntilMs?: number;
|
|
41
|
+
/** 最近一次真正拿到响应(含空批次)的时刻,毫秒。 */
|
|
42
|
+
lastPollAtMs?: number;
|
|
28
43
|
}
|
|
29
44
|
|
|
30
45
|
export interface DriverOptions {
|
|
@@ -36,6 +51,13 @@ export interface DriverOptions {
|
|
|
36
51
|
pollTimeoutMs?: number;
|
|
37
52
|
reconnectBaseMs?: number;
|
|
38
53
|
reconnectMaxMs?: number;
|
|
54
|
+
/**
|
|
55
|
+
* 连续多少轮「既没消息也没响应」就重建连接。
|
|
56
|
+
* 0 表示不检查;默认 3 轮,约两分钟没有任何服务端响应就认为链路已死。
|
|
57
|
+
*/
|
|
58
|
+
deadAfterSilentRounds?: number;
|
|
59
|
+
/** 要求上层重建客户端(重连无望时的最后手段)。 */
|
|
60
|
+
onStalled?: () => void;
|
|
39
61
|
}
|
|
40
62
|
|
|
41
63
|
const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
|
|
@@ -46,8 +68,10 @@ export class ILinkDriver {
|
|
|
46
68
|
readonly #log: Logger;
|
|
47
69
|
readonly #onMessage: DriverOptions['onMessage'];
|
|
48
70
|
readonly #onStatus: DriverOptions['onStatus'];
|
|
71
|
+
readonly #onStalled?: () => void;
|
|
49
72
|
readonly #reconnectBaseMs: number;
|
|
50
73
|
readonly #reconnectMaxMs: number;
|
|
74
|
+
readonly #deadAfterSilentRounds: number;
|
|
51
75
|
|
|
52
76
|
#pollTimeoutMs: number;
|
|
53
77
|
#loop: Promise<void> | null = null;
|
|
@@ -57,6 +81,9 @@ export class ILinkDriver {
|
|
|
57
81
|
|
|
58
82
|
connected = false;
|
|
59
83
|
running = false;
|
|
84
|
+
lastPollAtMs = 0;
|
|
85
|
+
/** 连续多少轮拿不到服务端响应。 */
|
|
86
|
+
silentRounds = 0;
|
|
60
87
|
|
|
61
88
|
constructor(opts: DriverOptions) {
|
|
62
89
|
this.#api = opts.api;
|
|
@@ -64,9 +91,11 @@ export class ILinkDriver {
|
|
|
64
91
|
this.#log = opts.log;
|
|
65
92
|
this.#onMessage = opts.onMessage;
|
|
66
93
|
this.#onStatus = opts.onStatus;
|
|
94
|
+
this.#onStalled = opts.onStalled;
|
|
67
95
|
this.#pollTimeoutMs = opts.pollTimeoutMs ?? 35_000;
|
|
68
96
|
this.#reconnectBaseMs = opts.reconnectBaseMs ?? 1_000;
|
|
69
97
|
this.#reconnectMaxMs = opts.reconnectMaxMs ?? 30_000;
|
|
98
|
+
this.#deadAfterSilentRounds = opts.deadAfterSilentRounds ?? DEAD_AFTER_SILENT_ROUNDS;
|
|
70
99
|
}
|
|
71
100
|
|
|
72
101
|
start(): void {
|
|
@@ -95,6 +124,7 @@ export class ILinkDriver {
|
|
|
95
124
|
let syncBuf = '';
|
|
96
125
|
try {
|
|
97
126
|
syncBuf = await this.#store.loadSyncBuf();
|
|
127
|
+
if (syncBuf) this.#log.info(`从已保存的游标继续(${syncBuf.length} 字节)`);
|
|
98
128
|
} catch (err) {
|
|
99
129
|
this.#log.warn('读不到同步游标,从空游标开始', { error: errorText(err) });
|
|
100
130
|
}
|
|
@@ -133,26 +163,39 @@ export class ILinkDriver {
|
|
|
133
163
|
);
|
|
134
164
|
}
|
|
135
165
|
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
166
|
+
// 游标:区分「字段缺失」与「字段为空串」。后者是服务端要求重置,必须照做,
|
|
167
|
+
// 否则会一直带着旧游标问,永远拿不到新消息。
|
|
168
|
+
const buf = response?.get_updates_buf;
|
|
169
|
+
if (typeof buf === 'string') {
|
|
170
|
+
if (buf !== syncBuf) {
|
|
171
|
+
syncBuf = buf;
|
|
172
|
+
try {
|
|
173
|
+
await this.#store.saveSyncBuf(syncBuf);
|
|
174
|
+
} catch (err) {
|
|
175
|
+
this.#log.warn('同步游标没存下来', { error: errorText(err) });
|
|
176
|
+
}
|
|
142
177
|
}
|
|
143
178
|
}
|
|
179
|
+
|
|
144
180
|
const suggested = Number(response?.longpolling_timeout_ms);
|
|
145
181
|
if (Number.isFinite(suggested) && suggested > 0) {
|
|
146
182
|
this.#pollTimeoutMs = Math.min(Math.max(suggested, 5_000), 60_000);
|
|
147
183
|
}
|
|
148
184
|
|
|
185
|
+
// 真正拿到了响应(哪怕没有消息):链路是活的。
|
|
149
186
|
backoff = this.#reconnectBaseMs;
|
|
187
|
+
this.silentRounds = 0;
|
|
188
|
+
this.lastPollAtMs = Date.now();
|
|
150
189
|
if (!this.connected) {
|
|
151
190
|
this.connected = true;
|
|
152
|
-
this.#emit({ connected: true, expired: false, error: '' });
|
|
191
|
+
this.#emit({ connected: true, expired: false, error: '', lastPollAtMs: this.lastPollAtMs });
|
|
153
192
|
}
|
|
154
193
|
|
|
155
|
-
|
|
194
|
+
const messages = Array.isArray(response?.msgs) ? response.msgs : [];
|
|
195
|
+
if (messages.length) {
|
|
196
|
+
this.#log.info(`收到 ${messages.length} 条微信消息`);
|
|
197
|
+
}
|
|
198
|
+
for (const message of messages) {
|
|
156
199
|
if (this.#stopped) break;
|
|
157
200
|
try {
|
|
158
201
|
await this.#onMessage(message);
|
|
@@ -168,8 +211,18 @@ export class ILinkDriver {
|
|
|
168
211
|
return;
|
|
169
212
|
}
|
|
170
213
|
this.connected = false;
|
|
171
|
-
this
|
|
172
|
-
this.#
|
|
214
|
+
this.silentRounds += 1;
|
|
215
|
+
this.#emit({ connected: false, expired: false, error: errorText(err), lastPollAtMs: this.lastPollAtMs });
|
|
216
|
+
this.#log.warn('轮询失败,准备重连', { error: errorText(err), backoffMs: backoff, silentRounds: this.silentRounds });
|
|
217
|
+
|
|
218
|
+
// 连续多轮连不上:光靠退避重试没用了,让上层重建客户端(新的 dispatcher / 新连接)。
|
|
219
|
+
if (this.#deadAfterSilentRounds > 0 && this.silentRounds >= this.#deadAfterSilentRounds) {
|
|
220
|
+
this.#log.warn(`连续 ${this.silentRounds} 轮没有响应,请求重建连接`);
|
|
221
|
+
this.silentRounds = 0;
|
|
222
|
+
this.#onStalled?.();
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
|
|
173
226
|
await this.#sleep(backoff);
|
|
174
227
|
backoff = Math.min(backoff * 2, this.#reconnectMaxMs);
|
|
175
228
|
}
|
package/src/webui/client.ts
CHANGED
|
@@ -19,6 +19,8 @@ interface BindingState {
|
|
|
19
19
|
accountId: string;
|
|
20
20
|
userId: string;
|
|
21
21
|
lastMessageAt: string;
|
|
22
|
+
/** 已按部署时区格式化好的本地时间;优先用它,别直接截 lastMessageAt。 */
|
|
23
|
+
lastMessageLocal: string;
|
|
22
24
|
lastError: string;
|
|
23
25
|
contextTokens: number;
|
|
24
26
|
qrDataUrl: string;
|
|
@@ -36,6 +38,9 @@ const TEXT = {
|
|
|
36
38
|
refresh: '重新生成',
|
|
37
39
|
cancel: '取消扫码',
|
|
38
40
|
reconnect: '重新连接',
|
|
41
|
+
unbind: '解绑',
|
|
42
|
+
unbindConfirm: '解绑会清掉本机保存的微信凭据,之后要重新扫码才能收消息。微信里的那个对话不会消失。确定解绑?',
|
|
43
|
+
unbindDone: '已解绑,本机不再收发微信消息。',
|
|
39
44
|
verifyLabel: '手机微信显示的数字',
|
|
40
45
|
verifyPlaceholder: '例如 123456',
|
|
41
46
|
verifySubmit: '提交验证码',
|
|
@@ -59,6 +64,9 @@ const TEXT = {
|
|
|
59
64
|
refresh: 'New QR code',
|
|
60
65
|
cancel: 'Cancel',
|
|
61
66
|
reconnect: 'Reconnect',
|
|
67
|
+
unbind: 'Unbind',
|
|
68
|
+
unbindConfirm: 'Unbinding clears the WeChat credentials saved on this machine; you will need to scan again to receive messages. The chat in WeChat itself stays. Continue?',
|
|
69
|
+
unbindDone: 'Unbound. This machine no longer sends or receives WeChat messages.',
|
|
62
70
|
verifyLabel: 'The number shown in WeChat',
|
|
63
71
|
verifyPlaceholder: 'for example 123456',
|
|
64
72
|
verifySubmit: 'Submit',
|
|
@@ -120,9 +128,11 @@ async function mountBinding(ctx: WebUiPanelContext): Promise<void> {
|
|
|
120
128
|
const generateButton = ui.button(t.generate, { variant: 'primary' });
|
|
121
129
|
const cancelButton = ui.button(t.cancel, { size: 'sm' });
|
|
122
130
|
const reconnectButton = ui.button(t.reconnect, { size: 'sm' });
|
|
131
|
+
const unbindButton = ui.button(t.unbind, { variant: 'danger', size: 'sm' });
|
|
123
132
|
cancelButton.style.display = 'none';
|
|
124
133
|
reconnectButton.style.display = 'none';
|
|
125
|
-
|
|
134
|
+
unbindButton.style.display = 'none';
|
|
135
|
+
actions.append(generateButton, cancelButton, reconnectButton, unbindButton);
|
|
126
136
|
|
|
127
137
|
sheet.body.append(stateLine, whoLine, tokenLine, messageLine, qrBox, linkRow, verifyRow, actions);
|
|
128
138
|
|
|
@@ -133,6 +143,7 @@ async function mountBinding(ctx: WebUiPanelContext): Promise<void> {
|
|
|
133
143
|
accountId: '',
|
|
134
144
|
userId: '',
|
|
135
145
|
lastMessageAt: '',
|
|
146
|
+
lastMessageLocal: '',
|
|
136
147
|
lastError: '',
|
|
137
148
|
contextTokens: 0,
|
|
138
149
|
qrDataUrl: '',
|
|
@@ -166,9 +177,9 @@ async function mountBinding(ctx: WebUiPanelContext): Promise<void> {
|
|
|
166
177
|
tokenLine.textContent = next.bound ? t.tokenCount(next.contextTokens) : '';
|
|
167
178
|
tokenLine.style.display = next.bound ? '' : 'none';
|
|
168
179
|
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
180
|
+
// 用服务端给的本地时间;没有就退回原始值,但不截 UTC 钟点。
|
|
181
|
+
const stamp = next.lastMessageLocal || (next.lastMessageAt ? next.lastMessageAt.replace('T', ' ').slice(0, 19) : '');
|
|
182
|
+
messageLine.textContent = stamp ? t.lastMessage(stamp) : (next.bound ? t.noMessage : '');
|
|
172
183
|
messageLine.style.display = next.bound ? '' : 'none';
|
|
173
184
|
|
|
174
185
|
// 错误:优先显示扫码期的具体原因。
|
|
@@ -189,12 +200,13 @@ async function mountBinding(ctx: WebUiPanelContext): Promise<void> {
|
|
|
189
200
|
|
|
190
201
|
verifyRow.style.display = next.verifyRequired ? '' : 'none';
|
|
191
202
|
|
|
192
|
-
//
|
|
203
|
+
// 按钮:未绑定给「生成二维码」,扫码中给「取消」;已绑定给「重新连接」与「解绑」。
|
|
193
204
|
const binding = next.status === 'binding' || Boolean(next.qrDataUrl);
|
|
194
205
|
generateButton.textContent = binding ? t.refresh : t.generate;
|
|
195
206
|
generateButton.style.display = next.bound ? 'none' : '';
|
|
196
207
|
cancelButton.style.display = binding && !next.bound ? '' : 'none';
|
|
197
208
|
reconnectButton.style.display = next.bound ? '' : 'none';
|
|
209
|
+
unbindButton.style.display = next.bound ? '' : 'none';
|
|
198
210
|
};
|
|
199
211
|
|
|
200
212
|
const readState = async (): Promise<void> => {
|
|
@@ -239,6 +251,23 @@ async function mountBinding(ctx: WebUiPanelContext): Promise<void> {
|
|
|
239
251
|
})();
|
|
240
252
|
});
|
|
241
253
|
|
|
254
|
+
// 解绑会清凭据,先确认一次;不可撤销,所以给 danger 样式的确认框。
|
|
255
|
+
unbindButton.addEventListener('click', () => {
|
|
256
|
+
void (async () => {
|
|
257
|
+
const ok = await ui.confirm({ title: t.unbind, body: t.unbindConfirm, danger: true });
|
|
258
|
+
if (!ok) return;
|
|
259
|
+
unbindButton.disabled = true;
|
|
260
|
+
try {
|
|
261
|
+
paint(await ctx.invoke<BindingState>('unbind'));
|
|
262
|
+
ui.toast(t.unbindDone, 'ok');
|
|
263
|
+
} catch (err) {
|
|
264
|
+
ui.toast(err instanceof Error ? err.message : String(err), 'bad');
|
|
265
|
+
} finally {
|
|
266
|
+
unbindButton.disabled = false;
|
|
267
|
+
}
|
|
268
|
+
})();
|
|
269
|
+
});
|
|
270
|
+
|
|
242
271
|
const submitVerify = (): void => {
|
|
243
272
|
const code = verifyInput.value.trim();
|
|
244
273
|
if (!code) return;
|
package/src/world.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/**
|
|
2
2
|
* 微信 ClawBot World。
|
|
3
3
|
*
|
|
4
4
|
* 一个 iLink 一对一通道:扫码绑定、长轮询收消息、按类型回复文字/图片/文件。
|
|
@@ -428,6 +428,13 @@ export class WechatClawWorld implements World {
|
|
|
428
428
|
accountId: auth?.accountId ?? '',
|
|
429
429
|
userId: auth?.userId ?? '',
|
|
430
430
|
lastMessageAt: this.#lastMessageAt,
|
|
431
|
+
/**
|
|
432
|
+
* 面板显示用的本地时间。`lastMessageAt` 是 UTC ISO,直接截字符串会让操作者
|
|
433
|
+
* 看到 UTC 钟点(比如北京时间 05:11 显示成 21:11),所以这里按部署时区格式化。
|
|
434
|
+
*/
|
|
435
|
+
lastMessageLocal: this.#lastMessageAt
|
|
436
|
+
? `${this.#localStamp(Date.parse(this.#lastMessageAt))}`
|
|
437
|
+
: '',
|
|
431
438
|
lastError: login?.error || this.#lastError,
|
|
432
439
|
contextTokens: this.#contextCount,
|
|
433
440
|
startedAt: this.#startedAt,
|
|
@@ -460,6 +467,7 @@ export class WechatClawWorld implements World {
|
|
|
460
467
|
case 'verify': return this.#submitVerify(args?.[0]);
|
|
461
468
|
case 'cancel': return this.#cancelBinding();
|
|
462
469
|
case 'reconnect': return this.#reconnect();
|
|
470
|
+
case 'unbind': return this.#unbind();
|
|
463
471
|
default: throw new Error(`未知方法:${panel}.${method}`);
|
|
464
472
|
}
|
|
465
473
|
}
|
|
@@ -569,6 +577,59 @@ export class WechatClawWorld implements World {
|
|
|
569
577
|
return this.#publicState();
|
|
570
578
|
}
|
|
571
579
|
|
|
580
|
+
/**
|
|
581
|
+
* 解绑:清掉本机保存的凭据与游标,停掉长轮询,回到未绑定状态。
|
|
582
|
+
*
|
|
583
|
+
* 只清本机。微信侧的绑定关系在手机微信里,这里碰不到,所以面板文案要说清楚:
|
|
584
|
+
* 解绑后本机不再收消息,但微信里的那个 ClawBot 对话还在。
|
|
585
|
+
*/
|
|
586
|
+
async #unbind(): Promise<unknown> {
|
|
587
|
+
const hadToken = Boolean(this.#auth?.token);
|
|
588
|
+
|
|
589
|
+
// 停掉轮询,避免解绑后还有请求带着旧令牌出去。
|
|
590
|
+
const driver = this.#driver;
|
|
591
|
+
this.#driver = null;
|
|
592
|
+
if (driver) {
|
|
593
|
+
try {
|
|
594
|
+
await driver.stop();
|
|
595
|
+
} catch {
|
|
596
|
+
/* 停不下来也继续清凭据。 */
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
// 绑定流程也一并取消。
|
|
601
|
+
if (this.#login?.active) {
|
|
602
|
+
this.#login.active = false;
|
|
603
|
+
this.#loginAbort?.abort();
|
|
604
|
+
}
|
|
605
|
+
this.#login = null;
|
|
606
|
+
this.#loginAbort = null;
|
|
607
|
+
|
|
608
|
+
this.#auth = null;
|
|
609
|
+
this.#contextCount = 0;
|
|
610
|
+
this.#lastUserId = '';
|
|
611
|
+
this.#lastMessageAt = '';
|
|
612
|
+
this.#typingTickets.clear();
|
|
613
|
+
this.#lastError = '';
|
|
614
|
+
|
|
615
|
+
await this.#store.clearSession().catch((err) => {
|
|
616
|
+
this.#host?.log?.warn?.('清凭据失败', { error: errorText(err) });
|
|
617
|
+
});
|
|
618
|
+
|
|
619
|
+
this.#host?.log?.info?.(hadToken ? '微信已解绑' : '微信本来就没绑定,已清空本地状态');
|
|
620
|
+
|
|
621
|
+
await this.#pushEvent({
|
|
622
|
+
type: EVENT_LINK,
|
|
623
|
+
ts: nowIso(this.#timezone),
|
|
624
|
+
source: ID,
|
|
625
|
+
origin: 'internal',
|
|
626
|
+
text: hadToken ? '微信已解绑,本机不再收发消息。' : '微信本地状态已清空(原本未绑定)。',
|
|
627
|
+
meta: { kind: 'link/unbound' },
|
|
628
|
+
});
|
|
629
|
+
|
|
630
|
+
return this.#publicState();
|
|
631
|
+
}
|
|
632
|
+
|
|
572
633
|
async #startBinding(): Promise<unknown> {
|
|
573
634
|
if (this.#auth?.token) return this.#publicState();
|
|
574
635
|
if (this.#login?.active) return this.#publicState();
|
|
@@ -759,7 +820,7 @@ export class WechatClawWorld implements World {
|
|
|
759
820
|
this.#login.verifyCode = '';
|
|
760
821
|
}
|
|
761
822
|
await this.#rebuildClient();
|
|
762
|
-
this.#startDriver();
|
|
823
|
+
await this.#startDriver();
|
|
763
824
|
this.#host?.log?.info?.('微信绑定成功', { accountId, userId: shortId(userId) });
|
|
764
825
|
await this.#pushEvent({
|
|
765
826
|
type: EVENT_LINK,
|
|
@@ -821,7 +882,7 @@ export class WechatClawWorld implements World {
|
|
|
821
882
|
{ label: t.badgeAccount, value: state.bound ? (who || '—') : '—', tone: state.bound ? 'on' : 'off' },
|
|
822
883
|
{
|
|
823
884
|
label: t.badgeLast,
|
|
824
|
-
value: state.
|
|
885
|
+
value: state.lastMessageLocal ? state.lastMessageLocal.slice(11, 19) : '—',
|
|
825
886
|
tone: state.lastMessageAt ? 'on' : 'off',
|
|
826
887
|
},
|
|
827
888
|
{ label: t.badgeState, value: stateText, tone: state.connected ? 'on' : 'off' },
|
|
@@ -876,7 +937,7 @@ export class WechatClawWorld implements World {
|
|
|
876
937
|
|
|
877
938
|
this.#started = true;
|
|
878
939
|
if (this.#auth?.token) {
|
|
879
|
-
this.#startDriver();
|
|
940
|
+
await this.#startDriver();
|
|
880
941
|
} else {
|
|
881
942
|
host.log.info('微信尚未绑定,等待扫码');
|
|
882
943
|
}
|
|
@@ -903,6 +964,25 @@ export class WechatClawWorld implements World {
|
|
|
903
964
|
}
|
|
904
965
|
}
|
|
905
966
|
|
|
967
|
+
/** 把毫秒时间按部署时区格式化成 `YYYY-MM-DD HH:MM:SS`,给面板与回执看。 */
|
|
968
|
+
#localStamp(ms: number): string {
|
|
969
|
+
const d = new Date(Number.isFinite(ms) ? ms : Date.now());
|
|
970
|
+
try {
|
|
971
|
+
const parts = new Intl.DateTimeFormat('sv-SE', {
|
|
972
|
+
timeZone: this.#timezone || undefined,
|
|
973
|
+
year: 'numeric', month: '2-digit', day: '2-digit',
|
|
974
|
+
hour: '2-digit', minute: '2-digit', second: '2-digit',
|
|
975
|
+
hour12: false,
|
|
976
|
+
}).format(d);
|
|
977
|
+
return parts.replace(' ', ' ');
|
|
978
|
+
} catch {
|
|
979
|
+
// 时区名无效时退回本机时区,总比显示 UTC 强。
|
|
980
|
+
const pad = (n: number) => String(n).padStart(2, '0');
|
|
981
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} `
|
|
982
|
+
+ `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
|
|
906
986
|
#binDir(): string {
|
|
907
987
|
return `${this.#dataDir}/${ID}/bin`;
|
|
908
988
|
}
|
|
@@ -945,13 +1025,27 @@ export class WechatClawWorld implements World {
|
|
|
945
1025
|
});
|
|
946
1026
|
}
|
|
947
1027
|
|
|
948
|
-
|
|
1028
|
+
/**
|
|
1029
|
+
* 启动长轮询。
|
|
1030
|
+
*
|
|
1031
|
+
* 旧驱动必须先**真正停下**再起新的:两个驱动会各带自己的游标去问,服务端把消息推给其中
|
|
1032
|
+
* 一个、另一个把它写回旧游标,于是两边都以为「没新消息」。连续点几次重连正好触发这个。
|
|
1033
|
+
* 所以这里先置空(让旧驱动的回调立刻失效),再 await 它退出。
|
|
1034
|
+
*/
|
|
1035
|
+
async #startDriver(): Promise<void> {
|
|
949
1036
|
const api = this.#api;
|
|
950
1037
|
const auth = this.#auth;
|
|
951
1038
|
if (!api || !auth?.token) return;
|
|
1039
|
+
|
|
952
1040
|
const previous = this.#driver;
|
|
953
1041
|
this.#driver = null;
|
|
954
|
-
if (previous)
|
|
1042
|
+
if (previous) {
|
|
1043
|
+
try {
|
|
1044
|
+
await previous.stop();
|
|
1045
|
+
} catch (err) {
|
|
1046
|
+
this.#host?.log?.warn?.('旧驱动停止失败', { error: errorText(err) });
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
955
1049
|
|
|
956
1050
|
// 回调要认「这条消息是不是当前驱动发来的」,所以先声明再赋值。
|
|
957
1051
|
let driver: ILinkDriver;
|
|
@@ -961,6 +1055,7 @@ export class WechatClawWorld implements World {
|
|
|
961
1055
|
log: this.#host?.log ?? nullLoggerShim(),
|
|
962
1056
|
onMessage: (message): Promise<void> => this.#handleInbound(driver, message),
|
|
963
1057
|
onStatus: (status): void => this.#handleStatus(driver, status),
|
|
1058
|
+
onStalled: (): void => this.#handleStalled(driver),
|
|
964
1059
|
});
|
|
965
1060
|
this.#driver = driver;
|
|
966
1061
|
driver.start();
|
|
@@ -970,9 +1065,24 @@ export class WechatClawWorld implements World {
|
|
|
970
1065
|
});
|
|
971
1066
|
}
|
|
972
1067
|
|
|
1068
|
+
/** 重连多次都没响应:重建客户端(新连接)再起驱动,并如实记一条。 */
|
|
1069
|
+
#handleStalled(driver: ILinkDriver): void {
|
|
1070
|
+
if (driver !== this.#driver) return;
|
|
1071
|
+
this.#host?.log?.warn?.('微信长轮询长时间没有响应,重建连接');
|
|
1072
|
+
this.#lastError = '长轮询长时间没有响应,已重建连接';
|
|
1073
|
+
void (async () => {
|
|
1074
|
+
try {
|
|
1075
|
+
await this.#rebuildClient();
|
|
1076
|
+
await this.#startDriver();
|
|
1077
|
+
} catch (err) {
|
|
1078
|
+
this.#host?.log?.warn?.('重建连接失败', { error: errorText(err) });
|
|
1079
|
+
}
|
|
1080
|
+
})();
|
|
1081
|
+
}
|
|
1082
|
+
|
|
973
1083
|
async #restartDriver(): Promise<void> {
|
|
974
1084
|
await this.#rebuildClient();
|
|
975
|
-
this.#startDriver();
|
|
1085
|
+
await this.#startDriver();
|
|
976
1086
|
}
|
|
977
1087
|
|
|
978
1088
|
#handleStatus(driver: ILinkDriver, status: { connected: boolean; expired: boolean; error: string }): void {
|