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。

fix(voice): address OpenRouter OAuth review and CI failures

JiangJiahaob629bfec30a3
diff --cc apps/desktop/src/main/maker-host/__tests__/genericOAuth.test.ts
index 9357681e91,0354b59735..b7e486a21b
--- a/apps/desktop/src/main/maker-host/__tests__/genericOAuth.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/genericOAuth.test.ts
@@@ -13,7 -13,7 +13,7 @@@ import { providerPresetOAuth } from '@c
* - setDiscoveredProviderModels 的 additions-only merge。
*/
--import { describe, it, expect, beforeEach, afterEach } from 'vitest';
++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import type { OAuthProviderDescriptor, ProviderView } from '@cindy/model-providers';
import { fetchSavedOAuthProviderModels } from '../provider-model-fetch.js';
@@@ -632,6 -613,6 +632,48 @@@ describe('登录流与凭证落盘失�
});
describe('discoverGenericOAuthModels', () => {
++ // PR #6900 unit regression: the login follow-up (unlike saved refresh) could
++ // send more Bearer requests after cancellation. Hold a real catalog response
++ // at each async boundary; no subsequent page or late result may escape.
++ it.each(['before-request', 'first-page', 'next-page', 'speech-page', 'active'] as const)(
++ 'checks login ownership before every catalog request: %s', async (phase) => {
++ seedBlob('router', { access_token: 'fake-login-key' });
++ const oauth = providerPresetOAuth('openrouter')!;
++ const endpoint = oauth.modelsDiscoveryUrl!;
++ let current = phase !== 'before-request';
++ let release!: (value: unknown) => void;
++ const waiting = new Promise<unknown>(resolve => { release = resolve; });
++ const pausedUrl = phase === 'next-page' ? `${endpoint}?cursor=next`
++ : phase === 'speech-page' ? `${endpoint}?output_modalities=speech` : endpoint;
++ fetchResponder = (url) => {
++ const payload = url.includes('output_modalities=speech')
++ ? { data: [{ id: 'tts', architecture: { output_modalities: ['speech'] } }] }
++ : { data: ['chat'], ...(url === endpoint ? { next_cursor: 'next' } : {}) };
++ const response = new Response(JSON.stringify(payload));
++ if (url === pausedUrl && current && phase !== 'active') {
++ response.json = () => waiting.then(() => payload);
++ }
++ return response;
++ };
++ const pending = discoverGenericOAuthModels('router', oauth, undefined, 'claude-code', () => current);
++ if (phase !== 'before-request' && phase !== 'active') {
++ await vi.waitFor(() => expect(fetchCalls.at(-1)?.url).toBe(pausedUrl));
++ current = false;
++ release(undefined);
++ }
++ const result = await pending;
++ expect(fetchCalls.map(({ url }) => url)).toEqual(
++ phase === 'before-request' ? [] : [endpoint,
++ ...(['next-page', 'speech-page', 'active'].includes(phase) ? [`${endpoint}?cursor=next`] : []),
++ ...(['speech-page', 'active'].includes(phase) ? [`${endpoint}?output_modalities=speech`] : []),
++ ],
++ );
++ for (const request of fetchCalls) expect(request.headers).toEqual({ authorization: 'Bearer fake-login-key' });
++ if (phase === 'active') expect(result?.map(model => model.id)).toEqual(['chat', 'tts']);
++ else expect(result).toBeNull();
++ },
++ );
++
it('解析 {data:[{id}]} 形状并去重', async () => {
seedBlob('acme', { access_token: 'at' });
fetchResponder = () =>
diff --cc apps/desktop/src/main/maker-host/generic-oauth.ts
index 4fbbf4eace,4fbbf4eace..387dd6fef6
--- a/apps/desktop/src/main/maker-host/generic-oauth.ts
+++ b/apps/desktop/src/main/maker-host/generic-oauth.ts
@@@ -849,9 -849,9 +849,10 @@@ export async function discoverGenericOA
oauth: OAuthProviderDescriptor,
discoveryUrl?: string,
agent?: AgentKind,
++ isCurrent: () => boolean = () => true,
): Promise<DiscoveredModel[] | null> {
const url = discoveryUrl ?? oauth.modelsDiscoveryUrl;
-- if (!url) return null;
++ if (!url || !isCurrent()) return null;
const token = readCachedGenericOAuthAccessToken(providerId, oauth);
if (!token) return null;
const headers: Record<string, string> = { authorization: `Bearer ${token}` };
@@@ -872,14 -872,14 +873,19 @@@
} catch {
return null;
}
++ if (!isCurrent()) return null;
const pageDeadline = Date.now() + 30_000;
-- return collectModelDiscoveryPages(json, url, async nextUrl => {
++ const models = await collectModelDiscoveryPages(json, url, async nextUrl => {
++ // Login cancellation/account changes must stop pagination and the optional
++ // speech query before either can reuse the captured Bearer credential.
++ if (!isCurrent()) throw new Error('catalog operation is no longer current');
if (Date.now() >= pageDeadline) throw new Error('catalog deadline exceeded');
const page = await io.fetchImpl(nextUrl, { headers, redirect: 'error',
signal: AbortSignal.timeout(Math.max(1, Math.min(REFRESH_FETCH_TIMEOUT_MS, pageDeadline - Date.now()))) });
if (!page.ok) { await page.body?.cancel(); throw new Error('catalog page failed'); }
return page.json();
});
++ return isCurrent() ? models : null;
}
diff --cc apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index a2b912edb5,e7b63061f4..a403aaf3b0
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@@ -14534,6 -14535,6 +14535,7 @@@ describe('usage-limit wait (ordinary ta
getSession: () => rehydrate ? session : undefined,
closeSession: async () => {}, preflightBotRuntimeResources: async () => {},
getSessionMeta: async () => ({}), ensureRemoteReadyForSessionStart: async () => {},
++ statDirectory: async () => ({ isDirectory: () => true }),
checkWorkDirExists: async () => true, isOrcaMcpHydrated: () => !rehydrate,
buildCreateOptsWithStderr: x => x, synthesizeOrcaVendorOptionsFromDb: async () => rehydrate,
readSessionExtraDirsFromDb: async () => [], readSessionWorkingDirFromDb: async () => '/repo',
diff --cc apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerProject.test.ts
index 1b90fbc2f4,1b90fbc2f4..4993fbad08
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerProject.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerProject.test.ts
@@@ -495,38 -495,38 +495,52 @@@ describe('Worker worktree subproject di
const checkout = new Promise<void>((resolve) => {
finishCheckout = resolve;
});
-- vi.mocked(awaitBackgroundCheckout).mockReset().mockReturnValue(checkout);
++ let signalCheckoutStarted!: () => void;
++ const checkoutStarted = new Promise<void>((resolve) => { signalCheckoutStarted = resolve; });
++ vi.mocked(awaitBackgroundCheckout).mockReset().mockImplementation(() => {
++ signalCheckoutStarted();
++ return checkout;
++ });
const source = scenario === 'root' ? alias : path.join(alias, relative);
let settled = false;
const result = createWorkerWorktree(sessionId, source, 'main').then((value) => {
settled = true;
return value;
});
-- if (scenario === 'root') {
-- expect(await result).toBe(target);
-- expect(awaitBackgroundCheckout).not.toHaveBeenCalled();
++ try {
++ if (scenario === 'root') {
++ expect(await result).toBe(target);
++ expect(awaitBackgroundCheckout).not.toHaveBeenCalled();
++ return;
++ }
++ // Windows CI can spend >1s in the real Git probe. Await the actual
++ // boundary (or an early result/failure), not vi.waitFor's 1s deadline.
++ await Promise.race([checkoutStarted, result]);
++ expect(awaitBackgroundCheckout).toHaveBeenCalledWith(sessionId);
++ expect(settled).toBe(false);
++ if (present) {
++ mkdirSync(subproject, { recursive: true });
++ writeFileSync(path.join(subproject, 'AGENTS.md'), 'Checked out rules');
++ }
++ if (scenario === 'external-symlink') {
++ const external = path.join(fixture, 'outside-checkout');
++ mkdirSync(external);
++ mkdirSync(path.dirname(subproject), { recursive: true });
++ symlinkSync(external, subproject, process.platform === 'win32' ? 'junction' : 'dir');
++ }
finishCheckout();
-- return;
-- }
-- await vi.waitFor(() => expect(awaitBackgroundCheckout).toHaveBeenCalledWith(sessionId));
-- expect(settled).toBe(false);
-- if (present) {
-- mkdirSync(subproject, { recursive: true });
-- writeFileSync(path.join(subproject, 'AGENTS.md'), 'Checked out rules');
-- }
-- if (scenario === 'external-symlink') {
-- const external = path.join(fixture, 'outside-checkout');
-- mkdirSync(external);
-- mkdirSync(path.dirname(subproject), { recursive: true });
-- symlinkSync(external, subproject, process.platform === 'win32' ? 'junction' : 'dir');
++ expect(await result).toBe(present ? subproject : target);
++ if (scenario === 'missing' || scenario === 'external-symlink')
++ expect(createLogger('test').warn).toHaveBeenCalledWith(
++ 'Worker subproject is unavailable within the new worktree; using its root',
++ { sessionId },
++ );
++ } finally {
++ // A failed assertion must not leave a task using the next case's mocks
++ // or the fixture after afterAll removes it.
++ finishCheckout();
++ await result.catch(() => {});
}
-- finishCheckout();
-- expect(await result).toBe(present ? subproject : target);
-- if (scenario === 'missing' || scenario === 'external-symlink')
-- expect(createLogger('test').warn).toHaveBeenCalledWith(
-- 'Worker subproject is unavailable within the new worktree; using its root',
-- { sessionId },
-- );
},
);
});
diff --cc apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
index 9daf7840ba,9daf7840ba..29837bf650
--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
@@@ -3922,6 -3922,6 +3922,35 @@@ describe('provider:models-fetch handler
});
describe('provider:oauth mutation ordering', () => {
++ // PR #6900 unit: the login discovery callback must lose its authority on an
++ // owner switch too. Existing cancellation tests only invalidated the login ID.
++ it('invalidates login discovery and rolls credentials back after an owner change', async () => {
++ const harness = new IpcHarness();
++ const owner = { dataOwnerId: 'owner-a', generation: 1 };
++ let isCurrent!: () => boolean;
++ let finish!: () => void;
++ const pending = new Promise<void>(resolve => { finish = resolve; });
++ const rollbackCredentials = vi.fn(() => true);
++ const afterCommit = vi.fn();
++ const oauthLogin = vi.fn(async (_id: string, current: () => boolean) => {
++ isCurrent = current;
++ await pending;
++ return { ok: true, rollbackCredentials, afterCommit };
++ });
++ registerProviderHandlers(harness, makeDeps({ oauthLogin, currentOwnerSession: () => ({ ...owner }) }));
++ const login = harness.invoke(MAKER_INVOKE.PROVIDER_OAUTH_LOGIN, 'openrouter');
++ await vi.waitFor(() => expect(oauthLogin).toHaveBeenCalledOnce());
++ expect(isCurrent()).toBe(true);
++ owner.generation++;
++ const currentAfterSwitch = isCurrent();
++ finish();
++ const result = await login;
++ expect(currentAfterSwitch).toBe(false);
++ expect(result).toEqual({ ok: false, reason: 'login_cancelled' });
++ expect(rollbackCredentials).toHaveBeenCalledOnce();
++ expect(afterCommit).not.toHaveBeenCalled();
++ });
++
it('keeps the old persisted generation reusable when retirement fails before credential write', async () => {
const harness = new IpcHarness();
const providerId = 'logout-prewrite-retire';
diff --cc apps/desktop/src/main/maker-ipc/providerHandlers.ts
index 44b42fd89b,44b42fd89b..9c5f309d73
--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
@@@ -2465,6 -2465,6 +2465,7 @@@ export function registerProviderHandler
const ownerAtIngress = captureProviderOwnerSession();
const finishRouteMutation = deps.beginRouteMutation(id);
const generation = beginOAuthMutation(id);
++ const isCurrent = () => isOAuthMutationCurrent(id, generation) && providerMutationOwnerMatches(ownerAtIngress);
let owner: ProviderOAuthOwner | null = null;
let codexHostPrepared = false;
try {
@@@ -2477,25 -2477,25 +2478,23 @@@
ownerAtIngress,
);
codexHostPrepared = preparation.prepared;
-- const result = await deps.oauthLogin(id, () => isOAuthMutationCurrent(id, generation), (url) => {
++ const result = await deps.oauthLogin(id, isCurrent, (url) => {
// Only the initiating local renderer gets this ephemeral authorization URL.
-- if (!ownerId || !sender || !isOAuthMutationCurrent(id, generation) ||
-- !providerMutationOwnerMatches(ownerAtIngress)) return;
++ if (!ownerId || !sender || !isCurrent()) return;
try {
sender.send?.(MAKER_PUSH.PROVIDER_OAUTH_PROGRESS, {
providerId: id, ownerId, phase: 'browser-url', url,
});
} catch { /* A closed renderer must not interrupt credential cleanup. */ }
}, method, (code) => {
-- if (!ownerId || !sender || !isOAuthMutationCurrent(id, generation) ||
-- !providerMutationOwnerMatches(ownerAtIngress)) return;
++ if (!ownerId || !sender || !isCurrent()) return;
try {
sender.send?.(MAKER_PUSH.PROVIDER_OAUTH_PROGRESS, {
providerId: id, phase: 'device-code', ...code,
});
} catch { /* The login still runs if its initiating window closes. */ }
});
-- if (isOAuthMutationCurrent(id, generation)) {
++ if (isCurrent()) {
if (result.ok) {
if (result.commitAccountCapabilities) {
// Credentials are installed: close cancellation before committing their
diff --cc apps/desktop/src/main/maker-ipc/register.ts
index 18dae74717,ede69bd2ab..c3cdc8420c
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@@ -7467,7 -7463,7 +7463,7 @@@ export function registerMakerIpc(maker
if (!fetched.has(key))
fetched.set(
key,
-- await discoverGenericOAuthModels(storageProviderId, oauth, url, agent),
++ await discoverGenericOAuthModels(storageProviderId, oauth, url, agent, isCurrent),
);
if (!isCurrent()) break;
const models = fetched.get(key);
diff --cc apps/desktop/src/main/voice-conversation/__tests__/ipc.test.ts
index 0f5c02b82a,0f5c02b82a..e94ec98880
--- a/apps/desktop/src/main/voice-conversation/__tests__/ipc.test.ts
+++ b/apps/desktop/src/main/voice-conversation/__tests__/ipc.test.ts
@@@ -1,4 -1,4 +1,5 @@@
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
++import { BUNDLED_CATALOG, buildUserProvider, providerPresetOAuth, type Catalog } from '@cindy/model-providers';
type Handler = (...args: unknown[]) => unknown;
const h = vi.hoisted(() => ({
@@@ -8,6 -8,6 +9,9 @@@
emit: vi.fn(),
append: vi.fn(),
boundary: false,
++ catalog: undefined as Catalog | undefined,
++ oauthToken: vi.fn<() => string | null>(),
++ readKey: vi.fn<() => string | null>(),
}));
vi.mock('electron', () => ({
ipcMain: {
@@@ -21,7 -21,7 +25,7 @@@ vi.mock('../../security/trustedAppRende
}));
vi.mock('../../cindy-brain/index.js', () => ({ hasEnabledGhostAssistantHook: () => false }));
vi.mock('../../maker-host/active-catalog.js', () => ({
-- getActiveCatalog: () => ({
++ getActiveCatalog: () => h.catalog ?? ({
providers: [
{
id: 'xd',
@@@ -33,9 -33,9 +37,12 @@@
}),
}));
vi.mock('../../secrets/providerSecretStore.js', () => ({
-- readCustomProviderKey: () => null,
++ readCustomProviderKey: h.readKey,
getProviderSecretStore: () => ({ get: () => 'test-key' }),
}));
++vi.mock('../../maker-host/generic-oauth.js', () => ({
++ readCachedGenericOAuthAccessToken: h.oauthToken,
++}));
vi.mock('../../model-access/effectiveEndpoint.js', () => ({
effectiveXdGatewayBaseUrl: () => 'https://gateway.test/v1',
}));
@@@ -75,6 -75,6 +82,9 @@@ beforeEach(() =>
h.trusted.mockReset();
h.append.mockReset();
h.boundary = false;
++ h.catalog = undefined;
++ h.oauthToken.mockReset().mockReturnValue(null);
++ h.readKey.mockReset().mockReturnValue(null);
setModelVisibilityMirror({});
vi.mocked(outboundFetch).mockReset();
let settings = normalizeVoiceInputSettings({});
@@@ -111,6 -111,6 +121,47 @@@ const start = () =
voice: 'alloy',
});
++// PR #6900 unit: injected model tests missed production credential-store wiring.
++// Exercise real IPC -> catalog -> voice query/synthesis with a legacy display ID,
++// then remove its login. Only the stored ID is read, never an API-key fallback.
++it('uses the saved OpenRouter OAuth connection without exposing its credential to the renderer', async () => {
++ const oauth = providerPresetOAuth('openrouter')!;
++ const modelId = 'elevenlabs/eleven-v3';
++ const provider = buildUserProvider({
++ id: 'xai', name: 'My router', auth: { method: 'oauth', oauth },
++ runtimes: { codex: { baseUrl: 'https://openrouter.ai/api/v1',
++ models: [{ id: modelId, name: 'Speech', mode: 'audio_speech' }] } },
++ });
++ h.catalog = { ...BUNDLED_CATALOG, providers: [provider] };
++ h.oauthToken.mockReturnValue('fake-saved-oauth-key');
++ h.readKey.mockReturnValue('fake-unrelated-api-key');
++ const models = await call('models');
++ expect(models).toEqual([expect.objectContaining({ providerId: 'custom:xai', id: modelId })]);
++ expect(h.oauthToken).toHaveBeenCalledWith('xai', oauth);
++ expect(JSON.stringify(models)).not.toContain('fake-saved-oauth-key');
++ const selection = { providerId: 'custom:xai', agent: 'codex', modelId, voice: 'sarah' };
++ vi.mocked(outboundFetch).mockResolvedValueOnce(new Response(JSON.stringify({ data: [
++ { id: modelId, supported_voices: ['sarah'] },
++ ] })));
++ expect(await call('voices', selection)).toMatchObject({ voices: [{ id: 'sarah' }] });
++ await call('start', { ...selection, callId: 'call', botId: 'bot', sessionId: 'canonical' });
++ vi.mocked(outboundFetch).mockResolvedValueOnce(new Response(new Uint8Array([1, 0]), {
++ headers: { 'Content-Type': 'audio/pcm' },
++ }));
++ await call('speak', { callId: 'call', requestId: 'oauth-speech', text: 'Hello' });
++ expect(vi.mocked(outboundFetch).mock.calls.map(([url]) => String(url))).toEqual([
++ 'https://openrouter.ai/api/v1/models?output_modalities=speech',
++ 'https://openrouter.ai/api/v1/audio/speech',
++ ]);
++ for (const [, init] of vi.mocked(outboundFetch).mock.calls)
++ expect(new Headers(init?.headers).get('authorization')).toBe('Bearer fake-saved-oauth-key');
++ expect(h.readKey).not.toHaveBeenCalled();
++ h.oauthToken.mockReturnValue(null);
++ expect(await call('models')).toEqual([]);
++ await expect(call('voices', selection)).rejects.toThrow('Voice conversation is unavailable');
++ expect(outboundFetch).toHaveBeenCalledTimes(2);
++});
++
// PR #6768 unit regression: model discovery must wait for current-owner display
// preferences. Existing IPC tests start with ready state and cannot catch this race.
it('waits for display preferences before returning the speech picker catalog', async () => {
diff --cc apps/desktop/src/main/voice-conversation/__tests__/openrouter.test.ts
index 4e2b342e5a,0000000000..a2a937b6e4
mode 100644,000000..100644
--- a/apps/desktop/src/main/voice-conversation/__tests__/openrouter.test.ts
+++ b/apps/desktop/src/main/voice-conversation/__tests__/openrouter.test.ts
@@@ -1,321 -1,0 +1,364 @@@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ BUNDLED_CATALOG,
+ buildUserProvider,
+ isAgentSelectableModel,
+ mergeDiscoveredRuntimeModels,
+ parseModelsListResponse,
++ providerPresetOAuth,
+} from '@cindy/model-providers';
+import { fetchProviderModels } from '../../maker-host/provider-model-fetch.js';
+import { resolveSpeechConnection, speechModels, type SpeechCatalogDeps } from '../models.js';
+import { SpeechSynthesisSession, type SpeechConnection } from '../speech.js';
+import { speechRequest } from '../speechProtocols.js';
+import { loadSpeechVoices } from '../voices.js';
+
+// Unit tier: exercise the actual discovery -> saved runtime -> picker -> transport path.
+// The ordinary OpenRouter catalog omits speech; its dedicated list has no Cindy mode.
+const catalogUrl = 'https://openrouter.ai/api/v1/models';
+const speechUrl = `${catalogUrl}?output_modalities=speech`;
+const speechId = 'elevenlabs/eleven-v3';
+const speechEntry = {
+ id: speechId,
+ name: 'Eleven v3',
+ architecture: { input_modalities: ['text'], output_modalities: ['speech'] },
+ supported_voices: ['george', 'sarah'],
+ pricing: { prompt: '0.00018' }, // per character, not per token
+};
+const chatEntry = {
+ id: 'openai/audio-chat',
+ architecture: { input_modalities: ['text', 'audio'], output_modalities: ['text', 'audio'] },
+ pricing: { prompt: '0.000001' },
+};
+const json = (data: unknown) => new Response(JSON.stringify(data));
+const connection: SpeechConnection = {
+ protocol: 'openai',
+ baseUrl: 'https://openrouter.ai/api/v1',
+ headers: { authorization: 'Bearer test-openrouter-key' },
+};
+const current = () => {};
+
+describe('OpenRouter speech integration', () => {
- it.each(['claude-code', 'codex', 'pi'] as const)(
- 'discovers speech alongside chat and executes the owning %s connection',
- async (agent) => {
++ // PR #6900: API-key-only fixtures missed discovered OAuth models being removed
++ // from the picker. Unit: real catalog projection and transport for both logins.
++ it.each((['claude-code', 'codex', 'pi'] as const).flatMap(agent =>
++ (['apiKey', 'oauth'] as const).map(auth => ({ agent, auth }))))(
++ 'discovers speech alongside chat and executes the owning $agent/$auth connection',
++ async ({ agent, auth }) => {
++ const oauth = providerPresetOAuth('openrouter')!;
+ const baseUrl = agent === 'claude-code' ? 'https://openrouter.ai/api' : connection.baseUrl;
+ const fetcher = vi.fn<typeof fetch>(async (url, init) => {
+ expect(init?.headers).toEqual({ authorization: 'Bearer test-openrouter-key' });
+ return json({ data: String(url) === speechUrl ? [speechEntry] : [chatEntry] });
+ });
+ const result = await fetchProviderModels(
+ {
+ agent,
+ baseUrl,
+ apiKey: 'test-openrouter-key',
+ redirect: 'error',
+ },
+ fetcher,
+ );
+ expect(fetcher.mock.calls.map(([url]) => String(url))).toEqual([catalogUrl, speechUrl]);
+ expect(result.ok).toBe(true);
+ const discovered = result.models!;
+ expect(discovered.find((m) => m.id === speechId)?.discoveredCost).toBeUndefined();
+ expect(discovered.find((m) => m.id === chatEntry.id)?.discoveredCost).toEqual({ input: 1 });
+ const saved = mergeDiscoveredRuntimeModels([], discovered);
+ const provider = buildUserProvider({
+ id: 'router',
+ name: 'My OpenRouter',
++ ...(auth === 'oauth' ? { auth: { method: 'oauth' as const, oauth } } : {}),
+ runtimes: {
+ [agent]: { baseUrl, models: saved },
+ },
+ });
+ provider.routing[agent]!.headerOverride = {
+ 'anthropic-version': '2023-06-01',
+ 'x-api-key': 'stale-key',
+ };
+ expect(provider.audioModels).toEqual([
+ expect.objectContaining({ id: speechId, mode: 'audio_speech' }),
+ ]);
+ expect(
+ provider.models[agent]!.filter((m) =>
+ isAgentSelectableModel(m, { userProvider: true }),
+ ).map((m) => m.id),
+ ).toEqual([chatEntry.id]);
+ const deps: SpeechCatalogDeps = {
+ catalog: { ...BUNDLED_CATALOG, providers: [provider] },
+ gatewayAllowed: false,
+ disabled: () => false,
+ readKey: vi.fn(() => 'test-openrouter-key'),
++ readOAuthToken: vi.fn(() => 'test-openrouter-key'),
+ gatewayConnection: () => {
+ throw new Error('not Gateway');
+ },
+ };
+ expect(speechModels(deps)).toEqual([
+ expect.objectContaining({
+ id: speechId,
+ providerId: 'router',
+ providerName: 'My OpenRouter',
+ agent,
+ protocol: 'openai',
+ protocolLocked: true,
+ defaultVoice: '',
+ speedRange: null,
+ }),
+ ]);
+ const selection = { providerId: 'router', agent, modelId: speechId, voice: 'sarah' };
+ const bound = resolveSpeechConnection(deps, { ...selection, protocol: 'elevenlabs' });
+ expect(bound.baseUrl).toBe(connection.baseUrl);
+ expect(bound.protocol).toBe('openai');
+ expect(bound.headers).toEqual(connection.headers);
- expect(deps.readKey).toHaveBeenCalledWith('router', agent);
++ if (auth === 'oauth') {
++ expect(deps.readOAuthToken).toHaveBeenCalledWith('router', oauth);
++ expect(deps.readKey).not.toHaveBeenCalled();
++ } else {
++ expect(deps.readKey).toHaveBeenCalledWith('router', agent);
++ expect(deps.readOAuthToken).not.toHaveBeenCalled();
++ }
+ expect(provider.routing[agent]?.upstream).toBe(baseUrl);
+ expect(() => resolveSpeechConnection(deps, { ...selection, speed: 1.5 })).toThrow(
+ 'invalid_speech_speed',
+ );
+ const request = speechRequest(bound, { modelId: speechId, voice: 'sarah', text: 'Hello' });
+ expect(request.url.href).toBe('https://openrouter.ai/api/v1/audio/speech');
+ expect(JSON.parse(request.body)).toEqual({
+ model: speechId,
+ voice: 'sarah',
+ input: 'Hello',
+ response_format: 'pcm',
+ });
+ expect(() =>
+ speechRequest(bound, { modelId: speechId, voice: 'sarah', text: 'Hello', speed: 1.5 }),
+ ).toThrow();
+ },
+ );
+
++ // Unit boundary: a name/model family or saved API key must not admit another
++ // OAuth contract, a non-official route, or a logged-out OpenRouter connection.
++ it.each(['unknown-oauth', 'subscription', 'native', 'proxy', 'wrong-path', 'wrong-auth', 'logged-out'] as const)(
++ 'keeps OAuth speech unavailable for %s', (kind) => {
++ const oauth = kind === 'subscription' ? providerPresetOAuth('minimax')!
++ : { ...providerPresetOAuth('openrouter')!, ...(kind === 'unknown-oauth'
++ ? { tokenUrl: 'https://auth.example/token' } : {}) };
++ const baseUrl = kind === 'proxy' ? 'https://proxy.example/api/v1'
++ : kind === 'wrong-path' ? 'https://openrouter.ai/proxy/v1' : connection.baseUrl;
++ const provider = buildUserProvider({
++ id: 'router', name: 'OpenRouter', auth: { method: 'oauth', oauth },
++ runtimes: { codex: { baseUrl, models: [{ id: speechId, name: speechId, mode: 'audio_speech' }] } },
++ });
++ if (kind === 'native') provider.auth.native = 'codex';
++ if (kind === 'wrong-auth') provider.routing.codex!.authStrategy = 'api-key-header';
++ const deps: SpeechCatalogDeps = {
++ catalog: { ...BUNDLED_CATALOG, providers: [provider] }, gatewayAllowed: false,
++ disabled: () => false, gatewayConnection: () => { throw new Error('not Gateway'); },
++ readKey: vi.fn(() => 'fake-unrelated-key'),
++ readOAuthToken: vi.fn(() => kind === 'logged-out' ? null : 'fake-oauth-key'),
++ };
++ expect(speechModels(deps)).toEqual([]);
++ expect(() => resolveSpeechConnection(deps, {
++ providerId: 'router', agent: 'codex', modelId: speechId, protocol: 'openai',
++ })).toThrow('model_unavailable');
++ expect(deps.readKey).not.toHaveBeenCalled();
++ if (kind !== 'logged-out') expect(deps.readOAuthToken).not.toHaveBeenCalled();
++ },
++ );
++
+ it('retains chat on a failed optional speech query, and honors an explicit catalog filter', async () => {
+ const spec = { agent: 'codex' as const, baseUrl: connection.baseUrl, apiKey: 'test-key' };
+ const fetcher = vi.fn<typeof fetch>(async (url) =>
+ String(url) === speechUrl ? new Response(null, { status: 503 }) : json({ data: [chatEntry] }),
+ );
+ expect((await fetchProviderModels(spec, fetcher)).models?.map((m) => m.id)).toEqual([
+ chatEntry.id,
+ ]);
+ expect(fetcher).toHaveBeenCalledTimes(2);
+ fetcher.mockClear();
+ await fetchProviderModels(
+ { ...spec, modelsUrl: `${catalogUrl}?output_modalities=text` },
+ fetcher,
+ );
+ expect(fetcher).toHaveBeenCalledOnce();
+ });
+
+ it('keeps user type/name overrides and does not infer TTS from audio or a different origin', () => {
+ const discovered = parseModelsListResponse({ data: [speechEntry, chatEntry] }, speechUrl)!;
+ expect(discovered[0].discoveredMetadata?.mode).toBe('audio_speech');
+ expect(discovered[0].discoveredMetadata?.nativeApi).toBeUndefined();
+ expect(discovered[1].discoveredMetadata?.mode).toBeUndefined();
+ const saved = mergeDiscoveredRuntimeModels(
+ [{ id: speechId, name: 'My name', mode: 'chat' }],
+ discovered,
+ );
+ expect(saved.find((m) => m.id === speechId)).toMatchObject({
+ name: 'My name',
+ mode: 'chat',
+ discoveredMetadata: { mode: 'audio_speech' },
+ });
+ expect(
+ parseModelsListResponse({ data: [speechEntry] }, 'https://proxy.test/api/v1/models')![0]
+ .discoveredMetadata?.mode,
+ ).toBeUndefined();
+ });
+
+ it.each([
+ 'https://openrouter.ai/proxy/v1',
+ 'https://openrouter.ai:8443/api/v1',
+ 'https://openrouter.ai.untrusted.test/api/v1',
+ 'http://openrouter.ai/api/v1',
+ ])('does not apply official routing or speed limits to %s', (baseUrl) => {
+ const provider = buildUserProvider({
+ id: 'proxy',
+ name: 'Proxy',
+ runtimes: {
+ codex: {
+ baseUrl,
+ models: [{ id: speechId, name: speechId, mode: 'audio_speech', nativeApi: null }],
+ },
+ },
+ });
+ const deps: SpeechCatalogDeps = {
+ catalog: { ...BUNDLED_CATALOG, providers: [provider] },
+ gatewayAllowed: false,
+ disabled: () => false,
+ readKey: () => 'test-key',
+ gatewayConnection: () => {
+ throw new Error('not Gateway');
+ },
+ };
+ expect(speechModels(deps)[0]).toMatchObject({ protocolLocked: false });
+ expect(() =>
+ resolveSpeechConnection(deps, { providerId: 'proxy', agent: 'codex', modelId: speechId }),
+ ).toThrow('model_unavailable');
+ const explicit = resolveSpeechConnection(deps, {
+ providerId: 'proxy',
+ agent: 'codex',
+ modelId: speechId,
+ protocol: 'openai',
+ });
+ expect(explicit.baseUrl).toBe(baseUrl);
+ expect(explicit.speedRange).toBeUndefined();
+ });
+
+ it('loads and refreshes only the selected model voices, keeping manual IDs valid', async () => {
+ const fetcher = vi
+ .fn<typeof fetch>()
+ .mockResolvedValueOnce(
+ json({
+ data: [
+ { ...speechEntry, supported_voices: ['george', 'sarah', 'george', null, '../bad'] },
+ { id: 'another-model', supported_voices: ['wrong-model'] },
+ ],
+ }),
+ )
+ .mockResolvedValueOnce(json({ data: [{ ...speechEntry, supported_voices: ['alice'] }] }));
+ expect(await loadSpeechVoices(connection, speechId, fetcher, current, 'router')).toEqual({
+ source: 'provider',
+ voices: [
+ { id: 'george', name: 'george' },
+ { id: 'sarah', name: 'sarah' },
+ ],
+ });
+ expect(await loadSpeechVoices(connection, speechId, fetcher, current, 'router')).toEqual({
+ source: 'provider',
+ voices: [{ id: 'alice', name: 'alice' }],
+ });
+ expect(fetcher).toHaveBeenCalledWith(
+ speechUrl,
+ expect.objectContaining({ method: 'GET', headers: connection.headers, redirect: 'error' }),
+ );
+ expect(
+ JSON.parse(
+ speechRequest(connection, { modelId: speechId, voice: 'custom-voice-id', text: 'Hello' })
+ .body,
+ ).voice,
+ ).toBe('custom-voice-id');
+ });
+
+ it.each([null, undefined])(
+ 'keeps manual entry when supported_voices is %s',
+ async (supported_voices) => {
+ expect(
+ await loadSpeechVoices(
+ connection,
+ speechId,
+ vi.fn(async () => json({ data: [{ ...speechEntry, supported_voices }] })),
+ current,
+ ),
+ ).toEqual({ source: 'manual', voices: [] });
+ },
+ );
+
+ it('rejects missing models, malformed catalogs and stale account results', async () => {
+ for (const data of [
+ { data: [] },
+ { data: [{ ...speechEntry, supported_voices: 'sarah' }] },
+ {},
+ ]) {
+ await expect(
+ loadSpeechVoices(
+ connection,
+ speechId,
+ vi.fn(async () => json(data)),
+ current,
+ ),
+ ).rejects.toThrow();
+ }
+ let active = true;
+ await expect(
+ loadSpeechVoices(
+ connection,
+ speechId,
+ vi.fn(async () => {
+ active = false;
+ return json({ data: [speechEntry] });
+ }),
+ () => {
+ if (!active) throw new Error('stale account');
+ },
+ ),
+ ).rejects.toThrow('stale account');
+ });
+
+ it('never queries OpenRouter for Gateway or a third-party proxy', async () => {
+ const fetcher = vi.fn();
+ for (const baseUrl of ['https://proxy.test/api/v1', 'https://openrouter.ai/proxy/v1']) {
+ expect(
+ await loadSpeechVoices({ ...connection, baseUrl }, speechId, fetcher, current),
+ ).toEqual({ source: 'manual', voices: [] });
+ }
+ await loadSpeechVoices(connection, 'elevenlabs/eleven_v3', fetcher, current, 'xd');
+ expect(fetcher).not.toHaveBeenCalled();
+ });
+
+ it('streams binary PCM through the existing cancellable playback contract', async () => {
+ const fetcher = vi.fn<typeof fetch>(
+ async () =>
+ new Response(new Uint8Array([1, 0, 255, 127]), {
+ headers: { 'Content-Type': 'audio/pcm' },
+ }),
+ );
+ const speech = new SpeechSynthesisSession({
+ connection: () => connection,
+ fetch: fetcher,
+ assertCurrent: current,
+ });
+ expect(
+ await speech.start({
+ requestId: 'or-test',
+ modelId: speechId,
+ voice: 'sarah',
+ text: 'Hello',
+ }),
+ ).toEqual({ sampleRate: 24000 });
+ expect(new Uint8Array((await speech.read('or-test')).pcm)).toEqual(
+ new Uint8Array([1, 0, 255, 127]),
+ );
+ expect((await speech.read('or-test')).done).toBe(true);
+ speech.cancel();
+ });
+});
diff --cc apps/desktop/src/main/voice-conversation/index.ts
index a35eaf3de2,a35eaf3de2..b51b985564
--- a/apps/desktop/src/main/voice-conversation/index.ts
+++ b/apps/desktop/src/main/voice-conversation/index.ts
@@@ -1,12 -1,12 +1,14 @@@
import { CompanionCallDialogue } from './dialogue.js';
import { ipcMain, webContents, type IpcMainInvokeEvent } from 'electron';
import type { AsrProvider, AudioGate } from '@cindy/voice-input-core';
++import { storedCustomProviderId } from '@cindy/model-providers';
import {
normalizeVoiceConversationSelection,
normalizeSpeechModelSelection,
type VoiceConversationPreference,
} from '../../shared/voiceConversation.js';
import { getActiveCatalog } from '../maker-host/active-catalog.js';
++import { readCachedGenericOAuthAccessToken } from '../maker-host/generic-oauth.js';
import { getModelVisibilityOverride, waitForModelVisibilityMirror } from '../maker-host/model-visibility-mirror.js';
import { getProviderSecretStore, readCustomProviderKey } from '../secrets/providerSecretStore.js';
import { effectiveXdGatewayBaseUrl } from '../model-access/effectiveEndpoint.js';
@@@ -54,6 -54,6 +56,7 @@@ export function registerVoiceConversati
disabled: isProviderModelRouteDisabled,
visibilityOverride: getModelVisibilityOverride,
readKey: readCustomProviderKey,
++ readOAuthToken: (providerId, oauth) => readCachedGenericOAuthAccessToken(storedCustomProviderId(providerId), oauth),
gatewayConnection: () => ({
baseUrl: effectiveXdGatewayBaseUrl(),
apiKey: getProviderSecretStore().get('xd') ?? '',
diff --cc apps/desktop/src/main/voice-conversation/models.ts
index 11e3ded2fd,65b1254251..cd99fc4173
--- a/apps/desktop/src/main/voice-conversation/models.ts
+++ b/apps/desktop/src/main/voice-conversation/models.ts
@@@ -7,9 -7,9 +7,11 @@@ import
BUNDLED_CATALOG,
isLoopbackProviderUrl,
isModelVisible,
++ providerOAuthContract,
resolveModelNativeApi,
type AgentKind,
type Catalog,
++ type OAuthProviderDescriptor,
type ProviderMediaModel,
} from '@cindy/model-providers';
import {
@@@ -31,6 -30,6 +33,7 @@@ export type SpeechCatalogDeps =
visibilityOverride?(agent: AgentKind, providerId: string, modelId: string): boolean | undefined;
gatewayConnection(): { baseUrl: string; apiKey: string };
readKey(providerId: string, agent: AgentKind): string | null;
++ readOAuthToken?(providerId: string, oauth: OAuthProviderDescriptor): string | null;
};
type Binding = { model: VoiceConversationModel; connection: SpeechConnection | null };
@@@ -157,10 -156,10 +160,12 @@@ function bindings(deps: SpeechCatalogDe
});
continue;
}
++ const oauth = provider.auth.method === 'oauth' ? provider.auth.oauth : undefined;
++ const openRouterOAuth = !!oauth && providerOAuthContract(oauth) === 'openrouter';
if (
provider.source !== 'user' ||
provider.auth.native ||
-- !['apiKey', 'none'].includes(provider.auth.method)
++ (!['apiKey', 'none'].includes(provider.auth.method) && !openRouterOAuth)
)
continue;
const agent = media.sourceAgent;
@@@ -213,6 -209,6 +218,14 @@@
for (const name of route.headerDelete ?? []) delete headers[name.toLowerCase()];
if (provider.auth.method === 'none') {
if (route.authStrategy !== 'none' || !isLoopbackProviderUrl(base.toString())) continue;
++ } else if (provider.auth.method === 'oauth') {
++ // OpenRouter PKCE issues an API key into the generic OAuth store. Admit
++ // only that contract on its official API; subscription OAuth stays excluded.
++ if (!openRouterOAuth || !oauth || !openRouterBase ||
++ !openRouterSpeechBaseUrl(ownerBase.toString()) || route.authStrategy !== 'oauth-token') continue;
++ const token = deps.readOAuthToken?.(provider.id, oauth)?.trim();
++ if (!token) continue;
++ headers.authorization = `Bearer ${token}`;
} else {
if (route.authStrategy !== 'api-key-header') continue;
const key = deps.readKey(provider.id, agent)?.trim();
diff --cc apps/desktop/src/renderer/features/bots/__tests__/botIslandVisibility.test.tsx
index 2d64798822,2d64798822..8e7d431cc3
--- a/apps/desktop/src/renderer/features/bots/__tests__/botIslandVisibility.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botIslandVisibility.test.tsx
@@@ -170,7 -170,7 +170,10 @@@ describe('history ownership gate dispos
history.mockResolvedValue([]);
get.mockResolvedValue({ ...profile, sessions: [{ id: 'old-a', kind: 'channel', role: 'channel', status }] });
const view = render(<BotHistorySessionView />);
-- await waitFor(() => expect(view.getByTestId('chat').dataset.readonly).toBe('true'));
++ // Flush the ownership promises and passive disposal effect, not just the DOM
++ // mutation (which can be observed before that effect commits on a busy runner).
++ await act(async () => {});
++ expect(view.getByTestId('chat').dataset.readonly).toBe('true');
expect(consumeEntryAlert).toHaveBeenCalledExactlyOnceWith('old-a', '42');
});
diff --cc docs/product-rules/companion-voice-mode.md
index 161b49b16f,21d14dae12..97897618ed
--- a/docs/product-rules/companion-voice-mode.md
+++ b/docs/product-rules/companion-voice-mode.md
@@@ -57,34 -57,6 +57,39 @@@
## BYOK 音频合同
+OpenRouter 的普通 `/api/v1/models` 目录不包含完整语音列表。对未指定查询条件的官方目录,
+模型发现额外查询 `?output_modalities=speech`,按 ID 合并,并仅将明确输出 `speech` 的条目
+识别为 `audio_speech`;`audio` 输入/输出的聊天模型保持聊天分类,已有名称、类型及开关覆盖
+继续生效。额外查询失败时保留已获取的聊天目录;用户指定的过滤参数或代理目录不被改写。
+语音的按字符/时长报价不写入聊天的 token 单价字段。
++登录后的发现与手动刷新均在每次分页/语音补查前复核登录代次及当前账号;取消、关闭登录
++窗口或切换账号后,不再使用已捕获的凭证追加目录请求,迟到结果不写入模型配置。
+
+OpenRouter BYOK 的官方 `/api` 和 `/api/v1` 连接只在语音请求中统一到
+`https://openrouter.ai/api/v1/audio/speech`,使用对应连接的 Bearer key、OpenAI 兼容音频
+适配器及原模型 ID;聊天地址不变。每次进入型号、切换型号或点击音色刷新时,从语音模型
+目录读取该型号的 `supported_voices`,不套用 Gateway 或厂商直连的参考音色;缺少该字段时
+保留手动输入,查询失败沿用现有错误/重试行为,不覆盖已选音色。仍可手动输入并试听。
+音色目录仅在内存,不进入公共 Registry 或持久配置。
++官方 OpenRouter OAuth 连接同样可用:只放行已识别的 OpenRouter PKCE contract 与官方
++API 地址,复用当前账号 generic OAuth 凭证库中的 API key;缺少凭证时不可选、不回退到
++API Key 连接的密钥。其他订阅 OAuth、未知 OAuth contract 及代理地址仍不进入此语音路由。
+
+OpenRouter 的 `minimax/speech-*` 型号实测拒绝 PCM,因此直接请求 MP3,不先发起会失败的
+付费 PCM 请求或自动换模型。仅匹配官方 API 地址;Gateway、自定义代理与 MiniMax 原生
+SSE 仍保持原合同。MP3 每个句段在现有预取阶段完整接收,最多 8 MiB,保留响应头 30 秒、
+读取停滞 15 秒及账号/连接/取消校验。通过本机 IPC 返回明确标记的内存音频,由浏览器
+原生解码器按实际采样率解码,再复用有界播放、暂停与插话取消;不落盘、不新增解码依赖。
+解码后最多 10 分钟,迟到解码结果不可在取消后重新播放。按句切分及一个预取段保持不变,
+但 MP3 需收齐当前句段才能解码,不承诺逐音频帧开播;其他模型仍边收 PCM 边播放。
+
+OpenRouter 没有统一的型号语速范围,部分上游会拒绝非默认值,因此本阶段使用供应商默认
+语速,不发送 `speed`;设置页复用“不支持调整语速”的现有状态。Main 投影的可选
+`speedRange` 为本机能力信息(`null` 表示不支持、缺省沿用原协议范围),不接受 Renderer
+自报能力、不写入偏好、不加入远程协议。旧偏好中的语速在运行时忽略,明确修改设置时才
+通过原保存流程移除。可发现和可选择不等于账户具有执行权限;音频听感仍需按实际上游验收。
+接口依据:[OpenRouter TTS](https://openrouter.ai/docs/guides/overview/multimodal/tts)。
+
| 接口 | 请求与鉴权 | 响应 |
| --- | --- | --- |
| OpenAI 兼容 | `<base>/audio/speech`,Bearer,`model / voice / input / response_format: pcm` | 原始 24kHz、单声道、16bit little-endian PCM |