feat(onebot): implement mark all as read
Replace the compatibility no-op with a real batched read action for current groups and observed incoming private conversations. Exclude stale groups, group temporary sessions, and sent-message echoes from private targets, then expose the functional action through the generated MCP catalog. Add action and message-store regressions for target selection and delegation.
This commit is contained in:
8 files changed
+93
-14
No files matched your search
@@ -155,7 +155,7 @@
|
||||
{
|
||||
"name": "_mark_all_as_read",
|
||||
"aliases": [],
|
||||
"summary": "标记全部已读(no-op,待 RE 全读 cmd)",
|
||||
"summary": "标记全部已读",
|
||||
"readOnly": false,
|
||||
"params": [],
|
||||
"invariants": [],
|
||||
|
||||
@@ -158,7 +158,7 @@ export const ACTIONS: CatalogAction[] = [
|
||||
{
|
||||
"name": "_mark_all_as_read",
|
||||
"aliases": [],
|
||||
"summary": "标记全部已读(no-op,待 RE 全读 cmd)",
|
||||
"summary": "标记全部已读",
|
||||
"readOnly": false,
|
||||
"params": [],
|
||||
"invariants": [],
|
||||
|
||||
@@ -690,14 +690,13 @@ export const actions = [
|
||||
},
|
||||
}),
|
||||
|
||||
// _mark_all_as_read — no-op。NapCat 靠单次内核 IPC markAllMsgAsRead() 实现,
|
||||
// SnowLuma 无等价单包 SSO cmd;遍历所有会话逐个发已读报告是风控高危群发,
|
||||
// 故暂不真正执行(留待 RE 出"一键全读"cmd)。返回 ok 以兼容启动时盲调的客户端。
|
||||
defineAction({
|
||||
name: '_mark_all_as_read',
|
||||
summary: '标记全部已读(no-op,待 RE 全读 cmd)',
|
||||
summary: '标记全部已读',
|
||||
params: {},
|
||||
run: async () => {
|
||||
run: async (_p, ctx) => {
|
||||
const sessions = ctx.listReadSessions();
|
||||
await ctx.bridge.apis.message.markAllRead(sessions.groupIds, sessions.privateUserIds);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
} from './actions';
|
||||
import type { GroupSystemMessageQuery } from './modules/contact-actions';
|
||||
import type { ForwardPreviewMeta } from './modules/message-actions';
|
||||
import type { ReadSessionTargets } from './message-store';
|
||||
import type { JsonObject, JsonValue, MessageMeta } from './types';
|
||||
import { RETCODE, failedResponse, okResponse } from './types';
|
||||
import { type StreamSink, wrapStreamFrame, wrapStreamTerminal } from './streaming';
|
||||
@@ -38,6 +39,7 @@ export interface ApiActionContext {
|
||||
isOnline: () => boolean;
|
||||
getMessage: (messageId: number) => JsonObject | null;
|
||||
getMessageMeta: (messageId: number) => MessageMeta | null;
|
||||
listReadSessions: () => ReadSessionTargets;
|
||||
sendPrivateMessage: (userId: number, message: JsonValue, autoEscape: boolean, tempGroupId?: number) => Promise<MessageSendResult>;
|
||||
sendGroupMessage: (groupId: number, message: JsonValue, autoEscape: boolean) => Promise<MessageSendResult>;
|
||||
deleteMessage: (messageId: number, meta: MessageMeta) => Promise<void>;
|
||||
|
||||
@@ -66,6 +66,9 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
isOnline: () => true,
|
||||
getMessage: (messageId) => messageStore.findEvent(messageId),
|
||||
getMessageMeta: (messageId) => messageStore.findMeta(messageId),
|
||||
listReadSessions: () => messageStore.listReadSessions(
|
||||
bridge.identity.groups.map(group => group.groupId),
|
||||
),
|
||||
canSendImage: () => true,
|
||||
canSendRecord: () => true,
|
||||
sendPrivateMessage: (userId, message, autoEscape, tempGroupId) => sendPrivateMessage(ref, userId, message, autoEscape, tempGroupId),
|
||||
|
||||
@@ -2,6 +2,11 @@ import { DatabaseSync, type StatementSync } from 'node:sqlite';
|
||||
import type { JsonObject, MessageMeta } from './types';
|
||||
import { openSqliteDb } from './sqlite-open';
|
||||
|
||||
export interface ReadSessionTargets {
|
||||
groupIds: number[];
|
||||
privateUserIds: number[];
|
||||
}
|
||||
|
||||
export class MessageStore {
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly stmtStoreEvent: StatementSync;
|
||||
@@ -12,6 +17,7 @@ export class MessageStore {
|
||||
private readonly stmtResolveReplyPrivate: StatementSync;
|
||||
private readonly stmtListEventsAnchored: StatementSync;
|
||||
private readonly stmtListEventsLatest: StatementSync;
|
||||
private readonly stmtListIncomingC2CSessions: StatementSync;
|
||||
|
||||
constructor(dbPath: string) {
|
||||
// Replace .json extension with .db if present
|
||||
@@ -85,6 +91,18 @@ export class MessageStore {
|
||||
ORDER BY sequence DESC
|
||||
LIMIT ?`,
|
||||
);
|
||||
|
||||
this.stmtListIncomingC2CSessions = this.db.prepare(
|
||||
`SELECT session_id
|
||||
FROM messages
|
||||
WHERE is_group = 0
|
||||
AND data IS NOT NULL
|
||||
AND json_extract(data, '$.post_type') = 'message'
|
||||
AND json_extract(data, '$.message_type') = 'private'
|
||||
AND json_extract(data, '$.sub_type') = 'friend'
|
||||
GROUP BY session_id
|
||||
ORDER BY session_id ASC`,
|
||||
);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
@@ -209,7 +227,35 @@ export class MessageStore {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build read-report targets from current groups plus genuine incoming C2C
|
||||
* sessions. `is_group = 0` alone is insufficient: group temp sessions use
|
||||
* the same storage lane, and sent-message echoes may be keyed by self UIN.
|
||||
* Only an incoming `sub_type=friend` event can represent unread C2C state.
|
||||
*/
|
||||
listReadSessions(currentGroupIds: readonly number[]): ReadSessionTargets {
|
||||
const groupIds: number[] = [];
|
||||
const seenGroups = new Set<number>();
|
||||
for (const groupId of currentGroupIds) {
|
||||
if (!Number.isSafeInteger(groupId) || groupId <= 0) {
|
||||
throw new Error(`current group list contains invalid group id ${String(groupId)}`);
|
||||
}
|
||||
if (!seenGroups.has(groupId)) {
|
||||
seenGroups.add(groupId);
|
||||
groupIds.push(groupId);
|
||||
}
|
||||
}
|
||||
|
||||
const rows = this.stmtListIncomingC2CSessions.all() as Array<{ session_id: number }>;
|
||||
const privateUserIds: number[] = [];
|
||||
for (const row of rows) {
|
||||
if (!Number.isSafeInteger(row.session_id) || row.session_id <= 0) {
|
||||
throw new Error(`messages database contains invalid session id ${String(row.session_id)}`);
|
||||
}
|
||||
privateUserIds.push(row.session_id);
|
||||
}
|
||||
return { groupIds, privateUserIds };
|
||||
}
|
||||
|
||||
private initSchema(): void {
|
||||
this.db.exec(`
|
||||
|
||||
@@ -101,6 +101,7 @@ function fakeCtx(bridge: BridgeInterface, overrides: Partial<ApiActionContext> =
|
||||
bridge,
|
||||
getMessageMeta: () => null,
|
||||
getMessage: () => null,
|
||||
listReadSessions: () => ({ groupIds: [], privateUserIds: [] }),
|
||||
getLoginInfo: () => ({ userId: 1, nickname: '' }),
|
||||
isOnline: () => true,
|
||||
canSendImage: () => true,
|
||||
@@ -891,10 +892,8 @@ describe('extended-actions / ocr_image', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ─── TierB Phase 1: compat stubs (model_show / online_clients / mark_all_as_read) ───
|
||||
// These are kernel-only in NapCat (mock/no-op), so SnowLuma ships honest
|
||||
// compat shapes rather than RE-ing a wire that doesn't exist. We pin the
|
||||
// response *shape* of each. NOTE two deliberate divergences from NapCat:
|
||||
// ─── TierB Phase 1: compatibility actions ───
|
||||
// NOTE two deliberate divergences from NapCat:
|
||||
// • _get_model_show reuses NapCat's array/variants shape but ECHOES the
|
||||
// requested model instead of NapCat's hardcoded 'napcat'.
|
||||
// • get_online_clients returns the OneBot-v11/go-cqhttp { clients: [] }
|
||||
@@ -931,9 +930,15 @@ describe('extended-actions / TierB compat stubs', () => {
|
||||
expect(res.data).toMatchObject({ clients: [] });
|
||||
});
|
||||
|
||||
it('_mark_all_as_read is an accepted no-op', async () => {
|
||||
const res = await makeHandler(fakeCtx(fakeBridge())).handle('_mark_all_as_read', {});
|
||||
expect(res).toMatchObject({ status: 'ok', retcode: 0 });
|
||||
it('_mark_all_as_read passes every observed session to the batched SSO implementation', async () => {
|
||||
const markAllRead = vi.fn(async () => undefined);
|
||||
const bridge = fakeBridge({ apis: { message: { markAllRead } } });
|
||||
const res = await makeHandler(fakeCtx(bridge, {
|
||||
listReadSessions: () => ({ groupIds: [101, 102], privateUserIds: [201] }),
|
||||
})).handle('_mark_all_as_read', {});
|
||||
|
||||
expect(markAllRead).toHaveBeenCalledWith([101, 102], [201]);
|
||||
expect(res).toMatchObject({ status: 'ok', retcode: 0, data: null });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -187,4 +187,28 @@ describe('MessageStore', () => {
|
||||
expect(retrieved).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('listReadSessions', () => {
|
||||
it('uses current groups and only genuine incoming friend sessions', () => {
|
||||
const event = (postType: string, subType: string) => ({
|
||||
time: 1700000000,
|
||||
post_type: postType,
|
||||
message_type: 'private',
|
||||
sub_type: subType,
|
||||
});
|
||||
store.storeEvent(1001, false, 40001, 1, PRIVATE_MESSAGE_EVENT, event('message', 'friend'));
|
||||
store.storeEvent(1002, false, 40001, 2, PRIVATE_MESSAGE_EVENT, event('message', 'friend'));
|
||||
store.storeEvent(1003, false, 40002, 3, PRIVATE_MESSAGE_EVENT, event('message', 'group'));
|
||||
store.storeEvent(1004, false, 40003, 4, PRIVATE_MESSAGE_EVENT, event('message_sent', 'friend'));
|
||||
|
||||
expect(store.listReadSessions([30002, 30001, 30002])).toEqual({
|
||||
groupIds: [30002, 30001],
|
||||
privateUserIds: [40001],
|
||||
});
|
||||
});
|
||||
|
||||
it('fails on a corrupt current group target', () => {
|
||||
expect(() => store.listReadSessions([0])).toThrow('invalid group id 0');
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user