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。

Merge origin/main into feat/remote-agent-session-limits

fmfsaisai8a3e7a116cce
diff --cc apps/desktop/src/main/device-link/__tests__/providerShareManagement.test.ts
index 576abb88ef,1d6ceea5bf..303ff5b282
--- a/apps/desktop/src/main/device-link/__tests__/providerShareManagement.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/providerShareManagement.test.ts
@@@ -53,7 -60,13 +60,14 @@@ vi.mock('../providerShareGuest.js', ()
vi.mock('../providerShareGuestPrefs.js', () => ({ configureProviderShareGuestPrefs: vi.fn(), invalidateProviderShareGuestPrefsCache: vi.fn() }));
vi.mock('../providerShareGuestPrefsIpc.js', () => ({ setProviderShareCredentialConsentFromIpc: vi.fn() }));
- import { executeProviderShareManagementCommand, parseProviderShareCommand, registerProviderShareIpc, startProviderShareRuntime, stopProviderShareRuntime } from '../providerShareRuntime';
+ import {
+ executeProviderShareManagementCommand,
++ parseProviderShareCommand,
+ registerProviderShareIpc,
+ startProviderShareRuntime,
+ stopProviderShareRuntime,
+ trimProviderUsageHistory,
+ } from '../providerShareRuntime';
const createLink: ProviderShareManagementCommand = { action: 'create-link', providerId: 'anthropic' };
const LINK_ID = 'a'.repeat(64);
@@@ -80,23 -95,69 +96,81 @@@ beforeEach(() =>
afterEach(() => stopProviderShareRuntime());
+ const historyRow = (index: number, model = 'model-' + index): ProviderUsageHistoryView['self']['days'][number] => ({
+ day: '2026-10-17',
+ kind: 'claude-code',
+ providerId: 'anthropic',
+ memberKey: 'local',
+ model,
+ turns: 1,
+ inputTokens: 1,
+ outputTokens: 1,
+ cacheReadTokens: 0,
+ cacheCreateTokens: 0,
+ amount: null,
+ });
+
+ const historyWithRows = (rows: ProviderUsageHistoryView['self']['days']): ProviderUsageHistoryView => ({
+ providerId: 'anthropic',
+ todayKey: '2026-10-17',
+ coverageStart: null,
+ self: { lastUsedAt: null, days: rows },
+ relays: [],
+ members: [],
+ });
+
+ describe('provider share usage history wire budget', () => {
+ it('caps the global row count even when the newest day alone has more rows', () => {
+ const trimmed = trimProviderUsageHistory(historyWithRows(Array.from({ length: 5_001 }, (_, index) => historyRow(index))));
+ expect(trimmed.self.days).toHaveLength(5_000);
+ expect(trimmed.coverageStart).toBe('2026-10-17');
+ });
+
+ it('also trims by UTF-8 JSON bytes and reports the retained date', () => {
+ const rows = Array.from({ length: 4_000 }, (_, index) => '模型-' + index + '-' + '很'.repeat(600))
+ .map((model, index) => historyRow(index, model));
+ const trimmed = trimProviderUsageHistory(historyWithRows(rows));
+ expect(trimmed.self.days.length).toBeLessThan(rows.length);
+ expect(Buffer.byteLength(JSON.stringify(trimmed), 'utf8')).toBeLessThanOrEqual(2 * 1024 * 1024 - 1_024);
+ expect(trimmed.coverageStart).toBe('2026-10-17');
+ });
+
+ it('bounds ledger expansion and prices only the globally retained rows, preserving SDK costs and truncation', async () => {
+ const rawRows = Array.from({ length: 5_001 }, (_, index) => {
+ return { ...historyRow(index), sdkCostUsd: 0.25 };
+ });
+ usageStores.ownHistory.mockReturnValue({ self: { lastUsedAt: null, days: rawRows }, relays: [] });
+ host.snapshot.mockReturnValue([{ providerId: 'anthropic', shareId: 's', members: [{ memberId: 'm1' }] }]);
+ const result = await executeProviderShareManagementCommand({ action: 'usage-history', providerId: 'anthropic' }) as ProviderUsageHistoryView;
+ expect(usageStores.memberHistory).toHaveBeenCalledWith(new Set(['s']), {
+ maxRows: 5_001, memberKeys: new Set([JSON.stringify(['s', 'm1'])]),
+ });
+ expect(usageStores.pricing).toHaveBeenCalledTimes(5_000);
+ expect(result.self.days).toHaveLength(5_000);
+ expect(result.self.days[0]?.amount).toEqual({ amount: 0.25, currency: 'USD' });
+ expect(result.self.days[0]).not.toHaveProperty('sdkCostUsd');
+ expect(result.coverageStart).toBe('2026-10-17');
+ });
+ });
+
+describe('remote task limit management payloads', () => {
+ it.each([{ perDevice: 24 }, { total: 80 }, { perDevice: 16, total: 64 }])('preserves only supplied fields in %j', limits => {
+ expect(parseProviderShareCommand({ action: 'set-run-limits', limits })).toEqual({ action: 'set-run-limits', limits });
+ });
+ it.each([{}, { unknown: 1 }, { perDevice: '16' }, { perDevice: 0 }, { total: 1001 }, { total: 1.5 }])('rejects malformed patches %j', limits => {
+ expect(() => parseProviderShareCommand({ action: 'set-run-limits', limits })).toThrow('INVALID_PARAMS');
+ });
+});
+
describe('same-account share management during account transitions', () => {
it.each([
createLink, ...mutations,
+ { action: 'get-run-limits' },
+ { action: 'set-run-limits', limits: { perDevice: 16, total: 64 } },
+ { action: 'reset-run-limits' },
{ action: 'owned', range: '7d' },
{ action: 'own-usage', providerId: 'anthropic', range: '7d' },
+ { action: 'usage-history', providerId: 'anthropic' },
] satisfies ProviderShareManagementCommand[])('refuses $action at entry while teardown is pending', async (command) => {
state.boundaryPending = true;
await expect(executeProviderShareManagementCommand(command)).rejects.toThrow(/PRECONDITION_FAILED/);
diff --cc apps/desktop/src/main/provider-group/management.ts
index a92a94b954,c8b4739c45..ac491dd6dc
--- a/apps/desktop/src/main/provider-group/management.ts
+++ b/apps/desktop/src/main/provider-group/management.ts
@@@ -20,7 -20,7 +20,7 @@@ export function parseProviderManagement
return { action: 'manage-group', command: command as ProviderGroupManagementCommand };
}
const command = parseProviderShareCommand(raw.command);
- if (!['owned', 'own-usage', 'create-link', 'approve', 'reject', 'set-member', 'reshare-decide', 'get-run-limits', 'set-run-limits', 'reset-run-limits'].includes(command.action)) {
- if (!['owned', 'own-usage', 'usage-history', 'create-link', 'approve', 'reject', 'set-member', 'reshare-decide'].includes(command.action)) {
++ if (!['owned', 'own-usage', 'usage-history', 'create-link', 'approve', 'reject', 'set-member', 'reshare-decide', 'get-run-limits', 'set-run-limits', 'reset-run-limits'].includes(command.action)) {
throwIpcError('PERMISSION_DENIED', 'Only owner operations are available through management');
}
return { action: 'manage-share', command: command as ProviderShareManagementCommand };
diff --cc apps/desktop/src/renderer/features/provider-share/ProviderShareManagePage.tsx
index 493fa3fe06,366f558476..82cdc88bb2
--- a/apps/desktop/src/renderer/features/provider-share/ProviderShareManagePage.tsx
+++ b/apps/desktop/src/renderer/features/provider-share/ProviderShareManagePage.tsx
@@@ -445,15 -498,13 +499,15 @@@ export function ProviderShareManagePage
initialConfig={initialGroup} remoteProvider={remoteProvider} onConfigChange={setRemoteGroup}
/>
+ <RemoteAgentLimitsSection key={deviceId ?? 'local'} deviceId={deviceId} />
+
<ProviderUsageSection
providerId={providerId}
- providerName={providerName}
- own={own}
- ownFailed={ownFailed}
+ history={history}
+ status={usageStatus}
+ legacyOwn={legacyOwn}
members={members}
- membersLoading={!state && !loadFailed}
+ memberActions={memberActions}
selfDeviceName={selfDeviceName}
ownerDeviceId={deviceId}
groupConfig={deviceId ? remoteGroup : undefined}
diff --cc apps/desktop/src/renderer/features/provider-share/__tests__/ProviderShareManagePage.test.tsx
index d2b933cfaa,87202c1501..b700f2ff74
--- a/apps/desktop/src/renderer/features/provider-share/__tests__/ProviderShareManagePage.test.tsx
+++ b/apps/desktop/src/renderer/features/provider-share/__tests__/ProviderShareManagePage.test.tsx
@@@ -157,19 -191,11 +191,16 @@@ beforeEach(() =>
confirmSpy.mockClear();
command.mockReset();
command.mockImplementation(async (cmd: { action: string }) => {
- if (cmd.action === 'owned') return currentOwned;
+ if (cmd.action === 'owned') return owned();
if (cmd.action === 'own-usage') return ownUsage();
+ if (cmd.action === 'usage-history') return usageHistory();
if (cmd.action === 'received') return [];
+ if (cmd.action === 'get-run-limits') return {
+ value: { perDevice: 16, total: 64 }, defaults: { perDevice: 16, total: 64 },
+ isCustomized: false, customizedKeys: [], usage: { total: 0, devices: 0, largestDevice: 0 },
+ };
+ if (cmd.action === 'received-snapshot') return { ownerStamp: { dataOwnerId: null, ownerGeneration: 0 }, received: [], confirmedRegions: [] };
- if (cmd.action === 'set-member') return { ok: true };
- if (cmd.action === 'approve' || cmd.action === 'reject') {
- currentOwned = { ...currentOwned, shares: currentOwned.shares.map((share) => ({ ...share, requests: [] })) };
- return { ok: true };
- }
+ if (cmd.action === 'set-member' || cmd.action === 'approve' || cmd.action === 'reject') return { ok: true };
throw new Error(`unexpected ${cmd.action}`);
});
Object.assign(window, {
@@@ -195,13 -211,10 +216,11 @@@
if (cmd.action === 'list') return localGroups;
if (cmd.action === 'remote-manage') {
const action = cmd.request?.command?.action;
- if (action === 'owned') return currentOwned;
+ if (action === 'owned') return owned();
if (action === 'own-usage') return ownUsage();
+ if (action === 'usage-history') return usageHistory();
+ if (action === 'get-run-limits') return command(cmd.request?.command);
- if (action === 'approve' || action === 'reject') {
- currentOwned = { ...currentOwned, shares: currentOwned.shares.map((share) => ({ ...share, requests: [] })) };
- return { ok: true };
- }
+ if (action === 'approve' || action === 'reject') return { ok: true };
}
return { providerId: cmd.providerId, config: null, members: [] };
},
@@@ -499,39 -475,57 +481,57 @@@ describe('ProviderShareManagePage', ()
it('shows a provider without a group as a group of just this computer', async () => {
renderPage();
- const rows = await screen.findAllByTestId('provider-usage-row');
- expect(screen.getByText(/providerGroup\.usage\.description:/)).toBeTruthy();
- // 和建了组的一样有摘要与占比,只是收起时不写用了几台电脑(只有一台)。
+ await waitFor(() => expect(screen.getAllByTestId('provider-usage-model').length).toBeGreaterThan(0));
expect(screen.getByTestId('provider-usage-summary')).toBeTruthy();
- expect(rows[0]!.textContent).not.toMatch(/computerCount/);
-
- fireEvent.click(screen.getByRole('button', { name: /providerGroup\.usage\.expandAria.*Magi/ }));
- const self = screen.getAllByTestId('provider-usage-row')[0]!;
- const members = within(self).getAllByTestId('provider-usage-member');
- // 本机一行在前;以前经组在 Studio 上运行的那部分排在后面,写已移出组。
- expect(members.map((member) => member.getAttribute('data-member-key'))).toEqual(['local', 'device:studio:xd-2']);
- expect(members[0]!.textContent).toContain('providerGroup.member.local');
- expect(members[0]!.textContent).toContain("Magi's Mac Mini");
- expect(members[1]!.textContent).toContain('providerGroup.usage.removedMember');
-
- fireEvent.click(screen.getByRole('button', { name: /providerGroup\.usage\.expandAria.*Lizi/ }));
- const lizi = screen.getAllByTestId('provider-usage-row')[1]!;
- expect(within(lizi).getByText('Opus 5.5')).toBeTruthy();
- expect(within(lizi).getAllByText('$31.20').length).toBeGreaterThan(0);
- expect(within(lizi).getByText('providerShare.manage.members.estimateNote')).toBeTruthy();
+ // 只有一台:没有组内电脑的筛选与「按电脑」。
+ expect(screen.queryByRole('combobox', { name: 'providerGroup.usage.filter.computerAria' })).toBeNull();
+ expect(screen.queryByTestId('provider-usage-computer')).toBeNull();
+ expect(screen.getAllByTestId('provider-usage-model').map((row) => row.textContent)).toEqual(
+ expect.arrayContaining([expect.stringContaining('Opus 5.5')]),
+ );
+ expect(screen.getAllByText('$31.20').length).toBeGreaterThan(0);
+ expect(screen.getByText('providerShare.manage.members.estimateNote')).toBeTruthy();
});
- it('does not show zero for this computer when its usage could not be read', async () => {
+ it('does not show zero when usage could not be read', async () => {
++ const respond = command.getMockImplementation()!;
command.mockImplementation(async (cmd: { action: string }) => {
-- if (cmd.action === 'owned') return owned();
-- if (cmd.action === 'received') return [];
-- throw new Error('boom');
++ if (cmd.action === 'usage-history') throw new Error('boom');
++ return respond(cmd);
});
renderPage();
- const rows = await screen.findAllByTestId('provider-usage-row');
+ expect((await screen.findByRole('alert')).textContent).toBe('providerGroup.usage.loadFailed');
+ const rows = screen.getAllByTestId('provider-usage-row');
expect(rows[0]!.getAttribute('data-usage-party')).toBe('self');
- expect(rows[0]!.textContent).toContain('providerShare.manage.loadFailed');
- expect(rows[0]!.textContent).not.toMatch(/members\.tokens/);
+ expect(rows[0]!.textContent).not.toMatch(/\d(\.\d)?[kM]/);
+ });
+
+ // 那台电脑还没更新、不认识按天明细:退回所有时间的合计,时间固定为所有时间,不显示两张图。
+ it('falls back to all-time totals when the provider computer has not been updated', async () => {
+ const remoteCommand = vi.spyOn(window.electronAPI.providerGroup, 'command');
+ remoteCommand.mockImplementation(async (cmd) => {
+ if (cmd.action === 'remote-manage' && cmd.request.action === 'manage-share') {
+ const action = cmd.request.command.action;
+ if (action === 'usage-history') throw new Error('[UNSUPPORTED_CAPABILITY] Provider management requires an update');
+ if (action === 'own-usage') return ownUsage();
+ return command(cmd.request.command);
+ }
+ return { providerId: 'xd', config: null, members: [] };
+ });
+ renderPage('on', { deviceId: 'studio' });
+ await waitFor(() => expect(remoteCommand).toHaveBeenCalledWith({
+ action: 'remote-manage',
+ deviceId: 'studio',
+ request: { action: 'manage-share', command: { action: 'own-usage', providerId: 'xd', range: 'all' } },
+ }));
+ expect(await screen.findByText(/providerGroup\.usage\.legacyNote/)).toBeTruthy();
+ await waitFor(() => expect(usageRowText(0)).toContain('52.0k'));
+ // 分享的人所有时间的合计来自 owned。
+ expect(usageRowText(1)).toContain('1.5M');
+ // 选不了时间:不摆出时间范围与日期。
+ expect(screen.queryByRole('combobox', { name: 'usageHistory.range.ariaLabel' })).toBeNull();
+ expect(screen.queryByLabelText('usageHistory.range.date')).toBeNull();
+ expect(screen.queryByText('usageHistory.daily.title')).toBeNull();
});
it('pauses and removes a member after confirmation', async () => {
diff --cc apps/desktop/src/shared/providerManagement.ts
index c739956d2b,1ffeff0c4a..9238a932b3
--- a/apps/desktop/src/shared/providerManagement.ts
+++ b/apps/desktop/src/shared/providerManagement.ts
@@@ -12,7 -12,7 +12,7 @@@ export type ProviderGroupManagementComm
export type ProviderShareManagementCommand = Extract<
ProviderShareCommand,
- { action: 'owned' | 'own-usage' | 'create-link' | 'approve' | 'reject' | 'set-member' | 'reshare-decide' | 'get-run-limits' | 'set-run-limits' | 'reset-run-limits' }
- { action: 'owned' | 'own-usage' | 'usage-history' | 'create-link' | 'approve' | 'reject' | 'set-member' | 'reshare-decide' }
++ { action: 'owned' | 'own-usage' | 'usage-history' | 'create-link' | 'approve' | 'reject' | 'set-member' | 'reshare-decide' | 'get-run-limits' | 'set-run-limits' | 'reset-run-limits' }
>;
export type ProviderManagementRequest =
diff --cc apps/desktop/src/shared/providerShare.ts
index a7268f7217,dd3ba64cc6..72dc5f2459
--- a/apps/desktop/src/shared/providerShare.ts
+++ b/apps/desktop/src/shared/providerShare.ts
@@@ -186,11 -213,9 +218,12 @@@ export interface ProviderShareCredentia
}
export interface ProviderShareCommandResult {
+ 'get-run-limits': RemoteAgentLimitsView;
+ 'set-run-limits': RemoteAgentLimitsView;
+ 'reset-run-limits': RemoteAgentLimitsView;
owned: ProviderShareOwnerState;
'own-usage': ProviderOwnUsageView;
+ 'usage-history': ProviderUsageHistoryView;
'create-link': ProviderShareLinkCreated;
approve: { ok: true };
reject: { ok: true };