Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): TapDB 活跃改为交互驱动,消除 0 点尖峰
Kafeifei1d25b4a8cd37
diff --git a/apps/desktop/src/main/__tests__/heartbeatService.test.ts b/apps/desktop/src/main/__tests__/heartbeatService.test.tsindex 6f1c441f94..9c76b8f0ea 100644--- a/apps/desktop/src/main/__tests__/heartbeatService.test.ts+++ b/apps/desktop/src/main/__tests__/heartbeatService.test.ts@@ -136,34 +136,28 @@ describe('heartbeat service app-mode isolation', () => {expect(mocks.createHeartbeatClient.mock.calls[1][0].host.getUid()).toBe('cloud-user-2');});- it('keeps the TapDB daily-active cadence across signed-out, local, and cloud modes', async () => {+ it('never broadcasts to renderers, even across local-midnight boundaries', async () => {+ // 回归钉子:TapDB 的 0 点跨天续报(tapdb:daily-active)已删——它曾把所有过夜+ // 挂机设备的活跃压在 00:00-00:01,在 TapDB 小时趋势上制造 0 点尖峰。活跃现在+ // 由 renderer 侧交互驱动,main 的心跳服务不得再有任何面向 renderer 的广播。const { initHeartbeatService } = await loadService();initHeartbeatService();+ // 连跨三个本地日,期间任意切换 app-mode,都不允许出现广播或多余定时器行为。vi.setSystemTime(new Date(2026, 6, 23, 0, 0, 0));await vi.advanceTimersByTimeAsync(60_000);-pushAuthState(authState('local'));vi.setSystemTime(new Date(2026, 6, 24, 0, 0, 0));await vi.advanceTimersByTimeAsync(60_000);-pushAuthState(authState('cloud', 'cloud-user-1'));vi.setSystemTime(new Date(2026, 6, 25, 0, 0, 0));await vi.advanceTimersByTimeAsync(60_000);+ expect(mocks.rendererSend).not.toHaveBeenCalled();expect(mocks.createHeartbeatClient).toHaveBeenCalledTimes(1);- expect(mocks.rendererSend).toHaveBeenNthCalledWith(1, 'tapdb:daily-active', {- date: '2026-07-23',- });- expect(mocks.rendererSend).toHaveBeenNthCalledWith(2, 'tapdb:daily-active', {- date: '2026-07-24',- });- expect(mocks.rendererSend).toHaveBeenNthCalledWith(3, 'tapdb:daily-active', {- date: '2026-07-25',- });});- it('cleans up both loops and the auth subscription on quit', async () => {+ it('cleans up the heartbeat and the auth subscription on quit', async () => {mocks.authState = authState('cloud', 'cloud-user-1');const { initHeartbeatService } = await loadService();initHeartbeatService();diff --git a/apps/desktop/src/main/heartbeatService.ts b/apps/desktop/src/main/heartbeatService.tsindex 55f4ac8dc2..45858c3ae0 100644--- a/apps/desktop/src/main/heartbeatService.ts+++ b/apps/desktop/src/main/heartbeatService.ts@@ -8,9 +8,13 @@* 云端心跳;signed-out / local 模式不与云端联络(account-free 本地模式的* 隐私语义:本地模式不得向云端上报在线状态)* · cloud 归属人变更时重启心跳(uid 换人),离开 cloud 时停止- * - TapDB 日活节拍独立于云端心跳:任何模式下都按本地日期变更向 renderer 广播- * tapdb:daily-active(纯进程内通知,不产生云端请求)- * - App 退出时显式停心跳、停日活循环并退订 auth,确保不留 dangling timer+ * - App 退出时显式停心跳并退订 auth,确保不留 dangling timer+ *+ * 本服务曾经还承担 TapDB 的跨天日活节拍(60s 检查本地日期,0 点广播+ * tapdb:daily-active 让 renderer 续报)。该机制把所有过夜挂机设备的活跃事件压在+ * 00:00-00:01,在 TapDB 小时趋势上制造 0 点尖峰,且把「进程活着」误报成「用户+ * 活跃」。2026-07-28 起活跃改为 renderer 侧交互驱动(见+ * renderer/analytics/tapdbClient.ts 的「活跃口径」),此处不再有任何 TapDB 逻辑。** 设计原则:* - 跟主 server / IM / scheduler 一样,纯 host 层,不写任何业务逻辑@@ -18,7 +22,7 @@* - 即便 heartbeat-server 完全挂了,这里也不会影响 App 启动或任何业务*/-import { app, BrowserWindow } from 'electron';+import { app } from 'electron';import { createHeartbeatClient, type HeartbeatHandle } from '@cindy/heartbeat-client';import * as authManager from './authManager';import { createLogger } from './logger';@@ -28,15 +32,12 @@ import { getClientEndpoint } from './clientEndpointsService';const log = createLogger('heartbeat');const DEFAULT_INTERVAL_MS = 60_000;-const TAPDB_DAILY_ACTIVE_CHANNEL = 'tapdb:daily-active';type AuthStateSnapshot = ReturnType<typeof authManager.getAuthState>;let handle: HeartbeatHandle | null = null;let handleUid: string | null = null;-let tapdbTimer: NodeJS.Timeout | null = null;let unsubscribeAuth: (() => void) | null = null;-let lastTapdbActiveDate = getLocalDateKey();/** 已验证 cloud 会话返回其 user.id,其余模式一律 null(= 不上报云端心跳)。 */function verifiedCloudUserId(state: AuthStateSnapshot): string | null {@@ -87,56 +88,20 @@ function applyAuthState(state: AuthStateSnapshot): void {}export function initHeartbeatService(): void {- if (handle || tapdbTimer || unsubscribeAuth) {+ if (handle || unsubscribeAuth) {log.warn('initHeartbeatService called twice, ignoring');return;}- // TapDB 日活循环独立于云端心跳:signed-out / local 模式也要有本地日活节拍。- tapdbTimer = setInterval(() => {- emitTapdbDailyActiveIfNeeded();- }, DEFAULT_INTERVAL_MS);-unsubscribeAuth = authManager.onAuthStateChange((state) => {applyAuthState(state);});applyAuthState(authManager.getAuthState());- // App quit 时显式停掉,虽然进程退出 timer 自然消亡,但保留一个干净的 shutdown 路径+ // App quit 时显式停掉,保留一个干净的 shutdown 路径onQuit('heartbeat', () => {stopCloudHeartbeat();- if (tapdbTimer) {- clearInterval(tapdbTimer);- tapdbTimer = null;- }unsubscribeAuth?.();unsubscribeAuth = null;});}--function emitTapdbDailyActiveIfNeeded(): void {- const today = getLocalDateKey();- if (lastTapdbActiveDate === today) return;-- lastTapdbActiveDate = today;- broadcastToRenderers(TAPDB_DAILY_ACTIVE_CHANNEL, { date: today });- log.info(`tapdb daily active tick ${today}`);-}--function broadcastToRenderers(channel: string, payload: unknown): void {- for (const win of BrowserWindow.getAllWindows()) {- if (win.isDestroyed()) continue;- try {- win.webContents.send(channel, payload);- } catch (err) {- log.warn(`broadcast '${channel}' to window failed (non-fatal)`, err);- }- }-}--function getLocalDateKey(date = new Date()): string {- const year = date.getFullYear();- const month = String(date.getMonth() + 1).padStart(2, '0');- const day = String(date.getDate()).padStart(2, '0');- return `${year}-${month}-${day}`;-}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 2e2e1297f7..da74115134 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -295,7 +295,6 @@ const fanOutComputerPermissionGuideStatusChanged = createIpcFanOut(const fanOutAppUpdateProgress = createIpcFanOut('app-update-progress');const fanOutAuthStateChange = createIpcFanOut('auth:state-change');const fanOutAuthSessionExpired = createIpcFanOut('auth:session-expired');-const fanOutTapdbDailyActive = createIpcFanOut('tapdb:daily-active');// 使用统计(TapDB)的同意状态 / 开关变化;renderer 据此即时 init 或 opt-outconst fanOutAnalyticsSettingsChange = createIpcFanOut(ANALYTICS_SETTINGS_CHANGE_CHANNEL);const fanOutFullscreenChange = createIpcFanOut('fullscreen-change');@@ -1327,16 +1326,6 @@ contextBridge.exposeInMainWorld('electronAPI', {}): Promise<{ ok: true }> => ipcRenderer.invoke('profile:update', params),onAuthStateChange: fanOutAuthStateChange,onAuthSessionExpired: fanOutAuthSessionExpired,- onTapdbDailyActive: (callback: (payload: { date: string }) => void): (() => void) =>- fanOutTapdbDailyActive((payload) => {- if (- payload &&- typeof payload === 'object' &&- typeof (payload as { date?: unknown }).date === 'string'- ) {- callback(payload as { date: string });- }- }),// ── 使用统计(TapDB)同意闸 ──// 真相在 main(<userData>/analytics-settings.json);renderer 只读结论、只提交diff --git a/apps/desktop/src/renderer/__tests__/tapdbConsentGate.test.ts b/apps/desktop/src/renderer/__tests__/tapdbConsentGate.test.tsindex d95c870c61..01145c39f0 100644--- a/apps/desktop/src/renderer/__tests__/tapdbConsentGate.test.ts+++ b/apps/desktop/src/renderer/__tests__/tapdbConsentGate.test.ts@@ -41,6 +41,16 @@ let authListener: ((state: unknown) => void) | null = null;let getAnalyticsSettings: () => Promise<SettingsPayload>;/** 本文件内注册过的 visibilitychange 回调(见 hidePage)。 */const visibilityHandlers: Array<() => void> = [];+/**+ * tapdbClient 挂在 window 上的交互监听(focus / keydown / pointerdown)。+ * 与 visibilityHandlers 同理,每个 importClient 都会重新注册,这里按事件类型+ * 只保留最新一个,fireWindowEvent 只打本用例的监听器。+ */+const windowHandlers = new Map<string, () => void>();++function fireWindowEvent(type: 'focus' | 'keydown' | 'pointerdown'): void {+ windowHandlers.get(type)?.();+}function installElectronApi(initial: SettingsPayload): void {getAnalyticsSettings = vi.fn(async () => initial);@@ -60,7 +70,6 @@ function installElectronApi(initial: SettingsPayload): void {authListener = null;};},- onTapdbDailyActive: () => () => {},};}@@ -103,6 +112,7 @@ beforeEach(() => {settingsListener = null;authListener = null;visibilityHandlers.length = 0;+ windowHandlers.clear();Object.values(tapdb).forEach((fn) => fn.mockReset());vi.spyOn(document, 'addEventListener').mockImplementation(((type: string,@@ -112,6 +122,14 @@ beforeEach(() => {visibilityHandlers.push(() => handler(new Event('visibilitychange')));}}) as typeof document.addEventListener);+ vi.spyOn(window, 'addEventListener').mockImplementation(((+ type: string,+ handler: EventListenerOrEventListenerObject,+ ) => {+ if (typeof handler === 'function') {+ windowHandlers.set(type, () => handler(new Event(type)));+ }+ }) as typeof window.addEventListener);});afterEach(() => {@@ -357,3 +375,121 @@ describe('TapDB consent gate', () => {expect(tapdb.init).not.toHaveBeenCalled();});});++// ── 交互驱动的活跃上报 ───────────────────────────────────────────────────────+//+// 活跃事件只由真实交互(focus / keydown / pointerdown)触发,10 分钟节流;没有+// 定时器,0 点不会有任何自发上报。历史背景见 tapdbClient.ts 头部「活跃口径」。++describe('engagement-driven activity reporting', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date(2026, 6, 28, 12, 0, 0));+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ async function initAllowed() {+ installElectronApi(ALLOWED);+ const client = await importClient();+ client.initTapdb();+ await flush();+ return client;+ }++ it('app_start consumes the throttle window — input right after startup does not double-report', async () => {+ await initAllowed();+ expect(tapdb.pvEvent).toHaveBeenCalledTimes(1); // app_start++ fireWindowEvent('keydown');++ expect(tapdb.pvEvent).toHaveBeenCalledTimes(1);+ });++ it('reports app_engaged at most once per throttle window across rapid inputs', async () => {+ await initAllowed();++ vi.advanceTimersByTime(10 * 60 * 1000);+ fireWindowEvent('keydown');+ fireWindowEvent('keydown');+ fireWindowEvent('pointerdown');++ expect(tapdb.pvEvent).toHaveBeenCalledTimes(2); // app_start + 1 × app_engaged+ expect(tapdb.pvEvent).toHaveBeenLastCalledWith({ '#tag': 'app_engaged' });++ vi.advanceTimersByTime(10 * 60 * 1000);+ fireWindowEvent('focus');++ expect(tapdb.pvEvent).toHaveBeenCalledTimes(3);+ });++ it('each of focus / keydown / pointerdown can trigger a report', async () => {+ await initAllowed();++ for (const type of ['focus', 'keydown', 'pointerdown'] as const) {+ vi.advanceTimersByTime(10 * 60 * 1000);+ const before = tapdb.pvEvent.mock.calls.length;+ fireWindowEvent(type);+ expect(tapdb.pvEvent.mock.calls.length).toBe(before + 1);+ }+ });++ it('sends nothing at local midnight without user input', async () => {+ // 本次改造的核心断言:过夜挂机不再产生活跃事件,0 点尖峰结构性消失。+ vi.setSystemTime(new Date(2026, 6, 28, 23, 59, 0));+ await initAllowed();+ tapdb.pvEvent.mockClear();+ tapdb.setUser.mockClear();++ vi.advanceTimersByTime(2 * 60 * 1000); // 23:59 → 次日 00:01,期间无交互++ expect(tapdb.pvEvent).not.toHaveBeenCalled();+ expect(tapdb.setUser).not.toHaveBeenCalled();+ });++ it('first engagement of a new day re-binds the account, later windows do not', async () => {+ await initAllowed();+ authListener?.({ isAuthenticated: true, user: { id: 'user-1' } });+ expect(tapdb.setUser).toHaveBeenCalledTimes(1); // 当天登录时绑定++ // 次日 09:00 用户回来:首条交互既发 app_engaged,也重新 setUser(账号 DAU)。+ vi.setSystemTime(new Date(2026, 6, 29, 9, 0, 0));+ fireWindowEvent('pointerdown');++ expect(tapdb.pvEvent).toHaveBeenLastCalledWith({ '#tag': 'app_engaged' });+ expect(tapdb.setUser).toHaveBeenCalledTimes(2);++ // 同日后续窗口只发 pvEvent,不重复 setUser。+ vi.advanceTimersByTime(10 * 60 * 1000);+ fireWindowEvent('keydown');++ expect(tapdb.setUser).toHaveBeenCalledTimes(2);+ });++ it('ignores input while unconsented, then reports normally after consent', async () => {+ installElectronApi(DENIED);+ const client = await importClient();+ client.initTapdb();+ await flush();++ fireWindowEvent('keydown');+ expect(tapdb.pvEvent).not.toHaveBeenCalled();++ // 未放行期间的交互不消耗节流窗口:同意后立刻能发 app_start。+ settingsListener?.(ALLOWED);+ expect(tapdb.pvEvent).toHaveBeenCalledWith({ '#tag': 'app_start' });+ });++ it('stops engagement reports immediately after opt-out', async () => {+ await initAllowed();+ settingsListener?.({ privacyConsentAccepted: true, analyticsEnabled: false, allowed: false });+ tapdb.pvEvent.mockClear();++ vi.advanceTimersByTime(10 * 60 * 1000);+ fireWindowEvent('keydown');++ expect(tapdb.pvEvent).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/renderer/analytics/tapdbClient.ts b/apps/desktop/src/renderer/analytics/tapdbClient.tsindex 19c9722662..2e4dd15320 100644--- a/apps/desktop/src/renderer/analytics/tapdbClient.ts+++ b/apps/desktop/src/renderer/analytics/tapdbClient.ts@@ -35,6 +35,25 @@* page_hide 由 reportPageHide 自行守闸* - 重新打开 → optInTracking() 并补一次 app_start*+ * 活跃口径(2026-07-28 起,交互驱动):+ * 活跃事件(page_view #tag=app_engaged)只由用户对 Cindy 窗口的真实动作触发:+ * 窗口获得焦点 / 窗口内按键 / 窗口内按下指针,10 分钟内存节流。TapDB 的活跃+ * 指标按天与小时去重,事件时间戳因此落在真实使用时刻;账号口径的 setUser+ * (→ user_login,TapDB 账号 DAU 的唯一触发源)跟随当天首条活跃事件发出。+ * 桌面端同类先例:Firefox active ticks(近期输入 + 聚焦才计使用)。+ *+ * 刻意不做的事:+ * - 不监听 mousemove(高频)与 wheel(高频且涉及滚动合成路径);纯滚动阅读+ * 超过节流窗口且全程不点不敲的场景,由下一次 focus / 点击 / 按键兜住+ * - 不用定时器、不做跨天检测:第二天的首条事件由用户当天第一次动作自然触发,+ * 曾经的 0 点定时续报(main 的 tapdbTimer → tapdb:daily-active 广播)已删,+ * 它把所有过夜挂机设备的活跃压在 00:00-00:01,制造小时趋势的 0 点尖峰,+ * 且把「进程活着」误报成「用户活跃」+ * - 节流状态不持久化:窗口 reload 后最多提前一条,服务端按天去重,无害+ *+ * SDK 发送层已核实(vendored 1.0.0):未配置 batch 时无 BatchConsumer,每条+ * 事件独立 AjaxTask 即发即弃(失败至多原地重试 3 次后丢弃),不存在堆积面。+ ** Overlay 窗口(voice-input-overlay / voice-input-dictionary-toast)不引入此模块,* 避免一次浮窗弹出被算成一次 PV。*/@@ -76,9 +95,34 @@ let sdkAppliedAllowed: boolean | null = null;/** 每收到一次广播 +1;用于丢弃 IPC 往返期间已经过期的初始快照。 */let settingsEpoch = 0;let currentUserId: string | null = null;-let lastActiveDate: string | null = null;let lastSetUserDate: string | null = null;+// ── Engagement throttle ─────────────────────────────────────────────────────++/** 交互活跃上报的节流窗口。远大于单次输入间隔,一天上限 144 条。 */+const ENGAGED_REPORT_INTERVAL_MS = 10 * 60 * 1000;+/**+ * 下一次允许上报活跃的时刻(epoch ms)。仅内存:reload 丢失只会让上报提前一条,+ * 服务端按天去重,无害。任何 tag 的上报(含 app_start)都会推进它,避免冷启动+ * app_start 后紧跟的第一次点击立刻再发一条。+ */+let nextEngagedReportAt = 0;++/**+ * 交互信号统一入口(focus / keydown / pointerdown)。绝大多数调用在第一行的+ * 数值比较后返回 —— 高频输入路径上零分配、不足 1μs,不碰输入管线。+ * 闸检查放在节流窗口推进之前:未放行期间的交互不消耗窗口,放行后首次交互立报。+ */+function onEngagedSignal(): void {+ if (Date.now() < nextEngagedReportAt) return;+ if (!sdkInitialized || !reportingAllowed) return;+ try {+ reportActive('app_engaged');+ } catch (err) {+ log.error('engaged report failed (non-fatal)', err);+ }+}+// ── Gate ────────────────────────────────────────────────────────────────────/**@@ -124,18 +168,14 @@ export function initTapdb(): void {log.error('onAuthStateChange subscription failed (non-fatal)', err);}- // 跨天检测复用 main 进程 heartbeat 的 60s 节拍;renderer 只负责调用 TapDB SDK。+ // 交互驱动的活跃信号(见文件头「活跃口径」)。capture 挂在 window 捕获阶段,+ // 业务代码的 stopPropagation 挡不住;onEngagedSignal 自带节流与同意闸。try {- window.electronAPI.onTapdbDailyActive((payload) => {- try {- if (!sdkInitialized || !reportingAllowed) return;- reportActive('app_daily_active', payload.date);- } catch (err) {- log.error('daily active report failed (non-fatal)', err);- }- });+ window.addEventListener('focus', onEngagedSignal);+ window.addEventListener('keydown', onEngagedSignal, { capture: true });+ window.addEventListener('pointerdown', onEngagedSignal, { capture: true });} catch (err) {- log.error('daily active subscription failed (non-fatal)', err);+ log.error('engagement listeners failed (non-fatal)', err);}// page_hide 由本模块自己发,不走 SDK 的 autoTrack —— SDK 的 trackPageHideEvent@@ -222,7 +262,6 @@ function applyReportingAllowed(next: boolean): void {// autoTrack.pageHide,改由 reportPageHide 自己守闸(见 initTapdb)。TapDBAPI.optOutTracking();sdkAppliedAllowed = false;- lastActiveDate = null;lastSetUserDate = null;log.info('reporting disabled (opt-out)');return;@@ -310,14 +349,15 @@ function applySuperProperties(): void {});}-function reportActive(tag: 'app_start' | 'app_daily_active', dateKey = getLocalDateKey()): void {- const today = dateKey;- if (lastActiveDate === today && tag === 'app_daily_active') return;+function reportActive(tag: 'app_start' | 'app_engaged'): void {+ // 先推进节流窗口再上报:即便 pvEvent 抛异常,10 分钟内也不再重试(fire-and-forget,+ // 防止持续输入在 SDK 故障时反复触发)。app_start 同样消耗窗口,避免启动瞬间双发。+ nextEngagedReportAt = Date.now() + ENGAGED_REPORT_INTERVAL_MS;TapDBAPI.pvEvent({ '#tag': tag });- lastActiveDate = today;- log.info(`active ${tag} ${today}`);+ log.info(`active ${tag}`);+ const today = getLocalDateKey();if (currentUserId !== null && lastSetUserDate !== today) {reportSetUser(currentUserId, tag, today);}@@ -325,7 +365,7 @@ function reportActive(tag: 'app_start' | 'app_daily_active', dateKey = getLocalDfunction reportSetUser(userId: string,- reason: 'auth_state' | 'app_daily_active' | 'app_start',+ reason: 'auth_state' | 'app_engaged' | 'app_start',dateKey = getLocalDateKey(),): void {TapDBAPI.setUser(userId);@@ -348,7 +388,7 @@ export const __testing = {sdkAppliedAllowed = null;settingsEpoch = 0;currentUserId = null;- lastActiveDate = null;lastSetUserDate = null;+ nextEngagedReportAt = 0;},};diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 5958a8b214..4f351f2934 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1541,7 +1541,6 @@ interface ElectronAPI {authConsumeAccountDeletionRestoredNotice: () => Promise<boolean>;onAuthStateChange: (callback: (state: AuthStateChangePayload) => void) => () => void;onAuthSessionExpired: (callback: (state: AuthSessionExpiredPayload) => void) => () => void;- onTapdbDailyActive: (callback: (payload: { date: string }) => void) => () => void;// ── 使用统计(TapDB)同意闸 ──getAnalyticsSettings: () => Promise<AnalyticsSettingsPayload>;