diff --git a/src/main/http-server.ts b/src/main/http-server.ts index ca92e30..2e8024a 100644 --- a/src/main/http-server.ts +++ b/src/main/http-server.ts @@ -47,6 +47,14 @@ import type { VoiceTranscriptState } from '../shared/voice-recognition' import { voiceMessageReferenceOf } from './voice-pipeline/voice-message-identity' +import type { + MessageBrokerStatus, + MessageEventBroker, + MessageEventRecord, + MessageGap, + MessageSubscription +} from './services/message-event-broker' +import type { AgentTaskRecord, AgentTaskView } from '../shared/agent-task' export const DEFAULT_HTTP_HOST = '127.0.0.1' export const DEFAULT_HTTP_PORT = 6131 @@ -83,14 +91,41 @@ export interface HttpServerOptions { appVersionProvider?: () => string wechatSendCapabilityProvider?: () => Promise wechatSendExecutor?: (request: WechatActionRequest) => Promise + /** 实时消息事件代理。未注入时 `/api/v1/events/messages` 返回 503。 */ + messageEventBroker?: MessageEventBroker + /** SSE 心跳间隔(毫秒)。测试用;生产默认 15s。 */ + messageEventsHeartbeatMs?: number } let configuredQueryApiService: LocalQueryApiService | undefined let configuredGroupStatsService: Pick | undefined +let configuredMessageEventBroker: MessageEventBroker | undefined export function setLocalQueryApiService(service: LocalQueryApiService | undefined): void { configuredQueryApiService = service } +/** + * 注入实时消息事件代理。 + * + * 刻意用模块级注入而不是每次 `startHttpServer` 传参:API server 可能在数据库 + * 初始化之前启动,事件代理必须在数据库就绪前就存在,才能在 SSE 里如实报告 + * `database: unavailable` 而不是把连接直接打回 503。 + */ +export function setMessageEventBroker(broker: MessageEventBroker | undefined): void { + configuredMessageEventBroker = broker +} + +export interface AgentTaskInspector { + list(limit: number): AgentTaskRecord[] + get(id: string): AgentTaskRecord | undefined +} + +let configuredAgentTaskInspector: AgentTaskInspector | undefined +/** 注入只读任务视图。写入仍由 AgentTaskDispatcher 独占。 */ +export function setAgentTaskInspector(inspector: AgentTaskInspector | undefined): void { + configuredAgentTaskInspector = inspector +} + export function setLocalGroupStatsService( service: Pick | undefined ): void { @@ -1364,6 +1399,263 @@ function createAgentApiRoute( }) } +const MESSAGE_EVENTS_ROUTE = '/api/v1/events/messages' +const AGENT_TASKS_ROUTE = '/api/v1/agent-tasks' +const DEFAULT_MESSAGE_EVENTS_HEARTBEAT_MS = 15_000 +const MESSAGE_EVENTS_MAX_FILTERS = 20 + +/** SSE 连接句柄:`close` 优雅结束,`destroy` 用于服务停止时强制释放。 */ +interface MessageEventStreamHandle { + close(): void + destroy(): void +} + +function writeSseFrame( + res: ServerResponse, + frame: { id?: string; event?: string; data?: unknown } +): boolean { + try { + let text = '' + if (frame.id) text += `id: ${frame.id}\n` + if (frame.event) text += `event: ${frame.event}\n` + if (frame.data !== undefined) text += `data: ${JSON.stringify(frame.data)}\n` + res.write(`${text}\n`) + return true + } catch { + return false + } +} + +/** + * 解析会话过滤参数。 + * + * 只接受 `conversation_id` / `conversation_ids`(可重复、可逗号分隔), + * 值必须是会话 md5 —— 与 `messageRef.c` 同口径。username 不接受: + * 事件层无法把 username 当作稳定会话标识交给下游。 + */ +function parseConversationFilter(url: URL): string[] { + const raw = [ + ...url.searchParams.getAll('conversation_id'), + ...url.searchParams.getAll('conversation_ids') + ] + const ids: string[] = [] + for (const value of raw) { + for (const part of value.split(',')) { + const trimmed = part.trim() + if (!trimmed) continue + if (!/^[A-Za-z0-9_-]{1,128}$/.test(trimmed)) { + throw new Error('会话标识格式无效:需要 conversation md5') + } + if (!ids.includes(trimmed)) ids.push(trimmed) + } + } + if (ids.length > MESSAGE_EVENTS_MAX_FILTERS) { + throw new Error(`conversation_id 最多 ${MESSAGE_EVENTS_MAX_FILTERS} 个`) + } + return ids +} + +function createMessageEventsRoute( + pathname: string, + brokerProvider: () => MessageEventBroker | undefined, + trackStream: (handle: MessageEventStreamHandle) => () => void, + heartbeatMs: number +): RouteHandler | undefined { + if (pathname !== MESSAGE_EVENTS_ROUTE) return undefined + + return withMethods(['GET'], async ({ req, res, url }) => { + const broker = brokerProvider() + if (!broker) { + return sendJson(res, 503, { + error: 'events_unavailable', + message: '实时消息事件服务尚未就绪' + }) + } + + let conversationIds: string[] + try { + conversationIds = parseConversationFilter(url) + } catch (error) { + return sendError(res, 400, error instanceof Error ? error.message : String(error)) + } + + const headerLastEventId = req.headers['last-event-id'] + const lastEventId = + (typeof headerLastEventId === 'string' ? headerLastEventId : undefined) || + url.searchParams.get('last_event_id') || + undefined + const backfillEnabled = url.searchParams.get('backfill') !== '0' + const filterMode = conversationIds.length > 0 ? 'conversation' : 'all' + + res.writeHead(200, { + 'Content-Type': 'text/event-stream; charset=utf-8', + 'Cache-Control': 'no-cache, no-transform', + Connection: 'keep-alive', + 'X-Accel-Buffering': 'no', + 'X-Request-Id': String(res.getHeader('X-Request-Id') || '') + }) + res.flushHeaders?.() + req.socket?.setNoDelay(true) + // 重连间隔由服务端给出,客户端不必自己猜。 + res.write('retry: 3000\n\n') + + let closed = false + let subscription: MessageSubscription | null = null + let heartbeat: ReturnType | null = null + let untrack: (() => void) | null = null + + const cleanup = (): void => { + if (closed) return + closed = true + if (heartbeat) { + clearInterval(heartbeat) + heartbeat = null + } + subscription?.close() + untrack?.() + try { + res.end() + } catch { + // 连接可能已经被对端关掉,这里只是幂等收尾。 + } + } + + const destroy = (): void => { + cleanup() + try { + res.destroy() + } catch { + // 同上。 + } + } + + untrack = trackStream({ close: cleanup, destroy }) + req.on('close', cleanup) + res.on('close', cleanup) + res.on('error', cleanup) + + try { + subscription = broker.subscribe( + { conversationIds, lastEventId, backfill: backfillEnabled }, + { + onStatus(status: MessageBrokerStatus & { subscriptionId: string }) { + writeSseFrame(res, { + event: 'status', + data: { + ...status, + filter: filterMode, + conversationCount: conversationIds.length, + heartbeatMs, + backfill: backfillEnabled ? 'enabled' : 'disabled' + } + }) + }, + onEvent(event: MessageEventRecord, origin: 'live' | 'replay' | 'db_backfill') { + if (closed) return + if ( + !writeSseFrame(res, { + id: String(event.seq), + event: 'message', + data: { ...event, origin } + }) + ) { + cleanup() + } + }, + onGap(gap: MessageGap) { + writeSseFrame(res, { event: 'gap', data: gap }) + } + } + ) + } catch (error) { + writeSseFrame(res, { + event: 'error', + data: { + error: 'too_many_subscribers', + message: error instanceof Error ? error.message : String(error) + } + }) + cleanup() + return + } + + let lastDatabase = broker.status().database + heartbeat = setInterval(() => { + if (closed) return + res.write(`: heartbeat ${Date.now()}\n\n`) + /* + * 数据库断开/重连不是错误,是订阅状态的一部分: + * 只在这个状态真的变化时补发一条 status,避免每 15s 刷一次无信息事件。 + */ + const nextDatabase = broker.status().database + if (nextDatabase !== lastDatabase) { + lastDatabase = nextDatabase + writeSseFrame(res, { + event: 'status', + data: { ...broker.status(), subscriptionId: subscription?.id ?? '', filter: filterMode } + }) + } + }, heartbeatMs) + heartbeat.unref?.() + }) +} + +/** 记录 → 对外视图。`triggerKey` 属于内部幂等键,不对外暴露。 */ +function toAgentTaskView(record: AgentTaskRecord): AgentTaskView { + return { + id: record.id, + provider: record.provider, + conversationId: record.conversationId, + status: record.status, + prompt: record.prompt, + createdAt: record.createdAt, + updatedAt: record.updatedAt, + ...(record.submittedAt !== undefined ? { submittedAt: record.submittedAt } : {}), + ...(record.completedAt !== undefined ? { completedAt: record.completedAt } : {}), + ...(record.externalMessageId ? { externalMessageId: record.externalMessageId } : {}), + ...(record.errorKind ? { errorKind: record.errorKind } : {}), + ...(record.errorMessage ? { errorMessage: record.errorMessage } : {}), + replies: record.replies + } +} + +function createAgentTaskRoute( + pathname: string, + inspectorProvider: () => AgentTaskInspector | undefined +): RouteHandler | undefined { + if (pathname === AGENT_TASKS_ROUTE) { + return withMethods(['GET'], ({ res, url }) => { + const inspector = inspectorProvider() + if (!inspector) return sendError(res, 503, '任务服务尚未就绪') + const requested = Number(url.searchParams.get('limit') ?? '20') + const limit = Number.isFinite(requested) + ? Math.max(1, Math.min(Math.floor(requested), 100)) + : 20 + const tasks = inspector.list(limit).map(toAgentTaskView) + sendJson(res, 200, { count: tasks.length, tasks }) + }) + } + + const prefix = `${AGENT_TASKS_ROUTE}/` + if (!pathname.startsWith(prefix)) return undefined + const rawId = pathname.slice(prefix.length) + if (!rawId || rawId.includes('/')) return undefined + + return withMethods(['GET'], ({ res }) => { + const inspector = inspectorProvider() + if (!inspector) return sendError(res, 503, '任务服务尚未就绪') + let id: string + try { + id = decodeURIComponent(rawId) + } catch { + return sendError(res, 400, '任务 ID 无效') + } + const task = inspector.get(id) + if (!task) return sendError(res, 404, '任务不存在') + sendJson(res, 200, { task: toAgentTaskView(task) }) + }) +} + function requestIdFor(req: IncomingMessage): string { const incoming = req.headers['x-request-id'] return typeof incoming === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(incoming) @@ -1396,6 +1688,13 @@ export function startHttpServer( (() => personalWechatCapabilityService.getPersonalWechatSendCapability()), execute: options.wechatSendExecutor || ((request) => wechatActionGateway.execute(request)) } + const messageEventBroker = options.messageEventBroker + ? () => options.messageEventBroker + : () => configuredMessageEventBroker + const messageEventsHeartbeatMs = + options.messageEventsHeartbeatMs ?? DEFAULT_MESSAGE_EVENTS_HEARTBEAT_MS + /** 活着的 SSE 连接。`server.close()` 会等长连接自然结束,必须先主动释放。 */ + const eventStreams = new Set() return new Promise((resolve, reject) => { const server: Server = http.createServer(async (req, res) => { const requestId = requestIdFor(req) @@ -1419,6 +1718,16 @@ export function startHttpServer( createAgentApiRoute(url.pathname, agentApi) || createWechatSendRoute(url.pathname, wechatSendApi) || createScheduledReportRoute(url.pathname, scheduledReportApi) || + createMessageEventsRoute( + url.pathname, + messageEventBroker, + (handle) => { + eventStreams.add(handle) + return () => eventStreams.delete(handle) + }, + messageEventsHeartbeatMs + ) || + createAgentTaskRoute(url.pathname, () => configuredAgentTaskInspector) || (url.pathname.startsWith(QUERY_ROUTE_PREFIX) ? createQueryRoute(url.pathname, queryApi) : undefined) || @@ -1503,6 +1812,9 @@ export function startHttpServer( } // HTTP keep-alive 或长连接会阻塞 server.close(),退出时主动断开全部连接。 const timer = setTimeout(finish, 1_500) + // SSE 是长连接:先按订阅句柄释放,再交给 server.close 收尾。 + for (const stream of eventStreams) stream.destroy() + eventStreams.clear() server.close(() => finish()) server.closeIdleConnections?.() server.closeAllConnections?.() diff --git a/src/main/index.ts b/src/main/index.ts index a3c1360..bff017f 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -82,9 +82,11 @@ import { KeyService as KeyServiceWin } from './key-service-win' import * as chat from './services/chat-service' import { apiServer, + setAgentTaskInspector, setLocalGroupStatsService, setLocalQueryApiService, - setLocalVoiceTranscriptSnapshotProvider + setLocalVoiceTranscriptSnapshotProvider, + setMessageEventBroker } from './http-server' import { skillResourceService } from './services/skill-resource-service' import { buildLocalApiCurlCommand, testLocalApiRequest } from './services/local-api-test-service' @@ -187,6 +189,14 @@ import { configureWechatLocalExitNotice, wechatLocalExitNoticeService } from './services/wechat-local-exit-notice-service' +import { MessageEventBroker } from './services/message-event-broker' +import { AgentTaskDispatcher } from './services/agent-task-dispatcher' +import { AgentTaskStore } from './services/agent-task-store' +import { + loadWorkBuddyAgentSettings, + loadWorkBuddyCredentials +} from './services/agent-task-config' +import { WorkBuddyAgentTaskProvider } from './services/workbuddy-agent-provider' /** 「微信内退群监控消息」覆盖的群聊数(开关卡片的范围说明用,不是覆盖率)。 */ function exitNoticeGroupCount(): number { @@ -691,6 +701,90 @@ let recallArchiveMonitor: RecallArchiveMonitor | null = null let recallProtectionGeneration = 0 let recallJournalTimer: NodeJS.Timeout | null = null let wcdbBootstrapPromise: Promise | null = null + +/** + * 会话 username → md5。 + * + * `messageRef` 的 `c` 字段是 **contact.md5**(见 `local-query-api-service` 的 + * `toQueryMessage(contact.md5, ...)`),而 MessageListener 只持有 username。 + * 事件层必须在这里换一次,否则发出去的 messageRef 无法被 + * `/api/v1/query/message-context` 反查到会话。 + */ +function resolveConversationMd5(sessionId: string): string | undefined { + try { + return chat.getChatDb()?.getWcdb4Client()?.md5(sessionId) || undefined + } catch { + return undefined + } +} + +let messageEventBroker: MessageEventBroker | null = null + +/** + * 实时事件代理(单例)。 + * + * 复用 MessageListener 已经产生的事件,**不监听数据库**——数据库监控只有 + * `startMonitor` 一处。DB 句柄通过 `chat.getChatDb()` 动态取得, + * 所以切账号 / 重连后不需要重建 broker,已有 SSE 订阅也不会被切断。 + */ +function ensureMessageEventBroker(): MessageEventBroker { + if (messageEventBroker) return messageEventBroker + messageEventBroker = new MessageEventBroker({ + resolveConversationId: resolveConversationMd5, + isDatabaseReady: () => chat.isReady(), + readMessages: async (sessionIdOrMd5, startTimeSec, endTimeSec, limit) => { + const client = chat.getChatDb()?.getWcdb4Client() + if (!client) return [] + return client.getMessagesAsync(sessionIdOrMd5, startTimeSec, endTimeSec, { limit }) + }, + resolveSessionId: (conversationId) => { + const client = chat.getChatDb()?.getWcdb4Client() + if (!client) return undefined + try { + return client.getSessions().find((session) => client.md5(session.username) === conversationId) + ?.username + } catch { + return undefined + } + } + }) + setMessageEventBroker(messageEventBroker) + return messageEventBroker +} + +let agentTaskDispatcher: AgentTaskDispatcher | null = null + +/** + * `/ai` 任务投递。 + * + * 配置默认 `enabled: false`;没有白名单会话时**不处理任何消息**。 + * 凭证只从环境变量读取,缺凭证时任务会被记成 `auth_failed`,不会静默跳过。 + */ +function ensureAgentTaskDispatcher(): AgentTaskDispatcher { + if (agentTaskDispatcher) return agentTaskDispatcher + const settings = loadWorkBuddyAgentSettings() + const store = new AgentTaskStore({ + filePath: path.join(app.getPath('userData'), 'agent-tasks.json') + }) + const dispatcher = new AgentTaskDispatcher({ + settings, + store, + provider: new WorkBuddyAgentTaskProvider({ + baseUrl: settings.baseUrl, + timeoutMs: settings.timeoutMs, + credentials: loadWorkBuddyCredentials() + }), + resolveConversationId: resolveConversationMd5 + }) + setAgentTaskInspector({ + list: (limit) => store.list(limit), + get: (id) => store.get(id) + }) + if (settings.enabled) dispatcher.start() + agentTaskDispatcher = dispatcher + return dispatcher +} + type ColdImageLoadItem = { priority: number sequence: number @@ -1113,6 +1207,10 @@ app.whenReady().then(async () => { if (isLegacyMigrationHelper) { } try { + // 事件代理必须在数据库初始化之前就存在:API server 可能先启动, + // 此时 SSE 应当能如实报告 database=unavailable,而不是把连接打回 503。 + ensureMessageEventBroker() + ensureAgentTaskDispatcher() const migration = isUserDataIsolated ? null : await runFirstLaunchMigration(appDataRoots) apiTokenStore.setAutomaticGenerationBlocked(migration?.tokenBlockReason) if (!migration) { @@ -1746,6 +1844,27 @@ app.whenReady().then(async () => { if (isLegacyMigrationHelper) { ` group=${message.isGroup} self=${message.isSelf}` + ` mentions=${message.mentionTargets.length}` ) + /* + * 实时事件是 Automation 之外的第二个消费者,两者互不依赖: + * broker 只搬运已经回读并规范化的消息,不触发自动化、不调 AI。 + * 放在 Automation 之前,保证后者异常不会让 SSE 订阅者漏事件。 + */ + ensureMessageEventBroker().publish(message) + try { + void agentTaskDispatcher?.handleMessage(message).catch((error) => { + console.warn( + `[AgentTask] handleMessage failed: ${ + error instanceof Error ? error.message : String(error) + }` + ) + }) + } catch (error) { + console.warn( + `[AgentTask] 未初始化,已跳过本次消息: ${ + error instanceof Error ? error.message : String(error) + }` + ) + } // Automation 自带 isSelf / cooldown / 同消息幂等三重闸,不会形成回复循环。 // 用 try 包住同步那一段:`getAutomationService()` 在未初始化时会抛, // 而 `.catch()` 只能接住异步拒绝 —— 漏了这层就会把异常抛进 MessageListener 的投递循环。 diff --git a/src/main/services/agent-task-config.ts b/src/main/services/agent-task-config.ts new file mode 100644 index 0000000..15e4093 --- /dev/null +++ b/src/main/services/agent-task-config.ts @@ -0,0 +1,139 @@ +import fs from 'node:fs' +import path from 'node:path' +import { app } from 'electron' + +/** + * WorkBuddy Agent 接入配置。 + * + * **默认禁用**:`enabled` 为 false 时 dispatcher 不读任何消息,也不会做在线检测。 + * + * 配置来源(只认这两种): + * 1. `/workbuddy-agent.json` —— 非敏感开关; + * 2. 环境变量 —— **只放凭证**,不落盘、不进 Git、不进日志。 + * + * 配置文件里出现的 `accessToken` / `clientSecret` 等字段会被忽略: + * 凭证的唯一合法入口是环境变量,避免用户把 secret 写进可同步的目录。 + */ + +export interface WorkBuddyAgentSettings { + enabled: boolean + /** 允许触发 `/ai` 的会话 md5 白名单;为空 = 不触发任何会话。 */ + allowedConversations: string[] + /** 命令前缀,默认 `/ai`。只接受「前缀 + 空白」或整条等于前缀。 */ + commandPrefix: string + baseUrl: string + timeoutMs: number + pollIntervalMs: number + /** 单任务最长等待回复时间(毫秒)。超时后状态置 `timeout`,不再轮询。 */ + maxPollDurationMs: number +} + +export interface WorkBuddyCredentials { + accessToken?: string + refreshToken?: string + clientId?: string + clientSecret?: string +} + +export const WORKBUDDY_AGENT_CONFIG_FILE = 'workbuddy-agent.json' + +export const DEFAULT_WORKBUDDY_AGENT_SETTINGS: WorkBuddyAgentSettings = Object.freeze({ + enabled: false, + allowedConversations: [], + commandPrefix: '/ai', + baseUrl: 'https://www.workbuddy.cn', + timeoutMs: 15_000, + pollIntervalMs: 3_000, + maxPollDurationMs: 120_000 +}) + +function asString(value: unknown, fallback: string): string { + return typeof value === 'string' && value.trim() ? value.trim() : fallback +} + +function asPositiveInt(value: unknown, fallback: number, max: number): number { + const parsed = typeof value === 'number' ? value : Number(value) + if (!Number.isFinite(parsed) || parsed <= 0) return fallback + return Math.min(Math.floor(parsed), max) +} + +function asConversationList(value: unknown): string[] { + if (!Array.isArray(value)) return [] + const ids: string[] = [] + for (const item of value) { + if (typeof item !== 'string') continue + const trimmed = item.trim() + if (!trimmed || ids.includes(trimmed)) continue + ids.push(trimmed) + } + return ids +} + +export function resolveWorkBuddyAgentConfigPath(userDataDir?: string): string { + const root = userDataDir || app.getPath('userData') + return path.join(root, WORKBUDDY_AGENT_CONFIG_FILE) +} + +/** + * 读取配置。文件不存在 / JSON 损坏 / 字段类型不对,一律回落到默认值(**禁用**), + * 不抛错 —— 一个坏配置文件不应该让主进程启动失败。 + */ +export function loadWorkBuddyAgentSettings( + userDataDir?: string, + defaults: WorkBuddyAgentSettings = DEFAULT_WORKBUDDY_AGENT_SETTINGS +): WorkBuddyAgentSettings { + let parsed: Record = {} + try { + const filePath = resolveWorkBuddyAgentConfigPath(userDataDir) + if (fs.existsSync(filePath)) { + const raw = fs.readFileSync(filePath, 'utf8') + const value = JSON.parse(raw) as unknown + if (value && typeof value === 'object' && !Array.isArray(value)) { + parsed = value as Record + } + } + } catch { + parsed = {} + } + + return { + enabled: parsed.enabled === true, + allowedConversations: asConversationList(parsed.allowedConversations), + commandPrefix: asString(parsed.commandPrefix, defaults.commandPrefix), + baseUrl: asString(parsed.baseUrl, defaults.baseUrl).replace(/\/+$/, ''), + timeoutMs: asPositiveInt(parsed.timeoutMs, defaults.timeoutMs, 60_000), + pollIntervalMs: asPositiveInt(parsed.pollIntervalMs, defaults.pollIntervalMs, 60_000), + maxPollDurationMs: asPositiveInt( + parsed.maxPollDurationMs, + defaults.maxPollDurationMs, + 30 * 60_000 + ) + } +} + +/** + * 只从环境变量读取凭证。 + * + * 返回值可能全部为空 —— 调用方必须把这种情况当作 `auth_missing` 处理, + * 而不是回落到某个内置默认值。 + */ +export function loadWorkBuddyCredentials( + env: NodeJS.ProcessEnv = process.env +): WorkBuddyCredentials { + const pick = (key: string): string | undefined => { + const value = env[key] + return typeof value === 'string' && value.trim() ? value.trim() : undefined + } + return { + accessToken: pick('TRACEMEMO_WORKBUDDY_ACCESS_TOKEN'), + refreshToken: pick('TRACEMEMO_WORKBUDDY_REFRESH_TOKEN'), + clientId: pick('TRACEMEMO_WORKBUDDY_CLIENT_ID'), + clientSecret: pick('TRACEMEMO_WORKBUDDY_CLIENT_SECRET') + } +} + +/** 是否具备可用的凭证组合(无需真的请求成功)。 */ +export function hasWorkBuddyCredentials(credentials: WorkBuddyCredentials): boolean { + if (credentials.accessToken) return true + return Boolean(credentials.refreshToken && credentials.clientId && credentials.clientSecret) +} diff --git a/src/main/services/agent-task-dispatcher.ts b/src/main/services/agent-task-dispatcher.ts new file mode 100644 index 0000000..d952631 --- /dev/null +++ b/src/main/services/agent-task-dispatcher.ts @@ -0,0 +1,292 @@ +import { randomUUID } from 'node:crypto' +import type { AgentTaskRecord, AgentTaskReply } from '../../shared/agent-task' +import type { NormalizedIncomingMessage } from './message-listener-service' +import { classifyProviderError, type AgentTaskProvider } from './agent-task-provider' +import type { AgentTaskStore } from './agent-task-store' +import type { WorkBuddyAgentSettings } from './agent-task-config' + +/** + * AgentTaskDispatcher —— `/ai` 命令闸门 + 任务投递 + 回复轮询。 + * + * **默认关闭,且只认白名单会话**。这是刻意的产品边界: + * 收到任意普通微信消息就唤醒 AI,等于把聊天记录变成无人监督的指令流。 + * + * ```text + * NormalizedIncomingMessage + * ├─ enabled? no → 丢弃 + * ├─ 白名单会话? no → 丢弃 + * ├─ 自己发的? yes → 丢弃(防自触发循环) + * ├─ 以 `/ai ` 开头? no → 丢弃 + * └─ triggerKey 已提交? yes → 丢弃(同一条消息只投一次) + * ↓ + * AgentTaskProvider.submitTask + * ↓ + * 状态持久化(submitting → submitted → completed / timeout / auth_failed ...) + * ``` + * + * **不做的事**:不执行 shell、不删文件、不推代码、不发微信。 + * 任务内容只是转交给远端助理的一段文本;本模块不解释、不放行任何高风险动作。 + */ + +const MAX_REPLIES_PER_TASK = 50 +const MAX_PROMPT_CHARS = 4000 + +export type AgentTaskDispatchOutcome = + | 'disabled' + | 'ignored' + | 'duplicate' + | 'submitted' + | 'offline' + | 'auth_failed' + | 'failed' + +export interface AgentTaskDispatcherOptions { + settings: WorkBuddyAgentSettings + store: AgentTaskStore + provider: AgentTaskProvider + resolveConversationId: (sessionId: string) => string | undefined + now?: () => number +} + +export class AgentTaskDispatcher { + private readonly now: () => number + private pollTimer: ReturnType | null = null + private polling = false + + constructor(private readonly options: AgentTaskDispatcherOptions) { + this.now = options.now ?? Date.now + } + + /** + * 处理一条已规范化的消息。 + * + * 前置判断全部同步完成(没有 await),保证同一批事件里重复投递的同一条消息 + * 会在第二次调用时直接命中去重表。 + */ + async handleMessage(message: NormalizedIncomingMessage): Promise { + const settings = this.options.settings + if (!settings.enabled) return 'disabled' + if (message.isSelf) return 'ignored' + + const prompt = matchCommand(message.content, settings.commandPrefix) + if (!prompt) return 'ignored' + + const conversationId = this.options.resolveConversationId(message.sessionId) + if (!conversationId) return 'ignored' + if (!settings.allowedConversations.includes(conversationId)) return 'ignored' + + await this.options.store.load() + + const triggerKey = `${message.sessionId}:${message.localId}` + if (this.options.store.findByTrigger(triggerKey)) return 'duplicate' + + const now = this.now() + const record: AgentTaskRecord = { + id: randomUUID(), + provider: this.options.provider.id, + conversationId, + triggerKey, + prompt: prompt.slice(0, MAX_PROMPT_CHARS), + status: 'submitting', + createdAt: now, + updatedAt: now, + replies: [] + } + this.options.store.upsert(record) + /* + * 必须在发请求前落盘。debounce 的写入不足以支撑「不重复提交」—— + * 崩溃窗口正是发生在这两步之间。 + */ + await this.options.store.flush() + + let online: boolean + try { + online = await this.options.provider.checkOnline() + } catch (error) { + return this.finishFailure(record, error, 'online_check') + } + if (!online) { + this.update(record, { + status: 'offline', + errorKind: 'offline', + errorMessage: 'WorkBuddy 本机助理不在线,未提交' + }) + await this.options.store.flush() + return 'offline' + } + + try { + const { messageId } = await this.options.provider.submitTask({ content: record.prompt }) + this.update(record, { + status: 'submitted', + submittedAt: this.now(), + externalMessageId: messageId, + lastReplyId: messageId, + errorKind: undefined, + errorMessage: undefined + }) + await this.options.store.flush() + return 'submitted' + } catch (error) { + return this.finishFailure(record, error, 'submit') + } + } + + /** 启动轮询。重复调用是幂等的。 */ + start(): void { + if (this.pollTimer) return + this.pollTimer = setInterval(() => { + void this.pollOnce() + }, this.options.settings.pollIntervalMs) + this.pollTimer.unref?.() + } + + stop(): void { + if (this.pollTimer) { + clearInterval(this.pollTimer) + this.pollTimer = null + } + } + + /** + * 拉取所有 `submitted` 任务的增量回复。 + * + * 返回本次处理的任务数(便于测试与诊断)。并发调用会被直接跳过。 + */ + async pollOnce(): Promise { + if (this.polling) return 0 + this.polling = true + try { + await this.options.store.load() + const pending = this.options.store + .list(200) + .filter((record) => record.status === 'submitted' && Boolean(record.externalMessageId)) + let processed = 0 + + for (const record of pending) { + const startedAt = record.submittedAt ?? record.createdAt + if (this.now() - startedAt > this.options.settings.maxPollDurationMs) { + this.update(record, { + status: 'timeout', + errorKind: 'timeout', + errorMessage: '等待 WorkBuddy 回复超时,已停止轮询' + }) + processed += 1 + continue + } + + try { + const replies = await this.options.provider.fetchReplies( + record.lastReplyId ?? String(record.externalMessageId) + ) + const merged = mergeReplies(record.replies, replies) + const assistant = merged.find((reply) => reply.role === 'assistant') + this.update(record, { + replies: merged, + lastReplyId: + merged.length > 0 ? merged[merged.length - 1].messageId : record.lastReplyId, + ...(assistant + ? { + status: 'completed' as const, + completedAt: this.now(), + errorKind: undefined, + errorMessage: undefined + } + : {}) + }) + processed += 1 + } catch (error) { + this.finishFailure(record, error, 'poll') + } + } + + if (processed > 0) await this.options.store.flush() + return processed + } finally { + this.polling = false + } + } + + private finishFailure( + record: AgentTaskRecord, + error: unknown, + stage: 'online_check' | 'submit' | 'poll' + ): AgentTaskDispatchOutcome { + const info = classifyProviderError(error) + const authFailure = info.kind === 'auth_expired' || info.kind === 'auth_missing' + + /* + * 投递阶段只要发生「可能已经到达远端」的失败(超时 / 可重试的 5xx / 网络错误), + * 就必须记成 ambiguous_submission —— 自动重试会造成重复任务。 + */ + const ambiguous = + stage === 'submit' && + (info.kind === 'timeout' || (info.kind === 'http_error' && info.retryable)) + + if (ambiguous) { + this.update(record, { + status: 'failed', + errorKind: 'ambiguous_submission', + errorMessage: `投递结果未知:${info.message};不会自动重试` + }) + void this.options.store.flush() + return 'failed' + } + + /* + * 轮询阶段的普通失败(5xx / 网络抖动)不应把任务判死: + * 远端可能仍在执行,下一轮继续拉取即可。只有鉴权失败才改状态。 + */ + if (stage === 'poll' && !authFailure) { + this.update(record, { + status: record.status, + errorKind: info.kind, + errorMessage: info.message + }) + void this.options.store.flush() + return 'failed' + } + + this.update(record, { + status: authFailure ? 'auth_failed' : 'failed', + errorKind: info.kind, + errorMessage: info.message + }) + void this.options.store.flush() + return authFailure ? 'auth_failed' : 'failed' + } + + private update(record: AgentTaskRecord, patch: Partial): void { + Object.assign(record, patch, { updatedAt: this.now() }) + if (record.errorKind === undefined) delete record.errorKind + if (record.errorMessage === undefined) delete record.errorMessage + this.options.store.upsert(record) + } +} + +/** + * 只接受「前缀 + 空白」或整条等于前缀。 + * + * `/ai写日报` 不触发:没有分隔符时无法区分命令与普通文本, + * 宁可漏触发也不要把正常聊天吞掉。 + */ +export function matchCommand(content: string | undefined, prefix: string): string | null { + const text = String(content ?? '').trim() + if (!text || !prefix) return null + if (!text.toLowerCase().startsWith(prefix.toLowerCase())) return null + const rest = text.slice(prefix.length) + if (rest && !/^\s/.test(rest)) return null + return rest.trim() +} + +function mergeReplies(existing: AgentTaskReply[], incoming: AgentTaskReply[]): AgentTaskReply[] { + if (incoming.length === 0) return existing + const seen = new Set(existing.map((reply) => reply.messageId)) + const merged = [...existing] + for (const reply of incoming) { + if (seen.has(reply.messageId)) continue + seen.add(reply.messageId) + merged.push(reply) + } + return merged.slice(-MAX_REPLIES_PER_TASK) +} diff --git a/src/main/services/agent-task-provider.ts b/src/main/services/agent-task-provider.ts new file mode 100644 index 0000000..abc7dc7 --- /dev/null +++ b/src/main/services/agent-task-provider.ts @@ -0,0 +1,61 @@ +import type { AgentTaskErrorKind, AgentTaskReply } from '../../shared/agent-task' + +/** + * AgentTaskProvider —— 可替换的任务投递接口。 + * + * 第一版实现是 WorkBuddy;接口刻意只包含三件事:在线检测、投递、拉回复。 + * 任何「执行 shell / 发微信 / 改仓库」的能力都**不属于**这个接口。 + */ + +export interface AgentTaskProviderRequestOptions { + signal?: AbortSignal +} + +export interface AgentTaskProvider { + readonly id: string + /** 远端助理是否在线。false 时调用方必须放弃提交,不能降级成「假装已提交」。 */ + checkOnline(options?: AgentTaskProviderRequestOptions): Promise + /** + * 投递一条指令,返回远端消息 id。 + * + * 该调用**不是幂等的**:调用方负责按 `triggerKey` 去重, + * 并在失败时区分「确定没提交」与「不确定是否提交」。 + */ + submitTask( + input: { content: string }, + options?: AgentTaskProviderRequestOptions + ): Promise<{ messageId: string }> + /** 按游标增量拉取回复。 */ + fetchReplies( + afterMessageId: string, + options?: AgentTaskProviderRequestOptions & { limit?: number } + ): Promise +} + +export class AgentTaskProviderError extends Error { + constructor( + readonly kind: AgentTaskErrorKind, + message: string, + readonly retryable = false, + readonly httpStatus?: number + ) { + super(message) + this.name = 'AgentTaskProviderError' + } +} + +/** 把任意异常归类成可持久化的错误类型;未知异常一律 `internal`,不猜。 */ +export function classifyProviderError(error: unknown): { + kind: AgentTaskErrorKind + message: string + retryable: boolean +} { + if (error instanceof AgentTaskProviderError) { + return { kind: error.kind, message: error.message, retryable: error.retryable } + } + return { + kind: 'internal', + message: error instanceof Error ? error.message : String(error), + retryable: false + } +} diff --git a/src/main/services/agent-task-store.ts b/src/main/services/agent-task-store.ts new file mode 100644 index 0000000..e6a7fd8 --- /dev/null +++ b/src/main/services/agent-task-store.ts @@ -0,0 +1,203 @@ +import fs from 'node:fs/promises' +import path from 'node:path' +import type { AgentTaskRecord, AgentTaskReply } from '../../shared/agent-task' + +/** + * Agent 任务状态持久化。 + * + * 目的只有一个:**重启后不重复提交**。 + * 因此写入顺序必须是「先落 `submitting`,再发请求」——崩溃发生时磁盘上留下的是 + * 「不确定是否已提交」,而不是一句「没提交过」。 + * + * 文件为 JSON 数组,权限 0600,位于 ``;最多保留 `maxRecords` 条最新记录。 + */ + +const DEFAULT_MAX_RECORDS = 200 +const DEFAULT_DEBOUNCE_MS = 200 + +export interface AgentTaskStoreOptions { + filePath: string + maxRecords?: number + debounceMs?: number + now?: () => number +} + +function isRecord(value: unknown): value is Record { + return Boolean(value) && typeof value === 'object' && !Array.isArray(value) +} + +function sanitizeRecord(value: unknown): AgentTaskRecord | null { + if (!isRecord(value)) return null + const id = typeof value.id === 'string' ? value.id : '' + const triggerKey = typeof value.triggerKey === 'string' ? value.triggerKey : '' + const conversationId = typeof value.conversationId === 'string' ? value.conversationId : '' + const prompt = typeof value.prompt === 'string' ? value.prompt : '' + const status = typeof value.status === 'string' ? value.status : '' + if (!id || !triggerKey || !conversationId || !status) return null + return { + id, + provider: typeof value.provider === 'string' ? value.provider : 'workbuddy', + conversationId, + triggerKey, + prompt, + status: status as AgentTaskRecord['status'], + createdAt: typeof value.createdAt === 'number' ? value.createdAt : 0, + updatedAt: typeof value.updatedAt === 'number' ? value.updatedAt : 0, + ...(typeof value.submittedAt === 'number' ? { submittedAt: value.submittedAt } : {}), + ...(typeof value.completedAt === 'number' ? { completedAt: value.completedAt } : {}), + ...(typeof value.externalMessageId === 'string' + ? { externalMessageId: value.externalMessageId } + : {}), + ...(typeof value.lastReplyId === 'string' ? { lastReplyId: value.lastReplyId } : {}), + ...(typeof value.errorKind === 'string' + ? { errorKind: value.errorKind as AgentTaskRecord['errorKind'] } + : {}), + ...(typeof value.errorMessage === 'string' ? { errorMessage: value.errorMessage } : {}), + replies: Array.isArray(value.replies) + ? value.replies + .filter(isRecord) + .map( + (reply): AgentTaskReply => ({ + messageId: typeof reply.messageId === 'string' ? reply.messageId : '', + role: + reply.role === 'assistant' || reply.role === 'user' + ? reply.role + : ('other' as const), + text: typeof reply.text === 'string' ? reply.text : '', + ...(typeof reply.createdAt === 'string' ? { createdAt: reply.createdAt } : {}) + }) + ) + .filter((reply) => Boolean(reply.messageId)) + : [] + } +} + +export class AgentTaskStore { + private readonly records = new Map() + private readonly maxRecords: number + private readonly debounceMs: number + private readonly now: () => number + private loaded: Promise | null = null + private persistTimer: ReturnType | null = null + private writeChain: Promise = Promise.resolve() + + constructor(private readonly options: AgentTaskStoreOptions) { + this.maxRecords = Math.max(1, options.maxRecords ?? DEFAULT_MAX_RECORDS) + this.debounceMs = Math.max(0, options.debounceMs ?? DEFAULT_DEBOUNCE_MS) + this.now = options.now ?? Date.now + } + + async load(): Promise { + if (!this.loaded) this.loaded = this.loadFromDisk() + return this.loaded + } + + get(id: string): AgentTaskRecord | undefined { + const record = this.records.get(id) + return record ? { ...record, replies: [...record.replies] } : undefined + } + + findByTrigger(triggerKey: string): AgentTaskRecord | undefined { + for (const record of this.records.values()) { + if (record.triggerKey === triggerKey) return { ...record, replies: [...record.replies] } + } + return undefined + } + + list(limit = 50): AgentTaskRecord[] { + return Array.from(this.records.values()) + .sort((a, b) => b.createdAt - a.createdAt) + .slice(0, Math.max(1, Math.min(limit, this.maxRecords))) + .map((record) => ({ ...record, replies: [...record.replies] })) + } + + upsert(record: AgentTaskRecord): void { + this.records.set(record.id, { ...record, replies: [...record.replies] }) + this.trim() + this.schedulePersist() + } + + /** 强制写盘(测试与退出前调用)。 */ + async flush(): Promise { + if (this.persistTimer) { + clearTimeout(this.persistTimer) + this.persistTimer = null + } + const snapshot = JSON.stringify(this.list(this.maxRecords), null, 2) + this.writeChain = this.writeChain.then(() => this.writeSnapshot(snapshot)) + await this.writeChain + } + + private async loadFromDisk(): Promise { + let raw = '' + try { + raw = await fs.readFile(this.options.filePath, 'utf8') + } catch { + return + } + let parsed: unknown + try { + parsed = JSON.parse(raw) + } catch { + return + } + if (!Array.isArray(parsed)) return + + for (const item of parsed) { + const record = sanitizeRecord(item) + if (!record) continue + /* + * 恢复语义:`submitting` 表示「请求可能已经发出,但进程没等到响应」。 + * 这种情况绝不能重投,也不能谎称失败在本地 —— 标记为不可重试的 + * `ambiguous_submission`,让人工/后续阶段决定。 + */ + if (record.status === 'submitting') { + record.status = 'failed' + record.errorKind = 'ambiguous_submission' + record.errorMessage = '进程在投递过程中退出,无法确认远端是否已接收;不会自动重试' + record.updatedAt = this.now() + } else if (record.status === 'queued') { + record.status = 'failed' + record.errorKind = 'internal' + record.errorMessage = '进程在投递前退出,未发送' + record.updatedAt = this.now() + } + this.records.set(record.id, record) + } + this.trim() + } + + private trim(): void { + if (this.records.size <= this.maxRecords) return + const ordered = Array.from(this.records.values()).sort((a, b) => a.createdAt - b.createdAt) + const overflow = this.records.size - this.maxRecords + for (let index = 0; index < overflow; index += 1) { + this.records.delete(ordered[index].id) + } + } + + private schedulePersist(): void { + if (this.persistTimer) return + this.persistTimer = setTimeout(() => { + this.persistTimer = null + const snapshot = JSON.stringify(this.list(this.maxRecords), null, 2) + this.writeChain = this.writeChain.then(() => this.writeSnapshot(snapshot)) + }, this.debounceMs) + this.persistTimer.unref?.() + } + + private async writeSnapshot(snapshot: string): Promise { + const target = this.options.filePath + const temp = `${target}.tmp` + try { + await fs.mkdir(path.dirname(target), { recursive: true }) + await fs.writeFile(temp, snapshot, { encoding: 'utf8', mode: 0o600 }) + await fs.rename(temp, target) + await fs.chmod(target, 0o600).catch(() => undefined) + } catch (error) { + console.warn( + `[AgentTaskStore] persist failed: ${error instanceof Error ? error.message : String(error)}` + ) + } + } +} diff --git a/src/main/services/message-event-broker.ts b/src/main/services/message-event-broker.ts new file mode 100644 index 0000000..941464e --- /dev/null +++ b/src/main/services/message-event-broker.ts @@ -0,0 +1,571 @@ +import { createHash, randomUUID } from 'node:crypto' +import { encodeMessageRef } from '../../shared/local-query-api' +import { + normalizeIncomingMessage, + type NormalizedIncomingMessage +} from './message-listener-service' +import type { Wcdb4Message } from '../wcdb4-client' + +/** + * MessageEventBroker —— 实时消息事件的唯一分发层。 + * + * ```text + * MessageListenerService.onMessage + * ↓ NormalizedIncomingMessage + * MessageEventBroker + * ├─ 事件 ID / 规范化 / 有界环形缓冲 / 每订阅者游标 + * ├─ 已产生事件的重放(replay) + * └─ 数据库消息回补(db_backfill,独立标记) + * ``` + * + * **刻意不做的事**:不监听数据库(监听只有 `MessageListenerService` 一套)、 + * 不触发自动化、不调用 AI、不发送微信消息。本模块只负责「把已经产生的事件可靠地交出去」。 + * + * **两类补偿必须可区分**: + * - `replay`:事件曾经真实产生过,仍在本进程的环形缓冲里; + * - `db_backfill`:缓冲已经覆盖不到,只能从数据库按时间窗重读。它可能包含 + * 从未产生过事件的普通消息,也可能因为窗口/条数上限而不完整。 + * + * **单位契约**:`timestamp` 是 epoch **秒**(与 WCDB `create_time`、`getMessagesAsync` 一致); + * 缓冲 TTL / 去重 TTL 是毫秒。跨这条边界只允许在本文件里换算一次。 + */ + +/** 单条事件的文本上限。超出时显式标记 `textTruncated`,不静默截断。 */ +const DEFAULT_MAX_TEXT_CHARS = 4000 +/** 环形缓冲默认容量(条)。 */ +const DEFAULT_BUFFER_SIZE = 500 +/** 环形缓冲默认存活时间(毫秒)。 */ +const DEFAULT_BUFFER_TTL_MS = 5 * 60 * 1000 +/** 发布去重表默认存活时间(毫秒)。 */ +const DEFAULT_SEEN_TTL_MS = 10 * 60 * 1000 +/** 发布去重表默认容量。 */ +const DEFAULT_SEEN_MAX_ENTRIES = 5000 +/** 单订阅者「已投递 ID」记忆容量,用于避免回补与实时重叠时重复投递。 */ +const DEFAULT_SUBSCRIBER_SEEN_MAX = 2000 +/** 数据库回补的时间窗默认值(秒)。 */ +const DEFAULT_BACKFILL_LOOKBACK_SEC = 300 +/** 单会话回补条数默认上限。 */ +const DEFAULT_BACKFILL_LIMIT = 100 +/** 单次回补最多涉及的会话数。 */ +const DEFAULT_BACKFILL_MAX_CONVERSATIONS = 20 +/** 单个进程允许的并发 SSE 订阅数。 */ +const DEFAULT_MAX_SUBSCRIBERS = 32 + +export type MessageEventOrigin = 'live' | 'replay' | 'db_backfill' + +export interface MessageEventRecord { + /** 确定性 ID:同一会话 + 同一条消息永远得到同一个值(跨进程稳定)。 */ + id: string + /** 进程内单调序号,用于 SSE `Last-Event-ID` 的缓冲定位。 */ + seq: number + /** **会话 md5**,与 `messageRef` 的 `c` 字段同口径(不是微信 username)。 */ + conversationId: string + messageRef: string + /** epoch 秒。 */ + timestamp: number + messageType: number + isSelf: boolean + isGroup: boolean + senderId?: string + senderNickname?: string + text?: string + textTruncated?: boolean + mentionTargets: string[] +} + +export interface MessageBrokerStatus { + database: 'ready' | 'unavailable' + subscribers: number + buffered: number + oldestSeq: number | null + newestSeq: number | null +} + +export interface MessageGap { + reason: 'buffer_overflow' | 'invalid_cursor' | 'cursor_from_previous_process' + requestedLastEventId: string + oldestSeq: number | null + newestSeq: number | null + /** 是否触发了数据库回补。为 false 时必须让客户端知道这段空档没有补齐。 */ + backfill: + | 'scheduled' + | 'skipped_no_conversation_filter' + | 'skipped_database_unavailable' + | 'skipped_no_reader' + | 'disabled' +} + +export interface MessageEventSink { + onStatus(status: MessageBrokerStatus & { subscriptionId: string }): void + onEvent(event: MessageEventRecord, origin: MessageEventOrigin): void + onGap(gap: MessageGap): void +} + +export interface MessageSubscribeOptions { + /** 会话 md5 白名单;空/省略 = 全部会话(此时无法做有界回补)。 */ + conversationIds?: string[] + /** 上一次收到的 SSE id(`Last-Event-ID`)。 */ + lastEventId?: string + /** 是否允许在缓冲覆盖不到时从数据库回补。默认 true。 */ + backfill?: boolean +} + +export interface MessageSubscription { + readonly id: string + /** 该订阅已经投递到的最新序号(诊断用)。 */ + readonly lastDeliveredSeq: number + close(): void +} + +export interface MessageEventBrokerOptions { + /** + * username → 会话 md5。 + * + * 事件必须携带与 `encodeMessageRef()` 同口径的 conversationId(md5), + * 否则 `/query/message-context` 无法反查会话。返回 undefined 表示当前无法映射, + * 该消息会被计入 `unmapped` 并**不投递**(避免发出不可用的 messageRef)。 + */ + resolveConversationId: (sessionId: string) => string | undefined + /** 数据库当前是否可用。用于 status 事件,不做连接管理。 */ + isDatabaseReady?: () => boolean + /** 回补读取器。参数与 `getMessagesAsync(usernameOrMd5, startSec, endSec, {limit})` 一致。 */ + readMessages?: ( + sessionIdOrMd5: string, + startTimeSec: number, + endTimeSec: number, + limit: number + ) => Promise + /** md5 → username,仅回补时用于还原 `isGroup` 与 sender 语义。 */ + resolveSessionId?: (conversationId: string) => string | undefined + bufferSize?: number + bufferTtlMs?: number + seenTtlMs?: number + seenMaxEntries?: number + backfillLookbackSec?: number + backfillLimit?: number + backfillMaxConversations?: number + maxSubscribers?: number + maxTextChars?: number + now?: () => number +} + +interface SubscriberState { + id: string + conversationIds: Set | null + sink: MessageEventSink + deliveredIds: Map + lastDeliveredSeq: number + delivered: number + closed: boolean + backfillEnabled: boolean +} + +export class MessageEventBroker { + private readonly subscribers = new Map() + private buffer: MessageEventRecord[] = [] + /** 事件 ID → 序号。只保留仍在缓冲里的条目。 */ + private readonly index = new Map() + private nextSeq = 1 + private disposed = false + + private readonly seen = new Map() + private readonly bufferSize: number + private readonly bufferTtlMs: number + private readonly seenTtlMs: number + private readonly seenMaxEntries: number + private readonly backfillLookbackSec: number + private readonly backfillLimit: number + private readonly backfillMaxConversations: number + private readonly maxSubscribers: number + private readonly maxTextChars: number + private readonly now: () => number + + private counters = { + published: 0, + duplicates: 0, + unmapped: 0, + backfilled: 0, + gaps: 0, + rejected: 0 + } + + constructor(private readonly options: MessageEventBrokerOptions) { + this.bufferSize = Math.max(1, options.bufferSize ?? DEFAULT_BUFFER_SIZE) + this.bufferTtlMs = Math.max(1000, options.bufferTtlMs ?? DEFAULT_BUFFER_TTL_MS) + this.seenTtlMs = Math.max(1000, options.seenTtlMs ?? DEFAULT_SEEN_TTL_MS) + this.seenMaxEntries = Math.max(1, options.seenMaxEntries ?? DEFAULT_SEEN_MAX_ENTRIES) + this.backfillLookbackSec = Math.max( + 1, + options.backfillLookbackSec ?? DEFAULT_BACKFILL_LOOKBACK_SEC + ) + this.backfillLimit = Math.max(1, options.backfillLimit ?? DEFAULT_BACKFILL_LIMIT) + this.backfillMaxConversations = Math.max( + 1, + options.backfillMaxConversations ?? DEFAULT_BACKFILL_MAX_CONVERSATIONS + ) + this.maxSubscribers = Math.max(1, options.maxSubscribers ?? DEFAULT_MAX_SUBSCRIBERS) + this.maxTextChars = Math.max(64, options.maxTextChars ?? DEFAULT_MAX_TEXT_CHARS) + this.now = options.now ?? Date.now + } + + /** + * 发布一条已经由 MessageListener 回读并规范化的消息。 + * + * 返回 null 表示消息无法形成可用事件(会话未映射 / messageRef 构造失败), + * 或命中去重表(同一条消息被重复回读)。 + */ + publish(message: NormalizedIncomingMessage): MessageEventRecord | null { + if (this.disposed) return null + const record = this.toRecord(message) + if (!record) return null + + this.evictSeen(this.now()) + if (this.seen.has(record.id)) { + this.counters.duplicates += 1 + return null + } + + this.seen.set(record.id, this.now()) + this.trimSeen() + + record.seq = this.nextSeq + this.nextSeq += 1 + + this.buffer.push(record) + this.index.set(record.id, record.seq) + this.trimBuffer() + + this.counters.published += 1 + this.deliverLive(record) + return record + } + + /** + * 订阅消息事件。 + * + * 订阅会立刻收到一条 `status`;随后按 `lastEventId` 决定重放还是回补。 + * 返回的句柄必须由调用方在连接关闭时 `close()`,否则会占用订阅配额。 + */ + subscribe(options: MessageSubscribeOptions, sink: MessageEventSink): MessageSubscription { + if (this.subscribers.size >= this.maxSubscribers) { + throw new Error('消息事件订阅数已达上限') + } + + const state: SubscriberState = { + id: randomUUID(), + conversationIds: + options.conversationIds && options.conversationIds.length > 0 + ? new Set(options.conversationIds) + : null, + sink, + deliveredIds: new Map(), + lastDeliveredSeq: 0, + delivered: 0, + closed: false, + backfillEnabled: options.backfill !== false + } + this.subscribers.set(state.id, state) + sink.onStatus({ ...this.status(), subscriptionId: state.id }) + void this.resume(state, options.lastEventId) + + return { + id: state.id, + get lastDeliveredSeq(): number { + return state.lastDeliveredSeq + }, + close: () => { + state.closed = true + this.subscribers.delete(state.id) + } + } + } + + status(): MessageBrokerStatus { + return { + database: this.options.isDatabaseReady?.() === false ? 'unavailable' : 'ready', + subscribers: this.subscribers.size, + buffered: this.buffer.length, + oldestSeq: this.buffer[0]?.seq ?? null, + newestSeq: this.buffer[this.buffer.length - 1]?.seq ?? null + } + } + + stats(): typeof this.counters & MessageBrokerStatus { + return { ...this.counters, ...this.status() } + } + + dispose(): void { + this.disposed = true + for (const state of this.subscribers.values()) state.closed = true + this.subscribers.clear() + this.buffer = [] + this.index.clear() + this.seen.clear() + } + + private async resume(state: SubscriberState, lastEventId?: string): Promise { + const raw = typeof lastEventId === 'string' ? lastEventId.trim() : '' + // 没带游标 = 首次订阅,只接实时事件,不需要 gap。 + if (!raw) return + if (state.closed) return + + const oldest = this.buffer[0]?.seq ?? null + const newest = this.buffer[this.buffer.length - 1]?.seq ?? null + /** 本进程已经分配出去的最大序号(含未进缓冲的回补事件)。 */ + const maxAssigned = this.nextSeq - 1 + + const lastSeq = parseLastEventId(raw) + /* + * 带了游标但解析不了:不能当成「首次订阅」静默跳过 —— + * 那等于把客户端明确声明的断点吞掉。 + */ + if (lastSeq === null) { + await this.emitGap(state, raw, 'invalid_cursor', oldest, newest) + return + } + + /* + * 序号只在**本进程内**单调。客户端如果拿着上一个进程的游标(重启后 + * 序号会从 1 重新开始),它可能大于本进程已分配的任何序号 —— 这时 + * 既不能当成「已经收到最新」,也不能假装能重放,只能走 gap。 + */ + if (lastSeq > maxAssigned) { + await this.emitGap(state, raw, 'cursor_from_previous_process', oldest, newest) + return + } + + /* + * 只有「游标落在缓冲区间内」或「游标正好是本进程最后一个被淘汰的序号」 + * 才能保证重放完整。`lastSeq < oldest - 1` 说明中间已经有事件被淘汰, + * 必须显式报 gap,不能假装重放是连续的。 + */ + if (oldest !== null && lastSeq >= oldest - 1) { + for (const event of this.buffer) { + if (state.closed) return + if (event.seq <= lastSeq) continue + this.deliver(state, event, 'replay') + } + return + } + + /* + * 缓冲为空但有本进程分配过的序号:可能只发生过回补事件(不进缓冲), + * 也可能事件已按 TTL 全部淘汰。前者没有漏消息,后者必须报 gap。 + */ + if (oldest === null && lastSeq === maxAssigned) return + + await this.emitGap(state, raw, 'buffer_overflow', oldest, newest) + } + + private async emitGap( + state: SubscriberState, + lastEventId: string, + reason: MessageGap['reason'], + oldest: number | null, + newest: number | null + ): Promise { + this.counters.gaps += 1 + /* + * 先发 gap,再回补。反过来会让客户端先收到一批「来源不明」的消息, + * 然后才被告知中间有断档 —— 顺序本身就是语义的一部分。 + */ + const plan = this.backfillPlan(state) + state.sink.onGap({ + reason, + requestedLastEventId: String(lastEventId), + oldestSeq: oldest, + newestSeq: newest, + backfill: plan + }) + if (plan === 'scheduled') await this.runBackfill(state) + } + + /** + * 有界数据库回补的前置判定。 + * + * 边界(全部不可协商): + * - 只回补订阅时显式指定的会话;「全部会话」无法做有界回补; + * - 时间窗 ≤ `backfillLookbackSec`,单会话 ≤ `backfillLimit` 条; + * - 会话数 ≤ `backfillMaxConversations`; + * - 数据库不可用 / 没有读取器时明确跳过,不伪造事件。 + */ + private backfillPlan(state: SubscriberState): MessageGap['backfill'] { + if (!state.backfillEnabled) return 'disabled' + if (!state.conversationIds || state.conversationIds.size === 0) { + return 'skipped_no_conversation_filter' + } + if (!this.options.readMessages) return 'skipped_no_reader' + if (this.options.isDatabaseReady?.() === false) return 'skipped_database_unavailable' + return 'scheduled' + } + + /** 执行已经通过 `backfillPlan` 判定的回补。 */ + private async runBackfill(state: SubscriberState): Promise { + if (!state.conversationIds || !this.options.readMessages) return + + const nowMs = this.now() + const endSec = Math.floor(nowMs / 1000) + const startSec = endSec - this.backfillLookbackSec + const conversations = Array.from(state.conversationIds).slice(0, this.backfillMaxConversations) + + for (const conversationId of conversations) { + if (state.closed) return + const sessionId = this.options.resolveSessionId?.(conversationId) ?? conversationId + let rows: Wcdb4Message[] + try { + rows = await this.options.readMessages(sessionId, startSec, endSec, this.backfillLimit) + } catch (error) { + console.warn( + `[MessageEventBroker] backfill read failed: ${ + error instanceof Error ? error.message : String(error) + }` + ) + continue + } + for (const row of rows) { + if (state.closed) return + const normalized = normalizeIncomingMessage(sessionId, row) + if (!normalized) continue + const record = this.toRecord(normalized) + if (!record) continue + // 回补事件不进入环形缓冲:它是补偿,不是「本进程产生过」的事实。 + record.seq = this.nextSeq + this.nextSeq += 1 + this.counters.backfilled += 1 + this.deliver(state, record, 'db_backfill') + } + } + } + + private deliverLive(record: MessageEventRecord): void { + for (const state of this.subscribers.values()) { + if (state.closed) continue + if (state.conversationIds && !state.conversationIds.has(record.conversationId)) continue + this.deliver(state, record, 'live') + } + } + + private deliver( + state: SubscriberState, + record: MessageEventRecord, + origin: MessageEventOrigin + ): void { + if (state.closed) return + if (state.conversationIds && !state.conversationIds.has(record.conversationId)) return + if (state.deliveredIds.has(record.id)) return + + state.deliveredIds.set(record.id, this.now()) + this.trimSubscriberSeen(state) + state.lastDeliveredSeq = record.seq + state.delivered += 1 + try { + state.sink.onEvent(record, origin) + } catch (error) { + console.warn( + `[MessageEventBroker] subscriber sink threw: ${ + error instanceof Error ? error.message : String(error) + }` + ) + } + } + + private toRecord(message: NormalizedIncomingMessage): MessageEventRecord | null { + const conversationId = this.options.resolveConversationId(message.sessionId) + if (!conversationId) { + this.counters.unmapped += 1 + return null + } + let messageRef: string + try { + messageRef = encodeMessageRef(conversationId, message.localId) + } catch (error) { + this.counters.rejected += 1 + console.warn( + `[MessageEventBroker] messageRef rejected: ${ + error instanceof Error ? error.message : String(error) + }` + ) + return null + } + + const rawText = message.content ?? '' + const truncated = rawText.length > this.maxTextChars + return { + id: eventIdFor(conversationId, message.localId), + seq: 0, + conversationId, + messageRef, + timestamp: message.createTime, + messageType: message.messageType, + isSelf: message.isSelf, + isGroup: message.isGroup, + ...(message.senderId ? { senderId: message.senderId } : {}), + ...(message.senderNickname ? { senderNickname: message.senderNickname } : {}), + ...(rawText ? { text: truncated ? rawText.slice(0, this.maxTextChars) : rawText } : {}), + ...(truncated ? { textTruncated: true } : {}), + mentionTargets: message.mentionTargets + } + } + + private trimBuffer(): void { + const cutoff = this.now() - this.bufferTtlMs + while (this.buffer.length > 0) { + const oldest = this.buffer[0] + const expired = oldest.timestamp * 1000 < cutoff + if (this.buffer.length <= this.bufferSize && !expired) break + this.buffer.shift() + if (this.index.get(oldest.id) === oldest.seq) this.index.delete(oldest.id) + } + } + + private evictSeen(now: number): void { + for (const [id, seenAt] of this.seen) { + if (now - seenAt <= this.seenTtlMs) break + this.seen.delete(id) + } + } + + private trimSeen(): void { + if (this.seen.size <= this.seenMaxEntries) return + const overflow = this.seen.size - this.seenMaxEntries + let removed = 0 + for (const id of this.seen.keys()) { + this.seen.delete(id) + removed += 1 + if (removed >= overflow) break + } + } + + private trimSubscriberSeen(state: SubscriberState): void { + if (state.deliveredIds.size <= DEFAULT_SUBSCRIBER_SEEN_MAX) return + const overflow = state.deliveredIds.size - DEFAULT_SUBSCRIBER_SEEN_MAX + let removed = 0 + for (const id of state.deliveredIds.keys()) { + state.deliveredIds.delete(id) + removed += 1 + if (removed >= overflow) break + } + } +} + +/** 同一会话 + 同一条消息的确定性事件 ID。 */ +export function eventIdFor(conversationId: string, localId: string): string { + return `evt_${createHash('sha256') + .update(`${conversationId}\u0000${localId}`, 'utf8') + .digest('hex') + .slice(0, 24)}` +} + +/** + * 解析 SSE `Last-Event-ID`。 + * + * 只接受纯数字序号;其它形态(含上一版本客户端可能发来的任意字符串) + * 一律当成「没有游标」而不是猜一个位置 —— 猜错会导致静默漏消息。 + */ +export function parseLastEventId(value: unknown): number | null { + if (typeof value !== 'string' || !value.trim()) return null + const trimmed = value.trim() + if (!/^\d{1,15}$/.test(trimmed)) return null + const parsed = Number(trimmed) + return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null +} diff --git a/src/main/services/message-listener-service.ts b/src/main/services/message-listener-service.ts index d67b019..046d168 100644 --- a/src/main/services/message-listener-service.ts +++ b/src/main/services/message-listener-service.ts @@ -101,6 +101,8 @@ export interface MessageListenerStats { delivered: number /** 因 dedup 被丢弃的重复投递数。 */ deduped: number + /** 单个会话回读失败的次数(不中断同批其他会话)。 */ + failedReadbacks: number } export interface MessageListenerOptions { @@ -186,6 +188,43 @@ export function decodeSourcePayload(value: unknown): string | undefined { } } +/** + * 把 WCDB 行规范化为克制的 DTO。返回 null 表示这条行缺关键标识,无法投递。 + * + * 纯函数,**唯一**的规范化实现:实时回读与数据库回补都走这里, + * 避免两条路径对同一条消息给出不同字段。 + */ +export function normalizeIncomingMessage( + sessionUsername: string, + message: Wcdb4Message +): NormalizedIncomingMessage | null { + const localId = message.mesLocalID === undefined ? '' : String(message.mesLocalID) + if (!localId) return null + + const createTime = Number(message.msgCreateTime) || 0 + if (!createTime) return null + + const raw = (message.raw ?? {}) as Record + const source = decodeSourcePayload(raw.source) + const senderId = message.sender ? String(message.sender) : undefined + + return { + sessionId: sessionUsername, + localId, + serverId: message.serverId ? String(message.serverId) : undefined, + createTime, + messageType: Number(message.messageType) || 0, + // `mesDes === 0` 是自己发送。不用昵称 / sender 文本 / content / username 前缀判断。 + isSelf: Number(message.mesDes) === 0, + senderId, + senderNickname: message.senderNickname ? String(message.senderNickname) : undefined, + content: message.msgContent ? String(message.msgContent) : undefined, + source, + isGroup: sessionUsername.endsWith('@chatroom'), + mentionTargets: extractMentionTargets(source) + } +} + /** * 实时消息监听。 * @@ -233,7 +272,8 @@ export class MessageListenerService { coalescedEvents: 0, readbacks: 0, delivered: 0, - deduped: 0 + deduped: 0, + failedReadbacks: 0 } constructor( @@ -323,12 +363,27 @@ export class MessageListenerService { try { let delivered = 0 let sessions = 0 + let failures = 0 if (preciseSessions.length > 0) { for (const sessionId of preciseSessions) { if (this.disposed) return - delivered += await this.readbackSession(sessionId) - sessions += 1 + try { + delivered += await this.readbackSession(sessionId) + sessions += 1 + } catch (error) { + /* + * 单个会话读失败不能中断整批:pending 已在批次开始时清空, + * 跳出循环会让本批其余会话静默丢失。 + */ + failures += 1 + this.counters.failedReadbacks += 1 + console.warn( + `[MessageListener] session readback failed: ${ + error instanceof Error ? error.message : String(error) + }` + ) + } } } else { // legacy:旧 runtime 的 payload 不带会话,只能回读「最近活跃会话」。 @@ -338,11 +393,12 @@ export class MessageListenerService { sessions = 1 } - if (delivered > 0) { + if (delivered > 0 || failures > 0) { // 日志只记录协议版本、数量与耗时 —— **不含** wxid / 群名 / 昵称 / 正文 / source / sessionId。 console.log( `[MessageListener] protocol=${preciseSessions.length > 0 ? 'v2' : 'v1'}` + - ` sessions=${sessions} delivered=${delivered} readbackMs=${Date.now() - startedAt}` + + ` sessions=${sessions} delivered=${delivered} failures=${failures}` + + ` readbackMs=${Date.now() - startedAt}` + ` events=${this.counters.nativeEvents} coalesced=${this.counters.coalescedEvents}` ) } @@ -411,31 +467,7 @@ export class MessageListenerService { sessionUsername: string, message: Wcdb4Message ): NormalizedIncomingMessage | null { - const localId = message.mesLocalID === undefined ? '' : String(message.mesLocalID) - if (!localId) return null - - const createTime = Number(message.msgCreateTime) || 0 - if (!createTime) return null - - const raw = (message.raw ?? {}) as Record - const source = decodeSourcePayload(raw.source) - const senderId = message.sender ? String(message.sender) : undefined - - return { - sessionId: sessionUsername, - localId, - serverId: message.serverId ? String(message.serverId) : undefined, - createTime, - messageType: Number(message.messageType) || 0, - // `mesDes === 0` 是自己发送。不用昵称 / sender 文本 / content / username 前缀判断。 - isSelf: Number(message.mesDes) === 0, - senderId, - senderNickname: message.senderNickname ? String(message.senderNickname) : undefined, - content: message.msgContent ? String(message.msgContent) : undefined, - source, - isGroup: sessionUsername.endsWith('@chatroom'), - mentionTargets: extractMentionTargets(source) - } + return normalizeIncomingMessage(sessionUsername, message) } /** 登记并返回「是否是第一次见到」。同时做 TTL + 容量淘汰。 */ diff --git a/src/main/services/workbuddy-agent-provider.ts b/src/main/services/workbuddy-agent-provider.ts new file mode 100644 index 0000000..a7358da --- /dev/null +++ b/src/main/services/workbuddy-agent-provider.ts @@ -0,0 +1,367 @@ +import type { AgentTaskReply, AgentTaskReplyRole } from '../../shared/agent-task' +import { + AgentTaskProvider, + AgentTaskProviderError, + type AgentTaskProviderRequestOptions +} from './agent-task-provider' +import type { WorkBuddyCredentials } from './agent-task-config' + +/** + * WorkBuddy Local Assistant 适配器。 + * + * 契约来源(未在本仓库实测的部分会在下方逐条标注): + * - `GET /openapi/v2/localassistant` → `data.online` + * - `POST /openapi/v2/localassistant/message` → `data.message_id` + * - `GET /openapi/v2/localassistant/message?message_id=...` → 增量回复 + * - `POST /openapi/v2/token` → refresh + * + * **未实测**: + * 1. assistant 回复是否一定出现在 `message_id` 之后、是否保证只出现一次; + * 2. 真实账号下 refresh_token 是否轮换; + * 3. `content[]` 里除 `text` 之外的实际片段类型。 + * 因此第一版把「看到任意一条 assistant 回复」当作任务完成,而不是猜更细的状态机。 + * + * **安全边界**: + * - 凭证只从构造参数来(由 `loadWorkBuddyCredentials()` 读环境变量),本文件零硬编码; + * - 错误信息里只放 HTTP 状态与业务 `code`,不回显请求头或 token。 + */ + +const LOCAL_ASSISTANT_PATH = '/openapi/v2/localassistant' +const LOCAL_ASSISTANT_MESSAGE_PATH = '/openapi/v2/localassistant/message' +const TOKEN_PATH = '/openapi/v2/token' +/** 提前 60 秒刷新,避免边界上刚好过期。 */ +const TOKEN_EXPIRY_SKEW_MS = 60_000 + +interface WorkBuddyEnvelope { + code?: number + msg?: string + request_id?: string + data?: T +} + +export interface WorkBuddyProviderOptions { + baseUrl: string + timeoutMs: number + credentials: WorkBuddyCredentials + fetchImpl?: typeof fetch + now?: () => number +} + +export class WorkBuddyAccessTokenSource { + private cached: { token: string; expiresAt: number } | null = null + private readonly fetchImpl: typeof fetch + private readonly now: () => number + + constructor(private readonly options: WorkBuddyProviderOptions) { + this.fetchImpl = options.fetchImpl ?? fetch + this.now = options.now ?? Date.now + } + + /** 丢弃缓存。收到 401 时由 provider 调用,下一次会强制 refresh。 */ + invalidate(): void { + this.cached = null + } + + async getAccessToken(forceRefresh = false): Promise { + const credentials = this.options.credentials + + if (!forceRefresh && this.cached && this.now() < this.cached.expiresAt) { + return this.cached.token + } + + if (!forceRefresh && credentials.accessToken) { + // 静态 token 没有过期信息:先用,遇到 401 再走 refresh。 + this.cached = { token: credentials.accessToken, expiresAt: Number.POSITIVE_INFINITY } + return credentials.accessToken + } + + if (credentials.refreshToken && credentials.clientId && credentials.clientSecret) { + const token = await this.refresh(credentials) + this.cached = { + token: token.accessToken, + expiresAt: this.now() + Math.max(60, token.expiresIn) * 1000 - TOKEN_EXPIRY_SKEW_MS + } + return token.accessToken + } + + if (credentials.accessToken) { + throw new AgentTaskProviderError( + 'auth_expired', + 'WorkBuddy access_token 已失效,且没有配置 refresh_token', + false, + 401 + ) + } + throw new AgentTaskProviderError('auth_missing', '未配置 WorkBuddy 访问凭证', false) + } + + private async refresh( + credentials: WorkBuddyCredentials + ): Promise<{ accessToken: string; expiresIn: number }> { + const body = new URLSearchParams({ + grant_type: 'refresh_token', + refresh_token: String(credentials.refreshToken), + client_id: String(credentials.clientId), + client_secret: String(credentials.clientSecret) + }) + + const controller = new AbortController() + const timer = setTimeout(() => controller.abort(), this.options.timeoutMs) + let response: Response + try { + response = await this.fetchImpl(`${this.options.baseUrl}${TOKEN_PATH}`, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body, + signal: controller.signal + }) + } catch (error) { + throw classifyTokenFailure(error) + } finally { + clearTimeout(timer) + } + + const envelope = await readEnvelope(response) + if (!response.ok || (typeof envelope.code === 'number' && envelope.code !== 0)) { + throw new AgentTaskProviderError( + 'auth_expired', + `WorkBuddy 凭证刷新失败(HTTP ${response.status}${envelope.msg ? `:${envelope.msg}` : ''})`, + false, + response.status + ) + } + + const data = envelope.data as { access_token?: unknown; expires_in?: unknown } | undefined + if (!data || typeof data.access_token !== 'string' || !data.access_token) { + throw new AgentTaskProviderError('invalid_response', 'WorkBuddy 刷新响应缺少 access_token') + } + return { + accessToken: data.access_token, + expiresIn: typeof data.expires_in === 'number' ? data.expires_in : 3600 + } + } +} + +export class WorkBuddyAgentTaskProvider implements AgentTaskProvider { + readonly id = 'workbuddy' + private readonly tokenSource: WorkBuddyAccessTokenSource + private readonly fetchImpl: typeof fetch + + constructor(private readonly options: WorkBuddyProviderOptions) { + this.tokenSource = new WorkBuddyAccessTokenSource(options) + this.fetchImpl = options.fetchImpl ?? fetch + } + + async checkOnline(options: AgentTaskProviderRequestOptions = {}): Promise { + const data = await this.request<{ online?: unknown }>( + 'GET', + LOCAL_ASSISTANT_PATH, + undefined, + options + ) + return data?.online === true + } + + async submitTask( + input: { content: string }, + options: AgentTaskProviderRequestOptions = {} + ): Promise<{ messageId: string }> { + const data = await this.request<{ message_id?: unknown }>( + 'POST', + `${LOCAL_ASSISTANT_PATH}/message`, + { content: input.content, msg_type: 'text' }, + options + ) + if (!data || typeof data.message_id !== 'string' || !data.message_id) { + throw new AgentTaskProviderError('invalid_response', 'WorkBuddy 投递响应缺少 message_id') + } + return { messageId: data.message_id } + } + + async fetchReplies( + afterMessageId: string, + options: AgentTaskProviderRequestOptions & { limit?: number } = {} + ): Promise { + const query = new URLSearchParams({ + message_id: afterMessageId, + limit: String(Math.max(1, Math.min(options.limit ?? 20, 100))) + }) + const data = await this.request( + 'GET', + `${LOCAL_ASSISTANT_MESSAGE_PATH}?${query.toString()}`, + undefined, + options + ) + return parseReplies(data) + } + + private async request( + method: 'GET' | 'POST', + path: string, + body: unknown | undefined, + options: AgentTaskProviderRequestOptions, + retried = false + ): Promise { + const token = await this.tokenSource.getAccessToken(retried) + + const controller = new AbortController() + const timer = setTimeout(() => controller.abort(), this.options.timeoutMs) + const signal = options.signal + ? AbortSignal.any([controller.signal, options.signal]) + : controller.signal + + let response: Response + try { + response = await this.fetchImpl(`${this.options.baseUrl}${path}`, { + method, + headers: { + Authorization: `Bearer ${token}`, + ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}) + }, + ...(body !== undefined ? { body: JSON.stringify(body) } : {}), + signal + }) + } catch (error) { + throw classifyRequestFailure(error, options.signal) + } finally { + clearTimeout(timer) + } + + if (response.status === 401) { + if (!retried) { + this.tokenSource.invalidate() + return this.request(method, path, body, options, true) + } + throw new AgentTaskProviderError('auth_expired', 'WorkBuddy 鉴权失败(HTTP 401)', false, 401) + } + if (response.status === 403) { + throw new AgentTaskProviderError( + 'auth_expired', + 'WorkBuddy 授权不足(HTTP 403,检查 scope)', + false, + 403 + ) + } + + const envelope = await readEnvelope(response) + if (!response.ok) { + const retryable = response.status === 429 || response.status >= 500 + throw new AgentTaskProviderError( + 'http_error', + `WorkBuddy 请求失败(HTTP ${response.status}${envelope.msg ? `:${envelope.msg}` : ''})`, + retryable, + response.status + ) + } + if (typeof envelope.code === 'number' && envelope.code !== 0) { + throw new AgentTaskProviderError( + 'http_error', + `WorkBuddy 业务错误(code=${envelope.code}${envelope.msg ? `:${envelope.msg}` : ''})` + ) + } + return envelope.data as T + } +} + +async function readEnvelope(response: Response): Promise> { + let text = '' + try { + text = await response.text() + } catch { + return {} + } + if (!text) return {} + try { + const parsed = JSON.parse(text) as unknown + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + return parsed as WorkBuddyEnvelope + } + } catch { + // 非 JSON 响应:保留 HTTP 状态,交给调用方按 invalid_response 处理。 + } + return {} +} + +function classifyTokenFailure(error: unknown): AgentTaskProviderError { + if (error instanceof Error && error.name === 'AbortError') { + return new AgentTaskProviderError('timeout', 'WorkBuddy 凭证刷新超时', true) + } + return new AgentTaskProviderError( + 'http_error', + `WorkBuddy 凭证刷新请求失败:${error instanceof Error ? error.message : String(error)}`, + true + ) +} + +function classifyRequestFailure( + error: unknown, + externalSignal?: AbortSignal +): AgentTaskProviderError { + if (error instanceof Error && error.name === 'AbortError') { + if (externalSignal?.aborted) { + return new AgentTaskProviderError('internal', 'WorkBuddy 请求已取消') + } + return new AgentTaskProviderError('timeout', 'WorkBuddy 请求超时', true) + } + return new AgentTaskProviderError( + 'http_error', + `WorkBuddy 请求失败:${error instanceof Error ? error.message : String(error)}`, + true + ) +} + +function roleOf(value: unknown): AgentTaskReplyRole { + if (value === 'assistant') return 'assistant' + if (value === 'user') return 'user' + return 'other' +} + +function extractText(content: unknown): string { + if (typeof content === 'string') return content + if (!Array.isArray(content)) return '' + const parts: string[] = [] + for (const part of content) { + if (typeof part === 'string') { + parts.push(part) + continue + } + if (part && typeof part === 'object' && typeof (part as { text?: unknown }).text === 'string') { + parts.push((part as { text: string }).text) + } + } + return parts.join('\n').trim() +} + +/** + * 解析 `messages[]`。 + * + * 兼容 `data.messages` 与 `data` 直接是数组两种形态(契约文档只写了前者, + * 但历史接口在分页/增量下出现过裸数组,这里不做假设性拒绝)。 + */ +export function parseReplies(data: unknown): AgentTaskReply[] { + const list = Array.isArray(data) + ? data + : data && typeof data === 'object' && Array.isArray((data as { messages?: unknown }).messages) + ? (data as { messages: unknown[] }).messages + : [] + + const replies: AgentTaskReply[] = [] + for (const item of list) { + if (!item || typeof item !== 'object') continue + const record = item as Record + const messageId = + typeof record.message_id === 'string' + ? record.message_id + : typeof record.messageId === 'string' + ? record.messageId + : '' + if (!messageId) continue + replies.push({ + messageId, + role: roleOf(record.role), + text: extractText(record.content), + ...(typeof record.created_at === 'string' ? { createdAt: record.created_at } : {}) + }) + } + return replies +} diff --git a/src/shared/agent-task.ts b/src/shared/agent-task.ts new file mode 100644 index 0000000..e42bdb6 --- /dev/null +++ b/src/shared/agent-task.ts @@ -0,0 +1,77 @@ +/** + * Agent 任务的共享契约。 + * + * 这些类型会同时出现在主进程、HTTP 响应与测试里,所以只放**可序列化**的字段, + * 不放 provider 私有对象、不放开头、不放任何凭证。 + */ + +export type AgentTaskStatus = + | 'queued' + | 'submitting' + | 'submitted' + | 'completed' + | 'failed' + | 'timeout' + | 'offline' + | 'auth_failed' + +export type AgentTaskErrorKind = + | 'offline' + | 'auth_missing' + | 'auth_expired' + | 'timeout' + | 'http_error' + | 'invalid_response' + /** 提交过程中进程退出:无法确认远端是否已收到,**不允许重试**。 */ + | 'ambiguous_submission' + | 'internal' + +export type AgentTaskReplyRole = 'user' | 'assistant' | 'other' + +export interface AgentTaskReply { + messageId: string + role: AgentTaskReplyRole + text: string + createdAt?: string +} + +export interface AgentTaskRecord { + id: string + provider: string + /** 触发任务的会话 md5(与 `messageRef.c` 同口径)。 */ + conversationId: string + /** `${sessionId}:${localId}`:同一条微信消息只允许提交一次。 */ + triggerKey: string + /** 去掉 `/ai` 前缀后的指令。 */ + prompt: string + status: AgentTaskStatus + /** epoch 毫秒。 */ + createdAt: number + updatedAt: number + submittedAt?: number + completedAt?: number + /** WorkBuddy `POST /openapi/v2/localassistant/message` 返回的 `message_id`。 */ + externalMessageId?: string + /** 增量轮询的游标(最后一条已消费回复的 `message_id`)。 */ + lastReplyId?: string + errorKind?: AgentTaskErrorKind + errorMessage?: string + replies: AgentTaskReply[] +} + +/** 对外展示时使用的安全视图:不包含会话 username、wxid、凭证。 */ +export interface AgentTaskView { + id: string + provider: string + conversationId: string + status: AgentTaskStatus + prompt: string + createdAt: number + updatedAt: number + submittedAt?: number + completedAt?: number + externalMessageId?: string + errorKind?: AgentTaskErrorKind + errorMessage?: string + replies: AgentTaskReply[] +} diff --git a/tests/integration/message-events-sse.test.ts b/tests/integration/message-events-sse.test.ts new file mode 100644 index 0000000..8f4e666 --- /dev/null +++ b/tests/integration/message-events-sse.test.ts @@ -0,0 +1,469 @@ +import http from 'node:http' +import { afterEach, describe, expect, it, vi } from 'vitest' + +vi.mock('electron', () => ({ + app: { + getPath: () => `/tmp/tracememo-sse-${process.pid}`, + getAppPath: () => `/tmp/tracememo-sse-${process.pid}`, + getVersion: () => 'test-version', + isPackaged: false + }, + shell: { + openPath: async () => '', + openExternal: async () => undefined + }, + safeStorage: { + isEncryptionAvailable: () => true, + encryptString: (value: string) => Buffer.from(`encrypted:${value}`, 'utf8'), + decryptString: (value: Buffer) => value.toString('utf8').replace(/^encrypted:/, '') + } +})) + +vi.mock('../../src/main/services/chat-service', () => ({ + isReady: () => true, + listContacts: () => [], + listContactsAsync: async () => [], + listMessages: () => [], + getGroupSnapshot: () => ({ members: [] }), + listRecentChat: () => [], + resolveMd5: () => null +})) + +vi.mock('../../src/main/group-report-service', () => ({ + exportGroupReport: vi.fn(async () => ({ success: true })) +})) + +vi.mock('../../src/main/services/agent-group-report-service', () => ({ + generateAgentGroupReport: vi.fn(async () => ({ success: true })) +})) + +vi.mock('../../src/main/services/agent-hub-service', () => ({ + agentHubService: { + getStatus: () => ({ + hub: 'online', + connector: 'online', + dataApi: 'online', + databaseReady: true + }), + testSend: vi.fn(async () => ({ success: true })) + } +})) + +import { + startHttpServer, + setAgentTaskInspector, + type HttpServerHandle +} from '../../src/main/http-server' +import { MessageEventBroker } from '../../src/main/services/message-event-broker' +import { + normalizeIncomingMessage, + type NormalizedIncomingMessage +} from '../../src/main/services/message-listener-service' +import { decodeMessageRef } from '../../src/shared/local-query-api' +import type { Wcdb4Message } from '../../src/main/wcdb4-client' + +/** + * `/api/v1/events/messages` 的端到端契约。 + * + * 用真实 `http` 连接而不是直接调 handler:SSE 的正确性很大一部分在 + * 响应头、帧格式、连接关闭与 `server.close()` 的行为里,函数级测试覆盖不到。 + */ + +const TOKEN = 'S'.repeat(43) +const SESSION_A = 'group_A@chatroom' +const SESSION_B = 'user_B' +const CONVERSATION_A = 'md5_conversation_a' +const CONVERSATION_B = 'md5_conversation_b' + +const makeRow = (localId: string, content = 'hello'): Wcdb4Message => ({ + mesLocalID: localId, + serverId: `server-${localId}`, + mesDes: 1, + messageType: '1', + msgCreateTime: String(Math.floor(Date.now() / 1000)), + msgContent: content, + sender: 'OTHER_USER', + senderNickname: '对方', + senderAvatar: '', + raw: {} +}) + +const normalize = ( + sessionId: string, + localId: string, + content?: string +): NormalizedIncomingMessage => normalizeIncomingMessage(sessionId, makeRow(localId, content))! + +interface SseFrame { + id?: string + event?: string + data?: Record +} + +interface SseClient { + frames: SseFrame[] + close(): void + waitFor(predicate: (frame: SseFrame) => boolean, timeoutMs?: number): Promise +} + +const clients: SseClient[] = [] +const handles: HttpServerHandle[] = [] + +function parseBlock(block: string): SseFrame | null { + const frame: SseFrame = {} + for (const line of block.split('\n')) { + if (!line || line.startsWith(':')) continue + const separator = line.indexOf(':') + if (separator < 0) continue + const field = line.slice(0, separator) + const value = line.slice(separator + 1).replace(/^ /, '') + if (field === 'id') frame.id = value + else if (field === 'event') frame.event = value + else if (field === 'data') { + try { + frame.data = JSON.parse(value) as Record + } catch { + frame.data = { raw: value } + } + } + } + return Object.keys(frame).length > 0 ? frame : null +} + +function openSse( + handle: HttpServerHandle, + query = '', + options: { token?: string | null; lastEventId?: string } = {} +): Promise { + const url = `http://${handle.host}:${handle.port}/api/v1/events/messages${query}` + const headers: Record = { Accept: 'text/event-stream' } + const token = options.token === undefined ? TOKEN : options.token + if (token) headers.Authorization = `Bearer ${token}` + if (options.lastEventId) headers['Last-Event-ID'] = options.lastEventId + + return new Promise((resolve, reject) => { + const req = http.get(url, { headers }, (res) => { + if (res.statusCode !== 200) { + let body = '' + res.setEncoding('utf8') + res.on('data', (chunk) => { + body += chunk + }) + res.on('end', () => reject(new Error(`HTTP ${res.statusCode}: ${body}`))) + return + } + + const frames: SseFrame[] = [] + let buffer = '' + res.setEncoding('utf8') + res.on('data', (chunk: string) => { + buffer += chunk + let boundary = buffer.indexOf('\n\n') + while (boundary >= 0) { + const block = buffer.slice(0, boundary) + buffer = buffer.slice(boundary + 2) + const frame = parseBlock(block) + if (frame) frames.push(frame) + boundary = buffer.indexOf('\n\n') + } + }) + + const client: SseClient = { + frames, + close: () => { + res.destroy() + req.destroy() + }, + waitFor: (predicate, timeoutMs = 2_000) => + new Promise((resolveFrame, rejectFrame) => { + const startedAt = Date.now() + const timer = setInterval(() => { + const found = frames.find(predicate) + if (found) { + clearInterval(timer) + resolveFrame(found) + return + } + if (Date.now() - startedAt > timeoutMs) { + clearInterval(timer) + rejectFrame( + new Error(`SSE frame not received; got ${JSON.stringify(frames.slice(-3))}`) + ) + } + }, 10) + timer.unref?.() + }) + } + clients.push(client) + resolve(client) + }) + req.on('error', reject) + }) +} + +function makeBroker( + options: { + bufferSize?: number + dbReady?: () => boolean + reader?: ( + sessionId: string, + start: number, + end: number, + limit: number + ) => Promise + } = {} +): MessageEventBroker { + return new MessageEventBroker({ + resolveConversationId: (sessionId) => { + if (sessionId === SESSION_A) return CONVERSATION_A + if (sessionId === SESSION_B) return CONVERSATION_B + return undefined + }, + resolveSessionId: (conversationId) => + conversationId === CONVERSATION_A + ? SESSION_A + : conversationId === CONVERSATION_B + ? SESSION_B + : undefined, + isDatabaseReady: options.dbReady ?? (() => true), + readMessages: options.reader, + bufferSize: options.bufferSize ?? 20, + bufferTtlMs: 10 * 60 * 1000 + }) +} + +async function startFixtureServer(broker: MessageEventBroker): Promise { + const handle = await startHttpServer('127.0.0.1', 0, { + tokenProvider: () => TOKEN, + messageEventBroker: broker, + messageEventsHeartbeatMs: 40 + }) + handles.push(handle) + return handle +} + +afterEach(async () => { + for (const client of clients.splice(0)) client.close() + await Promise.all(handles.splice(0).map((handle) => handle.close())) +}) + +describe('GET /api/v1/events/messages', () => { + it('没有 Bearer token 时返回 401,不建立 SSE 流', async () => { + const handle = await startFixtureServer(makeBroker()) + await expect(openSse(handle, '', { token: null })).rejects.toThrow(/HTTP 401/) + }) + + it('连接先收到 status,再收到带 messageRef 的实时事件', async () => { + const broker = makeBroker() + const handle = await startFixtureServer(broker) + const client = await openSse(handle) + + const status = await client.waitFor((frame) => frame.event === 'status') + expect(status.data).toMatchObject({ database: 'ready', filter: 'all', backfill: 'enabled' }) + + broker.publish(normalize(SESSION_A, '1', '实时消息')) + const message = await client.waitFor((frame) => frame.event === 'message') + expect(message.id).toBe('1') + expect(message.data).toMatchObject({ + origin: 'live', + conversationId: CONVERSATION_A, + text: '实时消息', + isSelf: false + }) + expect(decodeMessageRef(String(message.data?.messageRef))).toEqual({ + conversationId: CONVERSATION_A, + messageId: '1' + }) + }) + + it('同一条消息重复发布只推送一次(事件去重)', async () => { + const broker = makeBroker() + const handle = await startFixtureServer(broker) + const client = await openSse(handle, `?conversation_id=${CONVERSATION_A}`) + await client.waitFor((frame) => frame.event === 'status') + + const message = normalize(SESSION_A, '1') + broker.publish(message) + broker.publish(message) + await client.waitFor((frame) => frame.event === 'message') + await new Promise((resolve) => setTimeout(resolve, 120)) + + expect(client.frames.filter((frame) => frame.event === 'message')).toHaveLength(1) + }) + + it('多个会话同时来消息:指定会话订阅只收到自己的,未过滤订阅全部收到', async () => { + const broker = makeBroker() + const handle = await startFixtureServer(broker) + const filtered = await openSse(handle, `?conversation_id=${CONVERSATION_A}`) + const all = await openSse(handle) + await filtered.waitFor((frame) => frame.event === 'status') + await all.waitFor((frame) => frame.event === 'status') + + broker.publish(normalize(SESSION_A, 'a1')) + broker.publish(normalize(SESSION_B, 'b1')) + broker.publish(normalize(SESSION_A, 'a2')) + + await all.waitFor( + (frame) => + frame.event === 'message' && + typeof frame.data?.conversationId === 'string' && + frame.data.conversationId === CONVERSATION_B + ) + await filtered.waitFor( + (frame) => + frame.event === 'message' && + typeof frame.data?.conversationId === 'string' && + frame.data.conversationId === CONVERSATION_A + ) + await new Promise((resolve) => setTimeout(resolve, 80)) + + const filteredMessages = filtered.frames.filter((frame) => frame.event === 'message') + const allMessages = all.frames.filter((frame) => frame.event === 'message') + expect(filteredMessages).toHaveLength(2) + expect(allMessages).toHaveLength(3) + expect(filteredMessages.every((frame) => frame.data?.conversationId === CONVERSATION_A)).toBe( + true + ) + }) + + it('SSE 重连:带上 Last-Event-ID 后补发断开期间的事件(origin=replay)', async () => { + const broker = makeBroker() + const handle = await startFixtureServer(broker) + const first = await openSse(handle) + await first.waitFor((frame) => frame.event === 'status') + + broker.publish(normalize(SESSION_A, '1')) + const firstMessage = await first.waitFor((frame) => frame.event === 'message') + const lastId = String(firstMessage.id) + first.close() + + broker.publish(normalize(SESSION_A, '2')) + + const second = await openSse(handle, `?conversation_id=${CONVERSATION_A}`, { + lastEventId: lastId + }) + const replayed = await second.waitFor((frame) => frame.event === 'message') + expect(replayed.data).toMatchObject({ origin: 'replay', text: 'hello' }) + expect(decodeMessageRef(String(replayed.data?.messageRef))).toEqual({ + conversationId: CONVERSATION_A, + messageId: '2' + }) + }) + + it('缓冲覆盖不到时先发 gap,再从数据库有界回补(origin=db_backfill)', async () => { + const reader = vi.fn(async (_sessionId: string, start: number, end: number) => { + expect(end - start).toBeLessThanOrEqual(300) + return [makeRow('9', '补回来的消息')] + }) + const broker = makeBroker({ bufferSize: 1, reader }) + const handle = await startFixtureServer(broker) + + for (const id of ['1', '2', '3', '4']) broker.publish(normalize(SESSION_A, id)) + + const client = await openSse(handle, `?conversation_id=${CONVERSATION_A}`, { + lastEventId: '1' + }) + const gap = await client.waitFor((frame) => frame.event === 'gap') + expect(gap.data).toMatchObject({ + reason: 'buffer_overflow', + requestedLastEventId: '1', + backfill: 'scheduled' + }) + const backfilled = await client.waitFor( + (frame) => frame.event === 'message' && frame.data?.origin === 'db_backfill' + ) + expect(backfilled.data?.text).toBe('补回来的消息') + expect(client.frames.findIndex((f) => f.event === 'gap')).toBeLessThan( + client.frames.findIndex((f) => f.event === 'message' && f.data?.origin === 'db_backfill') + ) + }) + + it('数据库不可用时 status 明确报告,恢复后心跳会补发状态变化', async () => { + let ready = false + const broker = makeBroker({ dbReady: () => ready }) + const handle = await startFixtureServer(broker) + + const client = await openSse(handle, `?conversation_id=${CONVERSATION_A}`) + const offline = await client.waitFor( + (frame) => frame.event === 'status' && frame.data?.database === 'unavailable' + ) + expect(offline.data).toMatchObject({ database: 'unavailable' }) + + ready = true + const recovered = await client.waitFor( + (frame) => frame.event === 'status' && frame.data?.database === 'ready', + 3_000 + ) + expect(recovered.data).toMatchObject({ database: 'ready' }) + }) + + it('客户端断开后释放订阅,不会留下僵尸订阅者', async () => { + const broker = makeBroker() + const handle = await startFixtureServer(broker) + const client = await openSse(handle) + await client.waitFor((frame) => frame.event === 'status') + expect(broker.status().subscribers).toBe(1) + + client.close() + await vi.waitFor(() => expect(broker.status().subscribers).toBe(0), { timeout: 3_000 }) + }) + + it('SSE 连接存活时 server.close() 仍能立即返回', async () => { + const broker = makeBroker() + const handle = await startFixtureServer(broker) + const client = await openSse(handle) + await client.waitFor((frame) => frame.event === 'status') + + const closed = await Promise.race([ + handle.close().then(() => 'closed'), + new Promise((resolve) => setTimeout(() => resolve('timeout'), 1_500)) + ]) + expect(closed).toBe('closed') + handles.splice(handles.indexOf(handle), 1) + }) +}) + +describe('GET /api/v1/agent-tasks', () => { + const record = { + id: 'task-1', + provider: 'workbuddy', + conversationId: CONVERSATION_A, + triggerKey: `${SESSION_A}:100`, + prompt: '写日报', + status: 'submitted' as const, + createdAt: 1, + updatedAt: 2, + externalMessageId: 'msg-1', + replies: [{ messageId: 'm2', role: 'assistant' as const, text: '好了' }] + } + + afterEach(() => setAgentTaskInspector(undefined)) + + it('需要 Bearer;返回安全视图,不泄露 triggerKey 与 username', async () => { + setAgentTaskInspector({ + list: () => [record], + get: (id) => (id === record.id ? record : undefined) + }) + const handle = await startFixtureServer(makeBroker()) + const url = `http://${handle.host}:${handle.port}/api/v1/agent-tasks` + + expect((await fetch(url)).status).toBe(401) + + const response = await fetch(url, { headers: { Authorization: `Bearer ${TOKEN}` } }) + expect(response.status).toBe(200) + const body = await response.json() + expect(body).toMatchObject({ count: 1, tasks: [{ id: 'task-1', status: 'submitted' }] }) + expect(JSON.stringify(body)).not.toContain('triggerKey') + expect(JSON.stringify(body)).not.toContain(SESSION_A) + }) + + it('单任务不存在时 404', async () => { + setAgentTaskInspector({ list: () => [], get: () => undefined }) + const handle = await startFixtureServer(makeBroker()) + const response = await fetch( + `http://${handle.host}:${handle.port}/api/v1/agent-tasks/missing`, + { headers: { Authorization: `Bearer ${TOKEN}` } } + ) + expect(response.status).toBe(404) + }) +}) diff --git a/tests/unit/agent-task-config.test.ts b/tests/unit/agent-task-config.test.ts new file mode 100644 index 0000000..98dfc04 --- /dev/null +++ b/tests/unit/agent-task-config.test.ts @@ -0,0 +1,105 @@ +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('electron', () => ({ + app: { getPath: () => '/tmp/tracememo-agent-config' } +})) + +import { + DEFAULT_WORKBUDDY_AGENT_SETTINGS, + loadWorkBuddyAgentSettings, + loadWorkBuddyCredentials +} from '../../src/main/services/agent-task-config' + +/** + * 配置边界: + * - 默认必须**禁用**; + * - 配置损坏不能阻断启动; + * - 凭证只能来自环境变量,配置文件里的同名字段必须被忽略。 + */ + +let root: string + +beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'tracememo-agent-config-')) +}) + +afterEach(() => { + fs.rmSync(root, { recursive: true, force: true }) +}) + +describe('loadWorkBuddyAgentSettings', () => { + it('没有配置文件时默认禁用且白名单为空', () => { + const settings = loadWorkBuddyAgentSettings(root) + expect(settings).toEqual(DEFAULT_WORKBUDDY_AGENT_SETTINGS) + expect(settings.enabled).toBe(false) + expect(settings.allowedConversations).toEqual([]) + }) + + it('配置损坏时回落默认值,不抛异常', () => { + fs.writeFileSync(path.join(root, 'workbuddy-agent.json'), '{not json') + expect(loadWorkBuddyAgentSettings(root).enabled).toBe(false) + }) + + it('类型不合法时逐项回落(enabled 只接受 true)', () => { + fs.writeFileSync( + path.join(root, 'workbuddy-agent.json'), + JSON.stringify({ + enabled: 'yes', + allowedConversations: [' md5_a ', 42, 'md5_a', ''], + timeoutMs: -5, + pollIntervalMs: 'abc' + }) + ) + const settings = loadWorkBuddyAgentSettings(root) + expect(settings.enabled).toBe(false) + expect(settings.allowedConversations).toEqual(['md5_a']) + expect(settings.timeoutMs).toBe(DEFAULT_WORKBUDDY_AGENT_SETTINGS.timeoutMs) + expect(settings.pollIntervalMs).toBe(DEFAULT_WORKBUDDY_AGENT_SETTINGS.pollIntervalMs) + }) + + it('配置文件里的凭证字段不会被读入(凭证只走环境变量)', () => { + fs.writeFileSync( + path.join(root, 'workbuddy-agent.json'), + JSON.stringify({ + enabled: true, + allowedConversations: ['md5_a'], + accessToken: 'should-be-ignored', + clientSecret: 'should-be-ignored' + }) + ) + const settings = loadWorkBuddyAgentSettings(root) as unknown as Record + expect(settings.enabled).toBe(true) + expect(settings.accessToken).toBeUndefined() + expect(settings.clientSecret).toBeUndefined() + }) +}) + +describe('loadWorkBuddyCredentials', () => { + it('只从环境变量读取,空字符串视为未配置', () => { + expect( + loadWorkBuddyCredentials({ + TRACEMEMO_WORKBUDDY_ACCESS_TOKEN: ' token ', + TRACEMEMO_WORKBUDDY_REFRESH_TOKEN: '', + TRACEMEMO_WORKBUDDY_CLIENT_ID: 'client', + TRACEMEMO_WORKBUDDY_CLIENT_SECRET: 'secret' + }) + ).toEqual({ + accessToken: 'token', + refreshToken: undefined, + clientId: 'client', + clientSecret: 'secret' + }) + }) + + it('没有任何环境变量时返回空对象(由 provider 判 auth_missing)', () => { + expect(loadWorkBuddyCredentials({})).toEqual({ + accessToken: undefined, + refreshToken: undefined, + clientId: undefined, + clientSecret: undefined + }) + }) +}) diff --git a/tests/unit/agent-task-dispatcher.test.ts b/tests/unit/agent-task-dispatcher.test.ts new file mode 100644 index 0000000..3f80e2b --- /dev/null +++ b/tests/unit/agent-task-dispatcher.test.ts @@ -0,0 +1,352 @@ +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { AgentTaskDispatcher, matchCommand } from '../../src/main/services/agent-task-dispatcher' +import { AgentTaskStore } from '../../src/main/services/agent-task-store' +import { + AgentTaskProviderError, + type AgentTaskProvider +} from '../../src/main/services/agent-task-provider' +import type { WorkBuddyAgentSettings } from '../../src/main/services/agent-task-config' +import type { NormalizedIncomingMessage } from '../../src/main/services/message-listener-service' + +/** + * `/ai` 闸门与任务生命周期。 + * + * 重点不是「能提交」,而是**不该提交的时候一次都不提交**: + * 默认禁用、非白名单、自己发的、没有 `/ai ` 前缀、同一条消息重复投递。 + */ + +const SESSION = 'group_A@chatroom' +const CONVERSATION = 'md5_conversation_a' +const NOW = 1_800_000_000_000 + +const settings = (overrides: Partial = {}): WorkBuddyAgentSettings => ({ + enabled: true, + allowedConversations: [CONVERSATION], + commandPrefix: '/ai', + baseUrl: 'https://workbuddy.test', + timeoutMs: 500, + pollIntervalMs: 1000, + maxPollDurationMs: 60_000, + ...overrides +}) + +const makeMessage = ( + overrides: Partial = {} +): NormalizedIncomingMessage => ({ + sessionId: SESSION, + localId: '100', + createTime: Math.floor(NOW / 1000), + messageType: 1, + isSelf: false, + senderId: 'OTHER_USER', + content: '/ai 写一份今天的日报', + isGroup: true, + mentionTargets: [], + ...overrides +}) + +function makeProvider(overrides: Partial = {}): AgentTaskProvider & { + checkOnline: ReturnType + submitTask: ReturnType + fetchReplies: ReturnType +} { + return { + id: 'workbuddy', + checkOnline: vi.fn(async () => true), + submitTask: vi.fn(async () => ({ messageId: 'msg-1' })), + fetchReplies: vi.fn(async () => []), + ...overrides + } as never +} + +let root: string +const stores: AgentTaskStore[] = [] + +beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'tracememo-agent-task-')) +}) + +afterEach(async () => { + // 先 flush 再删目录,否则 debounce 的写盘会和 teardown 抢跑(ENOENT 噪声)。 + await Promise.all(stores.splice(0).map((store) => store.flush())) + fs.rmSync(root, { recursive: true, force: true }) +}) + +function makeDispatcher( + options: { + settings?: WorkBuddyAgentSettings + provider?: ReturnType + storeFile?: string + } = {} +): { + dispatcher: AgentTaskDispatcher + store: AgentTaskStore + provider: ReturnType +} { + const provider = options.provider ?? makeProvider() + const store = new AgentTaskStore({ + filePath: options.storeFile ?? path.join(root, 'agent-tasks.json'), + debounceMs: 0 + }) + stores.push(store) + const dispatcher = new AgentTaskDispatcher({ + settings: options.settings ?? settings(), + store, + provider, + resolveConversationId: (sessionId) => (sessionId === SESSION ? CONVERSATION : undefined), + now: () => NOW + }) + return { dispatcher, store, provider } +} + +describe('命令识别', () => { + it('只接受「前缀 + 空白」,`/ai写` 不触发', () => { + expect(matchCommand('/ai 写日报', '/ai')).toBe('写日报') + expect(matchCommand(' /ai 写日报 ', '/ai')).toBe('写日报') + expect(matchCommand('/ai', '/ai')).toBe('') + expect(matchCommand('/ai写日报', '/ai')).toBeNull() + expect(matchCommand('请 /ai 写日报', '/ai')).toBeNull() + expect(matchCommand(undefined, '/ai')).toBeNull() + }) + + it('前缀大小写不敏感,但内容原样保留', () => { + expect(matchCommand('/AI 保留大小写 ABC', '/ai')).toBe('保留大小写 ABC') + }) +}) + +describe('闸门:不该提交时一次都不提交', () => { + it('默认禁用', async () => { + const { dispatcher, provider } = makeDispatcher({ settings: settings({ enabled: false }) }) + await expect(dispatcher.handleMessage(makeMessage())).resolves.toBe('disabled') + expect(provider.checkOnline).not.toHaveBeenCalled() + expect(provider.submitTask).not.toHaveBeenCalled() + }) + + it('白名单为空时等同于不触发', async () => { + const { dispatcher, provider } = makeDispatcher({ + settings: settings({ allowedConversations: [] }) + }) + await expect(dispatcher.handleMessage(makeMessage())).resolves.toBe('ignored') + expect(provider.submitTask).not.toHaveBeenCalled() + }) + + it('非白名单会话不触发', async () => { + const { dispatcher, provider } = makeDispatcher({ + settings: settings({ allowedConversations: ['md5_other'] }) + }) + await expect(dispatcher.handleMessage(makeMessage())).resolves.toBe('ignored') + expect(provider.submitTask).not.toHaveBeenCalled() + }) + + it('自己发送的消息不触发(防自循环)', async () => { + const { dispatcher, provider } = makeDispatcher() + await expect(dispatcher.handleMessage(makeMessage({ isSelf: true }))).resolves.toBe('ignored') + expect(provider.submitTask).not.toHaveBeenCalled() + }) + + it('普通消息不唤醒 AI', async () => { + const { dispatcher, provider } = makeDispatcher() + await expect(dispatcher.handleMessage(makeMessage({ content: '今天吃什么' }))).resolves.toBe( + 'ignored' + ) + await expect(dispatcher.handleMessage(makeMessage({ content: '/ai写日报' }))).resolves.toBe( + 'ignored' + ) + await expect(dispatcher.handleMessage(makeMessage({ content: '/ai ' }))).resolves.toBe( + 'ignored' + ) + expect(provider.submitTask).not.toHaveBeenCalled() + }) + + it('无法映射会话时不提交(拿不到 stable conversationId)', async () => { + const { dispatcher, provider } = makeDispatcher() + await expect( + dispatcher.handleMessage(makeMessage({ sessionId: 'unknown@chatroom' })) + ).resolves.toBe('ignored') + expect(provider.submitTask).not.toHaveBeenCalled() + }) +}) + +describe('提交与幂等', () => { + it('`/ai ` 命令只把去前缀后的文本交给 provider', async () => { + const { dispatcher, provider, store } = makeDispatcher() + await expect(dispatcher.handleMessage(makeMessage())).resolves.toBe('submitted') + + expect(provider.submitTask).toHaveBeenCalledTimes(1) + expect(provider.submitTask).toHaveBeenCalledWith({ content: '写一份今天的日报' }) + + const task = store.findByTrigger(`${SESSION}:100`) + expect(task).toMatchObject({ + status: 'submitted', + externalMessageId: 'msg-1', + provider: 'workbuddy', + conversationId: CONVERSATION + }) + }) + + it('同一条微信消息重复投递只提交一次', async () => { + const { dispatcher, provider } = makeDispatcher() + await expect(dispatcher.handleMessage(makeMessage())).resolves.toBe('submitted') + await expect(dispatcher.handleMessage(makeMessage())).resolves.toBe('duplicate') + await expect(dispatcher.handleMessage(makeMessage())).resolves.toBe('duplicate') + + expect(provider.submitTask).toHaveBeenCalledTimes(1) + }) + + it('进程重启后仍按 triggerKey 去重,不重复提交', async () => { + const storeFile = path.join(root, 'agent-tasks.json') + const first = makeDispatcher({ storeFile }) + await first.dispatcher.handleMessage(makeMessage()) + await first.store.flush() + + const second = makeDispatcher({ storeFile }) + await expect(second.dispatcher.handleMessage(makeMessage())).resolves.toBe('duplicate') + expect(second.provider.submitTask).not.toHaveBeenCalled() + }) + + it('离线时不提交,并如实记录 offline', async () => { + const provider = makeProvider({ checkOnline: vi.fn(async () => false) }) + const { dispatcher, store } = makeDispatcher({ provider }) + await expect(dispatcher.handleMessage(makeMessage())).resolves.toBe('offline') + + expect(provider.submitTask).not.toHaveBeenCalled() + expect(store.findByTrigger(`${SESSION}:100`)).toMatchObject({ + status: 'offline', + errorKind: 'offline' + }) + }) + + it('鉴权失败时记录 auth_failed,不重试', async () => { + const provider = makeProvider({ + checkOnline: vi.fn(async () => { + throw new AgentTaskProviderError('auth_expired', 'token 过期', false, 401) + }) + }) + const { dispatcher, store } = makeDispatcher({ provider }) + await expect(dispatcher.handleMessage(makeMessage())).resolves.toBe('auth_failed') + expect(provider.submitTask).not.toHaveBeenCalled() + expect(store.findByTrigger(`${SESSION}:100`)).toMatchObject({ + status: 'auth_failed', + errorKind: 'auth_expired' + }) + }) + + it('投递超时记为 ambiguous_submission,绝不自动重试', async () => { + const provider = makeProvider({ + submitTask: vi.fn(async () => { + throw new AgentTaskProviderError('timeout', 'request timeout', true) + }) + }) + const { dispatcher, store } = makeDispatcher({ provider }) + await expect(dispatcher.handleMessage(makeMessage())).resolves.toBe('failed') + + const task = store.findByTrigger(`${SESSION}:100`) + expect(task).toMatchObject({ status: 'failed', errorKind: 'ambiguous_submission' }) + expect(task?.errorMessage).toContain('不会自动重试') + + // 再投一次同一条消息:仍然被 triggerKey 去重,不会出现第二次远端调用。 + await expect(dispatcher.handleMessage(makeMessage())).resolves.toBe('duplicate') + expect(provider.submitTask).toHaveBeenCalledTimes(1) + }) +}) + +describe('回复轮询', () => { + it('拿到 assistant 回复后置 completed 并保存回复内容', async () => { + const provider = makeProvider({ + fetchReplies: vi.fn(async () => [ + { messageId: 'm2', role: 'assistant' as const, text: '日报已生成' } + ]) + }) + const { dispatcher, store } = makeDispatcher({ provider }) + await dispatcher.handleMessage(makeMessage()) + await expect(dispatcher.pollOnce()).resolves.toBe(1) + + expect(provider.fetchReplies).toHaveBeenCalledWith('msg-1') + const task = store.findByTrigger(`${SESSION}:100`) + expect(task).toMatchObject({ + status: 'completed', + replies: [{ messageId: 'm2', role: 'assistant', text: '日报已生成' }] + }) + expect(task?.completedAt).toBe(NOW) + }) + + it('只拿到 user 回显时保持 submitted,不提前宣告完成', async () => { + const provider = makeProvider({ + fetchReplies: vi.fn(async () => [{ messageId: 'm2', role: 'user' as const, text: '写日报' }]) + }) + const { dispatcher, store } = makeDispatcher({ provider }) + await dispatcher.handleMessage(makeMessage()) + await dispatcher.pollOnce() + + expect(store.findByTrigger(`${SESSION}:100`)?.status).toBe('submitted') + }) + + it('超过 maxPollDurationMs 后置 timeout 并停止轮询', async () => { + const provider = makeProvider() + const { dispatcher, store } = makeDispatcher({ + provider, + settings: settings({ maxPollDurationMs: -1 }) + }) + await dispatcher.handleMessage(makeMessage()) + await dispatcher.pollOnce() + + expect(store.findByTrigger(`${SESSION}:100`)?.status).toBe('timeout') + provider.fetchReplies.mockClear() + await dispatcher.pollOnce() + expect(provider.fetchReplies).not.toHaveBeenCalled() + }) + + it('轮询失败不会把已提交任务改成失败(保留下次重试)', async () => { + const provider = makeProvider({ + fetchReplies: vi.fn(async () => { + throw new AgentTaskProviderError('http_error', 'temporary', true, 503) + }) + }) + const { dispatcher, store } = makeDispatcher({ provider }) + await dispatcher.handleMessage(makeMessage()) + await dispatcher.pollOnce() + + expect(store.findByTrigger(`${SESSION}:100`)?.status).toBe('submitted') + }) +}) + +describe('持久化恢复', () => { + it('`submitting` 状态的记录在重启后被标记成不可重试的 ambiguous_submission', async () => { + const storeFile = path.join(root, 'agent-tasks.json') + fs.writeFileSync( + storeFile, + JSON.stringify([ + { + id: 'task-1', + provider: 'workbuddy', + conversationId: CONVERSATION, + triggerKey: `${SESSION}:100`, + prompt: '写日报', + status: 'submitting', + createdAt: NOW, + updatedAt: NOW, + replies: [] + } + ]) + ) + + const store = new AgentTaskStore({ filePath: storeFile, debounceMs: 0 }) + await store.load() + expect(store.findByTrigger(`${SESSION}:100`)).toMatchObject({ + status: 'failed', + errorKind: 'ambiguous_submission' + }) + }) + + it('store 文件权限为 0600', async () => { + const storeFile = path.join(root, 'agent-tasks.json') + const { dispatcher, store } = makeDispatcher({ storeFile }) + await dispatcher.handleMessage(makeMessage()) + await store.flush() + + expect(fs.statSync(storeFile).mode & 0o777).toBe(0o600) + }) +}) diff --git a/tests/unit/message-event-broker.test.ts b/tests/unit/message-event-broker.test.ts new file mode 100644 index 0000000..f8d86d4 --- /dev/null +++ b/tests/unit/message-event-broker.test.ts @@ -0,0 +1,409 @@ +import { describe, expect, it, vi } from 'vitest' +import { + MessageEventBroker, + eventIdFor, + parseLastEventId, + type MessageEventOrigin, + type MessageEventRecord, + type MessageGap +} from '../../src/main/services/message-event-broker' +import { + MessageListenerService, + normalizeIncomingMessage, + type NormalizedIncomingMessage +} from '../../src/main/services/message-listener-service' +import { decodeMessageRef } from '../../src/shared/local-query-api' +import { parseMonitorEvent } from '../../src/main/wcdb4-client' +import type { Wcdb4Client, Wcdb4Message } from '../../src/main/wcdb4-client' + +/** + * MessageEventBroker 的契约测试。 + * + * 覆盖三件容易「看起来对、实际漏消息」的事: + * 1. 事件 ID 与 messageRef 的确定性 / 可反解; + * 2. 缓冲覆盖得住时是 replay,覆盖不住时必须显式 gap + 有界回补; + * 3. 回补事件与实时事件在 `origin` 上必须可区分。 + */ + +const SESSION = 'group_A@chatroom' +const CONVERSATION = 'md5_conversation_a' +const NOW = 1_800_000_000_000 + +const makeRow = (overrides: Partial = {}): Wcdb4Message => ({ + mesLocalID: '100', + serverId: '7000000000000000001', + mesDes: 1, + messageType: '1', + msgCreateTime: String(Math.floor(NOW / 1000)), + msgContent: 'hello', + sender: 'OTHER_USER', + senderNickname: '对方', + senderAvatar: '', + raw: {}, + ...overrides +}) + +const normalize = (row: Wcdb4Message): NormalizedIncomingMessage => { + const normalized = normalizeIncomingMessage(SESSION, row) + if (!normalized) throw new Error('fixture row is not normalizable') + return normalized +} + +interface Collected { + statuses: unknown[] + events: Array<{ event: MessageEventRecord; origin: MessageEventOrigin }> + gaps: MessageGap[] + order: string[] +} + +function makeSink(): Collected & { + sink: { + onStatus: (status: unknown) => void + onEvent: (event: MessageEventRecord, origin: MessageEventOrigin) => void + onGap: (gap: MessageGap) => void + } +} { + const collected: Collected = { statuses: [], events: [], gaps: [], order: [] } + return { + ...collected, + get statuses() { + return collected.statuses + }, + get events() { + return collected.events + }, + get gaps() { + return collected.gaps + }, + get order() { + return collected.order + }, + sink: { + onStatus: (status) => { + collected.statuses.push(status) + collected.order.push('status') + }, + onEvent: (event, origin) => { + collected.events.push({ event, origin }) + collected.order.push(`event:${origin}`) + }, + onGap: (gap) => { + collected.gaps.push(gap) + collected.order.push('gap') + } + } + } +} + +function makeBroker( + options: { + bufferSize?: number + dbReady?: boolean + reader?: ReturnType + } = {} +): MessageEventBroker { + return new MessageEventBroker({ + resolveConversationId: (sessionId) => (sessionId === SESSION ? CONVERSATION : undefined), + resolveSessionId: (conversationId) => (conversationId === CONVERSATION ? SESSION : undefined), + isDatabaseReady: () => options.dbReady !== false, + readMessages: options.reader as never, + bufferSize: options.bufferSize ?? 10, + bufferTtlMs: 10 * 60 * 1000, + now: () => NOW + }) +} + +describe('事件 ID 与 messageRef', () => { + it('同一会话 + 同一条消息得到确定性 ID', () => { + expect(eventIdFor(CONVERSATION, '100')).toBe(eventIdFor(CONVERSATION, '100')) + expect(eventIdFor(CONVERSATION, '100')).not.toBe(eventIdFor(CONVERSATION, '101')) + expect(eventIdFor(CONVERSATION, '100')).toMatch(/^evt_[0-9a-f]{24}$/) + }) + + it('messageRef 用现有 encodeMessageRef 生成,能被 decodeMessageRef 反解', () => { + const broker = makeBroker() + const record = broker.publish(normalize(makeRow())) + expect(record).not.toBeNull() + expect(decodeMessageRef(record!.messageRef)).toEqual({ + conversationId: CONVERSATION, + messageId: '100' + }) + }) + + it('无法映射会话时不发布,也不伪造 messageRef', () => { + const broker = makeBroker() + const other = normalizeIncomingMessage('unknown_session', makeRow()) + expect(broker.publish(other!)).toBeNull() + expect(broker.stats().unmapped).toBe(1) + }) + + it('同一条消息重复回读只会产生一个事件', () => { + const broker = makeBroker() + const message = normalize(makeRow()) + expect(broker.publish(message)).not.toBeNull() + expect(broker.publish(message)).toBeNull() + expect(broker.stats()).toMatchObject({ published: 1, duplicates: 1 }) + }) + + it('超长正文显式标记 textTruncated,而不是静默截断', () => { + const broker = new MessageEventBroker({ + resolveConversationId: () => CONVERSATION, + maxTextChars: 64 + }) + const record = broker.publish(normalize(makeRow({ msgContent: 'x'.repeat(200) }))) + expect(record?.text).toHaveLength(64) + expect(record?.textTruncated).toBe(true) + }) +}) + +describe('订阅、过滤与重放', () => { + it('会话过滤只投递匹配的会话', () => { + const broker = makeBroker() + const a = makeSink() + const b = makeSink() + broker.subscribe({ conversationIds: [CONVERSATION] }, a.sink) + broker.subscribe({ conversationIds: ['md5_other'] }, b.sink) + + broker.publish(normalize(makeRow({ mesLocalID: '1' }))) + expect(a.events).toHaveLength(1) + expect(b.events).toHaveLength(0) + }) + + it('Last-Event-ID 落在缓冲内时按 replay 重放', () => { + const broker = makeBroker() + broker.publish(normalize(makeRow({ mesLocalID: '1' }))) + broker.publish(normalize(makeRow({ mesLocalID: '2' }))) + + const sink = makeSink() + broker.subscribe({ conversationIds: [CONVERSATION], lastEventId: '1' }, sink.sink) + + expect(sink.gaps).toHaveLength(0) + expect(sink.events.map((item) => item.origin)).toEqual(['replay']) + expect(decodeMessageRef(sink.events[0].event.messageRef)).toEqual({ + conversationId: CONVERSATION, + messageId: '2' + }) + }) + + it('进程重启后的旧游标不会被当成「已收到最新」而静默跳过', () => { + const broker = makeBroker() + broker.publish(normalize(makeRow({ mesLocalID: '1' }))) + + // 上一个进程可能把 seq 推到过 500;本进程只分配到 1。 + const sink = makeSink() + broker.subscribe({ conversationIds: [CONVERSATION], lastEventId: '500' }, sink.sink) + + expect(sink.events).toHaveLength(0) + expect(sink.gaps).toHaveLength(1) + expect(sink.gaps[0]).toMatchObject({ + reason: 'cursor_from_previous_process', + requestedLastEventId: '500' + }) + }) + + it('带了游标但格式非法时显式 gap,不当作首次订阅', () => { + const broker = makeBroker() + broker.publish(normalize(makeRow({ mesLocalID: '1' }))) + + const sink = makeSink() + broker.subscribe({ conversationIds: [CONVERSATION], lastEventId: 'evt_abc' }, sink.sink) + + expect(sink.gaps).toHaveLength(1) + expect(sink.gaps[0]).toMatchObject({ + reason: 'invalid_cursor', + requestedLastEventId: 'evt_abc' + }) + }) + + it('游标正好等于最新序号时既无重放也无 gap', () => { + const broker = makeBroker() + broker.publish(normalize(makeRow({ mesLocalID: '1' }))) + broker.publish(normalize(makeRow({ mesLocalID: '2' }))) + + const sink = makeSink() + broker.subscribe({ conversationIds: [CONVERSATION], lastEventId: '2' }, sink.sink) + expect(sink.events).toHaveLength(0) + expect(sink.gaps).toHaveLength(0) + }) + + it('游标早于缓冲下界时先 gap,再做有界数据库回补', async () => { + const reader = vi.fn(async () => [makeRow({ mesLocalID: '9' })]) + const broker = makeBroker({ bufferSize: 2, reader }) + for (const id of ['1', '2', '3', '4', '5']) { + broker.publish(normalize(makeRow({ mesLocalID: id }))) + } + + // 缓冲只剩 4、5;客户端说它只收到 1,中间 2、3 已经无法从缓冲重放。 + const sink = makeSink() + broker.subscribe({ conversationIds: [CONVERSATION], lastEventId: '1' }, sink.sink) + await vi.waitFor(() => expect(sink.events.length).toBe(1)) + + expect(sink.gaps).toHaveLength(1) + expect(sink.gaps[0]).toMatchObject({ + reason: 'buffer_overflow', + requestedLastEventId: '1', + oldestSeq: 4, + backfill: 'scheduled' + }) + // gap 必须先于回补事件送达:顺序本身就是语义。 + expect(sink.order[0]).toBe('status') + expect(sink.order[1]).toBe('gap') + expect(sink.events[0].origin).toBe('db_backfill') + expect(reader).toHaveBeenCalledTimes(1) + + const [sessionArg, startArg, endArg, limitArg] = reader.mock.calls[0] as unknown as [ + string, + number, + number, + number + ] + expect(sessionArg).toBe(SESSION) + expect(startArg).toBeLessThan(endArg) + expect(endArg - startArg).toBeLessThanOrEqual(300) + expect(limitArg).toBeLessThanOrEqual(100) + }) + + it('没有会话过滤时不做回补(无法有界),并如实说明', () => { + const reader = vi.fn(async () => []) + const broker = makeBroker({ bufferSize: 1, reader }) + for (const id of ['1', '2', '3']) broker.publish(normalize(makeRow({ mesLocalID: id }))) + + const sink = makeSink() + broker.subscribe({ lastEventId: '1' }, sink.sink) + + expect(sink.gaps).toHaveLength(1) + expect(sink.gaps[0].backfill).toBe('skipped_no_conversation_filter') + expect(reader).not.toHaveBeenCalled() + }) + + it('数据库不可用时明确标记,不伪造回补', () => { + const reader = vi.fn(async () => [makeRow()]) + const broker = makeBroker({ bufferSize: 1, dbReady: false, reader }) + for (const id of ['1', '2', '3']) broker.publish(normalize(makeRow({ mesLocalID: id }))) + + const status = broker.status() + expect(status.database).toBe('unavailable') + + const sink = makeSink() + broker.subscribe({ conversationIds: [CONVERSATION], lastEventId: '1' }, sink.sink) + + expect(sink.gaps[0].backfill).toBe('skipped_database_unavailable') + expect(reader).not.toHaveBeenCalled() + }) + + it('close 之后不再收到新事件', () => { + const broker = makeBroker() + const sink = makeSink() + const subscription = broker.subscribe({ conversationIds: [CONVERSATION] }, sink.sink) + broker.publish(normalize(makeRow({ mesLocalID: '1' }))) + subscription.close() + broker.publish(normalize(makeRow({ mesLocalID: '2' }))) + + expect(sink.events).toHaveLength(1) + expect(broker.status().subscribers).toBe(0) + }) + + it('订阅数达到上限时抛错,而不是静默丢弃订阅', () => { + const broker = new MessageEventBroker({ + resolveConversationId: () => CONVERSATION, + maxSubscribers: 1 + }) + broker.subscribe({}, makeSink().sink) + expect(() => broker.subscribe({}, makeSink().sink)).toThrow(/上限/) + }) +}) + +describe('parseLastEventId', () => { + it('只接受正整数序号', () => { + expect(parseLastEventId('12')).toBe(12) + expect(parseLastEventId(' 12 ')).toBe(12) + expect(parseLastEventId('0')).toBeNull() + expect(parseLastEventId('-1')).toBeNull() + expect(parseLastEventId('evt_abc')).toBeNull() + expect(parseLastEventId(undefined)).toBeNull() + expect(parseLastEventId('1'.repeat(20))).toBeNull() + }) +}) + +describe('有界性', () => { + it('缓冲条目不超过 bufferSize', () => { + const broker = makeBroker({ bufferSize: 3 }) + for (let index = 0; index < 10; index += 1) { + broker.publish(normalize(makeRow({ mesLocalID: String(index + 1) }))) + } + expect(broker.status().buffered).toBe(3) + expect(broker.status().newestSeq).toBe(10) + }) + + it('订阅者已投递 ID 记忆有界(回补与实时重叠不会重复投递)', () => { + const broker = makeBroker({ bufferSize: 50 }) + const sink = makeSink() + broker.subscribe({ conversationIds: [CONVERSATION] }, sink.sink) + + const message = normalize(makeRow({ mesLocalID: '1' })) + broker.publish(message) + // 直接走一次回补路径(同一个 reader 返回同一条消息),应当被订阅者去重。 + expect( + broker['deliver']( + broker['subscribers'].values().next().value!, + { + ...broker['buffer'][0] + }, + 'db_backfill' + ) + ).toBeUndefined() + expect(sink.events).toHaveLength(1) + }) +}) + +// 防未使用告警:保留类型引用,说明测试覆盖的是真实客户端形态。 +export type _ClientShape = Wcdb4Client + +describe('多订阅者与 Automation 扇出', () => { + it('多个订阅者并发收到同一条事件,互不影响', () => { + const broker = makeBroker() + const sinks = Array.from({ length: 5 }, () => makeSink()) + for (const sink of sinks) { + broker.subscribe({ conversationIds: [CONVERSATION] }, sink.sink) + } + + broker.publish(normalize(makeRow({ mesLocalID: 'fanout-1' }))) + + for (const sink of sinks) { + expect(sink.events).toHaveLength(1) + expect(sink.events[0].event.id).toBe(eventIdFor(CONVERSATION, 'fanout-1')) + } + expect(broker.status().subscribers).toBe(5) + }) + + it('同一批 native event 只让 Automation 与事件订阅各收到一次', async () => { + vi.useRealTimers() + const client = { + getSessions: vi.fn(() => [{ username: SESSION }]), + getMessagesAsync: vi.fn(async () => [makeRow({ mesLocalID: '1' })]) + } as unknown as Wcdb4Client + + const broker = makeBroker() + const sink = makeSink() + broker.subscribe({ conversationIds: [CONVERSATION] }, sink.sink) + + const listener = new MessageListenerService(client, { coalesceMs: 10 }) + const automation = vi.fn() + listener.onMessage((message) => { + broker.publish(message) + automation(message) + }) + + const v2 = parseMonitorEvent( + JSON.stringify({ version: 2, kind: 'message_change', session_id: SESSION, table: 'message' }) + ) + // 一条消息在真实环境会触发一连串 native event。 + listener.handleNativeChange(v2) + listener.handleNativeChange(v2) + listener.handleNativeChange(v2) + + await vi.waitFor(() => expect(sink.events.length).toBe(1), { timeout: 2_000 }) + expect(automation).toHaveBeenCalledTimes(1) + expect(broker.stats().published).toBe(1) + }) +}) diff --git a/tests/unit/message-listener-service.test.ts b/tests/unit/message-listener-service.test.ts index 7389c8b..bc5e2f3 100644 --- a/tests/unit/message-listener-service.test.ts +++ b/tests/unit/message-listener-service.test.ts @@ -105,7 +105,8 @@ describe('mention parser(纯函数)', () => { }) it('多人 @(逗号分隔)能够拆分为独立 username 列表', () => { - const source = '' + const source = + '' expect(extractMentionTargets(source)).toEqual(['OTHER_USER', 'SELF_USER']) }) }) @@ -149,8 +150,9 @@ describe('coalesce:一批 native event 只回读一次', () => { for (let index = 0; index < 17; index += 1) listener.handleNativeChange() await flush() - expect((client as unknown as { getMessagesAsync: ReturnType }).getMessagesAsync) - .toHaveBeenCalledTimes(1) + expect( + (client as unknown as { getMessagesAsync: ReturnType }).getMessagesAsync + ).toHaveBeenCalledTimes(1) expect(received).toHaveLength(1) expect(listener.stats()).toMatchObject({ nativeEvents: 17, @@ -186,9 +188,9 @@ describe('dedup', () => { listener.handleNativeChange() await flush() // 换成另一个 localId 再读一轮 - ;(client as unknown as { getMessagesAsync: ReturnType }).getMessagesAsync.mockResolvedValue( - [makeMessage({ mesLocalID: '101' })] - ) + ;( + client as unknown as { getMessagesAsync: ReturnType } + ).getMessagesAsync.mockResolvedValue([makeMessage({ mesLocalID: '101' })]) listener.handleNativeChange() await flush() @@ -201,9 +203,9 @@ describe('dedup', () => { collect(listener) const send = async (localId: string): Promise => { - ;(client as unknown as { getMessagesAsync: ReturnType }).getMessagesAsync.mockResolvedValue( - [makeMessage({ mesLocalID: localId })] - ) + ;( + client as unknown as { getMessagesAsync: ReturnType } + ).getMessagesAsync.mockResolvedValue([makeMessage({ mesLocalID: localId })]) listener.handleNativeChange() await flush() } @@ -263,9 +265,7 @@ describe('self / incoming', () => { describe('normalize 输出', () => { it('群消息:isGroup = true,且 mentionTargets 来自 source', async () => { const source = '' - const client = makeClient([ - makeMessage({ raw: { source: await zstdBuffer(source) } }) - ]) + const client = makeClient([makeMessage({ raw: { source: await zstdBuffer(source) } })]) const listener = new MessageListenerService(client) collect(listener) @@ -414,7 +414,12 @@ describe('parseMonitorEvent(协议解析)', () => { describe('MessageListener · precise session path', () => { const v2Event = (sessionId: string) => parseMonitorEvent( - JSON.stringify({ version: 2, kind: 'message_change', session_id: sessionId, table: 'message' }) + JSON.stringify({ + version: 2, + kind: 'message_change', + session_id: sessionId, + table: 'message' + }) ) const v1Event = () => parseMonitorEvent(JSON.stringify({ db: 'session.db', table: 'Session', action: 'update' })) @@ -519,3 +524,174 @@ describe('MessageListener · precise session path', () => { expect(received).toHaveLength(1) }) }) + +/** + * 回读进行中到达的事件必须被补读。 + * + * `develop` 已有 `pendingReadback` 机制;这一组锁的是它的边界行为, + * 以及本分支补充的「单会话失败隔离」。 + */ +describe('MessageListener · 回读进行中到达的事件', () => { + const v2Event = (sessionId: string) => + parseMonitorEvent( + JSON.stringify({ + version: 2, + kind: 'message_change', + session_id: sessionId, + table: 'message' + }) + ) + const v1Event = () => + parseMonitorEvent(JSON.stringify({ db: 'session.db', table: 'Session', action: 'update' })) + + it('A 回读未完成时到达的 B 事件不会丢,A 结束后补读 B', async () => { + let releaseA: ((rows: Wcdb4Message[]) => void) | null = null + const calls: string[] = [] + const client = { + getSessions: vi.fn(() => [{ username: 'A@chatroom' }]), + getMessagesAsync: vi.fn((sessionId: string) => { + calls.push(sessionId) + if (sessionId === 'A@chatroom' && !releaseA) { + return new Promise((resolve) => { + releaseA = resolve + }) + } + return Promise.resolve([ + makeMessage({ mesLocalID: sessionId === 'B@chatroom' ? '2' : '1' }) + ]) + }) + } as unknown as Wcdb4Client + + const listener = new MessageListenerService(client) + collect(listener) + + listener.handleNativeChange(v2Event('A@chatroom')) + await vi.advanceTimersByTimeAsync(130) + expect(calls).toEqual(['A@chatroom']) + + // A 还在回读,B 在这时到达。 + listener.handleNativeChange(v2Event('B@chatroom')) + await vi.advanceTimersByTimeAsync(200) + expect(calls).toEqual(['A@chatroom']) + expect(received).toHaveLength(0) + + releaseA!([makeMessage({ mesLocalID: '1' })]) + // develop 的补读走 coalesce 窗口(120ms),不是 0ms。 + await vi.advanceTimersByTimeAsync(150) + + expect(calls).toEqual(['A@chatroom', 'B@chatroom']) + expect(received.map((message) => message.localId).sort()).toEqual(['1', '2']) + }) + + it('回读进行中同一会话的新消息会在补读时投递', async () => { + let releaseFirst: ((rows: Wcdb4Message[]) => void) | null = null + let round = 0 + const client = { + getSessions: vi.fn(() => [{ username: 'A@chatroom' }]), + getMessagesAsync: vi.fn(() => { + round += 1 + if (round === 1) { + return new Promise((resolve) => { + releaseFirst = resolve + }) + } + return Promise.resolve([makeMessage({ mesLocalID: '1' }), makeMessage({ mesLocalID: '2' })]) + }) + } as unknown as Wcdb4Client + + const listener = new MessageListenerService(client) + collect(listener) + + listener.handleNativeChange(v2Event('A@chatroom')) + await vi.advanceTimersByTimeAsync(130) + listener.handleNativeChange(v2Event('A@chatroom')) + await vi.advanceTimersByTimeAsync(50) + + releaseFirst!([makeMessage({ mesLocalID: '1' })]) + await vi.advanceTimersByTimeAsync(150) + + expect(round).toBe(2) + expect(received.map((message) => message.localId)).toEqual(['1', '2']) + }) + + it('回读进行中到达的 legacy 事件同样会补读', async () => { + let releaseFirst: ((rows: Wcdb4Message[]) => void) | null = null + let round = 0 + const client = { + getSessions: vi.fn(() => [{ username: 'recent@chatroom' }]), + getMessagesAsync: vi.fn(() => { + round += 1 + if (round === 1) { + return new Promise((resolve) => { + releaseFirst = resolve + }) + } + return Promise.resolve([makeMessage({ mesLocalID: '7' })]) + }) + } as unknown as Wcdb4Client + + const listener = new MessageListenerService(client) + collect(listener) + + listener.handleNativeChange(v1Event()) + await vi.advanceTimersByTimeAsync(130) + listener.handleNativeChange(v1Event()) + await vi.advanceTimersByTimeAsync(150) + + releaseFirst!([]) + await vi.advanceTimersByTimeAsync(150) + + expect(round).toBe(2) + expect(received.map((message) => message.localId)).toEqual(['7']) + }) + + it('单个会话回读失败不会让同批其他会话丢失', async () => { + const calls: string[] = [] + const client = { + getSessions: vi.fn(() => [{ username: 'A@chatroom' }]), + getMessagesAsync: vi.fn(async (sessionId: string) => { + calls.push(sessionId) + if (sessionId === 'A@chatroom') throw new Error('shard unavailable') + return [makeMessage({ mesLocalID: sessionId === 'B@chatroom' ? '2' : '3' })] + }) + } as unknown as Wcdb4Client + + const listener = new MessageListenerService(client) + collect(listener) + + listener.handleNativeChange(v2Event('A@chatroom')) + listener.handleNativeChange(v2Event('B@chatroom')) + listener.handleNativeChange(v2Event('C@chatroom')) + await vi.advanceTimersByTimeAsync(200) + + expect(calls.sort()).toEqual(['A@chatroom', 'B@chatroom', 'C@chatroom']) + expect(received.map((message) => message.sessionId).sort()).toEqual([ + 'B@chatroom', + 'C@chatroom' + ]) + expect(listener.stats().failedReadbacks).toBe(1) + }) + + it('三个会话在同一窗口同时来消息,全部投递(不是只读最近一个)', async () => { + const calls: string[] = [] + const client = { + getSessions: vi.fn(() => [{ username: 'recent@chatroom' }]), + getMessagesAsync: vi.fn(async (sessionId: string) => { + calls.push(sessionId) + return [makeMessage({ mesLocalID: sessionId })] + }) + } as unknown as Wcdb4Client + + const listener = new MessageListenerService(client) + collect(listener) + + listener.handleNativeChange(v2Event('A@chatroom')) + listener.handleNativeChange(v2Event('B@chatroom')) + listener.handleNativeChange(v2Event('C@chatroom')) + await vi.advanceTimersByTimeAsync(200) + + expect(calls.sort()).toEqual(['A@chatroom', 'B@chatroom', 'C@chatroom']) + expect(received).toHaveLength(3) + expect(listener.stats().readbacks).toBe(3) + }) +}) diff --git a/tests/unit/workbuddy-agent-provider.test.ts b/tests/unit/workbuddy-agent-provider.test.ts new file mode 100644 index 0000000..c7e61e4 --- /dev/null +++ b/tests/unit/workbuddy-agent-provider.test.ts @@ -0,0 +1,259 @@ +import { describe, expect, it, vi } from 'vitest' +import { + WorkBuddyAgentTaskProvider, + WorkBuddyAccessTokenSource, + parseReplies +} from '../../src/main/services/workbuddy-agent-provider' +import { AgentTaskProviderError } from '../../src/main/services/agent-task-provider' +import type { WorkBuddyCredentials } from '../../src/main/services/agent-task-config' + +/** + * WorkBuddy Open API 适配器契约。 + * + * 这些用例**只验证客户端行为**(请求形状、鉴权、错误分类、解析), + * 不代表真实账号已经接入成功。真实链路需要凭证 + 在线助理,本轮未验证。 + */ + +type FetchMock = ReturnType +type FetchCall = [url: string, init: RequestInit] + +function callsOf(fetchImpl: FetchMock): FetchCall[] { + return fetchImpl.mock.calls as unknown as FetchCall[] +} + +function jsonResponse(payload: unknown, status = 200): Response { + return new Response(JSON.stringify(payload), { + status, + headers: { 'Content-Type': 'application/json' } + }) +} + +function provider( + fetchImpl: FetchMock, + credentials: WorkBuddyCredentials = { accessToken: 'token-1' } +): WorkBuddyAgentTaskProvider { + return new WorkBuddyAgentTaskProvider({ + baseUrl: 'https://workbuddy.test', + timeoutMs: 500, + credentials, + fetchImpl: fetchImpl as unknown as typeof fetch + }) +} + +describe('在线检测与投递', () => { + it('GET /openapi/v2/localassistant,带 Bearer,返回 data.online', async () => { + const fetchImpl = vi.fn(async () => jsonResponse({ code: 0, data: { online: true } })) + await expect(provider(fetchImpl).checkOnline()).resolves.toBe(true) + + const [url, init] = callsOf(fetchImpl)[0] + expect(url).toBe('https://workbuddy.test/openapi/v2/localassistant') + expect((init.headers as Record).Authorization).toBe('Bearer token-1') + }) + + it('online=false 如实返回 false(不降级成「已提交」)', async () => { + const fetchImpl = vi.fn(async () => jsonResponse({ code: 0, data: { online: false } })) + await expect(provider(fetchImpl).checkOnline()).resolves.toBe(false) + }) + + it('投递使用 msg_type=text,并读取 data.message_id', async () => { + const fetchImpl = vi.fn(async () => jsonResponse({ code: 0, data: { message_id: 'msg-001' } })) + const result = await provider(fetchImpl).submitTask({ content: '/ai 写日报' }) + + expect(result).toEqual({ messageId: 'msg-001' }) + const [url, init] = callsOf(fetchImpl)[0] + expect(url).toBe('https://workbuddy.test/openapi/v2/localassistant/message') + expect(init.method).toBe('POST') + expect(JSON.parse(String(init.body))).toEqual({ content: '/ai 写日报', msg_type: 'text' }) + }) + + it('投递响应缺 message_id 时报 invalid_response', async () => { + const fetchImpl = vi.fn(async () => jsonResponse({ code: 0, data: {} })) + await expect(provider(fetchImpl).submitTask({ content: 'x' })).rejects.toMatchObject({ + kind: 'invalid_response' + }) + }) +}) + +describe('鉴权', () => { + it('没有凭证时明确 auth_missing', async () => { + const fetchImpl = vi.fn() + await expect(provider(fetchImpl, {}).checkOnline()).rejects.toMatchObject({ + kind: 'auth_missing' + }) + expect(fetchImpl).not.toHaveBeenCalled() + }) + + it('401 时用 refresh_token 换新 token 并重试一次', async () => { + let messageCalls = 0 + const fetchImpl = vi.fn(async (input: unknown) => { + const url = String(input) + if (url.endsWith('/openapi/v2/token')) { + return jsonResponse({ code: 0, data: { access_token: 'fresh', expires_in: 3600 } }) + } + messageCalls += 1 + if (messageCalls === 1) return jsonResponse({ code: 401, msg: 'expired' }, 401) + return jsonResponse({ code: 0, data: { message_id: 'msg-2' } }) + }) + + const instance = provider(fetchImpl, { + accessToken: 'stale', + refreshToken: 'refresh-1', + clientId: 'client-1', + clientSecret: 'secret-1' + }) + await expect(instance.submitTask({ content: 'x' })).resolves.toEqual({ messageId: 'msg-2' }) + + expect(messageCalls).toBe(2) + const calls = callsOf(fetchImpl) + const tokenCall = calls.find(([url]) => url.endsWith('/token'))! + const body = String(tokenCall[1].body) + expect(body).toContain('grant_type=refresh_token') + expect(body).toContain('refresh_token=refresh-1') + + // 第二次投递必须使用刷新后的 token。 + const messageCallsWithInit = calls.filter(([url]) => url.endsWith('/localassistant/message')) + const secondHeaders = messageCallsWithInit[1][1].headers as Record + expect(secondHeaders.Authorization).toBe('Bearer fresh') + }) + + it('refresh 也失败时报 auth_expired,不无限重试', async () => { + const fetchImpl = vi.fn(async (input: unknown) => { + if (String(input).endsWith('/token')) { + return jsonResponse({ code: 400, msg: 'invalid_grant' }, 400) + } + return jsonResponse({ code: 401 }, 401) + }) + const instance = provider(fetchImpl, { + accessToken: 'stale', + refreshToken: 'bad', + clientId: 'c', + clientSecret: 's' + }) + await expect(instance.submitTask({ content: 'x' })).rejects.toMatchObject({ + kind: 'auth_expired' + }) + }) + + it('静态 token 遇到 401 且无 refresh 时给 auth_expired,错误里不回显 token', async () => { + const fetchImpl = vi.fn(async () => jsonResponse({ code: 401 }, 401)) + const instance = provider(fetchImpl, { accessToken: 'super-secret-token' }) + const error = await instance.submitTask({ content: 'x' }).catch((caught) => caught) + + expect(error).toBeInstanceOf(AgentTaskProviderError) + expect(error.kind).toBe('auth_expired') + expect(String(error.message)).not.toContain('super-secret-token') + }) + + it('403 归类为 auth_expired(scope 不足)', async () => { + const fetchImpl = vi.fn(async () => jsonResponse({ code: 403 }, 403)) + await expect(provider(fetchImpl).checkOnline()).rejects.toMatchObject({ + kind: 'auth_expired', + httpStatus: 403 + }) + }) +}) + +describe('超时与错误分类', () => { + it('请求超时归类为 timeout', async () => { + const fetchImpl = vi.fn( + (_url: unknown, init: RequestInit) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener('abort', () => { + const error = new Error('aborted') + error.name = 'AbortError' + reject(error) + }) + }) + ) + const instance = new WorkBuddyAgentTaskProvider({ + baseUrl: 'https://workbuddy.test', + timeoutMs: 20, + credentials: { accessToken: 'token-1' }, + fetchImpl: fetchImpl as unknown as typeof fetch + }) + + await expect(instance.checkOnline()).rejects.toMatchObject({ kind: 'timeout' }) + }) + + it('5xx 归类为可重试的 http_error', async () => { + const fetchImpl = vi.fn(async () => jsonResponse({ code: 500, msg: 'boom' }, 503)) + await expect(provider(fetchImpl).checkOnline()).rejects.toMatchObject({ + kind: 'http_error', + retryable: true, + httpStatus: 503 + }) + }) + + it('业务 code 非 0 时不当成功', async () => { + const fetchImpl = vi.fn(async () => jsonResponse({ code: 1001, msg: 'denied' })) + await expect(provider(fetchImpl).submitTask({ content: 'x' })).rejects.toMatchObject({ + kind: 'http_error' + }) + }) +}) + +describe('回复解析', () => { + it('从 data.messages 解析 role / content[] / created_at', async () => { + const fetchImpl = vi.fn(async () => + jsonResponse({ + code: 0, + data: { + messages: [ + { + message_id: 'm1', + role: 'assistant', + content: [ + { type: 'text', text: '第一段' }, + { type: 'text', text: '第二段' } + ], + created_at: '2026-10-23T03:00:00Z' + }, + { message_id: 'm2', role: 'system', content: 'plain' } + ] + } + }) + ) + + const replies = await provider(fetchImpl).fetchReplies('m0') + expect(replies).toEqual([ + { + messageId: 'm1', + role: 'assistant', + text: '第一段\n第二段', + createdAt: '2026-10-23T03:00:00Z' + }, + { messageId: 'm2', role: 'other', text: 'plain' } + ]) + + const [url] = callsOf(fetchImpl)[0] + expect(url).toContain('/openapi/v2/localassistant/message?') + expect(url).toContain('message_id=m0') + }) + + it('容错:data 直接是数组 / 缺 message_id 的条目被跳过', () => { + expect( + parseReplies([ + { message_id: 'a', role: 'assistant', content: [{ text: 'hi' }] }, + { role: 'assistant', content: 'no id' } + ]) + ).toEqual([{ messageId: 'a', role: 'assistant', text: 'hi' }]) + }) +}) + +describe('WorkBuddyAccessTokenSource', () => { + it('缓存未过期时复用 token,不发第二次请求', async () => { + const fetchImpl = vi.fn(async () => + jsonResponse({ code: 0, data: { access_token: 'cached', expires_in: 3600 } }) + ) + const source = new WorkBuddyAccessTokenSource({ + baseUrl: 'https://workbuddy.test', + timeoutMs: 500, + credentials: { refreshToken: 'r', clientId: 'c', clientSecret: 's' }, + fetchImpl: fetchImpl as unknown as typeof fetch + }) + + await expect(source.getAccessToken()).resolves.toBe('cached') + await expect(source.getAccessToken()).resolves.toBe('cached') + expect(fetchImpl).toHaveBeenCalledTimes(1) + }) +})