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(model-picker): 收藏先显示缓存,记住新建任务选的远程/分享模型

Dash2d50f0c2a7f5
diff --git a/apps/desktop/src/renderer/__tests__/remoteModelFavorites.test.tsx b/apps/desktop/src/renderer/__tests__/remoteModelFavorites.test.tsx
index ca48a5ef22..1e51c7c992 100644
--- a/apps/desktop/src/renderer/__tests__/remoteModelFavorites.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/remoteModelFavorites.test.tsx
@@ -2,7 +2,7 @@
import { act, createElement } from 'react';
import { createRoot } from 'react-dom/client';
import { beforeEach, afterEach, it, expect, vi } from 'vitest';
-import { useRemoteModelFavorites } from '@/state/useRemoteModelFavorites';
+import { useRemoteModelFavorites, __resetRemoteModelFavoritesCacheForTest } from '@/state/useRemoteModelFavorites';
const item = {
uid: 'fav-2',
providerId: 'remote-account',
@@ -34,9 +34,23 @@ beforeEach(() => {
},
},
});
+ __resetRemoteModelFavoritesCacheForTest();
root = createRoot(document.createElement('div'));
});
afterEach(() => act(() => root.unmount()));
+// 回归:远控时模型面板每次打开都重新挂载,收藏从空列表开始、等读回来才出现。
+// 重新挂载先显示上次读到的收藏,后台读到新的再替换。
+it('a freshly mounted panel shows the last favorites while the fresh read is in flight', async () => {
+ await act(async () => root.render(createElement(Probe, {})));
+ act(() => root.unmount());
+ root = createRoot(document.createElement('div'));
+ let resolve!: (v: unknown) => void;
+ invoke.mockImplementationOnce(() => new Promise((r) => { resolve = r; }));
+ await act(async () => root.render(createElement(Probe, {})));
+ expect(view.items).toEqual([item]);
+ await act(async () => resolve([{ ...item, effort: 'low' }]));
+ expect(view.items[0]?.effort).toBe('low');
+});
it('does not refresh for an opened or administratively cleared breaker', async () => {
await act(async () => root.render(createElement(Probe, {})));
invoke.mockClear();
diff --git a/apps/desktop/src/renderer/state/useRemoteModelFavorites.ts b/apps/desktop/src/renderer/state/useRemoteModelFavorites.ts
index 07094d63e9..5ca292f51a 100644
--- a/apps/desktop/src/renderer/state/useRemoteModelFavorites.ts
+++ b/apps/desktop/src/renderer/state/useRemoteModelFavorites.ts
@@ -16,6 +16,13 @@ export interface FavoriteStore {
update(uid: string, patch: ModelFavoritePatch): void | Promise<void>;
remove(uid: string): void | Promise<void>;
}
+// 上次从那台电脑读到的收藏(按数据归属代次 + 电脑):面板每次打开先显示它,再在后台读最新的。
+// 写入仍带 expected 交给那台电脑核对,旧快照改不坏真相。
+const lastFavorites = new Map<string, ModelFavoriteItem[]>();
+export function __resetRemoteModelFavoritesCacheForTest(): void {
+ lastFavorites.clear();
+}
+
/** Remote views already hold the device's sessions topic. Only invalidate this
* device's favorites; never reset the link or touch the controller's local store. */
export function useRemoteModelFavorites(deviceId?: string) {
@@ -28,7 +35,8 @@ export function useRemoteModelFavorites(deviceId?: string) {
const [errorCode, setErrorCode] = useState<string | null>(null);
const [writeErrorKey, setWriteErrorKey] = useState<string | null>(null);
const sequence = useRef(0);
- const items = state?.key === key ? state.items : [];
+ const cached = lastFavorites.get(key);
+ const items = state?.key === key ? state.items : (cached ?? []);
const refresh = async () => {
if (!deviceId) return;
const seq = ++sequence.current;
@@ -40,7 +48,9 @@ export function useRemoteModelFavorites(deviceId?: string) {
JSON.stringify(getDataOwnerGeneration()) !== JSON.stringify(owner)
)
return;
- setState({ key, items: parseModelFavorites(value) as ModelFavoriteItem[] });
+ const next = parseModelFavorites(value) as ModelFavoriteItem[];
+ lastFavorites.set(key, next);
+ setState({ key, items: next });
setError(false);
setErrorCode(null);
} catch (err) {
@@ -88,7 +98,7 @@ export function useRemoteModelFavorites(deviceId?: string) {
setWriteErrorKey(null);
if (
!deviceId ||
- state?.key !== key ||
+ (state?.key !== key && cached === undefined) ||
current.current !== key ||
JSON.stringify(getDataOwnerGeneration()) !== JSON.stringify(owner)
)
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index 387ff337dc..c30783b552 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -644,6 +644,8 @@ export default function NewRemoteSessionScreen() {
const [remoteAgentChoice, setRemoteAgentChoice] = useState<{
controlledDeviceId: string;
pick: NewSessionRemoteAgentPick;
+ /** 打开新建页时按记忆恢复的(不是本页刚选的):那台电脑 / 那个分享此刻用不了就退回被控电脑默认。 */
+ restored?: true;
} | null>(null);
// 只对选它时的那台被控电脑与那个 Agent 成立:换了电脑、在别处换了 Agent 就不再生效(按条件
// 判,不靠 effect 清——恢复草稿时电脑与草稿同一轮写入,effect 会把刚恢复的选择误清)。
@@ -1193,6 +1195,32 @@ export default function NewRemoteSessionScreen() {
}).activeSourceId;
return remoteAgentCatalog.providers.find((provider) => provider.id === sourceId) ?? null;
}, [remoteAgentCatalog, remoteAgentPick]);
+ // 恢复上次在这台被控电脑上给当前 agent 选的另一台电脑 / 分享来的模型。每个(电脑, agent)只试一次,
+ // 本页用户自己改过运行配置就不再恢复。
+ const remoteAgentRestoreKeyRef = useRef<string | null>(null);
+ useEffect(() => {
+ if (!newSessionPreferencesLoaded || !selectedDeviceId || userTouchedRuntimeRef.current) return;
+ const key = JSON.stringify([selectedDeviceId, draft.agentKind]);
+ if (remoteAgentRestoreKeyRef.current === key) return;
+ remoteAgentRestoreKeyRef.current = key;
+ const saved = newSessionPreferences?.remoteAgentByDevice[selectedDeviceId]?.[draft.agentKind];
+ if (!saved || isSharedTaskPeer(selectedDeviceId)) return;
+ setRemoteAgentChoice({ controlledDeviceId: selectedDeviceId, pick: saved, restored: true });
+ }, [draft.agentKind, newSessionPreferences, newSessionPreferencesLoaded, selectedDeviceId]);
+ // 恢复出来的选择此刻用不了(被控电脑不再提供远程模型、那台离线或读不到、模型已不在那份目录里)
+ // → 退回被控电脑的默认;记忆保留,那台恢复后下次打开照样选回。
+ const restoredRemoteAgentUnusable = !!remoteAgentChoice?.restored && !!remoteAgentPick && (
+ (deviceProviders.ready && !remoteAgentSupported)
+ || (!!remoteAgentCatalog && (
+ remoteAgentCatalog.status === 'error'
+ || !!remoteAgentCatalog.offline
+ || (remoteAgentCatalog.status === 'ready'
+ && !(remoteAgentPillProvider && getModel(remoteAgentPillProvider, remoteAgentPick.model, remoteAgentPick.agentKind)))
+ ))
+ );
+ useEffect(() => {
+ if (restoredRemoteAgentUnusable) setRemoteAgentChoice(null);
+ }, [restoredRemoteAgentUnusable]);
const catalogReadyRef = useRef(deviceProviders.ready);
catalogReadyRef.current = deviceProviders.ready;
// 供应商目录本身的渲染期镜像:异步回调(权限确认 .then)提交时用它现场重建目标
@@ -2580,6 +2608,12 @@ export default function NewRemoteSessionScreen() {
void loadBrowsePath(draft.workingDir.trim() || '~');
}, [draft.workingDir, loadBrowsePath, patchDraft, selectedDeviceId, initialWorkingDir]);
+ // 选回被控电脑自己的模型:不再在下次打开时恢复这个 agent 选过的其他电脑 / 分享来的模型。
+ const forgetRemoteAgentPick = useCallback((agentKind: NewSessionAgentKind) => {
+ if (!selectedDeviceId) return;
+ void saveNewSessionPreferences({ remoteAgentForDevice: { deviceId: selectedDeviceId, agentKind, pick: null } });
+ }, [selectedDeviceId]);
+
// 选「供应商 + 模型」(provider-aware):resolveRowSelection 原子落 model + providerId +
// effort + fast 四件套(effort 优先级与桌面同源:该来源记忆 → 沿用当前档 → 模型默认;
// 同模型换来源不沿用当前档;fast 按 (来源, 模型) 记忆恢复,fastEditable 门控)。
@@ -2587,6 +2621,7 @@ export default function NewRemoteSessionScreen() {
userTouchedRuntimeRef.current = true; // 用户手动选了模型 → 不再自动覆盖运行配置
runtimeActionSeqRef.current += 1; // 使在途的切 agent/恢复回调失效(最新者胜)
setRemoteAgentChoice(null);
+ forgetRemoteAgentPick(draft.agentKind);
setDraft((current) => {
const next = resolveRowSelection({
row,
@@ -2610,7 +2645,7 @@ export default function NewRemoteSessionScreen() {
});
requestHostChoiceWrite(true);
setModelSheetOpen(false);
- }, [capabilities, draftMemory, requestHostChoiceWrite]);
+ }, [capabilities, draft.agentKind, draftMemory, forgetRemoteAgentPick, requestHostChoiceWrite]);
// source.deviceId 非空 = 选的是另一台电脑(或分享来的)目录里的行:Agent 在那里运行。
const selectUnifiedModel = useCallback(async (
@@ -2647,7 +2682,18 @@ export default function NewRemoteSessionScreen() {
providerId: config.providerId, effort: config.effort, fastMode, permissionMode: permission }));
requestHostChoiceWrite(true);
}
- void saveNewSessionPreferences({ agentKind: config.agent });
+ // 选其他电脑 / 分享来的模型就记下(下次打开新建页恢复);选回被控电脑自己的就清掉。
+ void saveNewSessionPreferences({
+ agentKind: config.agent,
+ remoteAgentForDevice: {
+ deviceId: deviceAtStart,
+ agentKind: config.agent,
+ pick: remoteDeviceId
+ ? { deviceId: remoteDeviceId, agentKind: config.agent, model: config.modelId,
+ providerId: config.providerId, effort: config.effort, fastMode }
+ : null,
+ },
+ });
return true;
}, [creating, selectedDeviceId, maker, newSessionPreferences, draft.agentKind, draft.permissionMode, requestHostChoiceWrite]);
@@ -2656,12 +2702,13 @@ export default function NewRemoteSessionScreen() {
userTouchedRuntimeRef.current = true; // 用户手动选了模型 → 不再自动覆盖运行配置
runtimeActionSeqRef.current += 1; // 使在途的切 agent/恢复回调失效(最新者胜)
setRemoteAgentChoice(null);
+ forgetRemoteAgentPick(draft.agentKind);
explicitProviderModelSelectionRef.current = null;
setDraft((current) =>
reconcileRuntimeDraftWithCapabilities({ ...current, model: option.id, providerId: null }, capabilities));
requestHostChoiceWrite(true);
setModelSheetOpen(false);
- }, [capabilities, requestHostChoiceWrite]);
+ }, [capabilities, draft.agentKind, forgetRemoteAgentPick, requestHostChoiceWrite]);
// 选中行的 effort/fast 变更:落 draft(live 真相)+ 写草稿记忆(下次选回恢复)。
// 记忆槽的来源 id:显式选中的来源,未显式选时用当前高亮的默认来源(activeSourceIdRef)。
diff --git a/apps/mobile/src/__tests__/newSessionHostDefaults.test.tsx b/apps/mobile/src/__tests__/newSessionHostDefaults.test.tsx
index d1224664ea..b2f48b541c 100644
--- a/apps/mobile/src/__tests__/newSessionHostDefaults.test.tsx
+++ b/apps/mobile/src/__tests__/newSessionHostDefaults.test.tsx
@@ -79,7 +79,7 @@ function mount(deviceId = 'desktop', agentKind: NewSessionAgentKind = 'codex', f
draft: { ...DEFAULT_NEW_SESSION_DRAFT, agentKind, model: 'chosen', providerId: 'provider', effort: 'high', fastMode: false },
maker: { getNewMakerDefaults: vi.fn((agent?: string) => agent === failedAgent ? Promise.reject(new Error('read failed')) : pendingReads.get(agent as NewSessionAgentKind)?.promise ?? read.promise), applyNewMakerDraftPref: vi.fn(async () => {}) },
openLink: vi.fn(async () => {}),
- preferences: storedAgent ? { agentKind: storedAgent, permissionModeByAgent: {}, device: null, workspaceKind: null, workingDirByDevice: {} } : null,
+ preferences: storedAgent ? { agentKind: storedAgent, permissionModeByAgent: {}, device: null, workspaceKind: null, workingDirByDevice: {}, remoteAgentByDevice: {} } : null,
};
let state!: State;
function Harness() { state = usePageDefaults(bindings); return null; }
diff --git a/apps/mobile/src/__tests__/newSessionPreferenceStore.test.ts b/apps/mobile/src/__tests__/newSessionPreferenceStore.test.ts
index f916b6cf95..eb367b7021 100644
--- a/apps/mobile/src/__tests__/newSessionPreferenceStore.test.ts
+++ b/apps/mobile/src/__tests__/newSessionPreferenceStore.test.ts
@@ -126,6 +126,7 @@ describe('newSessionPreferenceStore', () => {
workspaceKind: null,
permissionModeByAgent: {},
workingDirByDevice: {},
+ remoteAgentByDevice: {},
});
expect(JSON.parse(store.get(__testing.storageKey) ?? '{}')).toEqual({
agentKind: 'codex',
@@ -153,6 +154,7 @@ describe('newSessionPreferenceStore', () => {
workspaceKind: null,
permissionModeByAgent: {},
workingDirByDevice: {},
+ remoteAgentByDevice: {},
});
store.set(__testing.storageKey, '{broken');
@@ -162,6 +164,7 @@ describe('newSessionPreferenceStore', () => {
workspaceKind: null,
permissionModeByAgent: {},
workingDirByDevice: {},
+ remoteAgentByDevice: {},
});
await saveNewSessionPreferences({
@@ -173,6 +176,7 @@ describe('newSessionPreferenceStore', () => {
workspaceKind: null,
permissionModeByAgent: {},
workingDirByDevice: {},
+ remoteAgentByDevice: {},
});
});
@@ -200,6 +204,7 @@ describe('newSessionPreferenceStore', () => {
workspaceKind: null,
permissionModeByAgent: { 'claude-code': 'bypassPermissions', codex: 'ask' },
workingDirByDevice: {},
+ remoteAgentByDevice: {},
});
// 落盘的 plan / 非法 agent 键在读取时被清洗。
@@ -212,6 +217,7 @@ describe('newSessionPreferenceStore', () => {
workspaceKind: null,
permissionModeByAgent: { codex: 'auto' },
workingDirByDevice: {},
+ remoteAgentByDevice: {},
});
});
@@ -237,6 +243,7 @@ describe('newSessionPreferenceStore', () => {
workspaceKind: 'dialogue',
permissionModeByAgent: {},
workingDirByDevice: { devA: '/repo/fourth', devB: ' /other/app ' },
+ remoteAgentByDevice: {},
});
expect(JSON.parse(store.get(__testing.storageKey) ?? '{}')).toEqual({
workspaceKind: 'dialogue',
@@ -247,11 +254,31 @@ describe('newSessionPreferenceStore', () => {
store.set(__testing.workingDirStorageKey(accountVaultKey('global', 'account-a')), JSON.stringify({ devA: '/repo/ok', devB: 42, ' ': '/x', devC: '', devD: ' /keep me ' }));
await expect(readNewSessionPreferences()).resolves.toMatchObject({
workingDirByDevice: { devA: '/repo/ok', devD: ' /keep me ' },
+ remoteAgentByDevice: {},
});
store.set(__testing.workingDirStorageKey(accountVaultKey('global', 'account-a')), JSON.stringify('bad'));
await expect(readNewSessionPreferences()).resolves.toMatchObject({ workingDirByDevice: {} });
});
+ // 回归:新建页选了其他电脑 / 分享来的模型,下次打开就回到被控电脑默认。按(账号, 被控电脑, agent)记,
+ // 选回被控电脑自己的模型即清掉。
+ it('remembers the remote or shared model per controlled device and agent, per account', async () => {
+ const { readNewSessionPreferences, saveNewSessionPreferences } =
+ await import('@/session/newSessionPreferenceStore');
+ const pick = { deviceId: 'share:s1', agentKind: 'codex' as const, model: 'gpt-x', providerId: 'openai', effort: 'high', fastMode: true };
+ await saveNewSessionPreferences({ remoteAgentForDevice: { deviceId: 'mac', agentKind: 'codex', pick } });
+ await saveNewSessionPreferences({ remoteAgentForDevice: { deviceId: 'mac', agentKind: 'pi', pick: { ...pick, agentKind: 'pi', deviceId: 'studio' } } });
+ expect((await readNewSessionPreferences()).remoteAgentByDevice).toEqual({
+ mac: { codex: pick, pi: { ...pick, agentKind: 'pi', deviceId: 'studio' } },
+ });
+ setMobileAuthOwner('account-b');
+ expect((await readNewSessionPreferences()).remoteAgentByDevice).toEqual({});
+ setMobileAuthOwner('account-a');
+ await saveNewSessionPreferences({ remoteAgentForDevice: { deviceId: 'mac', agentKind: 'codex', pick: null } });
+ await saveNewSessionPreferences({ remoteAgentForDevice: { deviceId: 'mac', agentKind: 'pi', pick: null } });
+ expect((await readNewSessionPreferences()).remoteAgentByDevice).toEqual({});
+ });
+
it('remembers either workspace mode across reloads without losing other preferences', async () => {
const { readNewSessionPreferences, saveNewSessionPreferences } =
await import('@/session/newSessionPreferenceStore');
diff --git a/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx b/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx
index 85d58a0b14..16a86902fc 100644
--- a/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx
+++ b/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx
@@ -162,7 +162,7 @@ function mountWorkspace(options: { initialWorkingDir?: string; restoredKind?: Ne
) {
await act(async () => {
resolveRead({ workspaceKind: kind, device: { deviceId, name: deviceId },
- agentKind: null, permissionModeByAgent: {}, workingDirByDevice });
+ agentKind: null, permissionModeByAgent: {}, workingDirByDevice, remoteAgentByDevice: {} });
await pendingRead;
});
},
diff --git a/apps/mobile/src/__tests__/remoteAgentCatalogs.test.ts b/apps/mobile/src/__tests__/remoteAgentCatalogs.test.ts
index c29e101f5a..69f1ee0bd2 100644
--- a/apps/mobile/src/__tests__/remoteAgentCatalogs.test.ts
+++ b/apps/mobile/src/__tests__/remoteAgentCatalogs.test.ts
@@ -149,8 +149,10 @@ describe('provider shares in the remote Agent catalogs', () => {
share('ready'),
];
expect(build({ shares }).map((item) => item.deviceId)).toEqual(['share:ready']);
- expect(build({ shares, keepDeviceIds: ['share:paused', 'share:offline'] }).map((item) => [item.deviceId, item.status]))
- .toEqual([['share:paused', 'ready'], ['share:offline', 'error'], ['share:ready', 'ready']]);
+ // 留下来的不可用分享标 offline:恢复出来的新建任务选择据此退回被控电脑默认,收藏也先不显示。
+ expect(build({ shares, keepDeviceIds: ['share:paused', 'share:offline'] })
+ .map((item) => [item.deviceId, item.status, item.offline ?? false]))
+ .toEqual([['share:paused', 'ready', true], ['share:offline', 'error', true], ['share:ready', 'ready', false]]);
});
it('only returns kept shares when reading for the model pill', () => {
diff --git a/apps/mobile/src/__tests__/remoteModelFavorites.test.tsx b/apps/mobile/src/__tests__/remoteModelFavorites.test.tsx
index 0d3b784beb..529a521bba 100644
--- a/apps/mobile/src/__tests__/remoteModelFavorites.test.tsx
+++ b/apps/mobile/src/__tests__/remoteModelFavorites.test.tsx
@@ -34,6 +34,7 @@ import {
useRemoteMobileFavorites,
mobileFavorite,
mobileFavoriteMutation,
+ __resetRemoteMobileFavoritesCacheForTest,
} from "@/session/useRemoteMobileFavorites";
const item = {
uid: "fav-1",
@@ -53,6 +54,7 @@ beforeEach(() => {
h.context.status = "online";
h.context.recoveringDeviceIds.clear();
h.unresponsive.clear();
+ __resetRemoteMobileFavoritesCacheForTest();
root = createRoot(document.createElement("div"));
});
afterEach(() => act(() => root.unmount()));
@@ -73,6 +75,20 @@ it.each(['peer', 'unresponsive'])('retains favorites and refreshes after %s reco
expect(h.view.items[0].effort).toBe('low');
expect(h.view.error).toBeNull();
});
+// 回归:任务页 / 新建页每次挂载选择器都从空列表开始,等读回来「收藏」才出现。
+// 重新挂载时先显示上次读到的收藏,后台读到新的再替换。
+it("a freshly mounted picker shows the last favorites while the fresh read is in flight", async () => {
+ await act(async () => root.render(createElement(Probe, {})));
+ act(() => root.unmount());
+ root = createRoot(document.createElement("div"));
+ let resolve!: (v: unknown) => void;
+ h.invoke.mockImplementationOnce(() => new Promise((r) => { resolve = r; }));
+ await act(async () => root.render(createElement(Probe, {})));
+ expect(h.view.ready).toBe(true);
+ expect(h.view.items).toEqual([mobileFavorite(item)]);
+ await act(async () => resolve([{ ...item, effort: "low" }]));
+ expect(h.view.items[0].effort).toBe("low");
+});
it("maps engine spelling and treats unchanged field order as no operation", () => {
const mobile = mobileFavorite(item);
expect(mobile.agent).toBe("claude-code");
diff --git a/apps/mobile/src/session/newSession.ts b/apps/mobile/src/session/newSession.ts
index 43387db4df..47b8f9f904 100644
--- a/apps/mobile/src/session/newSession.ts
+++ b/apps/mobile/src/session/newSession.ts
@@ -131,6 +131,12 @@ export interface NewSessionStoredPreferences {
* 按设备归属,避免把一台电脑的路径套到另一台;没有记忆的设备沿用最近项目默认逻辑。
*/
workingDirByDevice: Record<string, string>;
+ /**
+ * 每台被控电脑上、每个 agent 上次在新建页显式选的另一台电脑或分享来的模型
+ * (被控电脑 deviceId → agent → 选择)。选回被控电脑自己的模型即清掉;打开新建页时恢复,
+ * 那台电脑 / 那个分享此刻用不了时回到被控电脑的默认。与 workingDirByDevice 同样按账号存。
+ */
+ remoteAgentByDevice: Record<string, Partial<Record<NewSessionAgentKind, NewSessionRemoteAgentPick>>>;
}
export interface NewSessionDraftSummary {
diff --git a/apps/mobile/src/session/newSessionPreferenceStore.ts b/apps/mobile/src/session/newSessionPreferenceStore.ts
index 17ccc470aa..3d140f6ade 100644
--- a/apps/mobile/src/session/newSessionPreferenceStore.ts
+++ b/apps/mobile/src/session/newSessionPreferenceStore.ts
@@ -8,6 +8,7 @@ import {
normalizeNewSessionAgentKind,
type NewSessionAgentKind,
type NewSessionDeviceOption,
+ type NewSessionRemoteAgentPick,
type NewSessionStoredPreferences,
type NewSessionWorkspaceKind,
} from '@/session/newSession';
@@ -22,6 +23,8 @@ export interface NewSessionPreferencePatch {
permissionModeForAgent?: { agentKind: NewSessionAgentKind; mode: string };
/** 记住某台被控电脑上次显式选择的项目目录(单键合并进 workingDirByDevice;空值被忽略,#4103)。 */
workingDirForDevice?: { deviceId: string; workingDir: string };
+ /** 记住(pick)或清掉(null)某台被控电脑上某 agent 选的另一台电脑 / 分享来的模型。 */
+ remoteAgentForDevice?: { deviceId: string; agentKind: NewSessionAgentKind; pick: NewSessionRemoteAgentPick | null };
}
export async function readNewSessionPreferences(): Promise<NewSessionStoredPreferences> {
@@ -29,17 +32,24 @@ export async function readNewSessionPreferences(): Promise<NewSessionStoredPrefe
const owner = getMobileAuthOwner();
await writeChain;
const preferences = await loadNewSessionPreferences(owner.accountKey);
- return isMobileAuthOwnerCurrent(owner) ? preferences : { ...preferences, workingDirByDevice: {} };
+ return isMobileAuthOwnerCurrent(owner)
+ ? preferences
+ : { ...preferences, workingDirByDevice: {}, remoteAgentByDevice: {} };
}
function workingDirStorageKey(accountId: string): string {
return `${STORAGE_KEY}.working-directories.${encodeURIComponent(accountId)}`;
}
+function remoteAgentStorageKey(accountId: string): string {
+ return `${STORAGE_KEY}.remote-agents.${encodeURIComponent(accountId)}`;
+}
+
async function loadNewSessionPreferences(accountId: string): Promise<NewSessionStoredPreferences> {
- const [raw, directories] = await Promise.all([
+ const [raw, directories, remoteAgents] = await Promise.all([
AsyncStorage.getItem(STORAGE_KEY).catch(() => null),
accountId ? AsyncStorage.getItem(workingDirStorageKey(accountId)).catch(() => null) : null,
+ accountId ? AsyncStorage.getItem(remoteAgentStorageKey(accountId)).catch(() => null) : null,
]);
let preferences = emptyPreferences();
try {
@@ -53,6 +63,11 @@ async function loadNewSessionPreferences(accountId: string): Promise<NewSessionS
} catch {
// A malformed directory map must not prevent loading the other preferences.
}
+ try {
+ if (remoteAgents) preferences.remoteAgentByDevice = normalizeRemoteAgentByDevice(JSON.parse(remoteAgents));
+ } catch {
+ // Same as directories: a malformed map only loses this memory.
+ }
return preferences;
}
@@ -76,6 +91,8 @@ async function writeNewSessionPreferences(
const workingDirDeviceId = workingDirPatch?.deviceId.trim() ?? '';
// 路径原样保存(macOS / Linux 允许目录名首尾带空格,浏览器也原样返回);只用 trim 判空。
const workingDirValue = workingDirPatch && workingDirPatch.workingDir.trim() ? workingDirPatch.workingDir : '';
+ const remoteAgentPatch = patch.remoteAgentForDevice;
+ const remoteAgentDeviceId = remoteAgentPatch?.deviceId.trim() ?? '';
const next: NewSessionStoredPreferences = {
agentKind: patch.agentKind ?? current.agentKind,
workspaceKind: patch.workspaceKind ?? current.workspaceKind,
@@ -90,18 +107,39 @@ async function writeNewSessionPreferences(
workingDirDeviceId && workingDirValue
? { ...current.workingDirByDevice, [workingDirDeviceId]: workingDirValue }
: current.workingDirByDevice,
+ remoteAgentByDevice: remoteAgentPatch && remoteAgentDeviceId
+ ? withRemoteAgentPick(current.remoteAgentByDevice, remoteAgentDeviceId, remoteAgentPatch.agentKind, remoteAgentPatch.pick)
+ : current.remoteAgentByDevice,
};
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(serializePreferences(next))).catch(() => undefined);
if (workingDirDeviceId && workingDirValue && owner.accountKey && isMobileAuthOwnerCurrent(owner)) {
await AsyncStorage.setItem(workingDirStorageKey(owner.accountKey), JSON.stringify(next.workingDirByDevice)).catch(() => undefined);
}
+ if (remoteAgentDeviceId && owner.accountKey && isMobileAuthOwnerCurrent(owner)) {
+ await AsyncStorage.setItem(remoteAgentStorageKey(owner.accountKey), JSON.stringify(next.remoteAgentByDevice)).catch(() => undefined);
+ }
+}
+
+function withRemoteAgentPick(
+ current: NewSessionStoredPreferences['remoteAgentByDevice'],
+ deviceId: string,
+ agentKind: NewSessionAgentKind,
+ pick: NewSessionRemoteAgentPick | null,
+): NewSessionStoredPreferences['remoteAgentByDevice'] {
+ const { [agentKind]: _previous, ...others } = current[deviceId] ?? {};
+ const byAgent = pick ? { ...others, [agentKind]: { ...pick, agentKind } } : others;
+ const { [deviceId]: _device, ...rest } = current;
+ return Object.keys(byAgent).length > 0 ? { ...rest, [deviceId]: byAgent } : rest;
}
export function clearNewSessionPreferences(): Promise<void> {
const owner = getMobileAuthOwner();
const next = writeChain.then(async () => {
await AsyncStorage.removeItem(STORAGE_KEY);
- if (owner.accountKey) await AsyncStorage.removeItem(workingDirStorageKey(owner.accountKey));
+ if (owner.accountKey) {
+ await AsyncStorage.removeItem(workingDirStorageKey(owner.accountKey));
+ await AsyncStorage.removeItem(remoteAgentStorageKey(owner.accountKey));
+ }
});
writeChain = next.catch(() => undefined);
return writeChain;
@@ -114,6 +152,7 @@ function emptyPreferences(): NewSessionStoredPreferences {
device: null,
permissionModeByAgent: {},
workingDirByDevice: {},
+ remoteAgentByDevice: {},
};
}
@@ -129,6 +168,33 @@ function normalizeWorkingDirByDevice(value: unknown): Record<string, string> {
return out;
}
+function normalizeRemoteAgentByDevice(value: unknown): NewSessionStoredPreferences['remoteAgentByDevice'] {
+ const record = readRecord(value);
+ if (!record) return {};
+ const out: NewSessionStoredPreferences['remoteAgentByDevice'] = {};
+ for (const [controlledDeviceId, byAgentValue] of Object.entries(record)) {
+ const byAgent = readRecord(byAgentValue);
+ if (!controlledDeviceId.trim() || !byAgent) continue;
+ const picks: Partial<Record<NewSessionAgentKind, NewSessionRemoteAgentPick>> = {};
+ for (const agentKind of ['claude-code', 'codex', 'pi'] as const) {
+ const pick = readRecord(byAgent[agentKind]);
+ const deviceId = readString(pick?.deviceId);
+ const model = readString(pick?.model);
+ if (!pick || !deviceId || !model) continue;
+ picks[agentKind] = {
+ deviceId,
+ agentKind,
+ model,
+ providerId: readString(pick.providerId),
+ effort: typeof pick.effort === 'string' ? pick.effort : '',
+ fastMode: pick.fastMode === true,
+ };
+ }
+ if (Object.keys(picks).length > 0) out[controlledDeviceId.trim()] = picks;
+ }
+ return out;
+}
+
// 'plan' 是计划模式的实现细节(老被控端兼容路径),不是用户可记忆的权限档。
function isRememberablePermissionMode(mode: string): boolean {
return mode.trim().length > 0 && mode !== 'plan';
@@ -162,6 +228,7 @@ function normalizeStoredPreferences(value: unknown): NewSessionStoredPreferences
: null,
permissionModeByAgent: normalizePermissionModeByAgent(record.permissionModeByAgent),
workingDirByDevice: {},
+ remoteAgentByDevice: {},
};
}
@@ -208,4 +275,5 @@ function readString(value: unknown): string | null {
export const __testing = {
storageKey: STORAGE_KEY,
workingDirStorageKey,
+ remoteAgentStorageKey,
};
diff --git a/apps/mobile/src/session/remoteAgentCatalogs.ts b/apps/mobile/src/session/remoteAgentCatalogs.ts
index 4a997f3384..1d6e847ba9 100644
--- a/apps/mobile/src/session/remoteAgentCatalogs.ts
+++ b/apps/mobile/src/session/remoteAgentCatalogs.ts
@@ -91,6 +91,8 @@ export function providerShareRemoteCatalogs(input: {
deviceId: share.agentDeviceId,
name: input.deviceName(share),
status: payload ? 'ready' : 'error',
+ // 已暂停 / 分享者电脑不在线的分享只因被选着才留在清单里:与留下的离线电脑一样标出,选不了。
+ ...(reachable ? {} : { offline: true as const }),
providers: payload
? remoteAgentProviders(payload.providers).filter((provider) => provider.id === share.providerId)
: [],
diff --git a/apps/mobile/src/session/useRemoteMobileFavorites.ts b/apps/mobile/src/session/useRemoteMobileFavorites.ts
index a1db363ec9..811f1671d5 100644
--- a/apps/mobile/src/session/useRemoteMobileFavorites.ts
+++ b/apps/mobile/src/session/useRemoteMobileFavorites.ts
@@ -13,8 +13,17 @@ import {
} from "@/device-link/DeviceLinkContext";
import { startFocusedTopicSubscription } from "@/device-link/focusedTopicSubscription";
import { useUnresponsiveDevices } from "@/device-link/unresponsiveDevicesStore";
+import { subscribeMobileAuthOwner } from "@/auth/authOwnerGeneration";
import type { MobileModelFavorite } from "./unifiedMobileModels";
+// 上次从那台电脑读到的收藏(账号 + 电脑):每次打开选择器先显示它,再在后台读最新的。
+// 只用于显示与起草改动;写入仍带 expected 交给那台电脑核对,旧快照改不坏真相。
+const lastFavorites = new Map<string, RemoteModelFavorite[]>();
+subscribeMobileAuthOwner(() => lastFavorites.clear());
+export function __resetRemoteMobileFavoritesCacheForTest(): void {
+ lastFavorites.clear();
+}
+
export function mobileFavorite(item: RemoteModelFavorite): MobileModelFavorite {
return {
...item,
@@ -61,7 +70,8 @@ export function mobileFavoriteMutation(
export function useRemoteMobileFavorites(scope: string, visible: boolean) {
const { invoke, connectionEpoch, status, subscribe, unsubscribe, recoveringDeviceIds } =
useDeviceLink();
- const deviceId = (JSON.parse(scope) as [string, string])[1];
+ const [accountId, deviceId] = JSON.parse(scope) as [string, string];
+ const cacheKey = JSON.stringify([accountId, deviceId]);
const unavailable = useUnresponsiveDevices().has(deviceId) || recoveringDeviceIds.has(deviceId);
const binding = JSON.stringify([scope, connectionEpoch, status, visible]);
const current = useRef(binding);
@@ -81,6 +91,7 @@ export function useRemoteMobileFavorites(scope: string, visible: boolean) {
await invoke(deviceId, MODEL_FAVORITES_GET, []),
);
if (valid() && seq.current === request) {
+ lastFavorites.set(cacheKey, items);
setState({ binding, items });
setError(null);
}
@@ -114,15 +125,17 @@ export function useRemoteMobileFavorites(scope: string, visible: boolean) {
++seq.current;
};
}, [binding, invoke, subscribe, unsubscribe, unavailable]);
- const items = state?.binding === binding ? state.items : [];
+ const cached = lastFavorites.get(cacheKey);
+ const loaded = state?.binding === binding || cached !== undefined;
+ const items = state?.binding === binding ? state.items : (cached ?? []);
return {
- ready: state?.binding === binding && status === "online" && !unavailable,
+ ready: loaded && status === "online" && !unavailable,
items: items.map(mobileFavorite),
error,
save: async (next: MobileModelFavorite[]) => {
const mutation = mobileFavoriteMutation(items, next);
if (!mutation) return;
- if (!valid() || state?.binding !== binding || status !== "online")
+ if (!valid() || !loaded || status !== "online")
throw new Error("Favorites not ready");
++seq.current;
try {
diff --git a/docs/product-rules/model-selector-unified.md b/docs/product-rules/model-selector-unified.md
index f3554b9848..78f4ac32ff 100644
--- a/docs/product-rules/model-selector-unified.md
+++ b/docs/product-rules/model-selector-unified.md
@@ -66,6 +66,8 @@
### 1.5 收藏 = 配置副本
- **远程收藏按被控电脑共享**:Desktop 与 Mobile 连接同一台电脑时读取和修改该电脑当前账号的既有收藏。各被控电脑独立,不将控制端的本机收藏套用或自动合并到远端。收藏以单条新增、条件编辑、条件删除同步,等持久化确认后反馈成功;并发修改同一副本时拒绝旧快照覆盖,重读后再编辑。断线、账号切换、旧版不支持时不得声称已同步;不自动重试写操作,也不影响会话和连接恢复。
+- **远程收藏先显示上次读到的**(2026-10-19):控制端按账号 + 被控电脑记住最近一次读到的收藏,选择器每次打开(含任务页、新建页重新进入)先显示它,同时在后台重读,有变化再替换;读取失败保留原显示。缓存只用于显示与发起修改,修改仍带旧值交给被控电脑核对,不会用旧快照覆盖。只存在内存里,切换账号即清空。
+- **Mobile 新建任务记住其他电脑 / 分享来的模型**(2026-10-19):在新建页选了同账号另一台电脑或分享来的模型后,按账号 + 被控电脑 + Agent 记住,下次打开新建页恢复;选回被控电脑自己的模型即清掉。恢复出来的选择若此刻用不了(被控电脑不再提供远程模型、那台离线或读不到、分享已暂停或分享者离线、模型已不在那份目录里),退回被控电脑的默认,记忆保留。Desktop 在不重启时沿用草稿里的选择,重启后不恢复,维持原设计。
- **其他电脑上的模型照样收藏**(2026-10-13):同账号另一台电脑开放了远程调用的模型,收藏、编辑、取消收藏与本机模型完全一样,用户不用关心模型在哪台电脑上运行。收藏仍存在被控电脑上,运行位置编进来源(`agent-device-favorite:["<电脑>","<供应商>"]`,见 `packages/device-link/src/modelFavorites.ts`),不另加字段——旧版解析会丢掉不认识的字段,把那台电脑的供应商当成被控电脑的同名供应商而派错地方;编进来源后旧版只把这条当作不认识的供应商藏起来。它与本机收藏排在同一个收藏区,说明行带电脑名以区分本机同名模型;选中即在那台电脑运行。同一模型在本机与那台电脑上的收藏互不匹配。那台电脑离线(包括只因任务的 Agent 在那台、靠缓存目录留在列表里)、关闭远程调用、供应商被收进供应商组,或那台电脑上已没有这个模型时先不显示,收藏本身保留;Desktop 在那台电脑仍在列表里、目录还在读取或读取失败时置灰显示,Mobile 等目录读到后再显示。Desktop 收藏区里这类条目不弹参数浮层,参数在那台电脑的视图里调;已建任务的 Agent 已在那台电脑上时,点它先切到那台电脑的视图,再点一次应用。Mobile 暂不支持收藏分享来的模型。
- **Desktop 收藏视图不随浏览来源切换**(2026-10-13):★ / 全部统一展示任务所在电脑收藏的本机、同账号远程与分享模型,保持收藏顺序;点任何供应商图标时,收藏区与模型区都只显示该连接的条目,同品牌不同电脑、不同分享互不混用。分享收藏沿用带分享与成员身份的既有存储键,仅在原授权可用且对应目录包含模型时解析;浏览分享时点 ★ 同样返回聚合收藏。远控任务的分享收藏也读写被控电脑,不能写入控制端收藏。侧栏仍为供应商图标,不增加设备标题;配置与选择交互沿用既有路径。实现及回归见 `UnifiedModelPanel.tsx`、`providerShareFavorites.ts` 与 `remoteAgentDeviceFavoritesPanel.test.tsx`。