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(desktop): support long shared favorite sources

DavidShen8a7a274bafad
diff --git a/apps/desktop/src/renderer/__tests__/providerShareFavorites.test.tsx b/apps/desktop/src/renderer/__tests__/providerShareFavorites.test.tsx
index fece2be14e..8aa15865d8 100644
--- a/apps/desktop/src/renderer/__tests__/providerShareFavorites.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/providerShareFavorites.test.tsx
@@ -1,7 +1,8 @@
// @vitest-environment jsdom
import { act, cleanup, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import type { ProviderShareReceived } from '@cindy/device-link';
+import { parseModelFavorites, providerShareParsers, type ProviderShareReceived } from '@cindy/device-link';
+import type { ModelFavoritesHostApi } from '../../shared/modelFavoritesSync';
import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
import {
__resetForTest, addModelFavorite, listModelFavorites, setModelFavoritesOwner, useModelFavorites,
@@ -10,6 +11,7 @@ import {
parseProviderShareFavoriteSource, providerShareFavoriteSource, reconcileProviderShareFavorites,
useProviderShareFavorites, useProviderShareFavoriteCleanupFailed,
} from '@/state/providerShareFavorites';
+import { useModelFavoritesHost } from '@/state/useModelFavoritesHost';
const share = (shareId = 's1', memberId = 'm1'): ProviderShareReceived => ({
shareId, memberId, providerId: 'anthropic', providerLabel: 'Anthropic',
@@ -29,9 +31,52 @@ beforeEach(() => {
setModelFavoritesOwner('recipient');
publish([share(), share('s2', 'm2')]);
});
-afterEach(() => { cleanup(); vi.restoreAllMocks(); });
+afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
describe('recipient-owned shared model favorites', () => {
+ it('keeps long local sources out of legacy remote replies without removing stored favorites', () => {
+ const received = providerShareParsers.received({ ...share('s'.repeat(128), 'm'.repeat(128)), providerId: 'p'.repeat(256) });
+ publish([received]);
+ const view = mount(`share:${received.shareId}`);
+ act(() => view.result.current.store.add({ ...config, providerId: received.providerId }));
+ act(() => { addModelFavorite(config); });
+ const onRequest = vi.fn<ModelFavoritesHostApi['onRequest']>().mockReturnValue(() => {});
+ const reply = vi.fn<ModelFavoritesHostApi['reply']>();
+ vi.stubGlobal('electronAPI', { modelFavoritesHost: { onRequest, reply, ready: vi.fn(), changed: vi.fn() } });
+ renderHook(() => useModelFavoritesHost());
+ const request = onRequest.mock.calls[0]![0];
+ act(() => request({ requestId: 'get', expiresAt: Date.now() + 1000, ownerStamp: { dataOwnerId: 'recipient', ownerGeneration: 1 } }));
+ const items = reply.mock.calls[0]![0].items;
+ expect(parseModelFavorites(items)).toEqual([expect.objectContaining(config)]);
+ expect(listModelFavorites()).toHaveLength(2);
+ expect(view.result.current.items).toHaveLength(1);
+ });
+
+ it.each(['p'.repeat(256), '"\\'.repeat(128), '\ud800'.repeat(256)])('supports protocol-valid maximum identifiers including JSON escaping (%#)', (providerId) => {
+ const received = providerShareParsers.received({ ...share('s'.repeat(128), 'm'.repeat(128)), providerId });
+ const source = providerShareFavoriteSource(received);
+ expect(source.length).toBeGreaterThan(512);
+ expect(parseProviderShareFavoriteSource(source)).toEqual({
+ shareId: received.shareId, memberId: received.memberId, providerId, region: 'global',
+ });
+ addModelFavorite(config);
+ publish([received]);
+ const view = mount(`share:${received.shareId}`);
+ const longConfig = { ...config, providerId };
+ act(() => view.result.current.store.add(longConfig));
+ act(() => { setModelFavoritesOwner('other'); setModelFavoritesOwner('recipient'); });
+ expect(view.result.current.items).toEqual([{ ...longConfig, uid: expect.any(String) }]);
+ const uid = view.result.current.items[0]!.uid;
+ act(() => view.result.current.store.update(uid, { effort: 'low' }));
+ expect(view.result.current.items[0]?.effort).toBe('low');
+ act(() => publish([received]));
+ expect(view.result.current.items).toHaveLength(1);
+ const failed = renderHook(() => useProviderShareFavoriteCleanupFailed());
+ act(() => publish([]));
+ expect(failed.result.current).toBe(false);
+ expect(listModelFavorites()).toEqual([expect.objectContaining(config)]);
+ });
+
it.each(['cn', 'global'] as const)('keeps %s favorites usable and cleans only confirmed regions when the other region fails to load', (region) => {
const localShare = { ...share(), owner: { ...share().owner, region } };
const peerRegion = region === 'cn' ? 'global' as const : 'cn' as const;
diff --git a/apps/desktop/src/renderer/state/modelFavorites.ts b/apps/desktop/src/renderer/state/modelFavorites.ts
index fbca19fdcc..0932d761a0 100644
--- a/apps/desktop/src/renderer/state/modelFavorites.ts
+++ b/apps/desktop/src/renderer/state/modelFavorites.ts
@@ -78,6 +78,9 @@ import { createStorageReconciler } from './storageOpReplay';
let requireDurableWrite = false;
const STORAGE_KEY = 'xdt:modelFavorites:v1';
+// Shared sources contain two 128-character IDs and a 256-character provider ID.
+// JSON may expand each provider code unit to six characters (unpaired surrogates).
+export const LOCAL_FAVORITE_PROVIDER_ID_MAX_LENGTH = 2048;
/** 一条收藏所描述的完整配置(不含锚点)。 */
export interface ModelFavoriteConfig {
@@ -732,7 +735,7 @@ export function accessHostModelFavorites(ownerId: string | null, mutation?: Mode
};
const base = readDurable();
if (!mutation) return base.items;
- const op = parseModelFavoriteMutation(mutation);
+ const op = parseModelFavoriteMutation(mutation, LOCAL_FAVORITE_PROVIDER_ID_MAX_LENGTH);
if (op.kind !== 'add') {
const current = base.items.find(item => item.uid === op.expected.uid);
if (!current || !sameModelFavorite(current, op.expected)) throw new Error('Favorite changed; refresh before retrying');
diff --git a/apps/desktop/src/renderer/state/providerShareFavorites.ts b/apps/desktop/src/renderer/state/providerShareFavorites.ts
index 10ea7b3df2..c7bcbb74b3 100644
--- a/apps/desktop/src/renderer/state/providerShareFavorites.ts
+++ b/apps/desktop/src/renderer/state/providerShareFavorites.ts
@@ -8,6 +8,7 @@ import {
import type { ProviderShareReceivedSnapshot } from '../../shared/providerShare';
import {
accessHostModelFavorites,
+ LOCAL_FAVORITE_PROVIDER_ID_MAX_LENGTH,
type ModelFavoriteConfig,
type ModelFavoriteItem,
} from './modelFavorites';
@@ -17,13 +18,13 @@ const PREFIX = 'provider-share-favorite:';
type Source = { shareId: string; memberId: string; providerId: string; region: ProviderShareReceived['owner']['region'] };
/**
- * 复用受邀者账号的收藏存储和同步协议。providerId 是带分享/成员身份的存储键,
+ * 复用受邀者账号的收藏存储;远程同步保留既有长度约束。providerId 是带分享/成员身份的存储键,
* 只在对应分享的选择器里投影为真实 providerId,绝不用于模型请求。
* 老客户端不认识这个来源时不会把它误认成本机同名供应商。
*/
export function providerShareFavoriteSource(source: Pick<ProviderShareReceived, 'shareId' | 'memberId' | 'providerId' | 'owner'>): string {
const key = PREFIX + JSON.stringify([source.shareId, source.memberId, source.providerId, source.owner.region]);
- if (!source.shareId || !source.memberId || !source.providerId || key.length > 512)
+ if (!source.shareId || !source.memberId || !source.providerId || key.length > LOCAL_FAVORITE_PROVIDER_ID_MAX_LENGTH)
throw new Error('Invalid shared favorite source');
return key;
}
diff --git a/apps/desktop/src/renderer/state/useModelFavoritesHost.ts b/apps/desktop/src/renderer/state/useModelFavoritesHost.ts
index 4670f45ef3..29409e4a7d 100644
--- a/apps/desktop/src/renderer/state/useModelFavoritesHost.ts
+++ b/apps/desktop/src/renderer/state/useModelFavoritesHost.ts
@@ -1,4 +1,5 @@
import { useEffect } from 'react';
+import { MODEL_FAVORITE_TEXT_MAX_LENGTH } from '@cindy/device-link';
import {
getDataOwnerGeneration,
isDataOwnerPushStampCurrent,
@@ -14,7 +15,9 @@ export function useModelFavoritesHost(): void {
if (Date.now() > request.expiresAt || !isDataOwnerPushStampCurrent(request.ownerStamp))
throw new Error('Expired favorite request');
const items = accessHostModelFavorites(request.ownerStamp.dataOwnerId, request.mutation);
- api.reply({ requestId: request.requestId, items: [...items] });
+ // Long local composite sources cannot be represented by the existing wire
+ // protocol. Keep them on disk without breaking older readers' entire list.
+ api.reply({ requestId: request.requestId, items: items.filter((item) => item.providerId.length <= MODEL_FAVORITE_TEXT_MAX_LENGTH) });
} catch {
api.reply({ requestId: request.requestId, failed: true });
}
diff --git a/packages/device-link/src/__tests__/modelFavorites.test.ts b/packages/device-link/src/__tests__/modelFavorites.test.ts
index 6564192b1a..58ec1637fc 100644
--- a/packages/device-link/src/__tests__/modelFavorites.test.ts
+++ b/packages/device-link/src/__tests__/modelFavorites.test.ts
@@ -42,3 +42,15 @@ it("strips unknown fields and rejects invalid identities, duplicates, and effort
}),
).toThrow("identity");
});
+
+it("allows a larger local source bound without changing wire or other field limits", () => {
+ const longItem = { ...item, providerId: 'p'.repeat(2048) };
+ const add = { kind: 'add', item: longItem };
+ expect(parseModelFavoriteMutation(add, 2048)).toMatchObject({ kind: 'add', item: { providerId: longItem.providerId } });
+ expect(() => parseModelFavoriteMutation(add)).toThrow();
+ expect(() => parseModelFavorites([longItem])).toThrow();
+ expect(() => parseModelFavoriteMutation({ kind: 'add', item: { ...item, providerId: 'p'.repeat(2049) } }, 2048)).toThrow();
+ expect(() => parseModelFavoriteMutation({ kind: 'add', item: { ...item, modelId: 'm'.repeat(513) } }, 2048)).toThrow();
+ expect(() => parseModelFavoriteMutation({ kind: 'remove', expected: { ...longItem, uid: 'u'.repeat(513) } }, 2048)).toThrow();
+ expect(parseModelFavorites([{ ...item, providerId: 'p'.repeat(512) }])).toHaveLength(1);
+});
diff --git a/packages/device-link/src/modelFavorites.ts b/packages/device-link/src/modelFavorites.ts
index 9673035fab..40d4b0d562 100644
--- a/packages/device-link/src/modelFavorites.ts
+++ b/packages/device-link/src/modelFavorites.ts
@@ -18,18 +18,20 @@ export type ModelFavoriteMutation =
item: Omit<RemoteModelFavorite, "uid">;
}
| { kind: "remove"; expected: RemoteModelFavorite };
-const text = (v: unknown): v is string =>
- typeof v === "string" && v.length > 0 && v.length <= 512;
+export const MODEL_FAVORITE_TEXT_MAX_LENGTH = 512;
+const text = (v: unknown, max = MODEL_FAVORITE_TEXT_MAX_LENGTH): v is string =>
+ typeof v === "string" && v.length > 0 && v.length <= max;
export function parseRemoteModelFavorite(
value: unknown,
needsUid = true,
+ providerIdMaxLength = MODEL_FAVORITE_TEXT_MAX_LENGTH,
): RemoteModelFavorite {
if (!value || typeof value !== "object")
throw new Error("Invalid model favorite");
const p = value as RemoteModelFavorite;
if (
(needsUid && !text(p.uid)) ||
- !text(p.providerId) ||
+ !text(p.providerId, providerIdMaxLength) ||
p.providerId === "*" ||
!text(p.modelId) ||
!["cc", "codex", "pi"].includes(p.agent) ||
@@ -51,17 +53,19 @@ export function parseRemoteModelFavorite(
}
export function parseModelFavoriteMutation(
value: unknown,
+ // Local composite source keys may be longer; wire callers retain the default.
+ providerIdMaxLength = MODEL_FAVORITE_TEXT_MAX_LENGTH,
): ModelFavoriteMutation {
if (!value || typeof value !== "object")
throw new Error("Invalid favorite operation");
const p = value as ModelFavoriteMutation;
if (p.kind === "add")
- return { kind: p.kind, item: parseRemoteModelFavorite(p.item, false) };
+ return { kind: p.kind, item: parseRemoteModelFavorite(p.item, false, providerIdMaxLength) };
if (p.kind === "remove")
- return { kind: p.kind, expected: parseRemoteModelFavorite(p.expected) };
+ return { kind: p.kind, expected: parseRemoteModelFavorite(p.expected, true, providerIdMaxLength) };
if (p.kind === "update") {
- const expected = parseRemoteModelFavorite(p.expected),
- item = parseRemoteModelFavorite(p.item, false);
+ const expected = parseRemoteModelFavorite(p.expected, true, providerIdMaxLength),
+ item = parseRemoteModelFavorite(p.item, false, providerIdMaxLength);
if (
expected.providerId !== item.providerId ||
expected.modelId !== item.modelId