Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 支持配置辅助模型
david0e010f4f7635
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 60922494d4..032c2610d1 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -684,6 +684,7 @@ import {resetCacheForNewDb as resetChatEmbedderCache,} from './embedders/chat-history-embedder.js';import { registerMakerTitleIpc } from './maker-ipc/title.js';+import { registerAuxiliaryModelSettingsIpc } from './maker-ipc/auxiliary-model-settings.js';import { registerContactsIpc } from './maker-ipc/contacts-ipc.js';import { disposeDesktopContactsManager } from './maker-host/maker-contacts-host.js';import { registerMakerHelpIpc } from './maker-ipc/help.js';@@ -5093,6 +5094,7 @@ const registerIpcHandlers = () => {onProviderModelAutoRefreshConfigured: markMakerProviderRefreshConfigured,});registerMakerTitleIpc({ isSessionTurnPendingCompletion });+ registerAuxiliaryModelSettingsIpc();registerMakerHelpIpc(ipcMaker);registerHelpFeedbackIpc();registerMakerPlanWriteIpc();diff --git a/apps/desktop/src/main/im/__tests__/fbotTitleAuxiliaryModel.test.ts b/apps/desktop/src/main/im/__tests__/fbotTitleAuxiliaryModel.test.tsnew file mode 100644index 0000000000..9ca26966d5--- /dev/null+++ b/apps/desktop/src/main/im/__tests__/fbotTitleAuxiliaryModel.test.ts@@ -0,0 +1,62 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const h = vi.hoisted(() => ({+ generatedTitle: null as string | null,+ selection: null as null | { pin: string },+ requestUtilityText: vi.fn(),+}));++vi.mock('../../maker-host/session-storage.js', () => ({+ desktopSessionStorage: { update: vi.fn() },+}));++vi.mock('../../maker-ipc/title.js', () => ({+ generateMakerSessionTitle: vi.fn(async () => h.generatedTitle),+}));++vi.mock('../../utility-model/auxiliary-model-settings-store.js', () => ({+ readAuxiliaryModelSelection: () => h.selection,+}));++vi.mock('../../utility-model/oneShotCandidates.js', () => ({+ requestUtilityText: (...args: unknown[]) => h.requestUtilityText(...args),+}));++vi.mock('../../maker-host/index.js', () => ({+ getMaker: () => ({}),+}));++vi.mock('../shared/sessionBroadcast.js', () => ({+ broadcastSessionPatched: vi.fn(),+}));++import { generateImSessionTitleText } from '../shared/fbotTitle.js';++beforeEach(() => {+ vi.clearAllMocks();+ h.generatedTitle = null;+ h.selection = null;+ h.requestUtilityText.mockResolvedValue({+ ok: true,+ text: '旧 utility 兜底标题',+ providerId: 'xd',+ model: 'fallback',+ transport: 'litellm-chat-completions',+ });+});++describe('IM task title auxiliary model boundary', () => {+ it('keeps the historical utility fallback in automatic mode', async () => {+ await expect(generateImSessionTitleText('task-1', '第一条消息')).resolves.toBe(+ '旧 utility 兜底标题',+ );+ expect(h.requestUtilityText).toHaveBeenCalledTimes(1);+ });++ it('fails closed when an explicit global title model was selected', async () => {+ h.selection = { pin: 'cat:openrouter:codex:openai/gpt-5-mini' };++ await expect(generateImSessionTitleText('task-1', '第一条消息')).resolves.toBeNull();+ expect(h.requestUtilityText).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/im/shared/fbotTitle.ts b/apps/desktop/src/main/im/shared/fbotTitle.tsindex c05008ffa1..1c55ee9177 100644--- a/apps/desktop/src/main/im/shared/fbotTitle.ts+++ b/apps/desktop/src/main/im/shared/fbotTitle.ts@@ -19,6 +19,7 @@import { desktopSessionStorage } from '../../maker-host/session-storage';import { generateMakerSessionTitle } from '../../maker-ipc/title';+import { readAuxiliaryModelSelection } from '../../utility-model/auxiliary-model-settings-store';import { broadcastSessionPatched } from './sessionBroadcast';export { broadcastSessionPatched } from './sessionBroadcast';@@ -72,6 +73,9 @@ export async function generateImSessionTitleText(): Promise<string | null> {const generated = (await generateMakerSessionTitle(seedText, 'claude-code', sessionId))?.trim();if (generated) return generated;+ // An explicit auxiliary model is an exact, fail-closed route. Do not hide a+ // failure by falling through to the legacy utility-model candidate chain.+ if (readAuxiliaryModelSelection('sessionTitleModel')) return null;try {// 动态 import 保持本模块的静态依赖链不继续膨胀(cindySlot 同款)。const [{ requestUtilityText }, { getMaker }] = await Promise.all([diff --git a/apps/desktop/src/main/maker-host/__tests__/auxiliary-title-one-shot.test.ts b/apps/desktop/src/main/maker-host/__tests__/auxiliary-title-one-shot.test.tsnew file mode 100644index 0000000000..9fb0540a57--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/auxiliary-title-one-shot.test.ts@@ -0,0 +1,131 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const h = vi.hoisted(() => ({+ selection: null as null | {+ pin: string;+ providerId: string;+ agentKind: 'codex' | 'claude-code';+ model: string;+ },+ requestText: vi.fn(),+ generateLegacy: vi.fn(),+ generateLegacyResult: vi.fn(),+}));++vi.mock('../../logger.js', () => ({+ createLogger: () => ({ warn: vi.fn() }),+}));++vi.mock('../../utility-model/auxiliary-model-settings-store.js', () => ({+ readAuxiliaryModelSelection: () => h.selection,+}));++vi.mock('../../utility-model/oneShotCandidates.js', () => ({+ requestExplicitUtilityText: (...args: unknown[]) => h.requestText(...args),+}));++vi.mock('../title-one-shot.js', () => ({+ generateTitleViaProvider: (...args: unknown[]) => h.generateLegacy(...args),+ generateTitleViaProviderResult: (...args: unknown[]) => h.generateLegacyResult(...args),+}));++import {+ generateTitleWithAuxiliaryModel,+ generateTitleWithAuxiliaryModelResult,+} from '../auxiliary-title-one-shot.js';++const REQUEST = {+ sessionId: 'task-1',+ agentKind: 'pi' as const,+ prompt: '给这项工作起名',+};++const SELECTION = {+ pin: 'cat:openrouter:codex:openai/gpt-5-mini',+ providerId: 'openrouter',+ agentKind: 'codex' as const,+ model: 'openai/gpt-5-mini',+};++beforeEach(() => {+ vi.clearAllMocks();+ h.selection = null;+ h.generateLegacy.mockResolvedValue('旧自动路由标题');+ h.generateLegacyResult.mockResolvedValue({ status: 'ok', title: '旧自动路由标题' });+});++describe('auxiliary task-title routing', () => {+ it('preserves the historical route in automatic mode for every task agent', async () => {+ await expect(generateTitleWithAuxiliaryModel(REQUEST)).resolves.toBe('旧自动路由标题');++ expect(h.generateLegacy).toHaveBeenCalledWith(REQUEST, {});+ expect(h.requestText).not.toHaveBeenCalled();+ });++ it('uses one exact configured catalog route independently of the task agent', async () => {+ h.selection = { ...SELECTION };+ h.requestText.mockImplementation(async (_prompt: string, options: Record<string, unknown>) => {+ const allowed = await (+ options.beforeDispatch as (route: typeof SELECTION) => Promise<boolean>+ )(SELECTION);+ return allowed+ ? {+ ok: true,+ text: '通用任务命名',+ providerId: SELECTION.providerId,+ model: SELECTION.model,+ transport: 'litellm-chat-completions',+ }+ : { ok: false, reason: 'all_candidates_failed', attempts: [] };+ });++ await expect(generateTitleWithAuxiliaryModel(REQUEST)).resolves.toBe('通用任务命名');+ expect(h.requestText).toHaveBeenCalledWith(+ REQUEST.prompt,+ expect.objectContaining({+ providerId: 'openrouter',+ agentKind: 'codex',+ model: 'openai/gpt-5-mini',+ }),+ );+ expect(h.generateLegacy).not.toHaveBeenCalled();+ });++ it('fails closed instead of falling back when the configured model fails', async () => {+ h.selection = { ...SELECTION };+ h.requestText.mockResolvedValue({+ ok: false,+ reason: 'all_candidates_failed',+ attempts: [],+ });++ await expect(generateTitleWithAuxiliaryModel(REQUEST)).resolves.toBeNull();+ await expect(generateTitleWithAuxiliaryModelResult(REQUEST)).resolves.toEqual({+ status: 'failed',+ });+ expect(h.generateLegacy).not.toHaveBeenCalled();+ expect(h.generateLegacyResult).not.toHaveBeenCalled();+ });++ it('cancels dispatch when the selected setting changes during credential work', async () => {+ h.selection = { ...SELECTION };+ h.requestText.mockImplementation(async (_prompt: string, options: Record<string, unknown>) => {+ h.selection = null;+ const allowed = await (+ options.beforeDispatch as (route: typeof SELECTION) => Promise<boolean>+ )(SELECTION);+ return allowed+ ? {+ ok: true,+ text: '不应采用',+ providerId: SELECTION.providerId,+ model: SELECTION.model,+ transport: 'litellm-chat-completions',+ }+ : { ok: false, reason: 'all_candidates_failed', attempts: [] };+ });++ await expect(generateTitleWithAuxiliaryModel(REQUEST)).resolves.toBeNull();+ expect(h.generateLegacy).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/maker-host/auxiliary-title-one-shot.ts b/apps/desktop/src/main/maker-host/auxiliary-title-one-shot.tsnew file mode 100644index 0000000000..f07b0ed277--- /dev/null+++ b/apps/desktop/src/main/maker-host/auxiliary-title-one-shot.ts@@ -0,0 +1,145 @@+/**+ * Session-title routing with an optional global catalog pin.+ *+ * Automatic mode delegates byte-for-byte to the existing session/provider+ * title path. An explicit selection is a single exact route and fails closed;+ * callers retain their existing heuristic/manual-error fallback semantics.+ */++import type { AgentKind } from '@cindy/maker-core';++import { createLogger } from '../logger.js';+import type { AuxiliaryModelSelection } from '../utility-model/auxiliary-model-settings-store.js';+import type {+ requestExplicitUtilityText,+ UtilityTextDispatchRoute,+} from '../utility-model/oneShotCandidates.js';+import type {+ generateTitleViaProvider,+ generateTitleViaProviderResult,+ TitleOneShotDeps,+ TitleOneShotResult,+} from './title-one-shot.js';+import { validateTitleOutput } from './title-output-validation.js';++const log = createLogger('maker-host/auxiliary-title-one-shot');++const AUXILIARY_TITLE_TIMEOUT_MS = 12_000;+const AUXILIARY_TITLE_MAX_TOKENS = 32;+const AUXILIARY_TITLE_OUTPUT_MAX_CHARS = 256;+const AUXILIARY_TITLE_VISUAL_MAX_CHARS = 40;++interface AuxiliaryTitleRuntimeDeps {+ readSelection: (+ key: 'sessionTitleModel',+ ) => AuxiliaryModelSelection | null | Promise<AuxiliaryModelSelection | null>;+ requestText: typeof requestExplicitUtilityText;+ generateLegacy: typeof generateTitleViaProvider;+ generateLegacyResult: typeof generateTitleViaProviderResult;+}++const DEFAULT_DEPS: AuxiliaryTitleRuntimeDeps = {+ // The settings store resolves owner-scoped Electron paths. Load it only when+ // title generation actually runs, not while title IPC modules are registered.+ readSelection: async (key) => {+ const { readAuxiliaryModelSelection } = await import(+ '../utility-model/auxiliary-model-settings-store.js'+ );+ return readAuxiliaryModelSelection(key);+ },+ // Keep the heavyweight utility-model/provider runtime out of title.ts's+ // startup import graph. It also lets lightweight title IPC tests provide+ // their existing Electron mocks without loading app-bound runtime config.+ requestText: async (prompt, opts) => {+ const { requestExplicitUtilityText: requestText } = await import(+ '../utility-model/oneShotCandidates.js'+ );+ return requestText(prompt, opts);+ },+ generateLegacy: async (args, deps) => {+ const { generateTitleViaProvider: generate } = await import('./title-one-shot.js');+ return generate(args, deps);+ },+ generateLegacyResult: async (args, deps) => {+ const { generateTitleViaProviderResult: generate } = await import('./title-one-shot.js');+ return generate(args, deps);+ },+};++type TitleRequest = {+ sessionId: string;+ agentKind: AgentKind;+ prompt: string;+ signal?: AbortSignal;+};++function selectionMatchesRoute(+ selection: AuxiliaryModelSelection,+ route: UtilityTextDispatchRoute,+): boolean {+ return (+ selection.providerId === route.providerId &&+ selection.agentKind === route.agentKind &&+ selection.model === route.model+ );+}++async function generateExplicitTitle(+ args: TitleRequest,+ selection: AuxiliaryModelSelection,+ deps: AuxiliaryTitleRuntimeDeps,+): Promise<TitleOneShotResult> {+ const result = await deps.requestText(args.prompt, {+ providerId: selection.providerId,+ agentKind: selection.agentKind,+ model: selection.model,+ maxTokens: AUXILIARY_TITLE_MAX_TOKENS,+ timeoutMs: AUXILIARY_TITLE_TIMEOUT_MS,+ signal: args.signal,+ // Settings may change while OAuth refresh/credential discovery awaits. The+ // paid request is dispatched only if the same exact pin is still active.+ beforeDispatch: async (route) => {+ const current = await deps.readSelection('sessionTitleModel');+ return current?.pin === selection.pin && selectionMatchesRoute(current, route);+ },+ });+ if (!result.ok) {+ log.warn('explicit auxiliary title model failed', {+ providerId: selection.providerId,+ model: selection.model,+ reason: result.reason,+ });+ return { status: 'failed' };+ }++ // Validate the complete response before the historical 40-character visual+ // truncation, matching title-one-shot's persisted-content boundary.+ const normalized = validateTitleOutput(result.text, AUXILIARY_TITLE_OUTPUT_MAX_CHARS);+ const title = normalized+ ? Array.from(normalized).slice(0, AUXILIARY_TITLE_VISUAL_MAX_CHARS).join('')+ : null;+ return title ? { status: 'ok', title } : { status: 'failed' };+}++export async function generateTitleWithAuxiliaryModel(+ args: TitleRequest,+ legacyDeps: TitleOneShotDeps = {},+ runtimeDeps: Partial<AuxiliaryTitleRuntimeDeps> = {},+): Promise<string | null> {+ const deps = { ...DEFAULT_DEPS, ...runtimeDeps };+ const selection = await deps.readSelection('sessionTitleModel');+ if (!selection) return deps.generateLegacy(args, legacyDeps);+ const result = await generateExplicitTitle(args, selection, deps);+ return result.status === 'ok' ? result.title : null;+}++export async function generateTitleWithAuxiliaryModelResult(+ args: TitleRequest,+ legacyDeps: TitleOneShotDeps = {},+ runtimeDeps: Partial<AuxiliaryTitleRuntimeDeps> = {},+): Promise<TitleOneShotResult> {+ const deps = { ...DEFAULT_DEPS, ...runtimeDeps };+ const selection = await deps.readSelection('sessionTitleModel');+ if (!selection) return deps.generateLegacyResult(args, legacyDeps);+ return generateExplicitTitle(args, selection, deps);+}diff --git a/apps/desktop/src/main/maker-ipc/__tests__/autoTitleIpcBoundary.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/autoTitleIpcBoundary.test.tsindex 81d8281b94..6b57c55042 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/autoTitleIpcBoundary.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/autoTitleIpcBoundary.test.ts@@ -64,6 +64,9 @@ vi.mock('../../maker-host/title-one-shot.js', () => ({generateTitleViaProvider: h.generateTitle,generateTitleViaProviderResult: h.generateTitleResult,}));+vi.mock('../../utility-model/auxiliary-model-settings-store.js', () => ({+ readAuxiliaryModelSelection: vi.fn(() => null),+}));vi.mock('../../messagePersistBroadcaster.js', () => ({drainPersistQueue: h.drainPersistQueue,}));diff --git a/apps/desktop/src/main/maker-ipc/__tests__/auxiliaryModelSettings.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/auxiliaryModelSettings.test.tsnew file mode 100644index 0000000000..c4b8e6a073--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/auxiliaryModelSettings.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it, vi } from 'vitest';++vi.mock('electron', () => ({+ ipcMain: { handle: vi.fn() },+}));++vi.mock('../../logger.js', () => ({+ createLogger: () => ({ warn: vi.fn() }),+}));++vi.mock('../../maker-host/active-catalog.js', () => ({+ getActiveCatalog: () => ({ providers: [] }),+}));++vi.mock('../../maker-host/model-disable-store.js', () => ({+ readModelDisableOverrides: () => ({ disabledModels: {}, disabledProviders: {} }),+}));++vi.mock('../../maker-host/provider-order-store.js', () => ({+ readProviderOrder: () => [],+}));++vi.mock('../../utility-model/auxiliary-model-settings-store.js', () => ({+ readAuxiliaryModelSettingsState: vi.fn(),+ writeAuxiliaryModelSettingsPatch: vi.fn(),+}));++vi.mock('../../utility-model/oneshotProviderUsability.js', () => ({+ hasOneshotProviderCredential: () => false,+}));++vi.mock('../../security/trustedAppRenderer.js', () => ({+ assertTrustedAppRendererEvent: vi.fn(),+}));++import {+ buildAuxiliaryModelOptions,+ parseAuxiliaryModelSettingsPatch,+} from '../auxiliary-model-settings.js';++const PIN = 'cat:openrouter:codex:openai/gpt-5-mini';++function catalog() {+ return {+ providers: [+ {+ id: 'openrouter',+ name: 'OpenRouter',+ source: 'user',+ agents: ['codex'],+ auth: { method: 'apiKey' },+ routing: {+ codex: {+ upstream: 'https://openrouter.example/v1',+ authStrategy: 'api-key-header',+ wireProtocol: 'openai-chat',+ },+ },+ models: {+ codex: [+ {+ id: 'openai/gpt-5-mini',+ name: 'GPT 5 mini',+ contextWindow: 100_000,+ group: 'custom:openrouter',+ },+ ],+ },+ },+ ],+ } as never;+}++describe('auxiliary model settings IPC helpers', () => {+ it('accepts only known canonical pins and null resets', () => {+ const allowed = new Set([PIN]);+ expect(parseAuxiliaryModelSettingsPatch({ sessionTitleModel: PIN }, allowed)).toEqual({+ sessionTitleModel: PIN,+ });+ expect(+ parseAuxiliaryModelSettingsPatch({ promptRecommendationModel: null }, allowed),+ ).toEqual({ promptRecommendationModel: null });++ expect(() =>+ parseAuxiliaryModelSettingsPatch({ sessionTitleModel: ` ${PIN}` }, allowed),+ ).toThrow(/canonical catalog model pin/);+ expect(() =>+ parseAuxiliaryModelSettingsPatch(+ { sessionTitleModel: 'cat:other:codex:model' },+ allowed,+ ),+ ).toThrow(/currently routable/);+ expect(() =>+ parseAuxiliaryModelSettingsPatch({ unexpected: PIN }, allowed),+ ).toThrow(/invalid keys/);+ });++ it('keeps a selected but credential-unavailable route visible and removable', () => {+ const options = buildAuxiliaryModelOptions({+ settings: { sessionTitleModel: PIN, promptRecommendationModel: null },+ catalog: catalog(),+ overrides: { disabledModels: {}, disabledProviders: {} },+ hasCredential: () => false,+ });++ expect(options).toEqual([+ expect.objectContaining({+ id: PIN,+ providerId: 'openrouter',+ modelId: 'openai/gpt-5-mini',+ available: false,+ }),+ ]);+ });++ it('does not expose a stale selection as available when it left the catalog', () => {+ const stalePin = 'cat:removed:claude-code:old-model';+ const options = buildAuxiliaryModelOptions({+ settings: { sessionTitleModel: stalePin, promptRecommendationModel: null },+ catalog: catalog(),+ overrides: { disabledModels: {}, disabledProviders: {} },+ hasCredential: () => true,+ });++ expect(options.find((option) => option.id === stalePin)).toMatchObject({+ available: false,+ providerId: 'removed',+ agentKind: 'claude-code',+ modelId: 'old-model',+ });+ });+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/promptPredictionRevision.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/promptPredictionRevision.test.tsindex fba8e690ea..eb5918875d 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/promptPredictionRevision.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/promptPredictionRevision.test.ts@@ -17,6 +17,14 @@ const h = vi.hoisted(() => ({providers: [{ id: 'provider-1' }],resolvedProviderId: 'provider-1',afterDispatch: null as null | (() => void),+ auxiliarySelection: null as null | {+ pin: string;+ providerId: string;+ agentKind: 'codex' | 'claude-code';+ model: string;+ },+ legacyCalls: 0,+ explicitRequest: vi.fn(),}));vi.mock('../../logger.js', () => ({@@ -69,6 +77,7 @@ vi.mock('../../maker-host/title-one-shot.js', () => ({}) => Promise<boolean>;},) => {+ h.legacyCalls += 1;h.beforeDispatchCalls += 1;const allowed = await deps.beforeDispatch?.({sessionId: request.sessionId,@@ -80,6 +89,14 @@ vi.mock('../../maker-host/title-one-shot.js', () => ({},}));+vi.mock('../../utility-model/auxiliary-model-settings-store.js', () => ({+ readAuxiliaryModelSelection: () => h.auxiliarySelection,+}));++vi.mock('../../utility-model/oneShotCandidates.js', () => ({+ requestExplicitUtilityText: (...args: unknown[]) => h.explicitRequest(...args),+}));+import { generatePromptPrediction } from '../promptPrediction.js';import {notePromptPredictionSessionStopped,@@ -119,6 +136,9 @@ beforeEach(() => {h.providers = [{ id: 'provider-1' }];h.resolvedProviderId = 'provider-1';h.afterDispatch = null;+ h.auxiliarySelection = null;+ h.legacyCalls = 0;+ h.explicitRequest.mockReset();h.rows = [{ ...VALID_ROW }, { ...VALID_ROW }];resetPromptPredictionStopLedgerForTests();});@@ -174,4 +194,52 @@ describe('prompt prediction completion revision guard', () => {expect(h.beforeDispatchCalls).toBe(1);expect(h.dbReads).toBe(2);});++ it('uses the independently configured recommendation route without the legacy task provider', async () => {+ h.auxiliarySelection = {+ pin: 'cat:openrouter:codex:openai/gpt-5-mini',+ providerId: 'openrouter',+ agentKind: 'codex',+ model: 'openai/gpt-5-mini',+ };+ h.explicitRequest.mockImplementation(+ async (_prompt: string, options: Record<string, unknown>) => {+ h.beforeDispatchCalls += 1;+ const allowed = await (+ options.beforeDispatch as (route: {+ providerId: string;+ agentKind: string;+ model: string;+ }) => Promise<boolean>+ )({+ providerId: 'openrouter',+ agentKind: 'codex',+ model: 'openai/gpt-5-mini',+ });+ return allowed+ ? {+ ok: true,+ text: '继续补测试',+ providerId: 'openrouter',+ model: 'openai/gpt-5-mini',+ transport: 'litellm-chat-completions',+ }+ : { ok: false, reason: 'all_candidates_failed', attempts: [] };+ },+ );++ await expect(predict()).resolves.toBe('继续补测试');+ expect(h.explicitRequest).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({+ providerId: 'openrouter',+ agentKind: 'codex',+ model: 'openai/gpt-5-mini',+ systemPrompt: expect.any(String),+ }),+ );+ expect(h.explicitRequest.mock.calls[0]?.[1]).not.toHaveProperty('reasoningEffort');+ expect(h.legacyCalls).toBe(0);+ expect(h.dbReads).toBe(2);+ });});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/regenerateSessionTitle.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/regenerateSessionTitle.test.tsindex 6abecaadea..ec1bc2c33c 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/regenerateSessionTitle.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/regenerateSessionTitle.test.ts@@ -28,6 +28,9 @@ vi.mock('../../maker-host/title-one-shot.js', () => ({generateTitleViaProvider: vi.fn(),generateTitleViaProviderResult: vi.fn(),}));+vi.mock('../../utility-model/auxiliary-model-settings-store.js', () => ({+ readAuxiliaryModelSelection: vi.fn(() => null),+}));vi.mock('../../i18n.js', () => ({getResolvedMainLocale: vi.fn(() => 'en'),}));diff --git a/apps/desktop/src/main/maker-ipc/auxiliary-model-settings.ts b/apps/desktop/src/main/maker-ipc/auxiliary-model-settings.tsnew file mode 100644index 0000000000..46769b5f6a--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/auxiliary-model-settings.ts@@ -0,0 +1,177 @@+/** Settings IPC for global auxiliary text model choices. */++import { ipcMain } from 'electron';+import type { Catalog, ModelDisableOverrides } from '@cindy/model-providers';++import {+ isValidAuxiliaryModelPinInput,+ type AuxiliaryModelOption,+ type AuxiliaryModelSettings,+ type AuxiliaryModelSettingsPatch,+ type AuxiliaryModelSettingsState,+} from '../../shared/auxiliaryModelSettings.js';+import { decodeCatalogModelPin } from '../../shared/catalogModelPin.js';+import { isIpcError } from '../../shared/ipc-errors.js';+import { createLogger } from '../logger.js';+import { getActiveCatalog } from '../maker-host/active-catalog.js';+import { readModelDisableOverrides } from '../maker-host/model-disable-store.js';+import { readProviderOrder } from '../maker-host/provider-order-store.js';+import {+ readAuxiliaryModelSettingsState,+ writeAuxiliaryModelSettingsPatch,+} from '../utility-model/auxiliary-model-settings-store.js';+import { hasOneshotProviderCredential } from '../utility-model/oneshotProviderUsability.js';+import {+ buildTextOneshotPinOptions,+ type OneshotCredentialProbe,+ type TextOneshotPinOption,+} from '../utility-model/textOneshotPinOptions.js';+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';+import { throwIpcError } from '../utils/ipcValidate.js';+import { MAKER_INVOKE } from './channels.js';++const log = createLogger('maker-ipc/auxiliary-model-settings');++function toWireOption(option: TextOneshotPinOption, available: boolean): AuxiliaryModelOption {+ if (option.agentKind !== 'codex' && option.agentKind !== 'claude-code') {+ throw new Error(`unsupported auxiliary model agent: ${option.agentKind}`);+ }+ return {+ ...option,+ agentKind: option.agentKind,+ available,+ };+}++/**+ * Return currently usable choices plus any persisted-but-unavailable selections.+ * The latter remain visible and removable without becoming selectable elsewhere.+ */+export function buildAuxiliaryModelOptions(args: {+ settings: AuxiliaryModelSettings;+ catalog: Catalog;+ overrides: ModelDisableOverrides | undefined;+ providerOrder?: readonly string[];+ hasCredential?: OneshotCredentialProbe;+}): AuxiliaryModelOption[] {+ const available = buildTextOneshotPinOptions(+ args.catalog,+ args.overrides,+ args.providerOrder,+ args.hasCredential,+ );+ const availableIds = new Set(available.map((option) => option.id));+ const result = available.map((option) => toWireOption(option, true));++ const allRoutable = buildTextOneshotPinOptions(args.catalog, args.overrides, args.providerOrder);+ const allById = new Map(allRoutable.map((option) => [option.id, option]));+ const persistedPins = new Set(+ [args.settings.sessionTitleModel, args.settings.promptRecommendationModel].filter(+ (pin): pin is string => typeof pin === 'string',+ ),+ );+ for (const pin of persistedPins) {+ if (availableIds.has(pin)) continue;+ const known = allById.get(pin);+ if (known) {+ result.push(toWireOption(known, false));+ continue;+ }+ const decoded = decodeCatalogModelPin(pin);+ if (!decoded) continue;+ result.push({+ id: pin,+ label: `${decoded.model} · ${decoded.providerId}`,+ group: decoded.providerId,+ providerId: decoded.providerId,+ agentKind: decoded.agentKind,+ modelId: decoded.model,+ modelName: decoded.model,+ budget: false,+ subscription: false,+ agentSuffix: decoded.agentKind === 'codex' ? 'Codex' : 'Claude Code',+ available: false,+ });+ }+ return result;+}++function settingsWire(): AuxiliaryModelSettingsState {+ const state = readAuxiliaryModelSettingsState();+ return {+ ...state.value,+ isCustomized: state.isCustomized,+ customizedKeys: state.customizedKeys,+ defaults: state.defaults,+ options: buildAuxiliaryModelOptions({+ settings: state.value,+ catalog: getActiveCatalog(),+ overrides: readModelDisableOverrides(),+ providerOrder: readProviderOrder(),+ hasCredential: hasOneshotProviderCredential,+ }),+ };+}++export function parseAuxiliaryModelSettingsPatch(+ raw: unknown,+ allowedPins: ReadonlySet<string>,+): AuxiliaryModelSettingsPatch {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {+ throwIpcError('INVALID_PARAMS', 'auxiliary model settings patch required');+ }+ const input = raw as Record<string, unknown>;+ const allowedKeys = new Set(['sessionTitleModel', 'promptRecommendationModel']);+ const keys = Object.keys(input);+ if (keys.length === 0 || keys.some((key) => !allowedKeys.has(key))) {+ throwIpcError('INVALID_PARAMS', 'auxiliary model settings patch has invalid keys');+ }++ const patch: AuxiliaryModelSettingsPatch = {};+ for (const key of keys) {+ const value = input[key];+ if (!isValidAuxiliaryModelPinInput(value)) {+ throwIpcError('INVALID_PARAMS', `${key} must be null or a canonical catalog model pin`);+ }+ if (value !== null && !allowedPins.has(value)) {+ throwIpcError('INVALID_PARAMS', `${key} is not a currently routable catalog model`);+ }+ patch[key as keyof AuxiliaryModelSettingsPatch] = value;+ }+ return patch;+}++export function registerAuxiliaryModelSettingsIpc(): void {+ ipcMain.handle(MAKER_INVOKE.AUXILIARY_MODEL_SETTINGS_GET, (event) => {+ assertTrustedAppRendererEvent(event);+ try {+ return settingsWire();+ } catch (error) {+ if (isIpcError(error)) throw error;+ log.warn('failed to read auxiliary model settings', { error });+ throwIpcError('INTERNAL', 'Failed to read auxiliary model settings');+ }+ });++ ipcMain.handle(MAKER_INVOKE.AUXILIARY_MODEL_SETTINGS_SET, async (event, rawPatch: unknown) => {+ assertTrustedAppRendererEvent(event);+ try {+ // Persisted intent ignores transient credential readiness, while execution+ // still validates credentials and fails closed immediately before dispatch.+ const allowedPins = new Set(+ buildTextOneshotPinOptions(+ getActiveCatalog(),+ readModelDisableOverrides(),+ readProviderOrder(),+ ).map((option) => option.id),+ );+ const patch = parseAuxiliaryModelSettingsPatch(rawPatch, allowedPins);+ await writeAuxiliaryModelSettingsPatch(patch);+ return settingsWire();+ } catch (error) {+ if (isIpcError(error)) throw error;+ log.warn('failed to write auxiliary model settings', { error });+ throwIpcError('INTERNAL', 'Failed to save auxiliary model settings');+ }+ });+}diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.tsindex 1bd6d898b7..6c7f7ae5a2 100644--- a/apps/desktop/src/main/maker-ipc/channels.ts+++ b/apps/desktop/src/main/maker-ipc/channels.ts@@ -357,6 +357,9 @@ export const MAKER_INVOKE = {SUBAGENT_MODEL_SETTINGS_GET: 'maker:subagent-model-settings:get',SUBAGENT_MODEL_SETTINGS_SET: 'maker:subagent-model-settings:set',SUBAGENT_MODEL_SETTINGS_RESET: 'maker:subagent-model-settings:reset',+ /** Global exact-model choices for short host-generated text tasks. */+ AUXILIARY_MODEL_SETTINGS_GET: 'maker:auxiliary-model-settings:get',+ AUXILIARY_MODEL_SETTINGS_SET: 'maker:auxiliary-model-settings:set',/** 视觉桥设置(两个清单:目标模型 + 视觉后端)。 */VISION_BRIDGE_SETTINGS_GET: 'maker:vision-bridge-settings:get',VISION_BRIDGE_SETTINGS_SET: 'maker:vision-bridge-settings:set',diff --git a/apps/desktop/src/main/maker-ipc/promptPrediction.ts b/apps/desktop/src/main/maker-ipc/promptPrediction.tsindex 8db2ef66db..9e4466918a 100644--- a/apps/desktop/src/main/maker-ipc/promptPrediction.ts+++ b/apps/desktop/src/main/maker-ipc/promptPrediction.ts@@ -21,6 +21,8 @@ import {buildTitleTarget,generateTitleViaProviderResult,} from '../maker-host/title-one-shot.js';+import { validateTitleOutput } from '../maker-host/title-output-validation.js';+import { readAuxiliaryModelSelection } from '../utility-model/auxiliary-model-settings-store.js';import {connectedProvidersForAgent,nativeDefaultSourceId,@@ -231,6 +233,118 @@ export async function generatePromptPrediction(beforeDispatchDrainUpdatedAt = undefined;}}+ const auxiliarySelection = readAuxiliaryModelSelection('promptRecommendationModel');+ if (auxiliarySelection) {+ const selectionStillCurrent = (route: {+ providerId: string;+ agentKind: AgentKind;+ model: string;+ }): boolean => {+ const current = readAuxiliaryModelSelection('promptRecommendationModel');+ return Boolean(+ current &&+ current.pin === auxiliarySelection.pin &&+ route.providerId === auxiliarySelection.providerId &&+ route.agentKind === auxiliarySelection.agentKind &&+ route.model === auxiliarySelection.model,+ );+ };+ const beforeExplicitDispatch = async (route: {+ providerId: string;+ agentKind: AgentKind;+ model: string;+ }): Promise<boolean> => {+ try {+ if (!selectionStillCurrent(route)) return false;+ const [row] = await getDbClient()+ .drizzle.select({+ agentKind: sessions.agentKind,+ status: sessions.status,+ source: sessions.source,+ remoteHostId: sessions.remoteHostId,+ providerId: sessions.providerId,+ workingDir: sessions.workingDir,+ updatedAt: sessions.updatedAt,+ activeTurnStartedAt: sessions.activeTurnStartedAt,+ lastTurnEndedAt: sessions.lastTurnEndedAt,+ })+ .from(sessions)+ .where(eq(sessions.id, params.sessionId))+ .limit(1);+ if (!row || row.status === 'deleted' || row.source === 'review' || row.remoteHostId) {+ return false;+ }+ if (dbToMakerAgentKind(row.agentKind) !== params.agentKind) return false;+ if (row.lastTurnEndedAt !== params.completionRevision) return false;+ if (+ row.activeTurnStartedAt != null &&+ row.activeTurnStartedAt >= params.completionRevision+ ) return false;+ if (wasPromptPredictionSessionStopped(params.sessionId)) return false;+ if (row.workingDir !== (params.workingDir ?? null)) return false;++ const [finalRow] = await getDbClient()+ .drizzle.select({+ agentKind: sessions.agentKind,+ status: sessions.status,+ source: sessions.source,+ remoteHostId: sessions.remoteHostId,+ providerId: sessions.providerId,+ workingDir: sessions.workingDir,+ updatedAt: sessions.updatedAt,+ activeTurnStartedAt: sessions.activeTurnStartedAt,+ lastTurnEndedAt: sessions.lastTurnEndedAt,+ })+ .from(sessions)+ .where(eq(sessions.id, params.sessionId))+ .limit(1);+ if (+ !finalRow ||+ finalRow.status === 'deleted' ||+ finalRow.source === 'review' ||+ finalRow.remoteHostId+ ) return false;+ if (dbToMakerAgentKind(finalRow.agentKind) !== params.agentKind) return false;+ if (finalRow.lastTurnEndedAt !== params.completionRevision) return false;+ if (+ finalRow.activeTurnStartedAt != null &&+ finalRow.activeTurnStartedAt >= params.completionRevision+ ) return false;+ if (wasPromptPredictionSessionStopped(params.sessionId)) return false;+ if (finalRow.providerId !== row.providerId) return false;+ if (finalRow.workingDir !== (params.workingDir ?? null)) return false;+ if (+ beforeDispatchDrainUpdatedAt &&+ finalRow.updatedAt !== beforeDispatchDrainUpdatedAt+ ) return false;+ return selectionStillCurrent(route);+ } catch {+ return false;+ }+ };++ // Keep the provider/runtime graph off the ordinary automatic path. It is+ // only needed when the user has selected an exact auxiliary route.+ const { requestExplicitUtilityText } = await import(+ '../utility-model/oneShotCandidates.js'+ );+ const explicit = await requestExplicitUtilityText(truncated, {+ providerId: auxiliarySelection.providerId,+ agentKind: auxiliarySelection.agentKind,+ model: auxiliarySelection.model,+ maxTokens: 96,+ timeoutMs: 12_000,+ systemPrompt,+ responseInstructions:+ 'Output only the predicted next user message — no quotes, markdown, or commentary.',+ beforeDispatch: beforeExplicitDispatch,+ });+ if (wasPromptPredictionSessionStopped(params.sessionId)) return null;+ if (!explicit.ok) return null;+ const normalized = validateTitleOutput(explicit.text, 512);+ return normalized ? Array.from(normalized).slice(0, 140).join('') : null;+ }+const result = await generateTitleViaProviderResult({sessionId: params.sessionId,@@ -251,6 +365,7 @@ export async function generatePromptPrediction(// - providerId: 会话 provider 被切换时中止,避免路由到过期 providerbeforeDispatch: async ({ sessionId, agentKind, providerId: resolvedProviderId }) => {try {+ if (readAuxiliaryModelSelection('promptRecommendationModel')) return false;// drainUpdatedAt 在 provider/凭证解析之前捕获,用于终末复核。// 若在 drain 之后、beforeDispatch 首次 DB 读之前用户发送了新消息,// row.updatedAt 和 finalRow.updatedAt 都会包含新值,仅做 row↔finalRow@@ -346,7 +461,7 @@ export async function generatePromptPrediction(// 仅与 row.updatedAt(beforeDispatch 内首次 DB 读)比较无法检测到// drain 之后、首次 DB 读之前发来的新消息——此时两次读都返回同一新值。if (drainUpdatedAt && finalRow.updatedAt !== drainUpdatedAt) return false;- return true;+ return readAuxiliaryModelSelection('promptRecommendationModel') === null;} catch {// 复查失败按 fail-closed 处理:宁可漏掉一次推荐,也不在归属不确定时外发付费调用。return false;diff --git a/apps/desktop/src/main/maker-ipc/title.ts b/apps/desktop/src/main/maker-ipc/title.tsindex e17d0cfbae..dfb4827f98 100644--- a/apps/desktop/src/main/maker-ipc/title.ts+++ b/apps/desktop/src/main/maker-ipc/title.ts@@ -26,11 +26,11 @@ import { getResolvedMainLocale } from '../i18n.js';import { getDbClient } from '../localDb/client/current.js';import { sessions } from '../localDb/schema.js';import { getDesktopProviderService } from '../maker-host/createDesktopProviderService.js';+import type { TitleOneShotResult } from '../maker-host/title-one-shot.js';import {- generateTitleViaProvider,- generateTitleViaProviderResult,- type TitleOneShotResult,-} from '../maker-host/title-one-shot.js';+ generateTitleWithAuxiliaryModel,+ generateTitleWithAuxiliaryModelResult,+} from '../maker-host/auxiliary-title-one-shot.js';import { validateTitleOutput } from '../maker-host/title-output-validation.js';import {regenerateTitleMaterial,@@ -111,7 +111,7 @@ export async function generateMakerSessionTitle(// "请提供用户消息内容"式回复当标题返回。直接放弃,调用方保留默认名。const trimmed = message.trim();if (!trimmed) return null;- return generateTitleViaProvider(+ return generateTitleWithAuxiliaryModel({sessionId: sessionId ?? '',agentKind,@@ -159,7 +159,7 @@ const defaultRegenerateDeps: RegenerateTitleDeps = {readSessionAgentKind: readSessionAgentKindFromDb,collectMaterial: regenerateTitleMaterial,generateTitle: (sessionId, agentKind, prompt) =>- generateTitleViaProviderResult(+ generateTitleWithAuxiliaryModelResult({ sessionId, agentKind, prompt },{readSessionProviderId: readSessionProviderIdFromDb,diff --git a/apps/desktop/src/main/utility-model/__tests__/auxiliary-model-settings-store.test.ts b/apps/desktop/src/main/utility-model/__tests__/auxiliary-model-settings-store.test.tsnew file mode 100644index 0000000000..26a1776a10--- /dev/null+++ b/apps/desktop/src/main/utility-model/__tests__/auxiliary-model-settings-store.test.ts@@ -0,0 +1,108 @@+import fs from 'node:fs';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('electron', () => ({+ app: { getPath: vi.fn(() => '/tmp/cindy-auxiliary-model-test') },+}));++vi.mock('../../maker-host/logger-adapter.js', () => ({+ desktopMakerLogger: {+ child: () => ({ info: vi.fn(), warn: vi.fn() }),+ },+}));++vi.mock('../../appSessionState.js', () => ({+ activeOwnerScopeKey: () => 'test-owner:1',+ ownerScopedUserDataPath: (...parts: string[]) =>+ path.join('/tmp/cindy-auxiliary-model-test', ...parts),+}));++import {+ __testing,+ readAuxiliaryModelSelection,+ readAuxiliaryModelSettings,+ readAuxiliaryModelSettingsState,+ resetAuxiliaryModelSettings,+ writeAuxiliaryModelSettingsPatch,+} from '../auxiliary-model-settings-store.js';++const settingsDir = '/tmp/cindy-auxiliary-model-test';+const settingsFile = path.join(settingsDir, 'auxiliary-model-settings.json');+const TITLE_PIN = 'cat:openrouter:codex:openai/gpt-5-mini';+const RECOMMENDATION_PIN = 'cat:anthropic:claude-code:claude-haiku-4-5';++describe('auxiliary model settings store', () => {+ beforeEach(async () => {+ fs.mkdirSync(settingsDir, { recursive: true });+ await resetAuxiliaryModelSettings();+ });++ afterEach(async () => {+ await resetAuxiliaryModelSettings();+ fs.rmSync(settingsDir, { recursive: true, force: true });+ });++ it('defaults both auxiliary tasks to their existing automatic routes', () => {+ expect(readAuxiliaryModelSettings()).toEqual({+ sessionTitleModel: null,+ promptRecommendationModel: null,+ });+ expect(readAuxiliaryModelSettingsState()).toMatchObject({+ isCustomized: false,+ customizedKeys: [],+ });+ });++ it('persists the two model selections independently as overrides', async () => {+ await writeAuxiliaryModelSettingsPatch({ sessionTitleModel: TITLE_PIN });+ await writeAuxiliaryModelSettingsPatch({+ promptRecommendationModel: RECOMMENDATION_PIN,+ });++ expect(JSON.parse(fs.readFileSync(settingsFile, 'utf-8'))).toEqual({+ sessionTitleModel: TITLE_PIN,+ promptRecommendationModel: RECOMMENDATION_PIN,+ });+ expect(readAuxiliaryModelSelection('sessionTitleModel')).toEqual({+ pin: TITLE_PIN,+ providerId: 'openrouter',+ agentKind: 'codex',+ model: 'openai/gpt-5-mini',+ });+ expect(readAuxiliaryModelSelection('promptRecommendationModel')).toEqual({+ pin: RECOMMENDATION_PIN,+ providerId: 'anthropic',+ agentKind: 'claude-code',+ model: 'claude-haiku-4-5',+ });+ });++ it('removes only the restored key, then removes the file at all defaults', async () => {+ await writeAuxiliaryModelSettingsPatch({+ sessionTitleModel: TITLE_PIN,+ promptRecommendationModel: RECOMMENDATION_PIN,+ });+ await writeAuxiliaryModelSettingsPatch({ sessionTitleModel: null });++ expect(JSON.parse(fs.readFileSync(settingsFile, 'utf-8'))).toEqual({+ promptRecommendationModel: RECOMMENDATION_PIN,+ });++ await writeAuxiliaryModelSettingsPatch({ promptRecommendationModel: null });+ expect(fs.existsSync(settingsFile)).toBe(false);+ });++ it('normalizes malformed or non-canonical disk values to automatic', () => {+ expect(+ __testing.normalize({+ sessionTitleModel: 'cat:openrouter:pi:model',+ promptRecommendationModel: ' cat:anthropic:claude-code:model ',+ }),+ ).toEqual({+ sessionTitleModel: null,+ promptRecommendationModel: 'cat:anthropic:claude-code:model',+ });+ });+});diff --git a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.tsindex 14b476ca30..e0a0d63015 100644--- a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts+++ b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts@@ -89,6 +89,7 @@ import {DEDICATED_AUTO_REVIEW_CANDIDATES,getUtilityTextCandidates,requestDedicatedAutoReviewCandidateText,+ requestExplicitUtilityText,requestUtilityText,toAnthropicApiModelId,} from '../oneShotCandidates.js';@@ -512,6 +513,131 @@ describe('utility one-shot candidates', () => {});});+ it('keeps system instructions separate on an exact auxiliary chat route', async () => {+ activeCatalog.mockReturnValue({+ providers: [{+ id: 'chat-only',+ name: 'Chat Only',+ source: 'user',+ agents: ['codex'],+ auth: { method: 'apiKey' },+ routing: {+ codex: {+ upstream: 'https://chat.example/v1',+ wireProtocol: 'openai-chat',+ authStrategy: 'api-key-header',+ },+ },+ models: {+ codex: [{ id: 'chat-model', name: 'Chat Model', contextWindow: 100_000 }],+ },+ }],+ } as never);+ readCustomKey.mockReturnValue('chat-secret');+ fetchMock.mockResolvedValueOnce({+ ok: true,+ text: async () => JSON.stringify({+ choices: [{ message: { content: 'next prompt' } }],+ }),+ } as never);++ const result = await requestExplicitUtilityText('reference material', {+ providerId: 'chat-only',+ agentKind: 'codex',+ model: 'chat-model',+ systemPrompt: 'SYSTEM POLICY',+ responseInstructions: 'ONE LINE ONLY',+ beforeDispatch: async (route) => route.providerId === 'chat-only',+ });++ expect(result).toMatchObject({ ok: true, text: 'next prompt' });+ expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({+ messages: [+ { role: 'system', content: 'SYSTEM POLICY\nONE LINE ONLY' },+ { role: 'user', content: 'reference material' },+ ],+ });+ });++ it('does not dispatch or fall back when the final exact-route guard rejects', async () => {+ activeCatalog.mockReturnValue({+ providers: [{+ id: 'chat-only',+ name: 'Chat Only',+ source: 'user',+ agents: ['codex'],+ auth: { method: 'apiKey' },+ routing: {+ codex: {+ upstream: 'https://chat.example/v1',+ wireProtocol: 'openai-chat',+ authStrategy: 'api-key-header',+ },+ },+ models: {+ codex: [{ id: 'chat-model', name: 'Chat Model', contextWindow: 100_000 }],+ },+ }],+ } as never);+ readCustomKey.mockReturnValue('chat-secret');++ const result = await requestExplicitUtilityText('must stay local', {+ providerId: 'chat-only',+ agentKind: 'codex',+ model: 'chat-model',+ beforeDispatch: async () => false,+ });++ expect(result).toMatchObject({+ ok: false,+ reason: 'all_candidates_failed',+ attempts: [expect.objectContaining({ providerId: 'chat-only', reason: 'request_failed' })],+ });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('passes instructions and the final guard through an exact builtin route', async () => {+ activeCatalog.mockReturnValue({+ providers: [{+ id: 'xd',+ name: 'XD Gateway',+ source: 'builtin',+ agents: ['claude-code'],+ auth: { method: 'managed' },+ routing: {+ 'claude-code': { upstream: 'https://ignored.invalid', authStrategy: 'gateway-key' },+ },+ models: {+ 'claude-code': [{ id: 'gpt-5.5', name: 'GPT-5.5', contextWindow: 1_000_000 }],+ },+ }],+ } as never);+ readKey.mockReturnValue('xd-key');+ fetchMock.mockResolvedValueOnce({+ ok: true,+ text: async () => JSON.stringify({ choices: [{ message: { content: 'next prompt' } }] }),+ } as never);+ const beforeDispatch = vi.fn(async () => true);++ const result = await requestExplicitUtilityText('reference material', {+ providerId: 'xd',+ agentKind: 'claude-code',+ model: 'gpt-5.5',+ systemPrompt: 'SYSTEM POLICY',+ responseInstructions: 'ONE LINE ONLY',+ beforeDispatch,+ });++ expect(result).toMatchObject({ ok: true, text: 'next prompt' });+ expect(beforeDispatch).toHaveBeenCalledTimes(2);+ expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({+ messages: [+ { role: 'system', content: 'SYSTEM POLICY\nONE LINE ONLY' },+ { role: 'user', content: 'reference material' },+ ],+ });+ });+it('uses Anthropic Messages for an explicitly selected pi anthropic-messages provider', async () => {activeCatalog.mockReturnValue({providers: [diff --git a/apps/desktop/src/main/utility-model/auxiliary-model-settings-store.ts b/apps/desktop/src/main/utility-model/auxiliary-model-settings-store.tsnew file mode 100644index 0000000000..5cbb5180f3--- /dev/null+++ b/apps/desktop/src/main/utility-model/auxiliary-model-settings-store.ts@@ -0,0 +1,90 @@+/**+ * Main-process source of truth for short auxiliary text model choices.+ *+ * Only explicit overrides are persisted. A missing key means “automatic”, so+ * restoring the default removes that key (and removes the file when both keys+ * are automatic).+ */++import {+ AUXILIARY_MODEL_SETTINGS_DEFAULTS,+ normalizeAuxiliaryModelPin,+ type AuxiliaryModelSettings,+ type AuxiliaryModelSettingsKey,+ type AuxiliaryModelSettingsPatch,+} from '../../shared/auxiliaryModelSettings.js';+import { decodeCatalogModelPin, type CatalogModelPinRoute } from '../../shared/catalogModelPin.js';+import { activeOwnerScopeKey, ownerScopedUserDataPath } from '../appSessionState.js';+import { desktopMakerLogger } from '../maker-host/logger-adapter.js';+import {+ createOverrideSettingsFile,+ type OverrideSettingsState,+} from '../maker-host/override-settings-file.js';++const log = desktopMakerLogger.child('auxiliary-model-settings-store');++function settingsFilePath(): string {+ return ownerScopedUserDataPath('auxiliary-model-settings.json');+}++function normalize(raw: unknown): AuxiliaryModelSettings {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {+ return { ...AUXILIARY_MODEL_SETTINGS_DEFAULTS };+ }+ const input = raw as Record<string, unknown>;+ return {+ sessionTitleModel: normalizeAuxiliaryModelPin(input.sessionTitleModel),+ promptRecommendationModel: normalizeAuxiliaryModelPin(input.promptRecommendationModel),+ };+}++const store = createOverrideSettingsFile<AuxiliaryModelSettings>({+ filePath: settingsFilePath,+ defaults: AUXILIARY_MODEL_SETTINGS_DEFAULTS,+ normalize,+ log,+ label: 'auxiliary model',+ scopeKey: activeOwnerScopeKey,+ maxBytes: 4 * 1024,+});++export interface AuxiliaryModelSelection extends CatalogModelPinRoute {+ pin: string;+}++/** Hot-path read; an external config edit becomes visible without restarting. */+export function readAuxiliaryModelSettings(): AuxiliaryModelSettings {+ store.invalidateIfChanged();+ return store.read();+}++export function readAuxiliaryModelSettingsState(): OverrideSettingsState<AuxiliaryModelSettings> {+ store.invalidateIfChanged();+ return store.readState();+}++/** A malformed disk value has already normalized to null and never reaches dispatch. */+export function readAuxiliaryModelSelection(+ key: AuxiliaryModelSettingsKey,+): AuxiliaryModelSelection | null {+ const pin = readAuxiliaryModelSettings()[key];+ if (!pin) return null;+ const route = decodeCatalogModelPin(pin);+ return route ? { ...route, pin } : null;+}++/** Owner-scoped atomic write; null removes the corresponding override key. */+export async function writeAuxiliaryModelSettingsPatch(+ patch: AuxiliaryModelSettingsPatch,+): Promise<void> {+ await store.writePatchAtomic(patch);+ log.info('auxiliary model settings written', {+ customizedKeys: store.readState().customizedKeys,+ });+}++export async function resetAuxiliaryModelSettings(): Promise<AuxiliaryModelSettings> {+ return store.resetAtomic();+}++export const __testing = { normalize };diff --git a/apps/desktop/src/main/utility-model/oneShotCandidates.ts b/apps/desktop/src/main/utility-model/oneShotCandidates.tsindex 459f2a1b81..b990ac0cc7 100644--- a/apps/desktop/src/main/utility-model/oneShotCandidates.ts+++ b/apps/desktop/src/main/utility-model/oneShotCandidates.ts@@ -1,7 +1,11 @@import { randomUUID } from 'node:crypto';import { type AgentKind, type Maker } from '@cindy/maker-core';-import { appendProviderRequestPath, storedCustomProviderId } from '@cindy/model-providers';+import {+ appendProviderRequestPath,+ isAgentSelectableModel,+ storedCustomProviderId,+} from '@cindy/model-providers';import { createLogger } from '../logger.js';import { getAppCapabilities } from '../appCapabilities.js';@@ -45,6 +49,12 @@ export type UtilityTextCapability = {transports: readonly UtilityModelTransport[];};+export interface UtilityTextDispatchRoute {+ providerId: string;+ agentKind: AgentKind;+ model: string;+}+export type UtilityTextCandidate = {providerId: string;model: string;@@ -60,6 +70,12 @@ export type UtilityTextRequestOptions = {reasoningEffort?: 'minimal' | 'low' | 'medium' | 'high';/** Abort an in-flight direct HTTP request when the owning workflow ends. */signal?: AbortSignal;+ /** Provider-native system/instructions text, kept separate from reference data. */+ systemPrompt?: string;+ /** Additional output-shape instruction (mainly for Responses-compatible routes). */+ responseInstructions?: string;+ /** Final ownership/config guard immediately before an explicit HTTP dispatch. */+ beforeDispatch?: (route: UtilityTextDispatchRoute) => Promise<boolean>;/** 显式任务来源;存在时禁止跨来源 fallback。 */providerId?: string;agentKind?: AgentKind;@@ -274,6 +290,33 @@ export async function requestUtilityText(return requestDefaultUtilityText(maker, prompt, opts);}+/** Execute one exact catalog route; failures never enter the default chain. */+export async function requestExplicitUtilityText(+ prompt: string,+ opts: UtilityTextRequestOptions & { providerId: string },+): Promise<UtilityTextResult> {+ const providerId = opts.providerId.trim();+ const explicitModel = opts.model?.trim();+ if (!providerId) return { ok: false, reason: 'no_candidate', attempts: [] };++ const disableOverrides = readModelDisableOverrides();+ if (+ isProviderDisabled(disableOverrides, providerId) ||+ (explicitModel && isModelDisabled(disableOverrides, providerId, explicitModel))+ ) {+ log.warn('utility text route disabled in settings', {+ providerId,+ model: explicitModel ?? null,+ });+ return { ok: false, reason: 'no_candidate', attempts: [] };+ }+ return requestExplicitProviderText(prompt, {+ ...opts,+ providerId,+ ...(explicitModel === undefined ? {} : { model: explicitModel }),+ });+}+const DEDICATED_AUTO_REVIEW_MAX_TOKENS = 384;/**@@ -480,6 +523,22 @@ async function requestDefaultUtilityText(return { ok: false, reason, attempts };}+function stableSnapshot(value: unknown): string {+ const normalize = (entry: unknown): unknown => {+ if (Array.isArray(entry)) return entry.map(normalize);+ if (entry && typeof entry === 'object') {+ return Object.keys(entry as Record<string, unknown>)+ .sort()+ .reduce<Record<string, unknown>>((result, key) => {+ result[key] = normalize((entry as Record<string, unknown>)[key]);+ return result;+ }, {});+ }+ return entry;+ };+ return JSON.stringify(normalize(value));+}+/*** Explicit task provider path. A selected custom provider is a single route,* not another entry in the XD fallback pool: a failed request must not leak@@ -558,6 +617,28 @@ async function requestExplicitProviderText(// 自定义供应商目录钉同样钳制到模型声明的输出上限(与 builtin 分支同口径,// 见 requestBuiltinProviderText 开头)。Codex 2026-08-06。+ const routeSnapshot = stableSnapshot({+ routing: selectedRouting,+ auth: provider.auth,+ source: provider.source,+ });+ const routeStillCurrent = (): boolean => {+ if (isProviderRouteMutationInProgress(provider.id)) return false;+ if (isProviderModelRouteDisabled(provider.id, model)) return false;+ const currentProvider = getActiveCatalog().providers.find((item) => item.id === provider.id);+ if (!currentProvider || !currentProvider.agents.includes(agentKind)) return false;+ const currentModel = currentProvider.models[agentKind]?.find((item) => item.id === model);+ if (+ !currentModel ||+ !isAgentSelectableModel(currentModel, { userProvider: currentProvider.source === 'user' })+ ) return false;+ return stableSnapshot({+ routing: currentProvider.routing[agentKind],+ auth: currentProvider.auth,+ source: currentProvider.source,+ }) === routeSnapshot;+ };+const catalogModel = provider.models[agentKind]?.find((m) => m.id === model);if (opts.maxTokens !== undefined && catalogModel?.maxOutput !== undefined) {opts = { ...opts, maxTokens: Math.min(opts.maxTokens, catalogModel.maxOutput) };@@ -572,6 +653,11 @@ async function requestExplicitProviderText(maxTokens: opts.maxTokens,timeoutMs: opts.timeoutMs,reasoningEffort: opts.reasoningEffort,+ signal: opts.signal,+ systemPrompt: opts.systemPrompt,+ responseInstructions: opts.responseInstructions,+ beforeDispatch: opts.beforeDispatch,+ routeStillCurrent,});}@@ -666,6 +752,24 @@ async function requestExplicitProviderText(timeoutMs: requestOpts?.timeoutMs,reasoningEffort: requestOpts?.reasoningEffort,signal: requestOpts?.signal,+ systemPrompt: requestOpts?.systemPrompt,+ responseInstructions: requestOpts?.responseInstructions,+ beforeDispatch: requestOpts?.beforeDispatch+ ? () => requestOpts.beforeDispatch!({ providerId: provider.id, agentKind, model })+ : undefined,+ credentialStillCurrent: requestOpts?.beforeDispatch+ ? () => {+ if (noAuth) return true;+ if (isOAuth) {+ return readCachedGenericOAuthAccessToken(+ storedCustomProviderId(provider.id),+ provider.auth.oauth,+ ) === credential;+ }+ return readCustomProviderKey(provider.id, agentKind) === credential;+ }+ : undefined,+ routeStillCurrent: requestOpts?.beforeDispatch ? routeStillCurrent : undefined,}),};return executeCandidates([candidate], prompt, [], opts);@@ -712,6 +816,10 @@ async function requestBuiltinProviderText(timeoutMs?: number;reasoningEffort?: 'minimal' | 'low' | 'medium' | 'high';signal?: AbortSignal;+ systemPrompt?: string;+ responseInstructions?: string;+ beforeDispatch?: (route: UtilityTextDispatchRoute) => Promise<boolean>;+ routeStillCurrent?: () => boolean;},): Promise<UtilityTextResult> {const profile: UtilityModelProfile = {@@ -761,6 +869,19 @@ async function requestBuiltinProviderText(timeoutMs: requestOpts?.timeoutMs ?? input.timeoutMs,reasoningEffort: requestOpts?.reasoningEffort ?? input.reasoningEffort,signal: requestOpts?.signal ?? input.signal,+ systemPrompt: requestOpts?.systemPrompt,+ responseInstructions: requestOpts?.responseInstructions,+ beforeDispatch: requestOpts?.beforeDispatch+ ? () => requestOpts.beforeDispatch!({+ providerId: input.provider.id,+ agentKind: input.agentKind,+ model: input.model,+ })+ : undefined,+ credentialStillCurrent: requestOpts?.beforeDispatch+ ? () => readClaudeApiKey() === apiKey && effectiveXdGatewayBaseUrl().trim() === baseUrl+ : undefined,+ routeStillCurrent: requestOpts?.beforeDispatch ? input.routeStillCurrent : undefined,}),}], prompt, [], input);}@@ -794,6 +915,19 @@ async function requestBuiltinProviderText(timeoutMs: requestOpts?.timeoutMs ?? input.timeoutMs,reasoningEffort: requestOpts?.reasoningEffort ?? input.reasoningEffort,signal: requestOpts?.signal ?? input.signal,+ systemPrompt: requestOpts?.systemPrompt,+ responseInstructions: requestOpts?.responseInstructions,+ beforeDispatch: requestOpts?.beforeDispatch+ ? () => requestOpts.beforeDispatch!({+ providerId: input.provider.id,+ agentKind: input.agentKind,+ model: input.model,+ })+ : undefined,+ credentialStillCurrent: requestOpts?.beforeDispatch+ ? async () => (await getValidClaudeAiOAuth())?.accessToken === oauth.accessToken+ : undefined,+ routeStillCurrent: requestOpts?.beforeDispatch ? input.routeStillCurrent : undefined,}),}], prompt, [], input);}@@ -836,6 +970,26 @@ async function requestBuiltinProviderText(// output ceiling after the response instead.supportsMaxOutputTokens: false,signal: requestOpts?.signal ?? input.signal,+ systemPrompt: requestOpts?.systemPrompt,+ responseInstructions: requestOpts?.responseInstructions,+ beforeDispatch: requestOpts?.beforeDispatch+ ? () => requestOpts.beforeDispatch!({+ providerId: input.provider.id,+ agentKind: input.agentKind,+ model: input.model,+ })+ : undefined,+ credentialStillCurrent: requestOpts?.beforeDispatch+ ? async () => {+ try {+ const current = await getChatgptBridgeAuth();+ return current.accountId === accountId && current.accessToken === creds.accessToken;+ } catch {+ return false;+ }+ }+ : undefined,+ routeStillCurrent: requestOpts?.beforeDispatch ? input.routeStillCurrent : undefined,}),}], prompt, [], input);}@@ -864,6 +1018,25 @@ async function requestBuiltinProviderText(reasoningEffort: requestOpts?.reasoningEffort ?? input.reasoningEffort,supportsReasoning: supportsXaiReasoning(input.model),signal: requestOpts?.signal ?? input.signal,+ systemPrompt: requestOpts?.systemPrompt,+ responseInstructions: requestOpts?.responseInstructions,+ beforeDispatch: requestOpts?.beforeDispatch+ ? () => requestOpts.beforeDispatch!({+ providerId: input.provider.id,+ agentKind: input.agentKind,+ model: input.model,+ })+ : undefined,+ credentialStillCurrent: requestOpts?.beforeDispatch+ ? async () => {+ try {+ return (await getGrokAccessToken()) === accessToken;+ } catch {+ return false;+ }+ }+ : undefined,+ routeStillCurrent: requestOpts?.beforeDispatch ? input.routeStillCurrent : undefined,}),}], prompt, [], input);}@@ -1128,6 +1301,16 @@ async function requestProviderHttpText(input: {supportsMaxOutputTokens?: boolean;/** Owning workflow cancellation; linked with the candidate timeout below. */signal?: AbortSignal;+ /** Provider-native system text, never concatenated with untrusted reference data. */+ systemPrompt?: string;+ /** Additional output-shape instructions. */+ responseInstructions?: string;+ /** Session/owner/config guard, evaluated immediately before each HTTP dispatch. */+ beforeDispatch?: () => Promise<boolean>;+ /** Re-read the credential captured by the request closure after the async guard. */+ credentialStillCurrent?: () => boolean | Promise<boolean>;+ /** Synchronous catalog/override snapshot guard. */+ routeStillCurrent?: () => boolean;}): Promise<string> {const controller = new AbortController();const timeoutMs = input.timeoutMs ?? 90_000;@@ -1136,6 +1319,9 @@ async function requestProviderHttpText(input: {else input.signal?.addEventListener('abort', abortFromParent, { once: true });const timeout = setTimeout(() => controller.abort(), timeoutMs);try {+ const instructions = [input.systemPrompt, input.responseInstructions]+ .filter((value): value is string => typeof value === 'string' && value.trim().length > 0)+ .join('\n');const supportsRequestedReasoning = Boolean(input.wire !== 'anthropic-messages'&& input.reasoningEffort@@ -1148,6 +1334,7 @@ async function requestProviderHttpText(input: {? {model: input.model,input: [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: input.prompt }] }],+ ...(instructions ? { instructions } : {}),...(!minimal ? {store: false,stream: true,@@ -1166,6 +1353,7 @@ async function requestProviderHttpText(input: {// maxOutput 兜底(模型自身输出能力);81920 只是模型不在目录时的最后// 回退,不是宿主承诺的输出上限。max_tokens: input.maxTokens ?? 81_920,+ ...(instructions ? { system: instructions } : {}),messages: [{ role: 'user', content: input.prompt }],}: {@@ -1174,17 +1362,33 @@ async function requestProviderHttpText(input: {...(!minimal && supportsRequestedReasoning? { reasoning_effort: input.reasoningEffort }: {}),- messages: [{ role: 'user', content: input.prompt }],+ messages: [+ ...(instructions ? [{ role: 'system', content: instructions }] : []),+ { role: 'user', content: input.prompt },+ ],};- const send = (minimal: boolean) => undiciFetch(input.endpoint, {- method: 'POST',- signal: controller.signal,- headers: {- ...(input.headers ?? {}),- 'Content-Type': 'application/json',- },- body: JSON.stringify(buildBody(minimal)),- });+ const canDispatch = async (): Promise<boolean> => {+ if (input.routeStillCurrent && !input.routeStillCurrent()) return false;+ if (input.beforeDispatch && !(await input.beforeDispatch())) return false;+ if (input.credentialStillCurrent && !(await input.credentialStillCurrent())) return false;+ if (input.routeStillCurrent && !input.routeStillCurrent()) return false;+ if (input.beforeDispatch && !(await input.beforeDispatch())) return false;+ return !input.routeStillCurrent || input.routeStillCurrent();+ };+ const send = async (minimal: boolean) => {+ if (!(await canDispatch())) {+ throw new UtilityTextExecutionError({ reason: 'request_failed' });+ }+ return undiciFetch(input.endpoint, {+ method: 'POST',+ signal: controller.signal,+ headers: {+ ...(input.headers ?? {}),+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(buildBody(minimal)),+ });+ };let response = await send(false);if (!response.ok@@ -1311,6 +1515,11 @@ async function requestCustomProviderText(input: {timeoutMs?: number;reasoningEffort?: 'minimal' | 'low' | 'medium' | 'high';signal?: AbortSignal;+ systemPrompt?: string;+ responseInstructions?: string;+ beforeDispatch?: () => Promise<boolean>;+ credentialStillCurrent?: () => boolean | Promise<boolean>;+ routeStillCurrent?: () => boolean;}): Promise<string> {const headers: Record<string, string> = {...(input.headers ?? {}),@@ -1358,6 +1567,11 @@ async function requestCustomProviderText(input: {reasoningEffort: input.reasoningEffort,retryWithMinimalBodyOnInvalidRequest: true,signal: input.signal,+ systemPrompt: input.systemPrompt,+ responseInstructions: input.responseInstructions,+ beforeDispatch: input.beforeDispatch,+ credentialStillCurrent: input.credentialStillCurrent,+ routeStillCurrent: input.routeStillCurrent,});}diff --git a/apps/desktop/src/main/utility-model/textOneshotPinOptions.ts b/apps/desktop/src/main/utility-model/textOneshotPinOptions.tsindex 43b2bd5af8..a42e2ddc01 100644--- a/apps/desktop/src/main/utility-model/textOneshotPinOptions.ts+++ b/apps/desktop/src/main/utility-model/textOneshotPinOptions.ts@@ -30,6 +30,10 @@ import {} from '@cindy/model-providers';import { applyProviderOrder } from '../../shared/providerOrder.js';+import {+ decodeCatalogModelPin,+ encodeCatalogModelPin,+} from '../../shared/catalogModelPin.js';/** oneshot 可路由的 agent(Pi 的 oneShot 未实现,不进钉档清单)。 */const ONESHOT_ROUTE_AGENTS = ['codex', 'claude-code'] as const;@@ -47,30 +51,19 @@ export type OneshotRoute =| { kind: 'utility-profile'; profileId: string }| { kind: 'catalog'; providerId: string; agentKind: AgentKind; model: string };-/** 目录钉值前缀(与轻量档位键区分:档位键永不带冒号)。 */-const CATALOG_PIN_PREFIX = 'cat:';-/** 目录钉编码:cat:<providerId>:<agentKind>:<modelId>(modelId 可含 '/' 与 ':')。 */export function encodeCatalogPin(providerId: string, agentKind: AgentKind, model: string): string {- return `${CATALOG_PIN_PREFIX}${providerId}:${agentKind}:${model}`;+ if (agentKind !== 'codex' && agentKind !== 'claude-code') {+ throw new Error(`unsupported catalog pin agent: ${agentKind}`);+ }+ return encodeCatalogModelPin({ providerId, agentKind, model });}/** 解码目录钉;不是目录钉(或形态残缺/agent 不可路由)返回 null。 */export function decodeCatalogPin(raw: string,): { providerId: string; agentKind: AgentKind; model: string } | null {- if (!raw.startsWith(CATALOG_PIN_PREFIX)) return null;- const rest = raw.slice(CATALOG_PIN_PREFIX.length);- const firstSep = rest.indexOf(':');- if (firstSep <= 0) return null;- const secondSep = rest.indexOf(':', firstSep + 1);- if (secondSep <= firstSep + 1) return null;- const providerId = rest.slice(0, firstSep);- const agentRaw = rest.slice(firstSep + 1, secondSep);- const model = rest.slice(secondSep + 1);- if (!model) return null;- if (!(ONESHOT_ROUTE_AGENTS as readonly string[]).includes(agentRaw)) return null;- return { providerId, agentKind: agentRaw as AgentKind, model };+ return decodeCatalogModelPin(raw);}/**diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex e6029d6e7f..e59f888ed1 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -111,6 +111,10 @@ import type {SubagentModelSettingsState,SubagentModelSettingsWriteResult,} from '../shared/subagentModelSettings';+import type {+ AuxiliaryModelSettingsPatch,+ AuxiliaryModelSettingsState,+} from '../shared/auxiliaryModelSettings';import {isModelVisibilityLegacyOwnerClaim,type ModelVisibilityLegacyOwnerClaim,@@ -6081,6 +6085,14 @@ contextBridge.exposeInMainWorld('electronAPI', {subagentModelSettingsReset: (): Promise<SubagentModelSettingsWriteResult> =>ipcRenderer.invoke('maker:subagent-model-settings:reset'),+ /** Global exact-model choices for task naming and composer recommendations. */+ auxiliaryModelSettingsGet: (): Promise<AuxiliaryModelSettingsState> =>+ ipcRenderer.invoke('maker:auxiliary-model-settings:get'),+ auxiliaryModelSettingsSet: (+ patch: AuxiliaryModelSettingsPatch,+ ): Promise<AuxiliaryModelSettingsState> =>+ ipcRenderer.invoke('maker:auxiliary-model-settings:set', patch),+/*** 视觉桥设置(两个清单:目标模型勾选 + 视觉后端主/备选)。* 读写 <userData>/vision-bridge-settings.json(main 为真源)。diff --git a/apps/desktop/src/renderer/cindy-brain/OneshotModelPinPicker.tsx b/apps/desktop/src/renderer/cindy-brain/OneshotModelPinPicker.tsxindex c3eb5d81ad..60d0ee182e 100644--- a/apps/desktop/src/renderer/cindy-brain/OneshotModelPinPicker.tsx+++ b/apps/desktop/src/renderer/cindy-brain/OneshotModelPinPicker.tsx@@ -7,7 +7,7 @@* 标题 + 搜索过滤;首行恒为「跟随默认」(身份卡声明了偏好模型时如实显示声明)。*/-import { useMemo, useState, type ReactNode } from 'react';+import { useMemo, useRef, useState, type ReactNode } from 'react';import { Check, ChevronDown, Search } from 'lucide-react';import { useTranslation } from 'react-i18next';@@ -30,6 +30,8 @@ export interface OneshotPinOption {/** Provider['routing'](IPC 载荷;ProviderLogoMark 的厂牌图标判定用)。 */routing?: import('@cindy/model-providers').Provider['routing'];agentSuffix?: string;+ /** False for a persisted route that is no longer credential/catalog ready. */+ available?: boolean;}export function OneshotModelPinPicker({@@ -41,6 +43,13 @@ export function OneshotModelPinPicker({onChange,ariaLabel,dense,+ defaultOptionLabel,+ searchPlaceholder,+ noResultsLabel,+ unavailableLabel,+ budgetLabel,+ subscriptionLabel,+ disabled,}: {/** 当前钉值;undefined = 跟随默认。 */value?: string;@@ -56,32 +65,44 @@ export function OneshotModelPinPicker({ariaLabel: string;/** 紧凑字号(设置页 12px;插件详情页 13px)。 */dense?: boolean;+ /** Generic settings surfaces can supply their own automatic-route copy. */+ defaultOptionLabel?: string;+ searchPlaceholder?: string;+ noResultsLabel?: string;+ unavailableLabel?: string;+ budgetLabel?: string;+ subscriptionLabel?: string;+ disabled?: boolean;}): ReactNode {const { t } = useTranslation();const [open, setOpen] = useState(false);const [query, setQuery] = useState('');+ const searchRef = useRef<HTMLInputElement>(null);const current = value ? options.find((o) => o.id === value) : undefined;// 覆盖值已不在当前清单(目录演进):如实显示原值,不假装跟随默认。// 存量档位钉不是 stale——它合法且仍可路由,只是不再能新建,展示友好名。const staleValue = value && !current && !legacyPinLabel ? value : null;- const triggerLabel = current?.label- ?? legacyPinLabel- ?? staleValue+ const automaticLabel = defaultOptionLabel?? (declaredLabel? t('settings.ghosts.detail.cindyPrefs.defaultOptionDeclared', { model: declaredLabel }): t('settings.ghosts.detail.cindyPrefs.defaultOption', { model: defaultLabel }));+ const triggerLabel = current?.label+ ?? legacyPinLabel+ ?? staleValue+ ?? automaticLabel;const filtered = useMemo(() => {const q = query.trim().toLowerCase();- if (!q) return options;- return options.filter(+ const visible = options.filter((option) => option.available !== false || option.id === value);+ if (!q) return visible;+ return visible.filter((o) =>o.modelName.toLowerCase().includes(q)|| o.modelId.toLowerCase().includes(q)|| o.group.toLowerCase().includes(q),);- }, [options, query]);+ }, [options, query, value]);const groups = useMemo(() => {const names: string[] = [];@@ -112,23 +133,43 @@ export function OneshotModelPinPicker({);return (- <Popover open={open} onOpenChange={setOpen}>+ <Popover+ open={open}+ onOpenChange={(next) => {+ if (disabled && next) return;+ setOpen(next);+ if (!next) setQuery('');+ }}+ ><PopoverTrigger asChild><buttontype="button"aria-label={ariaLabel}+ disabled={disabled}className={cn('flex h-8 w-[300px] max-w-[60%] min-w-0 shrink cursor-pointer appearance-none items-center justify-between gap-2 rounded-full border border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] py-0 pl-3 pr-2.5 text-[var(--settings-input-text)] outline-none focus:ring-2 focus:ring-[var(--focus-ring-soft)]',+ 'disabled:cursor-not-allowed disabled:opacity-60',dense ? 'text-12' : 'text-13',)}>- <span className="min-w-0 truncate">{triggerLabel}</span>+ <span className="flex min-w-0 items-center gap-1.5">+ <span className="min-w-0 truncate">{triggerLabel}</span>+ {current?.available === false && (+ <span className="shrink-0 text-11 text-[var(--text-tertiary)]">+ {unavailableLabel ?? t('settings.auxiliaryModels.unavailable')}+ </span>+ )}+ </span><ChevronDown size={13} className="shrink-0 text-[var(--text-tertiary)]" /></button></PopoverTrigger><PopoverContentalign="end"sideOffset={6}+ onOpenAutoFocus={(event) => {+ event.preventDefault();+ searchRef.current?.focus();+ }}className="w-[320px] overflow-hidden rounded-[12px] border border-[var(--model-dropdown-border)] bg-[var(--model-dropdown-bg)] p-2 shadow-[var(--shadow-menu)]"><div className="flex flex-col gap-1.5">@@ -136,11 +177,12 @@ export function OneshotModelPinPicker({<div className="flex items-center gap-2 rounded-full border border-[var(--model-dropdown-border)] bg-[var(--surface)] px-3 py-[7px]"><Search size={16} className="shrink-0 text-[var(--text-tertiary)]" /><input+ ref={searchRef}type="text"value={query}onChange={(e) => setQuery(e.target.value)}- placeholder={t('settings.ghosts.detail.cindyPrefs.searchPlaceholder')}- aria-label={t('settings.ghosts.detail.cindyPrefs.searchPlaceholder')}+ placeholder={searchPlaceholder ?? t('settings.ghosts.detail.cindyPrefs.searchPlaceholder')}+ aria-label={searchPlaceholder ?? t('settings.ghosts.detail.cindyPrefs.searchPlaceholder')}className="min-w-0 flex-1 bg-transparent text-14 text-[var(--model-item-text)] outline-none placeholder:text-[var(--text-tertiary)]"/></div>@@ -160,9 +202,7 @@ export function OneshotModelPinPicker({onClick={() => select(null)}><span className="min-w-0 truncate text-14 font-medium leading-5 text-[var(--model-item-text)]">- {declaredLabel- ? t('settings.ghosts.detail.cindyPrefs.defaultOptionDeclared', { model: declaredLabel })- : t('settings.ghosts.detail.cindyPrefs.defaultOption', { model: defaultLabel })}+ {automaticLabel}</span>{value === undefined && (<Check size={15} className="ml-2 shrink-0 text-[var(--model-item-check)]" />@@ -171,7 +211,7 @@ export function OneshotModelPinPicker({{groups.length === 0 ? (<div className="px-3 py-6 text-center text-13 text-[var(--text-tertiary)]">- {t('newChat.modelSelector.search.noResults')}+ {noResultsLabel ?? t('newChat.modelSelector.search.noResults')}</div>) : (groups.map((g) => (@@ -182,6 +222,7 @@ export function OneshotModelPinPicker({</div>{g.items.map((o) => {const active = value === o.id;+ const unavailable = o.available === false;return (<buttonkey={o.id}@@ -189,7 +230,8 @@ export function OneshotModelPinPicker({role="option"aria-selected={active}data-pin-id={o.id}- className={rowClass(active)}+ aria-disabled={unavailable}+ className={cn(rowClass(active), unavailable && 'opacity-60')}onClick={() => select(o.id)}><span className="flex min-w-0 flex-1 items-center gap-2.5">@@ -211,16 +253,21 @@ export function OneshotModelPinPicker({{o.agentSuffix}</span>)}+ {unavailable && (+ <span className="shrink-0 text-11 font-normal text-[var(--text-tertiary)]">+ {unavailableLabel ?? t('settings.auxiliaryModels.unavailable')}+ </span>+ )}</span><span className="ml-auto flex shrink-0 items-center gap-1.5">{o.subscription && (<span className="inline-flex shrink-0 items-center rounded-full bg-[var(--surface-chip)] px-2 py-[1px] text-11 font-medium text-[var(--text-secondary)]">- {t('settings.providers.models.subscription')}+ {subscriptionLabel ?? t('settings.providers.models.subscription')}</span>)}{o.budget && (<span className="inline-flex shrink-0 items-center rounded-full bg-[var(--accent-cta-bg)] px-2 py-[1px] text-11 font-medium leading-[1.45] text-[var(--accent-pure-cta-fg)]">- {t('settings.ghosts.detail.cindyPrefs.budgetBadge')}+ {budgetLabel ?? t('settings.ghosts.detail.cindyPrefs.budgetBadge')}</span>)}</span>diff --git a/apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx b/apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsxnew file mode 100644index 0000000000..40acbefdd5--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx@@ -0,0 +1,133 @@+/** Settings → Personalization: global models for short auxiliary text tasks. */++import { useCallback, useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { OneshotModelPinPicker, type OneshotPinOption } from '@/cindy-brain/OneshotModelPinPicker';+import { createLogger } from '@/lib/logger';+import { toast } from '@/lib/toast';+import type {+ AuxiliaryModelSettingsKey,+ AuxiliaryModelSettingsState,+} from '../../../shared/auxiliaryModelSettings';++const log = createLogger('AuxiliaryModelSection');++export function AuxiliaryModelSection() {+ const { t } = useTranslation();+ const [settings, setSettings] = useState<AuxiliaryModelSettingsState | null>(null);+ const [pending, setPending] = useState(false);+ const pendingRef = useRef(false);++ useEffect(() => {+ let disposed = false;+ void window.electronAPI.maker+ .auxiliaryModelSettingsGet()+ .then((next) => {+ if (!disposed) setSettings(next);+ })+ .catch((error) => {+ log.warn('auxiliaryModelSettingsGet failed', error);+ });+ return () => {+ disposed = true;+ };+ }, []);++ const persist = useCallback(+ async (key: AuxiliaryModelSettingsKey, pin: string | null): Promise<void> => {+ if (pendingRef.current) return;+ pendingRef.current = true;+ setPending(true);+ try {+ const next = await window.electronAPI.maker.auxiliaryModelSettingsSet({ [key]: pin });+ setSettings(next);+ } catch (error) {+ log.warn('auxiliaryModelSettingsSet failed', error);+ toast.error(+ error instanceof Error ? error.message : t('settings.auxiliaryModels.saveFailed'),+ );+ } finally {+ pendingRef.current = false;+ setPending(false);+ }+ },+ [t],+ );++ if (!settings) return null;++ const picker = (key: AuxiliaryModelSettingsKey, ariaLabel: string, automaticLabel: string) => (+ <OneshotModelPinPicker+ value={settings[key] ?? undefined}+ defaultLabel=""+ declaredLabel={null}+ options={settings.options as readonly OneshotPinOption[]}+ onChange={(pin) => {+ void persist(key, pin);+ }}+ ariaLabel={ariaLabel}+ dense+ disabled={pending}+ defaultOptionLabel={automaticLabel}+ searchPlaceholder={t('settings.auxiliaryModels.searchPlaceholder')}+ noResultsLabel={t('settings.auxiliaryModels.noResults')}+ unavailableLabel={t('settings.auxiliaryModels.unavailable')}+ budgetLabel={t('settings.auxiliaryModels.budget')}+ subscriptionLabel={t('settings.auxiliaryModels.subscription')}+ />+ );++ return (+ <div className="flex flex-col gap-[14px]">+ <div className="flex flex-col gap-1">+ <h2 className="text-16 font-medium leading-[1.2] text-[var(--settings-section-title)]">+ {t('settings.auxiliaryModels.title')}+ </h2>+ <p className="text-13 leading-[1.5] text-[var(--settings-section-desc)]">+ {t('settings.auxiliaryModels.description')}+ </p>+ </div>++ <div className="flex flex-col rounded-xl border border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)]">+ <div className="flex items-center justify-between gap-4 px-4 py-4">+ <div className="min-w-0 flex-1">+ <div className="text-14 font-medium text-[var(--text-primary)]">+ {t('settings.auxiliaryModels.sessionTitle.label')}+ </div>+ <p className="mt-1 text-12 leading-[1.5] text-[var(--text-tertiary)]">+ {t('settings.auxiliaryModels.sessionTitle.description')}+ </p>+ </div>+ {picker(+ 'sessionTitleModel',+ t('settings.auxiliaryModels.sessionTitle.ariaLabel'),+ t('settings.auxiliaryModels.sessionTitle.automatic'),+ )}+ </div>++ <div className="mx-4 h-px bg-[var(--settings-theme-card-border)]" />++ <div className="flex items-center justify-between gap-4 px-4 py-4">+ <div className="min-w-0 flex-1">+ <div className="text-14 font-medium text-[var(--text-primary)]">+ {t('settings.auxiliaryModels.promptRecommendation.label')}+ </div>+ <p className="mt-1 text-12 leading-[1.5] text-[var(--text-tertiary)]">+ {t('settings.auxiliaryModels.promptRecommendation.description')}+ </p>+ </div>+ {picker(+ 'promptRecommendationModel',+ t('settings.auxiliaryModels.promptRecommendation.ariaLabel'),+ t('settings.auxiliaryModels.promptRecommendation.automatic'),+ )}+ </div>++ <p className="px-4 pb-4 text-12 leading-[1.5] text-[var(--text-secondary)]">+ {t('settings.auxiliaryModels.explicitRouteHint')}+ </p>+ </div>+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/settings/SettingsView.tsx b/apps/desktop/src/renderer/components/settings/SettingsView.tsxindex 8592e45738..a804565543 100644--- a/apps/desktop/src/renderer/components/settings/SettingsView.tsx+++ b/apps/desktop/src/renderer/components/settings/SettingsView.tsx@@ -13,6 +13,7 @@ import { UserProfileCard } from './UserProfileCard';import { VoiceInputSection } from './VoiceInputSection';import { AppearanceSection } from './AppearanceSection';import { SubagentModelSection } from './SubagentModelSection';+import { AuxiliaryModelSection } from './AuxiliaryModelSection';import { VisionBridgeSection } from './VisionBridgeSection';import { ProvidersSection } from './ProvidersSection';import { McpServersSection } from './McpServersSection';@@ -438,6 +439,11 @@ export function SettingsView() {<section className="pb-[18px]" aria-label={t('settings.sections.subagentModels')}><SubagentModelSection key={`subagent-models:${mode}:${dataOwnerId ?? 'none'}`} /></section>+ <section className="pb-[18px]" aria-label={t('settings.sections.auxiliaryModels')}>+ <AuxiliaryModelSection+ key={`auxiliary-models:${mode}:${dataOwnerId ?? 'none'}`}+ />+ </section><section className="pb-[18px]" aria-label={t('settings.sections.visionBridge')}><VisionBridgeSection key={`vision-bridge:${mode}:${dataOwnerId ?? 'none'}`} /></section>diff --git a/apps/desktop/src/renderer/components/settings/__tests__/AuxiliaryModelSection.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/AuxiliaryModelSection.test.tsxnew file mode 100644index 0000000000..cc112820a7--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/__tests__/AuxiliaryModelSection.test.tsx@@ -0,0 +1,149 @@+// @vitest-environment jsdom++import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { AuxiliaryModelSettingsState } from '../../../../shared/auxiliaryModelSettings';++const TITLE_PIN = 'cat:openrouter:codex:openai/gpt-5-mini';+const RECOMMENDATION_PIN = 'cat:anthropic:claude-code:claude-haiku-4-5';++const h = vi.hoisted(() => ({+ get: vi.fn(),+ set: vi.fn(),+ toastError: vi.fn(),+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock('@/lib/logger', () => ({+ createLogger: () => ({ warn: vi.fn() }),+}));++vi.mock('@/lib/toast', () => ({+ toast: { error: h.toastError },+}));++vi.mock('@/cindy-brain/OneshotModelPinPicker', () => ({+ OneshotModelPinPicker: ({+ value,+ onChange,+ ariaLabel,+ disabled,+ }: {+ value?: string;+ onChange: (pin: string | null) => void;+ ariaLabel: string;+ disabled?: boolean;+ }) => {+ const titleRow = ariaLabel.includes('sessionTitle');+ const pin = titleRow ? TITLE_PIN : RECOMMENDATION_PIN;+ return (+ <div>+ <span>{`${ariaLabel}:${value ?? 'automatic'}`}</span>+ <button+ type="button"+ aria-label={`${ariaLabel}:select`}+ disabled={disabled}+ onClick={() => onChange(pin)}+ >+ select+ </button>+ <button+ type="button"+ aria-label={`${ariaLabel}:automatic`}+ disabled={disabled}+ onClick={() => onChange(null)}+ >+ automatic+ </button>+ </div>+ );+ },+}));++import { AuxiliaryModelSection } from '../AuxiliaryModelSection';++function state(partial: Partial<AuxiliaryModelSettingsState> = {}): AuxiliaryModelSettingsState {+ return {+ sessionTitleModel: null,+ promptRecommendationModel: null,+ isCustomized: false,+ customizedKeys: [],+ defaults: {+ sessionTitleModel: null,+ promptRecommendationModel: null,+ },+ options: [],+ ...partial,+ };+}++function installApi(): void {+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: {+ maker: {+ auxiliaryModelSettingsGet: h.get,+ auxiliaryModelSettingsSet: h.set,+ },+ },+ });+}++describe('AuxiliaryModelSection', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ installApi();+ h.get.mockResolvedValue(state());+ h.set.mockImplementation(async (patch: Partial<AuxiliaryModelSettingsState>) => state(patch));+ });++ it('renders separate controls for task naming and prompt recommendations', async () => {+ render(<AuxiliaryModelSection />);++ expect(await screen.findByText('settings.auxiliaryModels.sessionTitle.label')).toBeTruthy();+ expect(screen.getByText('settings.auxiliaryModels.promptRecommendation.label')).toBeTruthy();+ });++ it('writes each model choice to its own independent key', async () => {+ render(<AuxiliaryModelSection />);++ fireEvent.click(+ await screen.findByRole('button', {+ name: 'settings.auxiliaryModels.sessionTitle.ariaLabel:select',+ }),+ );+ await waitFor(() => expect(h.set).toHaveBeenLastCalledWith({ sessionTitleModel: TITLE_PIN }));++ fireEvent.click(+ screen.getByRole('button', {+ name: 'settings.auxiliaryModels.promptRecommendation.ariaLabel:select',+ }),+ );+ await waitFor(() =>+ expect(h.set).toHaveBeenLastCalledWith({+ promptRecommendationModel: RECOMMENDATION_PIN,+ }),+ );+ });++ it('restores automatic routing with a null override', async () => {+ h.get.mockResolvedValue(+ state({+ sessionTitleModel: TITLE_PIN,+ promptRecommendationModel: RECOMMENDATION_PIN,+ }),+ );+ render(<AuxiliaryModelSection />);++ fireEvent.click(+ await screen.findByRole('button', {+ name: 'settings.auxiliaryModels.sessionTitle.ariaLabel:automatic',+ }),+ );+ await waitFor(() => expect(h.set).toHaveBeenCalledWith({ sessionTitleModel: null }));+ });+});diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 6f5b9f7c33..26b228e27a 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -131,6 +131,7 @@"chipMetrics": "Usage indicator","memory": "Memory","subagentModels": "Subagents",+ "auxiliaryModels": "Auxiliary models","visionBridge": "Vision Bridge","compaction": "Context compaction","terminalShell": "Default terminal shell",@@ -2528,6 +2529,29 @@"deferredSuffix": " — running Codex sessions will apply this after their current task finishes"}},+ "auxiliaryModels": {+ "title": "Auxiliary models",+ "description": "Choose separate models for automatic task naming and composer prompt suggestions.",+ "sessionTitle": {+ "label": "Automatic task naming",+ "description": "Applies to Claude Code, Codex, and Pi tasks, plus manual AI renaming.",+ "ariaLabel": "Choose the automatic task naming model",+ "automatic": "Automatic (follow the current task)"+ },+ "promptRecommendation": {+ "label": "Composer prompt suggestions",+ "description": "Used only when prompt recommendations are enabled under Tips.",+ "ariaLabel": "Choose the composer prompt suggestion model",+ "automatic": "Automatic (keep current routing)"+ },+ "explicitRouteHint": "An explicit selection uses only that model. If it is unavailable, Cindy will not switch providers.",+ "searchPlaceholder": "Search models or providers",+ "noResults": "No available models",+ "unavailable": "Currently unavailable",+ "budget": "Discount",+ "subscription": "Subscription",+ "saveFailed": "Failed to save auxiliary model settings"+ },"compaction": {"title": "Context compaction","description": "Control when Claude Code and Pi automatically compact context. This setting does not affect Codex; Codex manages context compaction separately.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex e2c515a6d1..9a1c75f60f 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -131,6 +131,7 @@"chipMetrics": "使用量インジケーター","memory": "メモリ","subagentModels": "サブエージェント",+ "auxiliaryModels": "補助モデル","visionBridge": "ビジョンブリッジ","compaction": "コンテキスト圧縮","terminalShell": "デフォルトターミナルシェル",@@ -2527,6 +2528,29 @@"deferredSuffix": " — 実行中の Codex セッションには現在のタスク終了後に適用されます"}},+ "auxiliaryModels": {+ "title": "補助モデル",+ "description": "タスクの自動命名と入力欄のおすすめプロンプトに、それぞれ別のモデルを指定します。",+ "sessionTitle": {+ "label": "タスクの自動命名",+ "description": "Claude Code、Codex、Pi のタスクと、AI による手動の名前変更に適用されます。",+ "ariaLabel": "タスクの自動命名モデルを選択",+ "automatic": "自動選択(現在のタスクに従う)"+ },+ "promptRecommendation": {+ "label": "入力欄のおすすめプロンプト",+ "description": "「ヒント」で入力欄のおすすめを有効にした場合のみ使用します。",+ "ariaLabel": "入力欄のおすすめプロンプト用モデルを選択",+ "automatic": "自動選択(現在のルーティングを維持)"+ },+ "explicitRouteHint": "明示的に指定した場合は、そのモデルだけを使用します。利用できなくても、別のプロバイダーには切り替えません。",+ "searchPlaceholder": "モデルまたはプロバイダーを検索",+ "noResults": "利用可能なモデルがありません",+ "unavailable": "現在利用不可",+ "budget": "割引",+ "subscription": "サブスクリプション",+ "saveFailed": "補助モデル設定を保存できませんでした"+ },"compaction": {"title": "コンテキスト圧縮","description": "Claude Code と Pi がいつ自動的にコンテキストを圧縮するかを制御します。この設定は Codex に影響しません。Codex は独自にコンテキスト圧縮を管理します。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 26051f0270..56fe10d613 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -131,6 +131,7 @@"chipMetrics": "사용량 표시기","memory": "메모리","subagentModels": "하위 에이전트",+ "auxiliaryModels": "보조 모델","visionBridge": "비전 브리지","compaction": "컨텍스트 압축","terminalShell": "기본 터미널 셸",@@ -2527,6 +2528,29 @@"deferredSuffix": " — 실행 중인 Codex 세션에는 현재 작업이 끝난 후 적용됩니다"}},+ "auxiliaryModels": {+ "title": "보조 모델",+ "description": "작업 자동 이름 지정과 입력창 추천 프롬프트에 각각 다른 모델을 지정합니다.",+ "sessionTitle": {+ "label": "작업 자동 이름 지정",+ "description": "Claude Code, Codex, Pi 작업과 AI 수동 이름 바꾸기에 적용됩니다.",+ "ariaLabel": "작업 자동 이름 지정 모델 선택",+ "automatic": "자동 선택(현재 작업 따름)"+ },+ "promptRecommendation": {+ "label": "입력창 추천 프롬프트",+ "description": "‘팁’에서 입력창 추천을 켠 경우에만 사용합니다.",+ "ariaLabel": "입력창 추천 프롬프트 모델 선택",+ "automatic": "자동 선택(현재 라우팅 유지)"+ },+ "explicitRouteHint": "명시적으로 지정하면 해당 모델만 사용합니다. 사용할 수 없어도 다른 제공자로 전환하지 않습니다.",+ "searchPlaceholder": "모델 또는 제공자 검색",+ "noResults": "사용 가능한 모델이 없습니다",+ "unavailable": "현재 사용할 수 없음",+ "budget": "할인",+ "subscription": "구독",+ "saveFailed": "보조 모델 설정을 저장하지 못했습니다"+ },"compaction": {"title": "컨텍스트 압축","description": "Claude Code와 Pi가 언제 컨텍스트를 자동 압축할지 제어합니다. 이 설정은 Codex에 영향을 주지 않습니다. Codex는 컨텍스트 압축을 따로 관리합니다.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 9c2948a121..c43ea42fac 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -131,6 +131,7 @@"chipMetrics": "用量指示器","memory": "记忆","subagentModels": "Subagent",+ "auxiliaryModels": "辅助模型","visionBridge": "视觉桥","compaction": "上下文压缩","terminalShell": "默认终端 shell",@@ -2527,6 +2528,29 @@"deferredSuffix": " — 运行中的 Codex 任务将在当前执行结束后应用"}},+ "auxiliaryModels": {+ "title": "辅助模型",+ "description": "为任务自动命名和输入框推荐指令分别指定模型。",+ "sessionTitle": {+ "label": "任务自动命名",+ "description": "适用于 Claude Code、Codex、Pi 任务,以及手动 AI 重命名。",+ "ariaLabel": "选择任务自动命名模型",+ "automatic": "自动选择(跟随当前任务)"+ },+ "promptRecommendation": {+ "label": "输入框推荐指令",+ "description": "仅在“小技巧”中启用输入框推荐后调用。",+ "ariaLabel": "选择输入框推荐指令模型",+ "automatic": "自动选择(保持当前规则)"+ },+ "explicitRouteHint": "显式指定后只使用该模型;模型不可用时不会改用其他供应商。",+ "searchPlaceholder": "搜索模型或供应商",+ "noResults": "没有可用模型",+ "unavailable": "当前不可用",+ "budget": "折扣",+ "subscription": "订阅",+ "saveFailed": "保存辅助模型设置失败"+ },"compaction": {"title": "上下文压缩","description": "控制 Claude Code 和 Pi 何时自动压缩上下文。此设置不影响 Codex;Codex 单独管理上下文压缩。",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 4877c722f4..7d2949b6c1 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -131,6 +131,7 @@"chipMetrics": "用量指示器","memory": "記憶","subagentModels": "Subagent",+ "auxiliaryModels": "輔助模型","visionBridge": "視覺橋","compaction": "上下文壓縮","terminalShell": "預設終端 shell",@@ -2527,6 +2528,29 @@"deferredSuffix": " — 執行中的 Codex 任務將在當前執行結束後應用"}},+ "auxiliaryModels": {+ "title": "輔助模型",+ "description": "為任務自動命名與輸入框推薦指令分別指定模型。",+ "sessionTitle": {+ "label": "任務自動命名",+ "description": "適用於 Claude Code、Codex、Pi 任務,以及手動 AI 重新命名。",+ "ariaLabel": "選擇任務自動命名模型",+ "automatic": "自動選擇(跟隨目前任務)"+ },+ "promptRecommendation": {+ "label": "輸入框推薦指令",+ "description": "僅在「小技巧」中啟用輸入框推薦後呼叫。",+ "ariaLabel": "選擇輸入框推薦指令模型",+ "automatic": "自動選擇(維持目前規則)"+ },+ "explicitRouteHint": "明確指定後只使用該模型;模型無法使用時不會改用其他供應商。",+ "searchPlaceholder": "搜尋模型或供應商",+ "noResults": "沒有可用模型",+ "unavailable": "目前無法使用",+ "budget": "折扣",+ "subscription": "訂閱",+ "saveFailed": "儲存輔助模型設定失敗"+ },"compaction": {"title": "上下文壓縮","description": "控制 Claude Code 和 Pi 何時自動壓縮上下文。此設定不影響 Codex;Codex 單獨管理上下文壓縮。",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 313d842fc3..c3395778df 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -303,6 +303,10 @@ type SubagentModelSettingsState =import('../shared/subagentModelSettings').SubagentModelSettingsState;type SubagentModelSettingsWriteResult =import('../shared/subagentModelSettings').SubagentModelSettingsWriteResult;+type AuxiliaryModelSettingsPatch =+ import('../shared/auxiliaryModelSettings').AuxiliaryModelSettingsPatch;+type AuxiliaryModelSettingsState =+ import('../shared/auxiliaryModelSettings').AuxiliaryModelSettingsState;type VisionBridgeSettingsPatch =import('../shared/visionBridgeSettings').VisionBridgeSettingsPatch;type VisionBridgeSettingsState =@@ -5577,6 +5581,10 @@ interface ElectronAPI {patch: SubagentModelSettingsPatch,) => Promise<SubagentModelSettingsWriteResult>;subagentModelSettingsReset: () => Promise<SubagentModelSettingsWriteResult>;+ auxiliaryModelSettingsGet: () => Promise<AuxiliaryModelSettingsState>;+ auxiliaryModelSettingsSet: (+ patch: AuxiliaryModelSettingsPatch,+ ) => Promise<AuxiliaryModelSettingsState>;/** 视觉桥设置(目标模型勾选 + 视觉后端主/备选)。 */visionBridgeSettingsGet: () => Promise<VisionBridgeSettingsState>;diff --git a/apps/desktop/src/shared/auxiliaryModelSettings.ts b/apps/desktop/src/shared/auxiliaryModelSettings.tsnew file mode 100644index 0000000000..7add9bf20c--- /dev/null+++ b/apps/desktop/src/shared/auxiliaryModelSettings.ts@@ -0,0 +1,76 @@+import type { Provider } from '@cindy/model-providers';++import { decodeCatalogModelPin } from './catalogModelPin';++/** Main-owned model choices for short, host-generated auxiliary text. */+export interface AuxiliaryModelSettings {+ /** null = preserve the existing per-task/session automatic routing. */+ sessionTitleModel: string | null;+ /** null = preserve the existing prompt-recommendation automatic routing. */+ promptRecommendationModel: string | null;+}++export type AuxiliaryModelSettingsKey = keyof AuxiliaryModelSettings;+export type AuxiliaryModelSettingsPatch = Partial<AuxiliaryModelSettings>;++export const AUXILIARY_MODEL_SETTINGS_DEFAULTS: AuxiliaryModelSettings = {+ sessionTitleModel: null,+ promptRecommendationModel: null,+};++export const AUXILIARY_MODEL_PIN_MAX_LENGTH = 768;++/** Credential-free model metadata safe to expose to the trusted app renderer. */+export interface AuxiliaryModelOption {+ id: string;+ label: string;+ group: string;+ providerId: string;+ agentKind: 'codex' | 'claude-code';+ modelId: string;+ modelName: string;+ icon?: string;+ budget: boolean;+ subscription: boolean;+ routing?: Provider['routing'];+ agentSuffix?: string;+ /** False only for a persisted selection that is no longer currently usable. */+ available: boolean;+}++export interface AuxiliaryModelSettingsState extends AuxiliaryModelSettings {+ isCustomized: boolean;+ customizedKeys: string[];+ defaults: AuxiliaryModelSettings;+ options: AuxiliaryModelOption[];+}++function containsControlCharacter(value: string): boolean {+ for (let index = 0; index < value.length; index += 1) {+ const code = value.charCodeAt(index);+ if (code <= 31 || code === 127) return true;+ }+ return false;+}++/** Disk normalization: invalid values restore the automatic/default route. */+export function normalizeAuxiliaryModelPin(value: unknown): string | null {+ if (typeof value !== 'string') return null;+ const trimmed = value.trim();+ if (+ !trimmed ||+ trimmed.length > AUXILIARY_MODEL_PIN_MAX_LENGTH ||+ containsControlCharacter(trimmed) ||+ !decodeCatalogModelPin(trimmed)+ ) {+ return null;+ }+ return trimmed;+}++/** IPC validation is strict: only null or a canonical, bounded catalog pin. */+export function isValidAuxiliaryModelPinInput(value: unknown): value is string | null {+ if (value === null) return true;+ if (typeof value !== 'string') return false;+ return normalizeAuxiliaryModelPin(value) === value;+}diff --git a/apps/desktop/src/shared/catalogModelPin.ts b/apps/desktop/src/shared/catalogModelPin.tsnew file mode 100644index 0000000000..367a84b8bb--- /dev/null+++ b/apps/desktop/src/shared/catalogModelPin.ts@@ -0,0 +1,47 @@+/**+ * A stable catalog route pin for one-shot text work.+ *+ * The model id may contain both `/` and `:`, so only the first two separators+ * after `cat:` are structural. Keep this parser shared by persistence, IPC and+ * execution so a value accepted by Settings is always decoded the same way at+ * dispatch time.+ */++export const CATALOG_MODEL_PIN_PREFIX = 'cat:';++export type CatalogModelPinAgentKind = 'codex' | 'claude-code';++export interface CatalogModelPinRoute {+ providerId: string;+ agentKind: CatalogModelPinAgentKind;+ model: string;+}++const CATALOG_MODEL_PIN_AGENTS = new Set<CatalogModelPinAgentKind>(['codex', 'claude-code']);++/** Encode an exact provider × runtime × model route. */+export function encodeCatalogModelPin(route: CatalogModelPinRoute): string {+ return `${CATALOG_MODEL_PIN_PREFIX}${route.providerId}:${route.agentKind}:${route.model}`;+}++/** Decode a catalog pin; malformed or unsupported-runtime values return null. */+export function decodeCatalogModelPin(raw: string): CatalogModelPinRoute | null {+ if (!raw.startsWith(CATALOG_MODEL_PIN_PREFIX)) return null;+ const rest = raw.slice(CATALOG_MODEL_PIN_PREFIX.length);+ const firstSep = rest.indexOf(':');+ if (firstSep <= 0) return null;+ const secondSep = rest.indexOf(':', firstSep + 1);+ if (secondSep <= firstSep + 1) return null;++ const providerId = rest.slice(0, firstSep);+ const agentKind = rest.slice(firstSep + 1, secondSep);+ const model = rest.slice(secondSep + 1);+ if (!model || !CATALOG_MODEL_PIN_AGENTS.has(agentKind as CatalogModelPinAgentKind)) {+ return null;+ }+ return {+ providerId,+ agentKind: agentKind as CatalogModelPinAgentKind,+ model,+ };+}