diff --git a/packages/bridge/src/hook-manager.ts b/packages/bridge/src/hook-manager.ts index 49d38d3f..22473fc3 100644 --- a/packages/bridge/src/hook-manager.ts +++ b/packages/bridge/src/hook-manager.ts @@ -81,7 +81,7 @@ export type HookManagerDeps = { * Responsibilities: * - Route user commands (load/unload/refresh) to the matching session. * - Route watcher diff events to the matching session. - * - Forward session events ('login' / 'disconnected' / receive health) to BridgeManager. + * - Forward session events ('login' / 'disconnected' / transport health) to BridgeManager. * - Retry stuck-in-connecting sessions on every watcher tick (so a * failed connect eventually recovers without a manual refresh). * - Retry the bounded early-process auto-load race without retrying diff --git a/packages/bridge/src/hook-packet-client.ts b/packages/bridge/src/hook-packet-client.ts index e8935d2d..3898bc4e 100644 --- a/packages/bridge/src/hook-packet-client.ts +++ b/packages/bridge/src/hook-packet-client.ts @@ -1,8 +1,20 @@ import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender'; -import { QqHookClient, type QqHookSendReply } from './qq-hook-client'; +import { + HookPipeRequestError, + PIPE_STATUS_CONNECTION_UNAVAILABLE, + QqHookClient, + type QqHookSendReply, +} from './qq-hook-client'; + +export type OutboundHealthListener = (healthy: boolean) => void; export class HookPacketClient implements PacketSender { - constructor(private readonly client: QqHookClient) { } + private outboundHealthy = true; + + constructor( + private readonly client: QqHookClient, + private readonly onOutboundHealthChanged?: OutboundHealthListener, + ) { } async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = 15000): Promise { if (!this.client.isLoggedIn) { @@ -14,6 +26,7 @@ export class HookPacketClient implements PacketSender { wantReply: true, replyTimeoutMs: timeoutMs, }) as QqHookSendReply; + this.setOutboundHealthy(true); return { success: reply.error === 0, gotResponse: true, @@ -22,6 +35,10 @@ export class HookPacketClient implements PacketSender { responseData: reply.body, }; } catch (error) { + if (error instanceof HookPipeRequestError + && error.status === PIPE_STATUS_CONNECTION_UNAVAILABLE) { + this.setOutboundHealthy(false); + } return { success: false, gotResponse: false, @@ -31,4 +48,10 @@ export class HookPacketClient implements PacketSender { }; } } + + private setOutboundHealthy(healthy: boolean): void { + if (this.outboundHealthy === healthy) return; + this.outboundHealthy = healthy; + this.onOutboundHealthChanged?.(healthy); + } } diff --git a/packages/bridge/src/hook-session.ts b/packages/bridge/src/hook-session.ts index eecb61ac..5fb1429f 100644 --- a/packages/bridge/src/hook-session.ts +++ b/packages/bridge/src/hook-session.ts @@ -69,7 +69,7 @@ export type HookSessionDeps = { * Emitted events: * 'login' (uin, packetSender) — real-UIN login detected * 'disconnected' (wasLoggedIn) — connection dropped or torn down - * 'receive-health-changed' (healthy) — receive path confirmed stale/recovered + * 'receive-health-changed' (healthy) — combined receive/request path health changed * 'status-changed' (status, error) — status field mutated * 'disposed' () — session stopped tracking this PID */ @@ -107,6 +107,7 @@ export class HookSession extends EventEmitter { private nextLoginHintAt = 0; private nextLoginIdentityObservationAt = 0; private _receiveHealthy = true; + private _outboundHealthy = true; private receiveWatchUin = ''; private receiveWatchArmed = false; private receiveWatchTimer: ReturnType | null = null; @@ -130,7 +131,9 @@ export class HookSession extends EventEmitter { get uin(): string { return this._uin; } get method(): string { return this._method; } get isDisposed(): boolean { return this.disposed; } - get receiveHealthy(): boolean { return this._receiveHealthy; } + get receiveHealthy(): boolean { + return this._receiveHealthy && this._outboundHealthy; + } attachProcessInfo(info: { name?: string; path?: string }): void { if (info.name) this._name = info.name; @@ -499,7 +502,10 @@ export class HookSession extends EventEmitter { if (this.client?.isClosed) this.tearDownClient(); if (!this.client) { this.client = this.makeClient(this.pid); - this.sender = new HookPacketClient(this.client); + this.sender = new HookPacketClient( + this.client, + healthy => this.setOutboundHealthy(healthy), + ); this.bound = false; } if (!this.bound) { @@ -582,6 +588,7 @@ export class HookSession extends EventEmitter { this.bound = false; this.connected = false; this.loggedIn = false; + this._outboundHealthy = true; this.resetLoginHint(); } @@ -595,9 +602,13 @@ export class HookSession extends EventEmitter { this.stopLoginReconcile(); // A PID can switch accounts without an intermediate logout edge. Never // carry the previous account's heartbeat deadline into the new epoch. - if (this.receiveWatchUin !== this._uin) this.resetReceiveWatch(this._uin); + if (this.receiveWatchUin !== this._uin) { + this.resetReceiveWatch(this._uin); + this._outboundHealthy = true; + } } else { this.resetReceiveWatch(); + this._outboundHealthy = true; } // Only the connected/logged-in states are ours to set here; when fully @@ -844,8 +855,29 @@ export class HookSession extends EventEmitter { private setReceiveHealthy(healthy: boolean): void { if (this._receiveHealthy === healthy) return; + const previous = this.receiveHealthy; this._receiveHealthy = healthy; - this.emit('receive-health-changed', healthy); + if (previous !== this.receiveHealthy) { + this.emit('receive-health-changed', this.receiveHealthy); + } + } + + private setOutboundHealthy(healthy: boolean): void { + if (this._outboundHealthy === healthy) return; + const previous = this.receiveHealthy; + this._outboundHealthy = healthy; + if (previous !== this.receiveHealthy) { + this.emit('receive-health-changed', this.receiveHealthy); + } + if (healthy) { + this.log.info('request path recovered: PID=%d UIN=%s', this.pid, this._uin); + } else { + this.log.warn( + 'request path unavailable: PID=%d UIN=%s; reporting good=false', + this.pid, + this._uin, + ); + } } private resetReceiveWatch(uin = ''): void { diff --git a/packages/bridge/src/qq-hook-client.ts b/packages/bridge/src/qq-hook-client.ts index c89b76e4..1573c23c 100644 --- a/packages/bridge/src/qq-hook-client.ts +++ b/packages/bridge/src/qq-hook-client.ts @@ -23,6 +23,7 @@ export const MAX_PIPE_MSG_BYTES = 65536; export const MAX_PIPE_BODY_BYTES = 16 * 1024 * 1024; export const DEFAULT_ACK_TIMEOUT_MS = 5000; export const DEFAULT_REPLY_TIMEOUT_MS = 30000; +export const PIPE_STATUS_CONNECTION_UNAVAILABLE = -39; const DEFAULT_PIPE_PROBE_TIMEOUT_MS = 250; const packetLog = createLogger('QQHook.Packet'); const runtimeLog = createLogger('QQHook.Runtime'); @@ -273,8 +274,12 @@ function withTimeout(promise: Promise, timeoutMs: number, label: string): }); } -class HookPipeRequestError extends Error { - constructor(message: string) { +export class HookPipeRequestError extends Error { + constructor( + message: string, + readonly status: number, + readonly requestId: number, + ) { super(message); this.name = 'HookPipeRequestError'; } @@ -1064,7 +1069,11 @@ export class QqHookClient extends EventEmitter { return; } if (frame.op === PipeOp.error) { - const error = new HookPipeRequestError(frame.msg || `pipe error ${frame.status}`); + const error = new HookPipeRequestError( + frame.msg || `pipe error ${frame.status}`, + frame.status, + frame.requestId, + ); const ack = this.pendingAcks.get(frame.requestId); if (ack) { this.pendingAcks.delete(frame.requestId); diff --git a/packages/bridge/tests/hook-packet-client.test.ts b/packages/bridge/tests/hook-packet-client.test.ts new file mode 100644 index 00000000..e6502f9c --- /dev/null +++ b/packages/bridge/tests/hook-packet-client.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it, vi } from 'vitest'; +import { HookPacketClient } from '../src/hook-packet-client'; +import { + HookPipeRequestError, + PIPE_STATUS_CONNECTION_UNAVAILABLE, + type QqHookClient, +} from '../src/qq-hook-client'; + +function fakeClient(send: QqHookClient['send']): QqHookClient { + return { + isLoggedIn: true, + send, + } as unknown as QqHookClient; +} + +describe('HookPacketClient outbound health', () => { + it('reports native connection loss once and recovers after a successful request', async () => { + const healthChanged = vi.fn(); + const send = vi + .fn() + .mockRejectedValueOnce(new HookPipeRequestError( + 'The QQ connection changed. Please restart QQ and try again.', + PIPE_STATUS_CONNECTION_UNAVAILABLE, + 1, + )) + .mockRejectedValueOnce(new HookPipeRequestError( + 'The QQ connection changed. Please restart QQ and try again.', + PIPE_STATUS_CONNECTION_UNAVAILABLE, + 2, + )) + .mockResolvedValueOnce({ + requestId: 3, + error: 0, + message: '', + body: Buffer.from('ok'), + }); + const sender = new HookPacketClient(fakeClient(send), healthChanged); + + await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))) + .resolves.toMatchObject({ success: false, gotResponse: false }); + await sender.sendPacket('Test.Command', Buffer.alloc(0)); + await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))) + .resolves.toMatchObject({ success: true, gotResponse: true }); + + expect(healthChanged.mock.calls).toEqual([[false], [true]]); + }); + + it('does not classify ordinary request rejection as connection loss', async () => { + const healthChanged = vi.fn(); + const send = vi.fn().mockRejectedValue( + new HookPipeRequestError('This request is not valid.', -38, 1), + ); + const sender = new HookPacketClient(fakeClient(send), healthChanged); + + await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))) + .resolves.toMatchObject({ success: false, gotResponse: false }); + + expect(healthChanged).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/bridge/tests/hook-session.test.ts b/packages/bridge/tests/hook-session.test.ts index 28dca715..78f0246f 100644 --- a/packages/bridge/tests/hook-session.test.ts +++ b/packages/bridge/tests/hook-session.test.ts @@ -2,7 +2,12 @@ import { afterEach, describe, it, expect, vi } from 'vitest'; import { EventEmitter } from 'events'; import { HookSession } from '../src/hook-session'; import type { ManualMapHandle } from '../src/injector'; -import type { QqHookClient, QqHookPacket } from '../src/qq-hook-client'; +import { + HookPipeRequestError, + PIPE_STATUS_CONNECTION_UNAVAILABLE, + type QqHookClient, + type QqHookPacket, +} from '../src/qq-hook-client'; import type { QqPortLoginInfo } from '../src/qq-port-probe'; import type { PacketSender } from '@snowluma/common/packet-sender'; import type { PacketSink } from '@snowluma/common/protocol-types'; @@ -35,6 +40,7 @@ class FakeClient extends EventEmitter { shouldFailConnect = false; nativeReadyOnIdentityHint = false; identityHintFailures = 0; + sendError: Error | null = null; readonly sentPackets: Array<{ serviceCmd: string; body: Buffer }> = []; readonly loginIdentityHints: string[] = []; private loginState = { loggedIn: false, uin: '0', uinNumber: 0n }; @@ -58,6 +64,7 @@ class FakeClient extends EventEmitter { if (this.nativeReadyOnIdentityHint) this.fireLogin(uin); } async send(serviceCmd: string, body: Buffer) { + if (this.sendError) throw this.sendError; this.sentPackets.push({ serviceCmd, body: Buffer.from(body) }); return { requestId: this.sentPackets.length, @@ -1061,6 +1068,39 @@ describe('HookSession — end-to-end receive health (#233)', () => { ctx.currentClient().firePacket({ seq, error: 0, cmd, uin, body: Buffer.alloc(0) }); } + it('reports native outbound loss as unhealthy and recovers on the next successful request', async () => { + const { ctx, healthChanges } = await startReceiveSession(); + let sender: PacketSender | undefined; + ctx.session.on('login', (_uin: string, nextSender: PacketSender) => { + sender = nextSender; + }); + + try { + // Re-emit on a new account epoch so the test captures the session sender. + ctx.currentClient().fireLogin('20002'); + ctx.currentClient().sendError = new HookPipeRequestError( + 'The QQ connection changed. Please restart QQ and try again.', + PIPE_STATUS_CONNECTION_UNAVAILABLE, + 1, + ); + + await sender!.sendPacket('Test.Command', Buffer.alloc(0)); + expect(ctx.session.receiveHealthy).toBe(false); + expect(healthChanges).toEqual([false]); + + // Incoming traffic alone must not conceal a still-broken send path. + firePacket(ctx, HEARTBEAT_CMD, '20002'); + expect(ctx.session.receiveHealthy).toBe(false); + + ctx.currentClient().sendError = null; + await sender!.sendPacket('Test.Command', Buffer.alloc(0)); + expect(ctx.session.receiveHealthy).toBe(true); + expect(healthChanges).toEqual([false, true]); + } finally { + ctx.session.dispose(); + } + }); + it('becomes unhealthy only after an observed QQ heartbeat stays silent, then recovers on the next packet', async () => { vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] }); const { ctx, healthChanges } = await startReceiveSession(); diff --git a/packages/bridge/tests/qq-hook-client.test.ts b/packages/bridge/tests/qq-hook-client.test.ts index f38a6a66..4411f57e 100644 --- a/packages/bridge/tests/qq-hook-client.test.ts +++ b/packages/bridge/tests/qq-hook-client.test.ts @@ -688,10 +688,19 @@ describe('QqHookClient — packet TRACE', () => { message: 'send ack 1 timed out after 25 ms', }); - await expect(client.sendAndWait( + const requestError = await client.sendAndWait( 'Pipe.Error', Buffer.from([0xff]), - )).rejects.toThrow('send ack 2 timed out after 25 ms'); + ).then( + () => null, + (error: unknown) => error, + ); + expect(requestError).toMatchObject({ + name: 'HookPipeRequestError', + message: 'send ack 2 timed out after 25 ms', + status: 12, + requestId: 2, + }); expect(traceMessages(entries)).toEqual(expect.arrayContaining([ expect.stringMatching(/^packet_terminal serviceCmd="Ack\.Timeout" requestId=1 outcome=timeout reason=ack_timeout error="send ack 1 timed out after 25 ms" elapsedMs=\d+$/), diff --git a/packages/core/src/bridge/bridge-interface.ts b/packages/core/src/bridge/bridge-interface.ts index f9422a07..6ab3ba27 100644 --- a/packages/core/src/bridge/bridge-interface.ts +++ b/packages/core/src/bridge/bridge-interface.ts @@ -3,8 +3,8 @@ import type { BridgeContext } from './bridge-context'; export interface BridgeInterface extends BridgeContext { readonly activePid: number | null; - /** False only when every attached QQ process is confirmed stale. - * An unarmed watchdog remains true for compatibility. */ + /** False only when every attached QQ process has a confirmed receive or + * request-path failure. An unarmed watchdog remains true for compatibility. */ readonly receiveHealthy: boolean; /** Latest device snapshot observed on this Bridge lifecycle. `null` means * QQ has not emitted its cache notification since SnowLuma attached. */ diff --git a/packages/mcp/src/generated/catalog.json b/packages/mcp/src/generated/catalog.json index fe29bb99..4b586994 100644 --- a/packages/mcp/src/generated/catalog.json +++ b/packages/mcp/src/generated/catalog.json @@ -6970,7 +6970,7 @@ { "name": "get_status", "aliases": [], - "returns": "运行状态。`online` 表示账号在线;`good` 仅在接收链路确认停滞时为 `false`。", + "returns": "运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态。", "returnsSchema": { "type": "object", "properties": { @@ -6980,7 +6980,7 @@ }, "good": { "type": "boolean", - "description": "接收链路健康状态;仅在确认停滞时为 false" + "description": "收发链路健康状态;确认接收停滞或主动请求连接失效时为 false" } }, "required": [ diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index 9083070e..8aceee23 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -6973,7 +6973,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "get_status", "aliases": [], - "returns": "运行状态。`online` 表示账号在线;`good` 仅在接收链路确认停滞时为 `false`。", + "returns": "运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态。", "returnsSchema": { "type": "object", "properties": { @@ -6983,7 +6983,7 @@ export const ACTIONS: CatalogAction[] = [ }, "good": { "type": "boolean", - "description": "接收链路健康状态;仅在确认停滞时为 false" + "description": "收发链路健康状态;确认接收停滞或主动请求连接失效时为 false" } }, "required": [ diff --git a/packages/onebot/src/actions/info.ts b/packages/onebot/src/actions/info.ts index e4724e83..dd2c975b 100644 --- a/packages/onebot/src/actions/info.ts +++ b/packages/onebot/src/actions/info.ts @@ -27,12 +27,12 @@ export const actions = [ defineAction({ name: 'get_status', readOnly: true, - returns: '运行状态。`online` 表示账号在线;`good` 仅在接收链路确认停滞时为 `false`。', + returns: '运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态。', returnsSchema: { type: 'object', properties: { online: { type: 'boolean', description: '是否在线' }, - good: { type: 'boolean', description: '接收链路健康状态;仅在确认停滞时为 false' }, + good: { type: 'boolean', description: '收发链路健康状态;确认接收停滞或主动请求连接失效时为 false' }, }, required: ['online', 'good'], }, diff --git a/packages/onebot/tests/status-health.test.ts b/packages/onebot/tests/status-health.test.ts index c99db9a5..f5692659 100644 --- a/packages/onebot/tests/status-health.test.ts +++ b/packages/onebot/tests/status-health.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; import { ApiHandler, type ApiActionContext } from '../src/api-handler'; -describe('get_status receive health (#233)', () => { +describe('get_status transport health (#233, #342)', () => { it('keeps online true while reporting a stalled receive path as not good', async () => { const ctx = { isOnline: () => true, diff --git a/packages/runtime/native/snowluma-linux-arm64.node b/packages/runtime/native/snowluma-linux-arm64.node index 77d26392..7ca4befc 100644 Binary files a/packages/runtime/native/snowluma-linux-arm64.node and b/packages/runtime/native/snowluma-linux-arm64.node differ diff --git a/packages/runtime/native/snowluma-linux-arm64.so b/packages/runtime/native/snowluma-linux-arm64.so index e20f470f..c98b676e 100644 Binary files a/packages/runtime/native/snowluma-linux-arm64.so and b/packages/runtime/native/snowluma-linux-arm64.so differ diff --git a/packages/runtime/native/snowluma-linux-x64.node b/packages/runtime/native/snowluma-linux-x64.node index 893eecc7..79ef6489 100644 Binary files a/packages/runtime/native/snowluma-linux-x64.node and b/packages/runtime/native/snowluma-linux-x64.node differ diff --git a/packages/runtime/native/snowluma-linux-x64.so b/packages/runtime/native/snowluma-linux-x64.so index cf752168..50f30678 100644 Binary files a/packages/runtime/native/snowluma-linux-x64.so and b/packages/runtime/native/snowluma-linux-x64.so differ diff --git a/packages/runtime/native/snowluma-win32-x64.dll b/packages/runtime/native/snowluma-win32-x64.dll index 9cd0646b..47a47954 100644 Binary files a/packages/runtime/native/snowluma-win32-x64.dll and b/packages/runtime/native/snowluma-win32-x64.dll differ diff --git a/packages/runtime/native/snowluma-win32-x64.node b/packages/runtime/native/snowluma-win32-x64.node index 60fe6ca9..f5fd351d 100644 Binary files a/packages/runtime/native/snowluma-win32-x64.node and b/packages/runtime/native/snowluma-win32-x64.node differ