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(mobile): 新建任务默认模型改读被控电脑的新建任务默认 (#5816)

Dash8fae70274146
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index 0a7a4b868e..aab0c6e1b5 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -211,6 +211,8 @@ import {
isNewSessionDraftMissingPayloadOnly,
parseNewSessionDeviceOptions,
pickAgentDefaultRuntime,
+ hostDraftRuntimeFromDefaults,
+ isHostDraftDefaultsReady,
pickInitialNewSessionWorkspace,
pickNewSessionDefaultDevice,
resolveNewSessionAutoDefault,
@@ -222,6 +224,7 @@ import {
resolveSubmitGuardCatalog,
validateNewSessionDraft,
type NewSessionAgentKind,
+ type NewSessionRuntime,
type NewSessionDraft,
type NewSessionDeviceOption,
type NewSessionRemoteAgentPick,
@@ -1052,7 +1055,7 @@ export default function NewRemoteSessionScreen() {
const [voiceDraftCaretFrame, setVoiceDraftCaretFrame] = useState({ left: 0, top: 0 });
const voiceDraftCaretRef = useRef<View>(null);
const voiceDraftMeasuredBlockRef = useRef<View>(null);
- // 自动默认运行配置(跟随最近会话 / 区域默认 / 列表最上面)的守卫:用户一旦手动选过模型,就不再自动覆盖;
+ // 自动默认运行配置(跟随被控电脑新建任务默认 / 区域默认 / 列表最上面)的守卫:用户一旦手动选过模型,就不再自动覆盖;
// 记录已自动应用过的设备,切设备时(未手动选过)按新设备重算。
const userTouchedRuntimeRef = useRef(false);
// 模型已按哪台电脑的真实数据落定(见 isNewSessionRuntimePending);切到别的电脑即重新等待,
@@ -1068,6 +1071,109 @@ export default function NewRemoteSessionScreen() {
// 持久草稿不会写入该 ref,因此已下架模型仍走 mobile 的首项降级。
const explicitProviderModelSelectionRef = useRef<string | null>(null);
const autoDefaultDeviceRef = useRef<string | null>(null);
+ // 被控电脑的「新建任务默认」(与桌面远程新建同一读源 maker:get-new-maker-defaults):
+ // 默认模型 = 那台电脑上新建任务时用户上次选的模型,不再从任务列表推断「最近使用」。
+ // 选中设备后一次读齐三个 agent,供自动默认 / 恢复上次 agent / 切 agent 同步取用。
+ // 旧被控端(CHANNEL_NOT_ALLOWED)或重试后仍失败都算读完,回落目录区域默认,不无限等待。
+ const [hostDraftDefaults, setHostDraftDefaults] = useState<{
+ deviceId: string;
+ byAgent: Partial<Record<NewSessionAgentKind, NewSessionRuntime | null>>;
+ } | null>(null);
+ const hostDraftDefaultsRef = useRef(hostDraftDefaults);
+ hostDraftDefaultsRef.current = hostDraftDefaults;
+ // 在途读取:切 agent 时等它读完再选模型,避免先落目录默认、又因已手动切换而再也补不回来。
+ const hostDraftDefaultsLoadRef = useRef<{ deviceId: string; promise: Promise<void> } | null>(null);
+ useEffect(() => {
+ if (!selectedDeviceId || deviceLinkStatus !== 'online') return undefined;
+ if (hostDraftDefaultsRef.current?.deviceId === selectedDeviceId) return undefined;
+ const deviceId = selectedDeviceId;
+ let cancelled = false;
+ const readAgent = async (agentKind: NewSessionAgentKind) => {
+ for (let attempt = 0; ; attempt += 1) {
+ const defaults = await withTransientRemoteRetry(async () => {
+ await openLink(deviceId);
+ return maker.getNewMakerDefaults(agentKind);
+ }, { maxAttempts: 2 }).catch(() => undefined);
+ if (cancelled) return null;
+ // 被控端刚启动、渲染进程还没推来草稿时回 {}:稍后重读,不把它当成「从未选过模型」;
+ // 有限次后(含不带该字段的旧被控端)按无默认处理。读取失败不重读。
+ if (defaults === undefined || isHostDraftDefaultsReady(defaults) || attempt >= 2) {
+ return hostDraftRuntimeFromDefaults(defaults, agentKind);
+ }
+ await new Promise<void>((resolve) => setTimeout(resolve, 1_500));
+ if (cancelled) return null;
+ }
+ };
+ const promise = Promise.all(
+ NEW_SESSION_AGENT_OPTIONS.map(async ({ kind }) => [kind, await readAgent(kind)] as const),
+ ).then((entries) => {
+ if (cancelled) return;
+ const next = { deviceId, byAgent: Object.fromEntries(entries) };
+ // 同步更新镜像:等待中的切 agent 回调在下一次渲染前就要读到结果。
+ hostDraftDefaultsRef.current = next;
+ setHostDraftDefaults(next);
+ });
+ hostDraftDefaultsLoadRef.current = { deviceId, promise };
+ return () => {
+ cancelled = true;
+ };
+ }, [deviceLinkStatus, maker, openLink, selectedDeviceId]);
+ // 等该设备的被控电脑默认读完(读完、失败都算);没有在途读取(离线 / 未选设备)时不等,
+ // 按目录默认继续。effect 重跑会换一份新的在途读取,跟着等新的那份(有限次)。
+ const waitHostDraftDefaults = useCallback(async (deviceId: string) => {
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ if (hostDraftDefaultsRef.current?.deviceId === deviceId) return;
+ const load = hostDraftDefaultsLoadRef.current;
+ if (!load || load.deviceId !== deviceId) return;
+ await load.promise;
+ }
+ }, []);
+ const hostDefaultsSettled = !!selectedDeviceId && hostDraftDefaults?.deviceId === selectedDeviceId;
+ // 本页已写回被控电脑的选择(按设备、agent):优先于读取结果,避免选择前发出的读取
+ // 晚到后把旧模型带回来(切到别的 agent 再切回时)。
+ const hostChoiceOverridesRef = useRef(new Map<string, Partial<Record<NewSessionAgentKind, NewSessionRuntime>>>());
+ const hostRuntimeFor = useCallback(
+ (agentKind: NewSessionAgentKind): NewSessionRuntime | null => {
+ const deviceId = selectedDeviceRef.current;
+ const chosen = hostChoiceOverridesRef.current.get(deviceId)?.[agentKind];
+ if (chosen) return chosen;
+ const current = hostDraftDefaultsRef.current;
+ return current && current.deviceId === deviceId
+ ? current.byAgent[agentKind] ?? null
+ : null;
+ },
+ [],
+ );
+ // 在新建任务页选的模型 / 档位写回被控电脑的新建任务默认(与桌面远程新建同一写法
+ // maker:apply-new-maker-draft-pref active=true),下次在这台电脑上新建任务——不论手机、
+ // 桌面还是远程桌面——默认都是它。由选择入口发请求,本 effect 在草稿提交后读最终值写出;
+ // 写失败不打扰,本页草稿照常生效。远程 Agent(模型属于另一台电脑)不写回被控电脑。
+ const [hostChoiceRequest, setHostChoiceRequest] = useState<{ seq: number; markModelChoice: boolean } | null>(null);
+ const hostChoiceSentSeqRef = useRef(0);
+ const requestHostChoiceWrite = useCallback((markModelChoice: boolean) => {
+ setHostChoiceRequest((current) => ({ seq: (current?.seq ?? 0) + 1, markModelChoice }));
+ }, []);
+ useEffect(() => {
+ if (!hostChoiceRequest || hostChoiceRequest.seq === hostChoiceSentSeqRef.current) return;
+ hostChoiceSentSeqRef.current = hostChoiceRequest.seq;
+ if (!selectedDeviceId || remoteAgentChoice || !draft.model) return;
+ const { agentKind, model, providerId, effort, fastMode } = draft;
+ void maker.applyNewMakerDraftPref({
+ agent: agentKind,
+ providerId: providerId ?? '',
+ modelId: model,
+ active: true,
+ markModelChoice: hostChoiceRequest.markModelChoice,
+ ...(effort ? { effort } : {}),
+ fast: fastMode,
+ }).catch(() => undefined);
+ // 记下本页选择:切到别的 agent 再切回时取到它,不被在途或更早的读取结果覆盖。
+ const overrides = hostChoiceOverridesRef.current;
+ overrides.set(selectedDeviceId, {
+ ...overrides.get(selectedDeviceId),
+ [agentKind]: { agentKind, model, effort, providerId },
+ });
+ }, [draft, hostChoiceRequest, maker, remoteAgentChoice, selectedDeviceId]);
// selectedDeviceId 的渲染期镜像:异步回调(权限确认 .then)提交前比对触发时捕获的设备,
// 不一致即放弃写入 —— 防止确认弹窗期间用户切了设备,回调把旧设备的来源/配置写进草稿
// (Greptile review P1:异步切换写入旧设备来源)。
@@ -1296,14 +1402,14 @@ export default function NewRemoteSessionScreen() {
expectedDeviceId: preferredDefaultDevice?.deviceId ?? '',
selectedDeviceId,
})) return;
- // agent 偏好一到就恢复;模型要等目录或该 agent 的最近任务,否则选不出模型。
+ // agent 偏好一到就恢复;模型要等被控电脑的新建任务默认与目录,否则选不出模型。
const step = nextStoredAgentRestoreStep({
storedAgentKind,
restored,
modelReady: canResolveStoredAgentRuntime({
- agentKind: storedAgentKind,
- sessions,
deviceId: selectedDeviceId,
+ hostDefaultsSettled,
+ hostRuntime: hostRuntimeFor(storedAgentKind),
catalogReady: deviceProviders.ready,
providersUnsupported: deviceProviders.unsupported,
}),
@@ -1324,8 +1430,7 @@ export default function NewRemoteSessionScreen() {
);
const next = pickAgentDefaultRuntime({
agentKind: storedAgentKind,
- sessions,
- deviceId: selectedDeviceId || undefined,
+ hostRuntime: hostRuntimeFor(storedAgentKind),
modelRows: rowsNow,
currentEffort,
catalogReady: catalogReadyRef.current,
@@ -1401,12 +1506,14 @@ export default function NewRemoteSessionScreen() {
deviceProviders.unsupported,
deviceProviders.providers,
deviceProviders.modelVisibilityOverrides,
+ hostDefaultsSettled,
+ hostDraftDefaults,
+ hostRuntimeFor,
newSessionPreferences,
newSessionPreferences?.agentKind,
newSessionPreferencesLoaded,
preferredDefaultDevice?.deviceId,
selectedDeviceId,
- sessions,
]);
// 权限记忆恢复:偏好加载后按当前 agent 恢复上次选过的档(一次;对齐桌面 lastByVendor)。
@@ -1431,19 +1538,19 @@ export default function NewRemoteSessionScreen() {
};
}, [draft.agentKind, draft.permissionMode, newSessionPreferences, newSessionPreferencesLoaded]);
- // 新建任务默认运行配置 = 跟随最近一次会话(整套 agent+model+effort,按所选设备 scope);没有最近会话则
- // 优先区域默认、再用模型列表最上面那个。一旦用户手动选过模型即不再覆盖;切设备(未手动选过)按新设备重算。
+ // 新建任务默认运行配置 = 被控电脑记住的当前 agent 新建任务默认(model+effort+来源,与桌面远程新建同源);
+ // 没有则优先区域默认、再用模型列表最上面那个。一旦用户手动选过模型即不再覆盖;切设备(未手动选过)按新设备重算。
// 决策逻辑全在纯函数 resolveNewSessionAutoDefault 里(便于单测);此 effect 只负责"调纯函数 → setDraft + 更新 ref"。
- // 最近会话路径同步可得(sessions 在内存);列表最上面依赖 providers 异步,故 modelRows 就绪后此 effect 再触发。
+ // 被控电脑默认与 providers 都是异步到达,任一就绪后此 effect 再触发。
useEffect(() => {
if (!newSessionPreferencesLoaded) return;
const result = resolveNewSessionAutoDefault({
userTouched: userTouchedRuntimeRef.current,
appliedDeviceId: autoDefaultDeviceRef.current,
selectedDeviceId,
- sessions,
+ hostDefaultsSettled,
+ hostRuntime: hostRuntimeFor(draft.agentKind),
modelRows,
- // modelRows 按当前 draft.agentKind 构建;最近会话若是另一个 agent,纯函数内不做来源校验。
rowsAgentKind: draft.agentKind,
catalogReady: deviceProviders.ready,
visibilityOverrides: deviceProviders.modelVisibilityOverrides,
@@ -1472,7 +1579,7 @@ export default function NewRemoteSessionScreen() {
}).then((confirmed) => {
if (cancelled || userTouchedRuntimeRef.current) return;
applied = true;
- settleRuntime(result.patch.agentKind ? 'recent-task' : 'catalog-default', result.appliedDeviceId);
+ settleRuntime(result.source, result.appliedDeviceId);
setDraft((current) => {
// 自动默认重算(设备切换/最近会话变化)改了 (agent, model, providerId) 组合 →
// fastMode 按新组合重验(Codex review P2):A 设备记忆恢复的 fastMode:true 不得
@@ -1505,7 +1612,7 @@ export default function NewRemoteSessionScreen() {
autoDefaultDeviceRef.current = previousAutoDefaultDevice;
}
};
- }, [capabilities?.availableModels, deviceProviders.loading, draft.effort, draft.permissionMode, draft.agentKind, modelRows, deviceProviders.ready, deviceProviders.modelVisibilityOverrides, deviceProviders.unsupported, modelSections.connected.length, newSessionPreferences, newSessionPreferencesLoaded, selectedDeviceId, sessions]);
+ }, [capabilities?.availableModels, deviceProviders.loading, draft.effort, draft.permissionMode, draft.agentKind, modelRows, deviceProviders.ready, deviceProviders.modelVisibilityOverrides, deviceProviders.unsupported, modelSections.connected.length, newSessionPreferences, newSessionPreferencesLoaded, selectedDeviceId, hostDefaultsSettled, hostDraftDefaults, hostRuntimeFor]);
// 目录就绪后的来源终检(codex review P1):自动默认/恢复在目录加载期信任的来源可能已失效
// (provider 被删/断开/模型下架),就绪后必须复核——联合回退整对 (model, providerId)
@@ -2762,8 +2869,9 @@ export default function NewRemoteSessionScreen() {
fastMode: next.fastMode,
};
});
+ requestHostChoiceWrite(true);
setModelSheetOpen(false);
- }, [capabilities, draftMemory]);
+ }, [capabilities, draftMemory, requestHostChoiceWrite]);
// source.deviceId 非空 = 选的是另一台电脑(或分享来的)目录里的行:Agent 在那里运行。
const selectUnifiedModel = useCallback(async (
@@ -2798,10 +2906,11 @@ export default function NewRemoteSessionScreen() {
setRemoteAgentChoice(null);
setDraft(current => ({ ...current, agentKind: config.agent, model: config.modelId,
providerId: config.providerId, effort: config.effort, fastMode, permissionMode: permission }));
+ requestHostChoiceWrite(true);
}
void saveNewSessionPreferences({ agentKind: config.agent });
return true;
- }, [creating, selectedDeviceId, maker, newSessionPreferences, draft.agentKind, draft.permissionMode]);
+ }, [creating, selectedDeviceId, maker, newSessionPreferences, draft.agentKind, draft.permissionMode, requestHostChoiceWrite]);
// 扁平回退(被控端 0 供应商):只落 model、清来源(默认路由),effort 跟随 capabilities reconcile。
const selectFlatModel = useCallback((option: MobileModelOption) => {
@@ -2811,8 +2920,9 @@ export default function NewRemoteSessionScreen() {
explicitProviderModelSelectionRef.current = null;
setDraft((current) =>
reconcileRuntimeDraftWithCapabilities({ ...current, model: option.id, providerId: null }, capabilities));
+ requestHostChoiceWrite(true);
setModelSheetOpen(false);
- }, [capabilities]);
+ }, [capabilities, requestHostChoiceWrite]);
// 选中行的 effort/fast 变更:落 draft(live 真相)+ 写草稿记忆(下次选回恢复)。
// 记忆槽的来源 id:显式选中的来源,未显式选时用当前高亮的默认来源(activeSourceIdRef)。
@@ -2823,7 +2933,8 @@ export default function NewRemoteSessionScreen() {
if (effort && pid) draftMemory.setEffort(current.agentKind, pid, current.model, effort);
return { ...current, effort };
});
- }, [draftMemory]);
+ requestHostChoiceWrite(false);
+ }, [draftMemory, requestHostChoiceWrite]);
const changeSelectedFastMode = useCallback((enabled: boolean) => {
userTouchedRuntimeRef.current = true;
setDraft((current) => {
@@ -2831,7 +2942,8 @@ export default function NewRemoteSessionScreen() {
if (pid) draftMemory.setFast(current.agentKind, pid, current.model, enabled);
return { ...current, fastMode: enabled };
});
- }, [draftMemory]);
+ requestHostChoiceWrite(false);
+ }, [draftMemory, requestHostChoiceWrite]);
const toggleModelPicker = useCallback(() => {
setWorkspacePickerOpen(false);
@@ -4235,8 +4347,8 @@ export default function NewRemoteSessionScreen() {
</VoicePillWidthFrame>
);
- // 切 agent:跟随该 agent 的最近会话 → 否则该 agent 列表最上面 → 否则留空由用户选(见 pickAgentDefaultRuntime),
- // 同时 reconcile effort、来源跟随 model 同源(最近会话来源校验后继承 / 首项行 provider / 兜底 null)。
+ // 切 agent:跟随被控电脑该 agent 的新建任务默认 → 否则该 agent 列表最上面 → 否则留空由用户选(见 pickAgentDefaultRuntime),
+ // 同时 reconcile effort、来源跟随 model 同源(被控电脑默认来源校验后继承 / 首项行 provider / 兜底 null)。
// 手动切 agent = 手动选运行配置 → 之后自动默认不再覆盖。
const switchAgent = useCallback((nextKind: NewSessionAgentKind) => {
setAgentPickerOpen(false);
@@ -4251,7 +4363,9 @@ export default function NewRemoteSessionScreen() {
defaultPermissionModeForNewSessionAgent(nextKind);
void confirmFullAccessChange(draft.permissionMode, nextPermissionMode, {
restoringRememberedChoice: storedPermissionMode !== undefined,
- }).then((confirmed) => {
+ }).then(async (confirmed) => {
+ // 被控电脑默认还在读:等读完再选模型(切换已标记手动,之后自动默认不会再补)。
+ await waitHostDraftDefaults(selectedDeviceId);
// 确认期间设备已切换 → 放弃本次写入,新设备自己的 effect 会接管(Greptile P1)。
if (selectedDeviceId !== selectedDeviceRef.current) return;
// 确认期间用户又切了 agent / 手动选了模型 → 旧回调不得覆盖新选择(Greptile P1)。
@@ -4268,8 +4382,7 @@ export default function NewRemoteSessionScreen() {
);
const next = pickAgentDefaultRuntime({
agentKind: nextKind,
- sessions,
- deviceId: selectedDeviceId || undefined,
+ hostRuntime: hostRuntimeFor(nextKind),
modelRows: rowsNow,
currentEffort: current.effort,
catalogReady: catalogReadyRef.current,
@@ -4296,7 +4409,7 @@ export default function NewRemoteSessionScreen() {
};
});
});
- }, [draft.agentKind, draft.permissionMode, deviceProviders.providers, deviceProviders.modelVisibilityOverrides, newSessionPreferences, sessions, selectedDeviceId]);
+ }, [draft.agentKind, draft.permissionMode, deviceProviders.providers, deviceProviders.modelVisibilityOverrides, hostRuntimeFor, newSessionPreferences, selectedDeviceId, waitHostDraftDefaults]);
// 选中的 agent 在被控端未注册(如 Pi 二进制缺失)时,coerce 到首个可用来源,避免用户停在
// 被隐藏的选项、并防止创建出注定 requireAgent 报错的会话。仅在已拉到可用集后收敛一次。
diff --git a/apps/mobile/src/__tests__/deviceProvidersReadiness.test.tsx b/apps/mobile/src/__tests__/deviceProvidersReadiness.test.tsx
index ffbb02dd3a..ccca6467b5 100644
--- a/apps/mobile/src/__tests__/deviceProvidersReadiness.test.tsx
+++ b/apps/mobile/src/__tests__/deviceProvidersReadiness.test.tsx
@@ -105,7 +105,7 @@ describe('mobile provider visibility readiness', () => {
expect(state.error).toContain('[MODEL_VISIBILITY_NOT_READY]');
expect(allowsFlatFallback()).toBe(false);
expect(resolveNewSessionAutoDefault({
- userTouched: false, appliedDeviceId: null, selectedDeviceId: 'host', sessions: [],
+ userTouched: false, appliedDeviceId: null, selectedDeviceId: 'host', hostDefaultsSettled: true, hostRuntime: null,
modelRows: [], rowsAgentKind: 'codex', catalogReady: state.ready,
providersUnsupported: state.unsupported, currentEffort: 'medium',
availableModels: [{ id: 'hidden', label: 'Hidden', efforts: ['medium'],
diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.ts
index 4c7f459acb..d26abf4e60 100644
--- a/apps/mobile/src/__tests__/newSession.test.ts
+++ b/apps/mobile/src/__tests__/newSession.test.ts
@@ -14,6 +14,7 @@ import {
isStoredAgentRestorePending,
nextStoredAgentRestoreStep,
type StoredAgentRestoreState,
+ type NewSessionRuntime,
buildNewSessionCreatePreview,
buildRecentWorkspaceOptions,
applyRemoteAgentPick,
@@ -28,7 +29,8 @@ import {
parseExtraDirsInput,
pickAgentDefaultRuntime,
pickInitialNewSessionWorkspace,
- pickMostRecentSessionRuntime,
+ hostDraftRuntimeFromDefaults,
+ isHostDraftDefaultsReady,
pickNewSessionDefaultDevice,
resolveNewSessionAutoDefault,
resolveRecentModelAndProvider,
@@ -104,63 +106,46 @@ const deferred = <T,>() => {
return { promise, resolve, reject };
};
-describe('pickMostRecentSessionRuntime', () => {
- it('picks the most recent session runtime (agent+model+effort), cc → claude-code', () => {
- const runtime = pickMostRecentSessionRuntime([
- remoteSession('old', { model: 'claude-opus-4-8', effort: 'high', userSendAt: '2026-01-01T00:00:01.000Z' }),
- remoteSession('new', { model: 'gpt-5.4', effort: 'low', agentKind: 'codex', userSendAt: '2026-01-02T00:00:00.000Z' }),
- ]);
- expect(runtime).toEqual({ agentKind: 'codex', model: 'gpt-5.4', effort: 'low', providerId: null });
- });
-
- it('carries the recent session providerId (null = default route when unset)', () => {
- const runtime = pickMostRecentSessionRuntime([
- remoteSession('bound', { model: 'deepseek-v4-flash', providerId: 'deepseek', userSendAt: '2026-01-02T00:00:00.000Z' }),
- remoteSession('unbound', { model: 'gpt-5.4', agentKind: 'codex', userSendAt: '2026-01-01T00:00:00.000Z' }),
- ]);
- expect(runtime).toEqual({ agentKind: 'claude-code', model: 'deepseek-v4-flash', effort: 'medium', providerId: 'deepseek' });
- });
-
- it('maps cc agentKind to claude-code', () => {
- const runtime = pickMostRecentSessionRuntime([remoteSession('a', { agentKind: 'cc', model: 'claude-sonnet-4-6' })]);
- expect(runtime?.agentKind).toBe('claude-code');
- });
-
- it('sorts by activity time = userSendAt ?? updatedAt ?? createdAt (desc)', () => {
- const runtime = pickMostRecentSessionRuntime([
- remoteSession('viaUpdated', { model: 'm-updated', userSendAt: null, updatedAt: '2026-01-03T00:00:00.000Z' }),
- remoteSession('viaSend', { model: 'm-send', userSendAt: '2026-01-02T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z' }),
- ]);
- expect(runtime?.model).toBe('m-updated'); // updatedAt 2026-01-03 > userSendAt 2026-01-02
- });
+function hostRuntime(
+ agentKind: NewSessionRuntime['agentKind'],
+ model: string,
+ patch: Partial<Omit<NewSessionRuntime, 'agentKind' | 'model'>> = {},
+): NewSessionRuntime {
+ return { agentKind, model, effort: 'medium', providerId: null, ...patch };
+}
- it('excludes deleted sessions and sessions without a model', () => {
- expect(pickMostRecentSessionRuntime([
- remoteSession('del', { status: 'deleted', model: 'x', userSendAt: '2026-09-09T00:00:00.000Z' }),
- remoteSession('nomodel', { model: ' ', userSendAt: '2026-09-09T00:00:00.000Z' }),
- remoteSession('ok', { model: 'kept', userSendAt: '2026-01-01T00:00:00.000Z' }),
- ])?.model).toBe('kept');
+describe('hostDraftRuntimeFromDefaults', () => {
+ it('reads the host new-task default (model + effort + source) for the agent', () => {
+ expect(hostDraftRuntimeFromDefaults(
+ { model: 'claude-opus-5-5', effort: 'high', providerId: 'anthropic', modelChosenByUser: true, worktreeEnabled: false },
+ 'claude-code',
+ )).toEqual({ agentKind: 'claude-code', model: 'claude-opus-5-5', effort: 'high', providerId: 'anthropic' });
+ // providerId 缺省 / 空串 = 跟随被控端默认来源;旧端不回 modelChosenByUser 时保守采用其 model。
+ expect(hostDraftRuntimeFromDefaults({ model: 'gpt-6-astra', providerId: '' }, 'codex'))
+ .toEqual({ agentKind: 'codex', model: 'gpt-6-astra', effort: '', providerId: null });
});
- it('filters by deviceId (only sessions on the target device; sessions without deviceId are not excluded)', () => {
- const sessions = [
- remoteSession('other', { model: 'other-dev', deviceLinkDeviceId: 'devB', userSendAt: '2026-05-05T00:00:00.000Z' }),
- remoteSession('target', { model: 'target-dev', deviceLinkDeviceId: 'devA', userSendAt: '2026-01-01T00:00:00.000Z' }),
- ];
- expect(pickMostRecentSessionRuntime(sessions, { deviceId: 'devA' })?.model).toBe('target-dev');
+ it('returns null for old hosts, malformed payloads and empty drafts', () => {
+ expect(hostDraftRuntimeFromDefaults({}, 'claude-code')).toBeNull();
+ expect(hostDraftRuntimeFromDefaults({ worktreeEnabled: true }, 'claude-code')).toBeNull();
+ expect(hostDraftRuntimeFromDefaults(null, 'claude-code')).toBeNull();
+ expect(hostDraftRuntimeFromDefaults('claude-opus-5-5', 'claude-code')).toBeNull();
+ expect(hostDraftRuntimeFromDefaults({ model: ' ' }, 'claude-code')).toBeNull();
});
- it('filters by agentKind', () => {
- const sessions = [
- remoteSession('cc1', { model: 'claude-x', agentKind: 'cc', userSendAt: '2026-05-05T00:00:00.000Z' }),
- remoteSession('codex1', { model: 'gpt-x', agentKind: 'codex', userSendAt: '2026-01-01T00:00:00.000Z' }),
- ];
- expect(pickMostRecentSessionRuntime(sessions, { agentKind: 'codex' })?.model).toBe('gpt-x');
+ it('treats a snapshot without worktreeEnabled as not ready yet (host renderer cache not pushed)', () => {
+ expect(isHostDraftDefaultsReady({})).toBe(false);
+ expect(isHostDraftDefaultsReady({ providerModelMemory: {} })).toBe(false);
+ expect(isHostDraftDefaultsReady(null)).toBe(false);
+ expect(isHostDraftDefaultsReady({ worktreeEnabled: false })).toBe(true);
+ expect(isHostDraftDefaultsReady({ worktreeEnabled: true, model: 'm' })).toBe(true);
});
- it('returns null when no session matches', () => {
- expect(pickMostRecentSessionRuntime([])).toBeNull();
- expect(pickMostRecentSessionRuntime([remoteSession('del', { status: 'deleted' })])).toBeNull();
+ it('leaves a never-chosen host seed to the catalog regional default, like the desktop controller', () => {
+ expect(hostDraftRuntimeFromDefaults({ model: 'seed', modelChosenByUser: false, providerId: null }, 'pi')).toBeNull();
+ // 选过来源即视为明确选择。
+ expect(hostDraftRuntimeFromDefaults({ model: 'seed', modelChosenByUser: false, providerId: 'xd' }, 'pi'))
+ .toEqual({ agentKind: 'pi', model: 'seed', effort: '', providerId: 'xd' });
});
});
@@ -332,61 +317,49 @@ describe('resolveSubmitGuardCatalog —— 提交终检目录取信(代际安全
});
describe('stored agent restore gating', () => {
- const recentOpus = remoteSession('recent', {
- deviceLinkDeviceId: 'mac',
- model: 'claude-opus-5-5',
- effort: 'high',
+ it('waits for the host new-task defaults before resolving a model', () => {
+ // 被控电脑的默认还没读完:即使目录已就绪也不落定,否则会先落目录默认、读到的默认再也用不上。
+ expect(canResolveStoredAgentRuntime({
+ deviceId: 'mac',
+ hostDefaultsSettled: false,
+ hostRuntime: null,
+ catalogReady: true,
+ providersUnsupported: false,
+ })).toBe(false);
});
- it('waits while neither the catalog nor a recent task for the agent is available', () => {
- // 冷启动:目录未就绪、任务列表还没到 —— 此刻恢复只能落到内置 Sonnet 4.6。
+ it('waits while neither the catalog nor a host default for the agent is available', () => {
expect(canResolveStoredAgentRuntime({
- agentKind: 'claude-code',
- sessions: [],
deviceId: 'mac',
+ hostDefaultsSettled: true,
+ hostRuntime: null,
catalogReady: false,
providersUnsupported: false,
})).toBe(false);
expect(pickAgentDefaultRuntime({
agentKind: 'claude-code',
- sessions: [],
+ hostRuntime: null,
modelRows: [],
currentEffort: 'medium',
- deviceId: 'mac',
catalogReady: false,
})).toMatchObject({ model: '', effort: 'medium' });
});
- it('proceeds once a recent task of the stored agent exists on the device', () => {
+ it('proceeds once the host gives a default for the agent', () => {
expect(canResolveStoredAgentRuntime({
- agentKind: 'claude-code',
- sessions: [recentOpus],
deviceId: 'mac',
+ hostDefaultsSettled: true,
+ hostRuntime: hostRuntime('claude-code', 'claude-opus-5-5', { effort: 'high' }),
catalogReady: false,
providersUnsupported: false,
})).toBe(true);
- // 其他设备或其他 agent 的任务不算。
- expect(canResolveStoredAgentRuntime({
- agentKind: 'codex',
- sessions: [recentOpus],
- deviceId: 'mac',
- catalogReady: false,
- providersUnsupported: false,
- })).toBe(false);
- expect(canResolveStoredAgentRuntime({
- agentKind: 'claude-code',
- sessions: [recentOpus],
- deviceId: 'studio',
- catalogReady: false,
- providersUnsupported: false,
- })).toBe(false);
});
it('proceeds once the catalog is ready or explicitly unsupported, or without a device', () => {
- const base = { agentKind: 'claude-code' as const, sessions: [], deviceId: 'mac' };
+ const base = { deviceId: 'mac', hostDefaultsSettled: true, hostRuntime: null };
expect(canResolveStoredAgentRuntime({ ...base, catalogReady: true, providersUnsupported: false })).toBe(true);
expect(canResolveStoredAgentRuntime({ ...base, catalogReady: false, providersUnsupported: true })).toBe(true);
- expect(canResolveStoredAgentRuntime({ ...base, deviceId: '', catalogReady: false, providersUnsupported: false })).toBe(true);
+ expect(canResolveStoredAgentRuntime({ ...base, deviceId: '', hostDefaultsSettled: false, catalogReady: false, providersUnsupported: false })).toBe(true);
});
it('reports a pending restore only for an unapplied stored agent on the target device', () => {
@@ -448,9 +421,38 @@ describe('stored agent restore gating', () => {
expect(modelStep).not.toContain('permissionMode');
expect(modelStep).toContain('current.agentKind === storedAgentKind');
expect(storedSource).not.toContain('deviceProviders.loading');
- // 恢复待落定时不阻断「跟随最近任务」(Greptile P1)。
+ // 恢复待落定时不阻断自动默认(Greptile P1)。
expect(autoGuardSource).not.toContain('isStoredAgentRestorePending(');
});
+
+ it('reads and writes the host new-task defaults instead of inferring from task history', () => {
+ const source = readTextLf(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');
+ // 读:与桌面远程新建同一读源,三个 agent 一次读齐。
+ expect(source).toContain('return maker.getNewMakerDefaults(agentKind);');
+ expect(source).toContain('return hostDraftRuntimeFromDefaults(defaults, agentKind);');
+ // 写:本页的模型选择写回被控电脑;远程 Agent 的模型属于另一台电脑,不写回。
+ expect(source).toMatch(/active: true,\s+markModelChoice: hostChoiceRequest\.markModelChoice,/);
+ expect(source).toContain('if (!selectedDeviceId || remoteAgentChoice || !draft.model) return;');
+ expect(source).not.toContain('pickMostRecentSessionRuntime');
+ // 三个本机选择入口(供应商行 / 统一面板 / 旧端扁平列表)都写回。
+ for (const name of ['selectProviderModelRow', 'selectUnifiedModel', 'selectFlatModel']) {
+ const start = source.indexOf(`const ${name} = useCallback(`);
+ const body = source.slice(start, source.indexOf('\n }, [', start));
+ expect(body, name).toContain('requestHostChoiceWrite(true);');
+ }
+ // 被控端刚启动回 {} 时有限次重读,不当成「从未选过模型」(Codex P1)。
+ expect(source).toContain('if (defaults === undefined || isHostDraftDefaultsReady(defaults) || attempt >= 2) {');
+ // 本页写回的选择优先于读取结果,晚到的旧读取不能把它覆盖(Codex P1)。
+ const runtimeForStart = source.indexOf('const hostRuntimeFor = useCallback(');
+ const runtimeForBody = source.slice(runtimeForStart, source.indexOf('\n );', runtimeForStart));
+ expect(runtimeForBody.indexOf('hostChoiceOverridesRef.current.get(deviceId)')).toBeLessThan(runtimeForBody.indexOf('current.byAgent[agentKind]'));
+ // 切 agent 先等被控电脑默认读完再选模型,不把目录默认当成最终选择(Greptile P1)。
+ const switchStart = source.indexOf('const switchAgent = useCallback(');
+ const switchBody = source.slice(switchStart, source.indexOf('\n }, [', switchStart));
+ const waitAt = switchBody.indexOf('await waitHostDraftDefaults(selectedDeviceId);');
+ expect(waitAt).toBeGreaterThan(-1);
+ expect(waitAt).toBeLessThan(switchBody.indexOf('pickAgentDefaultRuntime({'));
+ });
});
describe('pickAgentDefaultRuntime on hosts without provider:list', () => {
@@ -460,7 +462,7 @@ describe('pickAgentDefaultRuntime on hosts without provider:list', () => {
} as MobileModelOption);
it('uses the advertised capabilities model instead of settling an empty one', () => {
- const base = { agentKind: 'claude-code' as const, sessions: [], modelRows: [], currentEffort: 'medium', catalogReady: false };
+ const base = { agentKind: 'claude-code' as const, hostRuntime: null, modelRows: [], currentEffort: 'medium', catalogReady: false };
expect(pickAgentDefaultRuntime({ ...base, flatModels: [flat('a', false), flat('b', true)] }))
.toMatchObject({ model: 'b', providerId: null, effort: 'high' });
expect(pickAgentDefaultRuntime({ ...base, flatModels: [flat('a', false)] })).toMatchObject({ model: 'a', providerId: null });
@@ -552,13 +554,10 @@ describe('isNewSessionRuntimePending', () => {
});
describe('pickAgentDefaultRuntime', () => {
- it('follows the target agent\'s most recent session model + effort (reconciled)', () => {
+ it('follows the host new-task default of the target agent (model + effort reconciled)', () => {
const runtime = pickAgentDefaultRuntime({
agentKind: 'codex',
- sessions: [
- remoteSession('cc', { agentKind: 'cc', model: 'claude-opus-4-8', userSendAt: '2026-02-02T00:00:00.000Z' }),
- remoteSession('cx', { agentKind: 'codex', model: 'gpt-5.4', effort: 'high', userSendAt: '2026-01-01T00:00:00.000Z' }),
- ],
+ hostRuntime: hostRuntime('codex', 'gpt-5.4', { effort: 'high' }),
modelRows: [modelRow('gpt-5.4', ['low', 'medium', 'high'], 'medium')],
currentEffort: 'medium',
catalogReady: true,
@@ -570,7 +569,7 @@ describe('pickAgentDefaultRuntime', () => {
it('reconciles the recent effort down to the model default when unsupported', () => {
const runtime = pickAgentDefaultRuntime({
agentKind: 'codex',
- sessions: [remoteSession('cx', { agentKind: 'codex', model: 'gpt-5.4', effort: 'xhigh', userSendAt: '2026-01-01T00:00:00.000Z' })],
+ hostRuntime: hostRuntime('codex', 'gpt-5.4', { effort: 'xhigh' }),
modelRows: [modelRow('gpt-5.4', ['low', 'medium'], 'low')],
currentEffort: 'medium',
catalogReady: true,
@@ -582,7 +581,7 @@ describe('pickAgentDefaultRuntime', () => {
it('omits the effort when the catalog is ready but the model has no row (delisted → omit, codex P2)', () => {
const runtime = pickAgentDefaultRuntime({
agentKind: 'codex',
- sessions: [remoteSession('cx', { agentKind: 'codex', model: 'gpt-legacy', effort: 'high', userSendAt: '2026-01-01T00:00:00.000Z' })],
+ hostRuntime: hostRuntime('codex', 'gpt-legacy', { effort: 'high' }),
modelRows: [modelRow('gpt-5.4', ['low', 'medium'], 'low')],
currentEffort: 'medium',
catalogReady: true,
@@ -594,7 +593,7 @@ describe('pickAgentDefaultRuntime', () => {
it('keeps the recent effort while the catalog is not ready (no authoritative section model yet)', () => {
const runtime = pickAgentDefaultRuntime({
agentKind: 'codex',
- sessions: [remoteSession('cx', { agentKind: 'codex', model: 'gpt-legacy', effort: 'high', userSendAt: '2026-01-01T00:00:00.000Z' })],
+ hostRuntime: hostRuntime('codex', 'gpt-legacy', { effort: 'high' }),
modelRows: [],
currentEffort: 'medium',
catalogReady: false,
@@ -606,7 +605,7 @@ describe('pickAgentDefaultRuntime', () => {
it('inherits the recent session providerId when that provider still offers the model (#1898)', () => {
const runtime = pickAgentDefaultRuntime({
agentKind: 'claude-code',
- sessions: [remoteSession('ds', { agentKind: 'cc', model: 'deepseek-v4-flash', providerId: 'prov-deepseek-v4-flash', userSendAt: '2026-01-01T00:00:00.000Z' })],
+ hostRuntime: hostRuntime('claude-code', 'deepseek-v4-flash', { providerId: 'prov-deepseek-v4-flash' }),
modelRows: [modelRow('deepseek-v4-flash', ['low', 'medium'], 'medium')],
currentEffort: 'medium',
catalogReady: true,
@@ -617,7 +616,7 @@ describe('pickAgentDefaultRuntime', () => {
it('reroutes to another connected provider offering the same model when the recent provider is gone (codex P1)', () => {
const runtime = pickAgentDefaultRuntime({
agentKind: 'claude-code',
- sessions: [remoteSession('ds', { agentKind: 'cc', model: 'deepseek-v4-flash', providerId: 'prov-deleted', userSendAt: '2026-01-01T00:00:00.000Z' })],
+ hostRuntime: hostRuntime('claude-code', 'deepseek-v4-flash', { providerId: 'prov-deleted' }),
modelRows: [modelRow('deepseek-v4-flash', ['low', 'medium'], 'medium')],
currentEffort: 'medium',
catalogReady: true,
@@ -669,7 +668,7 @@ describe('pickAgentDefaultRuntime', () => {
it('falls back to the catalog top row (with its provider) when no provider offers the recent model', () => {
const runtime = pickAgentDefaultRuntime({
agentKind: 'claude-code',
- sessions: [remoteSession('ds', { agentKind: 'cc', model: 'delisted-model', providerId: 'prov-deleted', userSendAt: '2026-01-01T00:00:00.000Z' })],
+ hostRuntime: hostRuntime('claude-code', 'delisted-model', { providerId: 'prov-deleted' }),
modelRows: [modelRow('claude-sonnet-4-6', ['low', 'medium'], 'low'), modelRow('claude-haiku', ['low'], 'low')],
currentEffort: 'high',
catalogReady: true,
@@ -680,7 +679,7 @@ describe('pickAgentDefaultRuntime', () => {
it('leaves the model empty with the default route when the catalog is ready but empty and the provider is gone', () => {
const runtime = pickAgentDefaultRuntime({
agentKind: 'codex',
- sessions: [remoteSession('ds', { agentKind: 'codex', model: 'delisted-model', providerId: 'prov-deleted', userSendAt: '2026-01-01T00:00:00.000Z' })],
+ hostRuntime: hostRuntime('codex', 'delisted-model', { providerId: 'prov-deleted' }),
modelRows: [],
currentEffort: 'medium',
catalogReady: true,
@@ -692,7 +691,7 @@ describe('pickAgentDefaultRuntime', () => {
it('trusts the recent providerId while modelRows are still loading (empty)', () => {
const runtime = pickAgentDefaultRuntime({
agentKind: 'claude-code',
- sessions: [remoteSession('ds', { agentKind: 'cc', model: 'deepseek-v4-flash', providerId: 'deepseek', userSendAt: '2026-01-01T00:00:00.000Z' })],
+ hostRuntime: hostRuntime('claude-code', 'deepseek-v4-flash', { providerId: 'deepseek' }),
modelRows: [],
currentEffort: 'medium',
catalogReady: false,
@@ -703,7 +702,7 @@ describe('pickAgentDefaultRuntime', () => {
it('falls back the model together when the catalog is ready but empty (loaded ≠ loading, codex P1)', () => {
const runtime = pickAgentDefaultRuntime({
agentKind: 'claude-code',
- sessions: [remoteSession('ds', { agentKind: 'cc', model: 'deepseek-v4-flash', providerId: 'deepseek', userSendAt: '2026-01-01T00:00:00.000Z' })],
+ hostRuntime: hostRuntime('claude-code', 'deepseek-v4-flash', { providerId: 'deepseek' }),
modelRows: [],
currentEffort: 'medium',
catalogReady: true,
@@ -726,7 +725,7 @@ describe('pickAgentDefaultRuntime', () => {
});
const runtime = pickAgentDefaultRuntime({
agentKind: 'claude-code',
- sessions: [remoteSession('s', { agentKind: 'cc', model: 'shared-model', providerId: 'provB', effort: 'xhigh', userSendAt: '2026-01-01T00:00:00.000Z' })],
+ hostRuntime: hostRuntime('claude-code', 'shared-model', { effort: 'xhigh', providerId: 'provB' }),
modelRows: [shared('provA', ['low'], 'low'), shared('provB', ['high', 'xhigh'], 'high')],
currentEffort: 'medium',
catalogReady: true,
@@ -748,7 +747,7 @@ describe('pickAgentDefaultRuntime', () => {
});
const runtime = pickAgentDefaultRuntime({
agentKind: 'claude-code',
- sessions: [remoteSession('s', { agentKind: 'cc', model: 'shared-model', providerId: 'provB', effort: 'xhigh', userSendAt: '2026-01-01T00:00:00.000Z' })],
+ hostRuntime: hostRuntime('claude-code', 'shared-model', { effort: 'xhigh', providerId: 'provB' }),
// 目录未就绪时的残留行:只有 provA 提供同 modelId,provB 不在其中
modelRows: [shared('provA', ['low'], 'low')],
currentEffort: 'medium',
@@ -758,10 +757,10 @@ describe('pickAgentDefaultRuntime', () => {
expect(runtime).toEqual({ agentKind: 'claude-code', model: 'shared-model', effort: 'xhigh', providerId: 'provB' });
});
- it('falls back to the top of the target agent\'s model list when it has no recent session', () => {
+ it('falls back to the top of the target agent\'s model list when the host default belongs to another agent', () => {
const runtime = pickAgentDefaultRuntime({
agentKind: 'codex',
- sessions: [remoteSession('cc', { agentKind: 'cc', model: 'claude-opus-4-8', userSendAt: '2026-02-02T00:00:00.000Z' })],
+ hostRuntime: hostRuntime('claude-code', 'claude-opus-4-8'),
modelRows: [modelRow('gpt-5.4', ['low', 'medium'], 'low'), modelRow('gpt-mini', ['low'], 'low')],
currentEffort: 'high', // 不被目标模型支持 → reconcile 到默认 'low'
catalogReady: true,
@@ -778,14 +777,14 @@ describe('pickAgentDefaultRuntime', () => {
// 区域默认来自 provider 行 → 携带该行 provider(#1898 语义,merge main 后适配)
expect(pickAgentDefaultRuntime({
agentKind: 'claude-code',
- sessions: [],
+ hostRuntime: null,
modelRows: rows,
currentEffort: 'high',
catalogReady: true,
})).toEqual({ agentKind: 'claude-code', model: 'cc-regional', effort: 'medium', providerId: 'prov-cc-regional' });
expect(pickAgentDefaultRuntime({
agentKind: 'pi',
- sessions: [],
+ hostRuntime: null,
modelRows: rows,
currentEffort: 'high',
catalogReady: true,
@@ -795,7 +794,7 @@ describe('pickAgentDefaultRuntime', () => {
it('uses only the explicit Pi regional default marker', () => {
expect(pickAgentDefaultRuntime({
agentKind: 'pi',
- sessions: [],
+ hostRuntime: null,
modelRows: [
modelRow('top', ['low'], 'low'),
modelRow('pi-regional', ['high'], 'high', ['pi']),
@@ -825,7 +824,7 @@ describe('pickAgentDefaultRuntime', () => {
// [A/foo(无标记), B/foo(标记)]:必须在行层面选中 B,携带 B 的来源并按其档位表校准
const runtime = pickAgentDefaultRuntime({
agentKind: 'claude-code',
- sessions: [],
+ hostRuntime: null,
modelRows: [shared('provA', false, ['low'], 'low'), shared('provB', true, ['high', 'xhigh'], 'high')],
currentEffort: 'high',
catalogReady: true,
@@ -836,14 +835,14 @@ describe('pickAgentDefaultRuntime', () => {
it('leaves the model empty and omits effort when the catalog is ready but empty (codex P2)', () => {
expect(pickAgentDefaultRuntime({
agentKind: 'codex',
- sessions: [],
+ hostRuntime: null,
modelRows: [],
currentEffort: 'medium',
catalogReady: true,
})).toEqual({ agentKind: 'codex', model: '', effort: '', providerId: null });
expect(pickAgentDefaultRuntime({
agentKind: 'claude-code',
- sessions: [],
+ hostRuntime: null,
modelRows: [],
currentEffort: 'high',
catalogReady: true,
@@ -853,7 +852,7 @@ describe('pickAgentDefaultRuntime', () => {
it('skips the top-row branch while the catalog is not ready (stale rows from the previous device, codex P1)', () => {
const runtime = pickAgentDefaultRuntime({
agentKind: 'codex',
- sessions: [],
+ hostRuntime: null,
modelRows: [modelRow('gpt-5.4', ['low', 'medium'], 'low')],
currentEffort: 'medium',
catalogReady: false,
@@ -863,37 +862,6 @@ describe('pickAgentDefaultRuntime', () => {
expect(runtime.providerId).toBeNull();
});
- it('scopes the recent lookup to the selected device', () => {
- const runtime = pickAgentDefaultRuntime({
- agentKind: 'codex',
- sessions: [
- remoteSession('other', { agentKind: 'codex', model: 'gpt-other', deviceLinkDeviceId: 'devB', userSendAt: '2026-05-05T00:00:00.000Z' }),
- remoteSession('target', { agentKind: 'codex', model: 'gpt-5.4', effort: 'low', deviceLinkDeviceId: 'devA', userSendAt: '2026-01-01T00:00:00.000Z' }),
- ],
- modelRows: [modelRow('gpt-5.4', ['low', 'medium'], 'low')],
- currentEffort: 'medium',
- deviceId: 'devA',
- catalogReady: true,
- });
- // 历史坏数据自愈(copilot P2):providerId 空但目录有同名行 → 补全为该行 provider
- expect(runtime).toEqual({ agentKind: 'codex', model: 'gpt-5.4', effort: 'low', providerId: 'prov-gpt-5.4' });
- });
-
- it('never inherits a provider across devices (device filter wins before provider carry)', () => {
- const runtime = pickAgentDefaultRuntime({
- agentKind: 'codex',
- sessions: [
- remoteSession('onB', { agentKind: 'codex', model: 'gpt-5.4', providerId: 'prov-b', deviceLinkDeviceId: 'devB', userSendAt: '2026-05-05T00:00:00.000Z' }),
- ],
- modelRows: [modelRow('gpt-5.4', ['low', 'medium'], 'low')],
- currentEffort: 'medium',
- deviceId: 'devA',
- catalogReady: true,
- });
- // devB 的会话被设备过滤排除 → 落到列表首项分支,来源取该行的 provider,不串 devB 的 prov-b
- expect(runtime).toEqual({ agentKind: 'codex', model: 'gpt-5.4', effort: 'medium', providerId: 'prov-gpt-5.4' });
- });
-
it('resolves the default source by agent rule for a null providerId offered by multiple sources (codex review P2)', () => {
// 同名模型由多个来源提供时,不得取目录首行(anthropic 在前)——被控端默认路由
// 按 agent 解析(effectiveSourceIdForModel,codex 优先 openai 其次 xd),UI 高亮与
@@ -940,7 +908,8 @@ describe('resolveNewSessionAutoDefault', () => {
userTouched: false,
appliedDeviceId: null as string | null,
selectedDeviceId: 'devA',
- sessions: [] as RemoteSession[],
+ hostDefaultsSettled: true,
+ hostRuntime: null as NewSessionRuntime | null,
modelRows: [] as ProviderModelRow[],
rowsAgentKind: 'claude-code' as const,
catalogReady: true,
@@ -948,41 +917,62 @@ describe('resolveNewSessionAutoDefault', () => {
currentEffort: 'medium',
};
- it('intent ①: follows the most recent session as a whole runtime (agent+model+effort reconciled)', () => {
+ it('intent ⓪: waits until the host new-task defaults are read (no premature catalog default)', () => {
+ expect(resolveNewSessionAutoDefault({
+ ...baseInput,
+ hostDefaultsSettled: false,
+ modelRows: [modelRow('claude-sonnet-4-6', ['low', 'medium'], 'low')],
+ })).toBeNull();
+ });
+
+ it('intent ①: follows the host new-task default of the current agent (model + effort reconciled, agent untouched)', () => {
const result = resolveNewSessionAutoDefault({
...baseInput,
- sessions: [remoteSession('cx', { agentKind: 'codex', model: 'gpt-5.4', effort: 'high', deviceLinkDeviceId: 'devA', userSendAt: '2026-01-01T00:00:00.000Z' })],
+ rowsAgentKind: 'codex',
+ hostRuntime: hostRuntime('codex', 'gpt-5.4', { effort: 'high' }),
modelRows: [modelRow('gpt-5.4', ['low', 'medium', 'high'], 'medium')],
});
+ // 历史坏数据自愈(copilot P2):providerId 空但目录有同名行 → 补全为该行 provider
expect(result).toEqual({
appliedDeviceId: 'devA',
+ source: 'host-default',
patch: {
- agentKind: 'codex',
model: 'gpt-5.4',
effort: 'high',
- permissionMode: 'auto',
- providerId: null,
+ providerId: 'prov-gpt-5.4',
},
});
});
- it('intent ①+: inherits the recent session providerId when the provider still offers the model (#1898)', () => {
+ it('intent ①a: a host default is the only default — task history no longer steers it', () => {
+ // 回归:自动化 / 测试任务(从未由用户发消息)曾因更新时间最新被当成「最近使用」,
+ // 把新建任务默认带成 Haiku。现在没有被控电脑默认时只看目录区域默认。
const result = resolveNewSessionAutoDefault({
...baseInput,
- sessions: [remoteSession('ds', { agentKind: 'cc', model: 'deepseek-v4-flash', providerId: 'prov-deepseek-v4-flash', deviceLinkDeviceId: 'devA', userSendAt: '2026-01-01T00:00:00.000Z' })],
+ modelRows: [
+ modelRow('claude-haiku-4-5', ['high'], 'high'),
+ modelRow('claude-opus-5-5', ['high'], 'high', ['claude-code']),
+ ],
+ });
+ expect(result).toMatchObject({ source: 'catalog-default', patch: { model: 'claude-opus-5-5' } });
+ });
+
+ it('intent ①+: inherits the host default providerId when the provider still offers the model (#1898)', () => {
+ const result = resolveNewSessionAutoDefault({
+ ...baseInput,
+ hostRuntime: hostRuntime('claude-code', 'deepseek-v4-flash', { providerId: 'prov-deepseek-v4-flash' }),
modelRows: [modelRow('deepseek-v4-flash', ['low', 'medium', 'high'], 'medium')],
});
expect(result?.patch).toMatchObject({
- agentKind: 'claude-code',
model: 'deepseek-v4-flash',
providerId: 'prov-deepseek-v4-flash',
});
});
- it('intent ①-: reroutes to another provider offering the same model when the recent provider is gone (codex P1)', () => {
+ it('intent ①-: reroutes to another provider offering the same model when the host default provider is gone (codex P1)', () => {
const result = resolveNewSessionAutoDefault({
...baseInput,
- sessions: [remoteSession('ds', { agentKind: 'cc', model: 'deepseek-v4-flash', providerId: 'prov-gone', deviceLinkDeviceId: 'devA', userSendAt: '2026-01-01T00:00:00.000Z' })],
+ hostRuntime: hostRuntime('claude-code', 'deepseek-v4-flash', { providerId: 'prov-gone' }),
modelRows: [modelRow('deepseek-v4-flash', ['low', 'medium', 'high'], 'medium')],
});
expect(result?.patch).toMatchObject({
@@ -991,10 +981,10 @@ describe('resolveNewSessionAutoDefault', () => {
});
});
- it('intent ①-fallback: falls back to the catalog top row when no provider offers the recent model', () => {
+ it('intent ①-fallback: falls back to the catalog top row when no provider offers the host default model', () => {
const result = resolveNewSessionAutoDefault({
...baseInput,
- sessions: [remoteSession('ds', { agentKind: 'cc', model: 'delisted-model', providerId: 'prov-gone', deviceLinkDeviceId: 'devA', userSendAt: '2026-01-01T00:00:00.000Z' })],
+ hostRuntime: hostRuntime('claude-code', 'delisted-model', { providerId: 'prov-gone' }),
modelRows: [modelRow('claude-sonnet-4-6', ['low', 'medium'], 'low')],
});
expect(result?.patch).toMatchObject({
@@ -1003,70 +993,30 @@ describe('resolveNewSessionAutoDefault', () => {
});
});
- it('intent ①x: trusts the recent providerId when it belongs to a different agent than the rows (codex P1)', () => {
- // 目录按 claude-code 构建,最近会话是 codex —— 目录不一致时不做校验,合法来源不被误清
+ it('intent ①z: ignores a host default that belongs to another agent than the rows', () => {
const result = resolveNewSessionAutoDefault({
...baseInput,
rowsAgentKind: 'claude-code',
- catalogReady: true,
- sessions: [remoteSession('cx', { agentKind: 'codex', model: 'gpt-5.4', providerId: 'prov-codex-only', deviceLinkDeviceId: 'devA', userSendAt: '2026-01-01T00:00:00.000Z' })],
- modelRows: [modelRow('claude-sonnet-4-6', ['low', 'medium'], 'medium')],
- });
- expect(result?.patch).toMatchObject({
- agentKind: 'codex',
- model: 'gpt-5.4',
- providerId: 'prov-codex-only',
- });
- });
-
- it('intent ①b: keeps the recent effort when the recent model is not in modelRows (cross-agent / delisted)', () => {
- const result = resolveNewSessionAutoDefault({
- ...baseInput,
- sessions: [remoteSession('cx', { agentKind: 'codex', model: 'gpt-legacy', effort: 'high', deviceLinkDeviceId: 'devA', userSendAt: '2026-01-01T00:00:00.000Z' })],
+ hostRuntime: hostRuntime('codex', 'gpt-5.4', { effort: 'xhigh', providerId: 'prov-codex-only' }),
modelRows: [modelRow('claude-sonnet-4-6', ['low', 'medium'], 'medium')],
});
- expect(result?.patch).toEqual({
- agentKind: 'codex',
- model: 'gpt-legacy',
- effort: 'high',
- permissionMode: 'auto',
- providerId: null,
- });
+ expect(result).toMatchObject({ source: 'catalog-default', patch: { model: 'claude-sonnet-4-6' } });
});
- it('intent ①y: cross-agent follow keeps recent effort verbatim — rows belong to another agent and have no authority over its effort ladder (reviewer P2)', () => {
- // 目录按 claude-code 构建,最近会话是 codex(gpt-5.4 + xhigh);cc 目录里恰好也有
- // 同名 gpt-5.4 但档位表不含 xhigh —— 修复前命中该行,effort 被错 reconcile 成
- // cc 默认档 'medium',随后渲染目录按 codex 重建而 effort 不再复核,错档一路带进创建。
+ it('intent ①r: reconciles the host default effort against the matched row ladder', () => {
const result = resolveNewSessionAutoDefault({
...baseInput,
- rowsAgentKind: 'claude-code',
- sessions: [remoteSession('cx', { agentKind: 'codex', model: 'gpt-5.4', effort: 'xhigh', providerId: 'prov-codex-only', deviceLinkDeviceId: 'devA', userSendAt: '2026-01-01T00:00:00.000Z' })],
- modelRows: [modelRow('gpt-5.4', ['low', 'medium'], 'medium')],
- });
- expect(result?.patch).toMatchObject({
- agentKind: 'codex',
- model: 'gpt-5.4',
- effort: 'xhigh',
- providerId: 'prov-codex-only',
- });
- });
-
- it('intent ①r: same-agent follow still reconciles effort against the matched row ladder', () => {
- const result = resolveNewSessionAutoDefault({
- ...baseInput,
- sessions: [remoteSession('ds', { agentKind: 'cc', model: 'deepseek-v4-flash', effort: 'xhigh', providerId: 'prov-deepseek-v4-flash', deviceLinkDeviceId: 'devA', userSendAt: '2026-01-01T00:00:00.000Z' })],
+ hostRuntime: hostRuntime('claude-code', 'deepseek-v4-flash', { effort: 'xhigh', providerId: 'prov-deepseek-v4-flash' }),
modelRows: [modelRow('deepseek-v4-flash', ['low', 'medium'], 'medium')],
});
expect(result?.patch).toMatchObject({
- agentKind: 'claude-code',
model: 'deepseek-v4-flash',
effort: 'medium', // xhigh 不在该 agent 目录档位表 → reconcile 到模型默认档
providerId: 'prov-deepseek-v4-flash',
});
});
- it('intent ②: no recent session → top of the model list (model + reconciled effort + row provider, agentKind untouched)', () => {
+ it('intent ②: no host default → top of the model list (model + reconciled effort + row provider, agentKind untouched)', () => {
const result = resolveNewSessionAutoDefault({
...baseInput,
currentEffort: 'high', // 不被首个模型支持 → reconcile 到默认 'low'
@@ -1074,6 +1024,7 @@ describe('resolveNewSessionAutoDefault', () => {
});
expect(result).toEqual({
appliedDeviceId: 'devA',
+ source: 'catalog-default',
patch: { model: 'claude-sonnet-4-6', effort: 'low', providerId: 'prov-claude-sonnet-4-6' },
});
expect(result?.patch).not.toHaveProperty('agentKind');
@@ -1088,7 +1039,7 @@ describe('resolveNewSessionAutoDefault', () => {
expect(result).toBeNull();
});
- it('intent ②a: no recent session → regional default before the top row (upstream main 移植)', () => {
+ it('intent ②a: no host default → regional default before the top row (upstream main 移植)', () => {
const result = resolveNewSessionAutoDefault({
...baseInput,
currentEffort: 'high',
@@ -1144,12 +1095,8 @@ describe('resolveNewSessionAutoDefault', () => {
});
it('intent ③: switching device (not manually touched) recomputes for the new device', () => {
- const sessions = [
- remoteSession('onA', { model: 'model-A', deviceLinkDeviceId: 'devA', userSendAt: '2026-01-01T00:00:00.000Z' }),
- remoteSession('onB', { model: 'model-B', deviceLinkDeviceId: 'devB', userSendAt: '2026-02-02T00:00:00.000Z' }),
- ];
expect(resolveNewSessionAutoDefault({
- ...baseInput, sessions, appliedDeviceId: 'devA', selectedDeviceId: 'devB',
+ ...baseInput, hostRuntime: hostRuntime('claude-code', 'model-B'), appliedDeviceId: 'devA', selectedDeviceId: 'devB',
modelRows: [modelRow('model-B', ['low'], 'low')],
})?.patch).toMatchObject({ model: 'model-B' });
});
@@ -1158,19 +1105,19 @@ describe('resolveNewSessionAutoDefault', () => {
expect(resolveNewSessionAutoDefault({
...baseInput,
userTouched: true,
- sessions: [remoteSession('cx', { model: 'gpt-5.4', deviceLinkDeviceId: 'devA', userSendAt: '2026-01-01T00:00:00.000Z' })],
+ hostRuntime: hostRuntime('claude-code', 'gpt-5.4'),
modelRows: [modelRow('gpt-5.4', ['low'], 'low')],
})).toBeNull();
});
- it('returns null when modelRows are not ready yet and there is no recent session (no premature set)', () => {
- expect(resolveNewSessionAutoDefault({ ...baseInput, sessions: [], modelRows: [] })).toBeNull();
+ it('returns null when modelRows are not ready yet and there is no host default (no premature set)', () => {
+ expect(resolveNewSessionAutoDefault({ ...baseInput, modelRows: [] })).toBeNull();
});
it('applies the capabilities flat default when the catalog is explicitly unavailable (old host without provider:list, codex P2)', () => {
const result = resolveNewSessionAutoDefault({
...baseInput,
- sessions: [],
+ hostRuntime: null,
modelRows: [],
catalogReady: false,
providersUnsupported: true,
@@ -1189,6 +1136,7 @@ describe('resolveNewSessionAutoDefault', () => {
// 目录明确不可用(旧被控端)→ 放行 capabilities 扁平回退;扁平列表无 provider 结构 → 默认路由
expect(result).toEqual({
appliedDeviceId: 'devA',
+ source: 'catalog-default',
patch: {
model: 'flat-default',
effort: 'medium',
@@ -1200,7 +1148,7 @@ describe('resolveNewSessionAutoDefault', () => {
it('does not fall back to flat defaults while the catalog is merely loading (error is empty, codex P2)', () => {
expect(resolveNewSessionAutoDefault({
...baseInput,
- sessions: [],
+ hostRuntime: null,
modelRows: [],
catalogReady: false,
providersUnsupported: false,
@@ -2996,13 +2944,13 @@ describe('closed saved model requires reselection', () => {
const selected = { model: 'closed', providerId: 'prov-closed' };
const visibilityOverrides = { 'codex:prov-closed:closed': false };
const rows = [modelRow('replacement', ['medium'], 'medium')];
- const sessions = [remoteSession('saved', { ...selected, agentKind: 'codex', effort: 'high', deviceLinkDeviceId: 'devA' })];
+ const saved = hostRuntime('codex', selected.model, { providerId: selected.providerId, effort: 'high' });
it('preserves the hidden pair during catalog reconciliation and remembered-agent restoration', () => {
expect(resolveRecentModelAndProvider(rows, selected, 'codex', true, visibilityOverrides)).toEqual(selected);
- expect(pickAgentDefaultRuntime({ agentKind: 'codex', sessions, modelRows: rows,
+ expect(pickAgentDefaultRuntime({ agentKind: 'codex', hostRuntime: saved, modelRows: rows,
currentEffort: 'medium', catalogReady: true, visibilityOverrides })).toMatchObject({ ...selected, effort: 'high' });
expect(resolveNewSessionAutoDefault({ userTouched: false, appliedDeviceId: null, selectedDeviceId: 'devA',
- sessions, modelRows: rows, rowsAgentKind: 'codex', catalogReady: true, visibilityOverrides,
+ hostDefaultsSettled: true, hostRuntime: saved, modelRows: rows, rowsAgentKind: 'codex', catalogReady: true, visibilityOverrides,
currentEffort: 'medium' })?.patch).toMatchObject(selected);
});
it('carries fresh visibility with its rows through the submit guard', async () => {
diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.ts
index b929af82e1..c3c842e59a 100644
--- a/apps/mobile/src/device-link/mobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts
@@ -387,17 +387,31 @@ export interface MobileSessionModelPref {
/**
* 草稿「模型 effort/fast」写穿入参(隧道 maker:apply-new-maker-draft-pref,形状对齐被控端
- * APPLY_NEW_MAKER_DRAFT_PREF 校验)。手机只做非选中行双写(active 恒 false),被控端草稿
- * 默认随之更新,使「下次在被控端 / 桌面控制端选中该模型」拿到同一份 effort/fast。
+ * APPLY_NEW_MAKER_DRAFT_PREF 校验)。
+ * - active=false:会话里非选中行双写,被控端草稿默认随之更新,使「下次在被控端 / 桌面控制端
+ * 选中该模型」拿到同一份 effort/fast(providerId 必填)。
+ * - active=true:新建任务页的当前选择写回被控端新建任务默认(与桌面远程新建同一写法);
+ * markModelChoice=true 表示用户明确选了这个模型,false 只同步档位 / Fast、不打选模标记。
*/
-export interface MobileNewMakerDraftPref {
- agent: MobileAgentKind;
- providerId: string;
- modelId: string;
- active: false;
- effort?: string;
- fast?: boolean;
-}
+export type MobileNewMakerDraftPref =
+ | {
+ agent: MobileAgentKind;
+ providerId: string;
+ modelId: string;
+ active: false;
+ effort?: string;
+ fast?: boolean;
+ }
+ | {
+ agent: MobileAgentKind;
+ /** '' = 跟随被控端默认来源。 */
+ providerId: string;
+ modelId: string;
+ active: true;
+ markModelChoice: boolean;
+ effort?: string;
+ fast?: boolean;
+ };
/**
* 工作端 maker:get-new-maker-defaults 回包的手机端消费子集。完整形状是被控端
diff --git a/apps/mobile/src/session/newSession.ts b/apps/mobile/src/session/newSession.ts
index cf28443b89..9cc94ba628 100644
--- a/apps/mobile/src/session/newSession.ts
+++ b/apps/mobile/src/session/newSession.ts
@@ -189,7 +189,7 @@ export const DEFAULT_NEW_SESSION_DRAFT: NewSessionDraft = {
agentKind: 'claude-code',
workspaceKind: 'project',
workingDir: '',
- // 不写死模型:由最近任务 / 被控端目录落定(见 isNewSessionRuntimePending),
+ // 不写死模型:由被控电脑的新建任务默认 / 目录落定(见 isNewSessionRuntimePending),
// 都拿不到时留空让用户自己选,不替用户挑一个电脑上未必可用的模型。
model: '',
providerId: null,
@@ -712,73 +712,77 @@ function findSectionModelRow(
}
/**
- * 从现有会话列表挑"最近一次"的整套运行配置(agent + model + effort + providerId),用于新建对话
- * 默认跟随最近会话。providerId 取自该会话在被控端落盘的来源选择(null = 默认路由)。
- * 过滤:排除 status==='deleted'、无 model;可选 `deviceId`(只看该设备——模型列表 per-device,跨设备 model 可能
- * 在目标设备不存在,来源同理——同设备过滤保证继承的来源在目标设备存在);可选 `agentKind`(只看该 agent)。
- * 排序:按活动时间(userSendAt ?? updatedAt ?? createdAt)降序取第一条。
- * 映射 `RemoteSession.agentKind`:'codex'|'pi' 原样保留,其余(含 'cc')归一为 'claude-code'。无匹配→null。
- * deviceId 过滤口径对齐 buildRecentWorkspaceOptions:仅当 session 带了 deviceLinkDeviceId 且与目标不符才排除。
+ * 被控电脑的新建任务默认回包是否已就绪。被控端只有在渲染进程推来草稿镜像后才回
+ * worktreeEnabled;刚启动时回 {}(或只有模型预设),这时不能当成「从未选过模型」,
+ * 调用方应稍后重读。旧被控端同样不带该字段,由调用方有限次重读后按无默认处理。
*/
-export function pickMostRecentSessionRuntime(
- sessions: readonly RemoteSession[],
- options: { deviceId?: string; agentKind?: NewSessionAgentKind } = {},
+export function isHostDraftDefaultsReady(defaults: unknown): boolean {
+ return !!defaults && typeof defaults === 'object'
+ && Object.prototype.hasOwnProperty.call(defaults, 'worktreeEnabled');
+}
+
+/**
+ * 被控电脑「新建任务默认」(maker:get-new-maker-defaults 回包)→ 该 agent 的默认运行配置。
+ * 与桌面远程新建同一读源(deviceLinkDraftDefaults):在某台电脑上新建任务,默认就是那台电脑上
+ * 新建任务时用户上次选的模型;不再从任务列表推断(自动化 / 测试任务会被误当成「最近使用」)。
+ * 返回 null 时由调用方按目录区域默认兜底:
+ * - 旧被控端回 {} / 形状异常 / 无 model;
+ * - 被控端明确从未选过模型(modelChosenByUser=false)且未选来源 —— 它的 model 只是种子,
+ * 与桌面同口径交给目录的 newSessionDefault 标记决定。
+ */
+export function hostDraftRuntimeFromDefaults(
+ defaults: unknown,
+ agentKind: NewSessionAgentKind,
): NewSessionRuntime | null {
- let best: { runtime: NewSessionRuntime; activityAt: string } | null = null;
- for (const session of sessions) {
- if (session.status === 'deleted') continue;
- const model = session.model?.trim();
- if (!model) continue;
- if (options.deviceId && session.deviceLinkDeviceId && session.deviceLinkDeviceId !== options.deviceId) continue;
- const agentKind: NewSessionAgentKind = session.agentKind === 'codex' || session.agentKind === 'pi'
- ? session.agentKind
- : 'claude-code';
- if (options.agentKind && agentKind !== options.agentKind) continue;
- const activityAt = session.userSendAt ?? session.updatedAt ?? session.createdAt;
- if (!best || activityAt.localeCompare(best.activityAt) > 0) {
- best = {
- runtime: { agentKind, model, effort: session.effort?.trim() ?? '', providerId: session.providerId ?? null },
- activityAt,
- };
- }
- }
- return best?.runtime ?? null;
+ if (!defaults || typeof defaults !== 'object') return null;
+ const value = defaults as {
+ model?: unknown;
+ effort?: unknown;
+ providerId?: unknown;
+ modelChosenByUser?: unknown;
+ };
+ const model = typeof value.model === 'string' ? value.model.trim() : '';
+ if (!model) return null;
+ const providerId = typeof value.providerId === 'string' && value.providerId ? value.providerId : null;
+ if (value.modelChosenByUser === false && providerId === null) return null;
+ const effort = typeof value.effort === 'string' ? value.effort.trim() : '';
+ return { agentKind, model, effort, providerId };
}
/**
* 算"切到某 agent 后的默认运行配置(model + effort + providerId)",供新建对话「切 agent」入口复用,
* 与初始自动默认共用同一套 fallback 口径。纯函数:所有输入显式传入,不读 react / 设备状态。
* model 优先级:
- * 1) 该 agent 的最近一次会话模型(pickMostRecentSessionRuntime,按 deviceId scope);
+ * 1) 被控电脑记住的该 agent 新建任务默认(hostDraftRuntimeFromDefaults,与桌面远程新建同源);
* 2) 否则取区域门控后的新任务默认;无标记再取该 agent 的模型列表最上面那个
* (modelRows[0] —— providers 已加载时同步可得,与下拉渲染的第一项一致);
* 3) 被控端明确不支持目录(旧电脑)时取它能力表里的模型:区域默认标记优先,否则首个;
* 4) 否则留空(不写死模型),由用户自己选。
* providerId 跟随 model 同源:
- * 1) 跟随最近会话 → 继承该会话的来源(validateModelProviderId 校验:目录已就绪且来源
+ * 1) 跟随被控电脑默认 → 继承其来源(validateModelProviderId 校验:目录已就绪且来源
* 已删/不再提供该模型时清空回默认路由;同设备+同 agent 范围,供应商集天然兼容);
* 2) 取列表首项 → 该行的 provider(modelRows[0].provider.id);
* 3) 能力表模型 / 都没有 → null(默认路由)。
- * effort:reconcile 到目标 model 的合法档(reconcileEffortForModel,base = 最近会话 effort ?? 当前 effort,
+ * effort:reconcile 到目标 model 的合法档(reconcileEffortForModel,base = 被控电脑默认 effort ?? 当前 effort,
* SectionModel 按 (providerId, modelId) 精确匹配行——同模型多来源时不串档);
* 拿不到目标 model 对应的 SectionModel(model 不在 modelRows 里,如模型留空或历史模型已下架)
* 时保留 base effort 不动。
*/
export function pickAgentDefaultRuntime(args: {
agentKind: NewSessionAgentKind;
- sessions: readonly RemoteSession[];
+ /** 被控电脑该 agent 的新建任务默认(hostDraftRuntimeFromDefaults);null = 无 / 旧被控端。 */
+ hostRuntime: NewSessionRuntime | null;
modelRows: readonly ProviderModelRow[];
currentEffort: string;
- deviceId?: string;
- /** 供应商目录是否已就绪(加载完成);未就绪时来源校验信任最近会话(见 validateModelProviderId)。 */
+ /** 供应商目录是否已就绪(加载完成);未就绪时来源校验信任被控电脑默认(见 validateModelProviderId)。 */
catalogReady: boolean;
visibilityOverrides?: Record<string, boolean> | null;
/** 仅当被控端明确不支持 provider:list 时传入该 agent 的能力表模型(与 resolveNewSessionAutoDefault 同口径)。 */
flatModels?: readonly MobileModelOption[];
}): NewSessionRuntime {
- const { agentKind, sessions, modelRows, currentEffort, deviceId, catalogReady } = args;
+ const { agentKind, modelRows, currentEffort, catalogReady } = args;
let flatModel: MobileModelOption | undefined;
- const recent = pickMostRecentSessionRuntime(sessions, { deviceId, agentKind });
+ const recent = args.hostRuntime?.agentKind === agentKind ? args.hostRuntime : null;
const baseEffort = recent?.effort ?? currentEffort;
let model: string;
let providerId: string | null;
@@ -814,7 +818,7 @@ export function pickAgentDefaultRuntime(args: {
// 目录未就绪时不做 effort 校准:catalogReady=false 时 modelRows 可能是上一设备
// 的残留行,findSectionModelRow 的 modelId 回退会按错误来源校准 effort;新目录
// 确认原 (provider, model) 有效后组合未变化又不再重校准,用户可能在能力表到达前
- // 提交该来源不支持的档位(codex review P2)。未就绪时保留最近任务的 effort。
+ // 提交该来源不支持的档位(codex review P2)。未就绪时保留被控电脑默认的 effort。
// catalogReady 且无匹配行 = 目录为空/模型下架:旧自定义模型的
// 档位对之后选的模型无效——省略 effort,由被控端取默认(codex review P2:模型无行
// 回退时不得沿用旧档位;与 reconcileEffortAfterFallback 的 no-row 口径一致)。
@@ -830,7 +834,7 @@ export function pickAgentDefaultRuntime(args: {
/**
* 新建页的模型是否仍在等数据落定(草稿初值为空 / 恢复上次 agent 时数据未到)。
* 等待期间模型药丸显示「正在读取模型」且不能创建。
- * 落定 = 自动默认或恢复上次 agent 已按最近任务 / 目录写入模型,或用户自己改过运行配置。
+ * 落定 = 自动默认或恢复上次 agent 已按被控电脑默认 / 目录写入模型,或用户自己改过运行配置。
* 数据不会再来时结束等待:目录拉取失败(含旧被控端不支持目录)、或目录已就绪但为空;
* 此时若仍没有模型,药丸显示「未选择模型」,由用户自己选。
*/
@@ -872,7 +876,7 @@ export interface StoredAgentRestoreState {
/**
* 恢复上次 agent 的下一步。不变量:agent 不依赖任何数据,偏好一到就恢复;只有模型要等
- * 目录或该 agent 的最近任务(canResolveStoredAgentRuntime),且只补一次。
+ * 被控电脑默认与目录(canResolveStoredAgentRuntime),且只补一次。
* - 'full':数据已够,agent + 权限 + 模型一次恢复;
* - 'agent':数据未到,先恢复 agent + 权限,模型用占位——否则目录一直拉不到时草稿停在
* 别的 agent,创建会建错 agent 并把它存成新偏好;
@@ -892,50 +896,54 @@ export function nextStoredAgentRestoreStep(input: {
/**
* 恢复上次的 agent 时,是否已有足够数据选模型(pickAgentDefaultRuntime 的输入):
- * 供应商目录已就绪 / 被控端明确不支持目录,或该设备上已有这个 agent 的最近任务。
- * 两者都没有时 pickAgentDefaultRuntime 选不出模型(留空),
+ * 先等被控电脑的新建任务默认读完(否则会先按目录默认落定,读到的默认再也用不上);
+ * 之后供应商目录已就绪 / 被控端明确不支持目录,或被控电脑已给出该 agent 的默认即可。
+ * 都没有时 pickAgentDefaultRuntime 选不出模型(留空),
* 这时只先恢复 agent(见 nextStoredAgentRestoreStep),模型等数据到了再补。
* 不能用 `loading === false` 代替:useDeviceProviders 的 loading 初值就是 false,拉取失败后也是。
*/
export function canResolveStoredAgentRuntime(input: {
- agentKind: NewSessionAgentKind;
- sessions: readonly RemoteSession[];
deviceId: string;
+ /** 被控电脑新建任务默认是否已读完(成功、旧被控端或读取失败都算读完)。 */
+ hostDefaultsSettled: boolean;
+ hostRuntime: NewSessionRuntime | null;
catalogReady: boolean;
providersUnsupported: boolean;
}): boolean {
if (!input.deviceId) return true;
+ if (!input.hostDefaultsSettled) return false;
if (input.catalogReady || input.providersUnsupported) return true;
- return pickMostRecentSessionRuntime(input.sessions, {
- deviceId: input.deviceId,
- agentKind: input.agentKind,
- }) !== null;
+ return input.hostRuntime !== null;
}
/**
* 新建对话「自动默认运行配置」effect 的决策核心(纯函数,从 new.tsx 那个 effect 内联逻辑抽出,便于单测)。
- * 返回 null = 本次不动 draft(已手动选过 / 无 selectedDevice / 该设备已应用过 / modelRows 未就绪且无 recent);
+ * 返回 null = 本次不动 draft(已手动选过 / 无 selectedDevice / 该设备已应用过 / 被控电脑默认未读完 /
+ * modelRows 未就绪且无被控电脑默认);
* 返回 { patch, appliedDeviceId } = 调用方 setDraft(prev => ({ ...prev, ...patch })) 并记录 appliedDeviceId。
- * 三条意图与 effect 完全一致:
- * 1) 有最近会话(按 selectedDeviceId scope)→ 整套跟随(agentKind + model + effort + providerId,
+ * 意图(与桌面远程新建同一口径,不再从任务列表推断「最近使用」):
+ * 0) 被控电脑新建任务默认未读完 → null(读完再定,避免先落目录默认);
+ * 1) 被控电脑给出当前 agent 的默认 → 跟随(model + effort + providerId,不动 agentKind;
* effort reconcile 同 pickAgentDefaultRuntime 口径:SectionModel 按 (providerId, modelId)
* 精确匹配;providerId 经 validateModelProviderId 校验后继承);
- * 2) 无最近会话 → 区域默认标记优先;无 provider 结构时才信 capabilities 扁平标记
+ * 2) 无默认 → 区域默认标记优先;无 provider 结构时才信 capabilities 扁平标记
* (上游 main 移植);无标记再取 provider 列表最上面(model + effort reconcile + 该行
* provider,不动 agentKind);
- * 3) 无最近会话且目录未就绪 / 两份模型列表都未就绪 → null(等下次数据就绪再设,绝不误设)。
+ * 3) 无默认且目录未就绪 / 两份模型列表都未就绪 → null(等下次数据就绪再设,绝不误设)。
* currentEffort = 当前 draft.effort,作为 reconcile 的 base(与 effect 里 setDraft updater 读 current.effort 等价)。
*/
export function resolveNewSessionAutoDefault(input: {
userTouched: boolean;
appliedDeviceId: string | null;
selectedDeviceId: string;
- sessions: readonly RemoteSession[];
+ /** 被控电脑新建任务默认是否已读完(成功、旧被控端或读取失败都算读完)。 */
+ hostDefaultsSettled: boolean;
+ /** 被控电脑 rowsAgentKind 的新建任务默认(hostDraftRuntimeFromDefaults);null = 无。 */
+ hostRuntime: NewSessionRuntime | null;
modelRows: readonly ProviderModelRow[];
- /** modelRows 是按哪个 agent 的目录构建的。跟随的最近会话可能是另一个 agent ——
- * 目录不一致时不做来源校验(无权评判,直接信任),否则会把合法来源误清(codex review P1)。 */
+ /** modelRows 是按哪个 agent 的目录构建的;被控电脑默认只在同一 agent 时采用。 */
rowsAgentKind: NewSessionAgentKind;
- /** 供应商目录是否已就绪;未就绪时来源校验信任最近会话(见 validateModelProviderId)。 */
+ /** 供应商目录是否已就绪;未就绪时来源校验信任被控电脑默认(见 validateModelProviderId)。 */
catalogReady: boolean;
visibilityOverrides?: Record<string, boolean> | null;
/** Only an explicitly unsupported provider:list channel permits capabilities fallback. */
@@ -943,12 +951,12 @@ export function resolveNewSessionAutoDefault(input: {
/** 仅在 provider-aware 列表不可用时传入,避免绕过被控端的模型可见性设置(上游 main 移植)。 */
availableModels?: readonly MobileModelOption[];
currentEffort: string;
-}): { patch: Partial<NewSessionDraft>; appliedDeviceId: string } | null {
+}): { patch: Partial<NewSessionDraft>; appliedDeviceId: string; source: 'host-default' | 'catalog-default' } | null {
const {
userTouched,
appliedDeviceId,
selectedDeviceId,
- sessions,
+ hostDefaultsSettled,
modelRows,
rowsAgentKind,
catalogReady,
@@ -959,38 +967,32 @@ export function resolveNewSessionAutoDefault(input: {
if (userTouched) return null;
if (!selectedDeviceId) return null;
if (appliedDeviceId === selectedDeviceId) return null;
- const recent = pickMostRecentSessionRuntime(sessions, { deviceId: selectedDeviceId });
+ if (!hostDefaultsSettled) return null;
+ const recent = input.hostRuntime?.agentKind === rowsAgentKind ? input.hostRuntime : null;
if (recent) {
// 联合解析(口径同 pickAgentDefaultRuntime):来源失效时 model 随之一并回退
- // (codex review P1);目录 agent 不一致时不评判、维持信任。
+ // (codex review P1)。
const { model, providerId } = resolveRecentModelAndProvider(
modelRows,
{ model: recent.model, providerId: recent.providerId },
- recent.agentKind,
- catalogReady && recent.agentKind === rowsAgentKind,
+ rowsAgentKind,
+ catalogReady,
input.visibilityOverrides,
);
- // 跨 agent 跟随时 modelRows 按当前 agent 构建,其档位表对目标 agent 无权威——
- // 命中同名模型行会把 recent.effort 错 reconcile 成当前 agent 的默认档(独立
- // review P2)。此时直接用 recent.effort;渲染后目录按目标 agent 重建,由既有
- // 就绪终检链路校准。同 agent 才按精确匹配行 reconcile(原有口径)。
- const sectionModel = recent.agentKind === rowsAgentKind
- ? findSectionModelRow(modelRows, model, providerId)?.model
- : undefined;
+ const sectionModel = findSectionModelRow(modelRows, model, providerId)?.model;
return {
appliedDeviceId: selectedDeviceId,
+ source: 'host-default',
patch: {
- agentKind: recent.agentKind,
model,
effort: sectionModel
? reconcileEffortForModel(sectionModel, recent.effort || currentEffort)
: recent.effort || currentEffort,
- permissionMode: defaultPermissionModeForNewSessionAgent(recent.agentKind),
providerId,
},
};
}
- // 无最近会话 → 区域默认标记优先;无 provider 结构时才信 capabilities 扁平标记
+ // 无被控电脑默认 → 区域默认标记优先;无 provider 结构时才信 capabilities 扁平标记
// (上游 main 移植);provider-aware 列表由调用方传空 availableModels,避免区域
// 默认绕过用户隐藏设置。目录未就绪(加载中/切设备间隙残留旧设备目录,
// ready=false)则不动,等就绪后 effect 重算(codex review P1);目录「明确不可用」
@@ -1011,6 +1013,7 @@ export function resolveNewSessionAutoDefault(input: {
if (!defaultModel) return null;
return {
appliedDeviceId: selectedDeviceId,
+ source: 'catalog-default',
patch: {
model: defaultModel.id,
effort: reconcileEffortForModel(defaultModel, currentEffort),