Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(plugins): 自动更新个人统计并补齐回调测试依赖

nana2d8468b9f4a4
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalFileIpc.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalFileIpc.test.ts
index b3165b9610..a54e5ee82f 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalFileIpc.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalFileIpc.test.ts
@@ -294,6 +294,7 @@ function harness(
getLayoutStore: () => ({ getLayout: () => ({}), setLayout: vi.fn() }),
layoutWithGhostPanel: () => null,
spawnIfResident: vi.fn(),
+ bindPluginUsage: vi.fn(async () => {}),
exportGhostPackage: exportPackage,
BrowserWindow: { fromWebContents: () => null },
dialog: { showSaveDialog: vi.fn() },
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalInstallIdentity.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalInstallIdentity.test.ts
index c4e6d26aae..5aa18d0e02 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalInstallIdentity.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalInstallIdentity.test.ts
@@ -25,7 +25,7 @@ describe('local root installation consent identity', () => {
};
const root: InstalledGhost = { ...organization, namespace: null, dir: '/plugins/_ns/_root/helper' };
const packageSha256 = 'a'.repeat(64);
- const prompt = vi.fn(async (_request: Omit<GhostInstallConsentRequest, 'requestId'>) => allow);
+ const prompt = vi.fn<(request: Omit<GhostInstallConsentRequest, 'requestId'>) => Promise<boolean>>(async () => allow);
const release = vi.fn();
const manager = {
list: () => [organization],
@@ -43,7 +43,8 @@ describe('local root installation consent identity', () => {
findInstalledGhostForDeliveryTarget, installedGhostStoragePart,
withGhostInstallLock: async (_id: string, operation: () => unknown) => operation(),
getLayoutStore: () => ({ getLayout: () => ({}) }), layoutWithGhostPanel: () => null,
- spawnIfResident: vi.fn(), markGhostRecommendationInstalled: vi.fn(), log: { warn: vi.fn() },
+ spawnIfResident: vi.fn(), bindPluginUsage: vi.fn(async () => {}),
+ markGhostRecommendationInstalled: vi.fn(), log: { warn: vi.fn() },
});
const installing = callbacks.install({ sender: {} }, '/tmp/helper.cindy', { enable: true, expectedPackageSha256: packageSha256 });
if (allow) {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts
index 62b44e7f47..32e1189427 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts
@@ -217,14 +217,19 @@ it('completes source replacement and another plugin uninstall without reversing
const code = ts.transpileModule(`return (async () => { ${source.slice(start, end)} })();`, {
compilerOptions: { target: ts.ScriptTarget.ES2022 },
}).outputText;
- const remove = new Function('activeOwnerScopeKey', 'pluginTaskUninstaller', 'storagePart', 'manager', 'relId', 'throwUninstallError', code);
+ const remove = new Function('activeOwnerScopeKey', 'pluginTaskUninstaller', 'storagePart', 'manager', 'relId', 'throwUninstallError', 'currentPluginUsageService', 'log', code);
+ const detach = vi.fn(async () => {});
+ const log = { warn: vi.fn() };
const removing = remove(() => scope.dir, (id: string, callback: () => Promise<void>) => service.withUninstall(id, callback),
- '_root__other', manager, '_ns/_root/other', (failure: { reason: string }) => { throw new Error(failure.reason); });
+ '_root__other', manager, '_ns/_root/other', (failure: { reason: string }) => { throw new Error(failure.reason); },
+ () => ({ detach }), log);
await new Promise<void>(resolve => setImmediate(resolve));
finish();
const [updated] = await Promise.all([updating, removing]);
expect(updated).toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });
expect(manager.list().some(ghost => ghost.manifest.id === 'other')).toBe(false);
+ expect(detach).toHaveBeenCalledExactlyOnceWith('_root__other');
+ expect(log.warn).not.toHaveBeenCalled();
expect((await tasks.get('task'))?.pluginId).toBe(archive);
});
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskAccountBoundary.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskAccountBoundary.test.ts
index 3563e1a651..7ea0eeb997 100644
--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskAccountBoundary.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskAccountBoundary.test.ts
@@ -83,7 +83,7 @@ describe('shared-task account boundary cleanup', () => {
expect(site[1]).toContain('releaseOwnership: releaseDeviceLinkOwnershipBeforeLogout');
expect(site[1]).toContain('onClosureFailure: () => markAccountBoundaryAbortedMidTeardown(reason)');
const next = teardown.slice(site.index! + site[0].length).trimStart();
- expect(next).toMatch(/^(?:try \{\s*)?await flushPluginTaskLifecycle\(\);\s*await lifecycleDbClientManager\.dispose\(reason\);/);
+ expect(next).toMatch(/^(?:try \{\s*)?await flushPluginTaskLifecycle\(\);\s*await flushPluginUsageLifecycle\(\);\s*await lifecycleDbClientManager\.dispose\(reason\);/);
}
expect(teardown).not.toContain('await closeSharedTasksBeforeLogout()');
});
diff --git a/apps/desktop/src/renderer/features/plugin/PluginUsageCard.tsx b/apps/desktop/src/renderer/features/plugin/PluginUsageCard.tsx
index 27bfd06ec1..45d0330729 100644
--- a/apps/desktop/src/renderer/features/plugin/PluginUsageCard.tsx
+++ b/apps/desktop/src/renderer/features/plugin/PluginUsageCard.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useId, useState } from 'react';
+import { useCallback, useEffect, useId, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Tip } from '@/components/ui/tooltip';
@@ -16,6 +16,9 @@ export function PluginUsageCard({
const [summary, setSummary] = useState<PluginUsageSummary | null>(null);
const [state, setState] = useState<'loading' | 'ready' | 'failed'>('loading');
const [clearing, setClearing] = useState(false);
+ const clearingRef = useRef(clearing);
+ clearingRef.current = clearing;
+ const [refreshVersion, setRefreshVersion] = useState(0);
const load = useCallback(async () => {
const next = await window.electronAPI.ghosts.usageSummary(ghostId);
if (!next) throw new Error('Usage unavailable');
@@ -23,39 +26,47 @@ export function PluginUsageCard({
}, [ghostId]);
useEffect(() => {
let live = true;
+ let inFlight = false;
setSummary(null);
setState('loading');
- void load()
- .then((value) => {
+ const read = async () => {
+ if (!live || inFlight) return;
+ inFlight = true;
+ try {
+ const value = await load();
if (live) {
setSummary(value);
setState('ready');
}
- })
- .catch(() => {
- if (live) setState('failed');
- });
+ } catch {
+ if (live) {
+ setSummary(null);
+ setState('failed');
+ }
+ } finally {
+ inFlight = false;
+ }
+ };
+ const readWhenVisible = () => {
+ if (document.visibilityState === 'visible' && !clearingRef.current) void read();
+ };
+ void read();
+ const timer = window.setInterval(readWhenVisible, 5_000);
+ document.addEventListener('visibilitychange', readWhenVisible);
return () => {
live = false;
+ window.clearInterval(timer);
+ document.removeEventListener('visibilitychange', readWhenVisible);
};
- }, [load]);
- const refresh = async () => {
- setState('loading');
- try {
- setSummary(await load());
- setState('ready');
- } catch {
- setSummary(null);
- setState('failed');
- }
- };
+ }, [load, refreshVersion]);
+ const refresh = () => setRefreshVersion((value) => value + 1);
const clear = async () => {
if (!summary || clearing || !confirmClear) return;
setClearing(true);
try {
if (!(await confirmClear())) return;
await window.electronAPI.ghosts.clearUsage(summary.subjectId);
- await refresh();
+ refresh();
} catch {
setSummary(null);
setState('failed');
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/PluginUsageCard.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/PluginUsageCard.test.tsx
index 5333cec5b8..12ead2b365 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/PluginUsageCard.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/PluginUsageCard.test.tsx
@@ -1,5 +1,5 @@
// @vitest-environment jsdom
-import { fireEvent, render, screen, waitFor, cleanup } from '@testing-library/react';
+import { act, fireEvent, render, screen, waitFor, cleanup } from '@testing-library/react';
import { afterEach, expect, it, vi } from 'vitest';
import { PluginUsageCard } from '../PluginUsageCard';
import { PluginSharedUsage } from '../PluginSharedUsage';
@@ -12,7 +12,11 @@ vi.mock('react-i18next', () => ({
i18n: { language: 'en' },
}),
}));
-afterEach(cleanup);
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
const summary: PluginUsageSummary = {
subjectId: 'subject1',
recordingStartedAt: 1,
@@ -31,6 +35,71 @@ function api(load = vi.fn(async () => summary)) {
});
return { load, clear };
}
+it('updates recent and rolling usage while the detail remains mounted', async () => {
+ vi.useFakeTimers();
+ const next = { ...summary, lastUsedAt: Date.UTC(2026, 9, 14, 12), callsLast7Days: 8 };
+ const { load } = api(vi.fn().mockResolvedValueOnce(summary).mockResolvedValue(next));
+ const view = render(<PluginUsageCard ghostId="plugin" />);
+ await act(async () => {});
+ const recent = view.container.querySelector('dd')!.textContent;
+ expect(screen.getByText('7')).toBeTruthy();
+ await act(async () => vi.advanceTimersByTimeAsync(5_000));
+ expect(screen.getByText('8')).toBeTruthy();
+ expect(view.container.querySelector('dd')!.textContent).not.toBe(recent);
+ expect(load).toHaveBeenCalledTimes(2);
+ view.unmount();
+ await act(async () => vi.advanceTimersByTimeAsync(10_000));
+ expect(load).toHaveBeenCalledTimes(2);
+});
+it('pauses automatic reads while hidden and refreshes when visible again', async () => {
+ vi.useFakeTimers();
+ const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible');
+ const { load } = api();
+ render(<PluginUsageCard ghostId="plugin" />);
+ await act(async () => {});
+ visibility.mockReturnValue('hidden');
+ await act(async () => vi.advanceTimersByTimeAsync(15_000));
+ expect(load).toHaveBeenCalledTimes(1);
+ visibility.mockReturnValue('visible');
+ await act(async () => fireEvent(document, new Event('visibilitychange')));
+ expect(load).toHaveBeenCalledTimes(2);
+});
+it('does not overlap polling or commit a response from a previous plugin', async () => {
+ vi.useFakeTimers();
+ let complete!: (value: PluginUsageSummary) => void;
+ const pending = new Promise<PluginUsageSummary>((resolve) => { complete = resolve; });
+ const { load } = api(vi.fn().mockResolvedValueOnce(summary).mockReturnValueOnce(pending)
+ .mockResolvedValue({ ...summary, callsLast7Days: 9 }));
+ const view = render(<PluginUsageCard ghostId="first" />);
+ await act(async () => {});
+ await act(async () => vi.advanceTimersByTimeAsync(15_000));
+ expect(load).toHaveBeenCalledTimes(2);
+ view.rerender(<PluginUsageCard ghostId="second" />);
+ await act(async () => {});
+ expect(screen.getByText('9')).toBeTruthy();
+ await act(async () => complete({ ...summary, callsLast7Days: 8 }));
+ expect(screen.queryByText('8')).toBeNull();
+ expect(screen.getByText('9')).toBeTruthy();
+});
+it('holds automatic reads during clear confirmation and ignores a pre-clear response', async () => {
+ vi.useFakeTimers();
+ let complete!: (value: PluginUsageSummary) => void;
+ let confirm!: (value: boolean) => void;
+ const pending = new Promise<PluginUsageSummary>((resolve) => { complete = resolve; });
+ const { load, clear } = api(vi.fn().mockResolvedValueOnce(summary).mockReturnValueOnce(pending)
+ .mockResolvedValue({ ...summary, lastUsedAt: null, callsLast7Days: 0 }));
+ render(<PluginUsageCard ghostId="plugin" confirmClear={() => new Promise(resolve => { confirm = resolve; })} />);
+ await act(async () => {});
+ await act(async () => vi.advanceTimersByTimeAsync(5_000));
+ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.usage.clear' }));
+ await act(async () => vi.advanceTimersByTimeAsync(10_000));
+ expect(load).toHaveBeenCalledTimes(2);
+ await act(async () => confirm(true));
+ expect(clear).toHaveBeenCalledWith('subject1');
+ expect(screen.getByText('0')).toBeTruthy();
+ await act(async () => complete(summary));
+ expect(screen.queryByText('7')).toBeNull();
+});
it('shows two personal metrics with a direct clear action after confirmation', async () => {
const { load, clear } = api();
const confirm = vi.fn(async () => true);
diff --git a/docs/acceptance/plugin-statistics-pr/README.md b/docs/acceptance/plugin-statistics-pr/README.md
index 5ee278595d..05859cb898 100644
--- a/docs/acceptance/plugin-statistics-pr/README.md
+++ b/docs/acceptance/plugin-statistics-pr/README.md
@@ -28,3 +28,11 @@
发布准备在 46f 上合入 canonical main c950b504649f2c64668c618320c352d159370961。主干未改变 migration/schema/锁文件,0126/0127 无撞号,三处测试 mock 合并保留双方新增接口。发布前已运行 52 文件 1072 项 Desktop 定向测试、协议包 165 项测试/类型构建、Desktop 类型检查、迁移静态校验及 14 项回放;当前截图不冒称整合后冷启动截图,统计组件/样式与 46f 相同。
本地全量门禁未执行,等待 PR CI。此次按已授权的影响面验证,未重跑无关整仓;独立 review、评分及插件基座指定 Approve 仍为合并前门禁。真实键盘激活、其他字号档位和长外语布局未验证;本轮未操作正式 profile、宿主、生产服务或数据。
+
+## 首轮审核修复(2026-10-14)
+
+c4aae2ad9 的 CI 中,两平台四分片共用的 6 项失败已在本地复现:账号退出的顺序断言漏了调用统计 flush,安装/卸载回调夹具漏了新增统计依赖。修复保留生产关闭、两类 flush、数据库释放及插件绑定/解绑行为;不改 main 产品代码。
+
+个人卡改为可见时每 5 秒查询本地统计,隐藏暂停、恢复可见即刷新。同一轮不重叠,清除确认期间不启动自动查询,离开实例或清除后不接受旧响应。新增 4 项回归在旧代码上失败;最终 7 文件 95 项测试、Desktop 类型检查及本轮 6 文件 ESLint 通过。卡片渲染和样式源码逐字未变,以上截图仍只说明原版本外观。
+
+本轮未恢复用户已停止的沙盒,未重新执行真实后台调用或实机轮询验收;自动刷新由挂载组件与 IPC 夹具回归覆盖。本地全量门禁未执行,新 head CI 与评分需重新取得。停止前 c4 main/preload/renderer 完整冷启动及三图验收实际已完成,独立 23 文件索引已核对;该记录不能算作本轮刷新修复的 runtime 验收。
diff --git a/docs/plugin-usage-statistics-implementation.md b/docs/plugin-usage-statistics-implementation.md
index 9779f3f033..ab7341bfdd 100644
--- a/docs/plugin-usage-statistics-implementation.md
+++ b/docs/plugin-usage-statistics-implementation.md
@@ -25,7 +25,7 @@
- 列表灰字保留范围、作者(存在时)与累计下载,移出版本和机器 ID。
- 已安装和市场详情的版本旁显示累计共享下载与使用;内容区不超过 520px 时 metadata 放到 hero 下一整行。
-- 个人卡只展示最近调用、近 7 日调用,没有任务列表、图标、分割线、更多菜单或正常态刷新;清除直接放标题右侧,保留确认与取消,失败态仍可重试。
+- 个人卡只展示最近调用、近 7 日调用,没有任务列表、图标、分割线、更多菜单或正常态刷新按钮;清除直接放标题右侧,保留确认与取消,失败态仍可重试。卡片保持打开时每 5 秒查询本地统计,隐藏时暂停、再次可见时读取;同一轮查询不重叠,离开实例或清除后的旧响应不覆盖新读数。
- 使用既有语义 token,双主题实现。标题 14/500/20,时间与次数 14/400/20,标签 12/400/16;padding 16、容器圆角 12、描边 1、间距 12/4/16。卡片跟随父内容宽度、自然高度,字号和行高随既有设置缩放。
真实截图及受测版本边界见 [公开验收摘要](acceptance/plugin-statistics-pr/README.md)。图片为隔离 Electron 中真实页面,不是生成稿或伪造统计。