Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): 统一辅助模型路由 (#3649)

Dash1e5c14124869
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index dbe0ede421..8013835cfb 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -374,7 +374,10 @@ import { readProviderOrder } from '../maker-host/provider-order-store.js';
import { guardedOutboundFetch, outboundFetch } from '../maker-host/outbound-fetch.js';
import { getSharedGhCliTokenSource } from '../git-context/ghCliTokenSource.js';
import { hasCodexOAuthLoginReadOnly } from '../maker-host/codex-oauth-readiness.js';
-import { getUtilityModelChainProfiles } from '../utility-model/UtilityModelSelection.js';
+import {
+ formatAuxiliaryModelRefLabel,
+ getEffectiveAuxiliaryModelChain,
+} from '../utility-model/resolveAuxiliaryModelChain.js';
import { utilityModelPinOptions } from '../../shared/utilityModelProfiles.js';
import { isKnownEmbeddingModel } from '@cindy/embedding-client';
import {
@@ -7148,14 +7151,14 @@ export function registerGhostIpc(): void {
};
// 文本类(快问快答)的可选项 = 当前供应商目录里的全部文本模型(2026-08-05
// 与刘佳黎定稿:安装插件即承担其成本,主机如实展示可选面)。每一项精确钉
- // 一组 供应商×agent×模型(cat: 编码)。defaultModel = 系统默认链链首(轻量
- // 档位),declaredModel = 身份卡声明的偏好(解析得到才给)——让"跟随默认"
+ // 一组 供应商×agent×模型(cat: 编码)。defaultModel = 当前辅助模型链链首,
+ // declaredModel = 身份卡声明的偏好(解析得到才给)——让"跟随默认"
// 行如实说出当前实际跟的是谁。
- const textChain = getUtilityModelChainProfiles();
- const textDefaultId = textChain[0]?.id ?? null;
+ const textChain = getEffectiveAuxiliaryModelChain();
+ const textDefaultId = textChain.refs[0] ?? null;
const textDefaultLabel = textDefaultId === null
? null
- : (utilityModelPinOptions().find((o) => o.id === textDefaultId)?.label ?? textDefaultId);
+ : formatAuxiliaryModelRefLabel(textDefaultId);
const textOptions = buildTextOneshotPinOptions(
getActiveCatalog(),
readModelDisableOverrides(),
diff --git a/apps/desktop/src/main/im/__tests__/fbotTitleAuxiliaryModel.test.ts b/apps/desktop/src/main/im/__tests__/fbotTitleAuxiliaryModel.test.ts
index dd752e509c..4c5629ca6a 100644
--- a/apps/desktop/src/main/im/__tests__/fbotTitleAuxiliaryModel.test.ts
+++ b/apps/desktop/src/main/im/__tests__/fbotTitleAuxiliaryModel.test.ts
@@ -2,9 +2,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const h = vi.hoisted(() => ({
generatedTitle: null as string | null,
- selection: null as null | { pin: string },
- onGenerate: null as null | (() => void),
- requestUtilityText: vi.fn(),
}));
vi.mock('../../maker-host/session-storage.js', () => ({
@@ -12,66 +9,38 @@ vi.mock('../../maker-host/session-storage.js', () => ({
}));
vi.mock('../../maker-ipc/title.js', () => ({
- generateMakerSessionTitle: vi.fn(async () => {
- h.onGenerate?.();
- return 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: () => ({}),
+ generateMakerSessionTitle: vi.fn(async () => h.generatedTitle),
}));
vi.mock('../shared/sessionBroadcast.js', () => ({
broadcastSessionPatched: vi.fn(),
}));
+import { generateMakerSessionTitle } from '../../maker-ipc/title.js';
import { generateImSessionTitleText } from '../shared/fbotTitle.js';
beforeEach(() => {
vi.clearAllMocks();
h.generatedTitle = null;
- h.selection = null;
- h.onGenerate = 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 () => {
+ it('delegates title generation to generateMakerSessionTitle', async () => {
+ h.generatedTitle = '飞书会话标题';
+
await expect(generateImSessionTitleText('task-1', '第一条消息')).resolves.toBe(
- '旧 utility 兜底标题',
+ '飞书会话标题',
+ );
+ expect(generateMakerSessionTitle).toHaveBeenCalledWith(
+ '第一条消息',
+ 'claude-code',
+ 'task-1',
);
- 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();
});
- it('preserves the initially selected exact route when settings change in flight', async () => {
- h.selection = { pin: 'cat:openrouter:codex:openai/gpt-5-mini' };
- h.onGenerate = () => {
- h.selection = null;
- };
+ it('returns null when generateMakerSessionTitle has no title', async () => {
+ h.generatedTitle = null;
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.ts
index d9c1ea1946..b9213a246f 100644
--- a/apps/desktop/src/main/im/shared/fbotTitle.ts
+++ b/apps/desktop/src/main/im/shared/fbotTitle.ts
@@ -19,7 +19,6 @@
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';
@@ -63,47 +62,13 @@ export async function generateAndPersistFbotTitle(
/**
* 只生成标题文本(不落库) — 供渠道自定义拼装(飞书话题标题)复用 oneshot 通道。
- * 标题 oneshot 失败(无 title target / 模型输出校验不过)时, 走 utility 链兜底
- * 再试一次 — 标题是展示层, 失败不阻塞, 但兜底能把 [飞书·话题] 0f9b9b 这类
- * 默认名救回正式话题名。
+ * 走共享辅助模型链(generateMakerSessionTitle → requestUtilityText),失败不兜底。
*/
export async function generateImSessionTitleText(
sessionId: string,
seedText: string,
): Promise<string | null> {
- // Preserve the route selected when this title attempt began. If the exact
- // route fails and Settings changes while it is in flight, falling through
- // based on the new value would silently send the same prompt to another
- // provider.
- const startedWithExplicitRoute = Boolean(
- readAuxiliaryModelSelection('sessionTitleModel'),
- );
- 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 (startedWithExplicitRoute) return null;
- try {
- // 动态 import 保持本模块的静态依赖链不继续膨胀(cindySlot 同款)。
- const [{ requestUtilityText }, { getMaker }] = await Promise.all([
- import('../../utility-model/oneShotCandidates.js'),
- import('../../maker-host/index.js'),
- ]);
- const r = await requestUtilityText(
- getMaker(),
- `给下面这条消息生成一个不超过 12 个字的会话标题, 只输出标题本身:\n\n${seedText
- .trim()
- .slice(0, 300)}`,
- { maxTokens: 24, timeoutMs: 12_000, reasoningEffort: 'minimal' },
- );
- if (r.ok) {
- const text = r.text.trim().replace(/^["'「『]+|["'」』]+$/g, '').slice(0, 40);
- if (text) return text;
- }
- } catch {
- /* swallow — 兜底失败保持原样 */
- }
- return null;
+ return (await generateMakerSessionTitle(seedText, 'claude-code', sessionId))?.trim() || null;
}
/** 落库 + 广播一个已拼装好的标题(渠道 composeGeneratedTitle 的产物)。 */
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.ts
index 047b518811..7e72290c69 100644
--- 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.ts
@@ -1,32 +1,35 @@
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;
- },
+ models: [] as string[],
+ ownerScope: 'local:owner-a:1',
requestText: vi.fn(),
- generateLegacy: vi.fn(),
- generateLegacyResult: vi.fn(),
+ oneShot: vi.fn(),
+ chainSource: 'auto' as 'auto' | 'custom' | 'env',
+ sessionBoundaryPending: false,
+ oneShotRouteDisabled: false,
}));
vi.mock('../../logger.js', () => ({
createLogger: () => ({ warn: vi.fn() }),
}));
-vi.mock('../../utility-model/auxiliary-model-settings-store.js', () => ({
- readAuxiliaryModelSelection: () => h.selection,
+vi.mock('../index.js', () => ({
+ getMaker: () => ({ oneShot: h.oneShot }),
}));
-vi.mock('../../utility-model/oneShotCandidates.js', () => ({
- requestExplicitUtilityText: (...args: unknown[]) => h.requestText(...args),
+vi.mock('../model-route-guard-live.js', () => ({
+ isAgentOneShotRouteDisabled: vi.fn(async () => h.oneShotRouteDisabled),
}));
-vi.mock('../title-one-shot.js', () => ({
- generateTitleViaProvider: (...args: unknown[]) => h.generateLegacy(...args),
- generateTitleViaProviderResult: (...args: unknown[]) => h.generateLegacyResult(...args),
+vi.mock('../../appSessionState.js', () => ({
+ activeOwnerScopeKey: () => h.ownerScope,
+ isAppSessionBoundaryPending: () => h.sessionBoundaryPending,
+}));
+
+vi.mock('../../utility-model/resolveAuxiliaryModelChain.js', () => ({
+ getEffectiveAuxiliaryModelChain: () => ({ source: h.chainSource, refs: [] }),
+ getEffectiveAuxiliaryModelChainSnapshot: () => JSON.stringify({ source: h.chainSource, refs: [] }),
}));
import {
@@ -40,95 +43,187 @@ const REQUEST = {
prompt: '给这项工作起名',
};
-const SELECTION = {
- pin: 'cat:openrouter:codex:openai/gpt-5-mini',
- providerId: 'openrouter',
+const CODEX_REQUEST = {
+ ...REQUEST,
agentKind: 'codex' as const,
- model: 'openai/gpt-5-mini',
};
+function runtimeDeps() {
+ return {
+ readModels: () => h.models,
+ readOwnerScope: () => h.ownerScope,
+ requestText: h.requestText,
+ };
+}
+
beforeEach(() => {
vi.clearAllMocks();
- h.selection = null;
- h.generateLegacy.mockResolvedValue('旧自动路由标题');
- h.generateLegacyResult.mockResolvedValue({ status: 'ok', title: '旧自动路由标题' });
+ h.models = [];
+ h.ownerScope = 'local:owner-a:1';
+ h.chainSource = 'auto';
+ h.sessionBoundaryPending = false;
+ h.oneShotRouteDisabled = false;
+ h.oneShot.mockResolvedValue('会话 Agent 命名');
+ h.requestText.mockImplementation(async (_prompt: string, options: Record<string, unknown>) => {
+ const allowed = await (options.beforeDispatch as () => Promise<boolean>)();
+ return allowed
+ ? {
+ ok: true,
+ text: '通用任务命名',
+ providerId: 'xd',
+ model: 'gpt-5.4-mini',
+ transport: 'litellm-chat-completions',
+ }
+ : { ok: false, reason: 'all_candidates_failed', attempts: [] };
+ });
});
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: [] };
- });
+ it('uses the shared utility chain in automatic mode', async () => {
+ await expect(generateTitleWithAuxiliaryModel(REQUEST, {}, runtimeDeps())).resolves.toBe(
+ '通用任务命名',
+ );
- await expect(generateTitleWithAuxiliaryModel(REQUEST)).resolves.toBe('通用任务命名');
expect(h.requestText).toHaveBeenCalledWith(
REQUEST.prompt,
expect.objectContaining({
- providerId: 'openrouter',
- agentKind: 'codex',
- model: 'openai/gpt-5-mini',
disableReasoning: true,
reasoningEffort: 'minimal',
responseInstructions: expect.stringContaining('Output only the short conversation title'),
}),
);
- expect(h.generateLegacy).not.toHaveBeenCalled();
});
- it('fails closed instead of falling back when the configured model fails', async () => {
- h.selection = { ...SELECTION };
+ it('falls back to the same session agent when the automatic chain is exhausted', async () => {
h.requestText.mockResolvedValue({
ok: false,
reason: 'all_candidates_failed',
attempts: [],
});
- await expect(generateTitleWithAuxiliaryModel(REQUEST)).resolves.toBeNull();
- await expect(generateTitleWithAuxiliaryModelResult(REQUEST)).resolves.toEqual({
- status: 'failed',
+ await expect(generateTitleWithAuxiliaryModel(CODEX_REQUEST, {}, runtimeDeps())).resolves.toBe(
+ '会话 Agent 命名',
+ );
+ expect(h.oneShot).toHaveBeenCalledWith(
+ 'codex',
+ CODEX_REQUEST.prompt,
+ expect.objectContaining({
+ maxTokens: 32,
+ responseInstructions: expect.stringContaining('Output only the short conversation title'),
+ }),
+ );
+ });
+
+ it('rechecks the disabled route while the session-agent fallback is starting', async () => {
+ h.requestText.mockResolvedValue({
+ ok: false,
+ reason: 'all_candidates_failed',
+ attempts: [],
+ });
+ h.oneShot.mockImplementation(async (_agentKind, _prompt, options) => {
+ h.oneShotRouteDisabled = true;
+ const allowed = await (options.beforeDispatch as () => Promise<boolean>)();
+ if (!allowed) throw new Error('disabled during startup');
+ return '不应采用';
});
- expect(h.generateLegacy).not.toHaveBeenCalled();
- expect(h.generateLegacyResult).not.toHaveBeenCalled();
+
+ await expect(generateTitleWithAuxiliaryModel(CODEX_REQUEST, {}, runtimeDeps())).resolves.toBeNull();
+ });
+
+ it('keeps an explicit custom chain fail-closed when it is exhausted', async () => {
+ h.chainSource = 'custom';
+ h.requestText.mockResolvedValue({
+ ok: false,
+ reason: 'all_candidates_failed',
+ attempts: [],
+ });
+
+ await expect(generateTitleWithAuxiliaryModel(CODEX_REQUEST, {}, runtimeDeps())).resolves.toBeNull();
+ expect(h.oneShot).not.toHaveBeenCalled();
});
it('cancels dispatch when the selected setting changes during credential work', async () => {
- h.selection = { ...SELECTION };
+ h.models = ['codex-gpt-5.4-mini'];
+ h.requestText.mockImplementation(async (_prompt: string, options: Record<string, unknown>) => {
+ h.models = [];
+ const allowed = await (options.beforeDispatch as () => Promise<boolean>)();
+ return allowed
+ ? {
+ ok: true,
+ text: '不应采用',
+ providerId: 'xd',
+ model: 'gpt-5.4-mini',
+ transport: 'litellm-chat-completions',
+ }
+ : { ok: false, reason: 'all_candidates_failed', attempts: [] };
+ });
+
+ await expect(generateTitleWithAuxiliaryModel(REQUEST, {}, runtimeDeps())).resolves.toBeNull();
+ });
+
+ it('cancels dispatch when the owner scope changes even if the model list is unchanged', async () => {
+ h.models = ['codex-gpt-5.4-mini'];
+ h.requestText.mockImplementation(async (_prompt: string, options: Record<string, unknown>) => {
+ h.ownerScope = 'cloud:owner-b:2';
+ const allowed = await (options.beforeDispatch as () => Promise<boolean>)();
+ return allowed
+ ? {
+ ok: true,
+ text: '不应采用',
+ providerId: 'xd',
+ model: 'gpt-5.4-mini',
+ transport: 'litellm-chat-completions',
+ }
+ : { ok: false, reason: 'all_candidates_failed', attempts: [] };
+ });
+
+ await expect(generateTitleWithAuxiliaryModel(REQUEST, {}, runtimeDeps())).resolves.toBeNull();
+ });
+
+ it('rechecks the owner scope after an async model read', async () => {
+ h.models = ['codex-gpt-5.4-mini'];
+ let readCount = 0;
+ const readModels = vi.fn(async () => {
+ readCount += 1;
+ if (readCount === 2) h.ownerScope = 'cloud:owner-b:2';
+ return h.models;
+ });
+ h.requestText.mockImplementation(async (_prompt: string, options: Record<string, unknown>) => {
+ const allowed = await (options.beforeDispatch as () => Promise<boolean>)();
+ return allowed
+ ? {
+ ok: true,
+ text: '不应采用',
+ providerId: 'xd',
+ model: 'gpt-5.4-mini',
+ transport: 'litellm-chat-completions',
+ }
+ : { ok: false, reason: 'all_candidates_failed', attempts: [] };
+ });
+
+ await expect(generateTitleWithAuxiliaryModel(REQUEST, {}, {
+ ...runtimeDeps(),
+ readModels,
+ })).resolves.toBeNull();
+ });
+
+ it('fails closed while the app session boundary is pending', async () => {
+ h.models = ['codex-gpt-5.4-mini'];
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);
+ h.sessionBoundaryPending = true;
+ const allowed = await (options.beforeDispatch as () => Promise<boolean>)();
return allowed
? {
ok: true,
text: '不应采用',
- providerId: SELECTION.providerId,
- model: SELECTION.model,
+ providerId: 'xd',
+ model: 'gpt-5.4-mini',
transport: 'litellm-chat-completions',
}
: { ok: false, reason: 'all_candidates_failed', attempts: [] };
});
- await expect(generateTitleWithAuxiliaryModel(REQUEST)).resolves.toBeNull();
- expect(h.generateLegacy).not.toHaveBeenCalled();
+ await expect(generateTitleWithAuxiliaryModel(REQUEST, {}, runtimeDeps())).resolves.toBeNull();
+ expect(h.oneShot).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.ts
index 88aa8f97fa..db1b6ec5eb 100644
--- a/apps/desktop/src/main/maker-host/auxiliary-title-one-shot.ts
+++ b/apps/desktop/src/main/maker-host/auxiliary-title-one-shot.ts
@@ -1,25 +1,27 @@
/**
- * Session-title routing with an optional global catalog pin.
+ * Session-title routing through the shared auxiliary-model chain.
*
- * 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.
+ * Automatic and custom chains both go through `requestUtilityText`. Automatic
+ * routing may fall back to the owning session agent when the auxiliary chain
+ * is unavailable; an explicit custom/env chain remains fail-closed.
*/
import type { AgentKind } from '@cindy/maker-core';
+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';
import { createLogger } from '../logger.js';
-import type { AuxiliaryModelSelection } from '../utility-model/auxiliary-model-settings-store.js';
-import type {
- requestExplicitUtilityText,
- UtilityTextDispatchRoute,
+import { isAgentOneShotRouteDisabled } from './model-route-guard-live.js';
+import { readAuxiliaryModelSettings } from '../utility-model/auxiliary-model-settings-store.js';
+import {
+ agentSupportsOneShot,
+ requestUtilityText,
} from '../utility-model/oneShotCandidates.js';
-import type {
- generateTitleViaProvider,
- generateTitleViaProviderResult,
- TitleOneShotDeps,
- TitleOneShotResult,
-} from './title-one-shot.js';
+import {
+ getEffectiveAuxiliaryModelChain,
+ getEffectiveAuxiliaryModelChainSnapshot,
+} from '../utility-model/resolveAuxiliaryModelChain.js';
+import { getMaker } from './index.js';
+import type { TitleOneShotDeps, TitleOneShotResult } from './title-one-shot.js';
import { validateTitleOutput } from './title-output-validation.js';
const log = createLogger('maker-host/auxiliary-title-one-shot');
@@ -32,40 +34,18 @@ const AUXILIARY_TITLE_RESPONSE_INSTRUCTIONS =
'Output only the short conversation title requested by the user message, without quotation marks or ending punctuation.';
interface AuxiliaryTitleRuntimeDeps {
- readSelection: (
- key: 'sessionTitleModel',
- ) => AuxiliaryModelSelection | null | Promise<AuxiliaryModelSelection | null>;
- requestText: typeof requestExplicitUtilityText;
- generateLegacy: typeof generateTitleViaProvider;
- generateLegacyResult: typeof generateTitleViaProviderResult;
+ readModels: () => string[] | Promise<string[]>;
+ readOwnerScope: () => string | Promise<string>;
+ requestText: (
+ prompt: string,
+ opts: Parameters<typeof requestUtilityText>[2],
+ ) => ReturnType<typeof requestUtilityText>;
}
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);
- },
+ readModels: () => readAuxiliaryModelSettings().models,
+ readOwnerScope: () => activeOwnerScopeKey(),
+ requestText: (prompt, opts) => requestUtilityText(getMaker(), prompt, opts),
};
type TitleRequest = {
@@ -75,26 +55,28 @@ type TitleRequest = {
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(
+async function generateAuxiliaryTitle(
args: TitleRequest,
- selection: AuxiliaryModelSelection,
deps: AuxiliaryTitleRuntimeDeps,
): Promise<TitleOneShotResult> {
+ const ownerScope = await deps.readOwnerScope();
+ const models = [...await deps.readModels()];
+ const snapshot = JSON.stringify(models);
+ const auxiliaryChain = getEffectiveAuxiliaryModelChain();
+ const auxiliaryChainSnapshot = getEffectiveAuxiliaryModelChainSnapshot();
+ const beforeDispatch = async () => {
+ if (isAppSessionBoundaryPending()) return false;
+ if ((await deps.readOwnerScope()) !== ownerScope) return false;
+ if (getEffectiveAuxiliaryModelChainSnapshot() !== auxiliaryChainSnapshot) return false;
+ const currentModels = JSON.stringify(await deps.readModels());
+ return !isAppSessionBoundaryPending()
+ && (await deps.readOwnerScope()) === ownerScope
+ && getEffectiveAuxiliaryModelChainSnapshot() === auxiliaryChainSnapshot
+ && currentModels === snapshot;
+ };
+ const beforeSessionAgentDispatch = async () =>
+ !(await isAgentOneShotRouteDisabled(args.agentKind)) && await beforeDispatch();
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,
// Short title budgets cannot afford provider-default thinking. Messages /
@@ -104,50 +86,67 @@ async function generateExplicitTitle(
reasoningEffort: 'minimal',
responseInstructions: AUXILIARY_TITLE_RESPONSE_INSTRUCTIONS,
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);
- },
+ // Settings may change while OAuth refresh/credential discovery awaits.
+ beforeDispatch,
});
if (!result.ok) {
- log.warn('explicit auxiliary title model failed', {
- providerId: selection.providerId,
- model: selection.model,
+ // A signed-out user still has the current session agent available. Only
+ // the automatic chain may use that same-agent fallback; custom and env
+ // chains are explicit routing decisions and must remain fail-closed.
+ const canFallbackToSessionAgent = auxiliaryChain.source === 'auto'
+ && agentSupportsOneShot(args.agentKind)
+ && await beforeSessionAgentDispatch();
+ if (canFallbackToSessionAgent) {
+ try {
+ const fallbackText = await getMaker().oneShot(args.agentKind, args.prompt, {
+ maxTokens: AUXILIARY_TITLE_MAX_TOKENS,
+ timeoutMs: AUXILIARY_TITLE_TIMEOUT_MS,
+ signal: args.signal,
+ responseInstructions: AUXILIARY_TITLE_RESPONSE_INSTRUCTIONS,
+ beforeDispatch: beforeSessionAgentDispatch,
+ });
+ const fallbackTitle = normalizeAuxiliaryTitle(fallbackText);
+ if (fallbackTitle) return { status: 'ok', title: fallbackTitle };
+ } catch (error) {
+ log.warn('auxiliary title session agent fallback failed', {
+ errorName: error instanceof Error ? error.name : typeof error,
+ });
+ }
+ }
+ log.warn('auxiliary title model failed', {
reason: result.reason,
});
return { status: 'failed' };
}
+ const title = normalizeAuxiliaryTitle(result.text);
+ return title ? { status: 'ok', title } : { status: 'failed' };
+}
+
+function normalizeAuxiliaryTitle(text: string): string | null {
// 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
+ const normalized = validateTitleOutput(text, AUXILIARY_TITLE_OUTPUT_MAX_CHARS);
+ return 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 = {},
+ _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);
+ const result = await generateAuxiliaryTitle(args, deps);
return result.status === 'ok' ? result.title : null;
}
export async function generateTitleWithAuxiliaryModelResult(
args: TitleRequest,
- legacyDeps: TitleOneShotDeps = {},
+ _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);
+ return generateAuxiliaryTitle(args, deps);
}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/autoTitleIpcBoundary.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/autoTitleIpcBoundary.test.ts
index 6b57c55042..d22a7a9c74 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/autoTitleIpcBoundary.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/autoTitleIpcBoundary.test.ts
@@ -60,12 +60,9 @@ vi.mock('../../localDb/latestMessageText.js', () => ({
vi.mock('../../maker-host/createDesktopProviderService.js', () => ({
getDesktopProviderService: vi.fn(),
}));
-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('../../maker-host/auxiliary-title-one-shot.js', () => ({
+ generateTitleWithAuxiliaryModel: h.generateTitle,
+ generateTitleWithAuxiliaryModelResult: h.generateTitleResult,
}));
vi.mock('../../messagePersistBroadcaster.js', () => ({
drainPersistQueue: h.drainPersistQueue,
@@ -79,6 +76,11 @@ vi.mock('../../security/trustedAppRenderer.js', () => ({
}
},
}));
+// title.ts imports promptPrediction statically; this boundary suite does not
+// exercise prediction itself, so keep the maker-host graph out of collection.
+vi.mock('../promptPrediction.js', () => ({
+ generatePromptPrediction: vi.fn(),
+}));
import { registerMakerTitleIpc } from '../title.js';
import { getDbClient } from '../../localDb/client/current.js';
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/auxiliaryModelSettings.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/auxiliaryModelSettings.test.ts
index c4b8e6a073..993e72735e 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/auxiliaryModelSettings.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/auxiliaryModelSettings.test.ts
@@ -10,6 +10,7 @@ vi.mock('../../logger.js', () => ({
vi.mock('../../maker-host/active-catalog.js', () => ({
getActiveCatalog: () => ({ providers: [] }),
+ isXdGatewayPaymentRequiredRoute: () => false,
}));
vi.mock('../../maker-host/model-disable-store.js', () => ({
@@ -29,6 +30,11 @@ vi.mock('../../utility-model/oneshotProviderUsability.js', () => ({
hasOneshotProviderCredential: () => false,
}));
+vi.mock('../../utility-model/oneShotCandidates.js', () => ({
+ isUtilityRouteDisabled: () => false,
+ isUtilityRoutePaymentRequired: () => false,
+}));
+
vi.mock('../../security/trustedAppRenderer.js', () => ({
assertTrustedAppRendererEvent: vi.fn(),
}));
@@ -39,6 +45,7 @@ import {
} from '../auxiliary-model-settings.js';
const PIN = 'cat:openrouter:codex:openai/gpt-5-mini';
+const PROFILE = 'codex-gpt-5.4-mini';
function catalog() {
return {
@@ -71,33 +78,63 @@ function catalog() {
} as never;
}
+function builtinCodexCatalog() {
+ return {
+ providers: [
+ {
+ id: 'openai',
+ name: 'OpenAI',
+ source: 'builtin',
+ agents: ['codex'],
+ auth: { method: 'oauth' },
+ routing: {
+ codex: {
+ upstream: 'https://openai.example/v1',
+ authStrategy: 'oauth-passthrough',
+ },
+ },
+ models: { codex: [] },
+ },
+ ],
+ } as never;
+}
+
describe('auxiliary model settings IPC helpers', () => {
- it('accepts only known canonical pins and null resets', () => {
+ it('accepts a unique models list and empty automatic reset', () => {
const allowed = new Set([PIN]);
- expect(parseAuxiliaryModelSettingsPatch({ sessionTitleModel: PIN }, allowed)).toEqual({
- sessionTitleModel: PIN,
+ expect(parseAuxiliaryModelSettingsPatch({ models: [PIN] }, allowed)).toEqual({
+ models: [PIN],
+ });
+ expect(parseAuxiliaryModelSettingsPatch({ models: [] }, allowed)).toEqual({
+ models: [],
+ });
+ expect(parseAuxiliaryModelSettingsPatch({ models: [PROFILE] }, allowed)).toEqual({
+ models: [PROFILE],
});
+ });
+
+ it('keeps a persisted catalog pin removable even when it left the live allowlist', () => {
expect(
- parseAuxiliaryModelSettingsPatch({ promptRecommendationModel: null }, allowed),
- ).toEqual({ promptRecommendationModel: null });
+ parseAuxiliaryModelSettingsPatch({ models: [PIN] }, new Set(), new Set([PIN])),
+ ).toEqual({ models: [PIN] });
+ });
+ it('rejects unknown keys, padded refs, and unroutable catalog pins', () => {
+ const allowed = new Set([PIN]);
expect(() =>
- parseAuxiliaryModelSettingsPatch({ sessionTitleModel: ` ${PIN}` }, allowed),
- ).toThrow(/canonical catalog model pin/);
+ parseAuxiliaryModelSettingsPatch({ sessionTitleModel: PIN }, allowed),
+ ).toThrow(/invalid keys/);
expect(() =>
- parseAuxiliaryModelSettingsPatch(
- { sessionTitleModel: 'cat:other:codex:model' },
- allowed,
- ),
- ).toThrow(/currently routable/);
+ parseAuxiliaryModelSettingsPatch({ models: [` ${PIN}`] }, allowed),
+ ).toThrow(/unique list of at most 3/);
expect(() =>
- parseAuxiliaryModelSettingsPatch({ unexpected: PIN }, allowed),
- ).toThrow(/invalid keys/);
+ parseAuxiliaryModelSettingsPatch({ models: ['cat:other:codex:model'] }, allowed),
+ ).toThrow(/not currently routable/);
});
it('keeps a selected but credential-unavailable route visible and removable', () => {
const options = buildAuxiliaryModelOptions({
- settings: { sessionTitleModel: PIN, promptRecommendationModel: null },
+ settings: { models: [PIN] },
catalog: catalog(),
overrides: { disabledModels: {}, disabledProviders: {} },
hasCredential: () => false,
@@ -113,10 +150,27 @@ describe('auxiliary model settings IPC helpers', () => {
]);
});
+ it('marks a migrated utility profile available when its direct route is usable', () => {
+ const options = buildAuxiliaryModelOptions({
+ settings: { models: [PROFILE] },
+ catalog: builtinCodexCatalog(),
+ overrides: { disabledModels: {}, disabledProviders: {} },
+ hasCredential: () => true,
+ });
+
+ expect(options).toEqual([
+ expect.objectContaining({
+ id: PROFILE,
+ providerId: 'openai',
+ available: true,
+ }),
+ ]);
+ });
+
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 },
+ settings: { models: [stalePin] },
catalog: catalog(),
overrides: { disabledModels: {}, disabledProviders: {} },
hasCredential: () => true,
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/predictPromptIpcBoundary.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/predictPromptIpcBoundary.test.ts
index 9b4e253a10..e2a3e227df 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/predictPromptIpcBoundary.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/predictPromptIpcBoundary.test.ts
@@ -271,6 +271,13 @@ vi.mock('../../localDb/client/current.js', () => ({
vi.mock('../promptPrediction.js', () => ({
generatePromptPrediction: h.predict,
}));
+// `maker-ipc/title.ts` statically imports the auxiliary title router, whose
+// production default dependency reads the Maker facade. Keep this boundary
+// test's existing lightweight module graph instead of evaluating the full
+// maker-host assembly during collection.
+vi.mock('../../maker-host/index.js', () => ({
+ getMaker: vi.fn(() => ({})),
+}));
vi.mock('../../messagePersistBroadcaster.js', () => ({
drainPersistQueue: h.drainPersistQueue,
}));
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/promptPredictionRevision.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/promptPredictionRevision.test.ts
index 71296581f9..6121a31c5c 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/promptPredictionRevision.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/promptPredictionRevision.test.ts
@@ -14,17 +14,9 @@ const h = vi.hoisted(() => ({
}>,
dbReads: 0,
beforeDispatchCalls: 0,
- providers: [{ id: 'provider-1' }],
- resolvedProviderId: 'provider-1',
+ models: [] as string[],
afterDispatch: null as null | (() => void),
- auxiliarySelection: null as null | {
- pin: string;
- providerId: string;
- agentKind: 'codex' | 'claude-code';
- model: string;
- },
- legacyCalls: 0,
- explicitRequest: vi.fn(),
+ requestUtilityText: vi.fn(),
}));
vi.mock('../../logger.js', () => ({
@@ -53,48 +45,16 @@ vi.mock('../../localDb/client/current.js', () => ({
}),
}));
-vi.mock('../../maker-host/createDesktopProviderService.js', () => ({
- getDesktopProviderService: () => ({
- listProviders: async () => h.providers,
- }),
-}));
-
-vi.mock('@cindy/model-providers', () => ({
- connectedProvidersForAgent: (providers: unknown[]) => providers,
- nativeDefaultSourceId: () => 'provider-1',
-}));
-
-vi.mock('../../maker-host/title-one-shot.js', () => ({
- buildTitleTarget: (providerId: string) =>
- providerId === 'provider-1' || providerId === 'xd' ? { providerId } : null,
- generateTitleViaProviderResult: async (
- request: { sessionId: string; agentKind: string },
- deps: {
- beforeDispatch?: (input: {
- sessionId: string;
- agentKind: string;
- providerId: string;
- }) => Promise<boolean>;
- },
- ) => {
- h.legacyCalls += 1;
- h.beforeDispatchCalls += 1;
- const allowed = await deps.beforeDispatch?.({
- sessionId: request.sessionId,
- agentKind: request.agentKind,
- providerId: h.resolvedProviderId,
- });
- if (allowed) h.afterDispatch?.();
- return allowed ? { status: 'ok', title: '继续补测试' } : { status: 'aborted', title: null };
- },
-}));
-
vi.mock('../../utility-model/auxiliary-model-settings-store.js', () => ({
- readAuxiliaryModelSelection: () => h.auxiliarySelection,
+ readAuxiliaryModelSettings: () => ({ models: h.models }),
}));
vi.mock('../../utility-model/oneShotCandidates.js', () => ({
- requestExplicitUtilityText: (...args: unknown[]) => h.explicitRequest(...args),
+ requestUtilityText: (...args: unknown[]) => h.requestUtilityText(...args),
+}));
+
+vi.mock('../../maker-host/index.js', () => ({
+ getMaker: () => ({}),
}));
import { generatePromptPrediction } from '../promptPrediction.js';
@@ -133,13 +93,31 @@ beforeEach(() => {
vi.clearAllMocks();
h.dbReads = 0;
h.beforeDispatchCalls = 0;
- h.providers = [{ id: 'provider-1' }];
- h.resolvedProviderId = 'provider-1';
h.afterDispatch = null;
- h.auxiliarySelection = null;
- h.legacyCalls = 0;
- h.explicitRequest.mockReset();
+ h.models = [];
h.rows = [{ ...VALID_ROW }, { ...VALID_ROW }];
+ h.requestUtilityText.mockImplementation(
+ async (_maker: unknown, _prompt: string, options: Record<string, unknown>) => {
+ h.beforeDispatchCalls += 1;
+ const allowed = await (
+ options.beforeDispatch as (route?: unknown) => Promise<boolean>
+ )({
+ providerId: 'xd',
+ agentKind: 'codex',
+ model: 'gpt-5.4-mini',
+ });
+ if (allowed) h.afterDispatch?.();
+ return allowed
+ ? {
+ ok: true,
+ text: '继续补测试',
+ providerId: 'xd',
+ model: 'gpt-5.4-mini',
+ transport: 'litellm-chat-completions',
+ }
+ : { ok: false, reason: 'all_candidates_failed', attempts: [] };
+ },
+ );
resetPromptPredictionStopLedgerForTests();
});
@@ -148,11 +126,18 @@ describe('prompt prediction completion revision guard', () => {
await expect(predict()).resolves.toBe('继续补测试');
expect(h.beforeDispatchCalls).toBe(1);
expect(h.dbReads).toBe(2);
+ expect(h.requestUtilityText).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.any(String),
+ expect.objectContaining({
+ disableReasoning: true,
+ reasoningEffort: 'minimal',
+ systemPrompt: expect.stringContaining('terse predictive text engine'),
+ }),
+ );
});
- it('显式 custom provider 没有 title wire 时允许回落官方 xd', async () => {
- h.providers = [{ id: 'custom:deepseek' }, { id: 'xd' }];
- h.resolvedProviderId = 'xd';
+ it('会话 custom provider 不挡 utility 预测', async () => {
h.rows = [
{ ...VALID_ROW, providerId: 'custom:deepseek' },
{ ...VALID_ROW, providerId: 'custom:deepseek' },
@@ -194,53 +179,4 @@ 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',
- disableReasoning: true,
- 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.ts
index ec1bc2c33c..57d2f6bf32 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/regenerateSessionTitle.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/regenerateSessionTitle.test.ts
@@ -24,26 +24,26 @@ vi.mock('../../localDb/latestMessageText.js', () => ({
vi.mock('../../maker-host/createDesktopProviderService.js', () => ({
getDesktopProviderService: vi.fn(),
}));
-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('../../maker-host/auxiliary-title-one-shot.js', () => ({
+ generateTitleWithAuxiliaryModel: vi.fn(),
+ generateTitleWithAuxiliaryModelResult: vi.fn(),
}));
vi.mock('../../i18n.js', () => ({
getResolvedMainLocale: vi.fn(() => 'en'),
}));
+// title.ts imports promptPrediction statically; this suite covers the
+// dependency-injected title flow and should not initialize maker-host.
+vi.mock('../promptPrediction.js', () => ({
+ generatePromptPrediction: vi.fn(),
+}));
import {
generateMakerSessionTitle,
regenerateMakerSessionTitle,
type RegenerateTitleDeps,
} from '../title.js';
-import {
- generateTitleViaProvider,
- type TitleOneShotResult,
-} from '../../maker-host/title-one-shot.js';
+import { generateTitleWithAuxiliaryModel } from '../../maker-host/auxiliary-title-one-shot.js';
+import type { TitleOneShotResult } from '../../maker-host/title-one-shot.js';
import { getResolvedMainLocale } from '../../i18n.js';
import type { RegenerateTitleMaterial } from '../../localDb/latestMessageText.js';
@@ -371,21 +371,21 @@ describe('regenerateMakerSessionTitle', () => {
describe('generateMakerSessionTitle', () => {
it('空/全空白消息(如仅图片附件的首条输入)→ null 且不发标题请求', async () => {
- vi.mocked(generateTitleViaProvider).mockClear();
+ vi.mocked(generateTitleWithAuxiliaryModel).mockClear();
expect(await generateMakerSessionTitle('', 'claude-code', 's1')).toBeNull();
expect(await generateMakerSessionTitle(' \n ', 'codex', 's1')).toBeNull();
- expect(generateTitleViaProvider).not.toHaveBeenCalled();
+ expect(generateTitleWithAuxiliaryModel).not.toHaveBeenCalled();
});
it('非空消息走 provider oneShot,prompt 使用 trim 后的消息', async () => {
- vi.mocked(generateTitleViaProvider).mockClear();
- vi.mocked(generateTitleViaProvider).mockResolvedValueOnce('登录失败排查');
+ vi.mocked(generateTitleWithAuxiliaryModel).mockClear();
+ vi.mocked(generateTitleWithAuxiliaryModel).mockResolvedValueOnce('登录失败排查');
expect(await generateMakerSessionTitle(' 帮我排查登录失败 ', 'claude-code', 's1')).toBe(
'登录失败排查',
);
- const [request] = vi.mocked(generateTitleViaProvider).mock.calls[0] as [
+ const [request] = vi.mocked(generateTitleWithAuxiliaryModel).mock.calls[0] as [
{ sessionId: string; agentKind: string; prompt: string },
];
expect(request.sessionId).toBe('s1');
@@ -401,12 +401,12 @@ describe('generateMakerSessionTitle', () => {
['ko', 'Korean'],
] as const)('界面语言 %s → auto-title prompt 明确要求 %s 标题', async (locale, language) => {
vi.mocked(getResolvedMainLocale).mockReturnValue(locale);
- vi.mocked(generateTitleViaProvider).mockClear();
- vi.mocked(generateTitleViaProvider).mockResolvedValueOnce('title');
+ vi.mocked(generateTitleWithAuxiliaryModel).mockClear();
+ vi.mocked(generateTitleWithAuxiliaryModel).mockResolvedValueOnce('title');
await generateMakerSessionTitle('message', 'claude-code', 's1');
- const request = vi.mocked(generateTitleViaProvider).mock.calls[0]?.[0];
+ const request = vi.mocked(generateTitleWithAuxiliaryModel).mock.calls[0]?.[0];
expect(request?.prompt).toContain(`Write the title in ${language}.`);
});
});
diff --git a/apps/desktop/src/main/maker-ipc/auxiliary-model-settings.ts b/apps/desktop/src/main/maker-ipc/auxiliary-model-settings.ts
index 369439d1c1..398819b7bb 100644
--- a/apps/desktop/src/main/maker-ipc/auxiliary-model-settings.ts
+++ b/apps/desktop/src/main/maker-ipc/auxiliary-model-settings.ts
@@ -1,10 +1,10 @@
-/** Settings IPC for global auxiliary text model choices. */
+/** Settings IPC for the shared auxiliary-model chain. */
import { ipcMain } from 'electron';
import type { Catalog, ModelDisableOverrides } from '@cindy/model-providers';
import {
- isValidAuxiliaryModelPinInput,
+ isValidAuxiliaryModelListInput,
type AuxiliaryModelOption,
type AuxiliaryModelSettings,
type AuxiliaryModelSettingsPatch,
@@ -12,11 +12,17 @@ import {
} from '../../shared/auxiliaryModelSettings.js';
import { decodeCatalogModelPin } from '../../shared/catalogModelPin.js';
import { isIpcError } from '../../shared/ipc-errors.js';
+import {
+ getUtilityModelProfile,
+ isUtilityModelProviderKind,
+ utilityTransportLabel,
+} from '../../shared/utilityModelProfiles.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 {
+ readAuxiliaryModelSettings,
readAuxiliaryModelSettingsState,
writeAuxiliaryModelSettingsPatch,
} from '../utility-model/auxiliary-model-settings-store.js';
@@ -26,6 +32,10 @@ import {
type OneshotCredentialProbe,
type TextOneshotPinOption,
} from '../utility-model/textOneshotPinOptions.js';
+import {
+ isUtilityRouteDisabled,
+ isUtilityRoutePaymentRequired,
+} from '../utility-model/oneShotCandidates.js';
import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
import { throwIpcError } from '../utils/ipcValidate.js';
import { MAKER_INVOKE } from './channels.js';
@@ -43,6 +53,37 @@ function toWireOption(option: TextOneshotPinOption, available: boolean): Auxilia
};
}
+function syntheticProfileOption(
+ id: string,
+ args: {
+ catalog: Catalog;
+ hasCredential?: OneshotCredentialProbe;
+ },
+): AuxiliaryModelOption {
+ const profile = getUtilityModelProfile(id as Parameters<typeof getUtilityModelProfile>[0]);
+ const providerId = profile.transport === 'codex-responses' ? 'openai' : 'xd';
+ const provider = args.catalog.providers.find((item) => item.id === providerId);
+ const available = Boolean(
+ provider
+ && args.hasCredential?.(provider, 'codex')
+ && !isUtilityRouteDisabled(profile)
+ && !isUtilityRoutePaymentRequired(profile),
+ );
+ return {
+ id,
+ label: `${profile.model} · ${utilityTransportLabel(profile.transport)}`,
+ group: providerId,
+ providerId,
+ agentKind: 'codex',
+ modelId: profile.model,
+ modelName: profile.model,
+ budget: false,
+ subscription: profile.transport === 'codex-responses',
+ agentSuffix: 'Codex',
+ available,
+ };
+}
+
/**
* Return currently usable choices plus any persisted-but-unavailable selections.
* The latter remain visible and removable without becoming selectable elsewhere.
@@ -65,18 +106,20 @@ export function buildAuxiliaryModelOptions(args: {
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) {
+ for (const pin of args.settings.models) {
if (availableIds.has(pin)) continue;
const known = allById.get(pin);
if (known) {
result.push(toWireOption(known, false));
continue;
}
+ if (isUtilityModelProviderKind(pin)) {
+ result.push(syntheticProfileOption(pin, {
+ catalog: args.catalog,
+ hasCredential: args.hasCredential,
+ }));
+ continue;
+ }
const decoded = decodeCatalogModelPin(pin);
if (!decoded) continue;
result.push({
@@ -98,13 +141,15 @@ export function buildAuxiliaryModelOptions(args: {
function settingsWire(): AuxiliaryModelSettingsState {
const state = readAuxiliaryModelSettingsState();
+ const models = Array.isArray(state.value.models) ? state.value.models : [];
+ const settings = { models };
return {
- ...state.value,
+ models,
isCustomized: state.isCustomized,
customizedKeys: state.customizedKeys,
- defaults: state.defaults,
+ defaults: state.defaults ?? { models: [] },
options: buildAuxiliaryModelOptions({
- settings: state.value,
+ settings,
catalog: getActiveCatalog(),
overrides: readModelDisableOverrides(),
providerOrder: readProviderOrder(),
@@ -116,29 +161,25 @@ function settingsWire(): AuxiliaryModelSettingsState {
export function parseAuxiliaryModelSettingsPatch(
raw: unknown,
allowedPins: ReadonlySet<string>,
+ persistedPins: ReadonlySet<string> = new Set(),
): 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))) {
+ if (keys.length === 0 || keys.some((key) => key !== 'models')) {
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;
+ if (!isValidAuxiliaryModelListInput(input.models)) {
+ throwIpcError('INVALID_PARAMS', 'models must be a unique list of at most 3 auxiliary refs');
}
- return patch;
+ for (const entry of input.models) {
+ if (isUtilityModelProviderKind(entry)) continue;
+ if (allowedPins.has(entry) || persistedPins.has(entry)) continue;
+ throwIpcError('INVALID_PARAMS', 'models contains a catalog pin that is not currently routable');
+ }
+ return { models: input.models };
}
export function registerAuxiliaryModelSettingsIpc(): void {
@@ -165,7 +206,11 @@ export function registerAuxiliaryModelSettingsIpc(): void {
readProviderOrder(),
).map((option) => option.id),
);
- const patch = parseAuxiliaryModelSettingsPatch(rawPatch, allowedPins);
+ const patch = parseAuxiliaryModelSettingsPatch(
+ rawPatch,
+ allowedPins,
+ new Set(readAuxiliaryModelSettings().models),
+ );
await writeAuxiliaryModelSettingsPatch(patch);
return settingsWire();
} catch (error) {
diff --git a/apps/desktop/src/main/maker-ipc/help.ts b/apps/desktop/src/main/maker-ipc/help.ts
index 0b49163a19..bb9c3dde30 100644
--- a/apps/desktop/src/main/maker-ipc/help.ts
+++ b/apps/desktop/src/main/maker-ipc/help.ts
@@ -5,10 +5,15 @@ import type { AgentKind, Maker, OneShotOptions } from '@cindy/maker-core';
import { BRAND_NAME } from '@cindy/maker-shared/branding';
import { createLogger } from '../logger.js';
+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';
import { isAgentOneShotRouteDisabled } from '../maker-host/model-route-guard-live.js';
import { getDbClient } from '../localDb/client/current.js';
import { sessions } from '../localDb/schema.js';
import { agentSupportsOneShot, requestUtilityText } from '../utility-model/oneShotCandidates.js';
+import {
+ getEffectiveAuxiliaryModelChain,
+ getEffectiveAuxiliaryModelChainSnapshot,
+} from '../utility-model/resolveAuxiliaryModelChain.js';
import { MAKER_INVOKE } from './channels.js';
import { DESKTOP_VISIBLE_SESSION_SOURCES } from '../../shared/sessionSource.js';
import type {
@@ -74,6 +79,32 @@ type HelpOneShotTarget = {
options: OneShotOptions;
};
+/**
+ * Help routing is owner-bound even though it is best-effort. Do not dispatch a
+ * prompt after the account/session boundary moved while credentials or the
+ * auxiliary chain were being resolved.
+ */
+function isHelpOwnerScopeCurrent(scopeKey: string, chainSnapshot?: string): boolean {
+ try {
+ return !isAppSessionBoundaryPending()
+ && activeOwnerScopeKey() === scopeKey
+ && (chainSnapshot === undefined || getEffectiveAuxiliaryModelChainSnapshot() === chainSnapshot);
+ } catch {
+ return false;
+ }
+}
+
+async function isHelpSessionAgentDispatchAllowed(
+ target: HelpOneShotTarget,
+ ownerScopeKey: string,
+ auxiliaryChainSnapshot: string,
+): Promise<boolean> {
+ if (!target.agentKind) return false;
+ if (!isHelpOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot)) return false;
+ if (await isAgentOneShotRouteDisabled(target.agentKind, target.options.model)) return false;
+ return isHelpOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot);
+}
+
function normalizeLocale(locale: unknown): HelpLocale {
return locale === 'zh-CN' || locale === 'zh-TW' || locale === 'en' || locale === 'ja' || locale === 'ko'
? locale
@@ -120,28 +151,40 @@ async function routeHelpTopics(
maker: Maker,
target: HelpOneShotTarget,
history: HelpMessage[],
+ ownerScopeKey: string,
): Promise<string[]> {
if (HELP_KNOWLEDGE.length === 0) return [];
try {
const prompt = buildRouterPrompt(history);
+ // Freeze this request's fallback policy before dispatch. Settings can be
+ // changed while the utility model is in flight; completion must not read a
+ // newer mode and accidentally cross the custom/automatic boundary.
+ const auxiliaryChain = getEffectiveAuxiliaryModelChain();
+ const auxiliaryChainSnapshot = getEffectiveAuxiliaryModelChainSnapshot();
const utility = await requestUtilityText(maker, prompt, {
maxTokens: 30,
timeoutMs: 12_000,
+ beforeDispatch: async () => isHelpOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot),
});
+ if (!isHelpOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot)) return [];
let raw = utility.ok ? utility.text : '';
- // 停用轴:agent one-shot 兜底同样是新的付费调用,目标模型/默认路由被停用时
- // 不派发(help 是 best-effort,静默降级到 summary-only,PR #744 review)。
+ const beforeSessionAgentDispatch = () =>
+ isHelpSessionAgentDispatchAllowed(target, ownerScopeKey, auxiliaryChainSnapshot);
+ // 自动档保留会话 agent 兜底。自定义 1–3 用尽即停,不再打当前任务大模型。
if (
!raw &&
+ auxiliaryChain.source === 'auto' &&
target.agentKind &&
- !(await isAgentOneShotRouteDisabled(target.agentKind, target.options.model))
+ await beforeSessionAgentDispatch()
) {
raw = await maker.oneShot(target.agentKind, prompt, {
...target.options,
maxTokens: 30,
timeoutMs: 12_000,
+ beforeDispatch: beforeSessionAgentDispatch,
});
}
+ if (!isHelpOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot)) return [];
return parseRouterOutput(raw, KNOWN_DOC_IDS);
} catch (err) {
// Routing is best-effort; on failure fall back to summary-only grounding.
@@ -323,26 +366,42 @@ export function registerMakerHelpIpc(maker: Maker): void {
if (!isValidHistory(req.messages)) return { kind: 'no-answer' };
const locale = normalizeLocale(req.locale);
try {
+ // Capture before any async agent/DB/model work. Both utility requests
+ // in this help turn must remain tied to the same owner scope.
+ const ownerScopeKey = activeOwnerScopeKey();
const preferredAgent = await getMostRecentSessionAgent();
const target = await pickHelpOneShotTarget(maker, preferredAgent);
const history = truncateHelpHistory(req.messages);
// Stage 1: route to relevant KB docs (cheap, index-only).
- const routedIds = await routeHelpTopics(maker, target, history);
+ const routedIds = await routeHelpTopics(maker, target, history, ownerScopeKey);
const docs = HELP_KNOWLEDGE.filter((d) => routedIds.includes(d.id));
// Stage 2: answer grounded in the routed docs (or summaries on miss).
const prompt = buildHelpPrompt(history, locale, target.agentKind, docs);
+ // As with topic routing, pin the fallback policy for this answer
+ // request before awaiting the utility model.
+ const auxiliaryChain = getEffectiveAuxiliaryModelChain();
+ const auxiliaryChainSnapshot = getEffectiveAuxiliaryModelChainSnapshot();
const utility = await requestUtilityText(maker, prompt, {
...target.options,
+ beforeDispatch: async () => isHelpOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot),
});
+ if (!isHelpOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot)) return { kind: 'no-answer' };
let raw = utility.ok ? utility.text : '';
- // 停用轴:同上,兜底一击的目标路由被停用则不派发(回落既有的失败文案路径)。
+ const beforeSessionAgentDispatch = () =>
+ isHelpSessionAgentDispatchAllowed(target, ownerScopeKey, auxiliaryChainSnapshot);
+ // 自动档保留会话 agent 兜底。自定义 1–3 用尽即停,不再打当前任务大模型。
if (
!raw &&
+ auxiliaryChain.source === 'auto' &&
target.agentKind &&
- !(await isAgentOneShotRouteDisabled(target.agentKind, target.options.model))
+ await beforeSessionAgentDispatch()
) {
- raw = await maker.oneShot(target.agentKind, prompt, target.options);
+ raw = await maker.oneShot(target.agentKind, prompt, {
+ ...target.options,
+ beforeDispatch: beforeSessionAgentDispatch,
+ });
}
+ if (!isHelpOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot)) return { kind: 'no-answer' };
if (utility.ok) {
log.debug('help ask used utility model', {
provider: utility.providerId,
diff --git a/apps/desktop/src/main/maker-ipc/promptPrediction.ts b/apps/desktop/src/main/maker-ipc/promptPrediction.ts
index 6d3616d671..394fb1c6b6 100644
--- a/apps/desktop/src/main/maker-ipc/promptPrediction.ts
+++ b/apps/desktop/src/main/maker-ipc/promptPrediction.ts
@@ -1,33 +1,18 @@
/**
* promptPrediction —— 输入框推荐提示词的 one-shot 预测。
*
- * 参考 title-one-shot.ts 的实现模式:复用同一套 provider/凭证/model routing
- * 基础设施,走 provider catalog 中的 titleModel(最经济模型)做单次 HTTP 请求,
- * 预测用户下一步会输入的提示词。不自己发 HTTP,不额外配置 endpoint。
- *
- * 与标题生成的差异:
- * - 触发时机:标题在首条用户消息发送时触发;推荐在 turn 完成后触发。
- * - prompt 构建:提取最近对话上下文,让模型预测下一步用户输入。
- * - 输出长度:标题 ≤20 字;推荐 ≤140 字符。
- * - 错误处理:失败静默返回 null,不 fallback 任何默认文案。
+ * 走共享辅助模型链(`requestUtilityText`),不再按当前任务目录挑最便宜模型。
+ * 失败静默返回 null,不 fallback 任何默认文案。
*/
import type { AgentKind } from '@cindy/maker-core';
import { dbToMakerAgentKind } from '../../shared/agentKindConversion.js';
import { getResolvedMainLocale } from '../i18n.js';
-import { getDesktopProviderService } from '../maker-host/createDesktopProviderService.js';
-import {
- buildTitleTarget,
- generateTitleViaProviderResult,
-} from '../maker-host/title-one-shot.js';
+import { getMaker } from '../maker-host/index.js';
import { validateTitleOutput } from '../maker-host/title-output-validation.js';
-import { readAuxiliaryModelSelection } from '../utility-model/auxiliary-model-settings-store.js';
-import {
- connectedProvidersForAgent,
- nativeDefaultSourceId,
- type ProviderView,
-} from '@cindy/model-providers';
+import { requestUtilityText } from '../utility-model/oneShotCandidates.js';
+import { readAuxiliaryModelSettings } from '../utility-model/auxiliary-model-settings-store.js';
import { eq } from 'drizzle-orm';
import { getDbClient } from '../localDb/client/current.js';
import { sessions } from '../localDb/schema.js';
@@ -46,6 +31,30 @@ const PREDICTION_RECENT_PAIRS = 3;
type SlimMessage = { role: string; content: string };
+type SessionPredictionRow = {
+ agentKind: typeof sessions.agentKind._.data;
+ status: typeof sessions.status._.data;
+ source: typeof sessions.source._.data;
+ remoteHostId: string | null;
+ providerId: string | null;
+ workingDir: string | null;
+ updatedAt: number;
+ activeTurnStartedAt: number | null;
+ lastTurnEndedAt: number | null;
+};
+
+const SESSION_PREDICTION_COLUMNS = {
+ 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,
+};
+
/**
* 从对话历史里提取最近几轮 user↔assistant 配对,截断后拼接成 prompt 素材。
* 跳过 tool_use / tool_result / thinking / error / system 等非对话角色。
@@ -104,10 +113,9 @@ function buildPredictionPrompt(
? `Current working directory: ${escapeReferenceData(workingDir)}`
: null;
- // 系统指令写入 Anthropic Messages API 顶层 system 字段(非 Anthropic wire 忽略),
- // 不混入 user message,避免被 Anthropic API 拒绝。
- // TODO(PR #1965): 该固定 system prompt 指令进入模型 system 段,按
- // docs/dev-rules/maker-core-and-agent-behavior.md §4 需在合并前取得维护者确认。
+ // 系统指令写入各辅助供应商对应的 system/instructions 段(Anthropic
+ // Messages API 使用顶层 system 字段),不混入 user message,避免被
+ // Anthropic API 拒绝。该固定指令有意随共享辅助链发送到所有支持的路由。
const system = [
'You are a terse predictive text engine for a coding chat input.',
'Return only the predicted next user message — no quotes, markdown, commentary, or multiple options.',
@@ -136,29 +144,22 @@ function buildPredictionPrompt(
return { system, user };
}
-/** 从 DB 读 sessions.provider_id。失败/空串 → null。 */
-async function readSessionProviderIdFromDb(sessionId: string): Promise<string | null> {
- if (!sessionId) return null;
- try {
- const [row] = await getDbClient()
- .drizzle.select({ providerId: sessions.providerId })
- .from(sessions)
- .where(eq(sessions.id, sessionId))
- .limit(1);
- return row?.providerId ?? null;
- } catch {
- return null;
- }
-}
-
-/** 某 agent 下已连接的供应商视图列表。失败 → []。 */
-async function listConnectedProvidersForAgent(agentKind: AgentKind): Promise<ProviderView[]> {
- try {
- const all = await getDesktopProviderService().listProviders({ allowSideEffects: true });
- return connectedProvidersForAgent(all, agentKind);
- } catch {
- return [];
+function sessionStillEligibleForPrediction(
+ row: SessionPredictionRow | undefined,
+ params: PromptPredictionParams,
+): boolean {
+ 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;
+ return true;
}
export interface PromptPredictionParams {
@@ -176,7 +177,7 @@ export interface PromptPredictionParams {
/**
* 预测用户下一步可能输入的提示词。
- * 无已连接 provider / 无 titleModel / 凭证缺失 / HTTP 失败 / 空响应 → 返回 null。
+ * 辅助模型链不可用 / HTTP 失败 / 空响应 / 会话资格变化 → 返回 null。
*/
export async function generatePromptPrediction(
params: PromptPredictionParams,
@@ -207,17 +208,6 @@ export async function generatePromptPrediction(
sessionId: params.sessionId,
});
- // 复用 title one-shot 通路,但覆盖 token/校验参数以适配预测场景:
- // - maxTokens=96: 标题仅需 32 token,预测 ≤140 chars 需要更多
- // - codexInstructions: 告诉模型这是预测而非标题
- // - systemPrompt: Anthropic Messages API 顶层 system 字段(非 Anthropic wire 忽略)
- // - maxOutputChars=512: 恢复 validateTitleOutput 输出校验(拦截多行/Markdown/role label),再交给 maxVisualChars=140 做展示截断
- // - maxVisualChars=140: 截断到推荐提示词上限
- // 在 provider/凭证解析之前捕获 drain 时的 updatedAt,供 beforeDispatch 终末复核。
- // 若在 drain 之后、beforeDispatch 首次 DB 读之前用户发送了新消息,row.updatedAt
- // 和 finalRow.updatedAt 都会包含新值,仅做两次 DB 读互相比较无法检测到轮次变化。
- // 优先使用 title.ts 中素材物化后传入的 materialDrainUpdatedAt(覆盖素材物化→provider
- // 解析之间的空窗),未传入时回退到在此处从 DB 读取。
let beforeDispatchDrainUpdatedAt: number | undefined;
if (params.materialDrainUpdatedAt != null) {
beforeDispatchDrainUpdatedAt = params.materialDrainUpdatedAt;
@@ -233,255 +223,51 @@ 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> => {
+
+ const modelsSnapshot = JSON.stringify(readAuxiliaryModelSettings().models);
+
+ const result = await requestUtilityText(getMaker(), truncated, {
+ maxTokens: 96,
+ timeoutMs: 12_000,
+ disableReasoning: true,
+ reasoningEffort: 'minimal',
+ systemPrompt,
+ responseInstructions:
+ 'Output only the predicted next user message — no quotes, markdown, or commentary.',
+ beforeDispatch: async () => {
try {
- if (!selectionStillCurrent(route)) return false;
+ if (JSON.stringify(readAuxiliaryModelSettings().models) !== modelsSnapshot) {
+ 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,
- })
+ .drizzle.select(SESSION_PREDICTION_COLUMNS)
.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;
+ if (!sessionStillEligibleForPrediction(row, params)) 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,
- })
+ .drizzle.select(SESSION_PREDICTION_COLUMNS)
.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 (!sessionStillEligibleForPrediction(finalRow, params)) return false;
if (finalRow.providerId !== row.providerId) return false;
- if (finalRow.workingDir !== (params.workingDir ?? null)) return false;
if (
- beforeDispatchDrainUpdatedAt &&
- finalRow.updatedAt !== beforeDispatchDrainUpdatedAt
+ beforeDispatchDrainUpdatedAt
+ && finalRow.updatedAt !== beforeDispatchDrainUpdatedAt
) return false;
- return selectionStillCurrent(route);
+ return JSON.stringify(readAuxiliaryModelSettings().models) === modelsSnapshot;
} 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,
- // Recommendation outputs share a short token budget with provider-native
- // thinking. Disable it so reasoning-first models still return body text.
- disableReasoning: true,
- 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,
- agentKind: params.agentKind,
- prompt: truncated,
},
- {
- readSessionProviderId: readSessionProviderIdFromDb,
- listConnectedProviders: listConnectedProvidersForAgent,
- // 派发紧前复查:会话在 drain 与 provider/凭证解析期间可能被切换 agent/删除/转远程。
- // (sessionAgentSwitchHandler 会提交 agentKind 变更,deleteSession 会软删除)上方
- // title.ts handler 里 drain 后的资格复核到 provider 实际发出 HTTP 之间仍有一段异步窗口。
- // 这里在发出付费请求的紧前再回读一次 DB 完整资格字段:
- // - agentKind: 会话被切换 agent 时中止,避免路由到切换前的 provider/账号
- // - status: 会话被软删除时中止,避免外发已删转写
- // - source: 会话被转为 review 时中止
- // - remoteHostId: 会话被转为远程时中止
- // - providerId: 会话 provider 被切换时中止,避免路由到过期 provider
- beforeDispatch: async ({ sessionId, agentKind, providerId: resolvedProviderId }) => {
- try {
- if (readAuxiliaryModelSelection('promptRecommendationModel')) return false;
- // drainUpdatedAt 在 provider/凭证解析之前捕获,用于终末复核。
- // 若在 drain 之后、beforeDispatch 首次 DB 读之前用户发送了新消息,
- // row.updatedAt 和 finalRow.updatedAt 都会包含新值,仅做 row↔finalRow
- // 比较无法检测到轮次变化。与 drainUpdatedAt 比较才可靠。
- const drainUpdatedAt = beforeDispatchDrainUpdatedAt;
- 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, sessionId))
- .limit(1);
- if (!row) return false;
- if (row.status === 'deleted') return false;
- if (row.source === 'review') return false;
- if (row.remoteHostId) return false;
- if (dbToMakerAgentKind(row.agentKind) !== agentKind) return false;
- if (row.lastTurnEndedAt !== params.completionRevision) return false;
- if (
- row.activeTurnStartedAt != null &&
- row.activeTurnStartedAt >= params.completionRevision
- )
- return false;
- if (wasPromptPredictionSessionStopped(sessionId)) return false;
- // 重新按 one-shot 同一口径解析当前有效来源。显式/默认来源若没有 title wire,
- // generateTitleViaProviderResult 会回落已连接的官方 xd;这里必须比较「解析后的
- // 实际来源」,不能拿 DB 原始 custom providerId 直接拒绝合法回落。
- const providers = await listConnectedProvidersForAgent(agentKind);
- const selectedProviderId =
- row.providerId ?? nativeDefaultSourceId(providers, agentKind);
- if (
- !selectedProviderId ||
- !providers.some((provider) => provider.id === selectedProviderId)
- ) return false;
- const officialFallbackAvailable =
- providers.some((provider) => provider.id === 'xd') &&
- buildTitleTarget('xd') != null;
- const expectedResolvedProviderId =
- buildTitleTarget(selectedProviderId) != null
- ? selectedProviderId
- : officialFallbackAvailable
- ? 'xd'
- : selectedProviderId;
- if (expectedResolvedProviderId !== resolvedProviderId) return false;
- // 紧前复查 workingDir:用户在 provider/凭证解析期间切换了工作目录,
- // 此时 buildPredictionPrompt 已嵌入旧 params.workingDir,继续派发
- // 会向 provider 外发过期本地路径。按 fail-closed 中止。
- if (row.workingDir !== (params.workingDir ?? null)) return false;
- // 终末复查:上方 listConnectedProvidersForAgent 是异步调用(实时读取
- // 凭证连接态且允许副作用),等待期间用户仍可能删除会话、切换 agent/provider、
- // 修改工作目录或把会话转为远程/review。在最后一个 await 之后再做一次无后续
- // await 的 DB 复核,把 TOCTOU 窗口缩到最小。
- 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, sessionId))
- .limit(1);
- if (!finalRow) return false;
- if (finalRow.status === 'deleted') return false;
- if (finalRow.source === 'review') return false;
- if (finalRow.remoteHostId) return false;
- if (dbToMakerAgentKind(finalRow.agentKind) !== agentKind) return false;
- if (finalRow.lastTurnEndedAt !== params.completionRevision) return false;
- if (
- finalRow.activeTurnStartedAt != null &&
- finalRow.activeTurnStartedAt >= params.completionRevision
- )
- return false;
- if (wasPromptPredictionSessionStopped(sessionId)) return false;
- // provider/凭证 rail 已在上方按 fallback 口径复核;最后一个 await 后只需确认
- // DB 原始选择没有再变化(含 explicit ↔ default),避免重开异步解析窗口。
- if (finalRow.providerId !== row.providerId) return false;
- if (finalRow.workingDir !== (params.workingDir ?? null)) return false;
- // 终末复核消息轮次:与 drain 时的 updatedAt(provider/凭证解析之前捕获)比较。
- // 仅与 row.updatedAt(beforeDispatch 内首次 DB 读)比较无法检测到
- // drain 之后、首次 DB 读之前发来的新消息——此时两次读都返回同一新值。
- if (drainUpdatedAt && finalRow.updatedAt !== drainUpdatedAt) return false;
- return readAuxiliaryModelSelection('promptRecommendationModel') === null;
- } catch {
- // 复查失败按 fail-closed 处理:宁可漏掉一次推荐,也不在归属不确定时外发付费调用。
- return false;
- }
- },
- },
- {
- maxTokens: 96,
- codexInstructions:
- 'Output only the predicted next user message — no quotes, markdown, or commentary.',
- systemPrompt,
- maxOutputChars: 512,
- maxVisualChars: 140,
- },
- );
+ });
+
// HTTP 已经发出后仍可能收到其它窗口 / Device Link 的 Stop。费用无法撤回,但返回值
// 必须丢弃,不能在用户明确停止后把推荐重新显示到输入框。
if (wasPromptPredictionSessionStopped(params.sessionId)) return null;
- return result.status === 'ok' ? result.title : null;
+ if (!result.ok) return null;
+ const normalized = validateTitleOutput(result.text, 512);
+ return normalized ? Array.from(normalized).slice(0, 140).join('') : null;
}
diff --git a/apps/desktop/src/main/maker-ipc/title.ts b/apps/desktop/src/main/maker-ipc/title.ts
index dfb4827f98..5b6a48bf17 100644
--- a/apps/desktop/src/main/maker-ipc/title.ts
+++ b/apps/desktop/src/main/maker-ipc/title.ts
@@ -1,11 +1,9 @@
/**
* registerMakerTitleIpc — maker:generate-title / maker:regenerate-title
*
- * 给会话起一个 ≤ 20 字标题。标题 oneShot 已统一为「单次 HTTP 请求」:按本会话所属 provider
- * (WYSIWYG,与模型选择器高亮同口径:DB 显式选中优先,无则取已连接供应商的原生默认)
- * 取 catalog 配的 `titleModel`(最经济模型),用该 provider 自家凭证直起
- * (见 maker-host/title-one-shot)。无标题 wire 的会话供应商回落官方 `xd`。
- * 起不出来(零已连接 / 官方也不可用 / 凭证缺失 / HTTP 失败 / 超时)
+ * 给会话起一个 ≤ 20 字标题。自动起名与 Magic 重命名都走辅助模型链
+ * (`generateTitleWithAuxiliaryModel`),不再按当前任务供应商目录捡最便宜的
+ * `titleModel`。起不出来(链上模型都不可用 / 凭证缺失 / HTTP 失败 / 超时)
* → 返回 null,renderer 回落「消息前 40 字」启发式。fire-and-forget,
* 不阻塞主流程,也不向用户暴露失败。
*
diff --git a/apps/desktop/src/main/sessionTaskSummary.ts b/apps/desktop/src/main/sessionTaskSummary.ts
index f090ef647c..7e06312a22 100644
--- a/apps/desktop/src/main/sessionTaskSummary.ts
+++ b/apps/desktop/src/main/sessionTaskSummary.ts
@@ -27,7 +27,12 @@ import { and, count, desc, eq, gt, isNotNull, isNull, lt, or, sql } from 'drizzl
import { getMaker } from './maker-host/index.js';
import { isAgentOneShotRouteDisabled } from './maker-host/model-route-guard-live.js';
+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from './appSessionState.js';
import { agentSupportsOneShot, requestUtilityText } from './utility-model/oneShotCandidates.js';
+import {
+ getEffectiveAuxiliaryModelChain,
+ getEffectiveAuxiliaryModelChainSnapshot,
+} from './utility-model/resolveAuxiliaryModelChain.js';
import { getDbClient } from './localDb/client/current.js';
import { latestMessageText, latestVisiblePreview } from './localDb/latestMessageText.js';
import { messages, sessions } from './localDb/schema.js';
@@ -86,6 +91,21 @@ function isOwnerScopeCurrent(scope: DataOwnerBroadcastScope | null): boolean {
}
}
+/**
+ * Utility-model requests are owner-bound even though they do not write to the
+ * local DB themselves. Keep the request tied to the session that started it;
+ * an account switch or teardown must fail closed before the paid dispatch.
+ */
+function isAuxiliaryOwnerScopeCurrent(scopeKey: string, chainSnapshot?: string): boolean {
+ try {
+ return !isAppSessionBoundaryPending()
+ && activeOwnerScopeKey() === scopeKey
+ && (chainSnapshot === undefined || getEffectiveAuxiliaryModelChainSnapshot() === chainSnapshot);
+ } catch {
+ return false;
+ }
+}
+
/**
* 广播 sessions:patched 到本机所有窗口 + device-link tap。tap 让该 patch 经 topic 路由
* 转发给订阅了 `sessions` 的控制端(push 驱动:控制端 applyPatch 即时镜像 summary,无需
@@ -263,6 +283,11 @@ export async function maybeGenerateSessionTaskSummary(
async function generateSummaryOnce(sessionId: string): Promise<void> {
let wroteFresh = false;
try {
+ // Capture before any async DB/model work. The fallback chain must not be
+ // allowed to dispatch under a different account after an owner switch.
+ const ownerScopeKey = activeOwnerScopeKey();
+ const auxiliaryChain = getEffectiveAuxiliaryModelChain();
+ const auxiliaryChainSnapshot = getEffectiveAuxiliaryModelChainSnapshot();
const db = getDbClient().drizzle;
const [session] = await db
.select({
@@ -327,7 +352,14 @@ async function generateSummaryOnce(sessionId: string): Promise<void> {
const utility = await requestUtilityText(getMaker(), prompt, {
maxTokens: 120,
timeoutMs: 30_000,
+ beforeDispatch: async () => isAuxiliaryOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot),
});
+ if (!isAuxiliaryOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot)) return;
+ const beforeSessionAgentDispatch = async () => {
+ if (!isAuxiliaryOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot)) return false;
+ if (await isAgentOneShotRouteDisabled(agentKind)) return false;
+ return isAuxiliaryOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot);
+ };
// 停用轴:agent one-shot 兜底是新的付费调用,该 agent 的默认路由被停用时不派发
// (摘要 best-effort,直接放弃本轮,PR #744 review)。
// oneShot 能力轴:Pi 未实现 oneShot(继承 BaseAgent 的 not-implemented),对 Pi 会话
@@ -335,11 +367,17 @@ async function generateSummaryOnce(sessionId: string): Promise<void> {
// 那样跨 agent 兜底 —— 会话 agent 不支持 oneShot 时直接跳过兜底(仅靠 utility-model)。
const text = utility.ok
? utility.text
- : !agentSupportsOneShot(agentKind) || (await isAgentOneShotRouteDisabled(agentKind))
+ : auxiliaryChain.source !== 'auto' ||
+ !agentSupportsOneShot(agentKind) ||
+ !(await beforeSessionAgentDispatch())
? ''
- : await getMaker().oneShot(agentKind, prompt, { maxTokens: 120 });
+ : await getMaker().oneShot(agentKind, prompt, {
+ maxTokens: 120,
+ beforeDispatch: beforeSessionAgentDispatch,
+ });
const summary = sanitize(text, maxCharsForTier(tier));
if (!summary) return;
+ if (!isAuxiliaryOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot)) return;
// 写回前重查会话状态:oneShot 是异步的(数秒),in-flight 期间会话可能已变化,无条件写回
// 会写入一份已过时的摘要(codex review)。任一不符即跳过:
@@ -369,6 +407,7 @@ async function generateSummaryOnce(sessionId: string): Promise<void> {
) {
return;
}
+ if (!isAuxiliaryOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot)) return;
// 直写 summary,不 bump updatedAt——摘要刷新不应引起 sidebar 重排
await db.update(sessions).set({ summary }).where(eq(sessions.id, sessionId));
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.ts
index 26a1776a10..58adda42df 100644
--- 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.ts
@@ -1,108 +1,380 @@
-import fs from 'node:fs';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import os from 'node:os';
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') },
+const h = vi.hoisted(() => ({
+ dir: '',
+ mode: 'cloud' as 'cloud' | 'local' | 'signed-out',
+ ownerId: 'test-owner' as string | null,
+ exclusive: true,
+ exclusiveReads: [] as boolean[],
+ legacyClaim: true,
}));
-vi.mock('../../maker-host/logger-adapter.js', () => ({
- desktopMakerLogger: {
- child: () => ({ info: vi.fn(), warn: vi.fn() }),
+vi.mock('electron', () => ({
+ app: {
+ getPath: (name: string) => {
+ if (name === 'userData') return h.dir;
+ throw new Error(`unexpected path ${name}`);
+ },
},
}));
vi.mock('../../appSessionState.js', () => ({
- activeOwnerScopeKey: () => 'test-owner:1',
- ownerScopedUserDataPath: (...parts: string[]) =>
- path.join('/tmp/cindy-auxiliary-model-test', ...parts),
+ ownerScopedUserDataPath: (...parts: string[]) => path.join(h.dir, 'owner', ...parts),
+ activeOwnerScopeKey: () => 'test-owner',
+ getActiveAppSession: () => ({
+ mode: h.mode,
+ dataOwnerId: h.ownerId,
+ generation: 0,
+ }),
+}));
+
+vi.mock('../../ownerNamespaceMigration.js', () => ({
+ hasExclusiveSharedLegacyUserDataAccess: () => h.exclusiveReads.shift() ?? h.exclusive,
+ hasLegacyOwnerNamespaceClaim: () => h.legacyClaim,
+}));
+
+vi.mock('../../maker-host/logger-adapter.js', () => ({
+ desktopMakerLogger: {
+ child: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),
+ },
}));
import {
- __testing,
- readAuxiliaryModelSelection,
+ isAuxiliaryModelCustomized,
readAuxiliaryModelSettings,
readAuxiliaryModelSettingsState,
- resetAuxiliaryModelSettings,
writeAuxiliaryModelSettingsPatch,
+ __testing,
} 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';
+const TITLE_PIN = 'cat:openai:codex:gpt-5.4-mini';
+const PROMPT_PIN = 'cat:xd:claude-code:kimi-k2.5';
+const CUSTOM_MODEL_PIN = 'cat:xd:codex:moonshotai/kimi-k2.6-custom';
-describe('auxiliary model settings store', () => {
- beforeEach(async () => {
- fs.mkdirSync(settingsDir, { recursive: true });
- await resetAuxiliaryModelSettings();
+function settingsPath(): string {
+ return path.join(h.dir, 'owner', 'auxiliary-model-settings.json');
+}
+
+function ownerVoicePath(): string {
+ return path.join(h.dir, 'owner', 'voice-input-models.json');
+}
+
+function unscopedVoicePath(): string {
+ return path.join(h.dir, 'voice-input-models.json');
+}
+
+function migrationStatePath(): string {
+ return path.join(h.dir, 'owner', 'auxiliary-model-settings-migration.json');
+}
+
+function writeJson(file: string, value: unknown): void {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, JSON.stringify(value), 'utf8');
+}
+
+function readJson(file: string): unknown {
+ return JSON.parse(readFileSync(file, 'utf8'));
+}
+
+describe('auxiliary-model-settings-store', () => {
+ beforeEach(() => {
+ h.dir = mkdtempSync(path.join(os.tmpdir(), 'cindy-auxiliary-model-'));
+ h.mode = 'cloud';
+ h.ownerId = 'test-owner';
+ h.exclusive = true;
+ h.exclusiveReads = [];
+ h.legacyClaim = true;
+ mkdirSync(path.join(h.dir, 'owner'), { recursive: true });
});
- afterEach(async () => {
- await resetAuxiliaryModelSettings();
- fs.rmSync(settingsDir, { recursive: true, force: true });
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ rmSync(h.dir, { recursive: true, force: true });
});
- it('defaults both auxiliary tasks to their existing automatic routes', () => {
- expect(readAuxiliaryModelSettings()).toEqual({
- sessionTitleModel: null,
- promptRecommendationModel: null,
+ it('treats an empty models list as automatic', () => {
+ expect(readAuxiliaryModelSettings()).toEqual({ models: [] });
+ expect(isAuxiliaryModelCustomized()).toBe(false);
+ expect(readAuxiliaryModelSettingsState().customizedKeys).toEqual([]);
+ });
+
+ it('persists a unique custom list and reports it as customized', async () => {
+ await writeAuxiliaryModelSettingsPatch({ models: [TITLE_PIN, PROMPT_PIN, TITLE_PIN] });
+
+ expect(readAuxiliaryModelSettings()).toEqual({ models: [TITLE_PIN, PROMPT_PIN] });
+ expect(isAuxiliaryModelCustomized()).toBe(true);
+ expect(readJson(settingsPath())).toEqual({ models: [TITLE_PIN, PROMPT_PIN] });
+ });
+
+ it('deletes the override file when restoring the empty automatic list', async () => {
+ await writeAuxiliaryModelSettingsPatch({ models: [TITLE_PIN] });
+ await writeAuxiliaryModelSettingsPatch({ models: [] });
+
+ expect(readAuxiliaryModelSettings()).toEqual({ models: [] });
+ expect(isAuxiliaryModelCustomized()).toBe(false);
+ expect(() => readFileSync(settingsPath())).toThrow();
+ });
+
+ it('keeps an existing models array and leaves legacy voice settings untouched', () => {
+ writeJson(settingsPath(), {
+ models: [TITLE_PIN],
+ sessionTitleModel: PROMPT_PIN,
+ });
+ writeJson(ownerVoicePath(), {
+ refinerProvider: 'litellm-kimi-k2.6',
+ sttProvider: 'cindy-voice',
+ });
+
+ expect(readAuxiliaryModelSettings()).toEqual({ models: [TITLE_PIN] });
+ expect(readJson(settingsPath())).toEqual({
+ models: [TITLE_PIN],
+ sessionTitleModel: PROMPT_PIN,
+ });
+ expect(readJson(ownerVoicePath())).toEqual({
+ refinerProvider: 'litellm-kimi-k2.6',
+ sttProvider: 'cindy-voice',
+ });
+ });
+
+ it('migrates legacy dual pins with the title pin first', async () => {
+ writeJson(settingsPath(), {
+ sessionTitleModel: TITLE_PIN,
+ promptRecommendationModel: PROMPT_PIN,
+ });
+
+ expect(readAuxiliaryModelSettings()).toEqual({ models: [TITLE_PIN, PROMPT_PIN] });
+ await __testing.flushLegacyMigration();
+ expect(readJson(settingsPath())).toEqual({ models: [TITLE_PIN, PROMPT_PIN] });
+ });
+
+ it('defers legacy migration while shared userData is not exclusive', async () => {
+ writeJson(settingsPath(), {
+ sessionTitleModel: TITLE_PIN,
+ promptRecommendationModel: PROMPT_PIN,
});
- expect(readAuxiliaryModelSettingsState()).toMatchObject({
- isCustomized: false,
- customizedKeys: [],
+ h.exclusive = false;
+
+ expect(readAuxiliaryModelSettings()).toEqual({ models: [TITLE_PIN, PROMPT_PIN] });
+ await __testing.flushLegacyMigration();
+ expect(readJson(settingsPath())).toEqual({
+ sessionTitleModel: TITLE_PIN,
+ promptRecommendationModel: PROMPT_PIN,
});
+
+ h.exclusive = true;
+ expect(readAuxiliaryModelSettings()).toEqual({ models: [TITLE_PIN, PROMPT_PIN] });
+ await __testing.flushLegacyMigration();
+ expect(readJson(settingsPath())).toEqual({ models: [TITLE_PIN, PROMPT_PIN] });
});
- it('persists the two model selections independently as overrides', async () => {
- await writeAuxiliaryModelSettingsPatch({ sessionTitleModel: TITLE_PIN });
- await writeAuxiliaryModelSettingsPatch({
- promptRecommendationModel: RECOMMENDATION_PIN,
+ it('rechecks shared-userData exclusivity after waiting for the migration lock', async () => {
+ writeJson(settingsPath(), {
+ sessionTitleModel: TITLE_PIN,
+ promptRecommendationModel: PROMPT_PIN,
});
+ // First check passes, but another shared instance appears before the
+ // updateAtomic callback obtains its lock.
+ h.exclusiveReads = [true, false];
- expect(JSON.parse(fs.readFileSync(settingsFile, 'utf-8'))).toEqual({
+ expect(readAuxiliaryModelSettings()).toEqual({ models: [TITLE_PIN, PROMPT_PIN] });
+ await __testing.flushLegacyMigration();
+ expect(readJson(settingsPath())).toEqual({
sessionTitleModel: TITLE_PIN,
- promptRecommendationModel: RECOMMENDATION_PIN,
+ promptRecommendationModel: PROMPT_PIN,
+ });
+
+ h.exclusive = true;
+ expect(readAuxiliaryModelSettings()).toEqual({ models: [TITLE_PIN, PROMPT_PIN] });
+ await __testing.flushLegacyMigration();
+ expect(readJson(settingsPath())).toEqual({ models: [TITLE_PIN, PROMPT_PIN] });
+ });
+
+ it('seals legacy voice migration when old auxiliary pins win, so reset stays automatic', async () => {
+ writeJson(settingsPath(), {
+ sessionTitleModel: TITLE_PIN,
+ promptRecommendationModel: PROMPT_PIN,
+ });
+ writeJson(ownerVoicePath(), {
+ refinerProvider: 'litellm-kimi-k2.6',
+ refinerProviderChain: ['litellm-kimi-k2.6', 'litellm-deepseek-v4-flash'],
+ });
+
+ expect(readAuxiliaryModelSettings()).toEqual({ models: [TITLE_PIN, PROMPT_PIN] });
+ await __testing.flushLegacyMigration();
+ expect(readJson(migrationStatePath())).toEqual({ legacyVoiceMigrationCompleted: true });
+
+ await writeAuxiliaryModelSettingsPatch({ models: [] });
+
+ expect(readAuxiliaryModelSettings()).toEqual({ models: [] });
+ expect(isAuxiliaryModelCustomized()).toBe(false);
+ expect(() => readFileSync(settingsPath())).toThrow();
+ expect(readJson(migrationStatePath())).toEqual({ legacyVoiceMigrationCompleted: true });
+ });
+
+ it('migrates a legacy voice chain when auxiliary settings were never customized', async () => {
+ writeJson(ownerVoicePath(), {
+ utilityModelProvider: 'litellm-kimi-k2.6',
+ utilityModel: 'moonshotai/kimi-k2.6-custom',
+ utilityModelProviderChain: ['codex-gpt-5.4-mini', 'litellm-kimi-k2.6'],
+ refinerProvider: 'codex-gpt-5.4-mini',
+ refinerModel: 'gpt-5.4-mini-custom',
+ refinerProviderChain: ['codex-gpt-5.4-mini', 'litellm-kimi-k2.6'],
+ sttProvider: 'cindy-voice',
+ });
+
+ expect(readAuxiliaryModelSettings()).toEqual({
+ models: [CUSTOM_MODEL_PIN, 'codex-gpt-5.4-mini', 'litellm-kimi-k2.6'],
+ });
+ await __testing.flushLegacyMigration();
+ expect(readJson(ownerVoicePath())).toEqual({
+ utilityModelProvider: 'litellm-kimi-k2.6',
+ utilityModel: 'moonshotai/kimi-k2.6-custom',
+ utilityModelProviderChain: ['codex-gpt-5.4-mini', 'litellm-kimi-k2.6'],
+ refinerProvider: 'codex-gpt-5.4-mini',
+ refinerModel: 'gpt-5.4-mini-custom',
+ refinerProviderChain: ['codex-gpt-5.4-mini', 'litellm-kimi-k2.6'],
+ sttProvider: 'cindy-voice',
+ });
+ expect(readJson(migrationStatePath())).toEqual({ legacyVoiceMigrationCompleted: true });
+ });
+
+ it('merges legacy file pins with the environment-provided fallback chain', async () => {
+ vi.stubEnv('XDT_UTILITY_MODEL_PROVIDER_CHAIN', 'codex-gpt-5.4-mini,litellm-deepseek-v4-flash');
+ writeJson(ownerVoicePath(), {
+ utilityModelProvider: 'litellm-kimi-k2.6',
+ });
+
+ expect(readAuxiliaryModelSettings()).toEqual({
+ models: ['litellm-kimi-k2.6', 'codex-gpt-5.4-mini', 'litellm-deepseek-v4-flash'],
+ });
+ await __testing.flushLegacyMigration();
+ expect(readJson(settingsPath())).toEqual({
+ models: ['litellm-kimi-k2.6', 'codex-gpt-5.4-mini', 'litellm-deepseek-v4-flash'],
+ });
+ });
+
+ it('keeps an environment-only legacy chain dynamic', async () => {
+ vi.stubEnv('XDT_UTILITY_MODEL_PROVIDER_CHAIN', 'litellm-kimi-k2.6,litellm-deepseek-v4-flash');
+
+ expect(readAuxiliaryModelSettings()).toEqual({ models: [] });
+ await __testing.flushLegacyMigration();
+
+ expect(() => readFileSync(settingsPath())).toThrow();
+ expect(() => readFileSync(migrationStatePath())).toThrow();
+ });
+
+ it('does not import the unscoped legacy voice file without a claimed cloud owner', async () => {
+ writeJson(unscopedVoicePath(), {
+ refinerProvider: 'litellm-kimi-k2.6',
+ refinerProviderChain: ['litellm-kimi-k2.6', 'litellm-deepseek-v4-flash'],
+ });
+ h.mode = 'local';
+ h.ownerId = 'local-owner';
+ h.legacyClaim = false;
+
+ expect(readAuxiliaryModelSettings()).toEqual({ models: [] });
+ await __testing.flushLegacyMigration();
+ expect(() => readFileSync(settingsPath())).toThrow();
+
+ h.mode = 'cloud';
+ h.ownerId = 'test-owner';
+ h.legacyClaim = true;
+ expect(readAuxiliaryModelSettings()).toEqual({
+ models: ['litellm-kimi-k2.6', 'litellm-deepseek-v4-flash'],
});
- expect(readAuxiliaryModelSelection('sessionTitleModel')).toEqual({
- pin: TITLE_PIN,
- providerId: 'openrouter',
- agentKind: 'codex',
- model: 'openai/gpt-5-mini',
+ await __testing.flushLegacyMigration();
+ expect(readJson(settingsPath())).toEqual({
+ models: ['litellm-kimi-k2.6', 'litellm-deepseek-v4-flash'],
});
- expect(readAuxiliaryModelSelection('promptRecommendationModel')).toEqual({
- pin: RECOMMENDATION_PIN,
- providerId: 'anthropic',
- agentKind: 'claude-code',
- model: 'claude-haiku-4-5',
+ });
+
+ it('does not re-import the legacy voice chain after restoring automatic defaults', async () => {
+ writeJson(ownerVoicePath(), {
+ refinerProvider: 'litellm-kimi-k2.6',
+ refinerProviderChain: ['litellm-kimi-k2.6', 'litellm-deepseek-v4-flash'],
});
+
+ expect(readAuxiliaryModelSettings()).toEqual({
+ models: ['litellm-kimi-k2.6', 'litellm-deepseek-v4-flash'],
+ });
+ await __testing.flushLegacyMigration();
+
+ await writeAuxiliaryModelSettingsPatch({ models: [] });
+
+ expect(readAuxiliaryModelSettings()).toEqual({ models: [] });
+ expect(isAuxiliaryModelCustomized()).toBe(false);
+ expect(() => readFileSync(settingsPath())).toThrow();
+ expect(readJson(migrationStatePath())).toEqual({ legacyVoiceMigrationCompleted: true });
});
- it('removes only the restored key, then removes the file at all defaults', async () => {
- await writeAuxiliaryModelSettingsPatch({
+ it('lets a customized auxiliary list win over a customized voice chain', () => {
+ writeJson(settingsPath(), {
sessionTitleModel: TITLE_PIN,
- promptRecommendationModel: RECOMMENDATION_PIN,
+ promptRecommendationModel: PROMPT_PIN,
+ });
+ writeJson(unscopedVoicePath(), {
+ refinerProvider: 'litellm-deepseek-v4-flash',
+ refinerProviderChain: ['litellm-deepseek-v4-flash', 'codex-gpt-5.4-mini'],
+ });
+
+ expect(readAuxiliaryModelSettings()).toEqual({ models: [TITLE_PIN, PROMPT_PIN] });
+ expect(readJson(unscopedVoicePath())).toEqual({
+ refinerProvider: 'litellm-deepseek-v4-flash',
+ refinerProviderChain: ['litellm-deepseek-v4-flash', 'codex-gpt-5.4-mini'],
+ });
+ });
+
+ it('does not migrate a leftover voice file a second time after models already exist', () => {
+ writeJson(settingsPath(), { models: [TITLE_PIN] });
+ writeJson(ownerVoicePath(), {
+ refinerProvider: 'litellm-kimi-k2.6',
+ refinerProviderChain: ['litellm-kimi-k2.6', 'litellm-deepseek-v4-flash'],
});
- await writeAuxiliaryModelSettingsPatch({ sessionTitleModel: null });
- expect(JSON.parse(fs.readFileSync(settingsFile, 'utf-8'))).toEqual({
- promptRecommendationModel: RECOMMENDATION_PIN,
+ expect(readAuxiliaryModelSettings()).toEqual({ models: [TITLE_PIN] });
+ expect(readJson(settingsPath())).toEqual({ models: [TITLE_PIN] });
+ expect(readJson(ownerVoicePath())).toEqual({
+ refinerProvider: 'litellm-kimi-k2.6',
+ refinerProviderChain: ['litellm-kimi-k2.6', 'litellm-deepseek-v4-flash'],
});
+ });
- await writeAuxiliaryModelSettingsPatch({ promptRecommendationModel: null });
- expect(fs.existsSync(settingsFile)).toBe(false);
+ it('exposes the same list normalization used on persist', () => {
+ expect(__testing.normalize({ models: [TITLE_PIN, ' ', TITLE_PIN, PROMPT_PIN] })).toEqual({
+ models: [TITLE_PIN, PROMPT_PIN],
+ });
});
- it('normalizes malformed or non-canonical disk values to automatic', () => {
+ it('preserves a legacy provider model override as the matching profile', () => {
expect(
- __testing.normalize({
- sessionTitleModel: 'cat:openrouter:pi:model',
- promptRecommendationModel: ' cat:anthropic:claude-code:model ',
+ __testing.legacyVoiceOverrideRefs({
+ refinerProvider: 'litellm',
+ refinerModel: 'qwen/qwen3.6-plus',
}),
- ).toEqual({
- sessionTitleModel: null,
- promptRecommendationModel: 'cat:anthropic:claude-code:model',
- });
+ ).toEqual(['litellm-qwen3.6-plus']);
+ });
+
+ it('keeps legacy refiner file fields ahead of utility environment overrides', () => {
+ vi.stubEnv('XDT_UTILITY_MODEL_PROVIDER', 'litellm-deepseek-v4-flash');
+ vi.stubEnv('XDT_UTILITY_MODEL_PROVIDER_CHAIN', 'codex-gpt-5.4-mini');
+
+ expect(
+ __testing.legacyVoiceOverrideRefs({
+ refinerProvider: 'litellm-kimi-k2.6',
+ refinerProviderChain: ['litellm-qwen3.6-plus'],
+ }),
+ ).toEqual(['litellm-kimi-k2.6', 'litellm-qwen3.6-plus']);
+ });
+
+ it('keeps the implicit default head when migrating a legacy fallback-only chain', () => {
+ expect(
+ __testing.legacyVoiceOverrideRefs({
+ refinerProviderChain: ['litellm-kimi-k2.6', 'litellm-deepseek-v4-flash'],
+ }),
+ ).toEqual(['codex-gpt-5.4-mini', 'litellm-kimi-k2.6', 'litellm-deepseek-v4-flash']);
});
});
diff --git a/apps/desktop/src/main/utility-model/__tests__/auxiliaryCustomNoAgentFallback.test.ts b/apps/desktop/src/main/utility-model/__tests__/auxiliaryCustomNoAgentFallback.test.ts
new file mode 100644
index 0000000000..0ed376bce0
--- /dev/null
+++ b/apps/desktop/src/main/utility-model/__tests__/auxiliaryCustomNoAgentFallback.test.ts
@@ -0,0 +1,50 @@
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { describe, expect, it } from 'vitest';
+
+const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '../../');
+
+describe('custom auxiliary chain does not hit the session agent', () => {
+ it('Help only allows the session oneShot fallback for the automatic chain', () => {
+ const source = readFileSync(path.join(root, 'maker-ipc/help.ts'), 'utf8');
+ expect(source.match(/const auxiliaryChain = getEffectiveAuxiliaryModelChain\(\);/g)?.length).toBe(2);
+ expect(source.match(/auxiliaryChain\.source === 'auto'/g)?.length).toBe(2);
+ expect(source).not.toContain('isAuxiliaryModelCustomized');
+ expect(source.match(/maker\.oneShot/g)?.length).toBeGreaterThan(0);
+ expect(source).toContain('const ownerScopeKey = activeOwnerScopeKey();');
+ expect(source.match(/beforeDispatch: async \(\) => isHelpOwnerScopeCurrent\(ownerScopeKey, auxiliaryChainSnapshot\)/g)?.length).toBe(2);
+ expect(source.match(/beforeDispatch: beforeSessionAgentDispatch/g)?.length).toBe(2);
+ expect(source).toContain('isHelpSessionAgentDispatchAllowed');
+ });
+
+ it('pinned-card summaries skip agent oneShot when the auxiliary list is customized', () => {
+ const source = readFileSync(path.join(root, 'sessionTaskSummary.ts'), 'utf8');
+ expect(source).toContain('const auxiliaryChain = getEffectiveAuxiliaryModelChain();');
+ expect(source).toContain("auxiliaryChain.source !== 'auto' ||");
+ expect(source).not.toContain('isAuxiliaryModelCustomized');
+ expect(source).toContain('await getMaker().oneShot');
+ expect(source).toContain('const ownerScopeKey = activeOwnerScopeKey();');
+ expect(source).toContain('const beforeSessionAgentDispatch = async () =>');
+ expect(source).toContain('beforeDispatch: beforeSessionAgentDispatch');
+ expect(source).toContain('isAgentOneShotRouteDisabled(agentKind)');
+ const disabledCheck = source.indexOf('isAgentOneShotRouteDisabled(agentKind)');
+ const ownerRecheck = source.indexOf('return isAuxiliaryOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot);', disabledCheck);
+ expect(ownerRecheck).toBeGreaterThan(disabledCheck);
+ });
+
+ it('voice refinement pins the effective auxiliary chain for the whole run', () => {
+ const source = readFileSync(path.join(root, 'voice-input/index.ts'), 'utf8');
+ expect(source).toContain('const auxiliaryChainSnapshot = getEffectiveAuxiliaryModelChainSnapshot();');
+ expect(source.match(/assertVoiceInputOwnerScopeCurrent\(ownerScopeKey, auxiliaryChainSnapshot\)/g)?.length).toBe(3);
+ expect(source).toContain('beforeDispatch: () => assertVoiceInputOwnerScopeCurrent(ownerScopeKey),');
+ });
+
+ it('dictionary learning uses the same owner and chain dispatch guard', () => {
+ const source = readFileSync(path.join(root, 'voice-input/index.ts'), 'utf8');
+ expect(source).toContain('const advisorAttempts: FallbackTextModelAttempt[] = readyAdvisorProfiles.map');
+ expect(source).toContain('client: guardRefinerClientAgainstUnavailableRoute(');
+ expect(source).toContain('assertVoiceInputOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot);');
+ });
+});
diff --git a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
index 13638d0144..773b3a9da7 100644
--- a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
+++ b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
@@ -19,6 +19,28 @@ vi.mock('../UtilityModelSelection.js', () => ({
getUtilityModelChainProfiles: vi.fn(),
}));
+const chainState = vi.hoisted(() => ({
+ source: 'auto' as 'auto' | 'custom' | 'env',
+ refs: ['codex-gpt-5.4-mini', 'litellm-gpt-5.4-mini'],
+}));
+
+const ownerState = vi.hoisted(() => ({
+ key: 'owner-a',
+ pending: false,
+}));
+
+vi.mock('../resolveAuxiliaryModelChain.js', () => ({
+ getEffectiveAuxiliaryModelChain: () => ({
+ source: chainState.source,
+ refs: [...chainState.refs],
+ }),
+}));
+
+vi.mock('../../appSessionState.js', () => ({
+ activeOwnerScopeKey: () => ownerState.key,
+ isAppSessionBoundaryPending: () => ownerState.pending,
+}));
+
vi.mock('../../maker-host/auth-adapters.js', () => ({
readClaudeApiKey: vi.fn(),
}));
@@ -125,6 +147,10 @@ describe('utility one-shot candidates', () => {
beforeEach(() => {
vi.clearAllMocks();
fetchMock.mockReset();
+ chainState.source = 'auto';
+ chainState.refs = ['codex-gpt-5.4-mini', 'litellm-gpt-5.4-mini'];
+ ownerState.key = 'owner-a';
+ ownerState.pending = false;
appCapabilities.mockReturnValue({ canUseCindyGateway: true } as never);
readKey.mockReturnValue(null);
readCodexCreds.mockRejectedValue(new Error('not authenticated'));
@@ -186,6 +212,108 @@ describe('utility one-shot candidates', () => {
expect(fetchMock).not.toHaveBeenCalled();
});
+ it('aborts the default chain when the owner changes before dispatch', async () => {
+ readKey.mockReturnValue('proxy-key');
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ choices: [{ message: { content: 'must not dispatch' } }] }),
+ } as never);
+
+ const request = requestUtilityText(makerMock(false), 'hello');
+ ownerState.key = 'owner-b';
+
+ const result = await request;
+
+ expect(result).toMatchObject({ ok: false });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('rechecks the owner after profile resolution before invoking Codex oneShot', async () => {
+ chainState.refs = ['codex-gpt-5.4-mini'];
+ getProfiles.mockReturnValue([{
+ id: 'codex-gpt-5.4-mini',
+ model: 'gpt-5.4-mini',
+ transport: 'codex-responses',
+ auth: 'codex',
+ settingsTab: 'connections',
+ missingCredentialMessage: 'codex missing',
+ }]);
+ const maker = makerMock(true);
+ vi.mocked(maker.getAgentAuthState).mockImplementation(async () => {
+ ownerState.key = 'owner-b';
+ return { authenticated: true };
+ });
+
+ const result = await requestUtilityText(maker, 'must stay with owner-a');
+
+ expect(result).toMatchObject({ ok: false });
+ expect(vi.mocked(maker.oneShot)).not.toHaveBeenCalled();
+ });
+
+ it('rechecks profile disable status at final Codex dispatch', async () => {
+ chainState.refs = ['codex-gpt-5.4-mini'];
+ const maker = makerMock(true);
+ vi.mocked(maker.oneShot).mockImplementation(async (_agent, _prompt, options) => {
+ readDisableOverrides.mockReturnValue({
+ disabledModels: {},
+ disabledProviders: { openai: true },
+ } as never);
+ const allowed = options?.beforeDispatch ? await options.beforeDispatch() : true;
+ if (!allowed) throw new Error('request_failed');
+ return 'must not dispatch';
+ });
+
+ const result = await requestUtilityText(maker, 'hello');
+
+ expect(result).toMatchObject({
+ ok: false,
+ reason: 'all_candidates_failed',
+ attempts: [expect.objectContaining({ reason: 'request_failed' })],
+ });
+ expect(vi.mocked(maker.oneShot)).toHaveBeenCalledOnce();
+ });
+
+ it('rechecks the owner after an async caller guard before LiteLLM dispatch', async () => {
+ chainState.refs = ['litellm-gpt-5.4-mini'];
+ readKey.mockReturnValue('proxy-key');
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ choices: [{ message: { content: 'must not dispatch' } }] }),
+ } as never);
+
+ const result = await requestUtilityText(makerMock(false), 'must stay with owner-a', {
+ beforeDispatch: async () => {
+ ownerState.key = 'owner-b';
+ return true;
+ },
+ });
+
+ expect(result).toMatchObject({ ok: false });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('runs the caller guard at the final LiteLLM dispatch boundary', async () => {
+ chainState.refs = ['litellm-gpt-5.4-mini'];
+ readKey.mockReturnValue('proxy-key');
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ choices: [{ message: { content: 'must not dispatch' } }] }),
+ } as never);
+
+ let guardCalls = 0;
+ const beforeDispatch = vi.fn(async () => {
+ guardCalls += 1;
+ return guardCalls < 3;
+ });
+ const result = await requestUtilityText(makerMock(false), 'must stay guarded', {
+ beforeDispatch,
+ });
+
+ expect(result).toMatchObject({ ok: false });
+ expect(beforeDispatch).toHaveBeenCalledTimes(3);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
it('applies paid availability only to direct XD LiteLLM utility routes', () => {
xdPaymentRequiredRoute.mockImplementation((model) => model === 'paid-model');
@@ -246,10 +374,58 @@ describe('utility one-shot candidates', () => {
});
expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({
max_tokens: 10,
- reasoning_effort: 'low',
+ thinking: { type: 'disabled' },
+ });
+ expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).not.toHaveProperty(
+ 'reasoning_effort',
+ );
+ });
+
+ it('passes system and response instructions through profile candidates', async () => {
+ const maker = makerMock(true);
+ chainState.refs = ['codex-gpt-5.4-mini', 'litellm-gpt-5.4-mini'];
+ readKey.mockReturnValue('proxy-key');
+ vi.mocked(maker.oneShot).mockRejectedValueOnce(new Error('codex unavailable'));
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ choices: [{ message: { content: 'lite text' } }] }),
+ } as never);
+
+ const result = await requestUtilityText(maker, 'reference', {
+ systemPrompt: 'SYSTEM POLICY',
+ responseInstructions: 'ONE LINE ONLY',
+ });
+
+ expect(result).toMatchObject({ ok: true, providerId: 'litellm-gpt-5.4-mini' });
+ expect(maker.oneShot).toHaveBeenCalledWith('codex', 'reference', expect.objectContaining({
+ systemPrompt: 'SYSTEM POLICY',
+ responseInstructions: 'ONE LINE ONLY',
+ }));
+ expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({
+ messages: [
+ { role: 'system', content: 'SYSTEM POLICY\nONE LINE ONLY' },
+ { role: 'user', content: 'reference' },
+ ],
});
});
+ it('stops before a later fallback when the auxiliary chain changes mid-request', async () => {
+ readKey.mockReturnValue('proxy-key');
+ const maker = makerMock(true);
+ vi.mocked(maker.oneShot).mockImplementationOnce(async () => {
+ chainState.refs = ['codex-gpt-5.4-mini'];
+ throw new Error('codex down');
+ });
+
+ const result = await requestUtilityText(maker, 'hello');
+
+ expect(result).toMatchObject({ ok: false });
+ expect(vi.mocked(maker.oneShot)).toHaveBeenCalledTimes(1);
+ expect(fetchMock).not.toHaveBeenCalled();
+ if (result.ok) throw new Error('expected the stale fallback chain to abort');
+ expect(result.attempts).toHaveLength(1);
+ });
+
it('chat-completions 的 content 为 parts 数组时拼接文本段(思考模型形态)', async () => {
readKey.mockReturnValue('proxy-key');
fetchMock.mockResolvedValueOnce({
@@ -340,6 +516,29 @@ describe('utility one-shot candidates', () => {
});
});
+ it('rechecks the owner for a pinned profile before invoking Codex oneShot', async () => {
+ const maker = makerMock(true);
+ vi.mocked(maker.getAgentAuthState).mockImplementation(async () => {
+ ownerState.key = 'owner-b';
+ return { authenticated: true };
+ });
+ getProfiles.mockReturnValue([{
+ id: 'codex-gpt-5.4-mini',
+ model: 'gpt-5.4-mini',
+ transport: 'codex-responses',
+ auth: 'codex',
+ settingsTab: 'connections',
+ missingCredentialMessage: 'codex missing',
+ }]);
+
+ const result = await requestUtilityText(maker, 'must stay with owner-a', {
+ pinnedProfileId: 'codex-gpt-5.4-mini',
+ });
+
+ expect(result).toMatchObject({ ok: false });
+ expect(vi.mocked(maker.oneShot)).not.toHaveBeenCalled();
+ });
+
it('不认的 pinnedProfileId 忽略,回落默认链', async () => {
readKey.mockReturnValue('proxy-key');
fetchMock.mockResolvedValueOnce({
@@ -384,6 +583,7 @@ describe('utility one-shot candidates', () => {
});
it('distinguishes an empty response from generic request failures', async () => {
+ chainState.refs = ['codex-gpt-5.4-mini'];
getProfiles.mockReturnValue([{
id: 'codex-gpt-5.4-mini',
model: 'gpt-5.4-mini',
@@ -414,8 +614,8 @@ describe('utility one-shot candidates', () => {
ok: false,
reason: 'timeout',
attempts: [
- expect.objectContaining({ providerId: 'litellm-gpt-5.4-mini', status: 'skipped' }),
expect.objectContaining({ providerId: 'codex-gpt-5.4-mini', reason: 'timeout' }),
+ expect.objectContaining({ providerId: 'litellm-gpt-5.4-mini', status: 'skipped' }),
],
});
});
@@ -611,6 +811,51 @@ describe('utility one-shot candidates', () => {
});
});
+ it('maps disabled thinking to Ollama reasoning_effort none', async () => {
+ activeCatalog.mockReturnValue({
+ providers: [{
+ id: 'cindy-local-ollama',
+ name: 'Ollama',
+ source: 'user',
+ agents: ['codex'],
+ auth: { method: 'none' },
+ routing: {
+ codex: {
+ upstream: 'http://127.0.0.1:11434/v1',
+ wireProtocol: 'openai-chat',
+ authStrategy: 'none',
+ },
+ },
+ models: {
+ codex: [{ id: 'qwen3.8:27b', name: 'Qwen 3.8 27B', contextWindow: 100_000 }],
+ },
+ }],
+ } as never);
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ text: async () => JSON.stringify({
+ choices: [{ message: { content: 'local title', reasoning: 'hidden chain' } }],
+ }),
+ } as never);
+
+ const result = await requestExplicitUtilityText('generate', {
+ providerId: 'cindy-local-ollama',
+ agentKind: 'codex',
+ model: 'qwen3.8:27b',
+ maxTokens: 32,
+ disableReasoning: true,
+ });
+
+ expect(result).toMatchObject({ ok: true, text: 'local title' });
+ const body = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body));
+ expect(body).toMatchObject({
+ model: 'qwen3.8:27b',
+ max_tokens: 32,
+ reasoning_effort: 'none',
+ });
+ expect(body).not.toHaveProperty('thinking');
+ });
+
it('keeps system instructions separate on an exact auxiliary chat route', async () => {
activeCatalog.mockReturnValue({
providers: [{
@@ -1786,6 +2031,45 @@ describe('utility one-shot candidates', () => {
});
});
+ it('fails closed when an explicit XD catalog model becomes payment-required', async () => {
+ activeCatalog.mockReturnValue({
+ providers: [{
+ id: 'xd',
+ name: 'XD Gateway',
+ source: 'builtin',
+ agents: ['codex'],
+ auth: { method: 'managed' },
+ routing: {
+ codex: { upstream: 'https://ignored.invalid', authStrategy: 'gateway-key' },
+ },
+ models: {
+ codex: [{ id: 'paid-model', name: 'Paid model', contextWindow: 1_000_000 }],
+ },
+ }],
+ } as never);
+ readKey.mockReturnValue('xd-key');
+ xdPaymentRequiredRoute.mockImplementation((model, agent) => model === 'paid-model' && agent === 'codex');
+
+ const result = await requestUtilityText(makerMock(false), 'generate', {
+ providerId: 'xd',
+ agentKind: 'codex',
+ model: 'paid-model',
+ });
+
+ expect(result).toEqual({
+ ok: false,
+ reason: 'no_candidate',
+ attempts: [{
+ providerId: 'xd',
+ model: 'paid-model',
+ transport: 'codex-responses',
+ status: 'skipped',
+ reason: 'model_unavailable',
+ }],
+ });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
it('uses Anthropic OAuth and the selected Anthropic routing for an explicit builtin provider', async () => {
activeCatalog.mockReturnValue({
providers: [{
@@ -1861,6 +2145,39 @@ describe('utility one-shot candidates', () => {
expect(body).not.toHaveProperty('max_output_tokens');
});
+ it('maps disabled reasoning to low for OpenAI Responses instead of unsupported minimal', async () => {
+ activeCatalog.mockReturnValue({
+ providers: [{
+ id: 'openai',
+ name: 'OpenAI',
+ source: 'builtin',
+ agents: ['codex'],
+ auth: { method: 'oauth' },
+ routing: { codex: { upstream: 'https://chatgpt.example/api/v1', authStrategy: 'oauth-passthrough' } },
+ models: { codex: [{ id: 'chatgpt/gpt-5.4-mini', name: 'GPT-5.4 Mini', contextWindow: 272_000 }] },
+ }],
+ } as never);
+ readCodexCreds.mockResolvedValue({ accessToken: 'codex-token', accountId: 'account-1' });
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ text: async () => 'data: {"type":"response.output_text.delta","delta":"title"}\ndata: [DONE]\n',
+ } as never);
+
+ const result = await requestUtilityText(makerMock(false), 'generate', {
+ providerId: 'openai',
+ agentKind: 'codex',
+ model: 'chatgpt/gpt-5.4-mini',
+ maxTokens: 32,
+ disableReasoning: true,
+ reasoningEffort: 'minimal',
+ });
+
+ expect(result).toMatchObject({ ok: true, providerId: 'openai', model: 'chatgpt/gpt-5.4-mini' });
+ const body = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body)) as Record<string, unknown>;
+ expect(body).toMatchObject({ reasoning: { effort: 'low' } });
+ expect(body).not.toHaveProperty('max_output_tokens');
+ });
+
it('routes the fixed cindy/auto-review alias without requiring a catalog entry', async () => {
readKey.mockReturnValue('xd-key');
activeCatalog.mockReturnValue({ providers: [] } as never);
@@ -2127,4 +2444,143 @@ describe('utility one-shot candidates', () => {
expect(body).not.toHaveProperty('reasoning');
},
);
+
+ it('tries a one-item custom chain in order and never expands to AUTO', async () => {
+ chainState.source = 'custom';
+ chainState.refs = ['litellm-kimi-k2.6'];
+ readKey.mockReturnValue('proxy-key');
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ choices: [{ message: { content: 'kimi text' } }] }),
+ } as never);
+
+ const result = await requestUtilityText(makerMock(false), 'hello', { maxTokens: 10 });
+
+ expect(result).toMatchObject({
+ ok: true,
+ text: 'kimi text',
+ providerId: 'litellm-kimi-k2.6',
+ model: 'moonshotai/kimi-k2.6',
+ });
+ expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({
+ model: 'moonshotai/kimi-k2.6',
+ thinking: { type: 'disabled' },
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('tries a two-item custom chain strictly in order', async () => {
+ chainState.source = 'custom';
+ chainState.refs = ['litellm-kimi-k2.6', 'litellm-gpt-5.4-mini'];
+ readKey.mockReturnValue('proxy-key');
+ fetchMock
+ .mockResolvedValueOnce({
+ ok: false,
+ status: 403,
+ body: { cancel: vi.fn(async () => undefined) },
+ } as never)
+ .mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ choices: [{ message: { content: 'mini text' } }] }),
+ } as never);
+
+ const result = await requestUtilityText(makerMock(false), 'hello');
+
+ expect(result).toMatchObject({
+ ok: true,
+ text: 'mini text',
+ providerId: 'litellm-gpt-5.4-mini',
+ });
+ expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({
+ model: 'moonshotai/kimi-k2.6',
+ });
+ expect(JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body))).toMatchObject({
+ model: 'gpt-5.4-mini',
+ });
+ });
+
+ it('tries a three-item custom chain and stops after the last success', async () => {
+ chainState.source = 'custom';
+ chainState.refs = [
+ 'litellm-kimi-k2.6',
+ 'litellm-gpt-5.4-mini',
+ 'litellm-deepseek-v4-flash',
+ ];
+ readKey.mockReturnValue('proxy-key');
+ fetchMock
+ .mockResolvedValueOnce({
+ ok: false,
+ status: 403,
+ body: { cancel: vi.fn(async () => undefined) },
+ } as never)
+ .mockResolvedValueOnce({
+ ok: false,
+ status: 503,
+ body: { cancel: vi.fn(async () => undefined) },
+ } as never)
+ .mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ choices: [{ message: { content: 'flash text' } }] }),
+ } as never);
+
+ const result = await requestUtilityText(makerMock(false), 'hello');
+
+ expect(result).toMatchObject({
+ ok: true,
+ text: 'flash text',
+ providerId: 'litellm-deepseek-v4-flash',
+ model: 'deepseek/deepseek-v4-flash',
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ });
+
+ it('does not fall back to AUTO candidates after a custom chain is exhausted', async () => {
+ chainState.source = 'custom';
+ chainState.refs = ['litellm-kimi-k2.6', 'litellm-deepseek-v4-flash'];
+ readKey.mockReturnValue('proxy-key');
+ fetchMock
+ .mockResolvedValueOnce({
+ ok: false,
+ status: 403,
+ body: { cancel: vi.fn(async () => undefined) },
+ } as never)
+ .mockResolvedValueOnce({
+ ok: false,
+ status: 503,
+ body: { cancel: vi.fn(async () => undefined) },
+ } as never);
+
+ const maker = makerMock(true);
+ const result = await requestUtilityText(maker, 'hello');
+
+ expect(result).toMatchObject({
+ ok: false,
+ reason: 'all_candidates_failed',
+ });
+ expect(result.ok === false ? result.attempts.map((attempt) => attempt.providerId) : []).toEqual([
+ 'litellm-kimi-k2.6',
+ 'litellm-deepseek-v4-flash',
+ ]);
+ expect(vi.mocked(maker.oneShot)).not.toHaveBeenCalled();
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('sends reasoning_effort when the caller turns thinking back on', async () => {
+ chainState.refs = ['litellm-gpt-5.4-mini'];
+ readKey.mockReturnValue('proxy-key');
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ choices: [{ message: { content: 'reasoned' } }] }),
+ } as never);
+
+ await requestUtilityText(makerMock(false), 'hello', {
+ disableReasoning: false,
+ reasoningEffort: 'low',
+ });
+
+ expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({
+ reasoning_effort: 'low',
+ });
+ expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).not.toHaveProperty('thinking');
+ });
});
diff --git a/apps/desktop/src/main/utility-model/__tests__/resolveAuxiliaryModelChain.test.ts b/apps/desktop/src/main/utility-model/__tests__/resolveAuxiliaryModelChain.test.ts
new file mode 100644
index 0000000000..45034cd76f
--- /dev/null
+++ b/apps/desktop/src/main/utility-model/__tests__/resolveAuxiliaryModelChain.test.ts
@@ -0,0 +1,125 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const h = vi.hoisted(() => ({
+ models: [] as string[],
+}));
+
+vi.mock('../auxiliary-model-settings-store.js', () => ({
+ readAuxiliaryModelSettings: () => ({ models: h.models }),
+ isAuxiliaryModelCustomized: () => h.models.length > 0,
+}));
+
+import { AUTO_AUXILIARY_MODEL_CHAIN } from '../../../shared/auxiliaryModelChain.js';
+import {
+ formatAuxiliaryModelRefLabel,
+ getEffectiveAuxiliaryModelChain,
+ getEffectiveAuxiliaryModelChainSnapshot,
+} from '../resolveAuxiliaryModelChain.js';
+
+const ENV_KEYS = [
+ 'XDT_UTILITY_MODEL_PROVIDER_CHAIN',
+ 'XDT_UTILITY_MODEL_PROVIDER',
+ 'XDT_UTILITY_MODEL',
+ 'XDT_VOICE_INPUT_REFINER_PROVIDER_CHAIN',
+ 'XDT_VOICE_INPUT_REFINER_PROVIDER',
+ 'XDT_VOICE_INPUT_REFINER_MODEL',
+] as const;
+
+function restoreEnv(): void {
+ for (const key of ENV_KEYS) {
+ vi.stubEnv(key, undefined);
+ }
+}
+
+describe('getEffectiveAuxiliaryModelChain', () => {
+ beforeEach(() => {
+ h.models = [];
+ restoreEnv();
+ });
+
+ afterEach(() => {
+ restoreEnv();
+ });
+
+ it('returns the frozen automatic chain when nothing is customized', () => {
+ expect(getEffectiveAuxiliaryModelChain()).toEqual({
+ source: 'auto',
+ refs: [...AUTO_AUXILIARY_MODEL_CHAIN],
+ });
+ });
+
+ it('uses the user custom list and never falls back to auto or env', () => {
+ h.models = ['litellm-kimi-k2.6', 'codex-gpt-5.4-mini'];
+ vi.stubEnv('XDT_UTILITY_MODEL_PROVIDER_CHAIN', 'litellm-gpt-5.4-mini,litellm-deepseek-v4-flash');
+
+ expect(getEffectiveAuxiliaryModelChain()).toEqual({
+ source: 'custom',
+ refs: ['litellm-kimi-k2.6', 'codex-gpt-5.4-mini'],
+ });
+ });
+
+ it('uses the env escape hatch only in automatic mode', () => {
+ vi.stubEnv('XDT_UTILITY_MODEL_PROVIDER', 'kimi-k2.6');
+ vi.stubEnv('XDT_UTILITY_MODEL_PROVIDER_CHAIN', 'litellm-gpt-5.4-mini,litellm-kimi-k2.6');
+
+ expect(getEffectiveAuxiliaryModelChain()).toEqual({
+ source: 'env',
+ refs: ['litellm-kimi-k2.6', 'litellm-gpt-5.4-mini'],
+ });
+ });
+
+ it('keeps the implicit default provider ahead of an env-only fallback chain', () => {
+ vi.stubEnv('XDT_UTILITY_MODEL_PROVIDER_CHAIN', 'litellm-kimi-k2.6,litellm-deepseek-v4-flash');
+
+ expect(getEffectiveAuxiliaryModelChain()).toEqual({
+ source: 'env',
+ refs: [
+ 'codex-gpt-5.4-mini',
+ 'litellm-kimi-k2.6',
+ 'litellm-deepseek-v4-flash',
+ ],
+ });
+ });
+
+ it('keeps legacy voice refiner env vars and model overrides working', () => {
+ vi.stubEnv('XDT_VOICE_INPUT_REFINER_PROVIDER', 'litellm');
+ vi.stubEnv('XDT_VOICE_INPUT_REFINER_MODEL', 'qwen/qwen3.6-plus');
+ vi.stubEnv('XDT_VOICE_INPUT_REFINER_PROVIDER_CHAIN', 'litellm-deepseek-v4-flash');
+
+ expect(getEffectiveAuxiliaryModelChain()).toEqual({
+ source: 'env',
+ refs: ['litellm-qwen3.6-plus', 'litellm-deepseek-v4-flash'],
+ });
+ });
+
+ it('preserves an unknown legacy model override as an exact catalog pin', () => {
+ vi.stubEnv('XDT_UTILITY_MODEL_PROVIDER', 'litellm');
+ vi.stubEnv('XDT_UTILITY_MODEL', 'qwen/qwen3.8-flash-local');
+
+ expect(getEffectiveAuxiliaryModelChain()).toEqual({
+ source: 'env',
+ refs: ['cat:xd:codex:qwen/qwen3.8-flash-local'],
+ });
+ });
+
+ it('uses the product-facing Cindy AI label for XD catalog refs', () => {
+ expect(formatAuxiliaryModelRefLabel('cat:xd:codex:deepseek/deepseek-v4-flash'))
+ .toBe('deepseek/deepseek-v4-flash · Cindy AI');
+ });
+
+ it('changes when the effective source or ordered refs change', () => {
+ const automatic = getEffectiveAuxiliaryModelChainSnapshot();
+ h.models = ['litellm-kimi-k2.6'];
+ const custom = getEffectiveAuxiliaryModelChainSnapshot();
+
+ expect(automatic).not.toBe(custom);
+ expect(JSON.parse(automatic)).toEqual({
+ source: 'auto',
+ refs: [...AUTO_AUXILIARY_MODEL_CHAIN],
+ });
+ expect(JSON.parse(custom)).toEqual({
+ source: 'custom',
+ refs: ['litellm-kimi-k2.6'],
+ });
+ });
+});
diff --git a/apps/desktop/src/main/utility-model/__tests__/textOneshotPinOptions.test.ts b/apps/desktop/src/main/utility-model/__tests__/textOneshotPinOptions.test.ts
index ab65d09c6d..ce7be9faed 100644
--- a/apps/desktop/src/main/utility-model/__tests__/textOneshotPinOptions.test.ts
+++ b/apps/desktop/src/main/utility-model/__tests__/textOneshotPinOptions.test.ts
@@ -99,8 +99,8 @@ describe('buildTextOneshotPinOptions', () => {
expect(options).toEqual([
{
id: 'cat:xd:codex:codex/gpt-5.5',
- label: 'Codex · GPT 5.5 折扣 · Cindy Gateway',
- group: 'Cindy Gateway',
+ label: 'Codex · GPT 5.5 折扣 · Cindy AI',
+ group: 'Cindy AI',
providerId: 'xd',
agentKind: 'codex',
modelId: 'codex/gpt-5.5',
@@ -309,8 +309,8 @@ describe('buildTextOneshotPinOptions', () => {
undefined,
);
expect(options.map((o) => [o.id, o.label])).toEqual([
- ['cat:xd:codex:gpt-5.5', 'Codex · GPT 5.5 · GW'],
- ['cat:xd:claude-code:gpt-5.5', 'Claude Code · GPT 5.5 · GW'],
+ ['cat:xd:codex:gpt-5.5', 'Codex · GPT 5.5 · Cindy AI'],
+ ['cat:xd:claude-code:gpt-5.5', 'Claude Code · GPT 5.5 · Cindy AI'],
['cat:dual:codex:gpt-5.5', 'Codex · GPT 5.5 · Dual'],
['cat:dual:claude-code:gpt-5.5', 'Claude Code · GPT 5.5 · Dual'],
]);
@@ -339,7 +339,7 @@ describe('buildTextOneshotPinOptions', () => {
);
expect(options.map((o) => [o.id, o.label])).toEqual([
- ['cat:xd:codex:gpt-5.5', 'Codex · GPT 5.5 · xd'],
+ ['cat:xd:codex:gpt-5.5', 'Codex · GPT 5.5 · Cindy AI'],
]);
});
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.ts
index 5cbb5180f3..d08594bcd3 100644
--- a/apps/desktop/src/main/utility-model/auxiliary-model-settings-store.ts
+++ b/apps/desktop/src/main/utility-model/auxiliary-model-settings-store.ts
@@ -1,20 +1,38 @@
/**
- * Main-process source of truth for short auxiliary text model choices.
+ * Main-process source of truth for the shared auxiliary-model chain.
*
- * 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).
+ * Only an explicit `models` override is persisted. An empty list (or a missing
+ * file) means “automatic”, so restoring the default deletes the file rather
+ * than writing a snapshot of the current built-in chain.
*/
+import fs from 'node:fs';
+import path from 'node:path';
+
+import { app } from 'electron';
+
import {
AUXILIARY_MODEL_SETTINGS_DEFAULTS,
- normalizeAuxiliaryModelPin,
+ normalizeAuxiliaryModelList,
+ normalizeAuxiliaryModelRef,
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 { encodeCatalogModelPin } from '../../shared/catalogModelPin.js';
+import {
+ getUtilityModelProfile,
+ isUtilityModelProviderKind,
+ resolveUtilityModelProviderKindAlias,
+} from '../../shared/utilityModelProfiles.js';
+import {
+ activeOwnerScopeKey,
+ getActiveAppSession,
+ ownerScopedUserDataPath,
+} from '../appSessionState.js';
+import {
+ hasExclusiveSharedLegacyUserDataAccess,
+ hasLegacyOwnerNamespaceClaim,
+} from '../ownerNamespaceMigration.js';
import { desktopMakerLogger } from '../maker-host/logger-adapter.js';
import {
createOverrideSettingsFile,
@@ -22,19 +40,360 @@ import {
} from '../maker-host/override-settings-file.js';
const log = desktopMakerLogger.child('auxiliary-model-settings-store');
+const VOICE_INPUT_MODELS_FILE = 'voice-input-models.json';
+const AUXILIARY_MODEL_MIGRATION_FILE = 'auxiliary-model-settings-migration.json';
function settingsFilePath(): string {
return ownerScopedUserDataPath('auxiliary-model-settings.json');
}
+function ownerVoiceModelsPath(): string {
+ return ownerScopedUserDataPath(VOICE_INPUT_MODELS_FILE);
+}
+
+function unscopedVoiceModelsPath(): string {
+ return path.join(app.getPath('userData'), VOICE_INPUT_MODELS_FILE);
+}
+
+function readDefaultLegacyMigrationEnv(): NodeJS.ProcessEnv {
+ // Vite replaces complete `process.env.XDT_*` expressions in the main bundle.
+ // Keep these direct reads in the migration module instead of relying on the
+ // runtime `process.env` object, which may not contain build-time injections.
+ return {
+ ...process.env,
+ XDT_UTILITY_MODEL_PROVIDER: process.env.XDT_UTILITY_MODEL_PROVIDER,
+ XDT_UTILITY_MODEL: process.env.XDT_UTILITY_MODEL,
+ XDT_UTILITY_MODEL_PROVIDER_CHAIN: process.env.XDT_UTILITY_MODEL_PROVIDER_CHAIN,
+ XDT_VOICE_INPUT_REFINER_PROVIDER: process.env.XDT_VOICE_INPUT_REFINER_PROVIDER,
+ XDT_VOICE_INPUT_REFINER_MODEL: process.env.XDT_VOICE_INPUT_REFINER_MODEL,
+ XDT_VOICE_INPUT_REFINER_PROVIDER_CHAIN: process.env.XDT_VOICE_INPUT_REFINER_PROVIDER_CHAIN,
+ };
+}
+
+function migrationStatePath(): string {
+ return ownerScopedUserDataPath(AUXILIARY_MODEL_MIGRATION_FILE);
+}
+
+function readClaimedUnscopedVoiceModels(): Record<string, unknown> | null {
+ const session = getActiveAppSession();
+ if (session.mode !== 'cloud' || !session.dataOwnerId) return null;
+ if (!hasLegacyOwnerNamespaceClaim(session.dataOwnerId)) return null;
+ return readJsonObject(unscopedVoiceModelsPath());
+}
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function readJsonObject(filePath: string): Record<string, unknown> | null {
+ try {
+ if (!fs.existsSync(filePath)) return null;
+ const parsed: unknown = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+ return isPlainObject(parsed) ? parsed : null;
+ } catch {
+ return null;
+ }
+}
+
+function hasLegacyVoiceMigrationMarker(): boolean {
+ return readJsonObject(migrationStatePath())?.legacyVoiceMigrationCompleted === true;
+}
+
+function markLegacyVoiceMigrationComplete(): void {
+ const file = migrationStatePath();
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(
+ file,
+ `${JSON.stringify({ legacyVoiceMigrationCompleted: true }, null, 2)}\n`,
+ 'utf-8',
+ );
+}
+
+function collectUniqueRefs(values: Array<string | null>): string[] {
+ const models: string[] = [];
+ for (const value of values) {
+ if (!value || models.includes(value)) continue;
+ models.push(value);
+ }
+ return models;
+}
+
+function refFromUnknown(value: unknown): string | null {
+ if (typeof value !== 'string') return null;
+ const trimmed = value.trim();
+ if (!trimmed) return null;
+ const catalogOrProfile = normalizeAuxiliaryModelRef(trimmed);
+ if (catalogOrProfile) return catalogOrProfile;
+ const alias = resolveUtilityModelProviderKindAlias(trimmed);
+ return alias && isUtilityModelProviderKind(alias) ? alias : null;
+}
+
+function refsFromUnknownList(value: unknown): string[] {
+ if (!Array.isArray(value)) return [];
+ return collectUniqueRefs(value.map((entry) => refFromUnknown(entry)));
+}
+
+function readLegacyStringList(
+ raw: Record<string, unknown>,
+ key: 'utilityModelProviderChain' | 'refinerProviderChain',
+): string[] | undefined {
+ const value = raw[key];
+ if (!Array.isArray(value)) return undefined;
+ const entries = value
+ .filter((entry): entry is string => typeof entry === 'string')
+ .map((entry) => entry.trim())
+ .filter(Boolean);
+ return entries.length > 0 ? entries : undefined;
+}
+
+function splitCommaList(value: string | undefined): string[] | undefined {
+ const entries = (value ?? '')
+ .split(',')
+ .map((entry) => entry.trim())
+ .filter(Boolean);
+ return entries.length > 0 ? entries : undefined;
+}
+
+function firstNonBlankString(...values: unknown[]): string | undefined {
+ for (const value of values) {
+ if (typeof value !== 'string') continue;
+ const trimmed = value.trim();
+ if (trimmed) return trimmed;
+ }
+ return undefined;
+}
+
+function hasLegacyVoiceFileOverride(raw: Record<string, unknown> | null): boolean {
+ if (!raw) return false;
+ return Boolean(
+ firstNonBlankString(
+ raw.utilityModelProvider,
+ raw.utilityModel,
+ raw.refinerProvider,
+ raw.refinerModel,
+ ) ||
+ readLegacyStringList(raw, 'utilityModelProviderChain')?.length ||
+ readLegacyStringList(raw, 'refinerProviderChain')?.length,
+ );
+}
+
+function legacyVoiceHeadRef(
+ raw: Record<string, unknown>,
+ env: NodeJS.ProcessEnv = readDefaultLegacyMigrationEnv(),
+): string | null {
+ // Match the legacy VoiceInputModelSelection precedence: utility file,
+ // refiner file, utility env, refiner env. In particular, an old file may
+ // only pin the provider while XDT_UTILITY_MODEL_PROVIDER_CHAIN supplies the
+ // fallback tail.
+ const providerValue = firstNonBlankString(
+ raw.utilityModelProvider,
+ raw.refinerProvider,
+ env.XDT_UTILITY_MODEL_PROVIDER,
+ env.XDT_VOICE_INPUT_REFINER_PROVIDER,
+ );
+ const providerRef = refFromUnknown(providerValue);
+ const model = firstNonBlankString(
+ raw.utilityModel,
+ raw.refinerModel,
+ env.XDT_UTILITY_MODEL,
+ env.XDT_VOICE_INPUT_REFINER_MODEL,
+ );
+ if (!providerRef && !model) return null;
+ const effectiveProviderRef = providerRef ?? resolveUtilityModelProviderKindAlias('');
+ if (!effectiveProviderRef) return null;
+ if (!model) return effectiveProviderRef;
+
+ // Preserve known model aliases as their exact profile key. This keeps the
+ // old `litellm` + `qwen/qwen3.6-plus` form on the same credential transport
+ // without freezing the provider's default model.
+ const modelAlias = resolveUtilityModelProviderKindAlias(model);
+ if (
+ modelAlias &&
+ isUtilityModelProviderKind(effectiveProviderRef) &&
+ getUtilityModelProfile(effectiveProviderRef).transport ===
+ getUtilityModelProfile(modelAlias).transport
+ ) {
+ return modelAlias;
+ }
+
+ // Unknown model ids can still be represented as an exact catalog route. The
+ // active catalog remains the final availability gate at dispatch time.
+ if (isUtilityModelProviderKind(effectiveProviderRef)) {
+ const profile = getUtilityModelProfile(effectiveProviderRef);
+ return normalizeAuxiliaryModelRef(
+ encodeCatalogModelPin({
+ providerId: profile.transport === 'codex-responses' ? 'openai' : 'xd',
+ agentKind: 'codex',
+ model,
+ }),
+ );
+ }
+ return effectiveProviderRef;
+}
+
+/**
+ * A voice/utility file counts as customized only when the user (or an old
+ * settings page) wrote a non-empty refiner/utility chain or a non-empty head.
+ * Sparse empty strings are the product default, not an override.
+ */
+function legacyVoiceOverrideRefs(
+ raw: Record<string, unknown> | null,
+ env: NodeJS.ProcessEnv = readDefaultLegacyMigrationEnv(),
+): string[] {
+ // Environment variables remain a live escape hatch. Only migrate when the
+ // legacy file itself contains a voice/utility override; otherwise the new
+ // resolver continues to return source: 'env' on every read.
+ if (!hasLegacyVoiceFileOverride(raw)) return [];
+ const source = raw ?? {};
+ const head = legacyVoiceHeadRef(source, env);
+ const rawChain =
+ readLegacyStringList(source, 'utilityModelProviderChain') ??
+ readLegacyStringList(source, 'refinerProviderChain') ??
+ splitCommaList(env.XDT_UTILITY_MODEL_PROVIDER_CHAIN) ??
+ splitCommaList(env.XDT_VOICE_INPUT_REFINER_PROVIDER_CHAIN);
+ const chain = refsFromUnknownList(rawChain);
+ const refs = collectUniqueRefs([head, ...chain]);
+ const hasExplicitHead = Boolean(
+ firstNonBlankString(
+ source.utilityModelProvider,
+ env.XDT_UTILITY_MODEL_PROVIDER,
+ source.refinerProvider,
+ env.XDT_VOICE_INPUT_REFINER_PROVIDER,
+ ) ||
+ firstNonBlankString(
+ source.utilityModel,
+ env.XDT_UTILITY_MODEL,
+ source.refinerModel,
+ env.XDT_VOICE_INPUT_REFINER_MODEL,
+ ),
+ );
+ const hasExplicitChain = Boolean(rawChain?.length);
+ if (!hasExplicitHead && !hasExplicitChain) return [];
+ if (head || !hasExplicitChain) return refs;
+
+ // The legacy resolver always supplied the default provider as the head when
+ // only a provider chain was configured. Preserve that ordering during the
+ // one-shot migration instead of promoting the first fallback to primary.
+ const defaultHead = resolveUtilityModelProviderKindAlias('');
+ return collectUniqueRefs([defaultHead, ...refs]);
+}
+
+type LegacyMigrationPlan = {
+ models: string[];
+ markVoiceMigrationComplete: boolean;
+};
+
+function readLegacyMigrationPlan(): LegacyMigrationPlan | null {
+ const file = settingsFilePath();
+ const raw = readJsonObject(file);
+
+ if (raw && Array.isArray(raw.models)) return null;
+
+ const fromOldPins = raw
+ ? collectUniqueRefs([
+ normalizeAuxiliaryModelRef(raw.sessionTitleModel),
+ normalizeAuxiliaryModelRef(raw.promptRecommendationModel),
+ ])
+ : [];
+
+ const legacyVoiceMigrationCompleted = hasLegacyVoiceMigrationMarker();
+ const ownerVoice = legacyVoiceMigrationCompleted
+ ? []
+ : legacyVoiceOverrideRefs(readJsonObject(ownerVoiceModelsPath()));
+ const unscopedVoice =
+ ownerVoice.length > 0 || legacyVoiceMigrationCompleted
+ ? []
+ : legacyVoiceOverrideRefs(readClaimedUnscopedVoiceModels());
+ const fromVoice = (ownerVoice.length > 0 ? ownerVoice : unscopedVoice).slice(0, 3);
+
+ if (fromOldPins.length > 0) {
+ return {
+ models: fromOldPins,
+ markVoiceMigrationComplete: fromVoice.length > 0,
+ };
+ }
+
+ if (legacyVoiceMigrationCompleted) return null;
+ if (fromVoice.length > 0) {
+ return { models: fromVoice, markVoiceMigrationComplete: true };
+ }
+ if (raw && ('sessionTitleModel' in raw || 'promptRecommendationModel' in raw)) {
+ // Empty legacy pins should be cleared as well, otherwise the generic store
+ // would keep reporting those obsolete keys as a customization.
+ return { models: [], markVoiceMigrationComplete: false };
+ }
+ return null;
+}
+
+let pendingLegacyMigration: Promise<void> | null = null;
+
+function scheduleLegacyMigration(): void {
+ if (pendingLegacyMigration) return;
+ const ownerScopeKey = activeOwnerScopeKey();
+ pendingLegacyMigration = (async () => {
+ // The legacy settings file is also read by older primary builds. A
+ // passive or concurrently running instance must not rewrite its schema
+ // underneath them; the next exclusive read will retry this idempotent
+ // migration.
+ if (!hasExclusiveSharedLegacyUserDataAccess()) {
+ log.info('legacy auxiliary model migration deferred: shared userData is not exclusive');
+ return;
+ }
+ let markVoiceMigrationComplete = false;
+ await store.updateAtomic(() => {
+ // The lock serializes writers but does not prove that this process is
+ // still the only reader of the shared legacy schema. Re-check after
+ // acquiring it; an older primary may have started while we waited.
+ if (!hasExclusiveSharedLegacyUserDataAccess()) return {};
+ // Re-read under the same lock immediately before writing. A concurrent
+ // settings save wins; stale migration data is never written over it.
+ const currentPlan = readLegacyMigrationPlan();
+ if (!currentPlan) return {};
+ markVoiceMigrationComplete = currentPlan.markVoiceMigrationComplete;
+ return { models: currentPlan.models };
+ });
+ // The marker is deliberately written after the target settings file has
+ // committed. If this process exits before this point, the persisted
+ // `models` array makes the migration idempotent and retry-safe. Never
+ // write the marker into a different owner after a session switch.
+ if (markVoiceMigrationComplete && activeOwnerScopeKey() === ownerScopeKey) {
+ markLegacyVoiceMigrationComplete();
+ }
+ })()
+ .catch((error) => {
+ log.warn('legacy auxiliary model migration failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ })
+ .finally(() => {
+ pendingLegacyMigration = null;
+ });
+}
+
+/**
+ * One-shot on-disk migration:
+ * - old dual pins (title + recommendation) collapse into `models`, title first
+ * - if auxiliary was never customized, a customized voice/utility chain moves in
+ * - both customized → auxiliary wins; the legacy voice file is left untouched
+ * so older clients and passive instances can continue reading it
+ */
+export function migrateLegacyAuxiliaryModelSettings(): void {
+ if (readLegacyMigrationPlan()) scheduleLegacyMigration();
+}
+
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>;
+ if (Array.isArray(input.models)) {
+ return { models: normalizeAuxiliaryModelList(input.models) };
+ }
return {
- sessionTitleModel: normalizeAuxiliaryModelPin(input.sessionTitleModel),
- promptRecommendationModel: normalizeAuxiliaryModelPin(input.promptRecommendationModel),
+ models: collectUniqueRefs([
+ normalizeAuxiliaryModelRef(input.sessionTitleModel),
+ normalizeAuxiliaryModelRef(input.promptRecommendationModel),
+ ]),
};
}
@@ -46,45 +405,95 @@ const store = createOverrideSettingsFile<AuxiliaryModelSettings>({
label: 'auxiliary model',
scopeKey: activeOwnerScopeKey,
maxBytes: 4 * 1024,
+ mergeOverrides: ({ patch, next, defaults, overrides }) => {
+ const nextOverrides = { ...overrides };
+ for (const key of Object.keys(patch) as Array<keyof AuxiliaryModelSettings>) {
+ const normalizedValue = next[key];
+ if (JSON.stringify(normalizedValue) === JSON.stringify(defaults[key])) {
+ delete nextOverrides[String(key)];
+ } else {
+ nextOverrides[String(key)] = normalizedValue;
+ }
+ }
+ if ('models' in patch) {
+ delete nextOverrides.sessionTitleModel;
+ delete nextOverrides.promptRecommendationModel;
+ }
+ return nextOverrides;
+ },
});
-export interface AuxiliaryModelSelection extends CatalogModelPinRoute {
- pin: string;
+function load(): OverrideSettingsState<AuxiliaryModelSettings> {
+ store.invalidateIfChanged();
+ const state = store.readState();
+ const plan = readLegacyMigrationPlan();
+ if (!plan) return state;
+ scheduleLegacyMigration();
+ return {
+ ...state,
+ value: { models: plan.models },
+ isCustomized: plan.models.length > 0,
+ customizedKeys: plan.models.length > 0 ? ['models'] : [],
+ };
}
/** Hot-path read; an external config edit becomes visible without restarting. */
export function readAuxiliaryModelSettings(): AuxiliaryModelSettings {
- store.invalidateIfChanged();
- return store.read();
+ return load().value;
}
export function readAuxiliaryModelSettingsState(): OverrideSettingsState<AuxiliaryModelSettings> {
- store.invalidateIfChanged();
- return store.readState();
+ return load();
}
-/** 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;
+export function isAuxiliaryModelCustomized(): boolean {
+ return readAuxiliaryModelSettings().models.length > 0;
}
-/** Owner-scoped atomic write; null removes the corresponding override key. */
+/** Owner-scoped atomic write; empty `models` removes the override file. */
export async function writeAuxiliaryModelSettingsPatch(
patch: AuxiliaryModelSettingsPatch,
): Promise<void> {
- await store.writePatchAtomic(patch);
+ if (patch.models?.length === 0) {
+ await store.updateAtomic(() => {
+ // A reset can race with the first legacy migration. Seal the legacy
+ // voice import while holding the same lock so it cannot resurrect the
+ // chain after this empty patch removes the new override.
+ const legacyVoice =
+ hasLegacyVoiceMigrationMarker() ||
+ legacyVoiceOverrideRefs(readJsonObject(ownerVoiceModelsPath())).length > 0 ||
+ legacyVoiceOverrideRefs(readClaimedUnscopedVoiceModels()).length > 0;
+ if (legacyVoice) markLegacyVoiceMigrationComplete();
+ return patch;
+ });
+ } else {
+ await store.writePatchAtomic(patch);
+ }
log.info('auxiliary model settings written', {
customizedKeys: store.readState().customizedKeys,
+ models: store.read().models.length,
});
}
export async function resetAuxiliaryModelSettings(): Promise<AuxiliaryModelSettings> {
- return store.resetAtomic();
+ return store.updateAtomic(() => {
+ // Keep this decision under the same settings lock as reset. Otherwise a
+ // pending migration could reacquire the lock after reset and resurrect the
+ // legacy voice chain that the user just cleared.
+ const legacyVoice =
+ hasLegacyVoiceMigrationMarker() ||
+ legacyVoiceOverrideRefs(readJsonObject(ownerVoiceModelsPath())).length > 0 ||
+ legacyVoiceOverrideRefs(readClaimedUnscopedVoiceModels()).length > 0;
+ if (legacyVoice) markLegacyVoiceMigrationComplete();
+ return { models: [] };
+ });
}
-export const __testing = { normalize };
+export const __testing = {
+ normalize,
+ migrateLegacyAuxiliaryModelSettings,
+ legacyVoiceOverrideRefs,
+ flushLegacyMigration: async () => {
+ await pendingLegacyMigration;
+ },
+};
diff --git a/apps/desktop/src/main/utility-model/oneShotCandidates.ts b/apps/desktop/src/main/utility-model/oneShotCandidates.ts
index 0d8acd5a86..7537662d86 100644
--- a/apps/desktop/src/main/utility-model/oneShotCandidates.ts
+++ b/apps/desktop/src/main/utility-model/oneShotCandidates.ts
@@ -9,6 +9,7 @@ import {
import { createLogger } from '../logger.js';
import { getAppCapabilities } from '../appCapabilities.js';
+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';
import { readClaudeApiKey } from '../maker-host/auth-adapters.js';
import { getChatgptBridgeAuth } from '../maker-host/anthropic-responses-bridge-host.js';
import { getValidClaudeAiOAuth } from '../maker-host/claude-oauth-refresh.js';
@@ -26,7 +27,10 @@ import { isModelDisabled, isProviderDisabled } from '@cindy/model-providers';
import { isProviderRouteMutationInProgress } from '../maker-host/provider-route.js';
import { effectiveXdGatewayBaseUrl } from '../model-access/effectiveEndpoint.js';
import { readCustomProviderKey } from '../secrets/providerSecretStore.js';
+import { MANAGED_OLLAMA_PROVIDER_ID } from '../../shared/localModelRuntime.js';
+import { parseAuxiliaryModelRef, type ParsedAuxiliaryModelRef } from '../../shared/auxiliaryModelChain.js';
import { getUtilityModelChainProfiles } from './UtilityModelSelection.js';
+import { getEffectiveAuxiliaryModelChain } from './resolveAuxiliaryModelChain.js';
import { getUtilityModelProfile, isUtilityModelProviderKind } from '../../shared/utilityModelProfiles.js';
import type { UtilityModelProfile, UtilityModelTransport } from '../../shared/utilityModelProfiles.js';
import type {
@@ -227,10 +231,9 @@ async function resolveUtilityTextCandidates(
): Promise<{ candidates: UtilityTextCandidate[]; attempts: UtilityTextAttempt[] }> {
// 钉住某一档时只拿那一个候选:钉了还沿链回落,等于用户的选择被悄悄换掉。
// 注意不能从链里筛——默认链只有 4 档,而可钉的档位有 9 个,链外的钉不上。
- const pinned =
- pinnedProfileId && isUtilityModelProviderKind(pinnedProfileId)
- ? getUtilityModelProfile(pinnedProfileId)
- : null;
+ const pinned = pinnedProfileId && isUtilityModelProviderKind(pinnedProfileId)
+ ? getUtilityModelProfile(pinnedProfileId)
+ : null;
if (pinnedProfileId && !pinned) {
log.warn('utility text pinned profile unknown, falling back to chain', { pinnedProfileId });
}
@@ -520,36 +523,75 @@ function inferUniqueProviderId(agentKind: AgentKind | undefined, model: string |
return matches.length === 1 ? matches[0]?.id : undefined;
}
-async function requestDefaultUtilityText(
- maker: Maker,
- prompt: string,
- opts?: UtilityTextRequestOptions & { capability?: UtilityTextCapability },
-): Promise<UtilityTextResult> {
- const { candidates, attempts } = await resolveUtilityTextCandidates(
- maker,
- opts?.capability ?? { transports: ['codex-responses', 'litellm-chat-completions'] },
- opts?.pinnedProfileId,
- );
- if (candidates.length === 0) {
- return { ok: false, reason: 'no_candidate', attempts };
+function auxiliaryRefDispatchRoute(parsed: ParsedAuxiliaryModelRef): UtilityTextDispatchRoute {
+ if (parsed.kind === 'catalog') {
+ return {
+ providerId: parsed.route.providerId,
+ agentKind: parsed.route.agentKind,
+ model: parsed.route.model,
+ };
}
+ const profile = getUtilityModelProfile(parsed.id);
+ return {
+ providerId: profile.transport === 'codex-responses' ? 'openai' : 'xd',
+ agentKind: 'codex',
+ model: profile.model,
+ };
+}
+async function runDefaultProfileCandidates(
+ prompt: string,
+ candidates: UtilityTextCandidate[],
+ attempts: UtilityTextAttempt[],
+ opts?: UtilityTextRequestOptions,
+): Promise<UtilityTextResult | null> {
for (const candidate of candidates) {
- // 逐候选执行前按**当前** override 重查(PR #744 review 第二十一轮):前一个
- // 候选失败/超时可能耗时数十秒,期间本候选可能已被停用 —— 不再对其付费下单,
- // 记 model_unavailable 落到下一候选。
- if (isUtilityRouteDisabled(candidate.profile)) {
- attempts.push(skippedAttempt(candidate.profile, 'model_unavailable'));
- continue;
- }
- // 前一个 fallback 候选可能运行数十秒;在每个 XD 候选真正执行前重读
- // owner-scoped v5 deny,避免订阅状态/模型目录刚变化后继续向网关下单。
- if (isUtilityRoutePaymentRequired(candidate.profile)) {
- attempts.push(skippedAttempt(candidate.profile, 'model_unavailable'));
- continue;
- }
+ // 逐候选执行前按**当前** override 重查(PR #744 review 第二十一轮):前一个
+ // 候选失败/超时可能耗时数十秒,期间本候选可能已被停用 —— 不再对其付费下单,
+ // 记 model_unavailable 落到下一候选。
+ if (isUtilityRouteDisabled(candidate.profile)) {
+ attempts.push(skippedAttempt(candidate.profile, 'model_unavailable'));
+ continue;
+ }
+ // 前一个 fallback 候选可能运行数十秒;在每个 XD 候选真正执行前重读
+ // owner-scoped v5 deny,避免订阅状态/模型目录刚变化后继续向网关下单。
+ if (isUtilityRoutePaymentRequired(candidate.profile)) {
+ attempts.push(skippedAttempt(candidate.profile, 'model_unavailable'));
+ continue;
+ }
+ // Profile candidates may spend time awaiting credential discovery before
+ // they reach this loop (for example maker.getAgentAuthState for Codex).
+ // Re-check the owning workflow immediately before invoking the candidate;
+ // otherwise a profile route can bypass the catalog HTTP path's final
+ // beforeDispatch fence and send the old owner's prompt after a switch.
+ if (
+ opts?.beforeDispatch
+ && !(await opts.beforeDispatch({
+ providerId: utilityRouteProviderIdFor(candidate.profile.transport, candidate.providerId),
+ agentKind: 'codex',
+ model: candidate.model,
+ }))
+ ) {
+ log.warn('utility text profile candidate aborted before dispatch', {
+ providerId: candidate.providerId,
+ model: candidate.model,
+ });
+ return null;
+ }
+ // The first guard above only covers the time spent resolving the candidate.
+ // Codex candidates can still await host startup inside `oneShot`, so pass a
+ // second guard through to the actual dispatch and re-read the profile's
+ // live disable state after any caller-owned async checks.
+ const candidateOpts: UtilityTextRequestOptions = {
+ ...(opts ?? {}),
+ beforeDispatch: async (route) => {
+ if (isUtilityRouteDisabled(candidate.profile)) return false;
+ if (opts?.beforeDispatch && !(await opts.beforeDispatch(route))) return false;
+ return !isUtilityRouteDisabled(candidate.profile);
+ },
+ };
try {
- const text = (await candidate.execute(prompt, opts)).trim();
+ const text = (await candidate.execute(prompt, candidateOpts)).trim();
if (!text) throw new UtilityTextExecutionError({ reason: 'empty_response' });
return {
ok: true,
@@ -570,11 +612,111 @@ async function requestDefaultUtilityText(
});
}
}
- const reason = aggregateFailureReason(attempts.filter((attempt) => attempt.status === 'failed'));
+ return null;
+}
+
+function failedChainResult(attempts: UtilityTextAttempt[]): UtilityTextResult {
+ const failed = attempts.filter((attempt) => attempt.status === 'failed');
+ const reason = failed.length > 0
+ ? aggregateFailureReason(failed)
+ : attempts.length > 0
+ ? 'no_candidate'
+ : 'all_candidates_failed';
log.warn('all utility text candidates failed', { reason, attempts: attempts.length });
return { ok: false, reason, attempts };
}
+async function requestDefaultUtilityText(
+ maker: Maker,
+ prompt: string,
+ opts?: UtilityTextRequestOptions & { capability?: UtilityTextCapability },
+): Promise<UtilityTextResult> {
+ // Default-chain resolution and credential discovery can both await. Capture
+ // the owner before either starts so callers that do not provide their own
+ // workflow guard still fail closed instead of dispatching into a new owner.
+ const ownerScopeKey = activeOwnerScopeKey();
+ // A fallback chain is a user-selected routing decision. If it changes while
+ // an earlier candidate is awaiting credentials or failing, do not dispatch a
+ // later candidate from the stale snapshot into the new configuration.
+ const initialChain = opts?.pinnedProfileId
+ ? null
+ : getEffectiveAuxiliaryModelChain();
+ const chainSnapshot = initialChain ? stableSnapshot(initialChain) : null;
+ const callerBeforeDispatch = opts?.beforeDispatch;
+ const requestSnapshotStillCurrent = (): boolean => {
+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== ownerScopeKey) return false;
+ return chainSnapshot === null
+ || stableSnapshot(getEffectiveAuxiliaryModelChain()) === chainSnapshot;
+ };
+ const requestOpts: UtilityTextRequestOptions & { capability?: UtilityTextCapability } = {
+ ...opts,
+ beforeDispatch: async (route) => {
+ if (!requestSnapshotStillCurrent()) return false;
+ if (callerBeforeDispatch && !(await callerBeforeDispatch(route))) return false;
+ // The caller guard may await account/database state. Re-check the
+ // captured owner, session boundary, and chain after that await so a
+ // concurrent account switch cannot turn a true result into permission
+ // to dispatch the old owner's prompt.
+ return requestSnapshotStillCurrent();
+ },
+ // Short auxiliary budgets cannot afford provider-default thinking. Callers
+ // that need reasoning must pass disableReasoning: false.
+ disableReasoning: opts?.disableReasoning ?? true,
+ };
+ const capability = opts?.capability ?? {
+ transports: ['codex-responses', 'litellm-chat-completions'],
+ };
+
+ if (opts?.pinnedProfileId) {
+ const { candidates, attempts } = await resolveUtilityTextCandidates(
+ maker,
+ capability,
+ opts.pinnedProfileId,
+ );
+ if (candidates.length === 0) {
+ return { ok: false, reason: 'no_candidate', attempts };
+ }
+ const success = await runDefaultProfileCandidates(prompt, candidates, attempts, requestOpts);
+ return success ?? failedChainResult(attempts);
+ }
+
+ const chain = initialChain!;
+ const attempts: UtilityTextAttempt[] = [];
+ for (const ref of chain.refs) {
+ const parsed = parseAuxiliaryModelRef(ref);
+ if (!parsed) continue;
+ if (
+ requestOpts.beforeDispatch
+ && !(await requestOpts.beforeDispatch(auxiliaryRefDispatchRoute(parsed)))
+ ) {
+ log.warn('utility text chain aborted before dispatch', { ref, source: chain.source });
+ return failedChainResult(attempts);
+ }
+ if (parsed.kind === 'profile') {
+ const resolved = await resolveUtilityTextCandidates(maker, capability, parsed.id);
+ attempts.push(...resolved.attempts);
+ if (resolved.candidates.length === 0) continue;
+ const success = await runDefaultProfileCandidates(
+ prompt,
+ resolved.candidates,
+ attempts,
+ requestOpts,
+ );
+ if (success) return success;
+ continue;
+ }
+ const result = await requestExplicitProviderText(prompt, {
+ ...requestOpts,
+ providerId: parsed.route.providerId,
+ agentKind: parsed.route.agentKind,
+ model: parsed.route.model,
+ });
+ if (result.ok) return result;
+ attempts.push(...result.attempts);
+ }
+ return failedChainResult(attempts);
+}
+
function stableSnapshot(value: unknown): string {
const normalize = (entry: unknown): unknown => {
if (Array.isArray(entry)) return entry.map(normalize);
@@ -680,6 +822,7 @@ async function requestExplicitProviderText(
const routeStillCurrent = (): boolean => {
if (isProviderRouteMutationInProgress(provider.id)) return false;
if (isProviderModelRouteDisabled(provider.id, model)) return false;
+ if (provider.id === 'xd' && isXdGatewayPaymentRequiredRoute(model, agentKind)) 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);
@@ -789,6 +932,7 @@ async function requestExplicitProviderText(
settingsTab: 'providers',
missingCredentialMessage: 'API key is required for the selected provider.',
};
+ const isOllama = isOllamaProviderRoute(provider.id, routing.upstream);
const candidate: UtilityTextCandidate = {
providerId: provider.id,
model,
@@ -799,6 +943,7 @@ async function requestExplicitProviderText(
baseUrl: routing.upstream,
requestPath: routing.requestPath,
wireProtocol: routing.wireProtocol,
+ isOllama,
headers: routing.headerOverride,
credential: credential ?? '',
authStrategy,
@@ -839,6 +984,14 @@ function inferProviderAgent(provider: ReturnType<typeof getActiveCatalog>['provi
return undefined;
}
+function isOllamaProviderRoute(providerId: string, upstream: string): boolean {
+ const normalizedId = providerId.trim().toLowerCase();
+ return providerId === MANAGED_OLLAMA_PROVIDER_ID
+ || normalizedId === 'ollama'
+ || normalizedId.includes('ollama')
+ || /(?:127\.0\.0\.1|localhost):11434(?:\/|$)/i.test(upstream);
+}
+
/** Matches the xAI bridge capability gate: coding/build variants reject `reasoning`. */
function supportsXaiReasoning(model: string): boolean {
const normalized = model.replace(/^xai\//, '');
@@ -899,6 +1052,12 @@ async function requestBuiltinProviderText(
if (routing.disabled) {
return { ok: false, reason: 'no_candidate', attempts: [skippedAttempt(profile, 'endpoint_missing')] };
}
+ // XD catalog entries can lose entitlement after they are selected. Recheck
+ // the owner-scoped payment snapshot before resolving credentials or creating
+ // an HTTP candidate, matching the profile-chain guard above.
+ if (input.provider.id === 'xd' && isXdGatewayPaymentRequiredRoute(input.model, input.agentKind)) {
+ return { ok: false, reason: 'no_candidate', attempts: [skippedAttempt(profile, 'model_unavailable')] };
+ }
// 插件显式传了 maxTokens 时,钳到该模型目录声明的输出上限(maxOutput),
// 避免发送超过模型能力的值被 provider 拒绝。缺省(未传)不钳,走模型自然输出。
@@ -1184,6 +1343,16 @@ async function resolveCodexCandidate(
model: profile.model,
maxTokens: opts?.maxTokens,
timeoutMs: opts?.timeoutMs,
+ signal: opts?.signal,
+ systemPrompt: opts?.systemPrompt,
+ responseInstructions: opts?.responseInstructions,
+ beforeDispatch: opts?.beforeDispatch
+ ? () => opts.beforeDispatch!({
+ providerId: utilityProfileRouteProviderId(profile),
+ agentKind,
+ model: profile.model,
+ })
+ : undefined,
}),
},
};
@@ -1214,7 +1383,17 @@ function resolveLiteLlmCandidate(profile: UtilityModelProfile): UtilityTextCandi
maxTokens: opts?.maxTokens,
timeoutMs: opts?.timeoutMs,
reasoningEffort: opts?.reasoningEffort,
+ disableReasoning: opts?.disableReasoning,
signal: opts?.signal,
+ systemPrompt: opts?.systemPrompt,
+ responseInstructions: opts?.responseInstructions,
+ beforeDispatch: opts?.beforeDispatch
+ ? () => opts.beforeDispatch!({
+ providerId: utilityProfileRouteProviderId(profile),
+ agentKind: 'codex',
+ model: profile.model,
+ })
+ : undefined,
routeStillAllowed: () => !isUtilityRoutePaymentRequired(profile),
}),
},
@@ -1229,7 +1408,12 @@ async function requestLiteLlmText(input: {
maxTokens?: number;
timeoutMs?: number;
reasoningEffort?: 'minimal' | 'low' | 'medium' | 'high';
+ disableReasoning?: boolean;
signal?: AbortSignal;
+ systemPrompt?: string;
+ responseInstructions?: string;
+ /** Async final dispatch fence, including owner/settings checks. */
+ beforeDispatch?: () => Promise<boolean>;
/** Synchronous owner entitlement fence immediately before the HTTP request. */
routeStillAllowed?: () => boolean;
}): Promise<string> {
@@ -1240,9 +1424,15 @@ async function requestLiteLlmText(input: {
else input.signal?.addEventListener('abort', abortFromParent, { once: true });
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
+ if (input.beforeDispatch && !(await input.beforeDispatch())) {
+ throw new UtilityTextExecutionError({ reason: 'request_failed' });
+ }
if (input.routeStillAllowed && !input.routeStillAllowed()) {
throw new UtilityTextExecutionError({ reason: 'request_failed' });
}
+ const instructions = [input.systemPrompt, input.responseInstructions]
+ .filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
+ .join('\n');
const response = await undiciFetch(joinProxyPath(input.baseUrl, '/v1/chat/completions'), {
method: 'POST',
signal: controller.signal,
@@ -1253,8 +1443,20 @@ async function requestLiteLlmText(input: {
body: JSON.stringify({
model: input.model,
...(input.maxTokens !== undefined ? { max_tokens: input.maxTokens } : {}),
- ...(input.reasoningEffort ? { reasoning_effort: input.reasoningEffort } : {}),
- messages: [{ role: 'user', content: input.prompt }],
+ ...(input.disableReasoning
+ ? { thinking: { type: 'disabled' } }
+ : input.reasoningEffort
+ ? { reasoning_effort: input.reasoningEffort }
+ : {}),
+ messages: [
+ ...(instructions
+ ? [{
+ role: 'system',
+ content: instructions,
+ }]
+ : []),
+ { role: 'user', content: input.prompt },
+ ],
}),
});
if (!response.ok) {
@@ -1362,6 +1564,8 @@ async function requestProviderHttpText(input: {
timeoutMs?: number;
reasoningEffort?: 'minimal' | 'low' | 'medium' | 'high';
disableReasoning?: boolean;
+ /** Ollama's OpenAI-compatible chat wire uses `reasoning_effort: "none"` to disable thinking. */
+ isOllama?: boolean;
/** Some coding-specialized models reject their wire's reasoning field. */
supportsReasoning?: boolean;
/** Unknown custom routes may reject optional fields from an otherwise compatible wire. */
@@ -1391,8 +1595,11 @@ async function requestProviderHttpText(input: {
const instructions = [input.systemPrompt, input.responseInstructions]
.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
.join('\n');
+ // Responses-compatible routes do not have a reasoning "off" value. The
+ // lowest common supported effort for the subscribed GPT models is `low`;
+ // sending `minimal` to GPT-5.4 mini is rejected by ChatGPT with HTTP 400.
const reasoningEffort = input.disableReasoning
- ? 'minimal'
+ ? input.wire === 'responses' ? 'low' : 'minimal'
: input.reasoningEffort;
const supportsRequestedReasoning = Boolean(
input.wire !== 'anthropic-messages'
@@ -1403,6 +1610,9 @@ async function requestProviderHttpText(input: {
|| input.maxTokens !== undefined
|| input.disableReasoning === true
|| supportsRequestedReasoning;
+ const ollamaReasoningOff = input.wire === 'chat-completions'
+ && input.isOllama === true
+ && input.disableReasoning === true;
const buildBody = (minimal: boolean) => input.wire === 'responses'
? {
model: input.model,
@@ -1433,8 +1643,12 @@ async function requestProviderHttpText(input: {
: {
model: input.model,
...(!minimal && input.maxTokens !== undefined ? { max_tokens: input.maxTokens } : {}),
- ...(!minimal && input.disableReasoning ? { thinking: { type: 'disabled' } } : {}),
- ...(!minimal && supportsRequestedReasoning
+ ...(!minimal && input.disableReasoning
+ ? ollamaReasoningOff
+ ? { reasoning_effort: 'none' }
+ : { thinking: { type: 'disabled' } }
+ : {}),
+ ...(!minimal && supportsRequestedReasoning && !ollamaReasoningOff
? { reasoning_effort: reasoningEffort }
: {}),
messages: [
@@ -1570,6 +1784,7 @@ function chatCompletionEmptyFingerprint(parsed: unknown): Record<string, unknown
.map((part) => (typeof part === 'object' && part !== null ? (part as { type?: unknown }).type : typeof part))
: undefined,
hasReasoningContent: typeof message.reasoning_content === 'string' && message.reasoning_content.length > 0,
+ hasReasoning: typeof message.reasoning === 'string' && message.reasoning.length > 0,
finishReason: first?.finish_reason,
messageKeys: Object.keys(message).slice(0, 8),
};
@@ -1581,6 +1796,7 @@ async function requestCustomProviderText(input: {
baseUrl: string;
requestPath?: string;
wireProtocol?: 'anthropic-messages' | 'openai-responses' | 'openai-chat';
+ isOllama?: boolean;
headers?: Record<string, string>;
credential: string;
authStrategy: 'api-key-header' | 'oauth-token' | 'none';
@@ -1642,6 +1858,7 @@ async function requestCustomProviderText(input: {
timeoutMs: input.timeoutMs,
reasoningEffort: input.reasoningEffort,
disableReasoning: input.disableReasoning,
+ isOllama: input.isOllama,
retryWithMinimalBodyOnInvalidRequest: true,
signal: input.signal,
systemPrompt: input.systemPrompt,
diff --git a/apps/desktop/src/main/utility-model/resolveAuxiliaryModelChain.ts b/apps/desktop/src/main/utility-model/resolveAuxiliaryModelChain.ts
new file mode 100644
index 0000000000..acda1e2ab1
--- /dev/null
+++ b/apps/desktop/src/main/utility-model/resolveAuxiliaryModelChain.ts
@@ -0,0 +1,156 @@
+/**
+ * Resolve the runtime auxiliary-model chain.
+ *
+ * Priority: user custom 1–3 (exhaust, no fallback) → env escape hatch → frozen
+ * automatic chain. Never sorts by live catalog price.
+ */
+
+import {
+ AUTO_AUXILIARY_MODEL_CHAIN,
+ parseAuxiliaryModelRef,
+ type ParsedAuxiliaryModelRef,
+} from '../../shared/auxiliaryModelChain.js';
+import { encodeCatalogModelPin } from '../../shared/catalogModelPin.js';
+import {
+ DEFAULT_UTILITY_MODEL_PROVIDER_KIND,
+ getUtilityModelProfile,
+ resolveUtilityModelProviderKindAlias,
+ utilityTransportLabel,
+} from '../../shared/utilityModelProfiles.js';
+import { isAuxiliaryModelCustomized, readAuxiliaryModelSettings } from './auxiliary-model-settings-store.js';
+
+export type AuxiliaryModelChainSource = 'custom' | 'auto' | 'env';
+
+export type EffectiveAuxiliaryModelChain = {
+ source: AuxiliaryModelChainSource;
+ refs: string[];
+};
+
+function firstNonBlank(...values: Array<string | undefined>): string | undefined {
+ return values.find((value) => typeof value === 'string' && value.trim().length > 0)?.trim();
+}
+
+function resolveEnvHeadRef(providerRaw: string | undefined, modelRaw: string | undefined): string | null {
+ // Preserve the exact model identity when migrating a legacy provider/model
+ // override. The resulting catalog pin remains subject to active-catalog
+ // membership at dispatch; unknown models fail closed instead of becoming an
+ // unlisted profile override. Do not introduce a second persisted ref format.
+ const provider = resolveUtilityModelProviderKindAlias(providerRaw ?? '')
+ ?? resolveUtilityModelProviderKindAlias('');
+ if (!provider) return null;
+ const profile = getUtilityModelProfile(provider);
+ const model = modelRaw?.trim();
+ if (!model || model === profile.model) return provider;
+ const modelAlias = resolveUtilityModelProviderKindAlias(model);
+ if (
+ modelAlias
+ && getUtilityModelProfile(modelAlias).transport === profile.transport
+ ) {
+ return modelAlias;
+ }
+ return encodeCatalogModelPin({
+ providerId: profile.transport === 'codex-responses' ? 'openai' : 'xd',
+ agentKind: 'codex',
+ model,
+ });
+}
+
+function readEnvUtilityChain(): string[] | null {
+ // Keep both generations of the escape hatch alive. Utility names take
+ // precedence when both are set, matching the legacy utility selection.
+ const chainRaw = firstNonBlank(
+ process.env.XDT_UTILITY_MODEL_PROVIDER_CHAIN,
+ process.env.XDT_VOICE_INPUT_REFINER_PROVIDER_CHAIN,
+ );
+ const headRaw = firstNonBlank(
+ process.env.XDT_UTILITY_MODEL_PROVIDER,
+ process.env.XDT_VOICE_INPUT_REFINER_PROVIDER,
+ );
+ const modelRaw = firstNonBlank(
+ process.env.XDT_UTILITY_MODEL,
+ process.env.XDT_VOICE_INPUT_REFINER_MODEL,
+ );
+ const entries: string[] = [];
+ if (typeof chainRaw === 'string' && chainRaw.trim()) {
+ for (const part of chainRaw.split(',')) {
+ const resolved = resolveUtilityModelProviderKindAlias(part.trim());
+ if (resolved && !entries.includes(resolved)) entries.push(resolved);
+ }
+ }
+ const hasHeadOrModelOverride = Boolean(headRaw || modelRaw);
+ if (hasHeadOrModelOverride) {
+ const headRef = resolveEnvHeadRef(headRaw, modelRaw);
+ if (headRef) {
+ const headProvider = resolveUtilityModelProviderKindAlias(headRaw ?? '')
+ ?? resolveUtilityModelProviderKindAlias('');
+ const rest = entries.filter((entry) => entry !== headProvider && entry !== headRef);
+ return [headRef, ...rest];
+ }
+ }
+ if (entries.length > 0) {
+ // `UtilityModelSelection` has always treated a provider-chain-only
+ // configuration as a fallback tail behind the implicit default provider.
+ // Keep that legacy ordering when migrating the escape hatch into the
+ // shared auxiliary chain; otherwise the first configured fallback would
+ // silently become the primary route.
+ return [
+ DEFAULT_UTILITY_MODEL_PROVIDER_KIND,
+ ...entries.filter((entry) => entry !== DEFAULT_UTILITY_MODEL_PROVIDER_KIND),
+ ];
+ }
+ return null;
+}
+
+export function getEffectiveAuxiliaryModelChain(): EffectiveAuxiliaryModelChain {
+ const custom = readAuxiliaryModelSettings().models;
+ if (custom.length > 0) {
+ return { source: 'custom', refs: [...custom] };
+ }
+ const envChain = readEnvUtilityChain();
+ if (envChain) {
+ return { source: 'env', refs: envChain };
+ }
+ return { source: 'auto', refs: [...AUTO_AUXILIARY_MODEL_CHAIN] };
+}
+
+/**
+ * Stable request-time identity for the effective auxiliary chain.
+ * Async callers capture this before resolving credentials or readiness, then
+ * fail closed if the user changes the routing decision while work is in flight.
+ */
+export function getEffectiveAuxiliaryModelChainSnapshot(): string {
+ const chain = getEffectiveAuxiliaryModelChain();
+ return JSON.stringify({ source: chain.source, refs: chain.refs });
+}
+
+export function getEffectiveAuxiliaryModelRefs(): string[] {
+ return getEffectiveAuxiliaryModelChain().refs;
+}
+
+export { isAuxiliaryModelCustomized };
+
+export function formatAuxiliaryModelRefLabel(ref: string): string {
+ const parsed = parseAuxiliaryModelRef(ref);
+ if (!parsed) return ref;
+ if (parsed.kind === 'profile') {
+ const profile = getUtilityModelProfile(parsed.id);
+ return `${profile.model} · ${utilityTransportLabel(profile.transport)}`;
+ }
+ if (parsed.route.providerId === 'xd') {
+ return `${parsed.route.model} · Cindy AI`;
+ }
+ const agent = parsed.route.agentKind === 'claude-code' ? 'Claude' : 'Codex';
+ const provider = parsed.route.providerId === 'anthropic' || parsed.route.providerId === 'openai'
+ ? agent
+ : parsed.route.providerId;
+ return `${parsed.route.model} · ${provider}`;
+}
+
+export function parsedAuxiliaryModelRefs(refs: readonly string[]): ParsedAuxiliaryModelRef[] {
+ const parsed: ParsedAuxiliaryModelRef[] = [];
+ for (const ref of refs) {
+ const item = parseAuxiliaryModelRef(ref);
+ if (item) parsed.push(item);
+ }
+ return parsed;
+}
diff --git a/apps/desktop/src/main/utility-model/textOneshotPinOptions.ts b/apps/desktop/src/main/utility-model/textOneshotPinOptions.ts
index fa25e46221..1ed521c610 100644
--- a/apps/desktop/src/main/utility-model/textOneshotPinOptions.ts
+++ b/apps/desktop/src/main/utility-model/textOneshotPinOptions.ts
@@ -167,6 +167,11 @@ function displayOrderedModels(models: readonly CatalogModel[]): CatalogModel[] {
);
}
+/** Product-facing provider name for the picker; keep the catalog id stable. */
+function displayProviderName(provider: Provider): string {
+ return provider.id === 'xd' ? 'Cindy AI' : provider.name;
+}
+
/**
* 凭证探测(可选):传入时只收当下有可用凭证的 (供应商 × agent)——没配
* key / 没登录的供应商钉上也只会在执行期 NO_CANDIDATE,不给了没用的选项。
@@ -205,11 +210,12 @@ export function buildTextOneshotPinOptions(
}
}
return entries.map((e) => {
- const base = `${e.model.name} · ${e.provider.name}`;
+ const providerName = displayProviderName(e.provider);
+ const base = `${e.model.name} · ${providerName}`;
return {
id: encodeCatalogPin(e.provider.id, e.agentKind, e.model.id),
label: `${AGENT_LABEL[e.agentKind]} · ${base}`,
- group: e.provider.name,
+ group: providerName,
providerId: e.provider.id,
agentKind: e.agentKind,
modelId: e.model.id,
diff --git a/apps/desktop/src/main/voice-input/CodexResponsesTextModelClient.ts b/apps/desktop/src/main/voice-input/CodexResponsesTextModelClient.ts
index 9bf7a966d9..23ed9aa645 100644
--- a/apps/desktop/src/main/voice-input/CodexResponsesTextModelClient.ts
+++ b/apps/desktop/src/main/voice-input/CodexResponsesTextModelClient.ts
@@ -104,6 +104,8 @@ type CodexResponsesTextModelClientOptions = {
* "重新登录 Codex" flow.
*/
onAuthInvalidated?: (reason: string) => void;
+ /** Called after request-time awaits and immediately before each fetch. */
+ beforeDispatch?: () => void;
};
/**
@@ -124,6 +126,7 @@ export class CodexResponsesTextModelClient implements TextModelClient {
private readonly timeoutMs: number;
private readonly onUsage?: (usage: CodexTokenUsage) => void;
private readonly onAuthInvalidated?: (reason: string) => void;
+ private readonly beforeDispatch?: () => void;
private authInvalidationNotified = false;
constructor(options: CodexResponsesTextModelClientOptions) {
@@ -133,6 +136,7 @@ export class CodexResponsesTextModelClient implements TextModelClient {
this.timeoutMs = options.timeoutMs ?? 8_000;
this.onUsage = options.onUsage;
this.onAuthInvalidated = options.onAuthInvalidated;
+ this.beforeDispatch = options.beforeDispatch;
}
async requestJson<T>(input: {
@@ -212,6 +216,7 @@ export class CodexResponsesTextModelClient implements TextModelClient {
// 代理解析放在看门狗与 timing 起表之前:它是本机一次解析(带 30s 缓存),
// 不该算进 response-headers 预算,也不该污染 send 耗时。
const dispatcher = await resolveRefinerDispatcher(this.baseUrl, codexResponsesDispatcher);
+ this.beforeDispatch?.();
armIdleTimeout('response headers');
const sendStart = performance.now();
let firstByteAt: number | null = null;
diff --git a/apps/desktop/src/main/voice-input/LiteLlmTextModelClient.ts b/apps/desktop/src/main/voice-input/LiteLlmTextModelClient.ts
index 336159f98b..cc665f804f 100644
--- a/apps/desktop/src/main/voice-input/LiteLlmTextModelClient.ts
+++ b/apps/desktop/src/main/voice-input/LiteLlmTextModelClient.ts
@@ -77,6 +77,8 @@ type LiteLlmTextModelClientOptions = {
}) => Promise<{ url: string; authorization: string }>;
timeoutMs?: number;
onUsage?: (usage: LiteLlmTokenUsage) => void;
+ /** Called after request target/dispatcher awaits and immediately before fetch. */
+ beforeDispatch?: () => void;
};
type ParsedSseBlock = { data: unknown };
@@ -89,6 +91,7 @@ export class LiteLlmTextModelClient implements TextModelClient {
}) => Promise<{ url: string; authorization: string }>;
private readonly timeoutMs: number;
private readonly onUsage?: (usage: LiteLlmTokenUsage) => void;
+ private readonly beforeDispatch?: () => void;
constructor(options: LiteLlmTextModelClientOptions) {
this.proxyApiKey = options.proxyApiKey;
@@ -96,6 +99,7 @@ export class LiteLlmTextModelClient implements TextModelClient {
this.requestTargetProvider = options.requestTargetProvider;
this.timeoutMs = options.timeoutMs ?? 8_000;
this.onUsage = options.onUsage;
+ this.beforeDispatch = options.beforeDispatch;
}
async requestJson<T>(input: {
@@ -168,6 +172,7 @@ export class LiteLlmTextModelClient implements TextModelClient {
// 代理解析放在看门狗起表之前:它是本机一次解析(带 30s 缓存),不该占用
// response-headers 的等待预算。
const dispatcher = await resolveRefinerDispatcher(target.url, refinerDispatcher);
+ this.beforeDispatch?.();
armIdleTimeout('response headers');
return undiciFetch(target.url, {
method: 'POST',
diff --git a/apps/desktop/src/main/voice-input/VoiceInputModelSelection.ts b/apps/desktop/src/main/voice-input/VoiceInputModelSelection.ts
index c4db0d4468..b8232bff7b 100644
--- a/apps/desktop/src/main/voice-input/VoiceInputModelSelection.ts
+++ b/apps/desktop/src/main/voice-input/VoiceInputModelSelection.ts
@@ -19,6 +19,8 @@ import {
validateVoiceInputCustomAsrConfig,
type VoiceInputCustomAsrConfig,
} from '../../shared/voiceInputCustomAsr.js';
+import { getEffectiveAuxiliaryModelChain } from '../utility-model/resolveAuxiliaryModelChain.js';
+import { mapAuxiliaryRefsToVoiceRefiners } from './mapAuxiliaryRefsToVoiceRefiners.js';
export {
validateVoiceInputCustomAsrConfig,
@@ -261,6 +263,24 @@ function readDefaultVoiceInputModelSelectionEnv(): NodeJS.ProcessEnv {
};
}
+function overlayAuxiliaryRefinerChain(
+ selection: VoiceInputModelSelection,
+): VoiceInputModelSelection {
+ const chain = getEffectiveAuxiliaryModelChain();
+ const mapped = mapAuxiliaryRefsToVoiceRefiners(chain.refs);
+ return {
+ ...selection,
+ refinerProvider: mapped[0] ?? DEFAULT_VOICE_INPUT_REFINER_PROVIDER_KIND,
+ // The legacy voice-input file may still contain a custom `refinerModel`.
+ // Once the shared auxiliary chain is active, every model (including exact
+ // catalog pins) comes from that chain; retaining this field would let the
+ // old model override the new chain head in resolveVoiceInputRefinerChainProfiles.
+ refinerModel: undefined,
+ refinerProviderChain: mapped,
+ refinerProviderChainSource: chain.source === 'custom' ? 'configured' : 'default',
+ };
+}
+
export function getVoiceInputModelSelection(): VoiceInputModelSelection {
ensureVoiceInputModelSelectionFile();
const configPath = getVoiceInputModelSelectionConfigPath();
@@ -268,7 +288,7 @@ export function getVoiceInputModelSelection(): VoiceInputModelSelection {
if (!cachedConfig || cachedConfig.configPath !== configPath || cachedMtimeMs !== mtimeMs) {
cachedConfig = loadVoiceInputModelSelection(configPath, mtimeMs);
}
- return cachedConfig;
+ return overlayAuxiliaryRefinerChain(cachedConfig);
}
export function reloadVoiceInputModelSelection(): VoiceInputModelSelection {
diff --git a/apps/desktop/src/main/voice-input/VoiceInputRefinerRouting.ts b/apps/desktop/src/main/voice-input/VoiceInputRefinerRouting.ts
index 24918f88b4..25e5788e20 100644
--- a/apps/desktop/src/main/voice-input/VoiceInputRefinerRouting.ts
+++ b/apps/desktop/src/main/voice-input/VoiceInputRefinerRouting.ts
@@ -1,5 +1,4 @@
import {
- DEFAULT_VOICE_INPUT_REFINER_PROVIDER_KIND,
type VoiceInputRefinerProfile,
type VoiceInputRefinerProviderKind,
type VoiceInputRefinerTransport,
@@ -7,25 +6,6 @@ import {
import type { VoiceInputProviderChainSource } from './VoiceInputModelSelection.js';
import { orderVoiceInputProvidersByHealth } from './VoiceInputProviderHealth.js';
-const CODEX_GPT_MINI: VoiceInputRefinerProviderKind = 'codex-gpt-5.4-mini';
-const LITELLM_GPT_MINI: VoiceInputRefinerProviderKind = 'litellm-gpt-5.4-mini';
-const LITELLM_KIMI: VoiceInputRefinerProviderKind = 'litellm-kimi-k2.6';
-const LITELLM_DEEPSEEK: VoiceInputRefinerProviderKind = 'litellm-deepseek-v4-flash';
-
-const DEFAULT_REFINER_ORDER_WITH_CODEX: readonly VoiceInputRefinerProviderKind[] = [
- CODEX_GPT_MINI,
- LITELLM_KIMI,
- LITELLM_GPT_MINI,
- LITELLM_DEEPSEEK,
-];
-
-const DEFAULT_REFINER_ORDER_WITHOUT_CODEX: readonly VoiceInputRefinerProviderKind[] = [
- LITELLM_GPT_MINI,
- LITELLM_KIMI,
- LITELLM_DEEPSEEK,
- CODEX_GPT_MINI,
-];
-
export type VoiceInputRefinerRoutingSelection = {
refinerProvider: VoiceInputRefinerProviderKind;
refinerProviderChain: readonly VoiceInputRefinerProviderKind[];
@@ -38,46 +18,14 @@ export type VoiceInputRefinerRoutingReadiness = {
};
/**
- * Runtime policy for the built-in refiner pool:
- * - Codex ready: keep Codex first, use Kimi as the heterogeneous fallback.
- * - Codex unavailable: use LiteLLM GPT first, then Kimi.
- *
- * Explicit user/provider-chain choices keep their configured order. Cooldown is
- * applied after this policy so a recently failed provider still moves behind
- * healthy candidates.
+ * Keep the configured auxiliary-model order. Health cooldown may move a recently
+ * failed provider behind healthy candidates. Do not reorder by Codex readiness.
*/
export function orderVoiceInputRefinerChainForRuntime(
selection: VoiceInputRefinerRoutingSelection,
- readinessList: readonly VoiceInputRefinerRoutingReadiness[],
-): VoiceInputRefinerProviderKind[] {
- const configured = [...selection.refinerProviderChain];
- const policyOrdered = isBuiltInDefaultRefinerSelection(selection)
- ? orderDefaultRefinerChainByReadiness(configured, readinessList)
- : configured;
- return orderVoiceInputProvidersByHealth('refiner', policyOrdered);
-}
-
-function orderDefaultRefinerChainByReadiness(
- configured: readonly VoiceInputRefinerProviderKind[],
- readinessList: readonly VoiceInputRefinerRoutingReadiness[],
+ _readinessList: readonly VoiceInputRefinerRoutingReadiness[],
): VoiceInputRefinerProviderKind[] {
- const codexReady = readinessList.some((readiness) =>
- readiness.provider === CODEX_GPT_MINI && readiness.ok,
- );
- const preferred = codexReady
- ? DEFAULT_REFINER_ORDER_WITH_CODEX
- : DEFAULT_REFINER_ORDER_WITHOUT_CODEX;
- const configuredSet = new Set(configured);
- const ordered = preferred.filter((provider) => configuredSet.has(provider));
- for (const provider of configured) {
- if (!ordered.includes(provider)) ordered.push(provider);
- }
- return ordered;
-}
-
-function isBuiltInDefaultRefinerSelection(selection: VoiceInputRefinerRoutingSelection): boolean {
- if (selection.refinerProvider !== DEFAULT_VOICE_INPUT_REFINER_PROVIDER_KIND) return false;
- return selection.refinerProviderChainSource === 'default';
+ return orderVoiceInputProvidersByHealth('refiner', [...selection.refinerProviderChain]);
}
/**
diff --git a/apps/desktop/src/main/voice-input/__tests__/CodexResponsesTextModelClient.test.ts b/apps/desktop/src/main/voice-input/__tests__/CodexResponsesTextModelClient.test.ts
index afbd04db54..41f002f058 100644
--- a/apps/desktop/src/main/voice-input/__tests__/CodexResponsesTextModelClient.test.ts
+++ b/apps/desktop/src/main/voice-input/__tests__/CodexResponsesTextModelClient.test.ts
@@ -208,6 +208,27 @@ describe('CodexResponsesTextModelClient', () => {
expect(undiciFetchMock).not.toHaveBeenCalled();
});
+ it('runs the final dispatch guard after request awaits and can fail closed on owner drift', async () => {
+ let ownerScope = 'owner-a';
+ const beforeDispatch = vi.fn(() => {
+ if (ownerScope !== 'owner-a') throw new Error('voice input owner scope changed');
+ });
+ const client = new CodexResponsesTextModelClient({
+ accessTokenProvider: async () => {
+ ownerScope = 'owner-b';
+ return 'tok';
+ },
+ accountIdProvider: async () => null,
+ beforeDispatch,
+ });
+
+ await expect(client.requestJson({
+ model: 'm', schemaName: 's', system: 'sys', user: {},
+ })).rejects.toThrow('voice input owner scope changed');
+ expect(beforeDispatch).toHaveBeenCalledOnce();
+ expect(undiciFetchMock).not.toHaveBeenCalled();
+ });
+
it('surfaces stream-level errors from response.failed events', async () => {
const onAuthInvalidated = vi.fn();
undiciFetchMock.mockResolvedValue(makeSseResponse([
diff --git a/apps/desktop/src/main/voice-input/__tests__/LiteLlmTextModelClient.test.ts b/apps/desktop/src/main/voice-input/__tests__/LiteLlmTextModelClient.test.ts
index 3ccd45710b..4a7588cbba 100644
--- a/apps/desktop/src/main/voice-input/__tests__/LiteLlmTextModelClient.test.ts
+++ b/apps/desktop/src/main/voice-input/__tests__/LiteLlmTextModelClient.test.ts
@@ -156,7 +156,8 @@ describe('LiteLlmTextModelClient', () => {
{ choices: [{ delta: { content: '{"text":"refined"}' } }] },
]));
- const client = new LiteLlmTextModelClient({ requestTargetProvider });
+ const beforeDispatch = vi.fn();
+ const client = new LiteLlmTextModelClient({ requestTargetProvider, beforeDispatch });
await expect(client.requestJson<{ text: string }>({
model: 'm',
@@ -168,6 +169,7 @@ describe('LiteLlmTextModelClient', () => {
expect(requestTargetProvider).toHaveBeenNthCalledWith(1, undefined);
expect(requestTargetProvider).toHaveBeenNthCalledWith(2, { forceRefresh: true });
expect(undiciFetchMock).toHaveBeenCalledTimes(2);
+ expect(beforeDispatch).toHaveBeenCalledTimes(2);
expect(undiciFetchMock.mock.calls[0]?.[1]).toMatchObject({
headers: expect.objectContaining({ Authorization: 'Bearer stale-token' }),
});
diff --git a/apps/desktop/src/main/voice-input/__tests__/RealtimeAsrWebSocketProvider.test.ts b/apps/desktop/src/main/voice-input/__tests__/RealtimeAsrWebSocketProvider.test.ts
index 78bd8ea687..cee7add429 100644
--- a/apps/desktop/src/main/voice-input/__tests__/RealtimeAsrWebSocketProvider.test.ts
+++ b/apps/desktop/src/main/voice-input/__tests__/RealtimeAsrWebSocketProvider.test.ts
@@ -147,6 +147,21 @@ describe('RealtimeAsrWebSocketProvider helpers', () => {
cachedTokens: 500_000,
completionTokens: 100_000,
})).toBeCloseTo(0.57, 8);
+
+ const knownCatalogProfile = getVoiceInputRefinerProfile(
+ 'cat:openai:codex:gpt-5.4-mini' as Parameters<typeof getVoiceInputRefinerProfile>[0],
+ );
+ expect(knownCatalogProfile.pricing).toEqual(defaultProfile.pricing);
+ expect(estimateVoiceInputRefinerCostUsd(knownCatalogProfile, {
+ promptTokens: 1_000_000,
+ cachedTokens: 500_000,
+ completionTokens: 100_000,
+ })).toBeCloseTo(0.57, 8);
+
+ const unknownCatalogProfile = getVoiceInputRefinerProfile(
+ 'cat:xd:codex:deepseek/deepseek-v4-flash' as Parameters<typeof getVoiceInputRefinerProfile>[0],
+ );
+ expect(unknownCatalogProfile.pricing).toBeUndefined();
});
it('uses provider-specific fallback error messages when upstream omits one', () => {
diff --git a/apps/desktop/src/main/voice-input/__tests__/VoiceInputRefinerRouting.test.ts b/apps/desktop/src/main/voice-input/__tests__/VoiceInputRefinerRouting.test.ts
index 550a81045a..e308cbf7ca 100644
--- a/apps/desktop/src/main/voice-input/__tests__/VoiceInputRefinerRouting.test.ts
+++ b/apps/desktop/src/main/voice-input/__tests__/VoiceInputRefinerRouting.test.ts
@@ -38,7 +38,7 @@ describe('VoiceInputRefinerRouting', () => {
resetVoiceInputProviderHealthForTests();
});
- it('uses Kimi as the second built-in refiner when Codex is ready', () => {
+ it('keeps configured order when Codex is ready', () => {
expect(orderVoiceInputRefinerChainForRuntime(defaultSelection, readiness([
'codex-gpt-5.4-mini',
'litellm-gpt-5.4-mini',
@@ -46,22 +46,22 @@ describe('VoiceInputRefinerRouting', () => {
'litellm-deepseek-v4-flash',
]))).toEqual([
'codex-gpt-5.4-mini',
- 'litellm-kimi-k2.6',
'litellm-gpt-5.4-mini',
+ 'litellm-kimi-k2.6',
'litellm-deepseek-v4-flash',
]);
});
- it('uses LiteLLM GPT first when Codex is unavailable', () => {
+ it('keeps configured order when Codex is unavailable', () => {
expect(orderVoiceInputRefinerChainForRuntime(defaultSelection, readiness([
'litellm-gpt-5.4-mini',
'litellm-kimi-k2.6',
'litellm-deepseek-v4-flash',
]))).toEqual([
+ 'codex-gpt-5.4-mini',
'litellm-gpt-5.4-mini',
'litellm-kimi-k2.6',
'litellm-deepseek-v4-flash',
- 'codex-gpt-5.4-mini',
]);
});
@@ -102,7 +102,7 @@ describe('VoiceInputRefinerRouting', () => {
]);
});
- it('applies cooldown after the built-in readiness policy', () => {
+ it('applies health cooldown without Codex readiness reorder', () => {
markVoiceInputProviderFailure('refiner', 'codex-gpt-5.4-mini', 'timeout');
expect(orderVoiceInputRefinerChainForRuntime(defaultSelection, readiness([
@@ -111,8 +111,8 @@ describe('VoiceInputRefinerRouting', () => {
'litellm-kimi-k2.6',
'litellm-deepseek-v4-flash',
]))).toEqual([
- 'litellm-kimi-k2.6',
'litellm-gpt-5.4-mini',
+ 'litellm-kimi-k2.6',
'litellm-deepseek-v4-flash',
'codex-gpt-5.4-mini',
]);
diff --git a/apps/desktop/src/main/voice-input/__tests__/mapAuxiliaryRefsToVoiceRefiners.test.ts b/apps/desktop/src/main/voice-input/__tests__/mapAuxiliaryRefsToVoiceRefiners.test.ts
new file mode 100644
index 0000000000..8f38a97cec
--- /dev/null
+++ b/apps/desktop/src/main/voice-input/__tests__/mapAuxiliaryRefsToVoiceRefiners.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, it, vi } from 'vitest';
+
+const activeCatalog = {
+ providers: [
+ {
+ id: 'openai',
+ source: 'builtin',
+ agents: ['codex'],
+ models: {
+ codex: [
+ { id: 'gpt-5.4-mini', name: 'GPT-5.4 mini', contextWindow: 272_000 },
+ ],
+ },
+ routing: { codex: { disabled: false } },
+ },
+ {
+ id: 'xd',
+ source: 'builtin',
+ agents: ['codex'],
+ models: {
+ codex: [
+ { id: 'deepseek/deepseek-v4-flash', name: 'DeepSeek V4 Flash', contextWindow: 272_000 },
+ { id: 'tencent/hy3', name: 'Hy3', contextWindow: 272_000 },
+ { id: 'qwen/qwen3.8-flash', name: 'Qwen3.8 Flash', contextWindow: 272_000 },
+ { id: 'disabled-model', name: 'Disabled', contextWindow: 272_000, disabled: true },
+ { id: 'paid-model', name: 'Paid', contextWindow: 272_000, availability: 'requires_payment' },
+ ],
+ },
+ routing: { codex: { disabled: false } },
+ },
+ ],
+};
+
+vi.mock('../../maker-host/active-catalog.js', () => ({
+ getActiveCatalog: () => activeCatalog,
+}));
+
+import {
+ isActiveCatalogVoiceRefinerProfile,
+ mapAuxiliaryRefToVoiceRefiner,
+ mapAuxiliaryRefsToVoiceRefiners,
+} from '../mapAuxiliaryRefsToVoiceRefiners.js';
+
+describe('mapAuxiliaryRefsToVoiceRefiners', () => {
+ it('maps profile keys 1:1 and skips Claude Messages catalog pins', () => {
+ expect(mapAuxiliaryRefToVoiceRefiner('codex-gpt-5.4-mini')).toBe('codex-gpt-5.4-mini');
+ expect(mapAuxiliaryRefToVoiceRefiner('litellm-kimi-k2.6')).toBe('litellm-kimi-k2.6');
+ expect(mapAuxiliaryRefToVoiceRefiner('cat:anthropic:claude-code:claude-haiku-4-5')).toBeNull();
+ });
+
+ it('maps OpenAI and Cindy gateway catalog pins onto matching refiner transports', () => {
+ expect(mapAuxiliaryRefToVoiceRefiner('cat:openai:codex:gpt-5.4-mini')).toBe(
+ 'cat:openai:codex:gpt-5.4-mini',
+ );
+ expect(mapAuxiliaryRefToVoiceRefiner('cat:xd:codex:deepseek/deepseek-v4-flash')).toBe(
+ 'cat:xd:codex:deepseek/deepseek-v4-flash',
+ );
+ expect(mapAuxiliaryRefToVoiceRefiner('cat:xd:codex:tencent/hy3')).toBe(
+ 'cat:xd:codex:tencent/hy3',
+ );
+ expect(mapAuxiliaryRefToVoiceRefiner('cat:xd:codex:qwen/qwen3.8-flash')).toBe(
+ 'cat:xd:codex:qwen/qwen3.8-flash',
+ );
+ });
+
+ it('skips catalog pins that are no longer active or selectable', () => {
+ expect(mapAuxiliaryRefToVoiceRefiner('cat:openai:codex:gpt-5.4-mini')).toBe(
+ 'cat:openai:codex:gpt-5.4-mini',
+ );
+ expect(mapAuxiliaryRefToVoiceRefiner('cat:xd:codex:missing-model')).toBeNull();
+ expect(mapAuxiliaryRefToVoiceRefiner('cat:xd:codex:disabled-model')).toBeNull();
+ expect(mapAuxiliaryRefToVoiceRefiner('cat:xd:codex:paid-model')).toBeNull();
+ });
+
+ it('skips catalog pins whose agent routing is disabled', () => {
+ const xdProvider = activeCatalog.providers.find((provider) => provider.id === 'xd');
+ if (!xdProvider) throw new Error('test fixture is missing the xd provider');
+ xdProvider.routing.codex.disabled = true;
+ try {
+ expect(mapAuxiliaryRefToVoiceRefiner('cat:xd:codex:deepseek/deepseek-v4-flash')).toBeNull();
+ } finally {
+ xdProvider.routing.codex.disabled = false;
+ }
+ });
+
+ it('rechecks retained catalog refiner profiles against the live catalog', () => {
+ const profile = { id: 'cat:xd:codex:deepseek/deepseek-v4-flash' };
+ expect(isActiveCatalogVoiceRefinerProfile(profile)).toBe(true);
+
+ const xdProvider = activeCatalog.providers.find((provider) => provider.id === 'xd');
+ if (!xdProvider) throw new Error('test fixture is missing the xd provider');
+ const originalModels = xdProvider.models.codex;
+ xdProvider.models.codex = originalModels.filter(
+ (model) => model.id !== 'deepseek/deepseek-v4-flash',
+ );
+ try {
+ expect(isActiveCatalogVoiceRefinerProfile(profile)).toBe(false);
+ } finally {
+ xdProvider.models.codex = originalModels;
+ }
+ });
+
+ it('returns an empty chain when nothing in the list can refine speech', () => {
+ expect(
+ mapAuxiliaryRefsToVoiceRefiners([
+ 'cat:anthropic:claude-code:claude-haiku-4-5',
+ 'cat:anthropic:claude-code:claude-sonnet-4-6',
+ ]),
+ ).toEqual([]);
+ });
+
+ it('preserves order and drops unusable or duplicate refs', () => {
+ expect(
+ mapAuxiliaryRefsToVoiceRefiners([
+ 'cat:anthropic:claude-code:claude-haiku-4-5',
+ 'codex-gpt-5.4-mini',
+ 'cat:openai:codex:gpt-5.4-mini',
+ 'litellm-kimi-k2.6',
+ ]),
+ ).toEqual(['codex-gpt-5.4-mini', 'litellm-kimi-k2.6']);
+ });
+});
diff --git a/apps/desktop/src/main/voice-input/index.ts b/apps/desktop/src/main/voice-input/index.ts
index f58c4a6a6e..319cb5816e 100644
--- a/apps/desktop/src/main/voice-input/index.ts
+++ b/apps/desktop/src/main/voice-input/index.ts
@@ -24,6 +24,7 @@ import {
isUtilityRouteDisabled,
isUtilityRoutePaymentRequired,
} from '../utility-model/oneShotCandidates.js';
+import { getEffectiveAuxiliaryModelChainSnapshot } from '../utility-model/resolveAuxiliaryModelChain.js';
import { getAppCapabilities } from '../appCapabilities.js';
import { getProviderSecretStore } from '../secrets/providerSecretStore.js';
import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
@@ -31,7 +32,11 @@ import {
desktopCodexAuthAdapter,
readOwnerScopedXdGatewayKey,
} from '../maker-host/auth-adapters.js';
-import { getActiveAppSession } from '../appSessionState.js';
+import {
+ activeOwnerScopeKey,
+ getActiveAppSession,
+ isAppSessionBoundaryPending,
+} from '../appSessionState.js';
import { claudeUpstreamEndpoint } from '../maker-host/runtime-configs.js';
import { throwIpcError } from '../utils/ipcValidate.js';
import {
@@ -70,6 +75,7 @@ import {
collectRefinerPrewarmTransports,
orderVoiceInputRefinerChainForRuntime,
} from './VoiceInputRefinerRouting.js';
+import { isActiveCatalogVoiceRefinerProfile } from './mapAuxiliaryRefsToVoiceRefiners.js';
import {
getMicrophoneSettingsUrl,
isExplicitMicrophonePermissionDenied,
@@ -329,6 +335,12 @@ export async function adviseAndRecordVoiceInputDictionaryLearning(
return { ok: true, actions: [], elapsedMs: 0 };
}
+ // Bind dictionary learning to the owner and auxiliary chain that initiated
+ // this advisor request. Readiness and model resolution below both await, so
+ // a later account or chain switch must fail closed before any advisor fetch
+ // or dictionary mutation.
+ const ownerScopeKey = activeOwnerScopeKey();
+ const auxiliaryChainSnapshot = getEffectiveAuxiliaryModelChainSnapshot();
const sourceLabel = options.sourceLabel ?? payload.source ?? 'in_app';
// 锚点资格只认 main 侧由 event.sender 反查出的 fromOverlaySender,不认 payload.source
// 这个 renderer 自报字段。锚点必须在任何 await 之前取:此刻的呈现代次才代表这次请求
@@ -381,7 +393,15 @@ export async function adviseAndRecordVoiceInputDictionaryLearning(
const advisorAttempts: FallbackTextModelAttempt[] = readyAdvisorProfiles.map((profile) => ({
profileId: profile.id as VoiceInputRefinerProviderKind,
model: profile.model,
- client: createVoiceInputTextModelClient(profile),
+ client: guardRefinerClientAgainstUnavailableRoute(
+ profile,
+ createVoiceInputTextModelClient(profile, {
+ beforeDispatch: () => {
+ assertVoiceInputOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot);
+ assertRefinerRouteAvailable(profile);
+ },
+ }),
+ ),
promptCacheScope: `dictionaryLearning:${profile.id}:${senderId}`,
}));
const advisor = new DictationDictionaryAdvisor({
@@ -397,6 +417,7 @@ export async function adviseAndRecordVoiceInputDictionaryLearning(
existingCandidates: toDictionaryLearningCandidateState(settings.dictionaryCandidates),
};
const result = await advisor.advise(adviceInput);
+ assertVoiceInputOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot);
const recordResult = voiceInputDataStore.recordDictionaryLearningActions(result.actions);
if (recordResult.newAutomaticEntries.length > 0) {
showVoiceInputDictionaryToast(
@@ -933,10 +954,32 @@ async function getVoiceInputRefinerReadiness(
};
}
+function assertRefinerRouteAvailable(profile: VoiceInputRefinerProfile): void {
+ if (isUtilityRouteDisabled(profile)) {
+ throw new Error('voice refiner route disabled in settings');
+ }
+ if (!isActiveCatalogVoiceRefinerProfile(profile)) {
+ throw new Error('voice refiner catalog route unavailable');
+ }
+ if (isUtilityRoutePaymentRequired(profile)) {
+ throw new Error('voice refiner route requires paid entitlement');
+ }
+}
+
+function assertVoiceInputOwnerScopeCurrent(ownerScopeKey: string, chainSnapshot?: string): void {
+ if (
+ isAppSessionBoundaryPending()
+ || activeOwnerScopeKey() !== ownerScopeKey
+ || (chainSnapshot !== undefined && getEffectiveAuxiliaryModelChainSnapshot() !== chainSnapshot)
+ ) {
+ throw new Error('voice input owner scope changed');
+ }
+}
+
/**
- * TextModelClient 的 live 可用性包装(BYOK):每次 requestJson(= 一次精修请求)
- * 前重查设置停用与 Cindy 账号付费权限;不可用即抛错,FallbackTextModelClient
- * 将其视为该档失败并自然落到下一档。
+ * TextModelClient 的 live 可用性包装(BYOK):先在 requestJson 入口快速失败,
+ * 再把同一判据传入具体 HTTP client,在每次实际 fetch 前最后复核一次。
+ * FallbackTextModelClient 会将任一复核失败视为该档失败并自然落到下一档。
*/
function guardRefinerClientAgainstUnavailableRoute(
profile: VoiceInputRefinerProfile,
@@ -944,14 +987,10 @@ function guardRefinerClientAgainstUnavailableRoute(
): TextModelClient {
return {
requestJson: (input) => {
- if (isUtilityRouteDisabled(profile)) {
- return Promise.reject(new Error('voice refiner route disabled in settings'));
- }
- // Refinement may start minutes after chain resolution. Re-read the live
- // owner-scoped catalog immediately before every direct XD request so a
- // newly denied paid model cannot be dispatched from a retained session.
- if (isUtilityRoutePaymentRequired(profile)) {
- return Promise.reject(new Error('voice refiner route requires paid entitlement'));
+ try {
+ assertRefinerRouteAvailable(profile);
+ } catch (error) {
+ return Promise.reject(error);
}
return client.requestJson(input);
},
@@ -971,6 +1010,8 @@ function createVoiceInputTextModelClient(
/** Idle watchdog per attempt; both clients re-arm it on every stream chunk. */
timeoutMs?: number;
voiceContext?: CindyVoiceRunContext;
+ /** Final route guard invoked immediately before each network dispatch. */
+ beforeDispatch?: () => void;
},
): TextModelClient {
if (options?.voiceContext) {
@@ -984,6 +1025,7 @@ function createVoiceInputTextModelClient(
),
onUsage: options.onUsage,
timeoutMs: options.timeoutMs,
+ beforeDispatch: options.beforeDispatch,
});
}
if (profile.transport === 'codex-responses') {
@@ -995,6 +1037,7 @@ function createVoiceInputTextModelClient(
onAuthInvalidated: (reason) => {
void desktopCodexAuthAdapter.invalidate(reason);
},
+ beforeDispatch: options?.beforeDispatch,
});
}
@@ -1006,6 +1049,7 @@ function createVoiceInputTextModelClient(
baseUrl: proxyBaseUrl,
onUsage: options?.onUsage,
timeoutMs: options?.timeoutMs,
+ beforeDispatch: options?.beforeDispatch,
});
}
@@ -2066,6 +2110,11 @@ export function registerVoiceInputIpc(): void {
});
ipcMain.handle('voice-input:start', async (event, payload: StartPayload | undefined): Promise<StartResult> => {
+ // Bind this run to the owner that initiated it before any cancellation,
+ // readiness, or credential await. A later account switch must fail closed
+ // at the final refiner dispatch instead of using the new owner's route.
+ const ownerScopeKey = activeOwnerScopeKey();
+ const auxiliaryChainSnapshot = getEffectiveAuxiliaryModelChainSnapshot();
const isInlineSender = !isGlobalVoiceInputOverlaySender(event.sender);
const existing = activeByWebContentsId.get(event.sender.id);
if (existing) {
@@ -2217,6 +2266,11 @@ export function registerVoiceInputIpc(): void {
?? `${VOICE_INPUT_REFINEMENT_CACHE_SCOPE}:${CINDY_MANAGED_REFINER_PROVIDER}`;
refiner = new DictationRefiner({
client: createVoiceInputTextModelClient(effectiveRefinerProfile, {
+ // Managed refinement is routed and failed over by voice-server;
+ // changing the local auxiliary chain must not cancel it. The
+ // owner fence still prevents a previous account's text from
+ // being sent after an account switch.
+ beforeDispatch: () => assertVoiceInputOwnerScopeCurrent(ownerScopeKey),
timeoutMs: VOICE_INPUT_MANAGED_REFINER_IDLE_TIMEOUT_MS,
voiceContext,
onUsage: ({ servedModel, ...usage }) => {
@@ -2252,6 +2306,10 @@ export function registerVoiceInputIpc(): void {
client: guardRefinerClientAgainstUnavailableRoute(
profile,
createVoiceInputTextModelClient(profile, {
+ beforeDispatch: () => {
+ assertVoiceInputOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot);
+ assertRefinerRouteAvailable(profile);
+ },
timeoutMs: VOICE_INPUT_REFINER_IDLE_TIMEOUT_MS,
onUsage: (usage) => {
if (!runId) return;
diff --git a/apps/desktop/src/main/voice-input/mapAuxiliaryRefsToVoiceRefiners.ts b/apps/desktop/src/main/voice-input/mapAuxiliaryRefsToVoiceRefiners.ts
new file mode 100644
index 0000000000..85ec3aa1a8
--- /dev/null
+++ b/apps/desktop/src/main/voice-input/mapAuxiliaryRefsToVoiceRefiners.ts
@@ -0,0 +1,84 @@
+/**
+ * Map the shared auxiliary-model chain onto BYOK voice-refiner transports.
+ *
+ * Claude Messages / Haiku catalog pins have no voice-refiner transport and are
+ * skipped. An empty result means "do not refine".
+ */
+
+import { isModelSelectableForNewRoute } from '@cindy/model-providers';
+
+import { parseAuxiliaryModelRef } from '../../shared/auxiliaryModelChain.js';
+import {
+ CATALOG_MODEL_PIN_PREFIX,
+ decodeCatalogModelPin,
+ type CatalogModelPinRoute,
+} from '../../shared/catalogModelPin.js';
+import { getActiveCatalog } from '../maker-host/active-catalog.js';
+import {
+ getVoiceInputRefinerProfile,
+ voiceInputRefinerProviderKindForCatalogRoute,
+ type VoiceInputRefinerProfile,
+ type VoiceInputRefinerProviderKind,
+} from '../../shared/voiceInputRefinerProfiles.js';
+
+/**
+ * Catalog pins are persisted across catalog refreshes, so membership must be
+ * checked again before a voice route is admitted. This keeps voice refinement
+ * fail-closed when a model is retired, disabled, or loses paid availability.
+ */
+function isActiveCatalogVoiceRoute(route: CatalogModelPinRoute): boolean {
+ const provider = getActiveCatalog().providers.find((entry) => entry.id === route.providerId);
+ const routing = provider?.routing[route.agentKind];
+ if (
+ !provider
+ || !provider.agents.includes(route.agentKind)
+ || !routing
+ || routing.disabled
+ ) return false;
+ const model = provider.models[route.agentKind]?.find((entry) => entry.id === route.model);
+ return Boolean(
+ model
+ && isModelSelectableForNewRoute(model, { userProvider: provider.source === 'user' }),
+ );
+}
+
+/**
+ * Re-check a retained catalog refiner profile against the live catalog. Voice
+ * refinement can be dispatched long after the profile was first resolved.
+ * Static utility profiles remain valid without a catalog lookup.
+ */
+export function isActiveCatalogVoiceRefinerProfile(
+ profile: Pick<VoiceInputRefinerProfile, 'id'>,
+): boolean {
+ if (!profile.id.startsWith(CATALOG_MODEL_PIN_PREFIX)) return true;
+ const route = decodeCatalogModelPin(profile.id);
+ return Boolean(route && isActiveCatalogVoiceRoute(route));
+}
+
+export function mapAuxiliaryRefToVoiceRefiner(ref: string): VoiceInputRefinerProviderKind | null {
+ const parsed = parseAuxiliaryModelRef(ref);
+ if (!parsed) return null;
+ if (parsed.kind === 'profile') {
+ return parsed.id;
+ }
+ if (!isActiveCatalogVoiceRoute(parsed.route)) return null;
+ return voiceInputRefinerProviderKindForCatalogRoute(parsed.route);
+}
+
+export function mapAuxiliaryRefsToVoiceRefiners(
+ refs: readonly string[],
+): VoiceInputRefinerProviderKind[] {
+ const out: VoiceInputRefinerProviderKind[] = [];
+ for (const ref of refs) {
+ const mapped = mapAuxiliaryRefToVoiceRefiner(ref);
+ if (!mapped) continue;
+ const mappedProfile = getVoiceInputRefinerProfile(mapped);
+ const duplicate = out.some((existing) => {
+ const existingProfile = getVoiceInputRefinerProfile(existing);
+ return existingProfile.transport === mappedProfile.transport
+ && existingProfile.model === mappedProfile.model;
+ });
+ if (!duplicate) out.push(mapped);
+ }
+ return out;
+}
diff --git a/apps/desktop/src/renderer/cindy-brain/OneshotModelPinPicker.tsx b/apps/desktop/src/renderer/cindy-brain/OneshotModelPinPicker.tsx
index dec8b3d690..a2d172b9bf 100644
--- a/apps/desktop/src/renderer/cindy-brain/OneshotModelPinPicker.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/OneshotModelPinPicker.tsx
@@ -2,8 +2,9 @@
* OneshotModelPinPicker — 快问快答(text.oneshot)钉档选择器。
*
* 钉值是目录钉(cat: 编码的 供应商×agent×模型),清单 = 当前供应商目录的全部
- * 文本模型(主侧 cindy-prefs 同步下发)。选择器先让用户选择 Agent,再只展示该
- * Agent 可用的模型;选中模型后才一次性写回完整钉值。模型层视觉与信息层级对齐
+ * 文本模型(主侧 cindy-prefs 同步下发)。默认选择器先让用户选择 Agent,再只展示该
+ * Agent 可用的模型;设置页也可直接按供应商展示全部可用模型。选中模型后才一次性写回完整钉值。
+ * 模型层视觉与信息层级对齐
* 新建对话 / 开协同的模型选择器(ModelSelector):厂牌图标 + 模型名 + 折扣/订阅
* 徽标 + 供应商分组标题 + 搜索过滤。第一层首行恒为「跟随默认」(身份卡声明了
* 偏好模型时如实显示声明)。
@@ -16,6 +17,7 @@ import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { ModelIconMark } from '@/components/new-chat/ModelSelector';
+import { PROVIDER_TITLE_KEY } from '@/lib/providerDisplayName';
import { decodeCatalogModelPin } from '../../shared/catalogModelPin';
/** 主侧 cindy-prefs 下发的目录钉条目(与 TextOneshotPinOption 同形)。 */
@@ -43,6 +45,23 @@ function agentKindLabel(agentKind: string): string {
return agentKind === 'claude-code' ? 'Claude Code' : agentKind === 'codex' ? 'Codex' : agentKind;
}
+function preferredAgentForModel(modelId: string): string {
+ return modelId.startsWith('claude') ? 'claude-code' : 'codex';
+}
+
+function displayProviderGroup(
+ option: Pick<OneshotPinOption, 'providerId' | 'group'>,
+ t: (key: string) => string,
+ translateProvider = false,
+): string {
+ // Plugin detail keeps the historical catalog group labels (for example GW).
+ // The settings-only provider view opts into product-facing names such as
+ // Cindy AI through `groupByProvider`.
+ if (!translateProvider) return option.group;
+ const titleKey = PROVIDER_TITLE_KEY[option.providerId];
+ return titleKey ? t(titleKey) : option.group;
+}
+
export function OneshotModelPinPicker({
value,
defaultLabel,
@@ -59,6 +78,7 @@ export function OneshotModelPinPicker({
budgetLabel,
subscriptionLabel,
disabled,
+ groupByProvider = false,
}: {
/** 当前钉值;undefined = 跟随默认。 */
value?: string;
@@ -82,6 +102,8 @@ export function OneshotModelPinPicker({
budgetLabel?: string;
subscriptionLabel?: string;
disabled?: boolean;
+ /** Show all routable models in provider groups without exposing the Agent rail. */
+ groupByProvider?: boolean;
}): ReactNode {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
@@ -94,21 +116,27 @@ export function OneshotModelPinPicker({
// 存量档位钉不是 stale——它合法且仍可路由,只是不再能新建,展示友好名。
const staleValue = value && !current && !legacyPinLabel ? value : null;
const staleRoute = staleValue ? decodeCatalogModelPin(staleValue) : null;
- const automaticLabel = defaultOptionLabel
- ?? (declaredLabel
+ 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 triggerLabel =
+ (groupByProvider && current
+ ? `${current.modelName} · ${displayProviderGroup(current, t, groupByProvider)}`
+ : current?.label) ??
+ legacyPinLabel ??
+ staleValue ??
+ automaticLabel;
const visibleOptions = useMemo(() => {
const visible: OneshotPinOption[] = [];
const indexByRouteName = new Map<string, number>();
for (const option of options) {
if (option.available === false && option.id !== value) continue;
- const routeName = `${option.providerId}\n${option.agentKind}\n${option.modelName.trim().toLowerCase()}`;
+ const routeName = groupByProvider
+ ? `${option.providerId}\n${option.modelId.trim().toLowerCase()}`
+ : `${option.providerId}\n${option.agentKind}\n${option.modelName.trim().toLowerCase()}`;
const existingIndex = indexByRouteName.get(routeName);
if (existingIndex === undefined) {
indexByRouteName.set(routeName, visible.length);
@@ -116,12 +144,21 @@ export function OneshotModelPinPicker({
continue;
}
const existing = visible[existingIndex]!;
- if (existing.id !== value && (option.id === value || existing.available === false)) {
+ const preferredRoute =
+ groupByProvider &&
+ option.agentKind === preferredAgentForModel(option.modelId) &&
+ existing.agentKind !== preferredAgentForModel(existing.modelId);
+ const replacesUnavailableRoute = existing.available === false && option.available !== false;
+ if (
+ (option.id === value && option.available !== false) ||
+ replacesUnavailableRoute ||
+ (existing.id !== value && preferredRoute)
+ ) {
visible[existingIndex] = option;
}
}
return visible;
- }, [options, value]);
+ }, [groupByProvider, options, value]);
const agentChoices = useMemo(() => {
const kinds: string[] = [];
@@ -136,29 +173,35 @@ export function OneshotModelPinPicker({
const selectedAgentLabel = selectedAgent ? agentKindLabel(selectedAgent) : '';
const filtered = useMemo(() => {
- if (!selectedAgent) return [];
const q = query.trim().toLowerCase();
- const visible = visibleOptions.filter((option) => option.agentKind === selectedAgent);
+ if (!groupByProvider && !selectedAgent) return [];
+ const visible = groupByProvider
+ ? visibleOptions
+ : visibleOptions.filter((option) => option.agentKind === selectedAgent);
if (!q) return visible;
return visible.filter(
(o) =>
- o.modelName.toLowerCase().includes(q)
- || o.modelId.toLowerCase().includes(q)
- || o.group.toLowerCase().includes(q),
+ o.modelName.toLowerCase().includes(q) ||
+ o.modelId.toLowerCase().includes(q) ||
+ displayProviderGroup(o, t, groupByProvider).toLowerCase().includes(q),
);
- }, [query, selectedAgent, visibleOptions]);
+ }, [groupByProvider, query, selectedAgent, t, visibleOptions]);
const groups = useMemo(() => {
const names: string[] = [];
for (const o of filtered) {
- if (!names.includes(o.group)) names.push(o.group);
+ const name = displayProviderGroup(o, t, groupByProvider);
+ if (!names.includes(name)) names.push(name);
}
- return names.map((name) => ({ name, items: filtered.filter((o) => o.group === name) }));
- }, [filtered]);
+ return names.map((name) => ({
+ name,
+ items: filtered.filter((o) => displayProviderGroup(o, t, groupByProvider) === name),
+ }));
+ }, [filtered, groupByProvider, t]);
useEffect(() => {
- if (open && selectedAgent) searchRef.current?.focus();
- }, [open, selectedAgent]);
+ if (open && (groupByProvider || selectedAgent)) searchRef.current?.focus();
+ }, [groupByProvider, open, selectedAgent]);
const select = (pin: string | null): void => {
// 点中的就是当前值(含 stale 行):只收起,不回写——stale 的目录钉已不在
@@ -184,6 +227,104 @@ export function OneshotModelPinPicker({
active && 'bg-[var(--model-item-hover)]',
);
+ const modelRows = (
+ <>
+ {groups.length === 0 &&
+ !(
+ staleValue &&
+ (groupByProvider || staleRoute?.agentKind === selectedAgent) &&
+ query.trim() === ''
+ ) ? (
+ <div className="px-3 py-6 text-center text-13 text-[var(--text-tertiary)]">
+ {noResultsLabel ?? t('newChat.modelSelector.search.noResults')}
+ </div>
+ ) : (
+ groups.map((g) => (
+ <div key={g.name} role="group" aria-label={g.name}>
+ <div className="mx-1 my-1 h-px bg-[var(--model-dropdown-border)]" />
+ <div className="truncate px-3 pb-0.5 pt-1 text-11 font-medium text-[var(--text-tertiary)]">
+ {g.name}
+ </div>
+ {g.items.map((o) => {
+ const active = value === o.id;
+ const unavailable = o.available === false;
+ return (
+ <button
+ key={o.id}
+ type="button"
+ role="option"
+ aria-selected={active}
+ data-pin-id={o.id}
+ aria-disabled={unavailable}
+ disabled={unavailable}
+ className={cn(rowClass(active), unavailable && 'opacity-60')}
+ onClick={unavailable ? undefined : () => select(o.id)}
+ >
+ <span className="flex min-w-0 flex-1 items-center gap-2.5">
+ <ModelIconMark
+ icon={o.icon}
+ providerId={o.providerId}
+ name={o.group}
+ routing={o.routing}
+ colorClass="text-[var(--text-secondary)]"
+ withMargin={false}
+ dense
+ />
+ <span className="flex min-w-0 flex-1 items-center gap-1.5">
+ <span className="truncate text-14 font-medium leading-5 text-[var(--model-item-text)]">
+ {o.modelName}
+ </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)]">
+ {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)]">
+ {budgetLabel ?? t('settings.ghosts.detail.cindyPrefs.budgetBadge')}
+ </span>
+ )}
+ </span>
+ </span>
+ {active && (
+ <Check size={15} className="ml-2 shrink-0 text-[var(--model-item-check)]" />
+ )}
+ </button>
+ );
+ })}
+ </div>
+ ))
+ )}
+
+ {staleValue &&
+ (groupByProvider || staleRoute?.agentKind === selectedAgent) &&
+ query.trim() === '' && (
+ <div role="group" aria-label={staleValue}>
+ <div className="mx-1 my-1 h-px bg-[var(--model-dropdown-border)]" />
+ <button
+ type="button"
+ role="option"
+ aria-selected
+ className={rowClass(true)}
+ onClick={() => select(staleValue)}
+ >
+ <span className="min-w-0 truncate text-14 font-medium leading-5 text-[var(--model-item-text)]">
+ {staleValue}
+ </span>
+ <Check size={15} className="ml-2 shrink-0 text-[var(--model-item-check)]" />
+ </button>
+ </div>
+ )}
+ </>
+ );
+
return (
<Popover
open={open}
@@ -202,7 +343,8 @@ export function OneshotModelPinPicker({
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)]',
+ 'flex h-8 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)]',
+ groupByProvider ? 'w-full max-w-full' : 'w-[300px] max-w-[60%]',
'disabled:cursor-not-allowed disabled:opacity-60',
dense ? 'text-12' : 'text-13',
)}
@@ -228,7 +370,48 @@ export function OneshotModelPinPicker({
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">
- {selectedAgent === null ? (
+ {groupByProvider ? (
+ <>
+ <button
+ type="button"
+ role="option"
+ aria-selected={value === undefined}
+ className={rowClass(value === undefined)}
+ onClick={() => select(null)}
+ >
+ <span className="min-w-0 truncate text-14 font-medium leading-5 text-[var(--model-item-text)]">
+ {automaticLabel}
+ </span>
+ {value === undefined && (
+ <Check size={15} className="ml-2 shrink-0 text-[var(--model-item-check)]" />
+ )}
+ </button>
+ <div className="mx-1 my-1 h-px bg-[var(--model-dropdown-border)]" />
+ <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={
+ 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>
+ <div
+ role="listbox"
+ aria-label={ariaLabel}
+ className="flex max-h-[300px] flex-col gap-0.5 overflow-y-auto overscroll-contain"
+ >
+ {modelRows}
+ </div>
+ </>
+ ) : selectedAgent === null ? (
<div
role="listbox"
aria-label={ariaLabel}
@@ -309,8 +492,12 @@ export function OneshotModelPinPicker({
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
- placeholder={searchPlaceholder ?? t('settings.ghosts.detail.cindyPrefs.searchPlaceholder')}
- aria-label={searchPlaceholder ?? 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>
@@ -320,94 +507,7 @@ export function OneshotModelPinPicker({
aria-label={`${ariaLabel}: ${selectedAgentLabel}`}
className="flex max-h-[300px] flex-col gap-0.5 overflow-y-auto overscroll-contain"
>
- {groups.length === 0
- && !(staleValue && staleRoute?.agentKind === selectedAgent && query.trim() === '') ? (
- <div className="px-3 py-6 text-center text-13 text-[var(--text-tertiary)]">
- {noResultsLabel ?? t('newChat.modelSelector.search.noResults')}
- </div>
- ) : (
- groups.map((g) => (
- <div key={g.name} role="group" aria-label={g.name}>
- <div className="mx-1 my-1 h-px bg-[var(--model-dropdown-border)]" />
- <div className="truncate px-3 pb-0.5 pt-1 text-11 font-medium text-[var(--text-tertiary)]">
- {g.name}
- </div>
- {g.items.map((o) => {
- const active = value === o.id;
- const unavailable = o.available === false;
- return (
- <button
- key={o.id}
- type="button"
- role="option"
- aria-selected={active}
- data-pin-id={o.id}
- 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">
- <ModelIconMark
- icon={o.icon}
- providerId={o.providerId}
- name={o.group}
- routing={o.routing}
- colorClass="text-[var(--text-secondary)]"
- withMargin={false}
- dense
- />
- <span className="flex min-w-0 flex-1 items-center gap-1.5">
- <span className="truncate text-14 font-medium leading-5 text-[var(--model-item-text)]">
- {o.modelName}
- </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)]">
- {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)]">
- {budgetLabel ?? t('settings.ghosts.detail.cindyPrefs.budgetBadge')}
- </span>
- )}
- </span>
- </span>
- {active && (
- <Check size={15} className="ml-2 shrink-0 text-[var(--model-item-check)]" />
- )}
- </button>
- );
- })}
- </div>
- ))
- )}
-
- {staleValue
- && staleRoute?.agentKind === selectedAgent
- && query.trim() === '' && (
- <div role="group" aria-label={staleValue}>
- <div className="mx-1 my-1 h-px bg-[var(--model-dropdown-border)]" />
- <button
- type="button"
- role="option"
- aria-selected
- className={rowClass(true)}
- onClick={() => select(staleValue)}
- >
- <span className="min-w-0 truncate text-14 font-medium leading-5 text-[var(--model-item-text)]">
- {staleValue}
- </span>
- <Check size={15} className="ml-2 shrink-0 text-[var(--model-item-check)]" />
- </button>
- </div>
- )}
+ {modelRows}
</div>
</>
)}
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/OneshotModelPinPicker.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/OneshotModelPinPicker.test.tsx
new file mode 100644
index 0000000000..66c270aba2
--- /dev/null
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/OneshotModelPinPicker.test.tsx
@@ -0,0 +1,204 @@
+// @vitest-environment jsdom
+
+import { fireEvent, render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+const OPENROUTER_PIN = 'cat:openrouter:codex:openai/gpt-5-mini';
+const ANTHROPIC_PIN = 'cat:anthropic:claude-code:claude-haiku-4-5';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) =>
+ ({
+ 'settings.providers.anthropic.title': 'Anthropic',
+ 'settings.providers.openai.title': 'OpenAI',
+ 'settings.providers.xd.title': 'Cindy AI',
+ })[key] ?? key,
+ }),
+}));
+
+vi.mock('@/components/ui/popover', () => ({
+ Popover: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+ PopoverTrigger: ({ children }: { children: React.ReactNode }) => children,
+ PopoverContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+}));
+
+vi.mock('@/components/new-chat/ModelSelector', () => ({
+ ModelIconMark: () => <span aria-hidden="true" />,
+}));
+
+import { OneshotModelPinPicker, type OneshotPinOption } from '../OneshotModelPinPicker';
+
+const options: OneshotPinOption[] = [
+ {
+ id: OPENROUTER_PIN,
+ label: 'GPT-5 mini · OpenRouter',
+ group: 'OpenRouter',
+ providerId: 'openrouter',
+ agentKind: 'codex',
+ modelId: 'openai/gpt-5-mini',
+ modelName: 'GPT-5 mini',
+ budget: false,
+ subscription: false,
+ available: true,
+ },
+ {
+ id: ANTHROPIC_PIN,
+ label: 'Claude Haiku 4.5 · Anthropic',
+ group: 'Anthropic',
+ providerId: 'anthropic',
+ agentKind: 'claude-code',
+ modelId: 'claude-haiku-4-5',
+ modelName: 'Claude Haiku 4.5',
+ budget: false,
+ subscription: false,
+ available: true,
+ },
+];
+
+const xdOption: OneshotPinOption = {
+ id: 'cat:xd:codex:deepseek/deepseek-v4-flash',
+ label: 'DeepSeek V4 Flash · XD Gateway',
+ group: 'XD Gateway',
+ providerId: 'xd',
+ agentKind: 'codex',
+ modelId: 'deepseek/deepseek-v4-flash',
+ modelName: 'DeepSeek V4 Flash',
+ budget: false,
+ subscription: false,
+ available: true,
+};
+
+describe('OneshotModelPinPicker provider-first mode', () => {
+ it('groups all suppliers without rendering the Agent rail', () => {
+ render(
+ <OneshotModelPinPicker
+ value={undefined}
+ defaultLabel=""
+ declaredLabel={null}
+ options={options}
+ onChange={vi.fn()}
+ ariaLabel="Auxiliary model"
+ groupByProvider
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'Auxiliary model' }));
+
+ expect(screen.getByRole('group', { name: 'OpenRouter' })).toBeTruthy();
+ expect(screen.getByRole('group', { name: 'Anthropic' })).toBeTruthy();
+ expect(
+ screen.getByPlaceholderText('settings.ghosts.detail.cindyPrefs.searchPlaceholder'),
+ ).toBeTruthy();
+ expect(screen.queryByText('Claude Code')).toBeNull();
+ expect(screen.queryByText('Codex')).toBeNull();
+ expect(screen.queryByRole('option', { name: /Claude Code/ })).toBeNull();
+ });
+
+ it('uses the standard Cindy AI name for the xd provider', () => {
+ render(
+ <OneshotModelPinPicker
+ value={xdOption.id}
+ defaultLabel=""
+ declaredLabel={null}
+ options={[xdOption]}
+ onChange={vi.fn()}
+ ariaLabel="Auxiliary model"
+ groupByProvider
+ />,
+ );
+
+ expect(screen.getByRole('button', { name: 'Auxiliary model' }).textContent)
+ .toContain('DeepSeek V4 Flash · Cindy AI');
+ fireEvent.click(screen.getByRole('button', { name: 'Auxiliary model' }));
+
+ expect(screen.getByRole('group', { name: 'Cindy AI' })).toBeTruthy();
+ expect(screen.queryByRole('group', { name: 'XD Gateway' })).toBeNull();
+ });
+
+ it('returns the exact provider and Agent pin for a selected row', () => {
+ const onChange = vi.fn();
+ render(
+ <OneshotModelPinPicker
+ value={undefined}
+ defaultLabel=""
+ declaredLabel={null}
+ options={options}
+ onChange={onChange}
+ ariaLabel="Auxiliary model"
+ groupByProvider
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'Auxiliary model' }));
+ fireEvent.click(screen.getByRole('option', { name: /Claude Haiku 4\.5/ }));
+
+ expect(onChange).toHaveBeenCalledWith(ANTHROPIC_PIN);
+ });
+
+ it('renders an unavailable current route but prevents selecting it', () => {
+ const onChange = vi.fn();
+ const unavailable = {
+ ...xdOption,
+ id: 'cat:xd:codex:retired-model',
+ modelId: 'retired-model',
+ modelName: 'Retired model',
+ label: 'Retired model · Cindy AI',
+ available: false,
+ };
+ render(
+ <OneshotModelPinPicker
+ value={unavailable.id}
+ defaultLabel=""
+ declaredLabel={null}
+ options={[unavailable]}
+ onChange={onChange}
+ ariaLabel="Auxiliary model"
+ groupByProvider
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'Auxiliary model' }));
+ const option = screen.getByRole('option', { name: /Retired model/ });
+ expect(option.getAttribute('disabled')).not.toBeNull();
+ fireEvent.click(option);
+
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('keeps an available same-model route when the current agent route is unavailable', () => {
+ const onChange = vi.fn();
+ const available = {
+ ...xdOption,
+ id: 'cat:xd:codex:shared-model',
+ modelId: 'shared-model',
+ modelName: 'Shared model',
+ label: 'Shared model · Cindy AI',
+ available: true,
+ };
+ const unavailable = {
+ ...available,
+ id: 'cat:xd:claude-code:shared-model',
+ agentKind: 'claude-code',
+ available: false,
+ };
+ render(
+ <OneshotModelPinPicker
+ value={unavailable.id}
+ defaultLabel=""
+ declaredLabel={null}
+ options={[available, unavailable]}
+ onChange={onChange}
+ ariaLabel="Auxiliary model"
+ groupByProvider
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'Auxiliary model' }));
+ const option = screen.getByRole('option', { name: /Shared model/ });
+ expect(option.getAttribute('disabled')).toBeNull();
+ fireEvent.click(option);
+
+ expect(onChange).toHaveBeenCalledWith(available.id);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx b/apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx
index 651b9579d2..494b2acf4e 100644
--- a/apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx
@@ -1,23 +1,34 @@
-/** Settings → Personalization: global models for short auxiliary text tasks. */
+/** Settings → Personalization: one ordered chain for short auxiliary text. */
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { Check, ChevronDown } from 'lucide-react';
+import * as Select from '@radix-ui/react-select';
-import { OneshotModelPinPicker, type OneshotPinOption } from '@/cindy-brain/OneshotModelPinPicker';
+import { OneshotModelPinPicker } from '@/cindy-brain/OneshotModelPinPicker';
+import { useAuth } from '@/contexts/AuthContext';
import { createLogger } from '@/lib/logger';
import { toast } from '@/lib/toast';
+import { cn } from '@/lib/utils';
import { isModelEnabled, useModelVisibilityVersion } from '@/state/modelVisibilityPrefs';
-import type {
- AuxiliaryModelSettingsKey,
- AuxiliaryModelSettingsState,
-} from '../../../shared/auxiliaryModelSettings';
+import {
+ AUTO_AUXILIARY_MODEL_CHAIN,
+ AUTO_AUXILIARY_MODEL_CHAIN_I18N_KEYS,
+} from '../../../shared/auxiliaryModelChain';
+import type { AuxiliaryModelSettingsState } from '../../../shared/auxiliaryModelSettings';
+import { DefaultOverrideControls } from './DefaultOverrideControls';
const log = createLogger('AuxiliaryModelSection');
+const SLOT_I18N = ['preferred', 'fallback1', 'fallback2'] as const;
+type AuxiliaryModelMode = 'automatic' | 'custom';
+
export function AuxiliaryModelSection() {
const { t } = useTranslation();
+ const { mode: authMode } = useAuth();
const [settings, setSettings] = useState<AuxiliaryModelSettingsState | null>(null);
const [pending, setPending] = useState(false);
+ const [drafting, setDrafting] = useState(false);
const pendingRef = useRef(false);
const modelVisibilityVersion = useModelVisibilityVersion();
@@ -36,14 +47,15 @@ export function AuxiliaryModelSection() {
};
}, []);
- const persist = useCallback(
- async (key: AuxiliaryModelSettingsKey, pin: string | null): Promise<void> => {
+ const persistModels = useCallback(
+ async (models: string[]): Promise<void> => {
if (pendingRef.current) return;
pendingRef.current = true;
setPending(true);
try {
- const next = await window.electronAPI.maker.auxiliaryModelSettingsSet({ [key]: pin });
+ const next = await window.electronAPI.maker.auxiliaryModelSettingsSet({ models });
setSettings(next);
+ if (models.length === 0) setDrafting(false);
} catch (error) {
log.warn('auxiliaryModelSettingsSet failed', error);
toast.error(
@@ -57,13 +69,13 @@ export function AuxiliaryModelSection() {
[t],
);
- const options = useMemo<readonly OneshotPinOption[]>(
+ const options = useMemo(
() =>
(settings?.options ?? []).map((option) => ({
...option,
available:
- option.available !== false
- && isModelEnabled(option.agentKind, option.providerId, {
+ option.available !== false &&
+ isModelEnabled(option.agentKind, option.providerId, {
id: option.modelId,
defaultEnabled: option.defaultEnabled,
}),
@@ -73,26 +85,60 @@ export function AuxiliaryModelSection() {
if (!settings) return null;
- const picker = (key: AuxiliaryModelSettingsKey, ariaLabel: string, automaticLabel: string) => (
- <OneshotModelPinPicker
- value={settings[key] ?? undefined}
- defaultLabel=""
- declaredLabel={null}
- options={options}
- 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')}
- />
- );
+ const models = Array.isArray(settings.models) ? settings.models : [];
+ const customized = models.length > 0;
+ const showCustom = customized || drafting;
+ // Keep the default/override split intact: first-time Custom is only a draft.
+ // Local and signed-out sessions cannot use Cindy AI routes, so do not seed
+ // those unavailable catalog pins into a draft that the user cannot select.
+ const automaticDraftModels =
+ authMode === 'cloud'
+ ? AUTO_AUXILIARY_MODEL_CHAIN.filter((ref) =>
+ options.some((option) => option.id === ref && option.available),
+ )
+ : [];
+ const activeModels = customized ? models : drafting ? automaticDraftModels : [];
+ const automaticChain = AUTO_AUXILIARY_MODEL_CHAIN_I18N_KEYS.map((key) =>
+ t(`settings.auxiliaryModels.chain.${key}`),
+ ).join(' → ');
+ const mode: AuxiliaryModelMode = showCustom ? 'custom' : 'automatic';
+
+ const selectMode = (nextMode: AuxiliaryModelMode): void => {
+ if (nextMode === 'custom') {
+ setDrafting(true);
+ return;
+ }
+ if (!customized) {
+ setDrafting(false);
+ return;
+ }
+ void persistModels([]);
+ };
+
+ const applySlot = (index: number, pin: string | null): void => {
+ if (index === 0 && !pin) {
+ if (customized) {
+ void persistModels([]);
+ } else {
+ setDrafting(false);
+ }
+ return;
+ }
+ const slots = [...activeModels];
+ if (!pin) {
+ slots.splice(index, 1);
+ } else if (index >= slots.length) {
+ slots.push(pin);
+ } else {
+ if (slots.some((entry, slotIndex) => slotIndex !== index && entry === pin)) return;
+ slots[index] = pin;
+ }
+ const unique: string[] = [];
+ for (const entry of slots) {
+ if (entry && !unique.includes(entry)) unique.push(entry);
+ }
+ void persistModels(unique);
+ };
return (
<div className="flex flex-col gap-[14px]">
@@ -107,42 +153,167 @@ export function AuxiliaryModelSection() {
<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 className="min-w-0 flex-1 text-14 font-medium text-[var(--text-primary)]">
+ {t('settings.auxiliaryModels.title')}
+ </div>
+ <div className="flex min-w-0 max-w-full items-center justify-end gap-2">
+ {showCustom ? (
+ <DefaultOverrideControls
+ isCustomized={customized || drafting}
+ showCustomizedBadge={customized}
+ disabled={pending}
+ onReset={() => {
+ if (!customized) {
+ setDrafting(false);
+ return;
+ }
+ void persistModels([]);
+ }}
+ />
+ ) : null}
+ <Select.Root
+ value={mode}
+ onValueChange={(value) => selectMode(value as AuxiliaryModelMode)}
+ disabled={pending}
+ >
+ <Select.Trigger
+ aria-label={t('settings.auxiliaryModels.title')}
+ className={cn(
+ 'flex h-9 w-[220px] max-w-full min-w-0 shrink items-center justify-between gap-3 rounded-full border px-3.5 text-13 outline-none transition-colors',
+ 'border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] text-[var(--settings-input-text)]',
+ 'hover:bg-[var(--settings-menu-bg-hover)] focus:ring-2 focus:ring-[var(--focus-ring-soft)]',
+ 'disabled:cursor-not-allowed disabled:opacity-55',
+ )}
+ >
+ <span className="min-w-0 truncate text-left">
+ <Select.Value />
+ </span>
+ <Select.Icon asChild>
+ <ChevronDown
+ size={14}
+ className="shrink-0 text-[var(--settings-eye-icon)]"
+ aria-hidden="true"
+ />
+ </Select.Icon>
+ </Select.Trigger>
+ <Select.Portal>
+ <Select.Content
+ position="popper"
+ side="bottom"
+ align="start"
+ sideOffset={6}
+ className={cn(
+ 'z-[10010] w-[var(--radix-select-trigger-width)] min-w-[220px] overflow-hidden rounded-xl p-2',
+ 'border border-[var(--settings-input-border)] bg-[var(--settings-theme-card-bg)]',
+ )}
+ >
+ <Select.Viewport className="flex flex-col gap-[2px]">
+ {(['automatic', 'custom'] as const).map((option) => (
+ <Select.Item
+ key={option}
+ value={option}
+ className={cn(
+ 'flex h-9 w-full cursor-pointer select-none items-center justify-between gap-3 rounded-[8px] px-3 text-left text-13 outline-none transition-colors',
+ 'text-[var(--settings-input-text)] data-[highlighted]:bg-[var(--settings-menu-bg-hover)]',
+ 'data-[state=checked]:bg-[var(--settings-menu-bg-selected)] data-[state=checked]:font-medium data-[state=checked]:text-[var(--settings-menu-text-selected)]',
+ )}
+ >
+ <Select.ItemText className="min-w-0 flex-1 whitespace-nowrap">
+ {t(
+ option === 'automatic'
+ ? 'settings.auxiliaryModels.automatic'
+ : 'settings.auxiliaryModels.customize',
+ )}
+ </Select.ItemText>
+ <Select.ItemIndicator>
+ <Check
+ size={16}
+ className="shrink-0 text-[var(--settings-theme-icon-active)]"
+ />
+ </Select.ItemIndicator>
+ </Select.Item>
+ ))}
+ </Select.Viewport>
+ </Select.Content>
+ </Select.Portal>
+ </Select.Root>
</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')}
+ {showCustom ? (
+ <>
+ {SLOT_I18N.map((slotKey, index) => {
+ const pin = activeModels[index];
+ const selectedByOtherSlot = new Set(
+ activeModels.filter((entry, slotIndex) => slotIndex !== index && entry),
+ );
+ const slotOptions = options.filter(
+ (option) => option.id === pin || !selectedByOtherSlot.has(option.id),
+ );
+ return (
+ <div key={slotKey}>
+ {index > 0 ? (
+ <div className="mx-4 h-px bg-[var(--settings-theme-card-border)]" />
+ ) : null}
+ <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.${slotKey}.label`)}
+ </div>
+ <p className="mt-1 text-12 leading-[1.5] text-[var(--text-tertiary)]">
+ {t(`settings.auxiliaryModels.${slotKey}.description`)}
+ </p>
+ </div>
+ <div className="w-[min(100%,320px)] shrink-0">
+ {/* One-shot pins already carry the exact provider + agent route. The
+ provider-first picker exposes every routable supplier without
+ surfacing Harness or a thinking-depth control. */}
+ <OneshotModelPinPicker
+ value={pin ?? undefined}
+ defaultLabel=""
+ declaredLabel={null}
+ options={slotOptions}
+ onChange={(next) => applySlot(index, next)}
+ ariaLabel={t(`settings.auxiliaryModels.${slotKey}.ariaLabel`)}
+ dense
+ defaultOptionLabel={t('settings.auxiliaryModels.emptySlot')}
+ 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')}
+ groupByProvider
+ disabled={pending || (index > 0 && !activeModels[index - 1])}
+ />
+ </div>
+ </div>
+ </div>
+ );
+ })}
+
+ <p className="px-4 pb-4 text-12 leading-[1.5] text-[var(--text-secondary)]">
+ {authMode !== 'cloud' ? (
+ <span className="mb-1 block text-[var(--text-tertiary)]">
+ {t('settings.auxiliaryModels.signInHint')}
+ </span>
+ ) : null}
+ {t('settings.auxiliaryModels.customHint')}
+ </p>
+ </>
+ ) : (
+ <div className="px-4 py-4">
+ <p className="text-12 leading-[1.5] text-[var(--text-tertiary)]">
+ {automaticChain}
</p>
+ {authMode !== 'cloud' ? (
+ <p className="mt-1 text-12 leading-[1.5] text-[var(--text-tertiary)]">
+ {t('settings.auxiliaryModels.signInHint')}
+ </p>
+ ) : null}
</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/DefaultOverrideControls.tsx b/apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx
index aafcb98478..1bf30984fc 100644
--- a/apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx
+++ b/apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx
@@ -8,12 +8,15 @@ export function DefaultOverrideControls({
isCustomized,
disabled,
alwaysVisible = false,
+ showCustomizedBadge = isCustomized,
onReset,
}: {
isCustomized: boolean;
disabled?: boolean;
/** 保留还原入口占位;无覆盖时按钮禁用,避免设置行宽度跳动。 */
alwaysVisible?: boolean;
+ /** Draft-only settings can keep the reset action without claiming a saved override. */
+ showCustomizedBadge?: boolean;
onReset: () => void;
}) {
const { t } = useTranslation();
@@ -23,7 +26,7 @@ export function DefaultOverrideControls({
return (
<div className="flex shrink-0 items-center gap-2">
- {isCustomized ? (
+ {isCustomized && showCustomizedBadge ? (
<span className="whitespace-nowrap rounded-full bg-[var(--surface-chip)] px-2 py-1 text-11 font-medium leading-none text-[var(--text-secondary)]">
{t('settings.defaults.customizedBadge')}
</span>
diff --git a/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx b/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx
index e125ffd668..cf686210cc 100644
--- a/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx
@@ -369,14 +369,11 @@ function VoiceInputServiceSourceCard() {
ready,
selection,
asrProfiles,
- refinerProfiles,
readiness,
customAsrApiKeyConfigured,
saving,
setServiceMode,
setAsrProvider,
- setRefinerProvider,
- setRefinerFallbackProvider,
saveCustomAsr,
clearCustomAsrApiKey,
resetToDefault,
@@ -441,6 +438,12 @@ function VoiceInputServiceSourceCard() {
setSearchParams(next, { replace: true });
}, [searchParams, setSearchParams]);
+ const openPersonalizationTab = useCallback(() => {
+ const next = new URLSearchParams(searchParams);
+ next.set('tab', 'personalization');
+ setSearchParams(next, { replace: true });
+ }, [searchParams, setSearchParams]);
+
const modeOptions = useMemo<ReadonlyArray<VoiceInputSelectOption<VoiceInputServiceModeData>>>(() => {
const byokOption: VoiceInputSelectOption<VoiceInputServiceModeData> = {
value: 'byok',
@@ -483,31 +486,11 @@ function VoiceInputServiceSourceCard() {
}))
), [asrProfiles, credentialSourceLabel, t]);
- const refinerOptions = useMemo<ReadonlyArray<VoiceInputSelectOption<string>>>(() => (
- refinerProfiles.map((profile) => ({
- value: profile.id,
- label: profile.model,
- description: credentialSourceLabel(profile),
- }))
- ), [refinerProfiles, credentialSourceLabel]);
-
- // Explicit BYOK fallback (opt-in): "none" keeps the primary running alone,
- // mirroring the single-credential reality of most BYOK setups.
- const refinerFallbackValue = selection?.refinerProviderChain?.[1] ?? '';
- const refinerFallbackOptions = useMemo<ReadonlyArray<VoiceInputSelectOption<string>>>(() => ([
- {
- value: '',
- label: t('settings.voiceInput.serviceSource.refinerFallback.none'),
- description: t('settings.voiceInput.serviceSource.refinerFallback.noneDescription'),
- },
- ...refinerProfiles
- .filter((profile) => profile.id !== selection?.refinerProvider)
- .map((profile) => ({
- value: profile.id,
- label: profile.model,
- description: credentialSourceLabel(profile),
- })),
- ]), [refinerProfiles, selection?.refinerProvider, credentialSourceLabel, t]);
+ const cannotRefineWithAuxiliary = Boolean(
+ selection
+ && selection.refinerProviderChainSource === 'configured'
+ && selection.refinerProviderChain.length === 0,
+ );
// BYOK credential problems map to i18n by credential source instead of the
// raw main-process message (which is an untranslated profile constant).
@@ -837,26 +820,26 @@ function VoiceInputServiceSourceCard() {
<VoiceInputInlineSettingRow
label={t('settings.voiceInput.serviceSource.refiner.label')}
- hint={t('settings.voiceInput.serviceSource.refiner.hint')}
- >
- <VoiceInputSelect
- value={selection?.refinerProvider ?? ''}
- options={refinerOptions}
- onChange={(value) => void setRefinerProvider(value)}
- ariaLabel={t('settings.voiceInput.serviceSource.refiner.ariaLabel')}
- />
- </VoiceInputInlineSettingRow>
-
- <VoiceInputInlineSettingRow
- label={t('settings.voiceInput.serviceSource.refinerFallback.label')}
- hint={t('settings.voiceInput.serviceSource.refinerFallback.hint')}
+ hint={
+ cannotRefineWithAuxiliary
+ ? t('settings.voiceInput.serviceSource.refiner.cannotRefine')
+ : t('settings.voiceInput.serviceSource.refiner.followHint')
+ }
>
- <VoiceInputSelect
- value={refinerFallbackValue}
- options={refinerFallbackOptions}
- onChange={(value) => void setRefinerFallbackProvider(value)}
- ariaLabel={t('settings.voiceInput.serviceSource.refinerFallback.ariaLabel')}
- />
+ <div className="flex items-center justify-end gap-2">
+ <span className="text-12 leading-[1.4] text-[var(--settings-section-sublabel)]">
+ {t('settings.voiceInput.serviceSource.refiner.followAuxiliary')}
+ </span>
+ <button
+ type="button"
+ onClick={openPersonalizationTab}
+ className={cn(
+ 'h-8 shrink-0 rounded-full border border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] px-3 text-12 font-medium text-[var(--settings-section-title)] outline-none transition-colors hover:border-[var(--settings-input-border-focus)] focus-visible:border-[var(--settings-input-border-focus)]',
+ )}
+ >
+ {t('settings.voiceInput.serviceSource.refiner.openAuxiliary')}
+ </button>
+ </div>
</VoiceInputInlineSettingRow>
{byokCredentialErrorText ? (
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/AuxiliaryModelSection.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/AuxiliaryModelSection.test.tsx
index 68f1c6272b..eff4f577cc 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/AuxiliaryModelSection.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/__tests__/AuxiliaryModelSection.test.tsx
@@ -1,18 +1,22 @@
// @vitest-environment jsdom
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import type { AuxiliaryModelSettingsState } from '../../../../shared/auxiliaryModelSettings';
+import type {
+ AuxiliaryModelOption,
+ AuxiliaryModelSettingsState,
+} from '../../../../shared/auxiliaryModelSettings';
+import { AUTO_AUXILIARY_MODEL_CHAIN } from '../../../../shared/auxiliaryModelChain';
-const TITLE_PIN = 'cat:openrouter:codex:openai/gpt-5-mini';
-const RECOMMENDATION_PIN = 'cat:anthropic:claude-code:claude-haiku-4-5';
+const PREFERRED_PIN = 'cat:openrouter:codex:openai/gpt-5-mini';
+const FALLBACK_PIN = 'cat:anthropic:claude-code:claude-haiku-4-5';
const h = vi.hoisted(() => ({
get: vi.fn(),
set: vi.fn(),
toastError: vi.fn(),
- isModelEnabled: vi.fn(),
+ authMode: 'cloud' as 'signed-out' | 'local' | 'cloud',
}));
vi.mock('react-i18next', () => ({
@@ -27,44 +31,58 @@ vi.mock('@/lib/toast', () => ({
toast: { error: h.toastError },
}));
-vi.mock('@/state/modelVisibilityPrefs', () => ({
- isModelEnabled: h.isModelEnabled,
- useModelVisibilityVersion: () => 0,
+vi.mock('@/contexts/AuthContext', () => ({
+ useAuth: () => ({ mode: h.authMode }),
+}));
+
+vi.mock('@/components/ui/tooltip', () => ({
+ Tip: ({ children }: { children: React.ReactElement }) => children,
}));
vi.mock('@/cindy-brain/OneshotModelPinPicker', () => ({
OneshotModelPinPicker: ({
value,
- onChange,
- ariaLabel,
disabled,
+ defaultOptionLabel,
+ groupByProvider,
options,
+ onChange,
+ ariaLabel,
}: {
value?: string;
- onChange: (pin: string | null) => void;
ariaLabel: string;
disabled?: boolean;
- options: Array<{ id: string; available?: boolean }>;
+ defaultOptionLabel?: string;
+ groupByProvider?: boolean;
+ options: readonly AuxiliaryModelOption[];
+ onChange: (pin: string | null) => void;
}) => {
- const titleRow = ariaLabel.includes('sessionTitle');
- const pin = titleRow ? TITLE_PIN : RECOMMENDATION_PIN;
- const displayedOptions = options.filter(
- (option) => option.available !== false || option.id === value,
- );
return (
<div>
- <span>{`${ariaLabel}:${value ?? 'automatic'}`}</span>
- <span data-testid={`${ariaLabel}:options`}>
- {displayedOptions.map((option) => `${option.id}:${option.available !== false}`).join('|')}
+ <span>{`${ariaLabel}:${value ?? defaultOptionLabel ?? 'empty'}`}</span>
+ <span data-testid={`${ariaLabel}:value`}>{value ?? 'empty'}</span>
+ <span data-testid={`${ariaLabel}:panel`}>
+ {`${Boolean(groupByProvider)}:${options.map((option) => option.group).join(',')}`}
</span>
+ {options.map((option) => (
+ <span key={option.id} data-testid={`${ariaLabel}:option:${option.id}`} />
+ ))}
<button
type="button"
aria-label={`${ariaLabel}:select`}
disabled={disabled}
- onClick={() => onChange(pin)}
+ onClick={() => onChange(PREFERRED_PIN)}
>
select
</button>
+ <button
+ type="button"
+ aria-label={`${ariaLabel}:select-fallback`}
+ disabled={disabled}
+ onClick={() => onChange(FALLBACK_PIN)}
+ >
+ select fallback
+ </button>
<button
type="button"
aria-label={`${ariaLabel}:automatic`}
@@ -82,19 +100,62 @@ import { AuxiliaryModelSection } from '../AuxiliaryModelSection';
function state(partial: Partial<AuxiliaryModelSettingsState> = {}): AuxiliaryModelSettingsState {
return {
- sessionTitleModel: null,
- promptRecommendationModel: null,
+ models: [],
isCustomized: false,
customizedKeys: [],
- defaults: {
- sessionTitleModel: null,
- promptRecommendationModel: null,
- },
+ defaults: { models: [] },
options: [],
...partial,
};
}
+const SUPPLIER_OPTIONS: AuxiliaryModelOption[] = [
+ {
+ id: PREFERRED_PIN,
+ label: 'GPT-5 mini · OpenRouter',
+ group: 'OpenRouter',
+ providerId: 'openrouter',
+ agentKind: 'codex',
+ modelId: 'openai/gpt-5-mini',
+ modelName: 'GPT-5 mini',
+ budget: false,
+ subscription: false,
+ agentSuffix: 'Codex',
+ available: true,
+ },
+ {
+ id: FALLBACK_PIN,
+ label: 'Claude Haiku 4.5 · Anthropic',
+ group: 'Anthropic',
+ providerId: 'anthropic',
+ agentKind: 'claude-code',
+ modelId: 'claude-haiku-4-5',
+ modelName: 'Claude Haiku 4.5',
+ budget: false,
+ subscription: false,
+ agentSuffix: 'Claude Code',
+ available: true,
+ },
+];
+
+const AUTOMATIC_OPTIONS: AuxiliaryModelOption[] = AUTO_AUXILIARY_MODEL_CHAIN.map(
+ (id, index) => ({
+ id,
+ label: ['DeepSeek V4 Flash', 'Hy3', 'Qwen3.8 Flash'][index]! + ' · Cindy AI',
+ group: 'Cindy AI',
+ providerId: 'xd',
+ agentKind: 'codex',
+ modelId: ['deepseek/deepseek-v4-flash', 'tencent/hy3', 'qwen/qwen3.8-flash'][index]!,
+ modelName: ['DeepSeek V4 Flash', 'Hy3', 'Qwen3.8 Flash'][index]!,
+ budget: false,
+ subscription: false,
+ agentSuffix: 'Codex',
+ available: true,
+ }),
+);
+
+const OPTIONS: AuxiliaryModelOption[] = [...AUTOMATIC_OPTIONS, ...SUPPLIER_OPTIONS];
+
function installApi(): void {
Object.defineProperty(window, 'electronAPI', {
configurable: true,
@@ -107,147 +168,288 @@ function installApi(): void {
});
}
+async function selectMode(modeKey: string): Promise<void> {
+ fireEvent.click(
+ await screen.findByRole('combobox', { name: 'settings.auxiliaryModels.title' }),
+ );
+ const option = await screen.findByRole('option', { name: modeKey });
+ await act(async () => {
+ fireEvent.click(option);
+ });
+}
+
describe('AuxiliaryModelSection', () => {
beforeEach(() => {
vi.clearAllMocks();
+ h.authMode = 'cloud';
+ Object.defineProperty(Element.prototype, 'scrollIntoView', {
+ configurable: true,
+ value: vi.fn(),
+ });
installApi();
- h.isModelEnabled.mockReturnValue(true);
- h.get.mockResolvedValue(state());
- h.set.mockImplementation(async (patch: Partial<AuxiliaryModelSettingsState>) => state(patch));
+ h.get.mockResolvedValue(state({ options: OPTIONS }));
+ h.set.mockImplementation(async (patch: { models?: string[] }) => {
+ const models = patch.models ?? [];
+ return state({
+ models,
+ isCustomized: models.length > 0,
+ customizedKeys: models.length > 0 ? ['models'] : [],
+ options: OPTIONS,
+ });
+ });
});
- it('renders separate controls for task naming and prompt recommendations', async () => {
+ it('renders a persistent automatic/custom mode selector above the automatic chain', async () => {
render(<AuxiliaryModelSection />);
- expect(await screen.findByText('settings.auxiliaryModels.sessionTitle.label')).toBeTruthy();
- expect(screen.getByText('settings.auxiliaryModels.promptRecommendation.label')).toBeTruthy();
+ expect(
+ (await screen.findByRole('combobox', { name: 'settings.auxiliaryModels.title' })).textContent,
+ ).toContain('settings.auxiliaryModels.automatic');
+ expect(screen.getByText(/settings.auxiliaryModels.chain.cindyDeepseekV4Flash/)).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'settings.auxiliaryModels.customize' })).toBeNull();
+ expect(screen.queryByText('settings.auxiliaryModels.preferred.label')).toBeNull();
});
- it('writes each model choice to its own independent key', async () => {
+ it('treats a GET payload without models as automatic instead of crashing', async () => {
+ h.get.mockResolvedValue({
+ models: [],
+ isCustomized: false,
+ customizedKeys: [],
+ defaults: { models: [] },
+ options: [],
+ } as AuxiliaryModelSettingsState);
+
render(<AuxiliaryModelSection />);
- fireEvent.click(
- await screen.findByRole('button', {
- name: 'settings.auxiliaryModels.sessionTitle.ariaLabel:select',
+ expect(
+ (await screen.findByRole('combobox', { name: 'settings.auxiliaryModels.title' })).textContent,
+ ).toContain('settings.auxiliaryModels.automatic');
+ });
+
+ it('opens the three custom slots without persisting and keeps the mode selector', async () => {
+ render(<AuxiliaryModelSection />);
+
+ await selectMode('settings.auxiliaryModels.customize');
+
+ expect(await screen.findByText('settings.auxiliaryModels.preferred.label')).toBeTruthy();
+ expect(screen.getByText('settings.auxiliaryModels.fallback1.label')).toBeTruthy();
+ expect(screen.getByText('settings.auxiliaryModels.fallback2.label')).toBeTruthy();
+ expect(
+ screen.getByRole('combobox', { name: 'settings.auxiliaryModels.title' }).textContent,
+ ).toContain('settings.auxiliaryModels.customize');
+ expect(screen.getByTestId('settings.auxiliaryModels.preferred.ariaLabel:value').textContent).toBe(
+ 'cat:xd:codex:deepseek/deepseek-v4-flash',
+ );
+ expect(screen.getByTestId('settings.auxiliaryModels.fallback1.ariaLabel:value').textContent).toBe(
+ 'cat:xd:codex:tencent/hy3',
+ );
+ expect(screen.getByTestId('settings.auxiliaryModels.fallback2.ariaLabel:value').textContent).toBe(
+ 'cat:xd:codex:qwen/qwen3.8-flash',
+ );
+ expect(screen.queryByText('settings.defaults.customizedBadge')).toBeNull();
+ const modeTrigger = screen.getByRole('combobox', { name: 'settings.auxiliaryModels.title' });
+ const restoreButton = screen.getByRole('button', { name: 'settings.defaults.restore' });
+ expect(restoreButton).toBeTruthy();
+ expect(
+ modeTrigger.compareDocumentPosition(restoreButton) & Node.DOCUMENT_POSITION_PRECEDING,
+ ).toBeTruthy();
+ expect(screen.getAllByText('settings.auxiliaryModels.customize')).toHaveLength(1);
+ expect(
+ screen.getByTestId('settings.auxiliaryModels.preferred.ariaLabel:panel').textContent,
+ ).toBe('true:Cindy AI,OpenRouter,Anthropic');
+ expect(h.set).not.toHaveBeenCalled();
+ });
+
+ it('filters unavailable automatic routes from a first-time custom draft', async () => {
+ h.get.mockResolvedValue(
+ state({
+ options: OPTIONS.map((option) =>
+ option.id === AUTO_AUXILIARY_MODEL_CHAIN[0]
+ ? { ...option, available: false }
+ : option,
+ ),
}),
);
- await waitFor(() => expect(h.set).toHaveBeenLastCalledWith({ sessionTitleModel: TITLE_PIN }));
+ render(<AuxiliaryModelSection />);
+
+ await selectMode('settings.auxiliaryModels.customize');
+
+ expect(screen.getByTestId('settings.auxiliaryModels.preferred.ariaLabel:value').textContent).toBe(
+ AUTO_AUXILIARY_MODEL_CHAIN[1],
+ );
+ expect(screen.getByTestId('settings.auxiliaryModels.fallback1.ariaLabel:value').textContent).toBe(
+ AUTO_AUXILIARY_MODEL_CHAIN[2],
+ );
+ expect(screen.getByTestId('settings.auxiliaryModels.fallback2.ariaLabel:value').textContent).toBe(
+ 'empty',
+ );
+ expect(h.set).not.toHaveBeenCalled();
+ });
+
+ it('does not seed Cindy AI defaults while signed out', async () => {
+ h.authMode = 'signed-out';
+ render(<AuxiliaryModelSection />);
+
+ await selectMode('settings.auxiliaryModels.customize');
+ expect(screen.getByTestId('settings.auxiliaryModels.preferred.ariaLabel:value').textContent).toBe(
+ 'empty',
+ );
+ expect(screen.getByText('settings.auxiliaryModels.signInHint')).toBeTruthy();
+ expect(h.set).not.toHaveBeenCalled();
+ });
+
+ it('returns to automatic without persisting when restore is used while drafting', async () => {
+ render(<AuxiliaryModelSection />);
+
+ await selectMode('settings.auxiliaryModels.customize');
+ fireEvent.click(await screen.findByRole('button', { name: 'settings.defaults.restore' }));
+
+ expect(
+ (await screen.findByRole('combobox', { name: 'settings.auxiliaryModels.title' })).textContent,
+ ).toContain('settings.auxiliaryModels.automatic');
+ expect(screen.queryByText('settings.auxiliaryModels.preferred.label')).toBeNull();
+ expect(h.set).not.toHaveBeenCalled();
+ });
+
+ it('persists the changed preferred pin while keeping the other automatic defaults', async () => {
+ render(<AuxiliaryModelSection />);
+
+ await selectMode('settings.auxiliaryModels.customize');
fireEvent.click(
- screen.getByRole('button', {
- name: 'settings.auxiliaryModels.promptRecommendation.ariaLabel:select',
+ await screen.findByRole('button', {
+ name: 'settings.auxiliaryModels.preferred.ariaLabel:select',
}),
);
+
await waitFor(() =>
expect(h.set).toHaveBeenLastCalledWith({
- promptRecommendationModel: RECOMMENDATION_PIN,
+ models: [PREFERRED_PIN, 'cat:xd:codex:tencent/hy3', 'cat:xd:codex:qwen/qwen3.8-flash'],
+ }),
+ );
+ });
+
+ it('shows all supplier groups while keeping the exact selected catalog pin', async () => {
+ h.get.mockResolvedValue(
+ state({
+ models: [PREFERRED_PIN],
+ isCustomized: true,
+ customizedKeys: ['models'],
+ options: SUPPLIER_OPTIONS,
+ }),
+ );
+ render(<AuxiliaryModelSection />);
+
+ expect(
+ (await screen.findByTestId('settings.auxiliaryModels.preferred.ariaLabel:panel')).textContent,
+ ).toBe('true:OpenRouter,Anthropic');
+ expect(
+ screen.getByRole('combobox', { name: 'settings.auxiliaryModels.title' }).textContent,
+ ).toContain('settings.auxiliaryModels.customize');
+
+ expect(h.set).not.toHaveBeenCalled();
+ });
+
+ it('disables a later slot until its preceding slot has a model', async () => {
+ h.get.mockResolvedValue(
+ state({
+ models: [PREFERRED_PIN],
+ isCustomized: true,
+ customizedKeys: ['models'],
+ options: OPTIONS,
}),
);
+ render(<AuxiliaryModelSection />);
+
+ const fallback2Select = await screen.findByRole('button', {
+ name: 'settings.auxiliaryModels.fallback2.ariaLabel:select',
+ });
+ expect((fallback2Select as HTMLButtonElement).disabled).toBe(true);
+
+ fireEvent.click(fallback2Select);
+ expect(h.set).not.toHaveBeenCalled();
});
- it('restores automatic routing with a null override', async () => {
+ it('does not offer or persist a model already selected in another slot', async () => {
h.get.mockResolvedValue(
state({
- sessionTitleModel: TITLE_PIN,
- promptRecommendationModel: RECOMMENDATION_PIN,
+ models: [PREFERRED_PIN, FALLBACK_PIN],
+ isCustomized: true,
+ customizedKeys: ['models'],
+ options: OPTIONS,
}),
);
render(<AuxiliaryModelSection />);
+ expect(
+ screen.queryByTestId(
+ `settings.auxiliaryModels.preferred.ariaLabel:option:${FALLBACK_PIN}`,
+ ),
+ ).toBeNull();
+ expect(
+ screen.queryByTestId(
+ `settings.auxiliaryModels.fallback1.ariaLabel:option:${PREFERRED_PIN}`,
+ ),
+ ).toBeNull();
+
fireEvent.click(
await screen.findByRole('button', {
- name: 'settings.auxiliaryModels.sessionTitle.ariaLabel:automatic',
+ name: 'settings.auxiliaryModels.fallback1.ariaLabel:select',
}),
);
- await waitFor(() => expect(h.set).toHaveBeenCalledWith({ sessionTitleModel: null }));
+ expect(h.set).not.toHaveBeenCalled();
});
- it('does not offer models hidden from the regular model selector', async () => {
- const hiddenPin = 'cat:xd:codex:claude-opus-5';
- const visiblePin = 'cat:xd:codex:deepseek/deepseek-v4-flash';
- h.isModelEnabled.mockImplementation(
- (_agent: string, _providerId: string, model: { id: string }) =>
- model.id !== 'claude-opus-5',
- );
+ it('clears a saved custom chain when automatic is selected', async () => {
h.get.mockResolvedValue(
state({
- options: [
- {
- id: hiddenPin,
- label: 'Claude Opus 5 · XD Gateway',
- group: 'XD Gateway',
- providerId: 'xd',
- agentKind: 'codex',
- modelId: 'claude-opus-5',
- modelName: 'Claude Opus 5',
- agentSuffix: 'Codex',
- budget: false,
- subscription: false,
- available: true,
- },
- {
- id: visiblePin,
- label: 'DeepSeek V4 Flash · XD Gateway',
- group: 'XD Gateway',
- providerId: 'xd',
- agentKind: 'codex',
- modelId: 'deepseek/deepseek-v4-flash',
- modelName: 'DeepSeek V4 Flash',
- agentSuffix: 'Codex',
- budget: false,
- subscription: false,
- available: true,
- },
- ],
+ models: [PREFERRED_PIN, FALLBACK_PIN],
+ isCustomized: true,
+ customizedKeys: ['models'],
+ options: OPTIONS,
}),
);
-
render(<AuxiliaryModelSection />);
- const titleOptions = await screen.findByTestId(
- 'settings.auxiliaryModels.sessionTitle.ariaLabel:options',
+ await selectMode('settings.auxiliaryModels.automatic');
+
+ await waitFor(() => {
+ expect(h.set).toHaveBeenCalledWith({ models: [] });
+ expect(
+ screen.getByRole('combobox', { name: 'settings.auxiliaryModels.title' }).textContent,
+ ).toContain('settings.auxiliaryModels.automatic');
+ });
+ });
+
+ it('restores automatic routing when the preferred slot is cleared', async () => {
+ h.get.mockResolvedValue(
+ state({
+ models: [PREFERRED_PIN, FALLBACK_PIN],
+ isCustomized: true,
+ customizedKeys: ['models'],
+ }),
);
- const recommendationOptions = screen.getByTestId(
- 'settings.auxiliaryModels.promptRecommendation.ariaLabel:options',
+ render(<AuxiliaryModelSection />);
+
+ fireEvent.click(
+ await screen.findByRole('button', {
+ name: 'settings.auxiliaryModels.preferred.ariaLabel:automatic',
+ }),
);
- expect(titleOptions.textContent).toBe(`${visiblePin}:true`);
- expect(recommendationOptions.textContent).toBe(`${visiblePin}:true`);
+ await waitFor(() => expect(h.set).toHaveBeenCalledWith({ models: [] }));
});
- it('keeps a selected hidden model visible only as an unavailable value', async () => {
- const hiddenPin = 'cat:xd:codex:claude-opus-5';
- h.isModelEnabled.mockReturnValue(false);
+ it('persists an empty list when restore is used on a saved custom chain', async () => {
h.get.mockResolvedValue(
state({
- sessionTitleModel: hiddenPin,
- options: [
- {
- id: hiddenPin,
- label: 'Claude Opus 5 · XD Gateway',
- group: 'XD Gateway',
- providerId: 'xd',
- agentKind: 'codex',
- modelId: 'claude-opus-5',
- modelName: 'Claude Opus 5',
- agentSuffix: 'Codex',
- defaultEnabled: false,
- budget: false,
- subscription: false,
- available: true,
- },
- ],
+ models: [PREFERRED_PIN],
+ isCustomized: true,
+ customizedKeys: ['models'],
}),
);
-
render(<AuxiliaryModelSection />);
- expect(
- (await screen.findByTestId('settings.auxiliaryModels.sessionTitle.ariaLabel:options'))
- .textContent,
- ).toBe(`${hiddenPin}:false`);
- expect(
- screen.getByTestId('settings.auxiliaryModels.promptRecommendation.ariaLabel:options')
- .textContent,
- ).toBe('');
+ fireEvent.click(await screen.findByRole('button', { name: 'settings.defaults.restore' }));
+ await waitFor(() => expect(h.set).toHaveBeenCalledWith({ models: [] }));
});
});
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
index de3d726f62..cf55621d69 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
@@ -51,6 +51,8 @@ vi.mock('react-i18next', () => ({
'settings.ghosts.detail.collapseInfoValue': `Collapse ${String(options?.label ?? '')}`,
'settings.ghosts.detail.panelNotDocked': 'Not docked',
'settings.ghosts.detail.cindyPrefs.noModels': 'No models available',
+ 'settings.providers.openai.title': 'OpenAI',
+ 'settings.providers.xd.title': 'Cindy AI',
'settings.defaults.restore': 'Restore default',
'settings.ghosts.detail.oauthScopeStale':
'This authorization does not include newly added permissions. Reconnect to enable them.',
@@ -790,8 +792,8 @@ describe('Ghost plugin detail sections', () => {
options: [
{
id: 'cat:xd:codex:codex/gpt-5.5',
- label: 'Codex · GPT 5.5 折扣 · GW',
- group: 'GW',
+ label: 'Codex · GPT 5.5 折扣 · Cindy AI',
+ group: 'Cindy AI',
providerId: 'xd',
agentKind: 'codex',
modelId: 'codex/gpt-5.5',
@@ -868,7 +870,7 @@ describe('Ghost plugin detail sections', () => {
fireEvent.click(agentList.querySelector('[data-agent-kind="codex"]')!);
let codexModels = await screen.findByRole('listbox');
- expect(within(codexModels).getByText('GW')).toBeTruthy();
+ expect(within(codexModels).getByText('Cindy AI')).toBeTruthy();
expect(within(codexModels).getByText('OpenAI')).toBeTruthy();
expect(codexModels.querySelector('[data-pin-id*="claude-code"]')).toBeNull();
@@ -931,8 +933,8 @@ describe('Ghost plugin detail sections', () => {
options: [
{
id: 'cat:xd:codex:codex/gpt-5.5',
- label: 'Codex · GPT 5.5 折扣 · GW',
- group: 'GW',
+ label: 'Codex · GPT 5.5 折扣 · Cindy AI',
+ group: 'Cindy AI',
providerId: 'xd',
agentKind: 'codex',
modelId: 'codex/gpt-5.5',
@@ -991,8 +993,8 @@ describe('Ghost plugin detail sections', () => {
options: [
{
id: 'cat:xd:codex:codex/gpt-5.5',
- label: 'Codex · GPT 5.5 折扣 · GW',
- group: 'GW',
+ label: 'Codex · GPT 5.5 折扣 · Cindy AI',
+ group: 'Cindy AI',
providerId: 'xd',
agentKind: 'codex',
modelId: 'codex/gpt-5.5',
diff --git a/apps/desktop/src/renderer/hooks/useVoiceInputUsageStats.ts b/apps/desktop/src/renderer/hooks/useVoiceInputUsageStats.ts
index 2ff57d0061..26580ada0f 100644
--- a/apps/desktop/src/renderer/hooks/useVoiceInputUsageStats.ts
+++ b/apps/desktop/src/renderer/hooks/useVoiceInputUsageStats.ts
@@ -192,7 +192,7 @@ function estimateRefineUsd(
let accountedUsage: VoiceInputRefinementTokenDelta = {};
let totalUsd = 0;
for (const [provider, usage] of Object.entries(stats.refinementTokensByProvider)) {
- if (!isVoiceInputRefinerProviderKind(provider)) continue;
+ if (!usage || !isVoiceInputRefinerProviderKind(provider)) continue;
totalUsd += estimateVoiceInputRefinerCostUsd(getVoiceInputRefinerProfile(provider), usage);
accountedUsage = addTokenUsage(accountedUsage, usage);
}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index f74d073c91..89d9a55c3c 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -1001,16 +1001,13 @@
},
"refiner": {
"label": "Refinement model",
- "hint": "Model used to clean up dictated text.",
+ "hint": "Follows the auxiliary model.",
+ "followAuxiliary": "Follow auxiliary model",
+ "followHint": "Refinement follows Settings → Personalization → Auxiliary models. Cindy-hosted voice is unchanged; refinement still runs on the server.",
+ "openAuxiliary": "Open auxiliary models",
+ "cannotRefine": "The current auxiliary models cannot refine speech (for example Claude Messages only), so this dictation will not be refined.",
"ariaLabel": "Voice refinement model"
},
- "refinerFallback": {
- "label": "Refinement fallback",
- "hint": "Backup model used only when the primary refiner fails; off by default.",
- "ariaLabel": "Voice refinement fallback model selection",
- "none": "No fallback",
- "noneDescription": "Keep the raw transcript when the primary model fails"
- },
"customAsr": {
"optionLabel": "Custom realtime ASR",
"optionDescription": "Uses a dedicated speech-recognition WebSocket and API key",
@@ -2679,28 +2676,40 @@
},
"auxiliaryModels": {
"title": "Auxiliary models",
- "description": "Choose one Agent and model pair for automatic task naming and another for 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)"
- },
+ "description": "Used for automatic task naming and AI rename, composer prompt suggestions, Help, pinned task summaries, IM / Feishu titles and group-context checks, scheduled-task scripts, plugin quick Q&A “follow default”, and BYOK voice refinement.",
+ "automatic": "Automatic recommendation",
+ "customize": "Custom",
+ "preferred": {
+ "label": "Preferred",
+ "description": "The first model used for short auxiliary text.",
+ "ariaLabel": "Choose the preferred auxiliary model"
+ },
+ "fallback1": {
+ "label": "Fallback 1",
+ "description": "Used if the preferred model is unavailable. Optional.",
+ "ariaLabel": "Choose the first fallback auxiliary model"
+ },
+ "fallback2": {
+ "label": "Fallback 2",
+ "description": "Used if the first two models are unavailable. Optional.",
+ "ariaLabel": "Choose the second fallback auxiliary model"
+ },
+ "emptySlot": "Not selected",
+ "customHint": "A custom chain is tried in this order only. If none of them work, Cindy will not switch to another model.",
+ "signInHint": "Sign in to Cindy to use the automatic recommendations. While signed out, choose a configured model from another provider under Custom.",
"chooseAgent": "Choose an Agent",
"backToAgents": "Back to Agent selection",
- "explicitRouteHint": "An explicit selection uses only that Agent and model. If unavailable, Cindy will not switch automatically.",
"searchPlaceholder": "Search models or providers",
"noResults": "No available models",
"unavailable": "Currently unavailable",
"budget": "Discount",
"subscription": "Subscription",
- "saveFailed": "Failed to save auxiliary model settings"
+ "saveFailed": "Failed to save auxiliary model settings",
+ "chain": {
+ "cindyHy3": "Hy3",
+ "cindyDeepseekV4Flash": "DeepSeek v4 flash",
+ "cindyQwen38Flash": "Qwen 3.8 Flash"
+ }
},
"compaction": {
"title": "Context compaction",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index e36972f39c..cfe124d1a2 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -1001,15 +1001,12 @@
},
"refiner": {
"label": "整えモデル",
- "hint": "話し言葉のテキストを整えるモデル。",
- "ariaLabel": "音声整えモデルの選択"
- },
- "refinerFallback": {
- "label": "整文フォールバック",
- "hint": "メインの整文モデルが失敗したときのみ使う予備モデル。既定では無効。",
- "ariaLabel": "音声整文フォールバックモデルの選択",
- "none": "フォールバックなし",
- "noneDescription": "メインモデルが失敗した場合は元の認識テキストを保持"
+ "hint": "補助モデルに従います。",
+ "followAuxiliary": "補助モデルに従う",
+ "followHint": "整えモデルは「設定 → パーソナライズ → 補助モデル」の順に従います。Cindy ホストの音声は影響を受けず、整えはサーバー側のままです。",
+ "openAuxiliary": "補助モデルへ",
+ "cannotRefine": "現在の補助モデルでは音声を整えられません(Claude Messages のみなど)。今回は整えません。",
+ "ariaLabel": "音声整えモデル"
},
"customAsr": {
"optionLabel": "カスタムリアルタイム ASR",
@@ -2678,28 +2675,40 @@
},
"auxiliaryModels": {
"title": "補助モデル",
- "description": "タスクの自動命名と入力欄のおすすめプロンプトに、それぞれ Agent とモデルの組み合わせを指定します。",
- "sessionTitle": {
- "label": "タスクの自動命名",
- "description": "Claude Code、Codex、Pi のタスクと、AI による手動の名前変更に適用されます。",
- "ariaLabel": "タスクの自動命名モデルを選択",
- "automatic": "自動選択(現在のタスクに従う)"
- },
- "promptRecommendation": {
- "label": "入力欄のおすすめプロンプト",
- "description": "「ヒント」で入力欄のおすすめを有効にした場合のみ使用します。",
- "ariaLabel": "入力欄のおすすめプロンプト用モデルを選択",
- "automatic": "自動選択(現在のルーティングを維持)"
- },
+ "description": "タスクの自動命名と AI による名前変更、入力欄のおすすめプロンプト、Help、ピン留めタスクの要約、IM / 飛書のタイトルとグループ文脈判定、スケジュール済みタスクのスクリプト、プラグインのクイック Q&A「デフォルトに従う」、および自分のキーによる音声整えに使います。",
+ "automatic": "自動おすすめ",
+ "customize": "カスタム",
+ "preferred": {
+ "label": "優先",
+ "description": "短い補助テキストで最初に使うモデル。",
+ "ariaLabel": "優先する補助モデルを選択"
+ },
+ "fallback1": {
+ "label": "予備 1",
+ "description": "優先モデルが使えないときに使うモデル。空でもかまいません。",
+ "ariaLabel": "1 番目の予備補助モデルを選択"
+ },
+ "fallback2": {
+ "label": "予備 2",
+ "description": "最初の 2 つが使えないときに使うモデル。空でもかまいません。",
+ "ariaLabel": "2 番目の予備補助モデルを選択"
+ },
+ "emptySlot": "未選択",
+ "customHint": "カスタム後は選んだ順にだけ試します。どれも使えない場合、別のモデルへは切り替えません。",
+ "signInHint": "Cindy にログインすると自動おすすめを使えます。未ログイン時は「カスタム」で設定済みの他のプロバイダーのモデルを選択してください。",
"chooseAgent": "Agent を選択",
"backToAgents": "Agent の選択に戻る",
- "explicitRouteHint": "明示的に指定した場合は、その Agent とモデルだけを使用します。利用できなくても自動では切り替えません。",
"searchPlaceholder": "モデルまたはプロバイダーを検索",
"noResults": "利用可能なモデルがありません",
"unavailable": "現在利用不可",
"budget": "割引",
"subscription": "サブスクリプション",
- "saveFailed": "補助モデル設定を保存できませんでした"
+ "saveFailed": "補助モデル設定を保存できませんでした",
+ "chain": {
+ "cindyHy3": "Hy3",
+ "cindyDeepseekV4Flash": "DeepSeek v4 flash",
+ "cindyQwen38Flash": "Qwen 3.8 Flash"
+ }
},
"compaction": {
"title": "コンテキスト圧縮",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 625ab09530..ebdcc9fb9e 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -1001,15 +1001,12 @@
},
"refiner": {
"label": "정리 모델",
- "hint": "구어체 텍스트를 정리하는 모델.",
- "ariaLabel": "음성 정리 모델 선택"
- },
- "refinerFallback": {
- "label": "다듬기 대체 모델",
- "hint": "기본 다듬기 모델이 실패할 때만 사용하는 대체 모델. 기본적으로 사용하지 않음.",
- "ariaLabel": "음성 다듬기 대체 모델 선택",
- "none": "대체 모델 없음",
- "noneDescription": "기본 모델이 실패하면 원본 인식 텍스트를 유지"
+ "hint": "보조 모델을 따릅니다.",
+ "followAuxiliary": "보조 모델 따르기",
+ "followHint": "정리 모델은 「설정 → 개인화 → 보조 모델」 순서를 따릅니다. Cindy 호스팅 음성은 영향을 받지 않으며, 정리는 서버에서 계속 실행됩니다.",
+ "openAuxiliary": "보조 모델로 이동",
+ "cannotRefine": "현재 보조 모델로는 음성을 다듬을 수 없습니다(예: Claude Messages만 해당). 이번에는 다듬지 않습니다.",
+ "ariaLabel": "음성 정리 모델"
},
"customAsr": {
"optionLabel": "사용자 지정 실시간 ASR",
@@ -2678,28 +2675,40 @@
},
"auxiliaryModels": {
"title": "보조 모델",
- "description": "작업 자동 이름 지정과 입력창 추천 프롬프트에 각각 Agent와 모델 조합을 지정합니다.",
- "sessionTitle": {
- "label": "작업 자동 이름 지정",
- "description": "Claude Code, Codex, Pi 작업과 AI 수동 이름 바꾸기에 적용됩니다.",
- "ariaLabel": "작업 자동 이름 지정 모델 선택",
- "automatic": "자동 선택(현재 작업 따름)"
- },
- "promptRecommendation": {
- "label": "입력창 추천 프롬프트",
- "description": "‘팁’에서 입력창 추천을 켠 경우에만 사용합니다.",
- "ariaLabel": "입력창 추천 프롬프트 모델 선택",
- "automatic": "자동 선택(현재 라우팅 유지)"
- },
+ "description": "작업 자동 이름 지정과 AI 이름 바꾸기, 입력창 추천 프롬프트, Help, 고정된 작업 요약, IM / Feishu 제목과 그룹 맥락 판단, 예약 작업 스크립트, 플러그인 빠른 Q&A의 「기본값 따르기」, 그리고 자체 키 음성 다듬기에 사용합니다.",
+ "automatic": "자동 추천",
+ "customize": "사용자 지정",
+ "preferred": {
+ "label": "기본",
+ "description": "짧은 보조 텍스트에 먼저 사용하는 모델.",
+ "ariaLabel": "기본 보조 모델 선택"
+ },
+ "fallback1": {
+ "label": "대체 1",
+ "description": "기본 모델을 사용할 수 없을 때 쓰는 모델. 비워 둘 수 있습니다.",
+ "ariaLabel": "첫 번째 대체 보조 모델 선택"
+ },
+ "fallback2": {
+ "label": "대체 2",
+ "description": "앞의 두 모델을 모두 사용할 수 없을 때 쓰는 모델. 비워 둘 수 있습니다.",
+ "ariaLabel": "두 번째 대체 보조 모델 선택"
+ },
+ "emptySlot": "선택 안 함",
+ "customHint": "사용자 지정 후에는 선택한 순서대로만 시도합니다. 모두 사용할 수 없어도 다른 모델로 바꾸지 않습니다.",
+ "signInHint": "Cindy에 로그인하면 자동 추천을 사용할 수 있습니다. 로그인하지 않은 상태에서는 「사용자 지정」에서 설정된 다른 제공자의 모델을 선택하세요.",
"chooseAgent": "Agent 선택",
"backToAgents": "Agent 선택으로 돌아가기",
- "explicitRouteHint": "명시적으로 지정하면 해당 Agent와 모델만 사용합니다. 사용할 수 없어도 자동으로 전환하지 않습니다.",
"searchPlaceholder": "모델 또는 제공자 검색",
"noResults": "사용 가능한 모델이 없습니다",
"unavailable": "현재 사용할 수 없음",
"budget": "할인",
"subscription": "구독",
- "saveFailed": "보조 모델 설정을 저장하지 못했습니다"
+ "saveFailed": "보조 모델 설정을 저장하지 못했습니다",
+ "chain": {
+ "cindyHy3": "Hy3",
+ "cindyDeepseekV4Flash": "DeepSeek v4 flash",
+ "cindyQwen38Flash": "Qwen 3.8 Flash"
+ }
},
"compaction": {
"title": "컨텍스트 압축",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index b181b6e298..a53658c668 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -1001,15 +1001,12 @@
},
"refiner": {
"label": "润色模型",
- "hint": "整理口语文本使用的模型。",
- "ariaLabel": "语音润色模型选择"
- },
- "refinerFallback": {
- "label": "润色备选模型",
- "hint": "主润色模型失败时改用的备选;默认不启用。",
- "ariaLabel": "语音润色备选模型选择",
- "none": "不使用备选",
- "noneDescription": "主模型失败时直接保留原始识别文本"
+ "hint": "跟随辅助模型。",
+ "followAuxiliary": "跟随辅助模型",
+ "followHint": "润色模型跟随「设置 → 个性化 → 辅助模型」的顺序。Cindy 托管语音不受影响,润色仍在服务端。",
+ "openAuxiliary": "前往辅助模型",
+ "cannotRefine": "当前辅助模型无法用于语音润色(例如纯 Claude Messages),这次不润色。",
+ "ariaLabel": "语音润色模型"
},
"customAsr": {
"optionLabel": "自定义实时 ASR",
@@ -2678,28 +2675,40 @@
},
"auxiliaryModels": {
"title": "辅助模型",
- "description": "为任务自动命名和输入框推荐指令分别指定一组 Agent 和模型。",
- "sessionTitle": {
- "label": "任务自动命名",
- "description": "适用于 Claude Code、Codex、Pi 任务,以及手动 AI 重命名。",
- "ariaLabel": "选择任务自动命名模型",
- "automatic": "自动选择(跟随当前任务)"
- },
- "promptRecommendation": {
- "label": "输入框推荐指令",
- "description": "仅在“小技巧”中启用输入框推荐后调用。",
- "ariaLabel": "选择输入框推荐指令模型",
- "automatic": "自动选择(保持当前规则)"
- },
+ "description": "用于任务自动命名和 AI 重命名、输入框推荐指令、Help、置顶任务摘要、IM / 飞书标题与群上下文判断、定时任务脚本、插件快问快答的「跟随默认」,以及自带密钥的语音润色。",
+ "automatic": "自动推荐",
+ "customize": "自定义",
+ "preferred": {
+ "label": "首选",
+ "description": "轻量文本优先使用的模型。",
+ "ariaLabel": "选择首选辅助模型"
+ },
+ "fallback1": {
+ "label": "备选 1",
+ "description": "首选不可用时改用的模型,可留空。",
+ "ariaLabel": "选择第一备选辅助模型"
+ },
+ "fallback2": {
+ "label": "备选 2",
+ "description": "前两个都不可用时改用的模型,可留空。",
+ "ariaLabel": "选择第二备选辅助模型"
+ },
+ "emptySlot": "未选择",
+ "customHint": "自定义后只按你选的顺序尝试;都不可用时不会偷偷换成别的模型。",
+ "signInHint": "登录 Cindy 后可使用自动推荐;未登录时请在自定义中选择已配置的其他供应商模型。",
"chooseAgent": "选择 Agent",
"backToAgents": "返回选择 Agent",
- "explicitRouteHint": "显式指定后只使用该 Agent 和模型;不可用时不会自动切换。",
"searchPlaceholder": "搜索模型或供应商",
"noResults": "没有可用模型",
"unavailable": "当前不可用",
"budget": "折扣",
"subscription": "订阅",
- "saveFailed": "保存辅助模型设置失败"
+ "saveFailed": "保存辅助模型设置失败",
+ "chain": {
+ "cindyHy3": "Hy3",
+ "cindyDeepseekV4Flash": "DeepSeek v4 Flash",
+ "cindyQwen38Flash": "Qwen 3.8 Flash"
+ }
},
"compaction": {
"title": "上下文压缩",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index ed9960cfba..afd8a0ad81 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -1001,15 +1001,12 @@
},
"refiner": {
"label": "潤色模型",
- "hint": "整理口語文字使用的模型。",
- "ariaLabel": "語音潤色模型選擇"
- },
- "refinerFallback": {
- "label": "潤色備選模型",
- "hint": "主潤色模型失敗時改用的備選;預設不啟用。",
- "ariaLabel": "語音潤色備選模型選擇",
- "none": "不使用備選",
- "noneDescription": "主模型失敗時直接保留原始識別文字"
+ "hint": "跟隨輔助模型。",
+ "followAuxiliary": "跟隨輔助模型",
+ "followHint": "潤色模型跟隨「設定 → 個人化 → 輔助模型」的順序。Cindy 託管語音不受影響,潤色仍在服務端。",
+ "openAuxiliary": "前往輔助模型",
+ "cannotRefine": "目前輔助模型無法用於語音潤色(例如純 Claude Messages),這次不潤色。",
+ "ariaLabel": "語音潤色模型"
},
"customAsr": {
"optionLabel": "自定義即時 ASR",
@@ -2678,28 +2675,40 @@
},
"auxiliaryModels": {
"title": "輔助模型",
- "description": "為任務自動命名與輸入框推薦指令分別指定一組 Agent 和模型。",
- "sessionTitle": {
- "label": "任務自動命名",
- "description": "適用於 Claude Code、Codex、Pi 任務,以及手動 AI 重新命名。",
- "ariaLabel": "選擇任務自動命名模型",
- "automatic": "自動選擇(跟隨目前任務)"
- },
- "promptRecommendation": {
- "label": "輸入框推薦指令",
- "description": "僅在「小技巧」中啟用輸入框推薦後呼叫。",
- "ariaLabel": "選擇輸入框推薦指令模型",
- "automatic": "自動選擇(維持目前規則)"
- },
+ "description": "用於任務自動命名和 AI 重新命名、輸入框推薦指令、Help、置頂任務摘要、IM / 飛書標題與群組上下文判斷、定時任務指令碼、插件快問快答的「跟隨預設」,以及自備金鑰的語音潤色。",
+ "automatic": "自動推薦",
+ "customize": "自訂",
+ "preferred": {
+ "label": "首選",
+ "description": "輕量文字優先使用的模型。",
+ "ariaLabel": "選擇首選輔助模型"
+ },
+ "fallback1": {
+ "label": "備選 1",
+ "description": "首選無法使用時改用的模型,可留空。",
+ "ariaLabel": "選擇第一備選輔助模型"
+ },
+ "fallback2": {
+ "label": "備選 2",
+ "description": "前兩個都無法使用時改用的模型,可留空。",
+ "ariaLabel": "選擇第二備選輔助模型"
+ },
+ "emptySlot": "未選擇",
+ "customHint": "自訂後只按你選的順序嘗試;都無法使用時不會偷偷換成別的模型。",
+ "signInHint": "登入 Cindy 後可使用自動推薦;未登入時請在自訂中選擇已設定的其他供應商模型。",
"chooseAgent": "選擇 Agent",
"backToAgents": "返回選擇 Agent",
- "explicitRouteHint": "明確指定後只使用該 Agent 和模型;無法使用時不會自動切換。",
"searchPlaceholder": "搜尋模型或供應商",
"noResults": "沒有可用模型",
"unavailable": "目前無法使用",
"budget": "折扣",
"subscription": "訂閱",
- "saveFailed": "儲存輔助模型設定失敗"
+ "saveFailed": "儲存輔助模型設定失敗",
+ "chain": {
+ "cindyHy3": "Hy3",
+ "cindyDeepseekV4Flash": "DeepSeek v4 Flash",
+ "cindyQwen38Flash": "Qwen 3.8 Flash"
+ }
},
"compaction": {
"title": "上下文壓縮",
diff --git a/apps/desktop/src/shared/__tests__/auxiliaryModelChain.test.ts b/apps/desktop/src/shared/__tests__/auxiliaryModelChain.test.ts
new file mode 100644
index 0000000000..d2d152e701
--- /dev/null
+++ b/apps/desktop/src/shared/__tests__/auxiliaryModelChain.test.ts
@@ -0,0 +1,56 @@
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ AUTO_AUXILIARY_MODEL_CHAIN,
+ AUTO_AUXILIARY_MODEL_CHAIN_I18N_KEYS,
+ parseAuxiliaryModelRef,
+} from '../auxiliaryModelChain.js';
+
+const SOURCE_PATH = path.join(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '../auxiliaryModelChain.ts',
+);
+
+describe('AUTO_AUXILIARY_MODEL_CHAIN', () => {
+ it('is the frozen cross-tenant chain, never a live price ranking', () => {
+ expect(AUTO_AUXILIARY_MODEL_CHAIN).toEqual([
+ 'cat:xd:codex:deepseek/deepseek-v4-flash',
+ 'cat:xd:codex:tencent/hy3',
+ 'cat:xd:codex:qwen/qwen3.8-flash',
+ ]);
+ expect(AUTO_AUXILIARY_MODEL_CHAIN_I18N_KEYS).toHaveLength(AUTO_AUXILIARY_MODEL_CHAIN.length);
+
+ const source = readFileSync(SOURCE_PATH, 'utf8');
+ expect(source).not.toMatch(/\bsort\s*\(/);
+ expect(source).not.toMatch(/price/i);
+ expect(source).not.toMatch(/cheapest/i);
+ });
+
+ it('parses profile keys and catalog pins', () => {
+ expect(parseAuxiliaryModelRef('cat:xd:codex:deepseek/deepseek-v4-flash')).toEqual({
+ kind: 'catalog',
+ route: {
+ providerId: 'xd',
+ agentKind: 'codex',
+ model: 'deepseek/deepseek-v4-flash',
+ },
+ });
+ expect(parseAuxiliaryModelRef('codex-gpt-5.4-mini')).toEqual({
+ kind: 'profile',
+ id: 'codex-gpt-5.4-mini',
+ });
+ expect(parseAuxiliaryModelRef('cat:anthropic:claude-code:claude-haiku-4-5')).toEqual({
+ kind: 'catalog',
+ route: {
+ providerId: 'anthropic',
+ agentKind: 'claude-code',
+ model: 'claude-haiku-4-5',
+ },
+ });
+ expect(parseAuxiliaryModelRef('not-a-model')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/shared/auxiliaryModelChain.ts b/apps/desktop/src/shared/auxiliaryModelChain.ts
new file mode 100644
index 0000000000..cc9a3d7ca3
--- /dev/null
+++ b/apps/desktop/src/shared/auxiliaryModelChain.ts
@@ -0,0 +1,63 @@
+import {
+ decodeCatalogModelPin,
+ encodeCatalogModelPin,
+ type CatalogModelPinRoute,
+} from './catalogModelPin.js';
+import {
+ isUtilityModelProviderKind,
+ type UtilityModelProviderKind,
+} from './utilityModelProfiles.js';
+
+/** User-custom chain length. Empty list means follow the built-in automatic chain. */
+export const AUXILIARY_MODEL_CHAIN_MAX = 3;
+
+/**
+ * Frozen automatic chain. Highest priority first.
+ *
+ * Keep this as a literal list. Do not rank it from the live catalog. The first
+ * three routes are Cindy AI models present in both the CN and Global public
+ * catalogs, so an account-scoped catalog can safely skip any route it does not
+ * expose and continue through the same cross-tenant order.
+ */
+export const AUTO_AUXILIARY_MODEL_CHAIN = [
+ encodeCatalogModelPin({
+ providerId: 'xd',
+ agentKind: 'codex',
+ model: 'deepseek/deepseek-v4-flash',
+ }),
+ encodeCatalogModelPin({
+ providerId: 'xd',
+ agentKind: 'codex',
+ model: 'tencent/hy3',
+ }),
+ encodeCatalogModelPin({
+ providerId: 'xd',
+ agentKind: 'codex',
+ model: 'qwen/qwen3.8-flash',
+ }),
+] as const;
+
+export type AuxiliaryModelRefKind = 'profile' | 'catalog';
+
+export type ParsedAuxiliaryModelRef =
+ | { kind: 'profile'; id: UtilityModelProviderKind }
+ | { kind: 'catalog'; route: CatalogModelPinRoute };
+
+export function parseAuxiliaryModelRef(value: string): ParsedAuxiliaryModelRef | null {
+ if (isUtilityModelProviderKind(value)) {
+ return { kind: 'profile', id: value };
+ }
+ const route = decodeCatalogModelPin(value);
+ return route ? { kind: 'catalog', route } : null;
+}
+
+export function isAuxiliaryModelRef(value: string): boolean {
+ return parseAuxiliaryModelRef(value) !== null;
+}
+
+/** Stable i18n suffixes for the frozen automatic chain, in the same order. */
+export const AUTO_AUXILIARY_MODEL_CHAIN_I18N_KEYS = [
+ 'cindyDeepseekV4Flash',
+ 'cindyHy3',
+ 'cindyQwen38Flash',
+] as const;
diff --git a/apps/desktop/src/shared/auxiliaryModelSettings.ts b/apps/desktop/src/shared/auxiliaryModelSettings.ts
index 4532eebd68..3517829cf8 100644
--- a/apps/desktop/src/shared/auxiliaryModelSettings.ts
+++ b/apps/desktop/src/shared/auxiliaryModelSettings.ts
@@ -1,21 +1,26 @@
import type { Provider } from '@cindy/model-providers';
-import { decodeCatalogModelPin } from './catalogModelPin';
+import {
+ AUXILIARY_MODEL_CHAIN_MAX,
+ isAuxiliaryModelRef,
+ parseAuxiliaryModelRef,
+} from './auxiliaryModelChain.js';
+import { decodeCatalogModelPin } from './catalogModelPin.js';
+import { isUtilityModelProviderKind } from './utilityModelProfiles.js';
-/** Main-owned model choices for short, host-generated auxiliary text. */
+/** Main-owned ordered model chain 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;
+ /**
+ * Ordered custom models. Empty = follow the current version's automatic chain.
+ * At most three unique refs (catalog pins or lightweight profile keys).
+ */
+ models: string[];
}
-export type AuxiliaryModelSettingsKey = keyof AuxiliaryModelSettings;
export type AuxiliaryModelSettingsPatch = Partial<AuxiliaryModelSettings>;
export const AUXILIARY_MODEL_SETTINGS_DEFAULTS: AuxiliaryModelSettings = {
- sessionTitleModel: null,
- promptRecommendationModel: null,
+ models: [],
};
export const AUXILIARY_MODEL_PIN_MAX_LENGTH = 768;
@@ -56,24 +61,77 @@ function containsControlCharacter(value: string): boolean {
return false;
}
-/** Disk normalization: invalid values restore the automatic/default route. */
-export function normalizeAuxiliaryModelPin(value: unknown): string | null {
+/** Disk normalization: invalid values are dropped; empty list restores automatic. */
+export function normalizeAuxiliaryModelRef(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)
+ !trimmed
+ || trimmed.length > AUXILIARY_MODEL_PIN_MAX_LENGTH
+ || containsControlCharacter(trimmed)
+ || !isAuxiliaryModelRef(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;
+export function normalizeAuxiliaryModelList(value: unknown): string[] {
+ if (!Array.isArray(value)) return [];
+ const models: string[] = [];
+ for (const entry of value) {
+ const ref = normalizeAuxiliaryModelRef(entry);
+ if (!ref || models.includes(ref)) continue;
+ models.push(ref);
+ if (models.length >= AUXILIARY_MODEL_CHAIN_MAX) break;
+ }
+ return models;
+}
+
+/**
+ * Accept a persisted or IPC value as a canonical auxiliary ref.
+ * Catalog pins must already be trimmed; profile keys must be exact ids.
+ */
+export function isValidAuxiliaryModelRefInput(value: unknown): value is string {
if (typeof value !== 'string') return false;
- return normalizeAuxiliaryModelPin(value) === value;
+ return normalizeAuxiliaryModelRef(value) === value;
+}
+
+export function isValidAuxiliaryModelListInput(value: unknown): value is string[] {
+ if (!Array.isArray(value)) return false;
+ if (value.length > AUXILIARY_MODEL_CHAIN_MAX) return false;
+ const seen = new Set<string>();
+ for (const entry of value) {
+ if (!isValidAuxiliaryModelRefInput(entry) || seen.has(entry)) return false;
+ seen.add(entry);
+ }
+ return true;
+}
+
+/** True when the user has an explicit 1–3 model override. */
+export function isCustomAuxiliaryModelList(models: readonly string[]): boolean {
+ return models.length > 0;
+}
+
+export function describeAuxiliaryModelRef(ref: string): {
+ providerId: string;
+ agentKind: 'codex' | 'claude-code';
+ model: string;
+} | null {
+ const parsed = parseAuxiliaryModelRef(ref);
+ if (!parsed) return null;
+ if (parsed.kind === 'catalog') return parsed.route;
+ return {
+ providerId: parsed.id.startsWith('codex-') ? 'openai' : 'xd',
+ agentKind: 'codex',
+ model: parsed.id,
+ };
+}
+
+export function isCatalogAuxiliaryRef(value: string): boolean {
+ return decodeCatalogModelPin(value) !== null;
+}
+
+export function isProfileAuxiliaryRef(value: string): boolean {
+ return isUtilityModelProviderKind(value);
}
diff --git a/apps/desktop/src/shared/voiceInputRefinerProfiles.ts b/apps/desktop/src/shared/voiceInputRefinerProfiles.ts
index 8184d274ba..076ed225a8 100644
--- a/apps/desktop/src/shared/voiceInputRefinerProfiles.ts
+++ b/apps/desktop/src/shared/voiceInputRefinerProfiles.ts
@@ -13,6 +13,11 @@ import {
type UtilityModelSettingsTab,
type UtilityModelTransport,
} from './utilityModelProfiles.js';
+import {
+ decodeCatalogModelPin,
+ encodeCatalogModelPin,
+ type CatalogModelPinRoute,
+} from './catalogModelPin.js';
export type VoiceInputRefinerTransport = UtilityModelTransport;
export type VoiceInputRefinerAuthKind = UtilityModelAuthKind;
@@ -33,10 +38,67 @@ export const DEFAULT_VOICE_INPUT_REFINER_PROVIDER_KIND = DEFAULT_UTILITY_MODEL_P
export const DEFAULT_VOICE_INPUT_REFINER_MODEL = DEFAULT_UTILITY_MODEL;
export const DEFAULT_VOICE_INPUT_REFINER_PROVIDER_CHAIN = DEFAULT_UTILITY_MODEL_PROVIDER_CHAIN;
-export type VoiceInputRefinerProviderKind = UtilityModelProviderKind;
+/**
+ * The auxiliary chain may contain an exact catalog pin whose model is not in
+ * the static utility profile table yet (for example a newly released Cindy
+ * Gateway model). Keep that pin as the runtime identity so voice refinement
+ * does not silently replace it with a different model.
+ */
+export type VoiceInputRefinerCatalogProviderKind = string & {
+ readonly __voiceInputRefinerCatalogProviderKind: unique symbol;
+};
+export type VoiceInputRefinerProviderKind =
+ | UtilityModelProviderKind
+ | VoiceInputRefinerCatalogProviderKind;
+
+const CATALOG_VOICE_REFINER_PROVIDERS = new Set(['openai', 'xd']);
+
+export function voiceInputRefinerProviderKindForCatalogRoute(
+ route: CatalogModelPinRoute,
+): VoiceInputRefinerCatalogProviderKind | null {
+ if (route.agentKind !== 'codex' || !CATALOG_VOICE_REFINER_PROVIDERS.has(route.providerId)) {
+ return null;
+ }
+ return encodeCatalogModelPin(route) as VoiceInputRefinerCatalogProviderKind;
+}
+
+function catalogVoiceRefinerProfile(
+ provider: VoiceInputRefinerCatalogProviderKind,
+): VoiceInputRefinerProfile | null {
+ const route = decodeCatalogModelPin(provider);
+ if (!route) return null;
+ const providerKind = voiceInputRefinerProviderKindForCatalogRoute(route);
+ if (providerKind !== provider) return null;
+ const isCodexResponses = route.providerId === 'openai';
+ const transport: VoiceInputRefinerTransport = isCodexResponses
+ ? 'codex-responses'
+ : 'litellm-chat-completions';
+ // Catalog pins are intentionally kept as the runtime identity, but known
+ // models should still use the static quote already used by the matching
+ // utility transport. Unknown catalog models remain unpriced rather than
+ // pretending that a reference quote is a live Gateway price.
+ const pricing = getUtilityModelProfiles().find(
+ (profile) => profile.transport === transport
+ && profile.model.trim().toLowerCase() === route.model.trim().toLowerCase(),
+ )?.pricing;
+ return {
+ id: provider,
+ model: route.model,
+ transport,
+ auth: isCodexResponses ? 'codex' : 'api-key',
+ settingsTab: 'providers',
+ ...(pricing ? { pricing } : {}),
+ missingCredentialMessage: isCodexResponses
+ ? 'Codex ChatGPT login is required for voice input refinement.'
+ : 'API key is required for LiteLLM voice input refinement.',
+ };
+}
export function getVoiceInputRefinerProfile(provider: VoiceInputRefinerProviderKind): VoiceInputRefinerProfile {
- const profile = getUtilityModelProfile(provider);
+ const profile = isUtilityModelProviderKind(provider)
+ ? getUtilityModelProfile(provider)
+ : catalogVoiceRefinerProfile(provider);
+ if (!profile) throw new Error(`Unknown voice input refiner provider ${provider}`);
return {
...profile,
missingCredentialMessage: profile.auth === 'codex'
@@ -50,11 +112,13 @@ export function getVoiceInputRefinerProfiles(): VoiceInputRefinerProfile[] {
}
export function isVoiceInputRefinerProviderKind(value: string): value is VoiceInputRefinerProviderKind {
- return isUtilityModelProviderKind(value);
+ return isUtilityModelProviderKind(value)
+ || Boolean(catalogVoiceRefinerProfile(value as VoiceInputRefinerCatalogProviderKind));
}
export function resolveVoiceInputRefinerProviderKindAlias(value: string): VoiceInputRefinerProviderKind | null {
- return resolveUtilityModelProviderKindAlias(value);
+ return resolveUtilityModelProviderKindAlias(value)
+ ?? (isVoiceInputRefinerProviderKind(value) ? value as VoiceInputRefinerProviderKind : null);
}
export function estimateVoiceInputRefinerCostUsd(
diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.md
index 4fd36f3ca1..2bc947c479 100644
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@ -37,7 +37,7 @@
| `desktop.overlay.toast` | desktop | Toast | App 常驻 ToastContainer(用户可见出口,不展开业务逻辑) | Toast, ToastContainer | apps/desktop/src/renderer/components/ui/toast/Toast.tsx, apps/desktop/src/renderer/components/ui/toast/ToastContainer.tsx, apps/desktop/src/renderer/components/ui/toast/index.ts | 4 | 4 | 2 |
| `desktop.plugins.app-main` | desktop | 插件主视图 | hash `/apps/:ghostId`(GhostMainViewFeatureLayout) | GhostMainViewFeatureLayout, GhostMainViewHost | apps/desktop/src/renderer/features/plugin/GhostMainViewFeatureLayout.tsx, apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx | 0 | 0 | 0 |
| `desktop.plugins.installed` | desktop | 已装插件 | hash `/plugins`(GhostPluginPage) | AddMarketplaceDialog, GhostPluginDetailView, GhostPluginPage, MarketPluginDetailView, MyPublishesSection, PluginManagementLayout, PluginScopePicker, UpdateAllDialog | apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx, apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx, apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx, apps/desktop/src/renderer/features/plugin/plugin-motion.css | 49 | 0 | 81 |
-| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 143 | 121 | 727 |
+| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 143 | 121 | 731 |
| `desktop.shell.main-layout` | desktop | 主窗口壳(标题栏 / 左右栏 / 内容区) | main BrowserWindow → renderer/index.tsx → main-entry.tsx → App → MainLayout (`#/` 受保护壳) | ChromeActions, FeishuConflictDialogHost, GhostMediaLightboxHost, MainLayout, RightSidebar, RightSidebarShell, SessionShareImportWizard, Sidebar, UpdateNoticeDialog, WindowControls | apps/desktop/src/renderer/cindy-brain/GhostMediaLightboxHost.tsx, apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx, apps/desktop/src/renderer/components/layout/BrowserWebviewPool.tsx, apps/desktop/src/renderer/components/layout/ChromeActions.tsx, apps/desktop/src/renderer/components/layout/ContentHeader.tsx, apps/desktop/src/renderer/components/layout/CredentialStoreBanner.tsx, apps/desktop/src/renderer/components/layout/FadeSwitcher.tsx, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx, apps/desktop/src/renderer/components/layout/MainLayout.tsx, apps/desktop/src/renderer/components/layout/RightSidebar.tsx, apps/desktop/src/renderer/components/layout/RightSidebarDetach.tsx, apps/desktop/src/renderer/components/layout/RightSidebarMaximize.tsx, apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/components/layout/chromeActionsGeometry.ts, apps/desktop/src/renderer/components/layout/chromeActionsLayout.ts, apps/desktop/src/renderer/components/layout/railChromeActions.ts, apps/desktop/src/renderer/components/layout/windowDrag.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx, apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx, apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx, apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx, apps/desktop/src/renderer/components/sidebar/Sidebar.tsx, apps/desktop/src/renderer/components/sidebar/SidebarIconButton.tsx, apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx, apps/desktop/src/renderer/components/sidebar/SortableList.tsx, apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx, apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx, apps/desktop/src/renderer/components/sidebar/VendorIcon.tsx, apps/desktop/src/renderer/components/sidebar/VendorReadinessBadge.tsx, apps/desktop/src/renderer/components/sidebar/WorktreeBadge.tsx, apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx, apps/desktop/src/renderer/components/title-bar/MenuButton.tsx, apps/desktop/src/renderer/components/title-bar/WindowControls.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/layout/LayoutRoot.tsx, apps/desktop/src/renderer/layout/PanelDragController.tsx, apps/desktop/src/renderer/layout/PanelDragPrototype.tsx, apps/desktop/src/renderer/layout/collapsePrefs.ts, apps/desktop/src/renderer/layout/layoutDevTools.ts, apps/desktop/src/renderer/layout/panePlacement.tsx, apps/desktop/src/renderer/layout/paneWidths.tsx, apps/desktop/src/renderer/layout/panelMaximize.tsx, apps/desktop/src/renderer/styles/globals.css | 145 | 72 | 288 |
| `desktop.skillhub.local` | desktop | SkillHub 本地技能 | hash `/skillhub/local` 及详情 `/skillhub/local/:kind/global/:name`、`/skillhub/local/:kind/project/:projectHash/:name` | InstallTargetPicker, PluginManagementLayout, SkillhubDetailView, SkillhubFeatureLayout, SkillhubHomeView, SkillhubMarketPreviewPanel | apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx | 41 | 0 | 71 |
| `desktop.skillhub.market` | desktop | SkillHub 市场 | hash `/skillhub/market`(SkillhubMarketListView) | InstallTargetPicker, MarketCard, MarketInfoEditDialog, SkillhubMarketListView, SkillhubMarketPreviewPanel, VisibilityEditorDialog | apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInfoEditDialog.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketPreviewTree.tsx, apps/desktop/src/renderer/features/skillhub/components/PlatformTagSelector.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillIcon.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillTagList.tsx, apps/desktop/src/renderer/features/skillhub/components/TeamScopePicker.tsx, apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsx | 46 | 0 | 59 |
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index e0879f606e..bc0090c622 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -1362,6 +1362,17 @@ export interface OneShotOptions {
* 用于 skillReview "用户主动取消发布" 等场景。
*/
signal?: AbortSignal;
+ /** Provider-native system/developer instructions for this one-shot request. */
+ systemPrompt?: string;
+ /** Additional provider-native output-shape instructions for this request. */
+ responseInstructions?: string;
+ /**
+ * Internal ownership/configuration fence checked immediately before a
+ * provider dispatch. Returning false must fail closed without sending the
+ * one-shot request (for example when the owning workflow was replaced while
+ * the agent host was starting).
+ */
+ beforeDispatch?: () => boolean | Promise<boolean>;
}
/**
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/one-shot-guard.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/one-shot-guard.test.ts
new file mode 100644
index 0000000000..a88f203a4e
--- /dev/null
+++ b/packages/maker-core/src/agents/claude-code/__tests__/one-shot-guard.test.ts
@@ -0,0 +1,88 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const h = vi.hoisted(() => ({
+ create: vi.fn(),
+}));
+
+vi.mock("@anthropic-ai/sdk", () => ({
+ default: class AnthropicMock {
+ messages = { create: h.create };
+ },
+ APIError: class APIErrorMock extends Error {},
+}));
+
+import { ClaudeCodeAgent } from "../index.js";
+import type { AgentDeps } from "../../base-agent.js";
+import type { AuthAdapter } from "../../../interfaces/auth-adapter.js";
+import type { Logger } from "../../../interfaces/logger.js";
+
+function createNoopLogger(): Logger {
+ const logger: Logger = {
+ trace() {},
+ debug() {},
+ info() {},
+ warn() {},
+ error() {},
+ fatal() {},
+ child() {
+ return logger;
+ },
+ };
+ return logger;
+}
+
+function createDeps(): AgentDeps {
+ const auth: AuthAdapter = {
+ async getState() {
+ return { authenticated: true };
+ },
+ async triggerLogin() {
+ return { authenticated: true };
+ },
+ async logout() {},
+ async getAuthEnv() {
+ return { ANTHROPIC_API_KEY: "test-key" };
+ },
+ };
+
+ return {
+ auth,
+ runtimeConfig: { endpoint: "https://example.test" },
+ binaryPath: process.execPath,
+ logger: createNoopLogger(),
+ };
+}
+
+describe("ClaudeCodeAgent oneShot dispatch guard", () => {
+ beforeEach(() => {
+ h.create.mockReset();
+ h.create.mockResolvedValue({
+ content: [{ type: "text", text: "ok" }],
+ usage: { input_tokens: 1, output_tokens: 1 },
+ });
+ });
+
+ it("fails closed before the Anthropic request when the guard rejects", async () => {
+ const beforeDispatch = vi.fn(async () => false);
+ const agent = new ClaudeCodeAgent(createDeps());
+
+ await expect(
+ agent.oneShot("hello", { beforeDispatch }),
+ ).rejects.toMatchObject({
+ reason: "network",
+ });
+ expect(beforeDispatch).toHaveBeenCalledOnce();
+ expect(h.create).not.toHaveBeenCalled();
+ });
+
+ it("dispatches when the guard accepts", async () => {
+ const beforeDispatch = vi.fn(async () => true);
+ const agent = new ClaudeCodeAgent(createDeps());
+
+ await expect(agent.oneShot("hello", { beforeDispatch })).resolves.toBe(
+ "ok",
+ );
+ expect(beforeDispatch).toHaveBeenCalledOnce();
+ expect(h.create).toHaveBeenCalledOnce();
+ });
+});
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index b6a27bb904..7b54d499b5 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -1005,6 +1005,9 @@ export class ClaudeCodeAgent extends BaseAgent {
const model = opts?.model ?? 'claude-haiku-4-5';
const maxTokens = opts?.maxTokens ?? 100;
const timeoutMs = opts?.timeoutMs ?? 30_000;
+ const instructions = [opts?.systemPrompt, opts?.responseInstructions]
+ .filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
+ .join('\n');
// Auth gate:与 startSession 对齐 — 未授权直接拒,不让 Anthropic 请求带空 key 跑出去
// (避免被 fallback 到用户系统级 ~/.claude/.credentials.json 之类的别处 OAuth)
@@ -1016,8 +1019,9 @@ export class ClaudeCodeAgent extends BaseAgent {
);
}
// oneShot 凭证优先走 getOneShotAuth()(host 侧直连专用,与子进程 env 正交):
- // Claude 'oauth' 模式下 getAuthEnv() 注入的是用户订阅 token,但 oneShot 无 system prompt、
- // 不能走订阅(会被 claude.ai OAuth 策略拒),host 通过 getOneShotAuth 固定回 gateway key +
+ // Claude 'oauth' 模式下 getAuthEnv() 注入的是用户订阅 token,但 oneShot 直连
+ // Anthropic Messages API 不能走订阅 token(会被 claude.ai OAuth 策略拒),host 通过
+ // getOneShotAuth 固定回 gateway key +
// gateway endpoint。不实现该方法的 adapter(或回 null)→ 回退旧逻辑(getAuthEnv 里的 key + runtimeConfig.endpoint)。
let apiKey: string | undefined;
let baseURL = this.deps.runtimeConfig.endpoint;
@@ -1054,10 +1058,18 @@ export class ClaudeCodeAgent extends BaseAgent {
maxRetries: 0,
});
+ // Auth and host setup can await asynchronous work. Re-check the caller's
+ // ownership fence immediately before the paid provider request, matching
+ // Codex oneShot's thread/start guard.
+ if (opts?.beforeDispatch && !(await opts.beforeDispatch())) {
+ throw new OneShotError('network', 'Claude oneShot dispatch guard rejected');
+ }
+
const resp = await client.messages.create(
{
model,
max_tokens: maxTokens,
+ ...(instructions ? { system: instructions } : {}),
messages: [{ role: 'user', content: prompt }],
},
{ signal: timeoutController.signal },
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 8d73e2cf78..9c5d69451c 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -459,6 +459,76 @@ describe('CodexAgent spawn configuration', () => {
});
});
+describe('CodexAgent oneShot dispatch guard', () => {
+ it('fails closed without thread/start when ownership changes during host startup', async () => {
+ const agent = new CodexAgent(createDeps());
+ const order: string[] = [];
+ const ensureStarted = vi.fn(async () => {
+ order.push('ensureStarted');
+ // Model the owning workflow being replaced while the Codex host is
+ // starting. The final guard must run after this await and before any RPC.
+ await Promise.resolve();
+ });
+ const request = vi.fn(async () => {
+ order.push('request');
+ throw new Error('thread/start must not be sent after guard rejection');
+ });
+ const subscribeThread = vi.fn(() => ({ release: vi.fn() }));
+ const host = { ensureStarted, request, subscribeThread };
+ Object.defineProperty(agent, 'getUtilityHost', {
+ value: vi.fn(async () => ({ key: 'test-utility-host', host })),
+ configurable: true,
+ });
+
+ const beforeDispatch = vi.fn(async () => {
+ order.push('beforeDispatch');
+ return false;
+ });
+
+ await expect(agent.oneShot('name this task', { beforeDispatch }))
+ .rejects.toMatchObject({ name: 'OneShotError', reason: 'network' });
+
+ expect(order).toEqual(['ensureStarted', 'beforeDispatch']);
+ expect(beforeDispatch).toHaveBeenCalledOnce();
+ expect(request).not.toHaveBeenCalled();
+ expect(subscribeThread).not.toHaveBeenCalled();
+ });
+
+ it('rechecks ownership before turn/start and releases the temporary thread', async () => {
+ const agent = new CodexAgent(createDeps());
+ const request = vi.fn(async (method: string) => {
+ if (method === Method.ThreadStart) return { thread: { id: 'thread-before-turn-guard' } };
+ throw new Error(`unexpected request: ${method}`);
+ });
+ const release = vi.fn(async () => undefined);
+ const subscribeThread = vi.fn(() => ({ release }));
+ const host = {
+ ensureStarted: vi.fn(async () => undefined),
+ request,
+ subscribeThread,
+ };
+ Object.defineProperty(agent, 'getUtilityHost', {
+ value: vi.fn(async () => ({ key: 'test-utility-host', host })),
+ configurable: true,
+ });
+
+ const beforeDispatch = vi
+ .fn<() => Promise<boolean>>()
+ .mockResolvedValueOnce(true)
+ .mockResolvedValueOnce(false);
+
+ await expect(agent.oneShot('name this task', { beforeDispatch }))
+ .rejects.toMatchObject({ name: 'OneShotError', reason: 'network' });
+
+ expect(beforeDispatch).toHaveBeenCalledTimes(2);
+ expect(request).toHaveBeenCalledTimes(1);
+ expect(request).toHaveBeenCalledWith(Method.ThreadStart, expect.any(Object));
+ expect(request).not.toHaveBeenCalledWith(Method.TurnStart, expect.any(Object));
+ expect(subscribeThread).toHaveBeenCalledWith('thread-before-turn-guard', expect.any(Object));
+ expect(release).toHaveBeenCalledOnce();
+ });
+});
+
function deferred<T>() {
let resolve!: (value: T | PromiseLike<T>) => void;
let reject!: (reason?: unknown) => void;
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index a247a030db..453c8a82c8 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -2889,6 +2889,9 @@ export class CodexAgent extends BaseAgent {
async oneShot(prompt: string, opts?: OneShotOptions): Promise<string> {
const log = this.deps.logger.child('codex/oneShot');
const timeoutMs = opts?.timeoutMs ?? 30_000;
+ const developerInstructions = [opts?.systemPrompt, opts?.responseInstructions]
+ .filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
+ .join('\n');
// OneShotOptions.maxTokens 在 Codex 协议层就没暴露 (protocol.ts ThreadStartParams /
// TurnStartParams 都没 max_tokens 字段) —— 静默忽略, 但调用方传了就 warn 一下,
// 避免未来加新 oneShot 场景时 "我设了上限怎么没生效" 的隐性 bug。
@@ -2904,12 +2907,21 @@ export class CodexAgent extends BaseAgent {
const { host } = await this.getUtilityHost();
await host.ensureStarted();
+ // Host startup can await credential discovery and process readiness. The
+ // caller may have been replaced during that window, so perform the final
+ // ownership/configuration check immediately before the real thread/start
+ // dispatch. A rejected guard must not create a thread for the old owner.
+ if (opts?.beforeDispatch && !(await opts.beforeDispatch())) {
+ throw new OneShotError('network', 'Codex oneShot dispatch guard rejected');
+ }
+
// 创建临时 thread (跟主 session 共享 server 但 thread state 隔离)
const startResp = await host.request<ThreadStartResponse>(Method.ThreadStart, {
cwd: os.tmpdir(),
model: opts?.model ?? 'gpt-5.4-mini',
approvalPolicy: 'never',
sandbox: 'read-only', // kebab-case (v2.rs SandboxMode)
+ ...(developerInstructions ? { developerInstructions } : {}),
} as ThreadStartParams);
const threadId = startResp.thread.id;
@@ -2959,6 +2971,21 @@ export class CodexAgent extends BaseAgent {
},
});
+ // thread/start 创建了临时 thread 后,到 turn/start 之间仍可能发生 owner 切换。
+ // 再次复核并在拒绝时释放订阅,避免把旧 owner 的 prompt 发进已创建的 thread。
+ if (opts?.beforeDispatch && !(await opts.beforeDispatch())) {
+ const pendingSubscription = subscription;
+ subscription = null;
+ try {
+ await pendingSubscription?.release();
+ } catch (releaseError) {
+ log.warn('oneShot dispatch guard rejected; failed to release temporary thread', {
+ error: releaseError instanceof Error ? releaseError.message : String(releaseError),
+ });
+ }
+ throw new OneShotError('network', 'Codex oneShot dispatch guard rejected before turn/start');
+ }
+
await host.request(Method.TurnStart, {
threadId,
input: [{ type: 'text', text: prompt }],