Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(provider-share): 限制最终额度与用量回包大小
fmfsaisai6c34f7d4087c
diff --git a/apps/desktop/src/main/device-link/__tests__/providerShareInsights.test.ts b/apps/desktop/src/main/device-link/__tests__/providerShareInsights.test.tsindex c102d183f8..5045d72cb7 100644--- a/apps/desktop/src/main/device-link/__tests__/providerShareInsights.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/providerShareInsights.test.ts@@ -1,5 +1,5 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import type { ProviderShareOwned } from '@cindy/device-link';+import { MAX_FRAME_BYTES, type ProviderShareOwned } from '@cindy/device-link';import type { ProviderUsageHistoryView } from '../../../shared/providerShare';import { parseProviderShareInsights } from '../../../shared/providerShareInsights';import { createProviderShareInsightsReader } from '../providerShareInsights';@@ -8,6 +8,7 @@ import { createProviderShareInsightsReader } from '../providerShareInsights';* 依据:provider-sharing 的最小范围及账号隔离;旧 dispatch/management 测试没有新 reader。* 最小失败输入:一项查询失败、在途关闭后重开、同 providerId 换账号、转来的一行用量。* 缓存回归:PR #6482 P1;旧覆盖仅单供应商,补 A→B→A、过期和旧失败晚于新读取的时序。+ * 回包预算:#4316096976,旧覆盖未包含昵称/头像膨胀;用大名单加已有预算内账本触发最终帧超限。* tier: unit;依赖注入,无 Electron/外网/真实等待。单文件耗时见执行报告。 */const day = {day: '2026-10-19',@@ -246,6 +247,88 @@ describe('provider share insights', () => {expect((await read('peer', request)).status.usage).toBe('ready');expect(deps.history).toHaveBeenCalledTimes(2);});+ it('budgets final member metadata and quota together with newest usage rows', async () => {+ const { deps, history } = fixture();+ const share = deps.shares()[0];+ share.members = Array.from({ length: 1_200 }, (_, index) => ({+ ...share.members[0],+ memberId: String(index),+ displayName: '名字'.repeat(40),+ avatarUrl: 'https://example.com/' + 'a'.repeat(600),+ }));+ history.self.days = Array.from({ length: 750 }, (_, index) => ({+ ...day,+ day: index < 375 ? '2026-10-18' : '2026-10-19',+ model: '模型'.repeat(300) + index,+ }));+ history.members = [];+ history.relays = [];+ expect(Buffer.byteLength(JSON.stringify(history))).toBeLessThan(MAX_FRAME_BYTES - 1_024);+ const read = createProviderShareInsightsReader({ ...deps, shares: () => [share] });+ const result = await read('peer', request);+ const frame = {+ v: 1,+ kind: 'invoke-result',+ id: 'request',+ dst: 'peer',+ payload: { ok: true, result },+ };+ expect(Buffer.byteLength(JSON.stringify(frame))).toBeLessThan(MAX_FRAME_BYTES);+ expect(result.status).toEqual({ quota: 'ready', usage: 'ready' });+ expect(result.usage?.parties).toHaveLength(1_201);+ const kept = result.usage!.parties[0].days;+ expect(kept.length).toBeGreaterThan(0);+ expect(kept.length).toBeLessThan(750);+ expect(kept.map((row) => row.model)).toEqual(+ [...history.self.days]+ .sort((a, b) => b.day.localeCompare(a.day))+ .slice(0, kept.length)+ .map((row) => row.model),+ );+ expect(result.usage?.coverageStart).toBe(kept.at(-1)?.day);+ expect(parseProviderShareInsights(result)).toEqual(result);+ expect(read.isCurrent('peer', result)).toBe(true);+ });+ it('keeps quota available when member metadata alone exceeds the frame budget', async () => {+ const { deps } = fixture();+ const share = deps.shares()[0];+ share.members = Array.from({ length: 10_000 }, (_, index) => ({+ ...share.members[0],+ memberId: String(index),+ displayName: '名字'.repeat(40),+ }));+ const read = createProviderShareInsightsReader({ ...deps, shares: () => [share] });+ const result = await read('peer', request);+ expect(result.status).toEqual({ quota: 'ready', usage: 'unavailable' });+ expect(result.usage).toBeNull();+ expect(result.quota?.accounts[0].balance?.remaining).toBe(0);+ expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThan(MAX_FRAME_BYTES - 1_024);+ });+ it('keeps usage available when the quota projection alone exceeds the frame budget', async () => {+ const { deps } = fixture();+ const quota = await deps.quota();+ const read = createProviderShareInsightsReader({+ ...deps,+ quota: async () => ({+ ...quota,+ accounts: Array.from({ length: 512 }, () => ({+ ...quota.accounts[0],+ windows: Array.from({ length: 32 }, () => ({+ kind: 'scoped' as const,+ label: '窗口'.repeat(64),+ remainingPercent: 50,+ resetsAt: null,+ windowMinutes: null,+ })),+ })),+ }),+ });+ const result = await read('peer', request);+ expect(result.status).toEqual({ quota: 'unavailable', usage: 'ready' });+ expect(result.quota).toBeNull();+ expect(result.usage?.parties[0].days[0].inputTokens).toBe(10);+ expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThan(MAX_FRAME_BYTES - 1_024);+ });it('rejects unauthorized members and a guest-supplied provider id', async () => {const { read, state } = fixture();await expect(read('peer', { version: 1, providerId: 'other' })).rejects.toThrow(diff --git a/apps/desktop/src/main/device-link/providerShareInsights.ts b/apps/desktop/src/main/device-link/providerShareInsights.tsindex f819994fca..81072b6f2d 100644--- a/apps/desktop/src/main/device-link/providerShareInsights.ts+++ b/apps/desktop/src/main/device-link/providerShareInsights.ts@@ -1,5 +1,5 @@import { createHash } from 'node:crypto';-import type { ProviderShareOwned } from '@cindy/device-link';+import { MAX_FRAME_BYTES, type ProviderShareOwned } from '@cindy/device-link';import type { ProviderUsageHistoryView } from '../../shared/providerShare.js';import type {ProviderShareInsights,@@ -118,6 +118,51 @@ function publicUsage(};}+// Match the existing history budget, reserving room for the invoke envelope.+const INSIGHTS_MAX_BYTES = MAX_FRAME_BYTES - 1_024;+const jsonBytes = (value: unknown): number => Buffer.byteLength(JSON.stringify(value), 'utf8');++function boundInsightsFrame(result: ProviderShareInsights): void {+ // An oversized capability must not turn the other capability into a transport error.+ if (result.quota && jsonBytes({ ...result, usage: null }) > INSIGHTS_MAX_BYTES) {+ result.quota = null;+ result.status.quota = 'unavailable';+ }+ const usage = result.usage;+ if (!usage || jsonBytes(result) <= INSIGHTS_MAX_BYTES) return;+ const rows = usage.parties.flatMap((party, index) => party.days.map((row) => ({ index, row })));+ rows.sort((a, b) => b.row.day.localeCompare(a.row.day));+ const bounded: ProviderShareUsageDetails = {+ ...usage,+ coverageStart: null,+ parties: usage.parties.map((party) => ({ ...party, days: [] })),+ };+ let bytes = jsonBytes({ ...result, usage: bounded });+ let kept = 0;+ for (const { index, row } of rows) {+ const days = bounded.parties[index]!.days;+ // Account for JSON array separators and the coverage marker as well as UTF-8 row bytes.+ const nextBytes =+ bytes ++ jsonBytes(row) ++ (days.length ? 1 : 0) ++ jsonBytes(row.day) -+ jsonBytes(bounded.coverageStart);+ if (nextBytes > INSIGHTS_MAX_BYTES) break;+ days.push(row);+ bounded.coverageStart = row.day;+ bytes = nextBytes;+ kept++;+ }+ // Never silently omit people or display zero usage when no history can fit.+ if (bytes > INSIGHTS_MAX_BYTES || (rows.length > 0 && kept === 0)) {+ result.usage = null;+ result.status.usage = 'unavailable';+ } else {+ result.usage = bounded;+ }+}+/** 最小只读投影;权限检查保留到实际发送,包括背压队列重发。 */export function createProviderShareInsightsReader(deps: ProviderShareInsightsDeps) {const checks = new WeakMap<object, { peer: string; assertCurrent(): void }>();@@ -206,6 +251,7 @@ export function createProviderShareInsightsReader(deps: ProviderShareInsightsDepquota,usage: history ? publicUsage(history, share, access.memberId, deps.owner()) : null,};+ boundInsightsFrame(result);checks.set(result, { peer, assertCurrent });return result;};diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 012701ca77..a00e22bd9f 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -1631,6 +1631,9 @@ G 与 O 之间不变。受邀者能调用的 channel 不变(仍是 `maker:remote只读请求不调用远程 Agent,不占任务名额。历史和额度分别合并短期在途读取,缓存不跨账号。- 普通额度为一项,组额度仅返回自有账号匿名数组及 partial 标记,不含设备、上游身份、凭证或第三方分享账号额度。用量按天/模型/公开昵称头像投影,合并设备维度,转来用量匿名汇总;历史裁剪口径沿用 usage-history。+ 最终投影还按 UTF-8 JSON 总字节限制在 `MAX_FRAME_BYTES - 1024`,预留 invoke 信封空间;预算包括昵称/头像、额度和历史行。+ 继续裁剪时优先保留较新的历史并更新 `coverageStart`;人员资料本身超限或连一行历史也无法容纳时,将 usage 标 unavailable,+ 不静默删除人员、不伪造零用量,也不让它拖掉可用 quota。quota 本身超限时独立标 unavailable。没有新增 wire 字段。- 旧受邀端不发新请求,模型使用不变;新受邀端收到 CHANNEL_NOT_ALLOWED 或不完整能力时显示需要更新。relay 信封、服务端、数据库与 Mobile 均不变;完整查看需要双方 Desktop 更新。实现与回归:`device-link/providerShareInsights.ts`、`dispatch.ts`、同目录 `__tests__/providerShareInsights.test.ts`、`providerShareDispatch.test.ts`。diff --git a/docs/product-rules/provider-sharing.md b/docs/product-rules/provider-sharing.mdindex b412be2971..6538285a7b 100644--- a/docs/product-rules/provider-sharing.md+++ b/docs/product-rules/provider-sharing.md@@ -347,6 +347,9 @@ Desktop「设置 → 模型供应商」的左栏(2026-10-08 用户裁决):关闭后重开不恢复旧回包。专用只读结果不进入通用完成缓存,不启动/接回远程 Agent。页面可见时最多每五秒复核,隐藏/换分享/账号/关系变化或查询失败清除旧展示;额度和用量失败分别处理。本机历史缓存十五秒、额度读取短缓存并合并在途查询,按账号隔离。+ 最终只读回包的字节预算包含额度、所有人的昵称/头像和历史行;超限时继续优先保留较新的历史行,并更新 `coverageStart`。+ 不静默删掉人员或把未返回的历史当作零用量;人员资料本身或一条历史都无法容纳时,用量显示不可用,额度仍独立返回。+ 额度本身超过回包预算时也只标额度不可用,不影响能够返回的用量。实现:`device-link/providerShareInsights.ts`、`providerShareQuota.ts`、`providerShareVisibility.ts` 与 renderer 同名功能组件;回归:`device-link/__tests__/providerShareInsights.test.ts`、`providerShareDispatch.test.ts`、`providerShareQuota.test.ts`、`providerShareVisibility.test.ts`。