Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(voice-input): 词典学习统一使用辅助模型通道 (#3981)
Dash9227cc077ff6
diff --git a/apps/desktop/src/main/utility-model/__tests__/auxiliaryCustomNoAgentFallback.test.ts b/apps/desktop/src/main/utility-model/__tests__/auxiliaryCustomNoAgentFallback.test.tsindex 0ed376bce0..82de3aa1c7 100644--- a/apps/desktop/src/main/utility-model/__tests__/auxiliaryCustomNoAgentFallback.test.ts+++ b/apps/desktop/src/main/utility-model/__tests__/auxiliaryCustomNoAgentFallback.test.ts@@ -42,9 +42,13 @@ describe('custom auxiliary chain does not hit the session agent', () => {});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);');+ const source = readFileSync(path.join(root, 'voice-input/index.ts'), 'utf8').replace(/\r\n/g, '\n');+ expect(source).toContain(`const advisorClient = new DictionaryLearningTextModelClient(+ (prompt, requestOptions) => requestUtilityText(getMaker(), prompt, requestOptions),+ () => assertVoiceInputOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot),+ );`);+ expect(source).toContain(`const result = await advisor.advise(adviceInput);+ assertVoiceInputOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot);+ const recordResult = voiceInputDataStore.recordDictionaryLearningActions(result.actions);`);});});diff --git a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.tsindex 773b3a9da7..b0e62fab33 100644--- a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts+++ b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts@@ -95,6 +95,8 @@ vi.mock('../../model-access/effectiveEndpoint.js', async () => {});import type { Maker } from '@cindy/maker-core';+import { DictationDictionaryAdvisor } from '@cindy/voice-input-core';+import { DictionaryLearningTextModelClient } from '../../voice-input/DictionaryLearningTextModelClient.js';import { fetch as undiciFetch } from 'undici';import { getAppCapabilities } from '../../appCapabilities.js';@@ -2445,6 +2447,160 @@ describe('utility one-shot candidates', () => {},);+ describe('dictionary learning through the auxiliary chain', () => {+ const action = {+ action: 'add_entry', term: 'Vibe Coding', aliases: ['web coding'],+ type: 'technical_term', confidence: 'high',+ };+ const responseText = JSON.stringify({ actions: [action] });++ function advisor(maker = makerMock(false)) {+ const client = new DictionaryLearningTextModelClient(+ (prompt, opts) => requestUtilityText(maker, prompt, opts),+ () => {},+ );+ return { client, advisor: new DictationDictionaryAdvisor({ client, model: 'auxiliary' }) };+ }++ function selectClaude() {+ chainState.source = 'custom';+ chainState.refs = ['cat:anthropic:claude-code:claude-haiku-4-5'];+ activeCatalog.mockReturnValue({ providers: [{+ id: 'anthropic', name: 'Anthropic', source: 'builtin', agents: ['claude-code'],+ auth: { method: 'oauth' },+ routing: { 'claude-code': { upstream: 'https://anthropic.example/v1', authStrategy: 'oauth-passthrough' } },+ models: { 'claude-code': [{ id: 'claude-haiku-4-5', name: 'Haiku', contextWindow: 200_000 }] },+ }] } as never);+ readClaudeOAuth.mockResolvedValue({ accessToken: 'fake-anthropic-token' });+ }++ const evidence = { beforeText: '继续试一下 web coding。', afterText: '继续试一下 Vibe Coding。' };++ it('learns through a selected Claude model without any Codex credentials', async () => {+ selectClaude();+ fetchMock.mockResolvedValueOnce({+ ok: true,+ text: async () => JSON.stringify({ content: [{ type: 'text', text: responseText }] }),+ } as never);+ const sut = advisor();++ expect((await sut.advisor.advise(evidence)).actions).toEqual([action]);+ expect(sut.client.servedRoute).toEqual({ providerId: 'anthropic', model: 'claude-haiku-4-5' });+ expect(readCodexCreds).not.toHaveBeenCalled();+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body)).max_tokens).toBe(4_096);+ });++ const invalidOutputs = ['not JSON', '{}', '{"actions":null}', '{"actions":{}}'];++ it.each(invalidOutputs)('falls back after user-provider output %s and accepts empty actions', async (invalidText) => {+ chainState.source = 'custom';+ chainState.refs = ['cat:dictionary-custom:codex:first', 'cat:dictionary-custom:codex:second'];+ activeCatalog.mockReturnValue({ providers: [{+ id: 'dictionary-custom', name: 'Dictionary Custom', source: 'user', agents: ['codex'],+ auth: { method: 'apiKey' },+ routing: { codex: {+ upstream: 'https://dictionary.example/v1', wireProtocol: 'openai-chat', authStrategy: 'api-key-header',+ } },+ models: { codex: ['first', 'second'].map((id) => ({ id, name: id, contextWindow: 100_000 })) },+ }] } as never);+ readCustomKey.mockReturnValue('fake-custom-key');+ for (const content of [invalidText, '{"actions":[]}']) {+ fetchMock.mockResolvedValueOnce({+ ok: true, text: async () => JSON.stringify({ choices: [{ message: { content } }] }),+ } as never);+ }+ const sut = advisor();++ expect((await sut.advisor.advise(evidence)).actions).toEqual([]);+ expect(sut.client.servedRoute).toEqual({ providerId: 'dictionary-custom', model: 'second' });+ expect(fetchMock.mock.calls.map(([, opts]) => JSON.parse(String(opts?.body)))).toEqual([+ expect.objectContaining({ model: 'first', max_tokens: 4_096 }),+ expect.objectContaining({ model: 'second', max_tokens: 4_096 }),+ ]);+ });++ it.each(invalidOutputs)('falls back to the third custom selection after %s and HTTP failure', async (invalidText) => {+ selectClaude();+ chainState.refs.push('litellm-kimi-k2.6', 'litellm-deepseek-v4-flash');+ readKey.mockReturnValue('fake-proxy-key');+ fetchMock+ .mockResolvedValueOnce({+ ok: true, text: async () => JSON.stringify({ content: [{ type: 'text', text: invalidText }] }),+ } as never)+ .mockResolvedValueOnce({ ok: false, status: 503, body: { cancel: vi.fn() } } as never)+ .mockResolvedValueOnce({+ ok: true, json: async () => ({ choices: [{ message: { content: responseText } }] }),+ } as never);+ const sut = advisor();++ expect((await sut.advisor.advise(evidence)).actions).toEqual([action]);+ expect(sut.client.servedRoute?.model).toBe('deepseek/deepseek-v4-flash');+ expect(fetchMock.mock.calls.map(([, opts]) => JSON.parse(String(opts?.body)).model)).toEqual([+ 'claude-haiku-4-5', 'moonshotai/kimi-k2.6', 'deepseek/deepseek-v4-flash',+ ]);+ });++ it.each(invalidOutputs)('falls back after profile output %s and accepts empty actions', async (invalidText) => {+ const maker = makerMock(true);+ vi.mocked(maker.oneShot).mockResolvedValue(invalidText);+ readKey.mockReturnValue('fake-proxy-key');+ fetchMock.mockResolvedValueOnce({+ ok: true, json: async () => ({ choices: [{ message: { content: '{"actions":[]}' } }] }),+ } as never);++ expect((await advisor(maker).advisor.advise(evidence)).actions).toEqual([]);+ expect(maker.oneShot).toHaveBeenCalledTimes(1);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('fails safely after invalid custom-chain output without trying unrelated defaults', async () => {+ selectClaude();+ fetchMock.mockResolvedValueOnce({+ ok: true, text: async () => JSON.stringify({ content: [{ type: 'text', text: 'private response body' }] }),+ } as never);+ const maker = makerMock(true);++ await expect(advisor(maker).advisor.advise(evidence))+ .rejects.toThrow('Dictionary learning failed: all_candidates_failed');+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(maker.oneShot).not.toHaveBeenCalled();+ });++ it.each(['owner', 'chain'] as const)('does not dispatch a fallback after the %s changes', async (changed) => {+ chainState.source = 'custom';+ chainState.refs = ['litellm-kimi-k2.6', 'litellm-deepseek-v4-flash'];+ readKey.mockReturnValue('fake-proxy-key');+ fetchMock.mockImplementationOnce(async () => {+ if (changed === 'owner') ownerState.key = 'owner-b';+ else chainState.refs = ['litellm-gpt-5.4-mini'];+ return { ok: true, json: async () => ({ choices: [{ message: { content: 'invalid' } }] }) } as never;+ });++ await expect(advisor().advisor.advise(evidence)).rejects.toThrow('Dictionary learning failed:');+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it.each(invalidOutputs)('rejects explicit builtin output %s without using defaults', async (invalidText) => {+ selectClaude();+ fetchMock.mockResolvedValueOnce({+ ok: true, text: async () => JSON.stringify({ content: [{ type: 'text', text: invalidText }] }),+ } as never);+ const maker = makerMock(true);+ const client = new DictionaryLearningTextModelClient(+ (prompt, opts) => requestUtilityText(maker, prompt, {+ ...opts, providerId: 'anthropic', agentKind: 'claude-code', model: 'claude-haiku-4-5',+ }),+ () => {},+ );++ await expect(new DictationDictionaryAdvisor({ client, model: 'auxiliary' }).advise(evidence))+ .rejects.toThrow('Dictionary learning failed: all_candidates_failed');+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(maker.oneShot).not.toHaveBeenCalled();+ });+ });+it('tries a one-item custom chain in order and never expands to AUTO', async () => {chainState.source = 'custom';chainState.refs = ['litellm-kimi-k2.6'];diff --git a/apps/desktop/src/main/utility-model/oneShotCandidates.ts b/apps/desktop/src/main/utility-model/oneShotCandidates.tsindex 7537662d86..53e10103fe 100644--- a/apps/desktop/src/main/utility-model/oneShotCandidates.ts+++ b/apps/desktop/src/main/utility-model/oneShotCandidates.ts@@ -115,6 +115,8 @@ export type UtilityTextRequestOptions = {systemPrompt?: string;/** Additional output-shape instruction (mainly for Responses-compatible routes). */responseInstructions?: string;+ /** Reject unusable output before selecting a winner, so the configured chain can continue. */+ validateResponse?: (text: string) => boolean;/** Final ownership/config guard immediately before an explicit HTTP dispatch. */beforeDispatch?: (route: UtilityTextDispatchRoute) => Promise<boolean>;/** 显式任务来源;存在时禁止跨来源 fallback。 */@@ -592,7 +594,7 @@ async function runDefaultProfileCandidates(};try {const text = (await candidate.execute(prompt, candidateOpts)).trim();- if (!text) throw new UtilityTextExecutionError({ reason: 'empty_response' });+ validateUtilityResponse(text, opts);return {ok: true,text,@@ -626,6 +628,13 @@ function failedChainResult(attempts: UtilityTextAttempt[]): UtilityTextResult {return { ok: false, reason, attempts };}+function validateUtilityResponse(text: string, opts?: UtilityTextRequestOptions): void {+ if (!text) throw new UtilityTextExecutionError({ reason: 'empty_response' });+ if (opts?.validateResponse && !opts.validateResponse(text)) {+ throw new UtilityTextExecutionError({ reason: 'request_failed' });+ }+}+async function requestDefaultUtilityText(maker: Maker,prompt: string,@@ -855,6 +864,7 @@ async function requestExplicitProviderText(signal: opts.signal,systemPrompt: opts.systemPrompt,responseInstructions: opts.responseInstructions,+ validateResponse: opts.validateResponse,beforeDispatch: opts.beforeDispatch,routeStillCurrent,});@@ -1029,6 +1039,7 @@ async function requestBuiltinProviderText(signal?: AbortSignal;systemPrompt?: string;responseInstructions?: string;+ validateResponse?: (text: string) => boolean;beforeDispatch?: (route: UtilityTextDispatchRoute) => Promise<boolean>;routeStillCurrent?: () => boolean;},@@ -1285,7 +1296,7 @@ async function executeCandidates(}try {const text = (await candidate.execute(prompt, opts)).trim();- if (!text) throw new UtilityTextExecutionError({ reason: 'empty_response' });+ validateUtilityResponse(text, opts);log.info('explicit utility text provider succeeded', {providerId: candidate.providerId,model: candidate.model,diff --git a/apps/desktop/src/main/voice-input/DictionaryLearningTextModelClient.ts b/apps/desktop/src/main/voice-input/DictionaryLearningTextModelClient.tsnew file mode 100644index 0000000000..bfeaec3f38--- /dev/null+++ b/apps/desktop/src/main/voice-input/DictionaryLearningTextModelClient.ts@@ -0,0 +1,69 @@+import type { TextModelClient } from '@cindy/voice-input-core';++import type { UtilityTextResult } from '../../shared/utilityTextResult.js';+import type { UtilityTextRequestOptions } from '../utility-model/oneShotCandidates.js';++type RequestText = (prompt: string, opts: UtilityTextRequestOptions) => Promise<UtilityTextResult>;++/** Adapt dictionary JSON requests to the full auxiliary chain, without voice transport filtering. */+export class DictionaryLearningTextModelClient implements TextModelClient {+ servedRoute?: { providerId: string; model: string };++ constructor(+ private readonly requestText: RequestText,+ private readonly assertRequestCurrent: () => void,+ ) {}++ async requestJson<T>(input: Parameters<TextModelClient['requestJson']>[0]): Promise<T> {+ this.assertRequestCurrent();+ this.servedRoute = undefined;+ // Model selection and fallback belong to requestUtilityText. The advisor's+ // model/cache labels must not pin a provider or reintroduce the voice chain.+ const result = await this.requestText(JSON.stringify(input.user), {+ systemPrompt: input.system,+ timeoutMs: 8_000,+ // The advisor returns at most three actions, not a general text response.+ maxTokens: 4_096,+ disableReasoning: true,+ beforeDispatch: async () => {+ this.assertRequestCurrent();+ return true;+ },+ validateResponse: (text) => {+ try {+ parseDictionaryResponse(text);+ return true;+ } catch {+ return false;+ }+ },+ });+ this.assertRequestCurrent();+ if (!result.ok) throw new Error(`Dictionary learning failed: ${result.reason}`);+ const parsed = parseDictionaryResponse(result.text);+ this.servedRoute = { providerId: result.providerId, model: result.model };+ return parsed as T;+ }+}++function parseDictionaryResponse(text: string): unknown {+ // Preserve the previous clients' fenced/wrapped JSON compatibility, but+ // never include model output in an exception sent to logs or the renderer.+ let parsed: unknown;+ try {+ try {+ parsed = JSON.parse(text.trim());+ } catch {+ const match = text.match(/\{[\s\S]*\}/);+ if (!match) throw new Error('Invalid dictionary response');+ parsed = JSON.parse(match[0]);+ }+ } catch {+ throw new Error('Invalid dictionary response');+ }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)+ || !('actions' in parsed) || !Array.isArray(parsed.actions)) {+ throw new Error('Invalid dictionary response');+ }+ return parsed;+}diff --git a/apps/desktop/src/main/voice-input/__tests__/DictionaryLearningTextModelClient.test.ts b/apps/desktop/src/main/voice-input/__tests__/DictionaryLearningTextModelClient.test.tsnew file mode 100644index 0000000000..72a0883cdb--- /dev/null+++ b/apps/desktop/src/main/voice-input/__tests__/DictionaryLearningTextModelClient.test.ts@@ -0,0 +1,97 @@+import { describe, expect, it, vi } from 'vitest';++import type { UtilityTextResult } from '../../../shared/utilityTextResult.js';+import type { UtilityTextRequestOptions } from '../../utility-model/oneShotCandidates.js';+import { DictionaryLearningTextModelClient } from '../DictionaryLearningTextModelClient.js';++const input = {+ model: 'auxiliary',+ schemaName: 'dictation_dictionary_learning',+ system: 'Existing dictionary learning instructions',+ user: { beforeText: 'web coding', afterText: 'Vibe Coding' },+};+const success: UtilityTextResult = {+ ok: true,+ text: '```json\n{"actions":[]}\n```',+ providerId: 'anthropic',+ model: 'fixture-model',+ transport: 'litellm-chat-completions',+};++describe('DictionaryLearningTextModelClient', () => {+ it('keeps system and evidence separate, accepts wrapped JSON, and leaves routing to the auxiliary chain', async () => {+ const requestText = vi.fn<(prompt: string, opts: UtilityTextRequestOptions) => Promise<UtilityTextResult>>()+ .mockResolvedValue(success);+ const guard = vi.fn();+ const client = new DictionaryLearningTextModelClient(requestText, guard);++ await expect(client.requestJson(input)).resolves.toEqual({ actions: [] });++ const [prompt, opts] = requestText.mock.calls[0];+ expect(JSON.parse(prompt)).toEqual(input.user);+ expect(opts.systemPrompt).toBe(input.system);+ expect(opts.maxTokens).toBe(4_096);+ expect(opts).not.toHaveProperty('providerId');+ expect(opts).not.toHaveProperty('model');+ expect(opts).not.toHaveProperty('pinnedProfileId');+ expect(opts.validateResponse?.(success.text)).toBe(true);+ expect(opts.validateResponse?.('{"actions":[]}')).toBe(true);+ for (const text of [+ 'private response body', '{"actions":', 'null', '[]',+ '{}', '{"action":"add_entry"}', '{"actions":null}', '{"actions":{}}',+ ]) {+ expect(opts.validateResponse?.(text)).toBe(false);+ }+ expect(client.servedRoute).toEqual({ providerId: 'anthropic', model: 'fixture-model' });+ expect(guard).toHaveBeenCalledTimes(2);+ });++ it('checks the original request scope immediately before dispatch', async () => {+ let current = true;+ const guard = () => {+ if (!current) throw new Error('request scope changed');+ };+ const requestText = vi.fn(async (_prompt: string, opts: UtilityTextRequestOptions) => {+ current = false;+ await opts.beforeDispatch?.({ providerId: 'anthropic', agentKind: 'claude-code', model: 'fixture' });+ return success;+ });++ await expect(new DictionaryLearningTextModelClient(requestText, guard).requestJson(input))+ .rejects.toThrow('request scope changed');+ });++ it('rejects a late success after the owner or auxiliary configuration changes', async () => {+ let current = true;+ const requestText = vi.fn(async () => {+ current = false;+ return success;+ });+ const client = new DictionaryLearningTextModelClient(requestText, () => {+ if (!current) throw new Error('request scope changed');+ });++ await expect(client.requestJson(input)).rejects.toThrow('request scope changed');+ expect(client.servedRoute).toBeUndefined();+ });++ it('reports exhausted auxiliary routes without exposing response bodies', async () => {+ const requestText = vi.fn(async (): Promise<UtilityTextResult> => ({+ ok: false, reason: 'all_candidates_failed', attempts: [],+ }));+ const client = new DictionaryLearningTextModelClient(requestText, () => {});++ await expect(client.requestJson(input)).rejects.toThrow('Dictionary learning failed: all_candidates_failed');+ expect(requestText).toHaveBeenCalledTimes(1);+ });++ it('does not return malformed JSON even if a requester ignores the validation hook', async () => {+ const client = new DictionaryLearningTextModelClient(+ async () => ({ ...success, text: 'private response body' }),+ () => {},+ );++ await expect(client.requestJson(input)).rejects.toThrow(/^Invalid dictionary response$/);+ expect(client.servedRoute).toBeUndefined();+ });+});diff --git a/apps/desktop/src/main/voice-input/index.ts b/apps/desktop/src/main/voice-input/index.tsindex 7a29e7a111..477fae3be3 100644--- a/apps/desktop/src/main/voice-input/index.ts+++ b/apps/desktop/src/main/voice-input/index.ts@@ -26,7 +26,9 @@ import {isProviderModelRouteDisabled,isUtilityRouteDisabled,isUtilityRoutePaymentRequired,+ requestUtilityText,} from '../utility-model/oneShotCandidates.js';+import { getMaker } from '../maker-host/index.js';import { getEffectiveAuxiliaryModelChainSnapshot } from '../utility-model/resolveAuxiliaryModelChain.js';import { getAppCapabilities } from '../appCapabilities.js';import { getProviderSecretStore } from '../secrets/providerSecretStore.js';@@ -47,6 +49,7 @@ import {prewarmCodexResponsesEndpoint,} from './CodexResponsesTextModelClient.js';import { ElevenLabsScribeProvider } from './ElevenLabsScribeProvider.js';+import { DictionaryLearningTextModelClient } from './DictionaryLearningTextModelClient.js';import { FallbackAsrProvider } from './FallbackAsrProvider.js';import {FallbackTextModelClient,@@ -376,41 +379,15 @@ export async function adviseAndRecordVoiceInputDictionaryLearning(};}- // Same fallback chain as dictation refinement: the advisor is a background- // task, but a primary refiner outage should degrade to a backup model- // instead of silently dropping dictionary learning.- const {- refinerReadinessList: advisorReadinessList,- readyRefinerProfiles: readyAdvisorProfiles,- } = await resolveVoiceInputRefinerChainForRuntime();- const advisorHeadProfile = readyAdvisorProfiles[0];- if (!advisorHeadProfile) {- return {- ok: false,- error: advisorReadinessList[0]?.error ?? 'Dictionary learning advisor requires a configured refiner.',- };- }-try {- const senderId = options.senderId ?? 'device-link';- const advisorAttempts: FallbackTextModelAttempt[] = readyAdvisorProfiles.map((profile) => ({- profileId: profile.id as VoiceInputRefinerProviderKind,- model: profile.model,- client: guardRefinerClientAgainstUnavailableRoute(- profile,- createVoiceInputTextModelClient(profile, {- beforeDispatch: () => {- assertVoiceInputOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot);- assertRefinerRouteAvailable(profile);- },- }),- ),- promptCacheScope: `dictionaryLearning:${profile.id}:${senderId}`,- }));+ const advisorClient = new DictionaryLearningTextModelClient(+ (prompt, requestOptions) => requestUtilityText(getMaker(), prompt, requestOptions),+ () => assertVoiceInputOwnerScopeCurrent(ownerScopeKey, auxiliaryChainSnapshot),+ );const advisor = new DictationDictionaryAdvisor({- client: new FallbackTextModelClient(advisorAttempts),- model: advisorHeadProfile.model,- promptCacheScope: `dictionaryLearning:${advisorHeadProfile.id}:${senderId}`,+ client: advisorClient,+ // The adapter resolves the shared auxiliary chain; this is not a route pin.+ model: 'auxiliary',debug: DICTIONARY_LEARNING_TEXT_DEBUG,});const settings = voiceInputDataStore.getSettings();@@ -447,9 +424,8 @@ export async function adviseAndRecordVoiceInputDictionaryLearning(confidence: action.confidence,reason: action.reason,})),- refinerProvider: advisorHeadProfile.id,- refinerModel: advisorHeadProfile.model,- refinerChain: readyAdvisorProfiles.map((profile) => profile.id),+ auxiliaryProvider: advisorClient.servedRoute?.providerId,+ auxiliaryModel: advisorClient.servedRoute?.model,ignoreReason: result.ignoreReason,elapsedMs: Math.round(result.elapsedMs),debugText: DICTIONARY_LEARNING_TEXT_DEBUG