Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): surface Grok Imagine for xAI API-key sources (#3875)
betterkitecce75fa3cfa8
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/xaiImageClient.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/xaiImageClient.test.tsindex 3d7c98bd93..5666d309a2 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/xaiImageClient.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/xaiImageClient.test.ts@@ -25,6 +25,33 @@ function channel(fetchImplementation: typeof fetch, overrides: Record<string, un}describe('xaiImageClient', () => {+ it('uses the xAI API-key source for Imagine generation', async () => {+ const doFetch = vi.fn<typeof fetch>(+ async () =>+ new Response(JSON.stringify({ data: [{ b64_json: 'aW1hZ2U=' }] }), { status: 200 }),+ );+ const hasApiKey = vi.fn(() => true);+ const result = await channel(doFetch, {+ hasApiKey,+ getApiKey: () => 'xai-platform-key',+ hasOAuthLogin: () => false,+ getCredentialGeneration: () => 0,+ }).generateImage({ model: 'xai/grok-imagine-image', prompt: '一只猫' });++ expect(result.data[0]?.b64_json).toBe('aW1hZ2U=');+ expect(hasApiKey).toHaveBeenCalled();+ expect((doFetch.mock.calls[0]?.[1]?.headers as Record<string, string>).Authorization).toBe(+ 'Bearer xai-platform-key',+ );++ const unavailable = channel(doFetch, {+ hasApiKey: () => false,+ hasOAuthLogin: () => false,+ getCredentialGeneration: () => 0,+ });+ expect(unavailable.ready()).toBe(false);+ });+it('复用 SuperGrok OAuth 调 Imagine generation 并保留原生画幅', async () => {const doFetch = vi.fn<typeof fetch>(async () =>diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex a6b65422e5..7b1919d447 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -351,6 +351,7 @@ import {readGhostSecret,readGhostSecretStrict,getProviderSecretStore,+ readCustomProviderKey,readGhostSecretTail,removeGhostSecret,removeGhostSecrets,@@ -368,6 +369,8 @@ import {isModelDisabledWithUniqueLegacyBasename,isProviderDisabled,type MediaCapability,+ xaiApiOfficialRuntimeAgents,+ XAI_API_CUSTOM_PROVIDER_ID,} from '@cindy/model-providers';import { readModelDisableOverrides } from '../maker-host/model-disable-store.js';import { readProviderOrder } from '../maker-host/provider-order-store.js';@@ -4066,6 +4069,35 @@ function getImageChannelRegistry(): ImageChannelRegistry {...(aspectRatio ? { size: GHOST_ASPECT_TO_GATEWAY_SIZE[aspectRatio] } : {}),}),});+ const readXaiApiImageKey = (): string | null => {+ // 图片凭证只取路由命中官方 api.x.ai 端点的 runtime:代理 runtime 的密钥+ // 不得发往官方图片端点(避免 401/403 与凭证披露,见 PR #3875 review)。+ const provider = getActiveCatalog().providers.find(+ (candidate) => candidate.id === XAI_API_CUSTOM_PROVIDER_ID,+ );+ for (const agent of xaiApiOfficialRuntimeAgents(provider)) {+ const value = readCustomProviderKey(XAI_API_CUSTOM_PROVIDER_ID, agent)?.trim();+ if (value) return value;+ }+ return null;+ };+ const hasXaiApiImageKey = (): boolean =>+ getActiveCatalog().providers.some(+ (provider) => provider.id === XAI_API_CUSTOM_PROVIDER_ID,+ ) && readXaiApiImageKey() !== null;+ registry.register(+ 'xai-api',+ createXaiImageChannel({+ hasApiKey: hasXaiApiImageKey,+ getApiKey: readXaiApiImageKey,+ hasOAuthLogin: () => false,+ getCredentialGeneration: () => 0,+ getOwnerScopeKey: () => activeOwnerScopeKey(),+ isOwnerBoundaryPending: () => isGhostBoundaryPending(),+ fetchImplementation: ((url, init) => outboundFetch(url as string, init)) as typeof fetch,+ beforeDispatch: (model) => assertMediaModelStillEnabled('image', model, 'xai-api'),+ }),+ );registry.register('xai',createXaiImageChannel({diff --git a/apps/desktop/src/main/cindy-brain/xaiImageClient.ts b/apps/desktop/src/main/cindy-brain/xaiImageClient.tsindex 0a1249f7eb..16549eaf6e 100644--- a/apps/desktop/src/main/cindy-brain/xaiImageClient.ts+++ b/apps/desktop/src/main/cindy-brain/xaiImageClient.ts@@ -1,9 +1,9 @@/**- * xAI Imagine image channel backed by the user's existing SuperGrok OAuth login.+ * xAI Imagine image channel backed by SuperGrok OAuth or an xAI platform API key.*- * The OAuth bearer used by the xAI agent bridge also works on the OpenAI-compatible- * Imagine endpoints. Credentials stay in Main; local source images are sent as data- * URIs and the response is normalized to ImageChannelResult.+ * Both credential families use the same OpenAI-compatible Imagine endpoints. Credentials+ * stay in Main; local source images are sent as data URIs and the response is normalized+ * to ImageChannelResult.*/import fs from 'node:fs/promises';@@ -27,8 +27,12 @@ interface XaiImageResponse {}export interface CreateXaiImageChannelOptions {+ /** Alternative API-key source; when present it takes precedence over OAuth. */+ hasApiKey?(): boolean;+ getApiKey?(): string | null | Promise<string | null>;hasOAuthLogin(): boolean;- getAccessToken(): Promise<string>;+ /** SuperGrok OAuth 凭证;仅在未提供 API key 源时必填。 */+ getAccessToken?(): Promise<string>;getCredentialGeneration(): number;getOwnerScopeKey(): string;isOwnerBoundaryPending(): boolean;@@ -126,6 +130,24 @@ function assertRequestScopeCurrent(}}+async function readCredential(+ opts: CreateXaiImageChannelOptions,+ ownerScopeKey: string,+): Promise<string> {+ if (opts.hasApiKey?.() === true) {+ assertOwnerScopeCurrent(opts, ownerScopeKey);+ const apiKey = await opts.getApiKey?.();+ assertOwnerScopeCurrent(opts, ownerScopeKey);+ const normalized = apiKey?.trim();+ if (!normalized) throw new Error('xAI 图像 API key 已不可用,请到设置中重新配置');+ return normalized;+ }+ if (!opts.getAccessToken) {+ throw new Error('xAI 图像通道缺少可用凭证,请配置 xAI API key 或登录 SuperGrok');+ }+ return opts.getAccessToken();+}+async function readBoundedImageResponse(response: Response,maxBytes: number,@@ -193,7 +215,7 @@ export function createXaiImageChannel(opts: CreateXaiImageChannelOptions): ImageassertRequestScopeCurrent(opts, ownerScopeKey, credentialGeneration);assertStillCurrent();const [token, images] = await Promise.all([- opts.getAccessToken(),+ readCredential(opts, ownerScopeKey),Promise.all(paths.map(sourceImage)),]);const isEdit = images.length > 0;@@ -278,7 +300,7 @@ export function createXaiImageChannel(opts: CreateXaiImageChannelOptions): Image}return {- ready: opts.hasOAuthLogin,+ ready: () => opts.hasApiKey?.() === true || opts.hasOAuthLogin(),maxEditImages: MAX_EDIT_SOURCES,generateImage: ({ model, prompt, aspectRatio }) => call({ model, prompt, aspectRatio }),editImage: ({ model, prompt, imagePaths, aspectRatio }) =>diff --git a/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.tsindex 5a3487c696..e8ba8db13a 100644--- a/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts@@ -187,6 +187,7 @@ import {buildUserProvider,type Catalog,type CustomProviderConfig,+ XAI_API_CUSTOM_PROVIDER_ID,} from '@cindy/model-providers';import { deriveCindyMediaConfig } from '../../cindy-brain/cindyMediaCatalog.js';import {@@ -358,6 +359,30 @@ describe('provider catalog realm reload', () => {h.customProviderRead.mockReset();});+ it('projects executable Imagine models onto the xAI API-key source', () => {+ setCustomProviders([+ buildUserProvider({+ id: XAI_API_CUSTOM_PROVIDER_ID,+ name: 'xAI API',+ runtimes: {+ codex: {+ baseUrl: 'https://api.x.ai/v1',+ wireProtocol: 'openai-chat',+ models: [{ id: 'grok-4.6', name: 'Grok 4.6' }],+ },+ },+ }),+ ]);++ const projected = getActiveCatalog().providers.find(+ (provider) => provider.id === XAI_API_CUSTOM_PROVIDER_ID,+ );+ const bundledXai = BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xai');+ expect(projected?.imageModels).toEqual(bundledXai?.imageModels);++ setCustomProviders([]);+ });+it('does not publish a migrated snapshot after a failed CAS write', async () => {const original: CustomProviderConfig = {id: 'cas-provider',diff --git a/apps/desktop/src/main/maker-host/active-catalog.ts b/apps/desktop/src/main/maker-host/active-catalog.tsindex 33ceca9d78..e7bbdfedb5 100644--- a/apps/desktop/src/main/maker-host/active-catalog.ts+++ b/apps/desktop/src/main/maker-host/active-catalog.ts@@ -30,6 +30,7 @@ import {BUNDLED_CATALOG,buildUserProvider,findModelRegistryRoute,+ projectXaiApiImageModels,type AgentKind,type Catalog,type CatalogCapabilityEvidence,@@ -1235,6 +1236,15 @@ function computeMerged(): Catalog {};});+ // The xAI API-key preset is chat-first in CustomProviderConfig, but its official+ // endpoint can execute the same Imagine catalog. Keep the executable media facts+ // in one projection so Settings and Art do not disagree. 未命中投影时保持原数组+ // 引用,让下方的 identity 短路继续生效。+ const projectedProviders = projectXaiApiImageModels(providers);+ if (projectedProviders !== providers) {+ providers = [...projectedProviders];+ }+if (providers === b.providers) return b; // 无 augment、无 custom → 原样返回return { ...b, providers }; // spread 保留 presets 等目录顶层字段}diff --git a/packages/model-providers/src/__tests__/user-provider.test.ts b/packages/model-providers/src/__tests__/user-provider.test.tsindex a110b5f42b..edd36b4008 100644--- a/packages/model-providers/src/__tests__/user-provider.test.ts+++ b/packages/model-providers/src/__tests__/user-provider.test.ts@@ -14,7 +14,10 @@ import {buildUserProvider,DEFAULT_CUSTOM_CONTEXT_WINDOW,LEGACY_XAI_CUSTOM_PROVIDER_RUNTIME_ID,+ projectXaiApiImageModels,storedCustomProviderId,+ xaiApiOfficialRuntimeAgents,+ XAI_API_CUSTOM_PROVIDER_ID,} from "../user-provider.js";import type { CustomProviderConfig } from "../types.js";import type { ModelRegistry } from "../modelAccessBean.js";@@ -60,6 +63,93 @@ describe("buildUserProvider (per-runtime)", () => {expect(p.models["claude-code"]).toBeUndefined();});+ it("projects official Imagine models onto the xAI API-key source", () => {+ const source = BUNDLED_CATALOG.providers.find((provider) => provider.id === "xai")!;+ const xaiApi = buildUserProvider({+ id: XAI_API_CUSTOM_PROVIDER_ID,+ name: "xAI API",+ runtimes: {+ codex: {+ baseUrl: "https://api.x.ai/v1",+ wireProtocol: "openai-chat",+ models: [{ id: "grok-4.6", name: "Grok 4.6" }],+ },+ },+ });++ const projected = projectXaiApiImageModels([source, xaiApi]);+ expect(projected.find((provider) => provider.id === XAI_API_CUSTOM_PROVIDER_ID)?.imageModels)+ .toEqual(source.imageModels);+ });++ it("does not project Imagine models onto a non-official API-key endpoint", () => {+ const source = BUNDLED_CATALOG.providers.find((provider) => provider.id === "xai")!;+ const proxy = buildUserProvider({+ id: XAI_API_CUSTOM_PROVIDER_ID,+ name: "xAI-compatible proxy",+ runtimes: {+ codex: {+ baseUrl: "https://proxy.example/v1",+ models: [{ id: "grok-4.6", name: "Grok 4.6" }],+ },+ },+ });++ expect(projectXaiApiImageModels([source, proxy])).toEqual([source, proxy]);+ });++ it("binds image credentials to runtimes routed at the official endpoint", () => {+ // 官方 codex 路由 + 代理 pi 路由:只有 codex 可作为凭证来源,防止把+ // 代理密钥发往官方图片端点(PR #3875 review P1)。+ const mixed = buildUserProvider({+ id: XAI_API_CUSTOM_PROVIDER_ID,+ name: "xAI API",+ runtimes: {+ codex: {+ baseUrl: "https://api.x.ai/v1",+ wireProtocol: "openai-chat",+ models: [{ id: "grok-4.6", name: "Grok 4.6" }],+ },+ pi: {+ baseUrl: "https://proxy.example/v1",+ models: [{ id: "grok-4.6", name: "Grok 4.6" }],+ },+ },+ });+ expect(xaiApiOfficialRuntimeAgents(mixed)).toEqual(["codex"]);++ // 只有 pi 命中官方端点:凭证来源是 pi,而不是固定顺序里的 codex 代理。+ const piOfficial = buildUserProvider({+ id: XAI_API_CUSTOM_PROVIDER_ID,+ name: "xAI API",+ runtimes: {+ codex: {+ baseUrl: "https://proxy.example/v1",+ models: [{ id: "grok-4.6", name: "Grok 4.6" }],+ },+ pi: {+ baseUrl: "https://api.x.ai/v1",+ models: [{ id: "grok-4.6", name: "Grok 4.6" }],+ },+ },+ });+ expect(xaiApiOfficialRuntimeAgents(piOfficial)).toEqual(["pi"]);++ // 无任何官方路由:没有可用凭证来源。+ const proxyOnly = buildUserProvider({+ id: XAI_API_CUSTOM_PROVIDER_ID,+ name: "xAI-compatible proxy",+ runtimes: {+ codex: {+ baseUrl: "https://proxy.example/v1",+ models: [{ id: "grok-4.6", name: "Grok 4.6" }],+ },+ },+ });+ expect(xaiApiOfficialRuntimeAgents(proxyOnly)).toEqual([]);+ expect(xaiApiOfficialRuntimeAgents(undefined)).toEqual([]);+ });+it("generates api-key-header routing with that runtime baseUrl, no key", () => {const p = buildUserProvider(codexOnly);expect(p.routing.codex).toEqual({diff --git a/packages/model-providers/src/index.ts b/packages/model-providers/src/index.tsindex 37a895a47b..ebe3445329 100644--- a/packages/model-providers/src/index.ts+++ b/packages/model-providers/src/index.ts@@ -55,8 +55,11 @@ export {buildUserProvider,DEFAULT_CUSTOM_CONTEXT_WINDOW,LEGACY_XAI_CUSTOM_PROVIDER_RUNTIME_ID,+ projectXaiApiImageModels,runtimeCustomProviderId,storedCustomProviderId,+ xaiApiOfficialRuntimeAgents,+ XAI_API_CUSTOM_PROVIDER_ID,} from './user-provider.js';export {appendProviderRequestPath,diff --git a/packages/model-providers/src/user-provider.ts b/packages/model-providers/src/user-provider.tsindex 11a5d2cf9c..464d47dd75 100644--- a/packages/model-providers/src/user-provider.ts+++ b/packages/model-providers/src/user-provider.ts@@ -32,6 +32,8 @@ export const DEFAULT_CUSTOM_CONTEXT_WINDOW = 200_000;* source. Preserve the stored id, but project that legacy row under a collision-free runtime id.*/export const LEGACY_XAI_CUSTOM_PROVIDER_RUNTIME_ID = "custom:xai";+/** Official API-key preset for xAI; distinct from the built-in SuperGrok OAuth provider. */+export const XAI_API_CUSTOM_PROVIDER_ID = "xai-api";export function runtimeCustomProviderId(providerId: string): string {return providerId === "xai"@@ -45,6 +47,71 @@ export function storedCustomProviderId(providerId: string): string {: providerId;}+function isOfficialXaiApiUpstream(upstream: string | undefined): boolean {+ try {+ const url = new URL(upstream ?? "");+ return (+ url.protocol === "https:" &&+ url.hostname === "api.x.ai" &&+ (url.pathname === "/v1" || url.pathname === "/v1/")+ );+ } catch {+ return false;+ }+}++/**+ * The chat-only xAI API preset uses the same public Imagine endpoints as the built-in+ * OAuth source. Project those catalog entries onto the API-key source only after the+ * official endpoint has been confirmed by the saved runtime routing.+ */+export function projectXaiApiImageModels(+ providers: readonly Provider[],+): readonly Provider[] {+ const xaiSource = providers.find((provider) => provider.id === "xai");+ if (+ !xaiSource?.imageModels?.length ||+ !providers.some((provider) => provider.id === XAI_API_CUSTOM_PROVIDER_ID)+ ) {+ return providers;+ }+ // 属性收窄无法跨越 map 回调边界,这里显式捕获非空清单。+ const sourceImageModels = xaiSource.imageModels;+ let changed = false;+ const projected = providers.map((provider) => {+ if (+ provider.id !== XAI_API_CUSTOM_PROVIDER_ID ||+ provider.source !== "user" ||+ provider.auth.method !== "apiKey" ||+ provider.imageModels?.length ||+ !Object.values(provider.routing).some((routing) =>+ isOfficialXaiApiUpstream(routing?.upstream),+ )+ ) {+ return provider;+ }+ changed = true;+ return { ...provider, imageModels: [...sourceImageModels] };+ });+ return changed ? projected : providers;+}++/**+ * Official-API image credentials may only come from runtimes whose saved routing+ * targets the official endpoint. Binding key reads to these agents prevents a+ * proxy-configured runtime's key from being disclosed to api.x.ai. Agents are+ * returned in fixed AGENT_ORDER so key selection stays deterministic when+ * several runtimes are official.+ */+export function xaiApiOfficialRuntimeAgents(+ provider: Provider | undefined,+): readonly AgentKind[] {+ if (!provider) return [];+ return AGENT_ORDER.filter((agent) =>+ isOfficialXaiApiUpstream(provider.routing[agent]?.upstream),+ );+}+/*** 自定义模型的默认 effort 档位(「参考默认设置」)——与内置当代旗舰模型对齐:* - claude-code:low/medium/high/xhigh/max(同 opus / fable);