Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(models): 支持收藏同账号其他电脑上的模型 (#5910)
Dashfe6dff382796
diff --git a/apps/desktop/src/renderer/__tests__/agentDeviceFavorites.test.tsx b/apps/desktop/src/renderer/__tests__/agentDeviceFavorites.test.tsxnew file mode 100644index 0000000000..aa7f2287ef--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/agentDeviceFavorites.test.tsx@@ -0,0 +1,206 @@+// @vitest-environment jsdom+/**+ * 远程 Agent 的收藏(model-selector-unified §1.5「远程收藏按被控电脑共享」):浏览另一台电脑的目录时,+ * 收藏仍读写任务所在电脑那一份列表,运行位置编进 providerId。锁住:+ * 1. 只投影编码成那台电脑的条目,并还原成那台的真实 providerId;+ * 2. 新增编码后写进 home,编辑 / 删除只认属于那台的锚点;+ * 3. 编码成任务所在电脑自己的条目按普通收藏用;分享的设备 id 不认;+ * 4. 编码后的 providerId 仍能经既有收藏同步协议(≤512)发给远程控制端。+ */+import { act, cleanup, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ agentDeviceFavoriteSource,+ MODEL_FAVORITE_TEXT_MAX_LENGTH,+ parseModelFavorites,+} from '@cindy/device-link';+import type { ModelFavoritesHostApi } from '../../shared/modelFavoritesSync';+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';+import {+ __resetForTest,+ addModelFavorite,+ listModelFavorites,+ setModelFavoritesOwner,+ useModelFavorites,+ type ModelFavoriteItem,+} from '@/state/modelFavorites';+import {+ agentDeviceOfFavorite,+ LOCAL_MODEL_FAVORITE_STORE,+ useAgentDeviceFavorites,+} from '@/state/agentDeviceFavorites';+import type { FavoriteStore } from '@/state/useRemoteModelFavorites';+import { useModelFavoritesHost } from '@/state/useModelFavoritesHost';++const config = {+ providerId: 'anthropic',+ modelId: 'opus',+ agent: 'cc' as const,+ effort: 'high' as const,+};+const mountLocal = (deviceId: string | undefined, homeDeviceId: string | null = null) =>+ renderHook(+ (props: { deviceId: string | undefined }) =>+ useAgentDeviceFavorites({+ deviceId: props.deviceId,+ homeDeviceId,+ home: { items: useModelFavorites(), store: LOCAL_MODEL_FAVORITE_STORE },+ }),+ { initialProps: { deviceId } },+ );++beforeEach(() => {+ __resetForTest();+ window.localStorage.clear();+ setDataOwnerGeneration('owner', 1);+ setModelFavoritesOwner('owner');+});+afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe('favorites of another computer live in the home list', () => {+ it('writes the encoded source into the home list and projects only that computer back', () => {+ addModelFavorite(config);+ const studio = mountLocal('device-c');+ expect(studio.result.current.items).toEqual([]);+ act(() => {+ studio.result.current.store.add(config);+ });+ const stored = listModelFavorites();+ expect(stored).toHaveLength(2);+ expect(stored[1]!.providerId).toBe(+ agentDeviceFavoriteSource({ deviceId: 'device-c', providerId: 'anthropic' }),+ );+ expect(studio.result.current.items).toEqual([{ ...config, uid: stored[1]!.uid }]);+ // 另一台电脑看不到 device-c 的收藏;同配置在本机与 device-c 是两条。+ const office = mountLocal('device-d');+ expect(office.result.current.items).toEqual([]);+ act(() => {+ studio.result.current.store.add(config);+ });+ expect(listModelFavorites()).toHaveLength(2);+ });++ it('edits and removes only anchors that belong to that computer', () => {+ addModelFavorite(config);+ const localUid = listModelFavorites()[0]!.uid;+ const studio = mountLocal('device-c');+ act(() => {+ studio.result.current.store.add(config);+ });+ const uid = studio.result.current.items[0]!.uid;+ act(() => {+ studio.result.current.store.update(uid, { effort: 'low', fast: true });+ });+ expect(listModelFavorites()[1]).toMatchObject({+ providerId: agentDeviceFavoriteSource({ deviceId: 'device-c', providerId: 'anthropic' }),+ effort: 'low',+ fast: true,+ });+ expect(studio.result.current.store.get(uid)).toMatchObject({+ providerId: 'anthropic',+ effort: 'low',+ });+ // 本机那条的锚点不能经那台电脑的视图改动或删除。+ expect(() => studio.result.current.store.remove(localUid)).toThrow();+ expect(() => studio.result.current.store.update(localUid, { effort: 'low' })).toThrow();+ act(() => {+ studio.result.current.store.remove(uid);+ });+ expect(listModelFavorites()).toEqual([expect.objectContaining(config)]);+ });++ it('keeps the home view in list order and treats the home computer encoding as a plain favorite', () => {+ addModelFavorite({+ ...config,+ providerId: agentDeviceFavoriteSource({ deviceId: 'device-c', providerId: 'anthropic' }),+ });+ addModelFavorite({+ ...config,+ providerId: agentDeviceFavoriteSource({ deviceId: 'home-pc', providerId: 'openai' }),+ });+ addModelFavorite(config);+ const home = mountLocal(undefined, 'home-pc');+ expect(home.result.current.items.map((item) => item.providerId)).toEqual([+ agentDeviceFavoriteSource({ deviceId: 'device-c', providerId: 'anthropic' }),+ 'openai',+ 'anthropic',+ ]);+ // 浏览任务所在电脑自己 = home 视图,不当作另一台电脑。+ home.rerender({ deviceId: 'home-pc' });+ expect(home.result.current.items.map((item) => item.providerId)[1]).toBe('openai');+ expect(agentDeviceOfFavorite(listModelFavorites()[1]!.providerId, 'home-pc')).toBeNull();+ expect(agentDeviceOfFavorite(listModelFavorites()[0]!.providerId, 'home-pc')).toEqual({+ deviceId: 'device-c',+ providerId: 'anthropic',+ });+ expect(agentDeviceOfFavorite('anthropic', null)).toBeNull();+ // 分享的设备 id 有自己的收藏存储,不认这种编码。+ expect(+ agentDeviceOfFavorite(+ agentDeviceFavoriteSource({ deviceId: 'share:abc', providerId: 'p' }),+ null,+ ),+ ).toBeNull();+ });++ it('writes through the remote home store when the home list is on a controlled computer', async () => {+ const encoded = agentDeviceFavoriteSource({ deviceId: 'device-c', providerId: 'anthropic' });+ const items: ModelFavoriteItem[] = [+ { uid: 'fav-1', ...config },+ { uid: 'fav-2', ...config, providerId: encoded },+ ];+ const store: FavoriteStore = {+ get: (uid) => items.find((item) => item.uid === uid),+ add: vi.fn(async () => {}),+ update: vi.fn(async () => {}),+ remove: vi.fn(async () => {}),+ };+ const view = renderHook(() =>+ useAgentDeviceFavorites({+ deviceId: 'device-c',+ homeDeviceId: 'device-b',+ home: { items, store },+ }),+ );+ expect(view.result.current.items).toEqual([{ uid: 'fav-2', ...config }]);+ await view.result.current.store.add({ ...config, effort: 'low' });+ expect(store.add).toHaveBeenCalledWith({ ...config, effort: 'low', providerId: encoded });+ await view.result.current.store.update('fav-2', { fast: true });+ expect(store.update).toHaveBeenCalledWith('fav-2', { fast: true });+ expect(() => view.result.current.store.remove('fav-1')).toThrow();+ await view.result.current.store.remove('fav-2');+ expect(store.remove).toHaveBeenCalledWith('fav-2');+ });++ it('fits the existing favorites wire protocol so a remote controller sees the entry', () => {+ const deviceId = '7f3c2a10-1b2c-4d5e-8f90-0123456789ab';+ const providerId = 'p'.repeat(256);+ const encoded = agentDeviceFavoriteSource({ deviceId, providerId });+ expect(encoded.length).toBeLessThanOrEqual(MODEL_FAVORITE_TEXT_MAX_LENGTH);+ const studio = mountLocal(deviceId);+ act(() => {+ studio.result.current.store.add({ ...config, providerId });+ });+ 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: 'owner', ownerGeneration: 1 },+ }),+ );+ expect(parseModelFavorites(reply.mock.calls[0]![0].items)).toEqual([+ expect.objectContaining({ providerId: encoded, modelId: 'opus' }),+ ]);+ });+});diff --git a/apps/desktop/src/renderer/__tests__/remoteAgentDeviceFavoritesPanel.test.tsx b/apps/desktop/src/renderer/__tests__/remoteAgentDeviceFavoritesPanel.test.tsxnew file mode 100644index 0000000000..7a5bb97286--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/remoteAgentDeviceFavoritesPanel.test.tsx@@ -0,0 +1,394 @@+// @vitest-environment jsdom+/**+ * 收藏另一台电脑上的模型(远程 Agent),用起来与本机收藏一样(model-selector-unified §1.5「远程收藏按+ * 被控电脑共享」):+ * 1. 浏览那台电脑的目录时点 ☆:写进任务所在电脑那一份收藏(运行位置编进 providerId),不读写那台+ * 电脑自己的收藏;+ * 2. 回到任务所在电脑的目录,收藏区照样列出它,来源名带那台电脑;选中 = 在那台电脑上运行;+ * 3. 那台的目录读不到时置灰列出;目录里已没有这个模型时不显示,收藏保留;+ * 4. 被控电脑上的任务:收藏读写被控电脑那一份(经设备互联)。+ */+import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react';+import React from 'react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ agentDeviceFavoriteSource,+ MODEL_FAVORITES_APPLY,+ MODEL_FAVORITES_GET,+ type ModelFavoriteMutation,+ type RemoteModelFavorite,+} from '@cindy/device-link';++vi.mock('react-i18next', async (importOriginal) => ({+ ...(await importOriginal<typeof import('react-i18next')>()),+ useTranslation: () => ({+ t: (key: string, options?: Record<string, string>) => {+ const table: Record<string, string> = {+ 'newChat.modelSelector.modelListAria': '模型列表',+ 'newChat.modelSelector.search.placeholderAll': '搜索模型…',+ 'newChat.modelSelector.unified.favoritesGroup': '收藏',+ 'newChat.modelSelector.unified.addFavorite': '收藏',+ 'newChat.modelSelector.unified.removeFavorite': '取消收藏',+ 'newChat.modelSelector.unified.customize': '自定义',+ 'newChat.modelSelector.unified.railAll': '全部',+ 'newChat.modelSelector.unified.railRemoteProvider': `${options?.provider ?? ''} · ${options?.device ?? ''}`,+ 'newChat.modelSelector.unified.remoteFavoriteUnavailable': `${options?.source ?? ''} · 读不到`,+ 'effortLevels.low': '低',+ 'effortLevels.high': '高',+ };+ return table[key] ?? options?.defaultValue ?? key;+ },+ }),+}));++vi.mock('@/lib/scrollbarAutoHide', () => ({ flashScrollbar: vi.fn() }));++vi.mock('@/hooks/useAgentCapabilities', () => ({+ evictDeviceCapabilities: vi.fn(),+ prefetchDeviceCapabilities: vi.fn(async () => {}),+ useAgentCapabilities: () => ({+ capabilities: { hasFastMode: false, effortLevels: [], availableModels: [] },+ loading: false,+ error: null,+ }),+}));+vi.mock('@/hooks/useApiKey', () => ({ useApiKey: () => ({ hasSavedKey: true }) }));+vi.mock('@/hooks/useConnectedSource', () => ({+ useConnectedSource: () => ({ hasConnectedSource: true, loading: false }),+}));+vi.mock('@/hooks/useModelPricing', () => ({+ useGatewayModelPricing: () => null,+ useReferenceModelPricing: () => null,+}));++const catalogs = vi.hoisted(() => {+ const provider = (+ id: string,+ name: string,+ models: readonly (readonly [string, string])[],+ extra: Record<string, unknown> = {},+ ) => ({+ id,+ name,+ source: 'user',+ agents: ['claude-code'],+ auth: { method: 'api-key' },+ routing: { 'claude-code': {} },+ connected: true,+ models: {+ 'claude-code': models.map(([modelId, modelName]) => ({+ id: modelId,+ name: modelName,+ contextWindow: 200000,+ efforts: ['low', 'high'],+ defaultEffort: 'high',+ })),+ },+ ...extra,+ });+ return {+ offline: new Set<string>(),+ local: [provider('a-local', 'A Local', [['a-model', 'A Model']])] as unknown[],+ byDevice: {+ 'device-b': [provider('b-main', 'B Main', [['b-model', 'B Model']])],+ 'device-c': [+ provider('c-open', 'C Open', [['c-model', 'C Model']], { remoteInvocationEnabled: true }),+ ],+ } as Record<string, unknown[]>,+ };+});++vi.mock('@/hooks/useProviders', () => ({+ useProviders: () => ({ providers: catalogs.local, providerOrder: [] }),+}));+vi.mock('@/hooks/useDeviceProviders', () => ({+ evictDeviceProviders: vi.fn(),+ prefetchDeviceProviders: vi.fn(async () => {}),+ useDeviceProviders: (deviceId?: string) =>+ deviceId && catalogs.offline.has(deviceId)+ ? { providers: [], loading: false, error: 'DEVICE_LINK_UNREACHABLE', unsupported: false }+ : {+ providers: deviceId ? (catalogs.byDevice[deviceId] ?? []) : [],+ loading: false,+ error: null,+ unsupported: false,+ },+}));+vi.mock('@/hooks/useDevicesProviders', () => ({+ useDevicesProviders: (deviceIds: readonly string[]) =>+ new Map(+ deviceIds.map((deviceId) => [+ deviceId,+ catalogs.offline.has(deviceId)+ ? { providers: [], loading: false, error: 'DEVICE_LINK_UNREACHABLE' }+ : { providers: catalogs.byDevice[deviceId] ?? [], loading: false, error: null },+ ]),+ ),+}));+vi.mock('@/state/modelVisibilityPrefs', () => ({+ isModelEnabled: () => true,+ useModelVisibilityVersion: () => 0,+}));+vi.mock('@/state/deviceLinkModelMirror', () => ({+ useDeviceLinkModelMirrorVersion: () => 0,+}));+vi.mock('@/hooks/useRemoteDeviceUsage', () => ({+ useRemoteCodexAccountUsage: () => null,+ useRemoteXaiSubscriptionUsage: () => null,+}));+vi.mock('@/hooks/useRemoteClaudeSubscriptionUsage', () => ({+ useRemoteClaudeSubscriptionUsage: () => null,+}));++import { ModelSelectorContent } from '@/components/new-chat/ModelSelector';+import { __resetForTest as resetEnginePrefs } from '@/state/modelEnginePrefs';+import {+ __resetForTest as resetFavorites,+ addModelFavorite,+ listModelFavorites,+} from '@/state/modelFavorites';++const devices = [{ deviceId: 'device-c', name: 'Studio' }];+const C_SOURCE = agentDeviceFavoriteSource({ deviceId: 'device-c', providerId: 'c-open' });++/** 设备互联:被控电脑 device-b 上的一份收藏(其他电脑的读写都记下来,应当一次都没有)。 */+let remoteLists: Record<string, RemoteModelFavorite[]>;+let invoke: ReturnType<typeof vi.fn>;+beforeEach(() => {+ resetEnginePrefs();+ resetFavorites();+ catalogs.offline.clear();+ remoteLists = { 'device-b': [] };+ let seq = 1;+ invoke = vi.fn(async (deviceId: string, channel: string, args: unknown[]) => {+ const list = remoteLists[deviceId];+ if (!list) throw new Error('no favorites on this device');+ if (channel === MODEL_FAVORITES_GET) return list;+ if (channel === MODEL_FAVORITES_APPLY) {+ const mutation = args[0] as ModelFavoriteMutation;+ if (mutation.kind === 'add') list.push({ uid: `fav-${seq++}`, ...mutation.item });+ if (mutation.kind === 'remove')+ remoteLists[deviceId] = list.filter((item) => item.uid !== mutation.expected.uid);+ return remoteLists[deviceId];+ }+ throw new Error(`unexpected ${channel}`);+ });+ vi.stubGlobal('electronAPI', {+ deviceLink: {+ invoke,+ onRemotePush: () => () => {},+ onStatusChanged: () => () => {},+ onPeerLinkReset: () => () => {},+ onResponsivenessChanged: () => () => {},+ },+ });+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++const list = () => screen.getByRole('listbox');+const favoritesGroup = () => within(list()).getByRole('group', { name: '收藏' });+const rowOf = (scope: HTMLElement, name: string) =>+ within(scope).getByText(name).closest('[data-unified-anchor]') as HTMLElement;++function renderPanel(+ remoteAgent: Partial<React.ComponentProps<typeof ModelSelectorContent>['remoteAgent']> = {},+ props: Partial<React.ComponentProps<typeof ModelSelectorContent>> = {},+) {+ const onUnifiedSelect = vi.fn(async () => true);+ const onRelocate = vi.fn(async () => true);+ const onProviderChange = vi.fn();+ render(+ React.createElement(ModelSelectorContent, {+ modelId: 'a-model',+ effort: 'high',+ onModelChange: vi.fn(),+ onEffortChange: vi.fn(),+ currentProviderId: 'a-local',+ onProviderChange,+ vendorKey: 'cc',+ onUnifiedSelect,+ remoteAgent: { devices, selectedDeviceId: null, ...remoteAgent },+ ...props,+ }),+ );+ return { onUnifiedSelect, onRelocate, onProviderChange };+}++describe('本机任务:收藏另一台电脑上的模型', () => {+ it('浏览那台电脑时点 ☆ 写进本机收藏,不读写那台电脑自己的收藏', async () => {+ renderPanel();+ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: 'C Open · Studio' }));+ });+ const row = rowOf(list(), 'C Model');+ await act(async () => {+ fireEvent.click(within(row).getByRole('button', { name: '收藏' }));+ });+ expect(listModelFavorites()).toEqual([+ expect.objectContaining({ providerId: C_SOURCE, modelId: 'c-model', agent: 'cc' }),+ ]);+ // 那台电脑的视图里照样列出这条收藏(还原成那台的真实 providerId)。+ expect(within(favoritesGroup()).getByText('C Model')).toBeTruthy();+ expect(invoke.mock.calls.some(([deviceId]) => deviceId === 'device-c')).toBe(false);+ });++ it('回到本机目录:收藏区列出它并带上电脑名,选中 = 在那台电脑运行', async () => {+ addModelFavorite({ providerId: C_SOURCE, modelId: 'c-model', agent: 'cc', effort: 'low' });+ const uid = listModelFavorites()[0]!.uid;+ const { onUnifiedSelect, onProviderChange } = renderPanel();+ const row = rowOf(favoritesGroup(), 'C Model');+ expect(within(row).getByText('C Open · Studio')).toBeTruthy();+ // 配置在那台电脑的目录里调,这里不出配置浮层。+ expect(within(row).queryByRole('button', { name: '自定义' })).toBeNull();+ await act(async () => {+ fireEvent.click(row);+ });+ expect(onUnifiedSelect).toHaveBeenCalledWith(+ expect.objectContaining({+ providerId: 'c-open',+ modelId: 'c-model',+ engine: 'cc',+ effort: 'low',+ favoriteUid: uid,+ agentDevice: { deviceId: 'device-c', name: 'Studio' },+ }),+ );+ expect(onProviderChange).not.toHaveBeenCalled();+ });++ it('在本机目录里取消这条收藏', async () => {+ addModelFavorite({ providerId: C_SOURCE, modelId: 'c-model', agent: 'cc' });+ renderPanel();+ const row = rowOf(favoritesGroup(), 'C Model');+ await act(async () => {+ fireEvent.click(within(row).getByRole('button', { name: '取消收藏' }));+ });+ expect(listModelFavorites()).toEqual([]);+ });++ it('已建任务:Agent 在本机时选中它 = 连运行位置一起换到那台电脑', async () => {+ addModelFavorite({ providerId: C_SOURCE, modelId: 'c-model', agent: 'cc' });+ const onRelocate = vi.fn(async () => true);+ const { onProviderChange } = renderPanel(+ { onRelocate },+ { actualRoute: true, onUnifiedSelect: undefined },+ );+ await act(async () => {+ fireEvent.click(rowOf(favoritesGroup(), 'C Model'));+ });+ expect(onRelocate).toHaveBeenCalledWith(+ expect.objectContaining({+ providerId: 'c-open',+ modelId: 'c-model',+ agent: 'claude-code',+ agentDevice: { deviceId: 'device-c', name: 'Studio' },+ }),+ );+ expect(onProviderChange).not.toHaveBeenCalled();+ });++ it('已建任务:Agent 已在那台电脑时切到那台的目录,由那里的会话链路选', async () => {+ addModelFavorite({ providerId: C_SOURCE, modelId: 'c-model', agent: 'cc' });+ const onRelocate = vi.fn(async () => true);+ renderPanel(+ { onRelocate, selectedDeviceId: 'device-c' },+ {+ actualRoute: true,+ onUnifiedSelect: undefined,+ modelId: 'c-model',+ currentProviderId: 'c-open',+ },+ );+ // 打开时停在那台的目录;切回本机目录(「全部」视图,按本机供应商筛的格不列其他电脑的收藏)。+ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: '全部' }));+ });+ await act(async () => {+ fireEvent.click(rowOf(favoritesGroup(), 'C Model'));+ });+ expect(onRelocate).not.toHaveBeenCalled();+ expect(+ screen.getByRole('button', { name: 'C Open · Studio' }).getAttribute('aria-pressed'),+ ).toBe('true');+ expect(within(favoritesGroup()).getByText('C Model')).toBeTruthy();+ });++ it('那台的目录读不到:置灰列出;目录里已没有这个模型:不显示,收藏保留', async () => {+ addModelFavorite({ providerId: C_SOURCE, modelId: 'c-model', agent: 'cc' });+ addModelFavorite({+ providerId: agentDeviceFavoriteSource({ deviceId: 'device-c', providerId: 'c-open' }),+ modelId: 'gone-model',+ agent: 'cc',+ });+ catalogs.offline.add('device-c');+ const { onUnifiedSelect } = renderPanel();+ const row = rowOf(favoritesGroup(), 'c-model');+ expect(row.getAttribute('aria-disabled')).toBe('true');+ expect(within(row).getByText('c-open · Studio · 读不到')).toBeTruthy();+ await act(async () => {+ fireEvent.click(row);+ });+ expect(onUnifiedSelect).not.toHaveBeenCalled();+ cleanup();++ catalogs.offline.clear();+ renderPanel();+ expect(within(favoritesGroup()).getByText('C Model')).toBeTruthy();+ expect(within(list()).queryByText('gone-model')).toBeNull();+ expect(listModelFavorites()).toHaveLength(2);+ });+});++describe('被控电脑上的任务:收藏读写被控电脑那一份', () => {+ it('浏览第三台电脑时点 ☆ 经设备互联写进被控电脑的收藏,回到被控电脑目录照样列出', async () => {+ renderPanel(+ { homeDeviceId: 'device-b' },+ { deviceId: 'device-b', modelId: 'b-model', currentProviderId: 'b-main' },+ );+ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: 'C Open · Studio' }));+ });+ const row = rowOf(list(), 'C Model');+ await act(async () => {+ fireEvent.click(within(row).getByRole('button', { name: '收藏' }));+ });+ expect(invoke).toHaveBeenCalledWith('device-b', MODEL_FAVORITES_APPLY, [+ {+ kind: 'add',+ item: expect.objectContaining({ providerId: C_SOURCE, modelId: 'c-model', agent: 'cc' }),+ },+ ]);+ expect(invoke.mock.calls.some(([deviceId]) => deviceId === 'device-c')).toBe(false);+ // 本机自己的收藏不动。+ expect(listModelFavorites()).toEqual([]);+ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: '全部' }));+ });+ expect(within(favoritesGroup()).getByText('C Model')).toBeTruthy();+ });++ it('远程控制(不经远程 Agent)照旧读被控电脑自己的收藏', async () => {+ remoteLists['device-b'] = [+ { uid: 'fav-9', providerId: 'b-main', modelId: 'b-model', agent: 'cc' },+ ];+ render(+ React.createElement(ModelSelectorContent, {+ modelId: 'b-model',+ effort: 'high',+ onModelChange: vi.fn(),+ onEffortChange: vi.fn(),+ currentProviderId: 'b-main',+ onProviderChange: vi.fn(),+ vendorKey: 'cc',+ deviceId: 'device-b',+ }),+ );+ await act(async () => {});+ expect(invoke).toHaveBeenCalledWith('device-b', MODEL_FAVORITES_GET, []);+ expect(within(favoritesGroup()).getByText('B Model')).toBeTruthy();+ });+});diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsxindex 5e38c93ead..463e8aee25 100644--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx@@ -1669,10 +1669,20 @@ function ModelSelectorContentView({});const providerIds = [...new Set(entries.map((entry) => entry.providerId))];return providerIds.length > 0- ? [{ deviceId: device.deviceId, providers: shared, providerIds }]+ ? [{ deviceId: device.deviceId, providers: shared, providerIds, entries }]: [];});}, [remoteAgentDevices, remoteDeviceCatalogs, remoteProviderGroups]);+ // 目录还在读或读取失败的其他电脑(分享不算):收藏区里它们的收藏置灰列出,不当作模型已下架。+ const remoteAgentUnavailableDeviceIds = useMemo(+ () =>+ (remoteAgentDevices ?? []).flatMap((device) => {+ if (isProviderShareAgentDeviceId(device.deviceId)) return [];+ const catalog = remoteDeviceCatalogs.get(device.deviceId);+ return !catalog || catalog.loading || catalog.error ? [device.deviceId] : [];+ }),+ [remoteAgentDevices, remoteDeviceCatalogs],+ );const hasRemoteAgent = remoteAgent !== undefined;const homeProviders = homeDeviceId ? homeDeviceProviders.providers : localProviders.providers;const homeModelVisibilityOverrides = homeDeviceProviders.modelVisibilityOverrides;@@ -3355,6 +3365,63 @@ function ModelSelectorContentView({}return applied;});+ /**+ * 收藏区里另一台电脑上的收藏(浏览任务所在电脑的目录时列出):效果与左侧栏切到那台电脑再选中它相同。+ * - 草稿:整行带着那台电脑交给 onUnifiedSelect(同浏览那台时的 withAgentDevice);+ * - 已建任务、Agent 不在那台:连运行位置一起换(onRelocate,同浏览那台时的 relocate);+ * - 已建任务、Agent 已在那台 / 那一项是任务归的供应商组:这一选择要走那台目录里的会话链路+ * (同引擎直切 / 跨引擎事务 / 组内留在原处),这里不另起一套 —— 切到那台的目录,同一条收藏在+ * 那里照样列出,由用户在那里选。+ */+ const selectDeviceFavorite: NonNullable<+ NonNullable<UnifiedModelPanelProps['remoteSources']>['onSelectDeviceFavorite']+ > = ({ deviceId: targetDeviceId, providerId, modelId: id, effort: rowEffort, config: rowConfig }) => {+ const rowEffortValue = rowEffort === '' ? undefined : rowEffort;+ const agentDevice = {+ deviceId: targetDeviceId,+ name: remoteAgentDevices?.find((device) => device.deviceId === targetDeviceId)?.name || targetDeviceId,+ };+ const dismissIfApplied = (applied: boolean) => {+ if (applied) {+ closeOptionsPanel();+ onDismiss?.();+ }+ return applied;+ };+ if (onUnifiedSelect) {+ return runLiveWrite(() =>+ onUnifiedSelect({+ providerId,+ modelId: id,+ ...(rowEffortValue ? { effort: rowEffortValue } : {}),+ engine: rowConfig.engine,+ fast: rowConfig.fast,+ favoriteUid: rowConfig.favoriteUid,+ agentDevice,+ }),+ ).then(dismissIfApplied);+ }+ const agent = vendorKeyToAgentKind(rowConfig.engine);+ const inBoundGroup =+ stayInGroup && boundEntry?.deviceId === targetDeviceId && boundEntry.providerId === providerId;+ const onRelocate = remoteAgent?.onRelocate;+ if (onRelocate && agent && targetDeviceId !== remoteAgentDeviceId && !inBoundGroup) {+ return runLiveWrite(() =>+ onRelocate({+ providerId,+ modelId: id,+ agent,+ ...(rowEffortValue ? { effort: rowEffortValue } : {}),+ fast: rowConfig.fast,+ agentDevice,+ }),+ ).then(dismissIfApplied);+ }+ closeOptionsPanel();+ setRemoteBrowseTouched(true);+ setRemoteBrowse({ deviceId: targetDeviceId, providerId });+ return false;+ };const panelSessionEngineFilter =sessionEngineFilter && relocate? {@@ -3474,6 +3541,11 @@ function ModelSelectorContentView({localProviderLabel: remoteAgentLocalLabel,groups: remoteAgentGroups,labelOf: remoteAgentLabelOf,+ // 远程收藏按任务所在电脑共享(§1.5):被控电脑上的任务读写那台的收藏,本机任务读写本机。+ ...(homeDeviceId ? { favoritesDeviceId: homeDeviceId } : {}),+ homeDeviceId: homeDeviceId ?? selfDeviceId,+ unavailableDeviceIds: remoteAgentUnavailableDeviceIds,+ onSelectDeviceFavorite: selectDeviceFavorite,active: remoteBrowse? { deviceId: remoteBrowse.deviceId, providerId: remoteActiveProviderId ?? '' }: null,diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsxindex 0f23d3e576..47ab4fcce2 100644--- a/apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx@@ -26,7 +26,8 @@ import {type SourceUsage = ProviderUsageSnapshots & {source: NonNullable<ProviderUsageSnapshots['source']>;};-const UsageContext = createContext<ReadonlyMap<string, SourceUsage>>(new Map());+const NO_USAGE: ReadonlyMap<string, SourceUsage> = new Map();+const UsageContext = createContext<ReadonlyMap<string, SourceUsage>>(NO_USAGE);const ClockContext = createContext(0);/** One reader per connection, shared by all model/favorite/sizing rows. Existing@@ -58,6 +59,7 @@ export function ModelSourceUsageProvider({providers,scope,groupUsageOf,+ isolated = false,children,}: {providers: readonly ProviderView[];@@ -65,6 +67,11 @@ export function ModelSourceUsageProvider({scope: ProviderUsageScope | null;/** 目录里的供应商组读谁的账号(provider-groups.md §10);缺省 = 都按目录归属读。 */groupUsageOf?: (providerId: string) => ProviderGroupUsage | null;+ /**+ * 不继承外层目录的用量:嵌在另一份目录里的行(收藏区里另一台电脑的收藏)与外层可能有同 id 的+ * 供应商,继承会把外层账号的余量显示在这一行上。+ */+ isolated?: boolean;children: ReactNode;}) {const [nowMs, setNowMs] = useState(Date.now);@@ -100,7 +107,15 @@ export function ModelSourceUsageProvider({);}, children): children;- return <ClockContext.Provider value={nowMs}>{content}</ClockContext.Provider>;+ return (+ <ClockContext.Provider value={nowMs}>+ {isolated ? (+ <UsageContext.Provider value={NO_USAGE}>{content}</UsageContext.Provider>+ ) : (+ content+ )}+ </ClockContext.Provider>+ );}interface QuotaWindow {diff --git a/apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx b/apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsxindex d667c09ed2..6e840a83f4 100644--- a/apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx+++ b/apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx@@ -1,5 +1,10 @@import { useRemoteModelFavorites } from '@/state/useRemoteModelFavorites';import { useProviderShareFavorites } from '@/state/providerShareFavorites';+import {+ agentDeviceOfFavorite,+ LOCAL_MODEL_FAVORITE_STORE,+ useAgentDeviceFavorites,+} from '@/state/agentDeviceFavorites';import { ensureProviderShareReceivedStarted } from '@/features/provider-share/providerShareStore';import { toast } from '@/lib/toast';import { matchesModelName } from '@/lib/modelDisplayNames';@@ -61,7 +66,10 @@ import {resolveFavoriteRowConfig,resolveUnifiedRowConfig,sameAnchor,+ unavailableFavoriteEntry,+ type ForeignFavoriteRow,type UnifiedAnchor,+ type UnifiedListRow,type UnifiedEngine,type UnifiedRailFilter,type UnifiedRailItem,@@ -78,6 +86,7 @@ const RAIL_ALL: UnifiedRailFilter = { kind: 'all' };/** 定宽 sizer 的行不接交互。 */const noop = (): void => {};const NO_FAVORITES: readonly ModelFavoriteItem[] = [];+const NO_PROVIDERS: readonly ProviderView[] = [];export interface UnifiedSelectedRow {/** 该行**生效**引擎(推荐 ⊕ override ⊕ 会话内 pinnedEngine ⊕ 收藏副本)。 */@@ -282,7 +291,31 @@ export interface UnifiedModelPanelProps {deviceId: string;providers: readonly ProviderView[];providerIds: readonly string[];+ /** 那台电脑可远程调用的模型行(收藏区按它解析那台电脑上的收藏)。 */+ entries: readonly UnifiedModelEntry[];}[];+ /**+ * 收藏存在哪一份列表里(model-selector-unified §1.5「远程收藏按被控电脑共享」):任务在被控电脑上+ * 时是那台的 deviceId(经设备互联读写);不传 = 本机收藏。浏览其他电脑时,那台的收藏也读写这一份,+ * 运行位置编进 providerId(见 state/agentDeviceFavorites)。+ */+ favoritesDeviceId?: string;+ /** 任务所在电脑自己的设备 id(已知时):收藏里编码成它的条目按普通收藏处理。 */+ homeDeviceId?: string | null;+ /** 在列表里、但目录还在读取或读取失败的电脑:收藏区里它的收藏置灰列出,不丢。 */+ unavailableDeviceIds?: readonly string[];+ /**+ * 浏览任务所在电脑的目录时,在收藏区里选中另一台电脑上的收藏 —— 结果与浏览那台电脑时选中它相同+ * (Agent 在那台运行)。不传 = 收藏区不列其他电脑的收藏。+ */+ onSelectDeviceFavorite?: (selection: {+ deviceId: string;+ providerId: string;+ /** 该行生效引擎的 wire id。 */+ modelId: string;+ effort: Effort | '';+ config: UnifiedSelectedRow;+ }) => void | boolean | Promise<void | boolean>;labelOf: (deviceId: string, providerId: string) => string;/** 正在浏览的远程供应商;null = 正在浏览本机目录。 */active: { deviceId: string; providerId: string } | null;@@ -361,13 +394,28 @@ export function UnifiedModelPanel({const { t } = useTranslation();const storedFavorites = useModelFavorites();const isSharedProvider = isProviderShareAgentDeviceId(deviceId);- const remoteFavorites = useRemoteModelFavorites(isSharedProvider ? undefined : deviceId);+ // 远程 Agent:收藏一律读写任务所在电脑那一份(§1.5),浏览其他电脑的目录时也不读那台自己的收藏;+ // 其余入口照旧 —— 远程控制读被控电脑的列表,本机读本机。+ const favoritesListDeviceId = isSharedProvider+ ? undefined+ : remoteSources ? remoteSources.favoritesDeviceId : deviceId;+ const remoteFavorites = useRemoteModelFavorites(favoritesListDeviceId);const sharedFavorites = useProviderShareFavorites(deviceId, storedFavorites);+ const favoritesHomeDeviceId = remoteSources?.homeDeviceId ?? null;+ const agentDeviceFavorites = useAgentDeviceFavorites({+ deviceId: remoteSources?.active && !isSharedProvider ? deviceId : undefined,+ homeDeviceId: favoritesHomeDeviceId,+ home: remoteSources?.favoritesDeviceId+ ? remoteFavorites+ : { items: storedFavorites, store: LOCAL_MODEL_FAVORITE_STORE },+ });useEffect(() => {if (isSharedProvider) ensureProviderShareReceivedStarted();}, [isSharedProvider]);const favorites = selectionPolicy === 'official' ? NO_FAVORITES- : isSharedProvider ? sharedFavorites.items : deviceId ? remoteFavorites.items : storedFavorites;+ : isSharedProvider ? sharedFavorites.items+ : remoteSources ? agentDeviceFavorites.items+ : deviceId ? remoteFavorites.items : storedFavorites;// 引擎 override / 深度 / Fast 三份 store 的版本号:任一变化都要重算行三元组与浮层// (其它窗口的 storage 事件、device-link 推送同样经这两个版本号进来)。远程 Agent 的档位记忆// 是另一份 store,版本号并进 memoryVersion。@@ -698,11 +746,46 @@ export function UnifiedModelPanel({],);+ // ── 收藏区里其他电脑上的收藏(远程 Agent,浏览任务所在电脑的目录时)────────────────+ // 它们与本目录的收藏存在同一份列表里(运行位置编进 providerId),这里按那台电脑的目录解析:+ // 目录在且模型还在 → 正常行;目录还在读 / 读取失败 → 置灰占位行;目录里已经没有 → 本轮不显示(不删)。+ const deviceFavoriteGroups = remoteSources?.groups;+ const unavailableDeviceIds = remoteSources?.unavailableDeviceIds;+ const deviceFavoritesEnabled =+ !!remoteSources?.onSelectDeviceFavorite &&+ !remoteSources.active &&+ selectionPolicy === 'personalized';+ const resolveDeviceFavorite = useMemo(() => {+ if (!deviceFavoritesEnabled) return undefined;+ return (item: ModelFavoriteItem): ForeignFavoriteRow | null => {+ const source = agentDeviceOfFavorite(item.providerId, favoritesHomeDeviceId);+ if (!source) return null;+ const favorite: ModelFavoriteItem = { ...item, providerId: source.providerId };+ const group = deviceFavoriteGroups?.find((candidate) => candidate.deviceId === source.deviceId);+ if (group) {+ const ofProvider = group.entries.filter((candidate) => candidate.providerId === source.providerId);+ const entry =+ ofProvider.find((candidate) => candidate.modelId === item.modelId) ??+ ofProvider.find((candidate) => entryMatchesModelId(candidate, item.modelId));+ return entry ? { entry, favorite, agentDeviceId: source.deviceId } : null;+ }+ return unavailableDeviceIds?.includes(source.deviceId)+ ? {+ entry: unavailableFavoriteEntry(favorite),+ favorite,+ agentDeviceId: source.deviceId,+ unavailable: true,+ }+ : null;+ };+ }, [deviceFavoritesEnabled, favoritesHomeDeviceId, deviceFavoriteGroups, unavailableDeviceIds]);+const sections = useMemo(() =>buildUnifiedListSections({entries,favorites,+ ...(resolveDeviceFavorite ? { resolveForeignFavorite: resolveDeviceFavorite } : {}),query,matchesQuery: (entry, q) => matchesModelName({id: entry.modelId, displayName: entry.displayName, description: entry.description,@@ -714,7 +797,7 @@ export function UnifiedModelPanel({? { recommendation: { agent: liveEngineAgent, ...selected } }: {}),}),- [entries, favorites, query, effectiveRail, effectiveEngineOf, providerOrder, t, scope, liveEngineAgent, selected.modelId, selected.providerId],+ [entries, favorites, resolveDeviceFavorite, query, effectiveRail, effectiveEngineOf, providerOrder, t, scope, liveEngineAgent, selected.modelId, selected.providerId],);// 打开或切视图时,把模型本体的当前行对齐到可视高度 35% 处;收藏可以滚出顶部。@@ -881,7 +964,9 @@ export function UnifiedModelPanel({optimistic: optimisticConfig,runExternal,} = useUnifiedRowActions({- favoriteStore: isSharedProvider ? sharedFavorites.store : deviceId ? remoteFavorites.store : undefined,+ favoriteStore: isSharedProvider+ ? sharedFavorites.store+ : remoteSources ? agentDeviceFavorites.store : deviceId ? remoteFavorites.store : undefined,onFavoriteError: () => toast.error(t('newChat.modelSelector.unified.favoritesSaveFailed')),interactionDisabled,isLiveRow,@@ -1038,6 +1123,95 @@ export function UnifiedModelPanel({[priceOf, providers, t],);+ /**+ * 收藏区里另一台电脑上的收藏(见 resolveDeviceFavorite)。与本目录的行刻意分开画:+ * - 来源名带那台电脑(同浏览那台时的「供应商 · 电脑」),图标 / 账号 / 用量都按那台的目录读,+ * 不拿本目录同 id 的供应商顶替;+ * - 不出配置浮层 —— 浮层里的引擎 / 档位 / 价格都按当前目录解析,换到这里会画错;要调配置去那台+ * 电脑的目录里调(同一条收藏在那里照样列出)。☆ 取消收藏照常可用;+ * - 选中交给调用方的 onSelectDeviceFavorite(Agent 在那台运行),不经本目录的选中 / 跨引擎链路。+ * `sizer` = 定宽 sizer 里的那一份:只量宽,不接交互、不读用量。+ */+ const renderDeviceFavoriteRow = (row: UnifiedListRow, sizer: boolean): ReactNode => {+ const rowDeviceId = row.agentDeviceId!;+ const favorite = row.favorite!;+ const group = remoteSources?.groups.find((candidate) => candidate.deviceId === rowDeviceId);+ const rowProviders = group?.providers ?? NO_PROVIDERS;+ const provider = rowProviders.find((candidate) => candidate.id === row.entry.providerId);+ const label = remoteSources?.labelOf(rowDeviceId, row.entry.providerId) ?? row.entry.providerId;+ // 档位与 Fast 只看那台目录的能力:本机引擎的 Fast 运行时能力与那台电脑无关。+ const config = resolveFavoriteRowConfig({ entry: row.entry, item: favorite });+ const key = anchorKey(row.anchor);+ const rowElement = (+ <UnifiedModelRow+ key={key}+ entry={row.entry}+ anchor={row.anchor}+ config={config}+ sourceLabel={+ row.unavailable+ ? t('newChat.modelSelector.unified.remoteFavoriteUnavailable', { source: label })+ : label+ }+ selected={false}+ active={false}+ isFavoriteRow+ justFavorited={false}+ configurationEnabled={configurationEnabled}+ customizable={false}+ interactionDisabled={sizer || interactionDisabled || actionPending || !!row.unavailable}+ paymentRequired={row.entry.availability === 'requires_payment'}+ {...(paymentRequiredLabel ? { paymentRequiredLabel } : {})}+ {...(paymentRequiredUnlockLabel ? { paymentRequiredUnlockLabel } : {})}+ {...(!sizer && onPaymentRequired ? { onPaymentRequired } : {})}+ effortLabelOf={effortLabelOf}+ providers={rowProviders}+ onReveal={noop}+ onRevealForKeyboard={noop}+ onSelect={+ sizer+ ? noop+ : () =>+ void runExternal(() =>+ remoteSources?.onSelectDeviceFavorite?.({+ deviceId: rowDeviceId,+ providerId: row.entry.providerId,+ modelId: config.wireModelId ?? row.anchor.modelId,+ effort: config.effort ?? '',+ config: {+ engine: config.engine,+ fast: config.fast,+ favoriteUid: favorite.uid,+ rowModelId: row.anchor.modelId,+ },+ }),+ )+ }+ onStar={+ sizer+ ? noop+ : selectionPolicy === 'personalized'+ ? () => removeFavorite(row.anchor, row.entry)+ : undefined+ }+ />+ );+ if (sizer) return rowElement;+ return (+ <ModelSourceUsageProvider+ key={key}+ isolated+ providers={provider ? [provider] : NO_PROVIDERS}+ scope={{ deviceId: rowDeviceId }}+ {...(providerGroupUsage+ ? { groupUsageOf: (providerId: string) => providerGroupUsage(rowDeviceId, providerId) }+ : {})}+ >+ {rowElement}+ </ModelSourceUsageProvider>+ );+ };+/*** 定宽 sizer 的内容:**rail = 全部 + 空搜索**的完整 sections(Chris 2026-08-19 实测:* 「一次打开内切 rail 视图,面板弹开一些,感觉有点怪」)。@@ -1060,13 +1234,14 @@ export function UnifiedModelPanel({? buildUnifiedListSections({entries,favorites,+ ...(resolveDeviceFavorite ? { resolveForeignFavorite: resolveDeviceFavorite } : {}),query: '',rail: RAIL_ALL,effectiveEngineOf,providerOrder,}): [],- [widthSizerActive, entries, favorites, effectiveEngineOf, providerOrder],+ [widthSizerActive, entries, favorites, resolveDeviceFavorite, effectiveEngineOf, providerOrder],);const panelContent = (@@ -1177,7 +1352,7 @@ export function UnifiedModelPanel({</span></div>)}- {deviceId && remoteFavorites.error ? <div role="status" className="px-3 py-2 text-13 text-[var(--text-secondary)]">{t('newChat.modelSelector.unified.favoritesSyncFailed')}</div> : null}+ {favoritesListDeviceId && remoteFavorites.error ? <div role="status" className="px-3 py-2 text-13 text-[var(--text-secondary)]">{t('newChat.modelSelector.unified.favoritesSyncFailed')}</div> : null}{remoteListPending ? (remoteSources?.failure ?? (<div@@ -1212,6 +1387,7 @@ export function UnifiedModelPanel({<span className="truncate">{sectionLabel(section)}</span></div>{section.rows.map((row) => {+ if (row.agentDeviceId) return renderDeviceFavoriteRow(row, false);const config = withOptimisticConfig(row.anchor,configOf(row.entry, row.favorite),@@ -1290,6 +1466,7 @@ export function UnifiedModelPanel({<span className="truncate">{sectionLabel(section)}</span></div>{section.rows.map((row) => {+ if (row.agentDeviceId) return renderDeviceFavoriteRow(row, true);const config = configOf(row.entry, row.favorite, RAIL_ALL);const priceDisplay = priceDisplayOf(row.entry, config);return (diff --git a/apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx b/apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsxindex 38e6de4b3b..8e844f70ea 100644--- a/apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx+++ b/apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx@@ -48,6 +48,7 @@ export function UnifiedModelRow({onRevealForKeyboard,priceDisplay,configurationEnabled = true,+ customizable = true,paymentRequired = false,paymentRequiredLabel,paymentRequiredUnlockLabel,@@ -75,6 +76,11 @@ export function UnifiedModelRow({/** 行内价格展示;不传 = 无报价。字段语义见 `UnifiedRowPriceDisplay`。 */priceDisplay?: UnifiedRowPriceDisplay;configurationEnabled?: boolean;+ /**+ * false = 这一行不出配置浮层(不画自定义按钮、不响应右键 / ←),行内仍按 configurationEnabled+ * 显示深度与 Fast。用于收藏区里另一台电脑的收藏:它的配置要在那台电脑的目录里调。+ */+ customizable?: boolean;/** 付费锁定行保留在原位置,可聚焦但不能选中、收藏或打开配置。 */paymentRequired?: boolean;paymentRequiredLabel?: string;@@ -88,7 +94,7 @@ export function UnifiedModelRow({const priceSymbol = priceDisplay?.symbol ?? '$';const engineOption = agentOptionOf(config.engine);const openConfig = (element: HTMLElement, toggle = false) => {- if (!paymentRequired) onReveal(anchor, element, toggle);+ if (!paymentRequired && customizable) onReveal(anchor, element, toggle);};const tripleTitle = `${engineOption.label}${configurationEnabled && config.effort ? ` · ${effortLabelOf(config.agent, config.effort)}` : ''@@ -108,7 +114,7 @@ export function UnifiedModelRow({'aria-disabled': interactionDisabled ? true : undefined,'aria-label': paymentRequiredActionLabel,// ← 开配置浮层是这一行唯一的键盘入口,不声明就只有摸索得到(读屏用户尤甚)。- 'aria-keyshortcuts': paymentRequired ? undefined : 'ArrowLeft',+ 'aria-keyshortcuts': paymentRequired || !customizable ? undefined : 'ArrowLeft',tabIndex: interactionDisabled ? -1 : 0,'data-model-selected': selected ? ('true' as const) : undefined,// Shared menu row: the panel's glide highlight; the chosen row keeps its static fill (below).@@ -135,6 +141,7 @@ export function UnifiedModelRow({return;}if (event.key === 'ArrowLeft') {+ if (!customizable) return;event.preventDefault();onRevealForKeyboard(anchor, event.currentTarget);return;@@ -269,7 +276,7 @@ export function UnifiedModelRow({/>)}{starButton}- {configurationEnabled && customizeButton}+ {configurationEnabled && customizable && customizeButton}{/* 常驻三元组:引擎图标 + 推理强度 + ⚡。所有行同构,自定义行整组提亮一档。设计稿 .l1-right:margin-left auto 把右侧簇推到最右,左侧簇贴名字排。 */}<span data-model-row-meta className="ml-auto flex shrink-0 items-center gap-2">diff --git a/apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts b/apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.tsindex 2925e5600c..d3b49cf45b 100644--- a/apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts+++ b/apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts@@ -381,6 +381,38 @@ export interface UnifiedListRow {entry: UnifiedModelEntry;/** 收藏区行才有;模型行为 undefined。 */favorite?: ModelFavoriteItem;+ /**+ * 收藏区里「在另一台电脑上运行」的收藏(远程 Agent):entry 来自那台电脑的目录,favorite 的+ * providerId 已还原成那台的真实 id。没有这个字段 = 本目录的行。+ */+ agentDeviceId?: string;+ /** 那台电脑的目录此刻读不到:行照常列出但不可选(entry 只是按收藏拼出的占位)。 */+ unavailable?: true;+}++/** 收藏区里本目录之外的那一条:由调用方按那台电脑的目录解析(见 buildUnifiedListSections)。 */+export interface ForeignFavoriteRow {+ entry: UnifiedModelEntry;+ favorite: ModelFavoriteItem;+ agentDeviceId: string;+ unavailable?: true;+}++/**+ * 另一台电脑的目录还没读到时,按收藏条目拼一个只用来展示的行(名字 = 模型 id,引擎 = 收藏存的那个,+ * 没有任何能力):行不可选,目录到了自然换成真条目。+ */+export function unavailableFavoriteEntry(item: ModelFavoriteItem): UnifiedModelEntry {+ const agent = agentKindOfEngine(item.agent);+ return {+ providerId: item.providerId,+ modelId: item.modelId,+ displayName: item.modelId,+ candidates: [agent],+ recommended: agent,+ nativeAgent: null,+ capabilities: {},+ };}export interface UnifiedListSection {@@ -514,6 +546,12 @@ export function buildUnifiedListSections(args: {/** 供应商组间显示顺序(设置页拖动序);缺省 = 入参首见序。 */providerOrder?: readonly string[];recommendation?: { agent: AgentKind; providerId: string | null; modelId: string };+ /**+ * 远程 Agent 浏览任务所在电脑的目录时:收藏里在其他电脑上运行的那几条交给调用方按那台的目录解析。+ * 返回 null = 本轮不显示(那台的目录里已经没有这个模型 / 不是这类收藏);**不删条目**。+ * 这些行只出现在 ★ / 全部视图,按本机供应商筛选的视图不列。+ */+ resolveForeignFavorite?: (item: ModelFavoriteItem) => ForeignFavoriteRow | null;}): UnifiedListSection[] {const { entries, favorites, effectiveEngineOf } = args;const q = args.query.trim().toLowerCase();@@ -527,6 +565,31 @@ export function buildUnifiedListSections(args: {// ── 收藏区 ── 恒置顶,在任何 rail 视图下都显示;按供应商筛选时只留该来源的收藏。const favRows: UnifiedListRow[] = [];for (const item of favorites) {+ const foreign = args.resolveForeignFavorite?.(item);+ if (foreign) {+ if (railProviderFilterId(rail) !== null) continue;+ if (+ rail.kind === 'engine' &&+ (effectiveEngineOf+ ? effectiveEngineOf(foreign.entry, foreign.favorite)+ : foreign.favorite.agent) !== engineOfAgentKind(rail.agent)+ )+ continue;+ if (!matches(foreign.entry, q)) continue;+ favRows.push({+ anchor: {+ kind: 'fav',+ uid: item.uid,+ providerId: foreign.favorite.providerId,+ modelId: foreign.favorite.modelId,+ },+ entry: foreign.entry,+ favorite: foreign.favorite,+ agentDeviceId: foreign.agentDeviceId,+ ...(foreign.unavailable ? { unavailable: true as const } : {}),+ });+ continue;+ }// 老收藏可能存的是某个引擎的 wire id(合并行之前的行身份就是 wire id):先按归一化 id// 精确命中,失配再按「任一引擎的 wire id」扫一遍 —— 否则升级后老收藏会整条消失。const entry =diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 64d4a338cb..1a6202319b 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -9832,6 +9832,7 @@"railAll": "All","railRemoteProvider": "{{provider}} · {{device}}","remoteLoading": "Loading models from that computer…",+ "remoteFavoriteUnavailable": "{{source}} · Can't read that computer's models right now","favoritesGroup": "Favorites","favoritesSaveFailed": "Could not save favorite changes","favoritesCleanupFailed": "Could not remove favorites for revoked provider shares",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 89744ed242..8f28a6854b 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -9795,6 +9795,7 @@"railAll": "すべて","railRemoteProvider": "{{provider}} · {{device}}","remoteLoading": "そのパソコンのモデルを読み込み中…",+ "remoteFavoriteUnavailable": "{{source}} · そのパソコンのモデルを読み込めません","favoritesGroup": "お気に入り","favoritesSaveFailed": "お気に入りの変更を保存できませんでした","favoritesCleanupFailed": "共有が解除されたモデルのお気に入りを削除できませんでした",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 7c0ab50b3a..4c85896b90 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -9795,6 +9795,7 @@"railAll": "전체","railRemoteProvider": "{{provider}} · {{device}}","remoteLoading": "그 컴퓨터의 모델을 불러오는 중…",+ "remoteFavoriteUnavailable": "{{source}} · 그 컴퓨터의 모델을 불러올 수 없음","favoritesGroup": "즐겨찾기","favoritesSaveFailed": "즐겨찾기 변경 사항을 저장하지 못했습니다","favoritesCleanupFailed": "공유가 해제된 모델의 즐겨찾기를 삭제하지 못했습니다",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 07a7112eb5..8ad88cf095 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -9795,6 +9795,7 @@"railAll": "全部","railRemoteProvider": "{{provider}} · {{device}}","remoteLoading": "正在读取那台电脑的模型…",+ "remoteFavoriteUnavailable": "{{source}} · 暂时读不到那台电脑的模型","favoritesGroup": "收藏","favoritesSaveFailed": "未能保存收藏更改","favoritesCleanupFailed": "未能清理已失效的分享模型收藏",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 6acd24b833..fb0d475565 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -9794,6 +9794,7 @@"railAll": "全部","railRemoteProvider": "{{provider}} · {{device}}","remoteLoading": "正在讀取那臺電腦的模型…",+ "remoteFavoriteUnavailable": "{{source}} · 暫時讀不到那臺電腦的模型","favoritesGroup": "收藏","favoritesSaveFailed": "未能儲存收藏變更","favoritesCleanupFailed": "未能清理已失效的分享模型收藏",diff --git a/apps/desktop/src/renderer/state/agentDeviceFavorites.ts b/apps/desktop/src/renderer/state/agentDeviceFavorites.tsnew file mode 100644index 0000000000..a15c853a2e--- /dev/null+++ b/apps/desktop/src/renderer/state/agentDeviceFavorites.ts@@ -0,0 +1,133 @@+import { useMemo } from 'react';+import {+ agentDeviceFavoriteSource,+ parseAgentDeviceFavoriteSource,+ type AgentDeviceFavoriteSource,+} from '@cindy/device-link';+import { isProviderShareAgentDeviceId } from '../../shared/providerShare';+import {+ addModelFavorite,+ getModelFavorite,+ removeModelFavorite,+ updateModelFavorite,+ type ModelFavoriteItem,+} from './modelFavorites';+import type { FavoriteStore } from './useRemoteModelFavorites';++/**+ * 远程 Agent 的收藏(model-selector-unified §1.5「远程收藏按被控电脑共享」):收藏仍存在任务所在电脑+ * (home)那一份列表里,「在同账号另一台电脑上运行」的那台编进 providerId(编码见+ * `@cindy/device-link` 的 agentDeviceFavoriteSource)。这里只做投影:浏览那台电脑的目录时把它的+ * 条目还原成那台的真实 providerId,写入时再编码回去存进 home 列表。+ *+ * 编码后的 providerId 只用于存储与匹配,绝不作为模型请求的 providerId。分享来的供应商+ * (`share:` 开头)有自己的存储键(providerShareFavorites),不经过这里。+ */++/** 本机那一份收藏的读写口(与 useUnifiedRowActions 缺省的本机 store 同一组函数)。 */+export const LOCAL_MODEL_FAVORITE_STORE: FavoriteStore = {+ get: getModelFavorite,+ add: (config) => {+ addModelFavorite(config);+ },+ update: updateModelFavorite,+ remove: removeModelFavorite,+};++/**+ * 这条收藏是不是「在另一台电脑上运行」的。编码里的电脑就是任务所在电脑时按普通收藏处理+ * (返回 null);分享的设备 id 不认(那是分享收藏的存储键,不该出现在这种编码里)。+ */+export function agentDeviceOfFavorite(+ providerId: string,+ homeDeviceId: string | null,+): AgentDeviceFavoriteSource | null {+ const source = parseAgentDeviceFavoriteSource(providerId);+ if (!source || source.deviceId === homeDeviceId || isProviderShareAgentDeviceId(source.deviceId))+ return null;+ return source;+}++/** 编码里的电脑就是任务所在电脑:还原成真实 providerId,当普通收藏用。 */+function homeProjection(item: ModelFavoriteItem, homeDeviceId: string | null): ModelFavoriteItem {+ if (!homeDeviceId) return item;+ const source = parseAgentDeviceFavoriteSource(item.providerId);+ return source && source.deviceId === homeDeviceId+ ? { ...item, providerId: source.providerId }+ : item;+}++/**+ * 按「正在浏览哪台电脑的目录」投影 home 收藏。+ *+ * - `deviceId` 为空(浏览任务所在电脑):列表**保持 home 的原顺序与全部条目**,只把编码成 home 自己的+ * 条目还原;其他电脑的条目原样留着(目录里匹配不到,由面板按那台的目录另行解析)。写入走 home。+ * - `deviceId` 为另一台电脑:只列编码成那台的条目并还原 providerId;新增时编码后写进 home,编辑 / 删除+ * 先核对锚点确实属于那台再交给 home(防止拿别处的 uid 改到不相干的条目)。+ */+export function useAgentDeviceFavorites(args: {+ deviceId: string | undefined;+ homeDeviceId: string | null;+ home: { items: readonly ModelFavoriteItem[]; store: FavoriteStore };+}): { items: readonly ModelFavoriteItem[]; store: FavoriteStore } {+ const { deviceId, homeDeviceId, home } = args;+ const target =+ deviceId && deviceId !== homeDeviceId && !isProviderShareAgentDeviceId(deviceId)+ ? deviceId+ : null;+ const items = useMemo(() => {+ if (!target)+ return homeDeviceId+ ? home.items.map((item) => homeProjection(item, homeDeviceId))+ : home.items;+ return home.items.flatMap((item) => {+ const source = parseAgentDeviceFavoriteSource(item.providerId);+ return source && source.deviceId === target+ ? [{ ...item, providerId: source.providerId }]+ : [];+ });+ }, [home.items, target, homeDeviceId]);+ const store = useMemo<FavoriteStore>(() => {+ if (!target) {+ return {+ get: (uid) => {+ const item = home.store.get(uid);+ return item ? homeProjection(item, homeDeviceId) : undefined;+ },+ add: (config) => home.store.add(config),+ update: (uid, patch) => home.store.update(uid, patch),+ remove: (uid) => home.store.remove(uid),+ };+ }+ const owned = (uid: string): ModelFavoriteItem | undefined => {+ const item = home.store.get(uid);+ const source = item ? parseAgentDeviceFavoriteSource(item.providerId) : null;+ return item && source?.deviceId === target+ ? { ...item, providerId: source.providerId }+ : undefined;+ };+ const expectOwned = (uid: string) => {+ if (!owned(uid)) throw new Error('Agent device favorite unavailable');+ };+ return {+ get: owned,+ add: (config) =>+ home.store.add({+ ...config,+ providerId: agentDeviceFavoriteSource({+ deviceId: target,+ providerId: config.providerId,+ }),+ }),+ update: (uid, patch) => {+ expectOwned(uid);+ return home.store.update(uid, patch);+ },+ remove: (uid) => {+ expectOwned(uid);+ return home.store.remove(uid);+ },+ };+ }, [home.store, target, homeDeviceId]);+ return { items, store };+}diff --git a/apps/mobile/src/__tests__/remoteAgentCatalogsProviderShare.test.tsx b/apps/mobile/src/__tests__/remoteAgentCatalogsProviderShare.test.tsxindex b8c599873c..592fff4e4e 100644--- a/apps/mobile/src/__tests__/remoteAgentCatalogsProviderShare.test.tsx+++ b/apps/mobile/src/__tests__/remoteAgentCatalogsProviderShare.test.tsx@@ -29,6 +29,8 @@ const link = vi.hoisted(() => ({readDeviceList: vi.fn(),connectionEpoch: 1,status: 'online' as const,+ presenceVersion: 1,+ getPresenceAvailability: vi.fn((_deviceId: string): boolean | null => null),}));vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => link }));@@ -81,6 +83,8 @@ beforeEach(async () => {clearAllDeviceProviders();clearAllProviderShareCatalogs();latest = [];+ link.presenceVersion = 1;+ link.getPresenceAvailability.mockImplementation(() => null);link.readDeviceList.mockResolvedValue({ devices: [device('controlled', 'Home Mac'), device('studio', 'Studio Mac')] });link.invoke.mockImplementation(async (deviceId: string, channel: string) => {if (channel === 'maker:provider:list' && deviceId === 'studio') {@@ -151,6 +155,15 @@ describe('remote Agent catalogs with provider shares', () => {expect(latest.map((catalog) => catalog.deviceId)).toContain('share:share-1');});+ it('marks a computer offline as soon as its live presence drops while the picker is open', async () => {+ await render({ enabled: true, controlledDeviceId: 'controlled', keepDeviceIds: [] });+ expect(latest.find((catalog) => catalog.deviceId === 'studio')?.offline).toBeUndefined();+ link.getPresenceAvailability.mockImplementation((deviceId) => (deviceId === 'studio' ? false : null));+ link.presenceVersion = 2;+ await render({ enabled: true, controlledDeviceId: 'controlled', keepDeviceIds: [] });+ expect(latest.find((catalog) => catalog.deviceId === 'studio')?.offline).toBe(true);+ });+it('shows the cached shares right away on the next open', async () => {await render({ enabled: true, controlledDeviceId: 'controlled', keepDeviceIds: [] });await act(async () => root.unmount());diff --git a/apps/mobile/src/__tests__/unifiedMobilePicker.test.tsx b/apps/mobile/src/__tests__/unifiedMobilePicker.test.tsxindex 763e34aeb0..2a09433992 100644--- a/apps/mobile/src/__tests__/unifiedMobilePicker.test.tsx+++ b/apps/mobile/src/__tests__/unifiedMobilePicker.test.tsx@@ -548,14 +548,14 @@ const studioCatalog = {providers:[{id:'account',name:'Studio Provider',models:{},connected:true,logoKind:'anthropic'}],};const remoteId = 'remote:["device-studio-mac","account"]';-async function mountRemote(selectedDeviceId:string|null,onSelect=vi.fn(async()=>true)) {+async function mountRemote(selectedDeviceId:string|null,onSelect=vi.fn(async()=>true),catalog:any=studioCatalog) {const onClose=vi.fn();await act(async()=>root.render(createElement(UnifiedModelPickerSheet,{visible:true,onClose,providers:[{id:'account',name:'Provider',models:{},connected:true}],agentKind:'codex',capabilities:{hasFastMode:true},activeModelId:'codex/model',selectedProviderId:'account',selectedEffort:'medium',selectedFastMode:false,existingSessionRoute:true,modelMemory:{getEffort:()=>undefined,getFast:()=>undefined,setEffort:vi.fn(),setFast:vi.fn()},unified:{scope:'user-device',agents:['codex','claude-code'],loadCapabilities:async()=>({hasFastMode:true}),onSelect,- remote:{catalogs:[studioCatalog],selectedDeviceId}},+ remote:{catalogs:[catalog],selectedDeviceId}},} as any)));return {onSelect,onClose};}@@ -595,7 +595,8 @@ it('opens on the Agent\'s computer and marks the current model there',async()=>{it('keeps settings of another computer\'s rows out of this phone\'s preferences',async()=>{const {onSelect}=await mountRemote(null);await act(async()=>test.view.onOptions(test.view.groups[1].rows[0]));- expect(test.view.options.favoritesDisabled).toBe(true);+ // 收藏照样可用(存到被控电脑,位置编进来源),参数调整仍不写进手机的偏好。+ expect(test.view.options.favoritesDisabled).toBe(false);expect(test.view.options.canReset).toBe(false);await act(async()=>test.view.options.onChange({...test.view.options.row.config,effort:'high'}));expect(test.save).not.toHaveBeenCalled();@@ -608,6 +609,98 @@ it('keeps settings of another computer\'s rows out of this phone\'s preferences'expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({effort:'high'}),{deviceId:'device-studio-mac'});});+// 收藏另一台电脑上的模型:收藏存在被控电脑,来源里编进电脑;和本机收藏排在一起,点开就在那台运行。+const studioSource = 'agent-device-favorite:["device-studio-mac","account"]';+it('favorites another computer\'s model with its location and lists it beside local favorites',async()=>{+ const {onSelect,onClose}=await mountRemote(null);+ await act(async()=>test.view.onOptions(test.view.groups[1].rows[0]));+ expect(test.view.options.isFavorite).toBe(false);+ await act(async()=>test.view.options.onFavorite());+ expect(test.save).toHaveBeenCalledWith(expect.objectContaining({favorites:[+ {uid:expect.any(String),providerId:studioSource,modelId:'model',agent:'codex',effort:'medium',fast:false},+ ]}));+ expect(test.view.options.isFavorite).toBe(true);+ expect(test.view.options.notice).toBe('models.unified.favoriteSaved');+ await act(async()=>test.view.onBack());+ expect(test.view.groups.map((g:any)=>g.key)).toEqual(['favorites','recommended',remoteId]);+ const favorite=test.view.groups[0].rows[0];+ expect(favorite.remoteDevice).toEqual({deviceId:'device-studio-mac',name:'Studio Mac'});+ expect(favorite.subtitle).toContain('Studio Mac');+ expect(favorite.providerMark).toMatchObject({name:'Studio Provider'});+ expect(favorite.selected).toBe(false);+ // 选中时按那台电脑上的供应商 id 发出,并带上电脑。+ await act(async()=>test.view.onSelect(favorite));+ expect(onSelect).toHaveBeenCalledWith({providerId:'account',modelId:'codex/model',agent:'codex',effort:'medium',fast:false},{deviceId:'device-studio-mac'});+ expect(onClose).toHaveBeenCalledOnce();+});+it('keeps a local favorite and another computer\'s favorite of the same model apart',async()=>{+ test.prefs.favorites=[{uid:'local',providerId:'account',modelId:'codex/model',agent:'codex',effort:'medium',fast:false}];+ await mountRemote(null);+ await act(async()=>test.view.onOptions(test.view.groups.find((g:any)=>g.key===remoteId).rows[0]));+ expect(test.view.options.isFavorite).toBe(false);+ await act(async()=>test.view.onBack());+ test.prefs.favorites=[{uid:'remote',providerId:studioSource,modelId:'codex/model',agent:'codex',effort:'medium',fast:false}];+ await mountRemote(null);+ await act(async()=>test.view.onOptions(test.view.groups.find((g:any)=>g.key==='recommended').rows[0]));+ expect(test.view.options.isFavorite).toBe(false);+});+it('removes and edits another computer\'s favorite without losing its location',async()=>{+ test.prefs.favorites=[{uid:'remote',providerId:studioSource,modelId:'codex/model',agent:'codex',effort:'medium',fast:false}];+ await mountRemote(null);+ await act(async()=>test.view.onOptions(test.view.groups[0].rows[0]));+ expect(test.view.options.isFavorite).toBe(true);+ await act(async()=>test.view.options.onEditFavorite());+ await act(async()=>test.view.options.onChange({...test.view.options.row.config,effort:'high'}));+ await act(async()=>test.view.options.onSaveEdit());+ expect(test.save).toHaveBeenLastCalledWith(expect.objectContaining({favorites:[+ {uid:'remote',providerId:studioSource,modelId:'model',agent:'codex',effort:'high',fast:false},+ ]}));+ expect(test.view.options.isFavorite).toBe(true);+ await act(async()=>test.view.options.onFavorite());+ expect(test.save).toHaveBeenLastCalledWith(expect.objectContaining({favorites:[]}));+});+it('adjusts parameters from another computer\'s favorite details without changing the copy',async()=>{+ test.prefs.favorites=[{uid:'remote',providerId:studioSource,modelId:'codex/model',agent:'codex',effort:'medium',fast:false}];+ const {onSelect}=await mountRemote(null);+ await act(async()=>test.view.onOptions(test.view.groups[0].rows[0]));+ expect(test.view.options.isFavorite).toBe(true);+ await act(async()=>test.view.options.onChange({...test.view.options.row.config,effort:'high'}));+ // 详情跟着调整走,原收藏不变、星标回到空心,并提示原收藏保留。+ expect(test.view.options.row.config.effort).toBe('high');+ expect(test.view.options.isFavorite).toBe(false);+ expect(test.view.options.notice).toBe('models.unified.originalFavoriteKept');+ expect(test.view.options.canReset).toBe(true);+ expect(test.save).not.toHaveBeenCalled();+ expect(onSelect).not.toHaveBeenCalled();+ await act(async()=>test.view.options.onReset());+ expect(test.view.options.row.config.effort).toBe('medium');+ expect(test.view.options.isFavorite).toBe(true);+});+it('hides favorites of a computer that is only listed because the Agent was there and it went offline',async()=>{+ test.prefs.favorites=[{uid:'remote',providerId:studioSource,modelId:'codex/model',agent:'codex',effort:'medium',fast:false}];+ await mountRemote(null,undefined,{...studioCatalog,offline:true});+ expect(test.view.groups.some((g:any)=>g.key==='favorites')).toBe(false);+ expect(test.save).not.toHaveBeenCalled();+});+it('hides a favorite whose computer is not in the list without deleting it',async()=>{+ test.prefs.favorites=[{uid:'away',providerId:'agent-device-favorite:["device-offline","account"]',modelId:'codex/model',agent:'codex',effort:'medium',fast:false}];+ await mountRemote(null);+ expect(test.view.groups.map((g:any)=>g.key)).toEqual(['recommended',remoteId]);+ expect(test.save).not.toHaveBeenCalled();+});+it('does not offer favorites for providers shared by another account',async()=>{+ const onSelect=vi.fn(async()=>true);+ await act(async()=>root.render(createElement(UnifiedModelPickerSheet,{+ visible:true,onClose:vi.fn(),providers:[{id:'account',name:'Provider',models:{},connected:true}],agentKind:'codex',capabilities:{hasFastMode:true},+ activeModelId:'codex/model',selectedProviderId:'account',selectedEffort:'medium',selectedFastMode:false,+ existingSessionRoute:true,modelMemory:{getEffort:()=>undefined,getFast:()=>undefined,setEffort:vi.fn(),setFast:vi.fn()},+ unified:{scope:'user-device',agents:['codex','claude-code'],loadCapabilities:async()=>({hasFastMode:true}),onSelect,+ remote:{catalogs:[{...studioCatalog,deviceId:'share:abc',name:'Shared'}],selectedDeviceId:null}},+ } as any)));+ await act(async()=>test.view.onOptions(test.view.groups[1].rows[0]));+ expect(test.view.options.favoritesDisabled).toBe(true);+});+// 供应商组(provider-groups.md §10,与桌面同口径):Mac Mini 把 Anthropic 建成了组(Mac Mini 自己 + grok-bot-vm),// 任务被组分到 grok-bot-vm 上运行。手机同样把 grok-bot-vm 的 Anthropic 收进组那一项;归组的任务在组那一项里// 选模型 = 留在 grok-bot-vm 只换模型,不当成换电脑。diff --git a/apps/mobile/src/session/UnifiedModelPickerSheet.tsx b/apps/mobile/src/session/UnifiedModelPickerSheet.tsxindex 26605bae8d..9e07c6c997 100644--- a/apps/mobile/src/session/UnifiedModelPickerSheet.tsx+++ b/apps/mobile/src/session/UnifiedModelPickerSheet.tsx@@ -5,6 +5,10 @@ import { formatQuotaResetCountdown } from "./sessionUsagePresentation";import { useMobileModelQuotas } from "./useMobileModelQuotas";import { useEffect, useMemo, useRef, useState } from "react";import * as ExpoCrypto from "expo-crypto";+import {+ agentDeviceFavoriteSource,+ parseAgentDeviceFavoriteSource,+} from "@cindy/device-link";import { useTranslation } from "react-i18next";import type { MobileProviderMarkProps } from "./MobileProviderMark";import type { AgentKind } from "@cindy/model-providers/types";@@ -30,6 +34,7 @@ import { budgetRowDisabled, presentPickerPrice } from "./modelPickerRows";import { mobileWeeklyQuota } from "./mobileModelRowPresentation";import { mobileAgentLabel } from "./sessionAgentSwitch";import type { RemoteAgentCatalog } from "./remoteAgentCatalogs";+import { isProviderShareAgentDeviceId } from "./providerShareAgentDevice";import {collectMobileProviderGroups,providerGroupEntryKey,@@ -508,14 +513,6 @@ export function UnifiedModelPickerSheet(};};const rows = entries.map((entry) => makeRow(entry));- const favorites = prefs.value.favorites.flatMap((item) => {- const entry = entries.find(- (entry) =>- entry.providerId === item.providerId &&- matchesEntry(entry, item.modelId),- );- return entry ? [makeRow(entry, item)] : [];- });// 供应商组只写组里有几台,不写是哪几台(provider-groups.md §10):「Claude · 供应商组 · 3 台电脑」。const groupBadge = (deviceId: string | null, id: string) => {const size = providerGroups.sizes.get(providerGroupEntryKey(deviceId, id));@@ -554,30 +551,38 @@ export function UnifiedModelPickerSheet(const makeRemoteRow = (directory: (typeof remoteDirectories)[number],entry: UnifiedModelEntry,+ favorite?: MobileModelFavorite,): UnifiedMobileRow => {const { catalog } = directory;const selected =+ !favorite &&directory.sourceId !== null &&entry.providerId === directory.sourceId &&matchesEntry(entry, p.activeModelId);- const key = `remote:${catalog.deviceId}:${modelKey(entry.providerId, entry.modelId)}`;+ const key =+ favorite?.uid ??+ `remote:${catalog.deviceId}:${modelKey(entry.providerId, entry.modelId)}`;const provider = catalog.providers.find((item) => item.id === entry.providerId,);// 不用手机这边按被控电脑供应商记的引擎偏好与档位记忆:同 id 的供应商在两台电脑上不是同一个。+ // 收藏行按收藏副本解析(位置已从 providerId 里拆出来,这里是那台电脑上的供应商 id)。const config =- (!selected ? remoteConfigs.get(key) : undefined) ??+ (!selected && !favorite ? remoteConfigs.get(key) : undefined) ??resolveMobileModelConfig(entry, {+ favorite,live: selected? { ...selection, providerId: directory.sourceId ?? "" }: undefined,pinned: p.existingSessionRoute ? p.agentKind : undefined,fastCapable,});+ const details = describe(entry, config, catalog.providers);return {key,entry,config,+ ...(favorite ? { favorite } : {}),providerMark: {providerId: entry.providerId,name: provider?.name ?? entry.providerId,@@ -587,7 +592,10 @@ export function UnifiedModelPickerSheet(remoteDevice: { deviceId: catalog.deviceId, name: catalog.name },selected,disabled: !caps[config.agent],- subtitle: describe(entry, config, catalog.providers),+ // 「收藏」一节没有带电脑名的分段标题,电脑名写进说明行,和本机同名模型的收藏区分开。+ subtitle: favorite+ ? [catalog.name, details].filter(Boolean).join(" · ")+ : details,effortLabel: effortText(config),costMarks: mobileCostMarks(provider,@@ -603,6 +611,37 @@ export function UnifiedModelPickerSheet(catalog: directory.catalog,rows: directory.entries.map((entry) => makeRemoteRow(directory, entry)),}));+ // 收藏和本机收藏排在同一节里:位置编在 providerId 里的,到那台电脑的目录里找模型,+ // 点开即在那台运行。那台电脑离线(包括只因任务的 Agent 在那台、靠缓存留在列表里)或没开放远程调用时+ // 先不显示,收藏本身保留。+ const favorites = prefs.value.favorites.flatMap((item) => {+ const source = parseAgentDeviceFavoriteSource(item.providerId);+ if (source) {+ const directory = remoteDirectories.find(+ (value) =>+ value.catalog.deviceId === source.deviceId && !value.catalog.offline,+ );+ const entry = directory?.entries.find(+ (value) =>+ value.providerId === source.providerId &&+ matchesEntry(value, item.modelId),+ );+ return directory && entry+ ? [+ makeRemoteRow(directory, entry, {+ ...item,+ providerId: source.providerId,+ }),+ ]+ : [];+ }+ const entry = entries.find(+ (entry) =>+ entry.providerId === item.providerId &&+ matchesEntry(entry, item.modelId),+ );+ return entry ? [makeRow(entry, item)] : [];+ });const rowProviderName = (row: UnifiedMobileRow) => {const device = row.remoteDevice;const catalog = device@@ -713,16 +752,35 @@ export function UnifiedModelPickerSheet(config: favoriteEdit?.config ?? target?.config ?? sourceRow.config,favorite: originFavorite,};+ // 这一行存进收藏时用的来源:被控电脑自己的供应商照旧;同账号另一台电脑的供应商把电脑编进去+ // (同 id 供应商在两台电脑上不是同一个)。分享来的供应商暂不支持收藏,返回 null。+ const favoriteSourceOf = (value: UnifiedMobileRow): string | null => {+ const device = value.remoteDevice;+ if (!device) return value.entry.providerId;+ if (isProviderShareAgentDeviceId(device.deviceId)) return null;+ try {+ return agentDeviceFavoriteSource({+ deviceId: device.deviceId,+ providerId: value.entry.providerId,+ });+ } catch {+ return null;+ }+ };+ const favoriteSource = row ? favoriteSourceOf(row) : null;// A source model can have several saved configurations. Match the complete// configuration without applying capability fallbacks to the saved values.- // 收藏按被控电脑的供应商记;另一台电脑目录里的行不参与(同 id 供应商不是同一个)。const matchingFavorite =row &&- !row.remoteDevice &&+ favoriteSource !== null &&prefs.value.favorites.find((item) =>+ item.providerId === favoriteSource &&matchesEntry(row.entry, item.modelId) &&- sameConfiguration({ ...item, modelId: row.config.modelId }, row.config),+ sameConfiguration(+ { ...item, providerId: row.config.providerId, modelId: row.config.modelId },+ row.config,+ ),);const recommendedConfig =row &&@@ -839,7 +897,14 @@ export function UnifiedModelPickerSheet()))return;- if (!isCurrent() || row.selected) return;+ if (!isCurrent()) return;+ // 从收藏打开的详情显示的是那份副本(target.config),与本机收藏一样跟着调整走;原收藏不变。+ if (target?.config) {+ setTarget({ ...target, config });+ if (matchingFavorite && !reset)+ setNotice(t("models.unified.originalFavoriteKept"));+ }+ if (row.selected) return;setRemoteConfigs((current) => {const next = new Map(current);if (reset) next.delete(key);@@ -1096,7 +1161,7 @@ export function UnifiedModelPickerSheet(.filter(Boolean).join(" · "),price: price ? `${price.title}\n${price.amountsLine}` : null,- favoritesDisabled: !prefs.favoritesReady || !!row.remoteDevice,+ favoritesDisabled: !prefs.favoritesReady || favoriteSource === null,isFavorite: !!matchingFavorite,canReset,configurationSummary: [@@ -1160,6 +1225,7 @@ export function UnifiedModelPickerSheet(item.uid === original.uid? {...config,+ providerId: item.providerId,modelId: row.entry.modelId,uid: item.uid,}@@ -1173,7 +1239,7 @@ export function UnifiedModelPickerSheet(});},onFavorite: () => {- if (!prefs.favoritesReady || favoriteEdit || row.remoteDevice)+ if (!prefs.favoritesReady || favoriteEdit || favoriteSource === null)return;void transact(async (isCurrent) => {if (matchingFavorite) {@@ -1189,7 +1255,11 @@ export function UnifiedModelPickerSheet(await prefs.save(addModelFavorite(prefs.value,- { ...row.config, modelId: row.entry.modelId },+ {+ ...row.config,+ providerId: favoriteSource,+ modelId: row.entry.modelId,+ },createFavoriteUid(),),);diff --git a/apps/mobile/src/session/remoteAgentCatalogs.ts b/apps/mobile/src/session/remoteAgentCatalogs.tsindex 1db4776c4b..4a997f3384 100644--- a/apps/mobile/src/session/remoteAgentCatalogs.ts+++ b/apps/mobile/src/session/remoteAgentCatalogs.ts@@ -19,6 +19,8 @@ export interface RemoteAgentCatalog {name: string;/** loading = 还没读到;error = 读不到(离线 / 没开远程控制 / 旧版本)且没有缓存。 */status: 'loading' | 'ready' | 'error';+ /** 此刻连不上(只因任务的 Agent 在这台才留在清单里,目录可能来自缓存)。 */+ offline?: true;providers: ProviderView[];modelVisibilityOverrides?: Record<string, boolean>;}diff --git a/apps/mobile/src/session/useRemoteAgentCatalogs.ts b/apps/mobile/src/session/useRemoteAgentCatalogs.tsindex eccd52b3ad..452de06921 100644--- a/apps/mobile/src/session/useRemoteAgentCatalogs.ts+++ b/apps/mobile/src/session/useRemoteAgentCatalogs.ts@@ -63,7 +63,8 @@ export function useRemoteAgentCatalogs(input: {/** 只读 keepDeviceIds 里的电脑(选择器没打开、只为模型药丸取 Agent 所在那台的目录时)。 */keepOnly?: boolean;}): RemoteAgentCatalog[] {- const { readDeviceList, invoke, openLink, connectionEpoch, status } = useDeviceLink();+ const { readDeviceList, invoke, openLink, connectionEpoch, status, presenceVersion, getPresenceAvailability } =+ useDeviceLink();const { accountGeneration } = useAuth();const { t } = useTranslation();const revoked = useRevokedDevices();@@ -210,13 +211,18 @@ export function useRemoteAgentCatalogs(input: {return useMemo(() => {if (devices.length === 0 && shareCatalogs.length === 0) return NO_CATALOGS;+ void presenceVersion;const deviceCatalogs = devices.map((device): RemoteAgentCatalog => {const state = catalogs.get(device.deviceId);const payload = state?.payload;+ // 设备清单是打开时的快照;面板开着期间上下线以实时 presence 为准(未知时沿用清单)。+ const presence = getPresenceAvailability(device.deviceId);+ const offline = presence === false || (presence !== true && !device.canOpen);return {deviceId: device.deviceId,name: device.name,status: state?.status ?? (device.canOpen ? 'loading' : 'error'),+ ...(offline ? { offline: true as const } : {}),providers: payload ? remoteAgentProviders(payload.providers) : [],...(payload?.modelVisibilityOverrides !== undefined? { modelVisibilityOverrides: payload.modelVisibilityOverrides }@@ -224,5 +230,5 @@ export function useRemoteAgentCatalogs(input: {};});return shareCatalogs.length === 0 ? deviceCatalogs : [...deviceCatalogs, ...shareCatalogs];- }, [catalogs, devices, shareCatalogs]);+ }, [catalogs, devices, shareCatalogs, presenceVersion, getPresenceAvailability]);}diff --git a/docs/product-rules/model-selector-unified.md b/docs/product-rules/model-selector-unified.mdindex d58ab9d093..a562dd3452 100644--- a/docs/product-rules/model-selector-unified.md+++ b/docs/product-rules/model-selector-unified.md@@ -66,6 +66,7 @@### 1.5 收藏 = 配置副本- **远程收藏按被控电脑共享**:Desktop 与 Mobile 连接同一台电脑时读取和修改该电脑当前账号的既有收藏。各被控电脑独立,不将控制端的本机收藏套用或自动合并到远端。收藏以单条新增、条件编辑、条件删除同步,等持久化确认后反馈成功;并发修改同一副本时拒绝旧快照覆盖,重读后再编辑。断线、账号切换、旧版不支持时不得声称已同步;不自动重试写操作,也不影响会话和连接恢复。+- **其他电脑上的模型照样收藏**(2026-10-13):同账号另一台电脑开放了远程调用的模型,收藏、编辑、取消收藏与本机模型完全一样,用户不用关心模型在哪台电脑上运行。收藏仍存在被控电脑上,运行位置编进来源(`agent-device-favorite:["<电脑>","<供应商>"]`,见 `packages/device-link/src/modelFavorites.ts`),不另加字段——旧版解析会丢掉不认识的字段,把那台电脑的供应商当成被控电脑的同名供应商而派错地方;编进来源后旧版只把这条当作不认识的供应商藏起来。它与本机收藏排在同一个收藏区,说明行带电脑名以区分本机同名模型;选中即在那台电脑运行。同一模型在本机与那台电脑上的收藏互不匹配。那台电脑离线(包括只因任务的 Agent 在那台、靠缓存目录留在列表里)、关闭远程调用、供应商被收进供应商组,或那台电脑上已没有这个模型时先不显示,收藏本身保留;Desktop 在那台电脑仍在列表里、目录还在读取或读取失败时置灰显示,Mobile 等目录读到后再显示。Desktop 收藏区里这类条目不弹参数浮层,参数在那台电脑的视图里调;已建任务的 Agent 已在那台电脑上时,点它先切到那台电脑的视图,再点一次应用。供应商分享(`share:`)沿用各自的收藏方式,Mobile 暂不支持收藏分享来的模型。- Desktop 行/浮层的 ☆ 是**单向「添加副本」动作**:把当前生效配置(模型+引擎+深度+Fast)拷进收藏区,点亮 0.7s 反馈后恢复;源头行不持有收藏态。重复添加去重。- **Mobile 收藏与参数调整分开**(用户确认交互原型,2026-10-02):按来源、模型、引擎、推理强度与 Fast 完整匹配已保存副本,展示当前配置摘要。空心星标对应「收藏此配置」,保存确认后保持实心星标并显示「已收藏 · 点击取消」;再次点击只删除匹配的副本,所有入口都保持当前配置与详情页,不触发恢复推荐。模型目录 ID 与同一条目的 wire ID 视为同一模型,不把已失效档位或不可用 Fast 自动降级后当成匹配。状态跟随被控端收藏快照,失败保留原状态并允许重试。diff --git a/packages/device-link/src/__tests__/modelFavorites.test.ts b/packages/device-link/src/__tests__/modelFavorites.test.tsindex 58ec1637fc..8985c95690 100644--- a/packages/device-link/src/__tests__/modelFavorites.test.ts+++ b/packages/device-link/src/__tests__/modelFavorites.test.ts@@ -5,6 +5,9 @@ import {MODEL_FAVORITES_GET,MODEL_FAVORITES_APPLY,MODEL_FAVORITES_CHANGED,+ MODEL_FAVORITE_TEXT_MAX_LENGTH,+ agentDeviceFavoriteSource,+ parseAgentDeviceFavoriteSource,} from "../index";import { REMOTE_INVOKE_ALLOWLIST, PUSH_FORWARD_ALLOWLIST } from "../allowlist";import { topicForPush } from "../topics";@@ -54,3 +57,16 @@ it("allows a larger local source bound without changing wire or other field limiexpect(() => parseModelFavoriteMutation({ kind: 'remove', expected: { ...longItem, uid: 'u'.repeat(513) } }, 2048)).toThrow();expect(parseModelFavorites([{ ...item, providerId: 'p'.repeat(512) }])).toHaveLength(1);});+it("encodes another computer's source into the favorite provider id and round-trips it", () => {+ const deviceId = "a".repeat(64);+ const key = agentDeviceFavoriteSource({ deviceId, providerId: "anthropic" });+ expect(key.length).toBeLessThanOrEqual(MODEL_FAVORITE_TEXT_MAX_LENGTH);+ expect(parseAgentDeviceFavoriteSource(key)).toEqual({ deviceId, providerId: "anthropic" });+ // The encoded source travels through the existing wire validation unchanged.+ expect(parseModelFavorites([{ ...item, providerId: key }])[0]!.providerId).toBe(key);+ expect(parseAgentDeviceFavoriteSource("anthropic")).toBeNull();+ expect(parseAgentDeviceFavoriteSource("agent-device-favorite:[\"only-one\"]")).toBeNull();+ expect(parseAgentDeviceFavoriteSource("agent-device-favorite:not-json")).toBeNull();+ expect(() => agentDeviceFavoriteSource({ deviceId: "", providerId: "anthropic" })).toThrow();+ expect(() => agentDeviceFavoriteSource({ deviceId, providerId: "p".repeat(500) })).toThrow();+});diff --git a/packages/device-link/src/modelFavorites.ts b/packages/device-link/src/modelFavorites.tsindex 40d4b0d562..cd7edfea70 100644--- a/packages/device-link/src/modelFavorites.ts+++ b/packages/device-link/src/modelFavorites.ts@@ -21,6 +21,35 @@ export type ModelFavoriteMutation =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;++/**+ * 收藏里「在同账号另一台电脑上运行」的来源:位置编进 providerId,收藏仍存在被控电脑上。+ * 不另加字段 —— 旧版解析会丢掉不认识的字段,把那台电脑的供应商当成被控电脑的同名供应商,+ * 任务就派错了地方;编进 providerId 后旧版只会看到一个不认识的供应商并把这条藏起来。+ * 只用于收藏的存储与匹配,绝不作为模型请求的 providerId。+ */+const AGENT_DEVICE_FAVORITE_PREFIX = "agent-device-favorite:";+export interface AgentDeviceFavoriteSource {+ deviceId: string;+ providerId: string;+}+export function agentDeviceFavoriteSource(source: AgentDeviceFavoriteSource): string {+ const key = AGENT_DEVICE_FAVORITE_PREFIX + JSON.stringify([source.deviceId, source.providerId]);+ if (!text(source.deviceId) || !text(source.providerId) || !text(key))+ throw new Error("Invalid agent device favorite source");+ return key;+}+export function parseAgentDeviceFavoriteSource(value: string): AgentDeviceFavoriteSource | null {+ if (!value.startsWith(AGENT_DEVICE_FAVORITE_PREFIX)) return null;+ try {+ const parts: unknown = JSON.parse(value.slice(AGENT_DEVICE_FAVORITE_PREFIX.length));+ if (!Array.isArray(parts) || parts.length !== 2 || !parts.every((part) => text(part)))+ return null;+ return { deviceId: parts[0], providerId: parts[1] };+ } catch {+ return null;+ }+}export function parseRemoteModelFavorite(value: unknown,needsUid = true,