Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 新建任务不再显示写死的 Sonnet 4.6,模型落定前不能创建 (#5706)
Dashfad2baaf5df0
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsxindex 95db0b0e74..3b63c3506b 100644--- a/apps/mobile/app/sessions/new.tsx+++ b/apps/mobile/app/sessions/new.tsx@@ -182,9 +182,11 @@ import {insertSlashCommand,mergeSlashCommands,} from '@/session/composerPalette';+import { mobileDebugLog } from '@/debug/mobileDebugLog';import {type StoredAgentRestoreState,applyRemoteAgentPick,+ assertSubmitModelResolved,DEFAULT_NEW_SESSION_DRAFT,NEW_SESSION_AGENT_OPTIONS,availableNewSessionAgentOptions,@@ -194,6 +196,7 @@ import {buildRecentWorkspaceOptions,filterRemoteDirectoryEntries,isCurrentRemoteBrowseRequest,+ isNewSessionRuntimePending,isStoredAgentRestorePending,nextStoredAgentRestoreStep,normalizeRemoteDirectoryDrives,@@ -406,6 +409,16 @@ function targetAgentHasFast(deviceId: string, agentKind: NewSessionAgentKind): breturn getCachedAgentCapabilities(buildAgentCapabilitiesCacheKey(deviceId, agentKind))?.hasFastMode === true;}+/** 旧被控端(明确不支持 provider:list)才用能力表模型兜底选默认;支持目录的电脑一律走目录。 */+function flatModelsForUnsupportedHost(+ deviceId: string,+ agentKind: NewSessionAgentKind,+ providersUnsupported: boolean,+): readonly MobileModelOption[] | undefined {+ if (!providersUnsupported || !deviceId) return undefined;+ return getCachedAgentCapabilities(buildAgentCapabilitiesCacheKey(deviceId, agentKind))?.availableModels;+}+interface WorktreeBranchListSnapshot {target: { deviceId: string; workingDir: string };branches: string[];@@ -1017,6 +1030,15 @@ export default function NewRemoteSessionScreen() {// 自动默认运行配置(跟随最近会话 / 区域默认 / 列表最上面)的守卫:用户一旦手动选过模型,就不再自动覆盖;// 记录已自动应用过的设备,切设备时(未手动选过)按新设备重算。const userTouchedRuntimeRef = useRef(false);+ // 模型已按哪台电脑的真实数据落定(见 isNewSessionRuntimePending);切到别的电脑即重新等待,+ // 未落定时药丸显示读取中、不能创建。+ const [runtimeSettledDeviceId, setRuntimeSettledDeviceId] = useState<string | null>(null);+ const mountedAtRef = useRef(Date.now());+ const runtimeSettledSourceRef = useRef('');+ const settleRuntime = useCallback((source: string, deviceId: string) => {+ runtimeSettledSourceRef.current = source;+ setRuntimeSettledDeviceId(deviceId);+ }, []);// 只保护当前页面刚从 provider 目录显式选中的模型,避免旧 capabilities 在途结果误回退;// 持久草稿不会写入该 ref,因此已下架模型仍走 mobile 的首项降级。const explicitProviderModelSelectionRef = useRef<string | null>(null);@@ -1234,7 +1256,7 @@ export default function NewRemoteSessionScreen() {expectedDeviceId: preferredDefaultDevice?.deviceId ?? '',selectedDeviceId,})) return;- // agent 偏好一到就恢复;模型要等目录或该 agent 的最近任务,否则只能落到内置兜底模型。+ // agent 偏好一到就恢复;模型要等目录或该 agent 的最近任务,否则选不出模型。const step = nextStoredAgentRestoreStep({storedAgentKind,restored,@@ -1247,7 +1269,10 @@ export default function NewRemoteSessionScreen() {}),});if (!step) return;- storedAgentRestoreRef.current = { agentKind: storedAgentKind, phase: step === 'agent' ? 'agent' : 'done' };+ mobileDebugLog('debug', 'new-session', 'stored agent restore', { step, agentKind: storedAgentKind });+ const previousRestore = restored;+ const restoreState: StoredAgentRestoreState = { agentKind: storedAgentKind, phase: step === 'agent' ? 'agent' : 'done' };+ storedAgentRestoreRef.current = restoreState;// 现场按最新目录算该 agent 的默认运行配置(rows 与 ready 必须同一代,codex review P2)。const resolveStoredRuntime = (currentEffort: string) => {const rowsNow = flattenProviderSections(@@ -1265,6 +1290,7 @@ export default function NewRemoteSessionScreen() {currentEffort,catalogReady: catalogReadyRef.current,visibilityOverrides: deviceProvidersRef.current.modelVisibilityOverrides,+ flatModels: flatModelsForUnsupportedHost(selectedDeviceId, storedAgentKind, deviceProvidersRef.current.unsupported),});return {model: next.model,@@ -1286,11 +1312,14 @@ export default function NewRemoteSessionScreen() {setDraft((current) => (current.agentKind === storedAgentKind? { ...current, ...resolveStoredRuntime(current.effort) }: current));+ settleRuntime('stored-agent-model', selectedDeviceId);return;}// 该路径同时负责恢复 agent 权限,下面的通用权限记忆 effect 不再重复弹框。appliedPermissionMemoryRef.current = true;+ const previousAutoDefaultDevice = autoDefaultDeviceRef.current;if (selectedDeviceId) autoDefaultDeviceRef.current = selectedDeviceId;+ let applied = false;const storedPermissionMode = newSessionPreferences?.permissionModeByAgent[storedAgentKind];const nextPermissionMode =storedPermissionMode ??@@ -1307,6 +1336,7 @@ export default function NewRemoteSessionScreen() {if (deviceAtTrigger !== selectedDeviceRef.current) return;// 确认期间用户又切了 agent / 手动选了模型 → 旧回调不得覆盖新选择。if (seqAtTrigger !== runtimeActionSeqRef.current) return;+ applied = true;setDraft((current) => ({...current,...resolveStoredRuntime(current.effort),@@ -1314,9 +1344,16 @@ export default function NewRemoteSessionScreen() {// 上次明确选择过的权限直接沿用;内置默认若升级到 Full access 仍需确认。permissionMode: confirmed ? nextPermissionMode : current.permissionMode,}));+ // 'agent' 只恢复了 agent,模型仍是占位,等数据到了由 'model' 落定。+ if (step === 'full') settleRuntime('stored-agent', deviceAtTrigger);})();return () => {cancelled = true;+ // 写入前依赖已变(effect 重跑):撤回「已恢复」与设备锁,让重跑的 effect 重新恢复。+ // 否则标记已落、草稿却没写,两条默认路径都不再处理,页面停在占位模型。+ if (applied) return;+ if (storedAgentRestoreRef.current === restoreState) storedAgentRestoreRef.current = previousRestore;+ if (autoDefaultDeviceRef.current === selectedDeviceId) autoDefaultDeviceRef.current = previousAutoDefaultDevice;};}, [draft.permissionMode,@@ -1379,7 +1416,9 @@ export default function NewRemoteSessionScreen() {currentEffort: draft.effort,});if (!result) return;+ const previousAutoDefaultDevice = autoDefaultDeviceRef.current;autoDefaultDeviceRef.current = result.appliedDeviceId;+ let applied = false;const nextAgentKind = result.patch.agentKind ?? draft.agentKind;const storedPermissionMode = appliedPermissionMemoryRef.current? undefined@@ -1392,6 +1431,8 @@ export default function NewRemoteSessionScreen() {restoringRememberedChoice: storedPermissionMode !== undefined,}).then((confirmed) => {if (cancelled || userTouchedRuntimeRef.current) return;+ applied = true;+ settleRuntime(result.patch.agentKind ? 'recent-task' : 'catalog-default', result.appliedDeviceId);setDraft((current) => {// 自动默认重算(设备切换/最近会话变化)改了 (agent, model, providerId) 组合 →// fastMode 按新组合重验(Codex review P2):A 设备记忆恢复的 fastMode:true 不得@@ -1419,12 +1460,16 @@ export default function NewRemoteSessionScreen() {});return () => {cancelled = true;+ // 写入前 effect 重跑:撤回设备锁,重跑时按最新数据重新应用,不把这台设备误记为已应用。+ if (!applied && autoDefaultDeviceRef.current === result.appliedDeviceId) {+ 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]);// 目录就绪后的来源终检(codex review P1):自动默认/恢复在目录加载期信任的来源可能已失效// (provider 被删/断开/模型下架),就绪后必须复核——联合回退整对 (model, providerId)- // (其他来源顶替 / 首项 / 内置默认),不留裸模型回落默认网关(codex review P2)。+ // (其他来源顶替 / 首项 / 留空),不留裸模型回落默认网关(codex review P2)。// 无变化时返回原引用,不触发额外渲染。useEffect(() => {if (!deviceProviders.ready) return;@@ -1454,6 +1499,29 @@ export default function NewRemoteSessionScreen() {() => ({ attachmentCount: attachments.length + pendingUploads.length }),[attachments.length, pendingUploads.length],);+ const runtimePending = isNewSessionRuntimePending({+ settled: !!selectedDeviceId && runtimeSettledDeviceId === selectedDeviceId,+ userTouched: userTouchedRuntimeRef.current,+ remoteAgentPicked: !!remoteAgentPick,+ selectedDeviceId: selectedDeviceId ?? '',+ catalogReady: deviceProviders.ready,+ catalogFailed: deviceProviders.error !== null,+ modelRowCount: modelRows.length,+ });+ const runtimePendingRef = useRef(runtimePending);+ runtimePendingRef.current = runtimePending;+ useEffect(() => {+ if (!runtimeSettledDeviceId) return;+ // 诊断用:新建页的模型经哪条路径、多久后落定(只记 agent 与模型 id,不含正文)。+ mobileDebugLog('info', 'new-session', 'runtime settled', {+ source: runtimeSettledSourceRef.current,+ agentKind: draft.agentKind,+ model: draft.model,+ elapsedMs: Date.now() - mountedAtRef.current,+ });+ // 每台电脑落定那一刻记一次。+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [runtimeSettledDeviceId]);const runtimeSummary = useMemo(() => buildDraftRuntimeSummary(draft, runtimeOptions),// effort / 权限标签按 app 语言解析,切换语言时必须重算,否则停留在上一语言。@@ -1468,7 +1536,11 @@ export default function NewRemoteSessionScreen() {remoteAgentModelName || remoteAgentPick.model,effortLabelFromRuntime({ currentModel: null, effortOptions: runtimeOptions.effortOptions }, remoteAgentPick.effort),].filter(Boolean).join(' · ')- : runtimeSummary.modelSummary;+ : runtimePending+ ? t('session.new.modelLoading')+ : draft.model.trim()+ ? runtimeSummary.modelSummary+ : t('session.new.noModelSelected');const pillAccessibilityModel = remoteAgentCatalog?.name? [pillModelSummary, remoteAgentCatalog.name].join(', '): pillModelSummary;@@ -1769,8 +1841,8 @@ export default function NewRemoteSessionScreen() {);}, []);const createValidation = useMemo(- () => validateNewSessionDraft(draft, draftContent),- [draft, draftContent],+ () => runtimePending ? t('session.new.modelLoading') : validateNewSessionDraft(draft, draftContent),+ [draft, draftContent, runtimePending, t],);const composerHasMessage = draft.firstMessage.trim().length > 0;// 「按下即录」的乐观反馈(与会话页/桌面同款,详见 [sessionId].tsx 同名状态注释)。@@ -1810,6 +1882,7 @@ export default function NewRemoteSessionScreen() {[draft, draftContent],);const canCreate = (!createValidation || (voiceIsListening && createValidationIsMissingPayload))+ && !runtimePending&& !creating&& !voiceIsProcessing&& !worktreeCreateBlocked;@@ -2012,6 +2085,13 @@ export default function NewRemoteSessionScreen() {userTouchedDeviceRef.current = true;explicitProviderModelSelectionRef.current = null;browseSeqRef.current += 1;+ // 换了电脑且用户没手动选过模型:丢掉上一台电脑自动选出的模型并重新等待,由新电脑的+ // 最近任务 / 目录 / 能力表重新落定;都拿不到时留空让用户选,不拿旧电脑的模型去创建。+ const clearAutoRuntime = option.deviceId !== selectedDeviceIdRef.current && !userTouchedRuntimeRef.current;+ if (clearAutoRuntime) {+ autoDefaultDeviceRef.current = null;+ setRuntimeSettledDeviceId(null);+ }selectedDeviceIdRef.current = option.deviceId;setSelectedDeviceId(option.deviceId);setSelectedDeviceName(option.name || option.deviceId);@@ -2047,10 +2127,11 @@ export default function NewRemoteSessionScreen() {composerAnnotationsRef.current?.forgetAllAttachments();setAttachmentError(null);initialWorkspaceKeyRef.current = null;- setDraft((current) =>- current.workspaceKind === 'project'- ? { ...current, workingDir: '' }- : current);+ setDraft((current) => ({+ ...current,+ ...(current.workspaceKind === 'project' ? { workingDir: '' } : {}),+ ...(clearAutoRuntime ? { model: '', providerId: null, fastMode: false } : {}),+ }));}, [attachments, auth, cancelVoiceForDeviceSwitch, creating, discardAllPendingUploads, voiceIsProcessing, voiceState]);const handleBack = useCallback(() => {@@ -4078,7 +4159,7 @@ export default function NewRemoteSessionScreen() {</VoicePillWidthFrame>);- // 切 agent:跟随该 agent 的最近会话 → 否则该 agent 列表最上面 → 否则内置默认(见 pickAgentDefaultRuntime),+ // 切 agent:跟随该 agent 的最近会话 → 否则该 agent 列表最上面 → 否则留空由用户选(见 pickAgentDefaultRuntime),// 同时 reconcile effort、来源跟随 model 同源(最近会话来源校验后继承 / 首项行 provider / 兜底 null)。// 手动切 agent = 手动选运行配置 → 之后自动默认不再覆盖。const switchAgent = useCallback((nextKind: NewSessionAgentKind) => {@@ -4117,6 +4198,7 @@ export default function NewRemoteSessionScreen() {currentEffort: current.effort,catalogReady: catalogReadyRef.current,visibilityOverrides: deviceProvidersRef.current.modelVisibilityOverrides,+ flatModels: flatModelsForUnsupportedHost(selectedDeviceId, nextKind, deviceProvidersRef.current.unsupported),});return {...current,@@ -4435,6 +4517,8 @@ export default function NewRemoteSessionScreen() {setError(t('session.new.selectDeviceError'));return;}+ // 模型仍是占位(最近任务 / 目录未到):不创建,按钮此时本就不可点,这里兜住其它提交入口。+ if (runtimePendingRef.current) return;// 旧协议 Plan 依赖会话级 permissionMode,不能安全进入断线创建 / 离线 FIFO。// 保留草稿与 Plan 选择,等 relay 和目标电脑恢复后再走原有在线兼容路径。if (@@ -4849,7 +4933,7 @@ export default function NewRemoteSessionScreen() {}// 提交点联合终检(Greptile/Codex review P1):目录就绪后的清理 effect 跑在渲染后,// 用户可能在清理生效前点创建——创建路径自身必须守卫;来源失效时 model 随之一并- // 回退(其他来源顶替 / 首项 / 内置默认),并同步校准 effort、组合变化时 fastMode+ // 回退(其他来源顶替 / 首项 / 留空),并同步校准 effort、组合变化时 fastMode// 保守置 false(codex review P2)。代际安全版(独立 review P1-1):唯一数据源 =// 设备缓存 + 代际,不再读渲染期 rows(catalogReadyRef 是渲染镜像,驱逐窗口内// 不可信);缓存命中即当前代已确认目录;未命中且曾驱逐 → join 在途重拉,await@@ -4895,6 +4979,7 @@ export default function NewRemoteSessionScreen() {effectiveDraft.agentKind,g.catalogKnown,);+ assertSubmitModelResolved(resolved, effectiveDraft.model);const pairChanged = resolved.model !== effectiveDraft.model || resolved.providerId !== effectiveDraft.providerId;// 目录就绪时**始终**按 fresh 精确行校准(codex review P2:来源未变时也按// 新目录校准运行选项)——provider revision 可能只改能力不删行(撤销 effort@@ -4992,6 +5077,7 @@ export default function NewRemoteSessionScreen() {effectiveDraft.agentKind,true,);+ assertSubmitModelResolved(resolved, effectiveDraft.model);const pairChanged = resolved.model !== effectiveDraft.model|| resolved.providerId !== effectiveDraft.providerId;// codex review P2:来源未变也按 fresh 精确行校准——fresh 目录就绪时始终@@ -5110,6 +5196,8 @@ export default function NewRemoteSessionScreen() {const createGoalSession = useCallback(async (input: { objective: string; limits?: MobileGoalLimitsInput }) => {if (leaveForeignOutboxRecovery()) return;if (creatingRef.current || goalBusy) return;+ // 与 create() 同一道门:模型仍在等这台电脑的数据时不创建(目标表单此时也是禁用的)。+ if (runtimePendingRef.current) return;if (!selectedDeviceId) {setGoalError(t('session.new.selectDeviceError'));return;@@ -5433,6 +5521,7 @@ export default function NewRemoteSessionScreen() {effectiveDraft.agentKind,g.catalogKnown,);+ assertSubmitModelResolved(resolved, effectiveDraft.model);const pairChanged = resolved.model !== effectiveDraft.model || resolved.providerId !== effectiveDraft.providerId;// codex review P2:目录就绪时**始终**按 fresh 精确行校准(来源未变也按新// 目录校准运行选项)——provider revision 只改能力不删行(撤销 effort 档位@@ -6685,10 +6774,12 @@ export default function NewRemoteSessionScreen() {) : (<ContextSheetGoalCreateFormbusy={goalBusy}- disabled={worktreeCreateBlocked}- disabledHint={worktreeCreateBlocked && worktreeControlCaptionKey- ? t(worktreeControlCaptionKey)- : undefined}+ disabled={worktreeCreateBlocked || runtimePending}+ disabledHint={runtimePending+ ? t('session.new.modelLoading')+ : worktreeCreateBlocked && worktreeControlCaptionKey+ ? t(worktreeControlCaptionKey)+ : undefined}error={goalError}initial={draft.firstMessage.trim() ? { objective: draft.firstMessage.trim() } : undefined}onSetGoal={(input) => void createGoalSession(input)}diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.tsindex a55a818e90..4c7f459acb 100644--- a/apps/mobile/src/__tests__/newSession.test.ts+++ b/apps/mobile/src/__tests__/newSession.test.ts@@ -9,6 +9,8 @@ import {NEW_SESSION_AGENT_OPTIONS,availableNewSessionAgentOptions,canResolveStoredAgentRuntime,+ assertSubmitModelResolved,+ isNewSessionRuntimePending,isStoredAgentRestorePending,nextStoredAgentRestoreStep,type StoredAgentRestoreState,@@ -352,7 +354,7 @@ describe('stored agent restore gating', () => {currentEffort: 'medium',deviceId: 'mac',catalogReady: false,- })).toMatchObject({ model: 'claude-sonnet-4-6', effort: 'medium' });+ })).toMatchObject({ model: '', effort: 'medium' });});it('proceeds once a recent task of the stored agent exists on the device', () => {@@ -436,7 +438,7 @@ describe('stored agent restore gating', () => {const source = readTextLf(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');const storedStart = source.indexOf('const storedAgentKind = newSessionPreferences?.agentKind;');const autoStart = source.indexOf('const result = resolveNewSessionAutoDefault({');- const storedSource = source.slice(storedStart, source.indexOf('storedAgentRestoreRef.current = {', storedStart));+ const storedSource = source.slice(storedStart, source.indexOf('storedAgentRestoreRef.current = restoreState', storedStart));const autoGuardSource = source.slice(source.lastIndexOf('useEffect(() => {', autoStart), autoStart);expect(storedSource).toContain('isStoredAgentRestorePending({');expect(storedSource).toContain('canResolveStoredAgentRuntime({');@@ -451,6 +453,104 @@ describe('stored agent restore gating', () => {});});+describe('pickAgentDefaultRuntime on hosts without provider:list', () => {+ const flat = (id: string, marked: boolean): MobileModelOption => ({+ id, label: id, efforts: ['low', 'high'], effortDisplayNames: {}, defaultEffort: 'high', supportsFastMode: false,+ ...(marked ? { newSessionDefault: ['claude-code'] } : {}),+ } 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 };+ 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 });+ // 能力表也没有时才留空。+ expect(pickAgentDefaultRuntime({ ...base, flatModels: [] })).toMatchObject({ model: '' });+ expect(pickAgentDefaultRuntime(base)).toMatchObject({ model: '' });+ });++ it('passes capabilities models only for unsupported hosts, on both stored-agent restore and agent switch', () => {+ const source = readTextLf(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');+ expect(source).toContain('flatModels: flatModelsForUnsupportedHost(selectedDeviceId, storedAgentKind, deviceProvidersRef.current.unsupported),');+ expect(source).toContain('flatModels: flatModelsForUnsupportedHost(selectedDeviceId, nextKind, deviceProvidersRef.current.unsupported),');+ expect(source).toContain('if (!providersUnsupported || !deviceId) return undefined;');+ });+});++describe('isNewSessionRuntimePending', () => {+ const base = {+ settled: false,+ userTouched: false,+ remoteAgentPicked: false,+ selectedDeviceId: 'mac-studio',+ catalogReady: false,+ catalogFailed: false,+ modelRowCount: 0,+ };++ it('keeps the placeholder model pending until real data settles it', () => {+ expect(isNewSessionRuntimePending(base)).toBe(true);+ // 目录就绪但自动默认 / 恢复还没写入:仍是占位。+ expect(isNewSessionRuntimePending({ ...base, catalogReady: true, modelRowCount: 3 })).toBe(true);+ expect(isNewSessionRuntimePending({ ...base, settled: true })).toBe(false);+ });++ it('never blocks a choice the user made', () => {+ expect(isNewSessionRuntimePending({ ...base, userTouched: true })).toBe(false);+ expect(isNewSessionRuntimePending({ ...base, remoteAgentPicked: true })).toBe(false);+ });++ it('falls back to the built-in model when no more data will arrive', () => {+ expect(isNewSessionRuntimePending({ ...base, selectedDeviceId: '' })).toBe(false);+ expect(isNewSessionRuntimePending({ ...base, catalogFailed: true })).toBe(false);+ expect(isNewSessionRuntimePending({ ...base, catalogReady: true, modelRowCount: 0 })).toBe(false);+ });++ it('rolls back the restore marker and device lock when an automatic write is dropped', () => {+ const source = readTextLf(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');+ const storedStart = source.indexOf('const storedAgentKind = newSessionPreferences?.agentKind;');+ const storedEffect = source.slice(storedStart, source.indexOf('}, [', storedStart));+ expect(storedEffect).toContain('if (storedAgentRestoreRef.current === restoreState) storedAgentRestoreRef.current = previousRestore;');+ expect(storedEffect).toContain('autoDefaultDeviceRef.current = previousAutoDefaultDevice;');+ const autoStart = source.indexOf('const result = resolveNewSessionAutoDefault({');+ const autoEffect = source.slice(autoStart, source.indexOf('}, [', autoStart));+ expect(autoEffect).toContain('autoDefaultDeviceRef.current = previousAutoDefaultDevice;');+ });++ it('binds the settled model to the computer it was settled for', () => {+ const source = readTextLf(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');+ // 切到另一台电脑后重新等待,不能沿用上一台电脑落定的模型直接创建。+ expect(source).toContain('settled: !!selectedDeviceId && runtimeSettledDeviceId === selectedDeviceId,');+ expect(source).toContain("settleRuntime('stored-agent', deviceAtTrigger);");+ expect(source).toContain("settleRuntime('stored-agent-model', selectedDeviceId);");+ expect(source).toContain('result.appliedDeviceId);');+ });++ it('drops the previous computer\'s auto-picked model on device switch and gates goal creation too', () => {+ const source = readTextLf(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');+ const selectStart = source.indexOf('const selectDevice = useCallback(');+ const selectDevice = source.slice(selectStart, source.indexOf('const handleBack = useCallback(', selectStart));+ // 用户没手动选过模型时清掉旧电脑的自动选择并重新等待;手动选过的保留。+ expect(selectDevice).toContain('option.deviceId !== selectedDeviceIdRef.current && !userTouchedRuntimeRef.current');+ expect(selectDevice).toContain('autoDefaultDeviceRef.current = null;');+ expect(selectDevice).toContain('setRuntimeSettledDeviceId(null);');+ expect(selectDevice).toContain("...(clearAutoRuntime ? { model: '', providerId: null, fastMode: false } : {}),");+ // 目标模式是独立创建入口:表单禁用 + 函数内兜底。+ const goalStart = source.indexOf('const createGoalSession = useCallback(');+ expect(source.slice(goalStart, goalStart + 400)).toContain('if (runtimePendingRef.current) return;');+ expect(source).toContain('disabled={worktreeCreateBlocked || runtimePending}');+ });++ it('aborts creation instead of sending an empty model after the submit-time catalog check', () => {+ expect(() => assertSubmitModelResolved({ model: 'claude-opus-5-5' }, 'claude-opus-5-5')).not.toThrow();+ expect(() => assertSubmitModelResolved({ model: '' }, 'delisted-model'))+ .toThrow('delisted-model 在这台电脑上已不可用,请重新选择模型后再发送。');+ // 三处提交终检(创建前两处 + 鉴权后重验)都要经过这道拦截。+ const source = readTextLf(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');+ expect(source.split('assertSubmitModelResolved(resolved, effectiveDraft.model);').length - 1).toBe(3);+ });+});+describe('pickAgentDefaultRuntime', () => {it('follows the target agent\'s most recent session model + effort (reconciled)', () => {const runtime = pickAgentDefaultRuntime({@@ -577,7 +677,7 @@ describe('pickAgentDefaultRuntime', () => {expect(runtime).toEqual({ agentKind: 'claude-code', model: 'claude-sonnet-4-6', effort: 'medium', providerId: 'prov-claude-sonnet-4-6' });});- it('falls back to DEFAULT_MODELS + default route when the catalog is ready but empty and the provider is gone', () => {+ 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' })],@@ -586,7 +686,7 @@ describe('pickAgentDefaultRuntime', () => {catalogReady: true,});// 回退内置默认且目录为空 → 省略 effort(codex P2:旧自定义档位对内置模型无效)- expect(runtime).toEqual({ agentKind: 'codex', model: 'gpt-5.4', effort: '', providerId: null });+ expect(runtime).toEqual({ agentKind: 'codex', model: '', effort: '', providerId: null });});it('trusts the recent providerId while modelRows are still loading (empty)', () => {@@ -610,7 +710,7 @@ describe('pickAgentDefaultRuntime', () => {});// 目录就绪但为空:来源失效且无人能提供该模型 → model 一并回退内置默认(不留裸模型)// + 省略 effort(codex P2:旧自定义档位对内置模型无效)- expect(runtime).toEqual({ agentKind: 'claude-code', model: 'claude-sonnet-4-6', effort: '', providerId: null });+ expect(runtime).toEqual({ agentKind: 'claude-code', model: '', effort: '', providerId: null });});it('reconciles effort with the exact (providerId, modelId) row when multiple providers offer the same model (Copilot)', () => {@@ -733,21 +833,21 @@ describe('pickAgentDefaultRuntime', () => {expect(runtime).toEqual({ agentKind: 'claude-code', model: 'shared-model', effort: 'high', providerId: 'provB' });});- it('falls back to DEFAULT_MODELS and omits effort when the catalog is ready but empty (codex P2)', () => {+ it('leaves the model empty and omits effort when the catalog is ready but empty (codex P2)', () => {expect(pickAgentDefaultRuntime({agentKind: 'codex',sessions: [],modelRows: [],currentEffort: 'medium',catalogReady: true,- })).toEqual({ agentKind: 'codex', model: 'gpt-5.4', effort: '', providerId: null });+ })).toEqual({ agentKind: 'codex', model: '', effort: '', providerId: null });expect(pickAgentDefaultRuntime({agentKind: 'claude-code',sessions: [],modelRows: [],currentEffort: 'high',catalogReady: true,- })).toEqual({ agentKind: 'claude-code', model: 'claude-sonnet-4-6', effort: '', providerId: null });+ })).toEqual({ agentKind: 'claude-code', model: '', effort: '', providerId: null });});it('skips the top-row branch while the catalog is not ready (stale rows from the previous device, codex P1)', () => {@@ -759,7 +859,7 @@ describe('pickAgentDefaultRuntime', () => {catalogReady: false,});// 目录未就绪 → 不抄残留目录的首项,落内置默认 + 默认路由- expect(runtime).toEqual({ agentKind: 'codex', model: 'gpt-5.4', effort: 'medium', providerId: null });+ expect(runtime).toEqual({ agentKind: 'codex', model: '', effort: 'medium', providerId: null });expect(runtime.providerId).toBeNull();});@@ -1177,6 +1277,8 @@ describe('new session default device follows the home device filter', () => {});describe('new session model', () => {+ const DRAFT_WITH_MODEL = { ...DEFAULT_NEW_SESSION_DRAFT, model: 'claude-sonnet-4-6' };+it('hides dot directories by default and restores them when enabled', () => {const entries = [{ name: '.config', kind: 'dir' as const, path: '/Users/cindy/.config' },@@ -1252,7 +1354,7 @@ describe('new session model', () => {it('builds device-link create-session args with desktop remote-project semantics', () => {expect(buildRemoteCreateSessionOptions({- ...DEFAULT_NEW_SESSION_DRAFT,+ ...DRAFT_WITH_MODEL,workingDir: ' /repo/xdt-maker ',firstMessage: 'hello',extraDirs: [' /repo/docs ', '/repo/docs', ''],@@ -1269,7 +1371,7 @@ describe('new session model', () => {});it('runs the Agent on the picked remote computer or share', () => {- const draft = { ...DEFAULT_NEW_SESSION_DRAFT, workingDir: '/repo/app', firstMessage: 'hi' };+ const draft = { ...DRAFT_WITH_MODEL, workingDir: '/repo/app', firstMessage: 'hi' };expect(applyRemoteAgentPick(draft, null)).toBe(draft);const remote = applyRemoteAgentPick(draft, {deviceId: 'share:s1', agentKind: 'codex', model: 'gpt-5.5', providerId: 'openai', effort: 'high', fastMode: true,@@ -1289,7 +1391,7 @@ describe('new session model', () => {it('builds folderless dialogue create-session args for controlled-side cwd allocation', () => {expect(buildRemoteCreateSessionOptions({- ...DEFAULT_NEW_SESSION_DRAFT,+ ...DRAFT_WITH_MODEL,workspaceKind: 'dialogue',workingDir: ' /repo/should-not-leak ',firstMessage: 'hello',@@ -1306,7 +1408,7 @@ describe('new session model', () => {it('omits effort from create-session args when the selected model has no effort control', () => {expect(buildRemoteCreateSessionOptions({- ...DEFAULT_NEW_SESSION_DRAFT,+ ...DRAFT_WITH_MODEL,workingDir: '/repo/xdt-maker',firstMessage: 'hello',model: 'claude-haiku-4-6',@@ -1323,7 +1425,7 @@ describe('new session model', () => {it('preserves a Codex Auto-review draft when creating the session', () => {expect(buildRemoteCreateSessionOptions({- ...DEFAULT_NEW_SESSION_DRAFT,+ ...DRAFT_WITH_MODEL,agentKind: 'codex',model: 'gpt-5.4',permissionMode: 'auto',@@ -1335,17 +1437,17 @@ describe('new session model', () => {});it('switches agent defaults without carrying a Claude model into Codex', () => {- const codex = withAgentDefaults(DEFAULT_NEW_SESSION_DRAFT, 'codex');+ const codex = withAgentDefaults(DRAFT_WITH_MODEL, 'codex');expect(codex).toMatchObject({agentKind: 'codex',- model: 'gpt-5.4',+ model: '',permissionMode: 'auto',});const claude = withAgentDefaults({ ...codex, fastMode: true }, 'claude-code');expect(claude).toMatchObject({agentKind: 'claude-code',- model: 'claude-sonnet-4-6',+ model: '',permissionMode: 'auto',fastMode: false,});@@ -1355,8 +1457,8 @@ describe('new session model', () => {expect(NEW_SESSION_AGENT_OPTIONS.map((option) => option.kind)).toEqual(['claude-code', 'codex', 'pi',]);- const pi = withAgentDefaults({ ...DEFAULT_NEW_SESSION_DRAFT, fastMode: true }, 'pi');- expect(pi).toMatchObject({ agentKind: 'pi', model: 'gpt-5.4', fastMode: true });+ const pi = withAgentDefaults({ ...DRAFT_WITH_MODEL, fastMode: true }, 'pi');+ expect(pi).toMatchObject({ agentKind: 'pi', model: '', fastMode: true });expect(buildRemoteCreateSessionOptions({...pi,workingDir: '/repo/xdt-maker',@@ -1404,27 +1506,29 @@ describe('new session model', () => {it('validates required path, model and first-message payload', () => {expect(validateNewSessionDraft(DEFAULT_NEW_SESSION_DRAFT)).toBe('请输入电脑端项目路径。');+ // 草稿初值不写死模型:由最近任务 / 目录落定,拿不到时留空让用户选。+ expect(DEFAULT_NEW_SESSION_DRAFT.model).toBe('');expect(validateNewSessionDraft({- ...DEFAULT_NEW_SESSION_DRAFT,+ ...DRAFT_WITH_MODEL,workspaceKind: 'dialogue',})).toBe('请输入首条消息或添加附件。');expect(validateNewSessionDraft({- ...DEFAULT_NEW_SESSION_DRAFT,+ ...DRAFT_WITH_MODEL,workingDir: '/repo',model: '',})).toBe('请输入模型。');expect(validateNewSessionDraft({- ...DEFAULT_NEW_SESSION_DRAFT,+ ...DRAFT_WITH_MODEL,workingDir: '/repo',firstMessage: '',})).toBe('请输入首条消息或添加附件。');expect(validateNewSessionDraft({- ...DEFAULT_NEW_SESSION_DRAFT,+ ...DRAFT_WITH_MODEL,workingDir: '/repo',firstMessage: 'run tests',})).toBeNull();expect(validateNewSessionDraft({- ...DEFAULT_NEW_SESSION_DRAFT,+ ...DRAFT_WITH_MODEL,workingDir: '/repo',firstMessage: '',}, { attachmentCount: 1 })).toBeNull();@@ -1432,7 +1536,7 @@ describe('new session model', () => {it('summarizes the mobile create-session draft for the top overview strip', () => {expect(summarizeNewSessionDraft({- ...DEFAULT_NEW_SESSION_DRAFT,+ ...DRAFT_WITH_MODEL,workingDir: '',firstMessage: '',})).toMatchObject({@@ -1445,7 +1549,7 @@ describe('new session model', () => {});expect(summarizeNewSessionDraft({- ...DEFAULT_NEW_SESSION_DRAFT,+ ...DRAFT_WITH_MODEL,workingDir: '/repo/xdt-maker',firstMessage: 'run tests',extraDirs: ['/repo/docs', '/repo/docs', ''],@@ -1456,7 +1560,7 @@ describe('new session model', () => {});expect(summarizeNewSessionDraft({- ...DEFAULT_NEW_SESSION_DRAFT,+ ...DRAFT_WITH_MODEL,workingDir: '/repo/xdt-maker',firstMessage: '',}, { attachmentCount: 2 })).toMatchObject({@@ -1465,7 +1569,7 @@ describe('new session model', () => {});expect(summarizeNewSessionDraft({- ...DEFAULT_NEW_SESSION_DRAFT,+ ...DRAFT_WITH_MODEL,agentKind: 'codex',workspaceKind: 'dialogue',workingDir: '',@@ -1483,7 +1587,7 @@ describe('new session model', () => {it('builds a final mobile create preview before sending to the controlled computer', () => {expect(buildNewSessionCreatePreview({- ...DEFAULT_NEW_SESSION_DRAFT,+ ...DRAFT_WITH_MODEL,workingDir: '',firstMessage: '',}, 'Carol Mac')).toMatchObject({@@ -1498,7 +1602,7 @@ describe('new session model', () => {});expect(buildNewSessionCreatePreview({- ...DEFAULT_NEW_SESSION_DRAFT,+ ...DRAFT_WITH_MODEL,workspaceKind: 'dialogue',workingDir: '',firstMessage: '请帮我总结这个项目,并给出下一步建议。',@@ -1515,7 +1619,7 @@ describe('new session model', () => {});expect(buildNewSessionCreatePreview({- ...DEFAULT_NEW_SESSION_DRAFT,+ ...DRAFT_WITH_MODEL,workingDir: '/repo/xdt-maker',firstMessage: '',}, 'Carol Mac', { attachmentCount: 2 })).toMatchObject({diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsxindex fe7544ed78..3c3f4cbb58 100644--- a/apps/mobile/src/auth/AuthContext.tsx+++ b/apps/mobile/src/auth/AuthContext.tsx@@ -223,8 +223,6 @@ export interface MobileUser {name: string;avatar: string | null;email: string | null;- defaultModel: string;- defaultEffort: string;membershipKind: 'personal' | 'org';membershipRole: 'owner' | 'admin' | 'member';orgId: string | null;diff --git a/apps/mobile/src/auth/profileMerge.ts b/apps/mobile/src/auth/profileMerge.tsindex 2726a1932f..45a04da035 100644--- a/apps/mobile/src/auth/profileMerge.ts+++ b/apps/mobile/src/auth/profileMerge.ts@@ -11,9 +11,6 @@ import type { AuthMembership } from '@cindy/auth-client';import type { MobileUser } from './AuthContext';-export const DEFAULT_MODEL = 'claude-sonnet-4-6';-export const DEFAULT_EFFORT = 'medium';-export function mapMembershipToMobileUser(membership: AuthMembership,passportId?: string,@@ -24,8 +21,6 @@ export function mapMembershipToMobileUser(// auth-server 自助头像(PATCH /api/me/profile);null = 未设置(首字母兜底)。avatar: membership.avatarUrl ?? null,email: membership.email,- defaultModel: DEFAULT_MODEL,- defaultEffort: DEFAULT_EFFORT,membershipKind: membership.kind,membershipRole: membership.role,orgId: membership.orgId,@@ -46,8 +41,6 @@ export function mergeMembershipWithExisting(...mapped,// membership 自助头像优先;未设置时保留既有展示值。avatar: mapped.avatar ?? existing.avatar,- defaultModel: existing.defaultModel,- defaultEffort: existing.defaultEffort,passportId: mapped.passportId || existing.passportId,orgLogoUrl: mapped.orgLogoUrl ?? existing.orgLogoUrl ?? null,};diff --git a/apps/mobile/src/debug/mobileDebugLog.ts b/apps/mobile/src/debug/mobileDebugLog.tsindex ad6874ee2e..4eba21f861 100644--- a/apps/mobile/src/debug/mobileDebugLog.ts+++ b/apps/mobile/src/debug/mobileDebugLog.ts@@ -7,7 +7,8 @@ export type MobileDebugScope =| "scroll"| "keyboard"| "files"- | "voice";+ | "voice"+ | "new-session";export type MobileDebugLevel = "debug" | "info" | "warn" | "error";type Sink = (level: MobileDebugLevel,diff --git a/apps/mobile/src/debug/visualMock.ts b/apps/mobile/src/debug/visualMock.tsindex 7284912b92..2a2732229f 100644--- a/apps/mobile/src/debug/visualMock.ts+++ b/apps/mobile/src/debug/visualMock.ts@@ -55,8 +55,6 @@ export const visualMockUser: MobileUser = {name: 'Visual Mock User',avatar: null,email: '[email protected]',- defaultModel: 'claude-sonnet-4-6',- defaultEffort: 'medium',membershipKind: 'personal',membershipRole: 'owner',orgId: null,diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.jsonindex 39827db8a4..4c17e76904 100644--- a/apps/mobile/src/i18n/locales/en/session.json+++ b/apps/mobile/src/i18n/locales/en/session.json@@ -7,6 +7,7 @@},"common": {"modelHiddenReselect": "{{model}} is turned off. Choose an enabled model before sending.",+ "modelUnavailableReselect": "{{model}} is no longer available on this computer. Choose another model before sending.","cancel": "Cancel","dismissRecommendation": "Dismiss recommendation","delete": "Delete",@@ -301,6 +302,7 @@"selectDeviceError": "Select a device.","enterProjectPath": "Enter the project path on the computer.","enterModel": "Enter a model.",+ "modelLoading": "Loading model…","enterFirstMessageOrAttachment": "Enter a first message or add an attachment.","noSessionIdReturned": "Could not confirm that the new session was created on the remote computer. Sync again to check.","sessionIdNotAdopted": "The Cindy version on the remote computer is incompatible. Update it and try again.",diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.jsonindex 40f2ac0f66..5944c39959 100644--- a/apps/mobile/src/i18n/locales/ja/session.json+++ b/apps/mobile/src/i18n/locales/ja/session.json@@ -7,6 +7,7 @@},"common": {"modelHiddenReselect": "{{model}} はオフになっています。送信する前に、有効なモデルを選んでください。",+ "modelUnavailableReselect": "{{model}} はこのコンピューターでは利用できなくなりました。送信する前に、別のモデルを選んでください。","cancel": "キャンセル","dismissRecommendation": "おすすめを閉じる","delete": "削除",@@ -301,6 +302,7 @@"selectDeviceError": "デバイスを選択してください。","enterProjectPath": "パソコン側のプロジェクトパスを入力してください。","enterModel": "モデルを入力してください。",+ "modelLoading": "モデルを読み込み中…","enterFirstMessageOrAttachment": "最初のメッセージを入力するか、添付を追加してください。","noSessionIdReturned": "リモートのパソコンで新しいセッションが作成されたか確認できません。再同期して確認してください。","sessionIdNotAdopted": "リモートのパソコンの Cindy は互換性のないバージョンです。更新してから再試行してください。",diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.jsonindex ddb4e27872..30c14e6b47 100644--- a/apps/mobile/src/i18n/locales/ko/session.json+++ b/apps/mobile/src/i18n/locales/ko/session.json@@ -7,6 +7,7 @@},"common": {"modelHiddenReselect": "{{model}} 모델이 꺼져 있습니다. 보내기 전에 켜져 있는 모델을 선택하세요.",+ "modelUnavailableReselect": "{{model}} 모델은 이 컴퓨터에서 더 이상 사용할 수 없습니다. 보내기 전에 다른 모델을 선택하세요.","cancel": "취소","dismissRecommendation": "추천 닫기","delete": "삭제",@@ -297,6 +298,7 @@"selectDeviceError": "기기를 선택하세요.","enterProjectPath": "컴퓨터의 프로젝트 경로를 입력하세요.","enterModel": "모델을 입력하세요.",+ "modelLoading": "모델을 불러오는 중…","enterFirstMessageOrAttachment": "첫 메시지를 입력하거나 첨부를 추가하세요.","noSessionIdReturned": "원격 컴퓨터에서 새 세션이 생성되었는지 확인할 수 없습니다. 다시 동기화하여 확인하세요.","sessionIdNotAdopted": "원격 컴퓨터의 Cindy 버전이 호환되지 않습니다. 업데이트한 후 다시 시도하세요.",diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.jsonindex 505c234b78..02dfd6de28 100644--- a/apps/mobile/src/i18n/locales/zh-CN/session.json+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json@@ -7,6 +7,7 @@},"common": {"modelHiddenReselect": "{{model}} 已关闭,请选择已开启的模型后再发送。",+ "modelUnavailableReselect": "{{model}} 在这台电脑上已不可用,请重新选择模型后再发送。","cancel": "取消","dismissRecommendation": "关闭推荐","delete": "删除",@@ -297,6 +298,7 @@"selectDeviceError": "请选择设备。","enterProjectPath": "请输入电脑端项目路径。","enterModel": "请输入模型。",+ "modelLoading": "正在读取模型…","enterFirstMessageOrAttachment": "请输入首条消息或添加附件。","noSessionIdReturned": "未能确认远程电脑上的新任务已创建,请重新同步后查看。","sessionIdNotAdopted": "远程电脑上的 Cindy 版本不兼容,请更新后重试。",diff --git a/apps/mobile/src/i18n/locales/zh-TW/session.json b/apps/mobile/src/i18n/locales/zh-TW/session.jsonindex 45080b76d3..a85e293e87 100644--- a/apps/mobile/src/i18n/locales/zh-TW/session.json+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json@@ -7,6 +7,7 @@},"common": {"modelHiddenReselect": "{{model}} 已關閉,請選擇已開啟的模型後再傳送。",+ "modelUnavailableReselect": "{{model}} 在這台電腦上已無法使用,請重新選擇模型後再傳送。","cancel": "取消","dismissRecommendation": "關閉推薦","delete": "刪除",@@ -301,6 +302,7 @@"selectDeviceError": "請選擇裝置。","enterProjectPath": "請輸入電腦端專案路徑。","enterModel": "請輸入模型。",+ "modelLoading": "正在讀取模型…","enterFirstMessageOrAttachment": "請輸入首條訊息或新增附件。","noSessionIdReturned": "無法確認遠端電腦上的新任務已建立,請重新同步後查看。","sessionIdNotAdopted": "遠端電腦上的 Cindy 版本不相容,請更新後重試。",diff --git a/apps/mobile/src/session/newSession.ts b/apps/mobile/src/session/newSession.tsindex d30e12e25d..cf28443b89 100644--- a/apps/mobile/src/session/newSession.ts+++ b/apps/mobile/src/session/newSession.ts@@ -189,7 +189,9 @@ export const DEFAULT_NEW_SESSION_DRAFT: NewSessionDraft = {agentKind: 'claude-code',workspaceKind: 'project',workingDir: '',- model: 'claude-sonnet-4-6',+ // 不写死模型:由最近任务 / 被控端目录落定(见 isNewSessionRuntimePending),+ // 都拿不到时留空让用户自己选,不替用户挑一个电脑上未必可用的模型。+ model: '',providerId: null,effort: 'medium',// Claude 保留 Auto-review 种子默认;用户上次在新建页选过的档走@@ -199,12 +201,6 @@ export const DEFAULT_NEW_SESSION_DRAFT: NewSessionDraft = {firstMessage: '',};-const DEFAULT_MODELS: Record<NewSessionAgentKind, string> = {- 'claude-code': 'claude-sonnet-4-6',- codex: 'gpt-5.4',- pi: 'gpt-5.4',-};-/** 新建交互式会话的权限种子默认;三个 agent 都保留 Auto-review。 */export function defaultPermissionModeForNewSessionAgent(_agentKind: NewSessionAgentKind): string {return 'auto';@@ -218,7 +214,7 @@ export function withAgentDefaults(return {...draft,agentKind,- model: DEFAULT_MODELS[agentKind],+ model: '',permissionMode: defaultPermissionModeForNewSessionAgent(agentKind),// 换 agent → 来源选择作废(各 agent 的供应商集不同),回到默认路由由被控端定。providerId: null,@@ -460,7 +456,7 @@ export function validateModelProviderId(* 1) 来源仍有效(或本来就走默认路由)→ 原样保留;* 2) 失效但仍有其他已连接来源提供该模型 → 顶替为该来源(模型照用);* 3) 没有任何来源提供该模型 → 落目录首项(连同其 provider);- * 4) 目录为空 → 该 agent 内置默认模型 + 默认路由;+ * 4) 目录为空 → 模型留空 + 默认路由,由用户自己选;* catalogReady=false 时不评判,维持信任语义(见 validateModelProviderId)。* 通用于「跟随最近会话」的自动默认与「提交点 / 目录就绪」的草稿终检(codex review P2:* 提交终检时同样联合回退)。@@ -521,7 +517,17 @@ export function resolveRecentModelAndProvider(}const top = modelRows[0];if (top) return { model: top.model.id, providerId: top.provider.id };- return { model: DEFAULT_MODELS[agentKind], providerId: null };+ return { model: '', providerId: null };+}++/**+ * 提交终检不得产出空模型:目录里已没有所选模型、也没有可顶替的行时,+ * resolveRecentModelAndProvider 会回退为空;电脑端拒收空模型,此时中止创建让用户重选。+ * 提交路径(创建前终检 / 鉴权后重验)统一经此判断。+ */+export function assertSubmitModelResolved(resolved: { model: string }, selectedModel: string): void {+ if (resolved.model.trim()) return;+ throw new Error(i18n.t('session.common.modelUnavailableReselect', { model: selectedModel }));}/**@@ -682,8 +688,8 @@ export function reconcileEffortAfterFallback(baseEffort: string,): string {const sectionModel = findSectionModelRow(modelRows, next.model, next.providerId)?.model;- // 无匹配行 = 回退到内置默认模型(目录为空/loaded-but-empty):旧自定义模型的档位- // 对新内置模型无效——省略 effort(创建时省略该字段,由被控端取默认),不得沿用+ // 无匹配行 = 目录为空/loaded-but-empty,模型已回退为空:旧模型的档位+ // 对之后选的模型无效——省略 effort(创建时省略该字段,由被控端取默认),不得沿用// (Codex review P2:沿用会向不支持该档位的模型发送非法 effort)。return sectionModel ? reconcileEffortForModel(sectionModel, baseEffort) : '';}@@ -746,15 +752,16 @@ export function pickMostRecentSessionRuntime(* 1) 该 agent 的最近一次会话模型(pickMostRecentSessionRuntime,按 deviceId scope);* 2) 否则取区域门控后的新任务默认;无标记再取该 agent 的模型列表最上面那个* (modelRows[0] —— providers 已加载时同步可得,与下拉渲染的第一项一致);- * 3) 否则该 agent 的内置默认 DEFAULT_MODELS[agentKind]。+ * 3) 被控端明确不支持目录(旧电脑)时取它能力表里的模型:区域默认标记优先,否则首个;+ * 4) 否则留空(不写死模型),由用户自己选。* providerId 跟随 model 同源:* 1) 跟随最近会话 → 继承该会话的来源(validateModelProviderId 校验:目录已就绪且来源* 已删/不再提供该模型时清空回默认路由;同设备+同 agent 范围,供应商集天然兼容);* 2) 取列表首项 → 该行的 provider(modelRows[0].provider.id);- * 3) 内置默认兜底 → null(默认路由)。+ * 3) 能力表模型 / 都没有 → null(默认路由)。* effort:reconcile 到目标 model 的合法档(reconcileEffortForModel,base = 最近会话 effort ?? 当前 effort,* SectionModel 按 (providerId, modelId) 精确匹配行——同模型多来源时不串档);- * 拿不到目标 model 对应的 SectionModel(model 不在 modelRows 里,如走了 DEFAULT_MODELS 兜底或历史模型已下架)+ * 拿不到目标 model 对应的 SectionModel(model 不在 modelRows 里,如模型留空或历史模型已下架)* 时保留 base effort 不动。*/export function pickAgentDefaultRuntime(args: {@@ -766,8 +773,11 @@ export function pickAgentDefaultRuntime(args: {/** 供应商目录是否已就绪(加载完成);未就绪时来源校验信任最近会话(见 validateModelProviderId)。 */catalogReady: boolean;visibilityOverrides?: Record<string, boolean> | null;+ /** 仅当被控端明确不支持 provider:list 时传入该 agent 的能力表模型(与 resolveNewSessionAutoDefault 同口径)。 */+ flatModels?: readonly MobileModelOption[];}): NewSessionRuntime {const { agentKind, sessions, modelRows, currentEffort, deviceId, catalogReady } = args;+ let flatModel: MobileModelOption | undefined;const recent = pickMostRecentSessionRuntime(sessions, { deviceId, agentKind });const baseEffort = recent?.effort ?? currentEffort;let model: string;@@ -793,24 +803,52 @@ export function pickAgentDefaultRuntime(args: {?? modelRows[0];model = chosenRow.model.id;providerId = chosenRow.provider.id;+ } else if (args.flatModels?.length) {+ flatModel = pickRegionalNewSessionDefault(args.flatModels, agentKind) ?? args.flatModels[0];+ model = flatModel.id;+ providerId = null;} else {- model = DEFAULT_MODELS[agentKind];+ model = '';providerId = null;}// 目录未就绪时不做 effort 校准:catalogReady=false 时 modelRows 可能是上一设备// 的残留行,findSectionModelRow 的 modelId 回退会按错误来源校准 effort;新目录// 确认原 (provider, model) 有效后组合未变化又不再重校准,用户可能在能力表到达前// 提交该来源不支持的档位(codex review P2)。未就绪时保留最近任务的 effort。- // catalogReady 且无匹配行 = 回退到内置默认(目录为空/模型下架):旧自定义模型的- // 档位对新内置模型无效——省略 effort,由被控端取默认(codex review P2:模型无行+ // catalogReady 且无匹配行 = 目录为空/模型下架:旧自定义模型的+ // 档位对之后选的模型无效——省略 effort,由被控端取默认(codex review P2:模型无行// 回退时不得沿用旧档位;与 reconcileEffortAfterFallback 的 no-row 口径一致)。const sectionModel = catalogReady ? findSectionModelRow(modelRows, model, providerId)?.model : undefined;const effort = sectionModel? reconcileEffortForModel(sectionModel, baseEffort)- : catalogReady && !modelNeedsReselection(args.visibilityOverrides, agentKind, model, providerId) ? '' : baseEffort;+ : flatModel+ ? reconcileEffortForModel(flatModel, baseEffort)+ : catalogReady && !modelNeedsReselection(args.visibilityOverrides, agentKind, model, providerId) ? '' : baseEffort;return { agentKind, model, effort, providerId };}+/**+ * 新建页的模型是否仍在等数据落定(草稿初值为空 / 恢复上次 agent 时数据未到)。+ * 等待期间模型药丸显示「正在读取模型」且不能创建。+ * 落定 = 自动默认或恢复上次 agent 已按最近任务 / 目录写入模型,或用户自己改过运行配置。+ * 数据不会再来时结束等待:目录拉取失败(含旧被控端不支持目录)、或目录已就绪但为空;+ * 此时若仍没有模型,药丸显示「未选择模型」,由用户自己选。+ */+export function isNewSessionRuntimePending(input: {+ settled: boolean;+ userTouched: boolean;+ remoteAgentPicked: boolean;+ selectedDeviceId: string;+ catalogReady: boolean;+ catalogFailed: boolean;+ modelRowCount: number;+}): boolean {+ if (input.settled || input.userTouched || input.remoteAgentPicked) return false;+ if (!input.selectedDeviceId) return false;+ if (input.catalogFailed) return false;+ return !(input.catalogReady && input.modelRowCount === 0);+}+/*** 「恢复上次选过的 agent」是否仍待落定:有记忆的 agent、模型尚未落定,且当前设备就是恢复* 目标(没有偏好设备 = 不限设备)。@@ -855,7 +893,7 @@ export function nextStoredAgentRestoreStep(input: {/*** 恢复上次的 agent 时,是否已有足够数据选模型(pickAgentDefaultRuntime 的输入):* 供应商目录已就绪 / 被控端明确不支持目录,或该设备上已有这个 agent 的最近任务。- * 两者都没有时 pickAgentDefaultRuntime 只能落到内置兜底模型(Claude 为 Sonnet 4.6),+ * 两者都没有时 pickAgentDefaultRuntime 选不出模型(留空),* 这时只先恢复 agent(见 nextStoredAgentRestoreStep),模型等数据到了再补。* 不能用 `loading === false` 代替:useDeviceProviders 的 loading 初值就是 false,拉取失败后也是。*/