feat(onebot): expose account session uptime

Expose account session uptime in status queries, matching the built-in status reply.

Fixes #486
This commit is contained in:
DrSmoothl committed 2026-09-27 13:41:17 +08:00
1 parent 797a4d754c
commit d610b3c90f
9 files changed
+46 -6

No files matched your search

+4 -3
View File
@@ -27,19 +27,20 @@ export const actions = [
defineAction({ defineAction({
name: 'get_status', name: 'get_status',
readOnly: true, readOnly: true,
returns: '运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态。', returns: '运行状态。`online` 表示账号在线;`good` 表示已确认的收发链路健康状态;`time` 为当前账号服务实例运行秒数,与 #sl 同源。',
returnsSchema: { returnsSchema: {
type: 'object', type: 'object',
properties: { properties: {
online: { type: 'boolean', description: '是否在线' }, online: { type: 'boolean', description: '是否在线' },
good: { type: 'boolean', description: '收发链路健康状态;确认接收停滞或主动请求连接失效时为 false' }, good: { type: 'boolean', description: '收发链路健康状态;确认接收停滞或主动请求连接失效时为 false' },
time: { type: 'integer', description: '当前账号服务实例运行秒数,与 #sl 同源;实例重建后重新计时' },
}, },
required: ['online', 'good'], required: ['online', 'good', 'time'],
}, },
params: {}, params: {},
run: (_p, ctx) => { run: (_p, ctx) => {
const online = ctx.isOnline(); const online = ctx.isOnline();
return okResponse({ online, good: online && ctx.bridge.receiveHealthy }); return okResponse({ online, good: online && ctx.bridge.receiveHealthy, time: Math.floor(ctx.getUptimeMs() / 1000) });
}, },
}), }),
+1
View File
@@ -49,6 +49,7 @@ export interface ApiActionContext {
bridge: BridgeInterface; bridge: BridgeInterface;
getLoginInfo: () => { userId: number; nickname: string }; getLoginInfo: () => { userId: number; nickname: string };
isOnline: () => boolean; isOnline: () => boolean;
getUptimeMs: () => number;
getMessage: (messageId: number) => JsonObject | null; getMessage: (messageId: number) => JsonObject | null;
getMessageMeta: (messageId: number) => MessageMeta | null; getMessageMeta: (messageId: number) => MessageMeta | null;
cacheMessageMetas: ( cacheMessageMetas: (
+2
View File
@@ -52,6 +52,7 @@ export interface OneBotInstanceContext {
converterCtx: ConverterContext; converterCtx: ConverterContext;
config: OneBotConfig; config: OneBotConfig;
musicSignUrl?: string; musicSignUrl?: string;
getUptimeMs(): number;
cacheMessageMeta(messageId: number, meta: MessageMeta): void; cacheMessageMeta(messageId: number, meta: MessageMeta): void;
dispatchEvent( dispatchEvent(
event: JsonObject, event: JsonObject,
@@ -68,6 +69,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
getLoginInfo: () => getLoginInfo(ref), getLoginInfo: () => getLoginInfo(ref),
isOnline: () => true, isOnline: () => true,
getUptimeMs: () => ref.getUptimeMs(),
getMessage: (messageId) => messageStore.findEvent(messageId), getMessage: (messageId) => messageStore.findEvent(messageId),
getMessageMeta: (messageId) => messageStore.findMeta(messageId), getMessageMeta: (messageId) => messageStore.findMeta(messageId),
cacheMessageMetas: (entries) => messageStore.storeMetas(entries), cacheMessageMetas: (entries) => messageStore.storeMetas(entries),
+3 -2
View File
@@ -62,7 +62,7 @@ export class OneBotInstance {
private lifecycleTail: Promise<void>; private lifecycleTail: Promise<void>;
private readonly rkeyCache: RKeyCache; private readonly rkeyCache: RKeyCache;
private readonly ctx: OneBotInstanceContext; private readonly ctx: OneBotInstanceContext;
/** Process-uptime baseline for the `#sl` status reply. */ /** Account-session uptime shared by the status action and `#sl`. */
private readonly startedAt = Date.now(); private readonly startedAt = Date.now();
/** Per-conversation last-reply timestamp for the `#sl` cooldown. */ /** Per-conversation last-reply timestamp for the `#sl` cooldown. */
private readonly statusCommandCooldown = new Map<string, number>(); private readonly statusCommandCooldown = new Map<string, number>();
@@ -180,6 +180,7 @@ export class OneBotInstance {
converterCtx: this.converterCtx, converterCtx: this.converterCtx,
config, config,
musicSignUrl: globalSettings.musicSignUrl, musicSignUrl: globalSettings.musicSignUrl,
getUptimeMs: () => Math.max(0, Date.now() - this.startedAt),
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta), cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
dispatchEvent: (event, source = 'bridge', startedAt) => this.dispatchEvent(event, source, startedAt), dispatchEvent: (event, source = 'bridge', startedAt) => this.dispatchEvent(event, source, startedAt),
}; };
@@ -477,7 +478,7 @@ export class OneBotInstance {
version: typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev', version: typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev',
platform: process.platform, platform: process.platform,
arch: process.arch, arch: process.arch,
uptimeMs: Date.now() - this.startedAt, uptimeMs: this.ctx.getUptimeMs(),
}); });
if (isGroup) await sendGroupMessage(this.ctx, sessionId, text, true); if (isGroup) await sendGroupMessage(this.ctx, sessionId, text, true);
else await sendPrivateMessage(this.ctx, sessionId, text, true); else await sendPrivateMessage(this.ctx, sessionId, text, true);
@@ -112,6 +112,7 @@ function makeRef(overrides: {
reactionStore?: Record<string, unknown>; reactionStore?: Record<string, unknown>;
converterCtx?: Record<string, unknown>; converterCtx?: Record<string, unknown>;
extraBridge?: Record<string, unknown>; extraBridge?: Record<string, unknown>;
getUptimeMs?: () => number;
} = {}): { } = {}): {
ref: OneBotInstanceContext; ref: OneBotInstanceContext;
api: ReturnType<typeof buildApiContext>; api: ReturnType<typeof buildApiContext>;
@@ -253,6 +254,7 @@ function makeRef(overrides: {
} as OneBotConfig, } as OneBotConfig,
cacheMessageMeta, cacheMessageMeta,
dispatchEvent, dispatchEvent,
getUptimeMs: overrides.getUptimeMs ?? (() => 0),
} as unknown as OneBotInstanceContext; } as unknown as OneBotInstanceContext;
return { return {
@@ -266,6 +268,17 @@ function makeRef(overrides: {
} }
describe('buildApiContext capabilities', () => { describe('buildApiContext capabilities', () => {
it('reads current uptime from each account session independently', () => {
let firstUptime = 1_999;
const first = makeRef({ getUptimeMs: () => firstUptime });
const second = makeRef({ getUptimeMs: () => 0 });
expect(first.api.getUptimeMs()).toBe(1_999);
expect(second.api.getUptimeMs()).toBe(0);
firstUptime = 3_001;
expect(first.api.getUptimeMs()).toBe(3_001);
expect(makeRef({ getUptimeMs: () => 0 }).api.getUptimeMs()).toBe(0);
});
it('reports the account as online and able to send image or record', () => { it('reports the account as online and able to send image or record', () => {
const { api } = makeRef(); const { api } = makeRef();
expect(api.isOnline()).toBe(true); expect(api.isOnline()).toBe(true);
+12 -1
View File
@@ -2,9 +2,20 @@ import { describe, expect, it } from 'vitest';
import { ApiHandler, type ApiActionContext } from '../src/api-handler'; import { ApiHandler, type ApiActionContext } from '../src/api-handler';
describe('get_status transport health (#233, #342)', () => { describe('get_status transport health (#233, #342)', () => {
it.each([0, 999, 1_000, 90_999])('reports whole session seconds for %i ms', async (uptimeMs) => {
const ctx = {
isOnline: () => true,
getUptimeMs: () => uptimeMs,
bridge: { receiveHealthy: true },
} as unknown as ApiActionContext;
const response = await new ApiHandler(ctx).handle('get_status', {});
expect(response.data).toEqual({ online: true, good: true, time: Math.floor(uptimeMs / 1000) });
});
it('keeps online true while reporting a stalled receive path as not good', async () => { it('keeps online true while reporting a stalled receive path as not good', async () => {
const ctx = { const ctx = {
isOnline: () => true, isOnline: () => true,
getUptimeMs: () => 90_999,
bridge: { receiveHealthy: false }, bridge: { receiveHealthy: false },
} as unknown as ApiActionContext; } as unknown as ApiActionContext;
const response = await new ApiHandler(ctx).handle('get_status', {}); const response = await new ApiHandler(ctx).handle('get_status', {});
@@ -12,7 +23,7 @@ describe('get_status transport health (#233, #342)', () => {
expect(response).toMatchObject({ expect(response).toMatchObject({
status: 'ok', status: 'ok',
retcode: 0, retcode: 0,
data: { online: true, good: false }, data: { online: true, good: false, time: 90 },
}); });
}); });
}); });
+2
View File
@@ -126,6 +126,8 @@ bot.when(
## Raw Action ## Raw Action
`await bot.getStatus()` 的 `time` 为当前账号服务实例的运行秒数,与 `#sl` 使用相同计时起点;实例重建后重新计时。
高频接口提供 camelCase 方法;其它 SnowLuma action 可以用 `raw` 或 `rawResponse`: 高频接口提供 camelCase 方法;其它 SnowLuma action 可以用 `raw` 或 `rawResponse`:
```ts ```ts
+2
View File
@@ -25,6 +25,8 @@ export interface LoginInfo {
export interface StatusInfo { export interface StatusInfo {
online: boolean; online: boolean;
good: boolean; good: boolean;
/** Current account-session uptime in seconds, matching #sl. */
time: number;
} }
export interface VersionInfo { export interface VersionInfo {
+7
View File
@@ -146,6 +146,13 @@ describe('SnowLumaApiClient.rawResponse', () => {
}); });
describe('SnowLumaApiClient typed actions', () => { describe('SnowLumaApiClient typed actions', () => {
it('exposes account-session uptime through getStatus', async () => {
const client = okClient({ online: true, good: true, time: 90 });
const status = await client.getStatus();
const seconds: number = status.time;
expect(seconds).toBe(90);
});
it('maps session helpers to empty-param OneBot actions', async () => { it('maps session helpers to empty-param OneBot actions', async () => {
const client = okClient(); const client = okClient();
const timeout = { timeoutMs: 2500 }; const timeout = { timeoutMs: 2500 };