Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 收紧辅助模型路由边界
DavidShendf5f8dadca08
diff --git a/apps/desktop/src/main/im/__tests__/fbotTitleAuxiliaryModel.test.ts b/apps/desktop/src/main/im/__tests__/fbotTitleAuxiliaryModel.test.tsindex 9ca26966d5..dd752e509c 100644--- a/apps/desktop/src/main/im/__tests__/fbotTitleAuxiliaryModel.test.ts+++ b/apps/desktop/src/main/im/__tests__/fbotTitleAuxiliaryModel.test.ts@@ -3,6 +3,7 @@ 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(),}));@@ -11,7 +12,10 @@ vi.mock('../../maker-host/session-storage.js', () => ({}));vi.mock('../../maker-ipc/title.js', () => ({- generateMakerSessionTitle: vi.fn(async () => h.generatedTitle),+ generateMakerSessionTitle: vi.fn(async () => {+ h.onGenerate?.();+ return h.generatedTitle;+ }),}));vi.mock('../../utility-model/auxiliary-model-settings-store.js', () => ({@@ -36,6 +40,7 @@ beforeEach(() => {vi.clearAllMocks();h.generatedTitle = null;h.selection = null;+ h.onGenerate = null;h.requestUtilityText.mockResolvedValue({ok: true,text: '旧 utility 兜底标题',@@ -59,4 +64,14 @@ describe('IM task title auxiliary model boundary', () => {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;+ };++ await expect(generateImSessionTitleText('task-1', '第一条消息')).resolves.toBeNull();+ expect(h.requestUtilityText).not.toHaveBeenCalled();+ });});diff --git a/apps/desktop/src/main/im/shared/fbotTitle.ts b/apps/desktop/src/main/im/shared/fbotTitle.tsindex 1c55ee9177..d9c1ea1946 100644--- a/apps/desktop/src/main/im/shared/fbotTitle.ts+++ b/apps/desktop/src/main/im/shared/fbotTitle.ts@@ -71,11 +71,18 @@ 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 (readAuxiliaryModelSelection('sessionTitleModel')) return null;+ if (startedWithExplicitRoute) return null;try {// 动态 import 保持本模块的静态依赖链不继续膨胀(cindySlot 同款)。const [{ requestUtilityText }, { getMaker }] = await Promise.all([diff --git a/apps/desktop/src/main/maker-host/__tests__/auxiliary-title-one-shot.test.ts b/apps/desktop/src/main/maker-host/__tests__/auxiliary-title-one-shot.test.tsindex 9fb0540a57..047b518811 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@@ -86,6 +86,9 @@ describe('auxiliary task-title routing', () => {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();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.tsindex f07b0ed277..88aa8f97fa 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@@ -28,6 +28,8 @@ const AUXILIARY_TITLE_TIMEOUT_MS = 12_000;const AUXILIARY_TITLE_MAX_TOKENS = 32;const AUXILIARY_TITLE_OUTPUT_MAX_CHARS = 256;const AUXILIARY_TITLE_VISUAL_MAX_CHARS = 40;+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: (@@ -95,6 +97,12 @@ async function generateExplicitTitle(model: selection.model,maxTokens: AUXILIARY_TITLE_MAX_TOKENS,timeoutMs: AUXILIARY_TITLE_TIMEOUT_MS,+ // Short title budgets cannot afford provider-default thinking. Messages /+ // chat routes receive their native disable flag; Responses routes use the+ // lowest supported effort because that protocol has no off value.+ disableReasoning: true,+ 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.diff --git a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.tsindex e0a0d63015..c0128ef75e 100644--- a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts+++ b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts@@ -421,6 +421,52 @@ describe('utility one-shot candidates', () => {});});+ it('rejects a retired model pinned to an explicit auxiliary route', async () => {+ activeCatalog.mockReturnValue({+ providers: [{+ id: 'tapsvc',+ name: 'Tap Service',+ source: 'user',+ agents: ['codex'],+ auth: { method: 'apiKey' },+ routing: {+ codex: {+ upstream: 'https://custom.example/v1',+ authStrategy: 'api-key-header',+ },+ },+ models: {+ codex: [{+ id: 'retired-mini',+ name: 'Retired Mini',+ contextWindow: 100_000,+ status: 'retired',+ }],+ },+ }],+ } as never);+ readCustomKey.mockReturnValue('custom-secret');++ const result = await requestUtilityText(makerMock(false), 'generate', {+ providerId: 'tapsvc',+ agentKind: 'codex',+ model: 'retired-mini',+ });++ expect(result).toMatchObject({+ ok: false,+ reason: 'no_candidate',+ attempts: [expect.objectContaining({+ providerId: 'tapsvc',+ model: 'retired-mini',+ status: 'skipped',+ reason: 'model_unavailable',+ })],+ });+ expect(readCustomKey).not.toHaveBeenCalled();+ expect(fetchMock).not.toHaveBeenCalled();+ });+it('does not read or send a custom-provider key while its route is mutating', async () => {activeCatalog.mockReturnValue({providers: [{@@ -625,12 +671,16 @@ describe('utility one-shot candidates', () => {model: 'gpt-5.5',systemPrompt: 'SYSTEM POLICY',responseInstructions: 'ONE LINE ONLY',+ disableReasoning: true,+ reasoningEffort: 'minimal',beforeDispatch,});expect(result).toMatchObject({ ok: true, text: 'next prompt' });expect(beforeDispatch).toHaveBeenCalledTimes(2);expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({+ thinking: { type: 'disabled' },+ reasoning_effort: 'minimal',messages: [{ role: 'system', content: 'SYSTEM POLICY\nONE LINE ONLY' },{ role: 'user', content: 'reference material' },diff --git a/apps/desktop/src/main/utility-model/__tests__/textOneshotPinOptions.test.ts b/apps/desktop/src/main/utility-model/__tests__/textOneshotPinOptions.test.tsindex 5939e685d7..ab65d09c6d 100644--- a/apps/desktop/src/main/utility-model/__tests__/textOneshotPinOptions.test.ts+++ b/apps/desktop/src/main/utility-model/__tests__/textOneshotPinOptions.test.ts@@ -49,6 +49,16 @@ describe('encodeCatalogPin / decodeCatalogPin', () => {});});+ it('编码包含分隔符的运行期供应商 ID', () => {+ const pin = encodeCatalogPin('custom:xai', 'codex', 'grok:4');+ expect(pin).toBe('cat:custom%3Axai:codex:grok:4');+ expect(decodeCatalogPin(pin)).toEqual({+ providerId: 'custom:xai',+ agentKind: 'codex',+ model: 'grok:4',+ });+ });+it('非目录钉 / 残缺形态 / 不可路由 agent 一律 null', () => {for (const bad of ['',@@ -138,6 +148,7 @@ describe('buildTextOneshotPinOptions', () => {models: {codex: [chat('disabled', { disabled: true }),+ chat('retired', { status: 'retired' }),chat('hidden-by-default', { defaultEnabled: false }),],},@@ -454,4 +465,11 @@ describe('resolveOneshotCatalogModel', () => {);expect(resolveOneshotCatalogModel(catalog, undefined, 'gpt-disabled')).toBeNull();});++ it('目录中已退役的模型不能作为声明路由', () => {+ const catalog = catalogOf(+ provider({ id: 'xd', models: { codex: [chat('gpt-retired', { status: 'retired' })] } }),+ );+ expect(resolveOneshotCatalogModel(catalog, undefined, 'gpt-retired')).toBeNull();+ });});diff --git a/apps/desktop/src/main/utility-model/oneShotCandidates.ts b/apps/desktop/src/main/utility-model/oneShotCandidates.tsindex b990ac0cc7..99c7a8c5ef 100644--- a/apps/desktop/src/main/utility-model/oneShotCandidates.ts+++ b/apps/desktop/src/main/utility-model/oneShotCandidates.ts@@ -3,7 +3,7 @@ import { randomUUID } from 'node:crypto';import { type AgentKind, type Maker } from '@cindy/maker-core';import {appendProviderRequestPath,- isAgentSelectableModel,+ isModelSelectableForNewRoute,storedCustomProviderId,} from '@cindy/model-providers';@@ -68,6 +68,12 @@ export type UtilityTextRequestOptions = {timeoutMs?: number;/** Optional lightweight reasoning hint for short internal classifiers. */reasoningEffort?: 'minimal' | 'low' | 'medium' | 'high';+ /**+ * Disable provider-native thinking for strict short-output budgets. Messages+ * and chat routes send `thinking.type=disabled`; Responses routes use the+ * lowest supported effort because that protocol has no off value.+ */+ disableReasoning?: boolean;/** Abort an in-flight direct HTTP request when the owning workflow ends. */signal?: AbortSignal;/** Provider-native system/instructions text, kept separate from reference data. */@@ -555,7 +561,8 @@ async function requestExplicitProviderText(// Model resolution is scoped to the selected agent. Never use provider.titleModel// here: that legacy field may belong to another runtime (for example Codex),// which would silently turn a Claude request into a Codex request.- const model = requestedModel || configuredModels[0]?.id || '';+ const model = requestedModel || configuredModels.find((item) =>+ isModelSelectableForNewRoute(item, { userProvider: provider?.source === 'user' }))?.id || '';const selectedRouting = agentKind ? provider?.routing[agentKind] : undefined;const transport: UtilityModelTransport =agentKind === 'codex' && selectedRouting?.wireProtocol !== 'openai-chat'@@ -601,7 +608,9 @@ async function requestExplicitProviderText(}],};}- if (requestedModel && !configuredModels.some((item) => item.id === requestedModel)) {+ if (requestedModel && !configuredModels.some((item) =>+ item.id === requestedModel+ && isModelSelectableForNewRoute(item, { userProvider: provider.source === 'user' }))) {return {ok: false,reason: 'no_candidate',@@ -630,7 +639,7 @@ async function requestExplicitProviderText(const currentModel = currentProvider.models[agentKind]?.find((item) => item.id === model);if (!currentModel ||- !isAgentSelectableModel(currentModel, { userProvider: currentProvider.source === 'user' })+ !isModelSelectableForNewRoute(currentModel, { userProvider: currentProvider.source === 'user' })) return false;return stableSnapshot({routing: currentProvider.routing[agentKind],@@ -653,6 +662,7 @@ async function requestExplicitProviderText(maxTokens: opts.maxTokens,timeoutMs: opts.timeoutMs,reasoningEffort: opts.reasoningEffort,+ disableReasoning: opts.disableReasoning,signal: opts.signal,systemPrompt: opts.systemPrompt,responseInstructions: opts.responseInstructions,@@ -751,6 +761,7 @@ async function requestExplicitProviderText(maxTokens: requestOpts?.maxTokens,timeoutMs: requestOpts?.timeoutMs,reasoningEffort: requestOpts?.reasoningEffort,+ disableReasoning: requestOpts?.disableReasoning,signal: requestOpts?.signal,systemPrompt: requestOpts?.systemPrompt,responseInstructions: requestOpts?.responseInstructions,@@ -815,6 +826,7 @@ async function requestBuiltinProviderText(maxTokens?: number;timeoutMs?: number;reasoningEffort?: 'minimal' | 'low' | 'medium' | 'high';+ disableReasoning?: boolean;signal?: AbortSignal;systemPrompt?: string;responseInstructions?: string;@@ -868,6 +880,7 @@ async function requestBuiltinProviderText(maxTokens: requestOpts?.maxTokens ?? input.maxTokens,timeoutMs: requestOpts?.timeoutMs ?? input.timeoutMs,reasoningEffort: requestOpts?.reasoningEffort ?? input.reasoningEffort,+ disableReasoning: requestOpts?.disableReasoning ?? input.disableReasoning,signal: requestOpts?.signal ?? input.signal,systemPrompt: requestOpts?.systemPrompt,responseInstructions: requestOpts?.responseInstructions,@@ -914,6 +927,7 @@ async function requestBuiltinProviderText(maxTokens: requestOpts?.maxTokens ?? input.maxTokens ?? catalogModel?.maxOutput ?? 81_920,timeoutMs: requestOpts?.timeoutMs ?? input.timeoutMs,reasoningEffort: requestOpts?.reasoningEffort ?? input.reasoningEffort,+ disableReasoning: requestOpts?.disableReasoning ?? input.disableReasoning,signal: requestOpts?.signal ?? input.signal,systemPrompt: requestOpts?.systemPrompt,responseInstructions: requestOpts?.responseInstructions,@@ -965,6 +979,7 @@ async function requestBuiltinProviderText(maxTokens: requestOpts?.maxTokens ?? input.maxTokens,timeoutMs: requestOpts?.timeoutMs ?? input.timeoutMs,reasoningEffort: requestOpts?.reasoningEffort ?? input.reasoningEffort,+ disableReasoning: requestOpts?.disableReasoning ?? input.disableReasoning,// ChatGPT's private Codex Responses endpoint rejects this public API// parameter with HTTP 400. The Auto reviewer enforces its own compact// output ceiling after the response instead.@@ -1016,6 +1031,7 @@ async function requestBuiltinProviderText(maxTokens: requestOpts?.maxTokens ?? input.maxTokens,timeoutMs: requestOpts?.timeoutMs ?? input.timeoutMs,reasoningEffort: requestOpts?.reasoningEffort ?? input.reasoningEffort,+ disableReasoning: requestOpts?.disableReasoning ?? input.disableReasoning,supportsReasoning: supportsXaiReasoning(input.model),signal: requestOpts?.signal ?? input.signal,systemPrompt: requestOpts?.systemPrompt,@@ -1293,6 +1309,7 @@ async function requestProviderHttpText(input: {maxTokens?: number;timeoutMs?: number;reasoningEffort?: 'minimal' | 'low' | 'medium' | 'high';+ disableReasoning?: 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. */@@ -1322,13 +1339,17 @@ async function requestProviderHttpText(input: {const instructions = [input.systemPrompt, input.responseInstructions].filter((value): value is string => typeof value === 'string' && value.trim().length > 0).join('\n');+ const reasoningEffort = input.disableReasoning+ ? 'minimal'+ : input.reasoningEffort;const supportsRequestedReasoning = Boolean(input.wire !== 'anthropic-messages'- && input.reasoningEffort+ && reasoningEffort&& input.supportsReasoning !== false,);const hasOptionalRequestFields = input.wire === 'responses'|| input.maxTokens !== undefined+ || input.disableReasoning === true|| supportsRequestedReasoning;const buildBody = (minimal: boolean) => input.wire === 'responses'? {@@ -1343,7 +1364,7 @@ async function requestProviderHttpText(input: {? { max_output_tokens: input.maxTokens }: {}),...(!minimal && supportsRequestedReasoning- ? { reasoning: { effort: input.reasoningEffort } }+ ? { reasoning: { effort: reasoningEffort } }: {}),}: input.wire === 'anthropic-messages'@@ -1354,13 +1375,15 @@ async function requestProviderHttpText(input: {// 回退,不是宿主承诺的输出上限。max_tokens: input.maxTokens ?? 81_920,...(instructions ? { system: instructions } : {}),+ ...(!minimal && input.disableReasoning ? { thinking: { type: 'disabled' } } : {}),messages: [{ role: 'user', content: input.prompt }],}: {model: input.model,...(!minimal && input.maxTokens !== undefined ? { max_tokens: input.maxTokens } : {}),+ ...(!minimal && input.disableReasoning ? { thinking: { type: 'disabled' } } : {}),...(!minimal && supportsRequestedReasoning- ? { reasoning_effort: input.reasoningEffort }+ ? { reasoning_effort: reasoningEffort }: {}),messages: [...(instructions ? [{ role: 'system', content: instructions }] : []),@@ -1514,6 +1537,7 @@ async function requestCustomProviderText(input: {maxTokens?: number;timeoutMs?: number;reasoningEffort?: 'minimal' | 'low' | 'medium' | 'high';+ disableReasoning?: boolean;signal?: AbortSignal;systemPrompt?: string;responseInstructions?: string;@@ -1565,6 +1589,7 @@ async function requestCustomProviderText(input: {maxTokens: input.maxTokens,timeoutMs: input.timeoutMs,reasoningEffort: input.reasoningEffort,+ disableReasoning: input.disableReasoning,retryWithMinimalBodyOnInvalidRequest: true,signal: input.signal,systemPrompt: input.systemPrompt,diff --git a/apps/desktop/src/main/utility-model/textOneshotPinOptions.ts b/apps/desktop/src/main/utility-model/textOneshotPinOptions.tsindex 3e597e0b40..fa25e46221 100644--- a/apps/desktop/src/main/utility-model/textOneshotPinOptions.ts+++ b/apps/desktop/src/main/utility-model/textOneshotPinOptions.ts@@ -19,7 +19,7 @@import {classifyModel,- isAgentSelectableModel,+ isModelSelectableForNewRoute,isModelDisabled,isProviderDisabled,type AgentKind,@@ -97,8 +97,7 @@ function isRoutableForOneshot(provider: Provider, agentKind: AgentKind): boolean* 更宽的判据会把 mode 缺省、group='image' 的网关条目放进钉档清单,钉死* 不回落 = 恒失败)。userProvider 标记镜像模型选择器的自定义供应商放行。 */function isChatModel(model: CatalogModel, provider: Provider): boolean {- return model.disabled !== true- && isAgentSelectableModel(model, { userProvider: provider.source === 'user' });+ return isModelSelectableForNewRoute(model, { userProvider: provider.source === 'user' });}const AGENT_LABEL: Record<(typeof ONESHOT_ROUTE_AGENTS)[number], string> = {diff --git a/apps/desktop/src/shared/catalogModelPin.ts b/apps/desktop/src/shared/catalogModelPin.tsindex 367a84b8bb..a6c66a84f0 100644--- a/apps/desktop/src/shared/catalogModelPin.ts+++ b/apps/desktop/src/shared/catalogModelPin.ts@@ -1,10 +1,10 @@/*** A stable catalog route pin for one-shot text work.*- * The model id may contain both `/` and `:`, so only the first two separators- * after `cat:` are structural. Keep this parser shared by persistence, IPC and- * execution so a value accepted by Settings is always decoded the same way at- * dispatch time.+ * The provider and model ids may contain `:`, so the provider segment is URI+ * encoded while the model remains the final opaque segment. Keep this parser+ * shared by persistence, IPC and execution so a value accepted by Settings is+ * always decoded the same way at dispatch time.*/export const CATALOG_MODEL_PIN_PREFIX = 'cat:';@@ -21,7 +21,7 @@ const CATALOG_MODEL_PIN_AGENTS = new Set<CatalogModelPinAgentKind>(['codex', 'cl/** Encode an exact provider × runtime × model route. */export function encodeCatalogModelPin(route: CatalogModelPinRoute): string {- return `${CATALOG_MODEL_PIN_PREFIX}${route.providerId}:${route.agentKind}:${route.model}`;+ return `${CATALOG_MODEL_PIN_PREFIX}${encodeURIComponent(route.providerId)}:${route.agentKind}:${route.model}`;}/** Decode a catalog pin; malformed or unsupported-runtime values return null. */@@ -33,10 +33,15 @@ export function decodeCatalogModelPin(raw: string): CatalogModelPinRoute | nullconst secondSep = rest.indexOf(':', firstSep + 1);if (secondSep <= firstSep + 1) return null;- const providerId = rest.slice(0, firstSep);+ let providerId: string;+ try {+ providerId = decodeURIComponent(rest.slice(0, firstSep));+ } catch {+ return null;+ }const agentKind = rest.slice(firstSep + 1, secondSep);const model = rest.slice(secondSep + 1);- if (!model || !CATALOG_MODEL_PIN_AGENTS.has(agentKind as CatalogModelPinAgentKind)) {+ if (!providerId || !model || !CATALOG_MODEL_PIN_AGENTS.has(agentKind as CatalogModelPinAgentKind)) {return null;}return {diff --git a/packages/maker-core/src/agents/pi/__tests__/cindySubagentForeground.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindySubagentForeground.test.tsindex a2b10bdfed..ecfe6f98d2 100644--- a/packages/maker-core/src/agents/pi/__tests__/cindySubagentForeground.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentForeground.test.ts@@ -335,7 +335,6 @@ setTimeout(() => process.exit(0), 20000).unref();const fs = require('node:fs');const path = require('node:path');const config = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));-fs.writeFileSync(path.join(config.runDir, 'started'), '1');const timer = setInterval(() => {let files = [];try { files = fs.readdirSync(path.join(config.runDir, 'controls')); } catch {}@@ -357,6 +356,10 @@ const timer = setInterval(() => {process.exit(0);}}, 20);+// Publish readiness only after the stop-control poller is installed. Writing+// this before setInterval leaves a small CI race where the parent aborts while+// this fixture is still initializing and observes only the process exit.+fs.writeFileSync(path.join(config.runDir, 'started'), '1');setTimeout(() => process.exit(2), 5000).unref();`, { mode: 0o700 });const previous = { ...process.env };