Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// @vitest-environment jsdom

// 2026-11-13 主人试用反馈:模式不能收藏、也不在「全部」里。现在「全部」整段列出模式,行尾 ☆ 收藏后出现在「收藏」,
// 点 ☆ 只收藏不选中。真实入口:ModelGroupsPickerSection + 本机收藏存储(localStorage)。Tier: unit。
// 点 ☆ 只收藏不选中。真实入口:ModelGroupsPickerSection + 跨端同步的收藏存储(modelFavorites)。Tier: unit。
import { act, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';

Expand All @@ -11,6 +11,10 @@ const i18nValue = { t: (key: string) => key };
vi.mock('react-i18next', () => ({ useTranslation: () => i18nValue }));
vi.mock('@/contexts/dataOwnerGeneration', () => ({ getDataOwnerGeneration: () => ({ dataOwnerId: 'owner-a' }) }));

import { MODEL_GROUP_FAVORITE_PROVIDER_ID } from '@cindy/device-link';

import { __resetForTest, __STORAGE_KEY, addModelFavorite, listModelFavorites, removeModelFavorite } from '@/state/modelFavorites';

import { ModelGroupsPickerSection } from '../ModelGroupsPickerSection';

const config = {
Expand All @@ -20,7 +24,10 @@ const config = {
],
} as unknown as ModelGroupsConfig;

afterEach(() => localStorage.clear());
afterEach(() => {
__resetForTest();
localStorage.clear();
});

describe('ModelGroupsPickerSection', () => {
it('lists every mode in 全部, and a starred mode shows up under 收藏 without being selected', () => {
Expand All @@ -42,13 +49,35 @@ describe('ModelGroupsPickerSection', () => {
expect(onSelect).toHaveBeenCalledWith({ type: 'route', id: 'cheap' });
favorites.unmount();

// 选择器都关着时,同账号的另一个窗口取消了收藏(本窗口这时不听 storage 事件):再打开要看到最新的。
localStorage.setItem('cindy:modelGroupFavorites:v1:owner-a', '[]');
// 路由收藏走跨端同步的收藏通道,手机端也能看到。
expect(listModelFavorites()).toEqual([
expect.objectContaining({ providerId: MODEL_GROUP_FAVORITE_PROVIDER_ID, modelId: 'cheap' }),
]);

// 选择器都关着时,同账号的另一个窗口(或手机)取消了收藏:再打开要看到最新的。
const stored = JSON.parse(localStorage.getItem(__STORAGE_KEY)!) as { items: unknown[] };
localStorage.setItem(__STORAGE_KEY, JSON.stringify({ ...stored, items: [] }));
window.dispatchEvent(new StorageEvent('storage', { key: __STORAGE_KEY, storageArea: localStorage }));
const reopened = render(<ModelGroupsPickerSection picker={picker} query="" onPicked={vi.fn()} variant="all" />);
expect(reopened.container.querySelector('[data-model-group-favorite="cheap"]')?.getAttribute('aria-pressed')).toBe('false');
reopened.unmount();
});

// 升级前收藏只存在本机 localStorage:打开选择器时搬进同步通道并删掉旧键,之后在别处取消不会被旧记录顶回来。
it('migrates legacy local route favorites into the synced favorites once', () => {
localStorage.setItem('cindy:modelGroupFavorites:v1:owner-a', JSON.stringify(['dev']));
const picker = { config, active: null, onSelect: vi.fn(), onManage: vi.fn() };
const view = render(<ModelGroupsPickerSection picker={picker} query="" onPicked={vi.fn()} variant="all" />);
expect(view.container.querySelector('[data-model-group-favorite="dev"]')?.getAttribute('aria-pressed')).toBe('true');
expect(localStorage.getItem('cindy:modelGroupFavorites:v1:owner-a')).toBeNull();
const migrated = listModelFavorites().find((item) => item.modelId === 'dev');
expect(migrated?.providerId).toBe(MODEL_GROUP_FAVORITE_PROVIDER_ID);

act(() => removeModelFavorite(migrated!.uid));
expect(view.container.querySelector('[data-model-group-favorite="dev"]')?.getAttribute('aria-pressed')).toBe('false');
view.unmount();
});

// 回归(2026-12-01 PR 设置跟进模型选模型组无反应): 异步 onSelect 解析前不得提前调 onPicked 关闭弹窗,
// 否则像 GhostCardModelSelect / PluginModelPickerPopover 这类关闭即结算的选择器会吞掉选择。Tier: unit。
it('waits for async onSelect before calling onPicked and stays open when selection returns false or rejects', async () => {
Expand Down Expand Up @@ -125,9 +154,12 @@ describe('ModelGroupsPickerSection', () => {
expect(onPicked).toHaveBeenCalledOnce();
});

// 回归(PR #14880 review): 插件表单 / 选模弹窗传入临时 favoritesOverride 时,点星标只改草稿副本,不写全局 localStorage。Tier: unit。
it('routes star toggles to favoritesOverride without mutating localStorage', () => {
localStorage.setItem('cindy:modelGroupFavorites:v1:owner-a', JSON.stringify(['dev']));
// 回归(PR #14880 review): 插件表单 / 选模弹窗传入临时 favoritesOverride 时,点星标只改草稿副本,不写全局收藏。Tier: unit。
it('routes star toggles to favoritesOverride without mutating the global favorites', () => {
addModelFavorite({ providerId: MODEL_GROUP_FAVORITE_PROVIDER_ID, modelId: 'dev', agent: 'cc' });
const globalRouteFavorites = () => listModelFavorites()
.filter((item) => item.providerId === MODEL_GROUP_FAVORITE_PROVIDER_ID)
.map((item) => item.modelId);
let draft = ['dev'];
const toggle = vi.fn((id: string) => {
draft = draft.includes(id) ? draft.filter((item) => item !== id) : [...draft, id];
Expand All @@ -145,7 +177,7 @@ describe('ModelGroupsPickerSection', () => {
expect(view.container.querySelector('[data-model-group-favorite="dev"]')?.getAttribute('aria-pressed')).toBe('true');
fireEvent.click(view.container.querySelector('[data-model-group-favorite="cheap"]')!);
expect(toggle).toHaveBeenCalledExactlyOnceWith('cheap');
expect(localStorage.getItem('cindy:modelGroupFavorites:v1:owner-a')).toBe(JSON.stringify(['dev']));
expect(globalRouteFavorites()).toEqual(['dev']);

view.rerender(
<ModelGroupsPickerSection
Expand All @@ -160,4 +192,21 @@ describe('ModelGroupsPickerSection', () => {
expect(screen.getByText('Cheap')).toBeTruthy();
view.unmount();
});

// 回归:localStorage 写满抛错时,migrateLegacy 不得误删旧本机收藏键,避免静默丢收藏。Tier: unit。
it('keeps the legacy localStorage key intact when persisting migrated favorites fails', () => {
localStorage.setItem('cindy:modelGroupFavorites:v1:owner-a', JSON.stringify(['dev']));
const setItemSpy = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
throw new DOMException('QuotaExceededError', 'QuotaExceededError');
});
try {
const picker = { config, active: null, onSelect: vi.fn() };
const view = render(<ModelGroupsPickerSection picker={picker} query="" onPicked={vi.fn()} variant="all" />);
expect(view.container.querySelector('[data-model-group-favorite="dev"]')?.getAttribute('aria-pressed')).toBe('true');
expect(localStorage.getItem('cindy:modelGroupFavorites:v1:owner-a')).toBe(JSON.stringify(['dev']));
view.unmount();
} finally {
setItemSpy.mockRestore();
}
});
});
Original file line number Diff line number Diff line change
@@ -1,24 +1,41 @@
/**
* 模型选择器里收藏的模式(model-groups.md §5):只记模式的 id,按账号分开存在这台电脑的 localStorage。
* 模式本身只存在这台电脑(设置里的 model-groups.json),所以收藏也不跨设备同步,不进模型收藏的同步协议。
* 模式被删后,收藏里留下的 id 在显示时按现有配置过滤,不报错。
* 模型选择器里收藏的自定义智能路由(model-groups.md §5)。
*
* 唯一真相是既有 `modelFavorites` 跨端同步通道(`providerId = "model-group-favorite:"`, `modelId = routeId`),
* 与手机端实时双向同步;模式被删后显示时按现有配置过滤,不报错。
*
* 旧版按账号存在本机 localStorage(`cindy:modelGroupFavorites:v1:<owner>`)的记录只做一次性迁移:
* 有人订阅或切换收藏时搬进同步通道并删掉旧键。迁移前显示时并上旧记录,避免升级瞬间收藏消失;
* 迁移后不再读旧键 —— 否则手机上取消的收藏会被这台电脑的旧记录一直顶回来。
*/
import { useSyncExternalStore } from 'react';
import {
isModelGroupFavoriteProviderId,
MODEL_GROUP_FAVORITE_PROVIDER_ID,
MODEL_GROUP_FAVORITE_WIRE_AGENT,
} from '@cindy/device-link';

import { getDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
import {
addModelFavorite,
listModelFavorites,
readDurableModelFavorites,
removeModelFavorite,
subscribeModelFavorites,
} from '@/state/modelFavorites';

const STORAGE_KEY = 'cindy:modelGroupFavorites:v1';
const LEGACY_STORAGE_KEY = 'cindy:modelGroupFavorites:v1';
const MAX_FAVORITES = 64;

const listeners = new Set<() => void>();
let cache: { key: string; ids: readonly string[] } | null = null;
let cache: { sig: string; ids: readonly string[] } | null = null;

function storageKey(): string {
function legacyStorageKey(): string {
const owner = getDataOwnerGeneration().dataOwnerId;
return owner ? `${STORAGE_KEY}:${encodeURIComponent(owner)}` : STORAGE_KEY;
return owner ? `${LEGACY_STORAGE_KEY}:${encodeURIComponent(owner)}` : LEGACY_STORAGE_KEY;
}

function read(key: string): readonly string[] {
function readLegacy(key: string): readonly string[] {
try {
const parsed: unknown = JSON.parse(localStorage.getItem(key) ?? '[]');
if (!Array.isArray(parsed)) return [];
Expand All @@ -28,9 +45,52 @@ function read(key: string): readonly string[] {
}
}

function readSynced(): readonly string[] {
try {
return [...new Set(listModelFavorites()
.filter((item) => isModelGroupFavoriteProviderId(item.providerId) && item.modelId.length > 0)
.map((item) => item.modelId))];
} catch {
return [];
}
}

function addSynced(id: string): void {
addModelFavorite({ providerId: MODEL_GROUP_FAVORITE_PROVIDER_ID, modelId: id, agent: MODEL_GROUP_FAVORITE_WIRE_AGENT });
}

/** 把本账号的旧本机收藏搬进同步通道,确认落盘后再删旧键;写不动(存储不可用)就留着下次再试。 */
function migrateLegacy(): void {
const key = legacyStorageKey();
let rawLegacy: string | null = null;
try {
rawLegacy = localStorage.getItem(key);
} catch {
return;
}
if (rawLegacy === null) return;
const legacy = readLegacy(key);
try {
if (legacy.length > 0) {
const synced = new Set(readSynced());
for (const id of legacy) if (!synced.has(id)) addSynced(id);
const durable = readDurableModelFavorites();
if (!durable) return;
const durableIds = new Set(
durable.filter((item) => isModelGroupFavoriteProviderId(item.providerId)).map((item) => item.modelId),
);
if (legacy.some((id) => !durableIds.has(id))) return;
}
localStorage.removeItem(key);
} catch {
// 留着旧键,显示时照样并上,下次订阅再迁。
}
}

function snapshot(): readonly string[] {
const key = storageKey();
if (!cache || cache.key !== key) cache = { key, ids: read(key) };
const ids = [...new Set([...readSynced(), ...readLegacy(legacyStorageKey())])].slice(0, MAX_FAVORITES);
const sig = ids.join('\u0000');
if (!cache || cache.sig !== sig) cache = { sig, ids };
return cache.ids;
}

Expand All @@ -39,31 +99,36 @@ function emit(): void {
}

function subscribe(listener: () => void): () => void {
// 没人订阅时本窗口不听别的窗口的改动:重新有人订阅时先丢掉缓存,补上这段时间别处的收藏变化。
if (listeners.size === 0) cache = null;
listeners.add(listener);
const onStorage = (event: StorageEvent) => {
if (event.key !== storageKey()) return;
cache = null;
// 同步通道自己常驻监听其它窗口和账号切换;收到通知时顺手检查新账号是否有旧本机键待迁(常规仅一次空读)。
const onSyncedChange = () => {
migrateLegacy();
listener();
};
window.addEventListener('storage', onStorage);
const unsubscribeSynced = subscribeModelFavorites(onSyncedChange);
migrateLegacy();
return () => {
listeners.delete(listener);
window.removeEventListener('storage', onStorage);
unsubscribeSynced();
};
}

/** 收藏或取消收藏一个模式;写失败只影响这次,不打断选择器。 */
/** 收藏或取消收藏一个模式;写进跨端同步的收藏,写失败不影响选择器。 */
export function toggleModelGroupFavorite(id: string): void {
const key = storageKey();
const current = read(key);
const next = current.includes(id) ? current.filter((item) => item !== id) : [...current, id].slice(-MAX_FAVORITES);
cache = { key, ids: next };
migrateLegacy();
const current = snapshot();
const removing = current.includes(id);
if (!removing && current.length >= MAX_FAVORITES) return;
try {
localStorage.setItem(key, JSON.stringify(next));
if (removing) {
for (const item of listModelFavorites()) {
if (isModelGroupFavoriteProviderId(item.providerId) && item.modelId === id) removeModelFavorite(item.uid);
}
} else {
addSynced(id);
}
} catch {
// 写不进去时这次收藏只在本窗口生效。
// 存储不可用时这次改动不生效,选择器照常可用。
}
emit();
}
Expand Down
11 changes: 11 additions & 0 deletions apps/desktop/src/renderer/state/modelFavorites.ts
Original file line number Diff line number Diff line change
Expand Up @@ -678,6 +678,17 @@ export function __resetForTest(): void {

export const __STORAGE_KEY = STORAGE_KEY;

/** 直接读当前分区已落盘到 localStorage 的收藏条目(绕过内存 cache),供迁移方确认持久化成功后再清旧键。 */
export function readDurableModelFavorites(): readonly ModelFavoriteItem[] | null {
if (typeof window === 'undefined') return null;
try {
const raw = window.localStorage.getItem(storageKey());
return raw === null ? [] : sanitize(JSON.parse(raw)).items;
} catch {
return null;
}
}

/** Narrow host RPC entry: preserve old data and use existing per-item operations.
* Synchronous execution prevents an owner change between comparison and write. */
export function accessHostModelFavorites(ownerId: string | null, mutation?: ModelFavoriteMutation): readonly ModelFavoriteItem[] {
Expand Down
Loading
Loading