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 working 活跃改为 30 分钟 (#1038)
Kafeifei07837f3f6602
diff --git a/apps/desktop/src/renderer/__tests__/tapdbConsentGate.test.ts b/apps/desktop/src/renderer/__tests__/tapdbConsentGate.test.tsindex 39411f0a98..441ce2b257 100644--- a/apps/desktop/src/renderer/__tests__/tapdbConsentGate.test.ts+++ b/apps/desktop/src/renderer/__tests__/tapdbConsentGate.test.ts@@ -24,10 +24,35 @@ const tapdb = vi.hoisted(() => ({optOutTracking: vi.fn(),}));+const workingStore = vi.hoisted(() => {+ const listeners = new Set<() => void>();+ let snapshot: ReadonlyMap<string, { isRunning: boolean }> = new Map();+ const subscribeAll = vi.fn((listener: () => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ });+ const getRunningSnapshot = vi.fn(() => snapshot);++ return {+ makerChatStore: { subscribeAll, getRunningSnapshot },+ setRunning(running: boolean): void {+ snapshot = running ? new Map([['session-working', { isRunning: true }]]) : new Map();+ for (const listener of listeners) listener();+ },+ reset(): void {+ listeners.clear();+ snapshot = new Map();+ subscribeAll.mockClear();+ getRunningSnapshot.mockClear();+ },+ };+});+vi.mock('@/vendor/tapdb/tapdb.esm.min.js', () => ({ default: tapdb }));vi.mock('@/lib/logger', () => ({createLogger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),}));+vi.mock('@/lib/makerChatStore', () => ({ makerChatStore: workingStore.makerChatStore }));vi.mock('../../shared/endpoints', () => ({ TAPDB_EVENT_URL: 'https://example.invalid/event' }));type SettingsPayload = {@@ -47,6 +72,7 @@ const visibilityHandlers: Array<() => void> = [];* 只保留最新一个,fireWindowEvent 只打本用例的监听器。*/const windowHandlers = new Map<string, () => void>();+let originalNavigatorLocksDescriptor: PropertyDescriptor | undefined;function fireWindowEvent(type: 'focus' | 'keydown' | 'pointerdown'): void {windowHandlers.get(type)?.();@@ -97,6 +123,50 @@ async function flush(): Promise<void> {await Promise.resolve();}+/**+ * Chromium Web Locks 的最小测试替身:同名请求严格串行,让两个独立 module 实例+ * 能在同一 fake-timer tick 内竞争,再由第二个锁持有者重读 localStorage。+ */+function installSerializedWebLocks() {+ let tail = Promise.resolve();+ const request = vi.fn((name: string, callback: (lock: { name: string }) => void) => {+ const current = tail.then(() => callback({ name }));+ tail = current.then(+ () => undefined,+ () => undefined,+ );+ return current;+ });+ Object.defineProperty(window.navigator, 'locks', {+ configurable: true,+ value: { request },+ });+ return request;+}++function installDeferredWebLock() {+ let acquire: (() => void) | null = null;+ const request = vi.fn(+ (name: string, callback: (lock: { name: string }) => void) =>+ new Promise<void>((resolve, reject) => {+ acquire = () => {+ Promise.resolve(callback({ name })).then(resolve, reject);+ };+ }),+ );+ Object.defineProperty(window.navigator, 'locks', {+ configurable: true,+ value: { request },+ });+ return {+ request,+ acquire(): void {+ if (!acquire) throw new Error('Web Lock request was not queued');+ acquire();+ },+ };+}+const DENIED: SettingsPayload = {privacyConsentAccepted: false,analyticsEnabled: true,@@ -109,10 +179,12 @@ const ALLOWED: SettingsPayload = {};beforeEach(() => {+ originalNavigatorLocksDescriptor = Object.getOwnPropertyDescriptor(window.navigator, 'locks');settingsListener = null;authListener = null;visibilityHandlers.length = 0;windowHandlers.clear();+ workingStore.reset();Object.values(tapdb).forEach((fn) => fn.mockReset());vi.spyOn(document, 'addEventListener').mockImplementation(((type: string,@@ -133,6 +205,11 @@ beforeEach(() => {});afterEach(() => {+ if (originalNavigatorLocksDescriptor) {+ Object.defineProperty(window.navigator, 'locks', originalNavigatorLocksDescriptor);+ } else {+ Reflect.deleteProperty(window.navigator, 'locks');+ }vi.restoreAllMocks();});@@ -279,13 +356,14 @@ describe('TapDB consent gate', () => {// 比初始快照新,旧快照不能把 optInTracking() 又打开。let resolveRead: (payload: SettingsPayload) => void = () => {};installElectronApi(ALLOWED);- (window as unknown as { electronAPI: { getAnalyticsSettings: unknown } }).electronAPI- .getAnalyticsSettings = vi.fn(- () =>- new Promise<SettingsPayload>((resolve) => {- resolveRead = resolve;- }),- );+ (+ window as unknown as { electronAPI: { getAnalyticsSettings: unknown } }+ ).electronAPI.getAnalyticsSettings = vi.fn(+ () =>+ new Promise<SettingsPayload>((resolve) => {+ resolveRead = resolve;+ }),+ );const client = await importClient();client.initTapdb();@@ -363,10 +441,11 @@ describe('TapDB consent gate', () => {it('fails closed when the settings read rejects', async () => {installElectronApi(DENIED);- (window as unknown as { electronAPI: { getAnalyticsSettings: unknown } }).electronAPI- .getAnalyticsSettings = vi.fn(async () => {- throw new Error('ipc down');- });+ (+ window as unknown as { electronAPI: { getAnalyticsSettings: unknown } }+ ).electronAPI.getAnalyticsSettings = vi.fn(async () => {+ throw new Error('ipc down');+ });const client = await importClient();client.initTapdb();@@ -378,8 +457,8 @@ describe('TapDB consent gate', () => {// ── 交互驱动的活跃上报 ───────────────────────────────────────────────────────//-// 活跃事件只由真实交互(focus / keydown / pointerdown)触发,10 分钟节流;没有-// 定时器,0 点不会有任何自发上报。历史背景见 tapdbClient.ts 头部「活跃口径」。+// 活跃事件由真实交互(focus / keydown / pointerdown)或会话 working 触发,+// 共用 30 分钟节流;working timer 不对齐 0 点。历史背景见 tapdbClient.ts 头部。describe('engagement-driven activity reporting', () => {beforeEach(() => {@@ -413,7 +492,7 @@ describe('engagement-driven activity reporting', () => {it('reports app_engaged at most once per throttle window across rapid inputs', async () => {await initAllowed();- vi.advanceTimersByTime(10 * 60 * 1000);+ vi.advanceTimersByTime(30 * 60 * 1000);fireWindowEvent('keydown');fireWindowEvent('keydown');fireWindowEvent('pointerdown');@@ -421,7 +500,7 @@ describe('engagement-driven activity reporting', () => {expect(tapdb.pvEvent).toHaveBeenCalledTimes(2); // app_start + 1 × app_engagedexpect(tapdb.pvEvent).toHaveBeenLastCalledWith({ '#tag': 'app_engaged' });- vi.advanceTimersByTime(10 * 60 * 1000);+ vi.advanceTimersByTime(30 * 60 * 1000);fireWindowEvent('focus');expect(tapdb.pvEvent).toHaveBeenCalledTimes(3);@@ -431,13 +510,113 @@ describe('engagement-driven activity reporting', () => {await initAllowed();for (const type of ['focus', 'keydown', 'pointerdown'] as const) {- vi.advanceTimersByTime(10 * 60 * 1000);+ vi.advanceTimersByTime(30 * 60 * 1000);const before = tapdb.pvEvent.mock.calls.length;fireWindowEvent(type);expect(tapdb.pvEvent.mock.calls.length).toBe(before + 1);}});+ it('reports every 30 minutes while a session remains working', async () => {+ await initAllowed();++ workingStore.setRunning(true);+ expect(tapdb.pvEvent).toHaveBeenCalledTimes(1); // app_start 已占用首个窗口++ vi.advanceTimersByTime(30 * 60 * 1000);+ expect(tapdb.pvEvent).toHaveBeenCalledTimes(2);+ expect(tapdb.pvEvent).toHaveBeenLastCalledWith({ '#tag': 'app_engaged' });++ vi.advanceTimersByTime(30 * 60 * 1000);+ expect(tapdb.pvEvent).toHaveBeenCalledTimes(3);+ expect(tapdb.pvEvent).toHaveBeenLastCalledWith({ '#tag': 'app_engaged' });+ });++ it('starts the rolling report when a session was already working before TapDB initializes', async () => {+ workingStore.setRunning(true);+ await initAllowed();++ expect(tapdb.pvEvent).toHaveBeenCalledTimes(1); // app_start+ vi.advanceTimersByTime(30 * 60 * 1000);++ expect(tapdb.pvEvent).toHaveBeenCalledTimes(2);+ expect(tapdb.pvEvent).toHaveBeenLastCalledWith({ '#tag': 'app_engaged' });+ });++ it('does not postpone the next report when working progress notifies repeatedly', async () => {+ await initAllowed();+ workingStore.setRunning(true);++ vi.advanceTimersByTime(29 * 60 * 1000);+ workingStore.setRunning(true); // 模拟 text/tool progress 的高频全局 notify+ vi.advanceTimersByTime(60 * 1000);++ expect(tapdb.pvEvent).toHaveBeenCalledTimes(2);+ expect(tapdb.pvEvent).toHaveBeenLastCalledWith({ '#tag': 'app_engaged' });+ });++ it('serializes aligned working timers across renderer windows', async () => {+ const lockRequest = installSerializedWebLocks();+ await initAllowed();+ // resetModules 模拟独立 renderer 的 module state;TapDB mock、working store 与+ // localStorage 仍按真实同源窗口共享。+ await initAllowed();+ tapdb.pvEvent.mockClear();++ workingStore.setRunning(true);+ vi.advanceTimersByTime(30 * 60 * 1000);+ await flush();+ await flush();++ expect(lockRequest).toHaveBeenCalledTimes(2);+ expect(tapdb.pvEvent).toHaveBeenCalledTimes(1);+ expect(tapdb.pvEvent).toHaveBeenCalledWith({ '#tag': 'app_engaged' });+ });++ it('drops a queued working report if work stops before the lock is acquired', async () => {+ const lock = installDeferredWebLock();+ await initAllowed();+ tapdb.pvEvent.mockClear();++ workingStore.setRunning(true);+ vi.advanceTimersByTime(30 * 60 * 1000);+ expect(lock.request).toHaveBeenCalledTimes(1);++ workingStore.setRunning(false);+ lock.acquire();+ await flush();+ await flush();++ expect(tapdb.pvEvent).not.toHaveBeenCalled();+ });++ it('stops the rolling report as soon as no session is working', async () => {+ await initAllowed();+ workingStore.setRunning(true);++ vi.advanceTimersByTime(30 * 60 * 1000);+ expect(tapdb.pvEvent).toHaveBeenCalledTimes(2);++ workingStore.setRunning(false);+ vi.advanceTimersByTime(60 * 60 * 1000);++ expect(tapdb.pvEvent).toHaveBeenCalledTimes(2);+ });++ it('shares one throttle window between working and human input', async () => {+ await initAllowed();+ workingStore.setRunning(true);++ vi.advanceTimersByTime(30 * 60 * 1000);+ expect(tapdb.pvEvent).toHaveBeenCalledTimes(2); // working++ fireWindowEvent('keydown');+ expect(tapdb.pvEvent).toHaveBeenCalledTimes(2);++ vi.advanceTimersByTime(30 * 60 * 1000);+ expect(tapdb.pvEvent).toHaveBeenCalledTimes(3); // working 继续+ });+it('sends nothing at local midnight without user input', async () => {// 本次改造的核心断言:过夜挂机不再产生活跃事件,0 点尖峰结构性消失。vi.setSystemTime(new Date(2026, 6, 28, 23, 59, 0));@@ -451,6 +630,24 @@ describe('engagement-driven activity reporting', () => {expect(tapdb.setUser).not.toHaveBeenCalled();});+ it('uses a rolling working timer across midnight instead of firing at 00:00', async () => {+ vi.setSystemTime(new Date(2026, 6, 28, 23, 59, 0));+ await initAllowed();+ authListener?.({ isAuthenticated: true, user: { id: 'user-1' } });+ workingStore.setRunning(true);+ tapdb.pvEvent.mockClear();+ tapdb.setUser.mockClear();++ vi.advanceTimersByTime(2 * 60 * 1000); // 00:01+ workingStore.setRunning(true); // 0 点后的 progress notify 也不能绕过滚动窗口+ expect(tapdb.pvEvent).not.toHaveBeenCalled();+ expect(tapdb.setUser).not.toHaveBeenCalled();++ vi.advanceTimersByTime(28 * 60 * 1000); // 00:29,距上次 app_start 30 分钟+ expect(tapdb.pvEvent).toHaveBeenCalledWith({ '#tag': 'app_engaged' });+ expect(tapdb.setUser).toHaveBeenCalledTimes(1);+ });+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' } });@@ -464,7 +661,7 @@ describe('engagement-driven activity reporting', () => {expect(tapdb.setUser).toHaveBeenCalledTimes(2);// 同日后续窗口只发 pvEvent,不重复 setUser。- vi.advanceTimersByTime(10 * 60 * 1000);+ vi.advanceTimersByTime(30 * 60 * 1000);fireWindowEvent('keydown');expect(tapdb.setUser).toHaveBeenCalledTimes(2);@@ -501,10 +698,10 @@ describe('engagement-driven activity reporting', () => {});it('a window opened before midnight does not swallow the next day’s first interaction', async () => {- // 23:55 上报后窗口本该到 00:05 —— 但已换日,00:03 的交互必须放行并补当日 setUser,+ // 23:55 上报后窗口本该到 00:25 —— 但已换日,00:03 的交互必须放行并补当日 setUser,// 否则「只在次日凌晨窗口内用了一下」的用户从第二天的活跃里整个消失。vi.setSystemTime(new Date(2026, 6, 28, 23, 55, 0));- await initAllowed(); // app_start 消耗窗口至次日 00:05+ await initAllowed(); // app_start 消耗窗口至次日 00:25authListener?.({ isAuthenticated: true, user: { id: 'user-1' } });tapdb.pvEvent.mockClear();tapdb.setUser.mockClear();@@ -522,15 +719,15 @@ describe('engagement-driven activity reporting', () => {await initAllowed();tapdb.pvEvent.mockClear();- vi.advanceTimersByTime(10 * 60 * 1000); // 本窗口内存窗口已过期+ vi.advanceTimersByTime(30 * 60 * 1000); // 本窗口内存窗口已过期window.localStorage.setItem('tapdb.lastEngagedReportAt', String(Date.now() - 30 * 1000));fireWindowEvent('keydown');expect(tapdb.pvEvent).not.toHaveBeenCalled();- // 让位后本窗口对齐共享窗口终点(还剩 9.5 分钟),而不是自己再吃满 10 分钟 ——- // 共享窗口一过就能上报,交替交互不会把间隔拉到近 20 分钟。- vi.advanceTimersByTime(9 * 60 * 1000 + 31 * 1000);+ // 让位后本窗口对齐共享窗口终点(还剩 29.5 分钟),而不是自己再吃满 30 分钟 ——+ // 共享窗口一过就能上报,交替交互不会把间隔拉到近 60 分钟。+ vi.advanceTimersByTime(29 * 60 * 1000 + 31 * 1000);fireWindowEvent('keydown');expect(tapdb.pvEvent).toHaveBeenCalledWith({ '#tag': 'app_engaged' });@@ -552,10 +749,11 @@ describe('engagement-driven activity reporting', () => {it('stops engagement reports immediately after opt-out', async () => {await initAllowed();+ workingStore.setRunning(true);settingsListener?.({ privacyConsentAccepted: true, analyticsEnabled: false, allowed: false });tapdb.pvEvent.mockClear();- vi.advanceTimersByTime(10 * 60 * 1000);+ vi.advanceTimersByTime(60 * 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 cac4c6e397..ef0aa44813 100644--- a/apps/desktop/src/renderer/analytics/tapdbClient.ts+++ b/apps/desktop/src/renderer/analytics/tapdbClient.ts@@ -35,20 +35,22 @@* 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(近期输入 + 聚焦才计使用)。+ * 活跃口径(2026-07-30 起,交互 + 工作驱动):+ * 活跃事件(page_view #tag=app_engaged)由两类真实使用信号触发:+ * - 用户对 Cindy 窗口的动作:窗口获得焦点 / 窗口内按键 / 窗口内按下指针;+ * - Cindy 会话确实处于 makerChatStore 的 running 状态。+ * 两类信号共用 30 分钟节流。running 期间保留一条只在工作时存在的滚动 timer,+ * 避免长工具调用没有 renderer 事件时整小时缺数;工作停止或统计关闭即取消。+ * TapDB 的活跃指标按天与小时去重,账号口径的 setUser(→ user_login,TapDB+ * 账号 DAU 的唯一触发源)跟随当天首条活跃事件发出。** 刻意不做的事:* - 不监听 mousemove(高频)与 wheel(高频且涉及滚动合成路径);纯滚动阅读* 超过节流窗口且全程不点不敲的场景,由下一次 focus / 点击 / 按键兜住- * - 不用定时器、不做跨天检测:第二天的首条事件由用户当天第一次动作自然触发,- * 曾经的 0 点定时续报(main 的 tapdbTimer → tapdb:daily-active 广播)已删,- * 它把所有过夜挂机设备的活跃压在 00:00-00:01,制造小时趋势的 0 点尖峰,- * 且把「进程活着」误报成「用户活跃」+ * - 不做整点/跨天定时续报:第二天首条真人操作会自然触发;持续 running 则按+ * 上次活跃时刻滚动 30 分钟,不对齐 0 点。曾经 main 的 tapdbTimer →+ * tapdb:daily-active 广播会把所有过夜挂机设备压在 00:00-00:01,且把+ * 「进程活着」误报成「用户活跃」,该机制仍保持删除* - 节流状态不持久化:窗口 reload 后最多提前一条,服务端按天去重,无害** SDK 发送层已核实(vendored 1.0.0):未配置 batch 时无 BatchConsumer,每条@@ -60,6 +62,7 @@import TapDBAPI from '@/vendor/tapdb/tapdb.esm.min.js';import { createLogger } from '@/lib/logger';+import { makerChatStore } from '@/lib/makerChatStore';import { TAPDB_EVENT_URL } from '../../shared/endpoints';const log = createLogger('tapdb');@@ -99,14 +102,20 @@ let lastSetUserDate: string | null = null;// ── Engagement throttle ─────────────────────────────────────────────────────-/** 交互活跃上报的节流窗口。远大于单次输入间隔,一天上限 144 条。 */-const ENGAGED_REPORT_INTERVAL_MS = 10 * 60 * 1000;+/** 活跃上报的统一节流窗口。真人交互与 working 共用,一天上限 48 条。 */+const ENGAGED_REPORT_INTERVAL_MS = 30 * 60 * 1000;/*** 跨窗口共享的「上次 app_engaged 上报时刻」localStorage key。detached 侧栏等* 窗口跑同一 renderer 入口,module 态各窗口独立 —— 只靠内存窗口,多窗口交替* 交互会成倍多发 app_engaged。*/const ENGAGED_SHARED_LAST_REPORT_KEY = 'tapdb.lastEngagedReportAt';+/**+ * localStorage 的单次读写同步,但「读 → 判断 → 写」不是跨 renderer 原子事务。+ * working timer 会把多个窗口对齐到同一截止时刻,因此用 Chromium Web Locks+ * 串行化 app_engaged 的领取,并在锁内重读共享时间。+ */+const ENGAGED_SHARED_LOCK_NAME = 'cindy.tapdb.app-engaged';/*** 下一次允许上报活跃的时刻(epoch ms)。仅内存:reload 丢失只会让上报提前一条,* 服务端按天去重,无害。任何 tag 的上报(含 app_start)都会推进它,避免冷启动@@ -115,20 +124,28 @@ const ENGAGED_SHARED_LAST_REPORT_KEY = 'tapdb.lastEngagedReportAt';let nextEngagedReportAt = 0;/*** 上次上报那天的本地午夜(epoch ms)。跨过它意味着换日:即便还在节流窗口内- * (如 23:55 报过、00:03 再交互),也放行补报,否则新一天头 10 分钟的活跃+ * (如 23:55 报过、00:03 再交互),也放行补报,否则新一天头 30 分钟的活跃* (连同当日 setUser)会被前一天的窗口整个吞掉。*/let engagedDayEndsAt = 0;+/** 只在至少一个会话 running 时存在;不对齐整点,避免重造 0 点尖峰。 */+let workingReportTimer: ReturnType<typeof setTimeout> | null = null;+/** makerChatStore 全会话 running 快照订阅。 */+let unsubscribeWorkingState: (() => void) | null = null;+/** 当前 renderer 已有一条 Web Lock 请求在途;高频交互不重复排队。 */+let engagedReportLockPending = false;+/** 在途 working 请求可被后到的真人信号升级,保留跨日立即上报语义。 */+let engagedReportLockAllowsNewDay = false;/**- * 交互信号统一入口(focus / keydown / pointerdown)。绝大多数调用在第一行的- * 数值比较后返回 —— 高频输入路径上零分配、不足 1μs,不碰输入管线。- * 闸检查放在节流窗口推进之前:未放行期间的交互不消耗窗口,放行后首次交互立报。+ * 在当前状态下实际尝试一次上报。Web Lock 路径会在获得锁后再调用这里,+ * 重新读取跨窗口时间并复核闸与节流条件。*/-function onEngagedSignal(): void {+function reportEngagedNowIfDue(allowNewDay: boolean): void {const now = Date.now();- if (now < nextEngagedReportAt && now < engagedDayEndsAt) return;+ if (now < nextEngagedReportAt && (!allowNewDay || now < engagedDayEndsAt)) return;if (!sdkInitialized || !reportingAllowed) return;+ if (!allowNewDay && !hasWorkingSession()) return;try {reportActive('app_engaged');} catch (err) {@@ -136,6 +153,94 @@ function onEngagedSignal(): void {}}+/**+ * 活跃信号统一入口。真人操作允许跨日首条立即上报,保留原有「不吞次日首次+ * 交互」语义;working 只按滚动窗口上报,避免 0 点后的 progress notify 重造尖峰。+ * 闸检查放在节流窗口推进之前:未放行期间的信号不消耗窗口。+ */+function reportEngagedIfDue(allowNewDay: boolean): void {+ const now = Date.now();+ if (now < nextEngagedReportAt && (!allowNewDay || now < engagedDayEndsAt)) return;+ if (!sdkInitialized || !reportingAllowed) return;+ if (engagedReportLockPending) {+ if (allowNewDay) engagedReportLockAllowsNewDay = true;+ return;+ }++ // Cindy 的受控 Electron Chromium 提供 Web Locks。测试/极端兼容环境缺失时+ // 维持原有 localStorage 去重退化路径,不能因统计锁不可用影响主流程。+ const lockManager = navigator.locks;+ if (!lockManager) {+ reportEngagedNowIfDue(allowNewDay);+ return;+ }++ engagedReportLockPending = true;+ engagedReportLockAllowsNewDay = allowNewDay;+ try {+ void lockManager+ .request(ENGAGED_SHARED_LOCK_NAME, () => {+ reportEngagedNowIfDue(engagedReportLockAllowsNewDay);+ })+ .catch((err) => {+ log.warn('engagement Web Lock failed; falling back to local throttle', err);+ reportEngagedNowIfDue(engagedReportLockAllowsNewDay);+ })+ .finally(() => {+ engagedReportLockPending = false;+ engagedReportLockAllowsNewDay = false;+ // working timer 在锁请求期间不另起 1ms 空转;锁释放后按新窗口重新排期。+ syncWorkingReport();+ });+ } catch (err) {+ const fallbackAllowNewDay = engagedReportLockAllowsNewDay;+ engagedReportLockPending = false;+ engagedReportLockAllowsNewDay = false;+ log.warn('engagement Web Lock unavailable; falling back to local throttle', err);+ reportEngagedNowIfDue(fallbackAllowNewDay);+ }+}++/** 真人交互(focus / keydown / pointerdown)入口。 */+function onEngagedSignal(): void {+ reportEngagedIfDue(true);+}++function hasWorkingSession(): boolean {+ for (const info of makerChatStore.getRunningSnapshot().values()) {+ if (info.isRunning) return true;+ }+ return false;+}++function clearWorkingReportTimer(): void {+ if (workingReportTimer === null) return;+ clearTimeout(workingReportTimer);+ workingReportTimer = null;+}++/**+ * 把 working 状态接入既有 app_engaged 路径。状态翻起时立即尝试一次;若被+ * app_start / 真人操作的共享窗口挡住,定时器直接对齐该窗口终点,不会顺延。+ */+function syncWorkingReport(): void {+ if (!sdkInitialized || !reportingAllowed || !hasWorkingSession()) {+ clearWorkingReportTimer();+ return;+ }++ reportEngagedIfDue(false);+ if (engagedReportLockPending) return;+ // makerChatStore 会随 text/tool progress 高频 notify。已有 timer 时保持原定时点,+ // 不在每一帧 clear + 重建;真人操作若推进了窗口,旧 timer 到点后会自行重新对齐。+ if (workingReportTimer !== null) return;+ const delayMs = Math.max(1, nextEngagedReportAt - Date.now());+ workingReportTimer = setTimeout(() => {+ workingReportTimer = null;+ syncWorkingReport();+ }, delayMs);+}+// ── Gate ────────────────────────────────────────────────────────────────────/**@@ -212,6 +317,16 @@ export function initTapdb(): void {log.error('engagement listeners failed (non-fatal)', err);}+ // 复用 Sidebar/通知的全会话 running 真相源。这里不使用+ // sessionBackgroundActivityStore:它的契约明确是纯视觉且接受短暂 stale,不能升级+ // 为统计行为依据,否则一次漏掉 false push 就会产生持续假活跃。+ try {+ unsubscribeWorkingState = makerChatStore.subscribeAll(syncWorkingReport);+ syncWorkingReport();+ } catch (err) {+ log.error('working-state subscription failed (non-fatal)', err);+ }+// page_hide 由本模块自己发,不走 SDK 的 autoTrack —— SDK 的 trackPageHideEvent// 内部用 trackWithBeacon,而那个方法**没有** _isCollectData() 闸(见 vendored// tapdb.esm.min.js)。沿用 SDK 自动上报的话,用户关掉统计后每次切走窗口仍会发出@@ -280,7 +395,10 @@ function applyReportingAllowed(next: boolean): void {// 关闭是用户的明确意图:**先立刻停掉我们自己的上报**,再去管 SDK。这一步不放在// try 里,因为它不可能失败,也绝不该因为后面 SDK 抛异常而回退(fail closed)。- if (!next) reportingAllowed = false;+ if (!next) {+ reportingAllowed = false;+ clearWorkingReportTimer();+ }try {if (!next) {@@ -307,6 +425,7 @@ function applyReportingAllowed(next: boolean): void {if (!sdkInitialized) return;reportingAllowed = true;sdkAppliedAllowed = true;+ syncWorkingReport();return;}@@ -317,6 +436,7 @@ function applyReportingAllowed(next: boolean): void {reportingAllowed = true;sdkAppliedAllowed = true;reportActive('app_start');+ syncWorkingReport();log.info('reporting re-enabled (opt-in)');} catch (err) {// sdkAppliedAllowed 没提交 = 下一次同值广播不会被 guard 挡掉,会重新尝试。@@ -384,7 +504,7 @@ function applySuperProperties(): void {}function reportActive(tag: 'app_start' | 'app_engaged'): void {- // 先推进节流窗口再上报:即便 pvEvent 抛异常,10 分钟内也不再重试(fire-and-forget,+ // 先推进节流窗口再上报:即便 pvEvent 抛异常,30 分钟内也不再重试(fire-and-forget,// 防止持续输入在 SDK 故障时反复触发)。app_start 同样消耗窗口,避免启动瞬间双发。const now = Date.now();nextEngagedReportAt = now + ENGAGED_REPORT_INTERVAL_MS;@@ -402,8 +522,8 @@ function reportActive(tag: 'app_start' | 'app_engaged'): void {now - sharedLast < ENGAGED_REPORT_INTERVAL_MS &&getLocalDateKey(new Date(sharedLast)) === getLocalDateKey(new Date(now))) {- // 让位时本窗口的下一次尝试对齐共享窗口终点,而不是从现在顺延满 10 分钟 ——- // 否则两窗口交替交互会把实际上报间隔拉长到近 20 分钟。+ // 让位时本窗口的下一次尝试对齐共享窗口终点,而不是从现在顺延满 30 分钟 ——+ // 否则两窗口交替交互会把实际上报间隔拉长到近 60 分钟。nextEngagedReportAt = sharedLast + ENGAGED_REPORT_INTERVAL_MS;return;}@@ -457,6 +577,11 @@ export const __testing = {lastSetUserDate = null;nextEngagedReportAt = 0;engagedDayEndsAt = 0;+ engagedReportLockPending = false;+ engagedReportLockAllowsNewDay = false;+ clearWorkingReportTimer();+ unsubscribeWorkingState?.();+ unsubscribeWorkingState = null;try {window.localStorage.removeItem(ENGAGED_SHARED_LAST_REPORT_KEY);} catch {