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(cindy-make): filter hidden tasks from usage surfaces

MagicLizi1cd6c4fdfc49
diff --git a/apps/desktop/src/main/localDb/__tests__/dailySessionUsage.db.test.ts b/apps/desktop/src/main/localDb/__tests__/dailySessionUsage.db.test.ts
index a15291cab0..0428966f8e 100644
--- a/apps/desktop/src/main/localDb/__tests__/dailySessionUsage.db.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/dailySessionUsage.db.test.ts
@@ -15,17 +15,18 @@ beforeEach(() => {
CREATE TABLE sessions (
id TEXT PRIMARY KEY, title TEXT NOT NULL, model TEXT NOT NULL, provider_id TEXT,
status TEXT NOT NULL, context_tokens INTEGER NOT NULL DEFAULT 0,
- context_window INTEGER NOT NULL DEFAULT 0, user_send_at INTEGER, updated_at INTEGER NOT NULL
+ context_window INTEGER NOT NULL DEFAULT 0, user_send_at INTEGER, updated_at INTEGER NOT NULL,
+ source TEXT
);
CREATE TABLE daily_session_usage (
day TEXT NOT NULL, session_id TEXT NOT NULL, tokens INTEGER NOT NULL DEFAULT 0,
updated_at INTEGER NOT NULL, PRIMARY KEY (day, session_id)
);
INSERT INTO sessions VALUES
- ('old', 'Renamed later', 'gpt-5.5', 'openai', 'active', 10, 100, 50, 40),
- ('recent', 'Recent', 'claude', NULL, 'archived', 0, 0, NULL, 70),
- ('gone', 'Deleted', 'gpt-5.5', NULL, 'deleted', 0, 0, NULL, 80),
- ('unused', 'No usage', 'gpt-5.5', NULL, 'active', 0, 0, NULL, 90);
+ ('old', 'Renamed later', 'gpt-5.5', 'openai', 'active', 10, 100, 50, 40, NULL),
+ ('recent', 'Recent', 'claude', NULL, 'archived', 0, 0, NULL, 70, NULL),
+ ('gone', 'Deleted', 'gpt-5.5', NULL, 'deleted', 0, 0, NULL, 80, NULL),
+ ('unused', 'No usage', 'gpt-5.5', NULL, 'active', 0, 0, NULL, 90, NULL);
INSERT INTO daily_session_usage VALUES
('2026-09-01', 'old', 5, 1), ('2026-09-01', 'gone', 6, 1),
('2026-09-25', 'recent', 7, 1), ('2026-09-25', 'gone', 8, 1);
@@ -55,6 +56,7 @@ describe('daily session usage SQL', () => {
title: 'Renamed later',
model: 'gpt-5.5',
providerId: 'openai',
+ source: null,
contextTokens: 10,
contextWindow: 100,
lastActiveAt: 50,
@@ -66,4 +68,11 @@ describe('daily session usage SQL', () => {
expect(usage.rows).toEqual([{ day: '2026-09-25', sessionId: 'recent', tokens: 7 }]);
expect(usage.tasks.map((task) => task.sessionId).sort()).toEqual(['old', 'recent']);
});
+
+ it.each(['cindy-make', 'cindy-make-merge'])('preserves %s metadata and accounting rows', async (source) => {
+ sqlite.prepare('UPDATE sessions SET source = ? WHERE id = ?').run(source, 'recent');
+ const usage = await getSessionUsageSince('2026-09-20');
+ expect(usage.tasks.find((task) => task.sessionId === 'recent')).toMatchObject({ source });
+ expect(usage.rows).toEqual([{ day: '2026-09-25', sessionId: 'recent', tokens: 7 }]);
+ });
});
diff --git a/apps/desktop/src/main/localDb/dailySessionUsage.ts b/apps/desktop/src/main/localDb/dailySessionUsage.ts
index dfc11492b9..7651a5c8ab 100644
--- a/apps/desktop/src/main/localDb/dailySessionUsage.ts
+++ b/apps/desktop/src/main/localDb/dailySessionUsage.ts
@@ -17,6 +17,7 @@ export interface UsageTaskMeta {
title: string;
model: string;
providerId: string | null;
+ source?: string | null;
contextTokens: number;
contextWindow: number;
/** userSendAt 与 updatedAt 中较新者 (unix ms)。 */
@@ -53,6 +54,7 @@ export async function getUsageTaskMeta(): Promise<UsageTaskMeta[]> {
title: sessions.title,
model: sessions.model,
providerId: sessions.providerId,
+ source: sessions.source,
contextTokens: sessions.contextTokens,
contextWindow: sessions.contextWindow,
userSendAt: sessions.userSendAt,
@@ -74,6 +76,7 @@ export async function getUsageTaskMeta(): Promise<UsageTaskMeta[]> {
title: row.title,
model: row.model,
providerId: row.providerId ?? null,
+ source: row.source ?? null,
contextTokens: row.contextTokens ?? 0,
contextWindow: row.contextWindow ?? 0,
lastActiveAt: Math.max(row.userSendAt ?? 0, row.updatedAt),
diff --git a/apps/desktop/src/main/menubar/__tests__/collect.test.ts b/apps/desktop/src/main/menubar/__tests__/collect.test.ts
index d01c682883..b129f168e2 100644
--- a/apps/desktop/src/main/menubar/__tests__/collect.test.ts
+++ b/apps/desktop/src/main/menubar/__tests__/collect.test.ts
@@ -12,6 +12,7 @@ import {
type MenubarCollectDeps,
} from '../collect';
import { topModels, type MenubarSubscriptionInput } from '../snapshot';
+import type { UsageHistoryPayload, UsageHistoryTask } from '../../usage/usageHistory';
const NOW = Date.UTC(2026, 9, 11, 3, 0, 0);
const nowSec = NOW / 1000;
@@ -102,6 +103,31 @@ describe('source mapping', () => {
});
describe('collectMenubarInputs', () => {
+ function task(sessionId: string, source?: string | null): UsageHistoryTask {
+ return {
+ taskKey: 'local:' + sessionId,
+ deviceId: 'local',
+ sessionId,
+ title: sessionId,
+ model: 'gpt-5.5',
+ providerId: null,
+ source,
+ contextTokens: 0,
+ contextWindow: 0,
+ lastActiveAt: NOW,
+ };
+ }
+
+ function usage(tasks: UsageHistoryTask[]): UsageHistoryPayload {
+ const money = { amount: 1, currency: 'USD', approximate: false, kind: 'actual-cost' } as const;
+ return {
+ todayKey: '2026-10-11',
+ modelDaily: [{ day: '2026-10-11', agentKind: 'codex', model: 'gpt-5.5', tokens: 1000, money, apiMoney: money, subscriptionEstimateMoney: money }],
+ tasks,
+ taskDaily: tasks.map((entry, index) => ({ day: '2026-10-11', taskKey: entry.taskKey, tokens: 100 - index })),
+ } as UsageHistoryPayload;
+ }
+
function deps(overrides: Partial<MenubarCollectDeps> = {}): MenubarCollectDeps {
return {
nowMs: NOW,
@@ -169,6 +195,39 @@ describe('collectMenubarInputs', () => {
]);
expect(collected.usage.days).toHaveLength(90);
});
+
+ it.each(['cindy-make', 'cindy-make-merge'])('hides %s usage tasks without changing accounting totals', async (source) => {
+ const input = usage([task('hidden', source), task('ordinary', null)]);
+ const collected = await collectMenubarInputs(deps({ readUsage: async () => input }));
+
+ expect(collected.tasks.map((entry) => entry.sessionId)).toEqual(['ordinary']);
+ expect(collected.tasks[0].tokensToday).toBe(99);
+ expect(collected.usage.scopes.local.daily.at(-1)).toEqual({ money: [0, 1, 0], paid: 1, tokens: [0, 1000, 0] });
+ expect(input.taskDaily).toHaveLength(2);
+ expect(input.tasks).toHaveLength(2);
+ });
+
+ it.each(['cindy-make', 'cindy-make-merge'])('checks live %s sources for legacy usage and running-only tasks', async (source) => {
+ const input = usage([task('legacy'), task('ordinary')]);
+ const collected = await collectMenubarInputs(deps({
+ readUsage: async () => input,
+ activities: () => [{ sessionId: 'running-only', phase: 'running', startedAtMs: NOW - 1000 } as never],
+ sessionRow: async (sessionId) => ({ title: sessionId, model: 'gpt-5.5', agentKind: 'codex', source: sessionId === 'ordinary' ? null : source }),
+ }));
+
+ expect(collected.tasks.map((entry) => entry.sessionId)).toEqual(['ordinary']);
+ });
+
+ it('applies the visible task limit after filtering live sources', async () => {
+ const hiddenIds = Array.from({ length: 35 }, (_, index) => 'hidden-' + index);
+ const ordinaryIds = Array.from({ length: 31 }, (_, index) => 'ordinary-' + index);
+ const collected = await collectMenubarInputs(deps({
+ activities: () => [...hiddenIds, ...ordinaryIds].map((sessionId) => ({ sessionId, phase: 'running', startedAtMs: NOW - 1000 } as never)),
+ sessionRow: async (sessionId) => ({ title: sessionId, model: 'gpt-5.5', agentKind: 'codex', source: sessionId.startsWith('hidden-') ? 'cindy-make' : null }),
+ }));
+
+ expect(collected.tasks.map((entry) => entry.sessionId)).toEqual(ordinaryIds.slice(0, 30));
+ });
});
describe('distinctRemoteSubscriptions', () => {
diff --git a/apps/desktop/src/main/menubar/collect.ts b/apps/desktop/src/main/menubar/collect.ts
index 6a76e1868d..1e721cbddb 100644
--- a/apps/desktop/src/main/menubar/collect.ts
+++ b/apps/desktop/src/main/menubar/collect.ts
@@ -7,6 +7,7 @@
*/
import type { ProviderView } from '@cindy/model-providers';
+import { CINDY_MAKE_ENABLED, isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';
import { matchCodexBucketForModel } from '@cindy/maker-shared/codex-usage-buckets';
import type {
ClaudeSubscriptionUsageSnapshot,
@@ -62,6 +63,7 @@ export interface MenubarSessionRow {
title: string | null;
model: string | null;
agentKind: string | null;
+ source?: string | null;
}
export interface MenubarCollectDeps {
@@ -564,37 +566,42 @@ async function collectTasks(
if (isSessionActivityRunning(activity)) ids.add(sessionId);
}
const ranked = [...ids]
+ .filter((sessionId) => CINDY_MAKE_ENABLED || !isCindyMakeSource(meta.get(sessionId)?.source))
.sort((a, b) => {
const runningA = activities.get(a) && isSessionActivityRunning(activities.get(a)!) ? 1 : 0;
const runningB = activities.get(b) && isSessionActivityRunning(activities.get(b)!) ? 1 : 0;
return runningB - runningA || (tokensBySession.get(b) ?? 0) - (tokensBySession.get(a) ?? 0);
- })
- .slice(0, MAX_TASK_ROWS);
-
- const rows = await Promise.all(
- ranked.map(async (sessionId): Promise<MenubarTaskInput | null> => {
- const row = await safe(`session:${sessionId}`, () => deps.sessionRow(sessionId), null);
- const info = meta.get(sessionId);
- const activity = activities.get(sessionId);
- const model = info?.model || row?.model || '';
- const title = row?.title?.trim() || info?.title?.trim() || '';
- if (!title && !model) return null;
- const tokens = tokensBySession.get(sessionId) ?? 0;
- const rate = rates.get(model);
- const running = activity ? isSessionActivityRunning(activity) : false;
- return {
- sessionId,
- title,
- harness: harnessOf(row?.agentKind ?? rate?.harness),
- model: model ? formatModelShort(model) : '',
- tokensToday: tokens,
- valueToday: rate && rate.tokens > 0 ? (tokens * rate.money) / rate.tokens : 0,
- contextPercent: info && info.contextWindow > 0 ? clampPercent((info.contextTokens / info.contextWindow) * 100) : null,
- running,
- startedAtMs: running ? (activity?.startedAtMs ?? null) : null,
- lastActiveAtMs: activity?.lastActivityAtMs ?? info?.lastActiveAt ?? deps.nowMs,
- };
- }),
- );
- return rows.filter((row): row is MenubarTaskInput => row !== null);
+ });
+
+ const rows: MenubarTaskInput[] = [];
+ for (let offset = 0; offset < ranked.length && rows.length < MAX_TASK_ROWS; offset += MAX_TASK_ROWS) {
+ const batch = await Promise.all(
+ ranked.slice(offset, offset + MAX_TASK_ROWS).map(async (sessionId): Promise<MenubarTaskInput | null> => {
+ const row = await safe(`session:${sessionId}`, () => deps.sessionRow(sessionId), null);
+ if (!CINDY_MAKE_ENABLED && isCindyMakeSource(row?.source)) return null;
+ const info = meta.get(sessionId);
+ const activity = activities.get(sessionId);
+ const model = info?.model || row?.model || '';
+ const title = row?.title?.trim() || info?.title?.trim() || '';
+ if (!title && !model) return null;
+ const tokens = tokensBySession.get(sessionId) ?? 0;
+ const rate = rates.get(model);
+ const running = activity ? isSessionActivityRunning(activity) : false;
+ return {
+ sessionId,
+ title,
+ harness: harnessOf(row?.agentKind ?? rate?.harness),
+ model: model ? formatModelShort(model) : '',
+ tokensToday: tokens,
+ valueToday: rate && rate.tokens > 0 ? (tokens * rate.money) / rate.tokens : 0,
+ contextPercent: info && info.contextWindow > 0 ? clampPercent((info.contextTokens / info.contextWindow) * 100) : null,
+ running,
+ startedAtMs: running ? (activity?.startedAtMs ?? null) : null,
+ lastActiveAtMs: activity?.lastActivityAtMs ?? info?.lastActiveAt ?? deps.nowMs,
+ };
+ }),
+ );
+ rows.push(...batch.filter((row): row is MenubarTaskInput => row !== null));
+ }
+ return rows.slice(0, MAX_TASK_ROWS);
}
diff --git a/apps/desktop/src/main/menubar/service.ts b/apps/desktop/src/main/menubar/service.ts
index 53087bd481..5e043ff77d 100644
--- a/apps/desktop/src/main/menubar/service.ts
+++ b/apps/desktop/src/main/menubar/service.ts
@@ -332,7 +332,7 @@ class MenubarService {
activities: () => getAgentIslandService()?.getSessionActivitySnapshots() ?? [],
sessionRow: async (sessionId) => {
const row = await getSessionRowSnapshot(sessionId);
- return row ? { title: row.title, model: row.model ?? null, agentKind: row.agentKind ?? null } : null;
+ return row ? { title: row.title, model: row.model ?? null, agentKind: row.agentKind ?? null, source: row.source ?? null } : null;
},
selfDeviceName: deviceName(),
onError: (scope, error) => log.warn('menu bar source failed', { scope, error: errorMessage(error) }),
diff --git a/apps/desktop/src/main/usage/__tests__/peerUsageSync.test.ts b/apps/desktop/src/main/usage/__tests__/peerUsageSync.test.ts
index 0ebf42d1dc..1bc5bb0051 100644
--- a/apps/desktop/src/main/usage/__tests__/peerUsageSync.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/peerUsageSync.test.ts
@@ -182,6 +182,57 @@ describe('usage device rows wire format', () => {
expect(isUnixMs(8.64e15 + 1)).toBe(false);
});
+ it('round-trips optional task sources without dropping legacy tasks or usage', async () => {
+ const sourceRows = rowsFor(['2026-09-26']);
+ const tasks = ['cindy-make', 'cindy-make-merge', null, undefined].map((source, index) => ({
+ sessionId: 'task-' + index,
+ title: 'Task ' + index,
+ model: 'gpt-5.5',
+ providerId: null,
+ source,
+ contextTokens: 0,
+ contextWindow: 0,
+ lastActiveAt: 1,
+ }));
+ const sessionRows = tasks.map((entry) => ({ day: '2026-09-26', sessionId: entry.sessionId, tokens: 5 }));
+ const decoded = await decodeUsageDeviceRowsResponse(
+ await readUsageDeviceRows(
+ {
+ getAllSpendDays: async () => sourceRows.spendDays,
+ getModelUsageSince: async () => sourceRows.modelRows,
+ getSessionUsageSince: async () => ({ rows: sessionRows, tasks }),
+ remoteVisibleTaskIds: async (ids) => new Set(ids),
+ todayKey: () => '2026-09-26',
+ },
+ { sinceDay: null },
+ ),
+ );
+ if (decoded?.kind !== 'rows') throw new Error('expected rows');
+ expect(decoded.rows.tasks.map((entry) => [entry.sessionId, entry.source])).toEqual([
+ ['task-0', 'cindy-make'],
+ ['task-1', 'cindy-make-merge'],
+ ['task-2', null],
+ ['task-3', null],
+ ]);
+ expect(decoded.rows.sessionRows).toEqual(sessionRows);
+ expect(decoded.rows.spendDays).toEqual(sourceRows.spendDays);
+ expect(decoded.rows.modelRows).toEqual(sourceRows.modelRows);
+ });
+
+ it('drops malformed task sources while retaining task metadata', () => {
+ const rows = sanitizeUsageDeviceRows({
+ ...rowsFor([]),
+ tasks: [
+ { sessionId: 'number', source: 1 },
+ { sessionId: 'long', source: 'x'.repeat(257) },
+ ],
+ });
+ expect(rows?.tasks.map((entry) => [entry.sessionId, entry.source])).toEqual([
+ ['number', null],
+ ['long', null],
+ ]);
+ });
+
it('drops a cached peer whose sync time is outside the Date range', async () => {
const h = harness({
readCache: async () =>
diff --git a/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts b/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
index 428959fb1e..3b301775d3 100644
--- a/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
@@ -835,11 +835,12 @@ describe('readUsageHistoryWith', () => {
describe('production cache and empty payload', () => {
it('overlays current local task metadata on a cached aggregate', async () => {
- const meta = (sessionId: string, title: string) => ({
+ const meta = (sessionId: string, title: string, source: string | null = null) => ({
sessionId,
title,
model: 'gpt-5.5',
providerId: null,
+ source,
contextTokens: 0,
contextWindow: 0,
lastActiveAt: 1,
@@ -855,9 +856,11 @@ describe('production cache and empty payload', () => {
const first = await readUsageHistory({ days: 30, includeTasks: true });
expect(first.tasks?.map((task) => task.title)).toEqual(['Old title', 'Doomed']);
// 重命名 s1、删除 s2:不产生用量,聚合缓存照常复用,但出口的任务元数据必须是当前值。
- vi.mocked(getUsageTaskMeta).mockResolvedValue([meta('s1', 'New title')]);
+ vi.mocked(getUsageTaskMeta).mockResolvedValue([meta('s1', 'New title', 'cindy-make')]);
const second = await readUsageHistory({ days: 30, includeTasks: true });
expect(second.tasks?.map((task) => [task.sessionId, task.title])).toEqual([['s1', 'New title']]);
+ expect(second.tasks?.[0].source).toBe('cindy-make');
+ expect(second.taskDaily).toEqual(first.taskDaily);
expect(getSessionUsageSince).toHaveBeenCalledTimes(1);
});
diff --git a/apps/desktop/src/main/usage/usageDeviceRows.ts b/apps/desktop/src/main/usage/usageDeviceRows.ts
index e8c0412475..76be6f8544 100644
--- a/apps/desktop/src/main/usage/usageDeviceRows.ts
+++ b/apps/desktop/src/main/usage/usageDeviceRows.ts
@@ -176,6 +176,7 @@ export function sanitizeUsageDeviceRows(value: unknown): UsageDeviceRows | null
title: typeof task.title === 'string' ? task.title.slice(0, 500) : '',
model: typeof task.model === 'string' ? task.model.slice(0, 256) : '',
providerId: isShortString(task.providerId) ? task.providerId : null,
+ source: isShortString(task.source) ? task.source : null,
contextTokens: finiteNonNegative(task.contextTokens),
contextWindow: finiteNonNegative(task.contextWindow),
lastActiveAt: isUnixMs(task.lastActiveAt) ? task.lastActiveAt : 0,
diff --git a/apps/desktop/src/main/usage/usageHistory.ts b/apps/desktop/src/main/usage/usageHistory.ts
index e22add3b67..6d158ceaea 100644
--- a/apps/desktop/src/main/usage/usageHistory.ts
+++ b/apps/desktop/src/main/usage/usageHistory.ts
@@ -193,6 +193,7 @@ export interface UsageHistoryTask {
title: string;
model: string;
providerId: string | null;
+ source?: string | null;
contextTokens: number;
contextWindow: number;
/** unix ms */
diff --git a/apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx b/apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx
index cd23ef06be..75f765fb27 100644
--- a/apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx
+++ b/apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx
@@ -15,6 +15,7 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useNavigate } from 'react-router-dom';
+import { CINDY_MAKE_ENABLED, isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';
import { cn } from '@/lib/utils';
import { formatCompactTokens, formatModelShort } from '@/lib/usageFormat';
@@ -71,6 +72,7 @@ export function buildUsageTaskRows(
}
const rows: UsageTaskRow[] = [];
for (const task of history.tasks) {
+ if (!CINDY_MAKE_ENABLED && isCindyMakeSource(task.source)) continue;
const tokens = tokensByTask.get(task.taskKey) ?? 0;
if (tokens > 0) rows.push({ ...task, tokens });
}
diff --git a/apps/desktop/src/renderer/components/settings/usage/__tests__/usageTaskTable.test.tsx b/apps/desktop/src/renderer/components/settings/usage/__tests__/usageTaskTable.test.tsx
index 9d70f59ab8..6a0ce21cfe 100644
--- a/apps/desktop/src/renderer/components/settings/usage/__tests__/usageTaskTable.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/usage/__tests__/usageTaskTable.test.tsx
@@ -86,6 +86,29 @@ describe('buildUsageTaskRows', () => {
expect(buildUsageTaskRows(payload, 'all').map((r) => r.taskKey)).toContain('laptop:b');
});
+ it.each(['local', 'laptop'])('filters Make tasks on %s before ranking without changing usage records', (deviceId) => {
+ const ordinary = Array.from({ length: 10 }, (_, index) => ({
+ ...task(deviceId, 'ordinary-' + index),
+ source: index % 2 === 0 ? null : undefined,
+ }));
+ const hidden = ['cindy-make', 'cindy-make-merge'].map((source) => ({
+ ...task(deviceId, source),
+ source,
+ }));
+ const daily = [...hidden, ...ordinary].map((entry, index) => ({
+ day: '2026-09-26',
+ taskKey: entry.taskKey,
+ tokens: 100 - index,
+ }));
+ const input = history(daily, [...hidden, ...ordinary]);
+
+ expect(buildUsageTaskRows(input, 'today').map((row) => row.taskKey)).toEqual(
+ ordinary.slice(0, 8).map((entry) => entry.taskKey),
+ );
+ expect(input.taskDaily).toEqual(daily);
+ expect(input.tasks).toEqual([...hidden, ...ordinary]);
+ });
+
it('reports the coverage start only when the range reaches before the first record', () => {
expect(usageTaskCoverageStart(payload, 'all')).toBe('2026-09-10');
expect(usageTaskCoverageStart(payload, '30d')).toBe('2026-09-10');
diff --git a/apps/desktop/src/renderer/components/ui/__tests__/sharedMenuCallers.test.tsx b/apps/desktop/src/renderer/components/ui/__tests__/sharedMenuCallers.test.tsx
index 519692a2cd..e305ffca49 100644
--- a/apps/desktop/src/renderer/components/ui/__tests__/sharedMenuCallers.test.tsx
+++ b/apps/desktop/src/renderer/components/ui/__tests__/sharedMenuCallers.test.tsx
@@ -5,7 +5,7 @@
* (DESIGN §4 Select & Dropdown). Each one is opened, chosen from by keyboard, and its
* callback arguments match what the hand-written version passed.
*/
-import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { VersionDropdown } from '@/components/UpdateNoticeDialog';
@@ -118,7 +118,7 @@ describe('right sidebar · add tab', () => {
expect(onAdd).toHaveBeenCalledWith('review');
expect(screen.queryByRole('menu')).toBeNull();
// Esc / select returns focus to the "+" button.
- expect(document.activeElement).toBe(add);
+ await waitFor(() => expect(document.activeElement).toBe(add));
});
it('closes on Escape without adding a tab and returns focus to "+"', async () => {
@@ -127,7 +127,7 @@ describe('right sidebar · add tab', () => {
await key('Escape');
expect(screen.queryByRole('menu')).toBeNull();
expect(onAdd).not.toHaveBeenCalled();
- expect(document.activeElement).toBe(add);
+ await waitFor(() => expect(document.activeElement).toBe(add));
});
it('closes when the host pane collapses and leaves focus off the hidden "+"', async () => {
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useUsageHistoryPeerRefresh.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/useUsageHistoryPeerRefresh.test.tsx
index ea1f2d2929..8847ee2376 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/useUsageHistoryPeerRefresh.test.tsx
+++ b/apps/desktop/src/renderer/hooks/__tests__/useUsageHistoryPeerRefresh.test.tsx
@@ -112,4 +112,16 @@ describe('useUsageHistory peer refresh', () => {
true,
]);
});
+
+ it('re-reads task metadata when a Make source arrives', async () => {
+ renderHook(() => useUsageHistory({ userId: 'task-source-refresh', includeTasks: true }));
+ await act(async () => {});
+ const initial = callsFor(undefined);
+
+ emitPatch('s1', { source: 'cindy-make' });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5_000);
+ });
+ expect(callsFor(undefined)).toBe(initial + 1);
+ });
});
diff --git a/apps/desktop/src/renderer/hooks/useUsageHistory.ts b/apps/desktop/src/renderer/hooks/useUsageHistory.ts
index 663486e53d..0419d34d02 100644
--- a/apps/desktop/src/renderer/hooks/useUsageHistory.ts
+++ b/apps/desktop/src/renderer/hooks/useUsageHistory.ts
@@ -116,6 +116,7 @@ export interface UsageHistoryTask {
title: string;
model: string;
providerId: string | null;
+ source?: string | null;
contextTokens: number;
contextWindow: number;
/** unix ms */
@@ -554,7 +555,7 @@ async function load(scopeKey: string, opts?: { forceRefresh?: boolean; resetPric
}
/** 影响「最耗 token 的任务」展示的任务字段。 */
-const TASK_META_KEYS = ['title', 'status', 'model', 'providerId'] as const;
+const TASK_META_KEYS = ['title', 'status', 'model', 'providerId', 'source'] as const;
export type UsageHistoryWindow = number | 'all';