Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(desktop): 按能力发现 xAI 图片和视频模型 (#2757)

Chris Zhangcbb6a9575af2
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 2f80c733f7..ca5860a164 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -526,6 +526,7 @@ import {
} from './maker-host/memory-settings-store.js';
import {
createAppFocusAutoRefreshTracker,
+ refreshProviderModelsManually,
requestProviderModelAutoRefresh,
resetProviderModelAutoRefreshCooldowns,
} from './maker-host/provider-model-auto-refresh.js';
@@ -548,6 +549,7 @@ import {
hasGrokOAuthLogin,
} from './maker-host/grok-oauth-login.js';
import { setXaiAuthInvalidatedHandler } from './maker-host/xai-auth-invalidation-host.js';
+import { clearXaiMediaModels } from './maker-host/model-discovery/xai-media.js';
import {
getChatgptBridgeAuth,
invalidateChatgptBridgeAuth,
@@ -3762,6 +3764,7 @@ const registerIpcHandlers = () => {
// 限流快照),否则用户会停在「显示已连接、请求连环 403」的假状态。
setXaiAuthInvalidatedHandler(() => {
resetProviderModelAutoRefreshCooldowns('xai');
+ clearXaiMediaModels();
clearXaiRateLimitSnapshot();
broadcastXaiAuthStateChanged();
});
@@ -3774,11 +3777,19 @@ const registerIpcHandlers = () => {
const result = await runGrokOAuthLogin();
if (result.ok) {
resetProviderModelAutoRefreshCooldowns('xai');
+ // 登录可直接覆盖旧账号凭证。先跨授权边界清掉旧账号发现快照,再补拉新账号;
+ // 旧在途请求由 discovery generation + owner scope 双重守卫作废。
+ clearXaiMediaModels();
// 登录成功后广播 provider 变更 —— 其它已打开的窗口(聊天/模型选择器等)跟随刷新
// xAI 连接态,不再等 remount/手动刷新(对齐 CLAUDE_OAUTH_LOGIN 的 broadcastClaudeAuthStateChanged)。
// 限流快照是账号级的:重登可能换账号,旧快照一并清掉(等新账号首个 xai/ 轮自然补上)。
clearXaiRateLimitSnapshot();
broadcastXaiAuthStateChanged();
+ void refreshProviderModelsManually('xai').catch((error) => {
+ createLogger('xai-model-refresh').warn('xAI models refresh after login failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
return { ok: true, authorized: true };
}
return { ok: false, reason: result.reason ?? 'unknown', authorized: hasGrokOAuthLogin() };
@@ -3787,6 +3798,7 @@ const registerIpcHandlers = () => {
try {
logoutGrok();
resetProviderModelAutoRefreshCooldowns('xai');
+ clearXaiMediaModels();
} catch (err) {
throwIpcError(
'INTERNAL',
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/xaiImageClient.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/xaiImageClient.test.ts
index df7e8f36d1..3d7c98bd93 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/xaiImageClient.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/xaiImageClient.test.ts
@@ -16,6 +16,7 @@ function channel(fetchImplementation: typeof fetch, overrides: Record<string, un
return createXaiImageChannel({
hasOAuthLogin: () => true,
getAccessToken: async () => 'grok-oauth-token',
+ getCredentialGeneration: () => 1,
getOwnerScopeKey: () => 'cloud:owner-a:1',
isOwnerBoundaryPending: () => false,
fetchImplementation,
@@ -53,6 +54,21 @@ describe('xaiImageClient', () => {
});
});
+ it('直接转发类型发现得到的未来图片模型,不依赖型号名白名单', async () => {
+ const doFetch = vi.fn<typeof fetch>(
+ async () =>
+ new Response(JSON.stringify({ data: [{ b64_json: 'aW1hZ2U=' }] }), { status: 200 }),
+ );
+
+ await channel(doFetch).generateImage({
+ model: 'xai/future-image-model',
+ prompt: 'future',
+ });
+
+ const body = JSON.parse(String(doFetch.mock.calls[0]?.[1]?.body));
+ expect(body.model).toBe('future-image-model');
+ });
+
it('改图把最多三张本地图片编码为 xAI JSON image fields', async () => {
const paths = await Promise.all(
[0, 1].map(async (index) => {
@@ -168,7 +184,30 @@ describe('xaiImageClient', () => {
channel(malformed).generateImage({ model: 'xai/grok-imagine-image', prompt: 'p' }),
).rejects.toThrow('不可信');
- const redirected = vi.fn<typeof fetch>(async (input) =>
+ const redirected = vi.fn<typeof fetch>(async (input) => {
+ const url = String(input);
+ if (url.includes('/images/generations')) {
+ return new Response(JSON.stringify({ data: [{ url: 'https://imgen.x.ai/output.png' }] }), {
+ status: 200,
+ });
+ }
+ if (url === 'https://imgen.x.ai/output.png') {
+ return new Response(null, { status: 302, headers: { Location: '/cdn/output.png' } });
+ }
+ return new Response(png, { status: 200, headers: { 'content-type': 'image/png' } });
+ });
+ await expect(
+ channel(redirected).generateImage({ model: 'xai/grok-imagine-image', prompt: 'p' }),
+ ).resolves.toEqual({
+ data: [{ b64_json: png.toString('base64') }],
+ output_format: 'png',
+ });
+ expect(redirected.mock.calls.slice(1)).toEqual([
+ ['https://imgen.x.ai/output.png', { redirect: 'manual' }],
+ ['https://imgen.x.ai/cdn/output.png', { redirect: 'manual' }],
+ ]);
+
+ const untrustedRedirect = vi.fn<typeof fetch>(async (input) =>
String(input).includes('/images/generations')
? new Response(JSON.stringify({ data: [{ url: 'https://imgen.x.ai/output.png' }] }), {
status: 200,
@@ -179,9 +218,93 @@ describe('xaiImageClient', () => {
}),
);
await expect(
- channel(redirected).generateImage({ model: 'xai/grok-imagine-image', prompt: 'p' }),
- ).rejects.toThrow('HTTP 302');
- expect(redirected.mock.calls[1]?.[1]).toMatchObject({ redirect: 'manual' });
+ channel(untrustedRedirect).generateImage({ model: 'xai/grok-imagine-image', prompt: 'p' }),
+ ).rejects.toThrow('不可信');
+ });
+
+ it('图片重定向保持账号与凭证代际,并拒绝缺失 Location、第二跳和伪图片', async () => {
+ const png = Buffer.from('89504e470d0a1a0a0000000d49484452', 'hex');
+ let ownerScope = 'cloud:owner-a:1';
+ let credentialGeneration = 1;
+ const generationSwitch = vi.fn<typeof fetch>(async (input) => {
+ const url = String(input);
+ if (url.includes('/images/generations')) {
+ return new Response(JSON.stringify({ data: [{ url: 'https://imgen.x.ai/output.png' }] }), {
+ status: 200,
+ });
+ }
+ if (url.endsWith('/output.png')) {
+ return new Response(null, {
+ status: 307,
+ headers: { Location: 'https://cdn.x.ai/final.png' },
+ });
+ }
+ credentialGeneration = 2;
+ return new Response(png, { status: 200 });
+ });
+ await expect(
+ channel(generationSwitch, {
+ getOwnerScopeKey: () => ownerScope,
+ getCredentialGeneration: () => credentialGeneration,
+ }).generateImage({ model: 'xai/grok-imagine-image', prompt: 'p' }),
+ ).rejects.toThrow('SuperGrok 凭证已切换');
+
+ credentialGeneration = 1;
+ const ownerSwitch = vi.fn<typeof fetch>(async (input) => {
+ if (String(input).includes('/images/generations')) {
+ return new Response(JSON.stringify({ data: [{ url: 'https://imgen.x.ai/output.png' }] }), {
+ status: 200,
+ });
+ }
+ ownerScope = 'cloud:owner-b:2';
+ return new Response(null, { status: 302, headers: { Location: 'https://cdn.x.ai/final.png' } });
+ });
+ await expect(
+ channel(ownerSwitch, { getOwnerScopeKey: () => ownerScope }).generateImage({
+ model: 'xai/grok-imagine-image',
+ prompt: 'p',
+ }),
+ ).rejects.toThrow('账号已切换');
+
+ ownerScope = 'cloud:owner-a:1';
+ for (const location of [undefined, 'https://cdn.x.ai/final.png']) {
+ let downloadCalls = 0;
+ const badRedirect = vi.fn<typeof fetch>(async (input) => {
+ if (String(input).includes('/images/generations')) {
+ return new Response(JSON.stringify({ data: [{ url: 'https://imgen.x.ai/output.png' }] }), {
+ status: 200,
+ });
+ }
+ downloadCalls += 1;
+ return new Response(null, {
+ status: 302,
+ ...(location ? { headers: { Location: location } } : {}),
+ });
+ });
+ await expect(
+ channel(badRedirect).generateImage({ model: 'xai/grok-imagine-image', prompt: 'p' }),
+ ).rejects.toThrow(location ? 'HTTP 302' : '缺少 Location');
+ expect(downloadCalls).toBe(location ? 2 : 1);
+ }
+
+ const fakeImage = vi.fn<typeof fetch>(async (input) => {
+ const url = String(input);
+ if (url.includes('/images/generations')) {
+ return new Response(JSON.stringify({ data: [{ url: 'https://imgen.x.ai/output.png' }] }), {
+ status: 200,
+ });
+ }
+ if (url.endsWith('/output.png')) {
+ return new Response(null, { status: 302, headers: { Location: 'https://cdn.x.ai/final.png' } });
+ }
+ return new Response(Buffer.from('<html>error</html>'), {
+ status: 200,
+ headers: { 'content-type': 'image/png' },
+ });
+ });
+ await expect(
+ channel(fakeImage).generateImage({ model: 'xai/grok-imagine-image', prompt: 'p' }),
+ ).rejects.toThrow('不是有效图片');
});
it('账号作用域在准备请求或等待响应期间改变时 fail closed', async () => {
diff --git a/apps/desktop/src/main/cindy-brain/cindyGatewayReadiness.ts b/apps/desktop/src/main/cindy-brain/cindyGatewayReadiness.ts
index ec18f82e33..3e2c2345bf 100644
--- a/apps/desktop/src/main/cindy-brain/cindyGatewayReadiness.ts
+++ b/apps/desktop/src/main/cindy-brain/cindyGatewayReadiness.ts
@@ -1,8 +1,9 @@
/**
* cindyGatewayReadiness.ts — cindy 槽向量 / 视频供应商的运行期就绪判据。
*
- * XD 是这两个类目当前唯一的网关执行来源;账号能力与随凭据成对下发的
- * endpoint 必须同时存在,才能把 XD 型号投影进插件清单。
+ * XD 是向量与网关视频型号的执行来源;账号能力与随凭据成对下发的 endpoint
+ * 必须同时存在,才能把 XD 型号投影进插件清单。订阅型视频来源由调用方按
+ * 自己的 OAuth 就绪状态另行判断。
*/
import { getAppCapabilities } from '../appCapabilities.js';
import { effectiveXdGatewayBaseUrl } from '../model-access/effectiveEndpoint.js';
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 4b32376af4..ceb6e711f3 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -306,7 +306,11 @@ import {
} from '../secrets/providerSecretStore.js';
import { getActiveCatalog } from '../maker-host/active-catalog.js';
import { projectProviderCatalogForBuildRegion } from '../maker-host/provider-access-policy.js';
-import { getGrokAccessToken, hasGrokOAuthLogin } from '../maker-host/grok-oauth-login.js';
+import {
+ getGrokAccessToken,
+ getGrokOAuthCredentialGeneration,
+ hasGrokOAuthLogin,
+} from '../maker-host/grok-oauth-login.js';
import { invalidateXaiBridgeAuth } from '../maker-host/xai-auth-invalidation-host.js';
import { isModelDisabled, isProviderDisabled } from '@cindy/model-providers';
import { readModelDisableOverrides } from '../maker-host/model-disable-store.js';
@@ -349,6 +353,7 @@ import { createGeminiImageChannel } from './geminiImageClient.js';
import { createCodexImageChannel } from './codexImageClient.js';
import { getCodexImageAuthBinding } from './codexImageAuthBinding.js';
import { createGatewayImageClient } from '../cindy-proxy-media/api/gatewayImageClient.js';
+import { createXaiVideoProvider } from '../cindy-proxy-media/video/providers/xai.js';
import * as blobStore from '../cindy-media/blobStore.js';
import * as ledger from '../cindy-media/ledger.js';
import { ingestMedia, supportedMime } from '../cindy-media/ingest.js';
@@ -3043,11 +3048,45 @@ export function getGhostScheduleSlot(): GhostScheduleSlot {
* 生成走主机统一图片通道(art 底层客户端,与聊天画图同一条付费链路);
* 产物落媒体总仓(blob + 账本,出生=该意识),意识只拿到指纹字符串。
*/
+function getVideoProviderRegistry() {
+ const registry = getCindyProxyMediaService().backend.videoRegistry;
+ if (!registry) return null;
+ const xaiAliases =
+ getActiveCatalog()
+ .providers.find((provider) => provider.id === 'xai')
+ ?.videoModels?.map((model) => model.id) ?? [];
+ if (xaiAliases.some((alias) => !registry.hasAlias(alias))) {
+ registry.registerOrExtend(
+ createXaiVideoProvider({
+ modelAliases: xaiAliases,
+ hasOAuthLogin: () => hasGrokOAuthLogin(),
+ getAccessToken: () => getGrokAccessToken(),
+ getCredentialGeneration: () => getGrokOAuthCredentialGeneration(),
+ getOwnerScopeKey: () => activeOwnerScopeKey(),
+ isOwnerBoundaryPending: () => isAppSessionBoundaryPending(),
+ fetchImplementation: ((url, init) => outboundFetch(url as string, init)) as typeof fetch,
+ beforeDispatch: (model) => assertMediaModelStillEnabled('video', model),
+ onAuthRejected: (failure) => invalidateXaiBridgeAuth(failure),
+ }),
+ );
+ }
+ return registry;
+}
+
+/** 视频目录的 provider 级就绪判据;未知来源绝不投影成可选型号。 */
+function isVideoCatalogProviderReady(providerId: string): boolean {
+ if (providerId === 'xd') return isXdGatewayProviderReady(providerId);
+ if (providerId === 'xai') {
+ return !isAppSessionBoundaryPending() && hasGrokOAuthLogin();
+ }
+ return false;
+}
+
/**
* 当前媒体能力配置(图像/视频同一套推导)——与会话模型列表**同一获取
* 来源**:providers.json 运行时目录(getActiveCatalog,OSS 热更 + 内置兜底),
- * 汇总各供应商的 imageModels/imageDefaults 或 videoModels/videoDefaults
- * (今天只有 xd 网关一家有)。清单与默认/档位选型全部来自目录,主机代码零
+ * 汇总各供应商的 imageModels/imageDefaults 或 videoModels/videoDefaults。
+ * 清单与默认/档位选型全部来自目录,主机代码零
* 模型字面量;派生规则见 cindyMediaCatalog.ts。
*
* 目录里没有该类目的任何模型(极端:远端目录带了 xd 段却不带媒体清单)→
@@ -3074,18 +3113,19 @@ function getCatalogMediaConfig(kind: CindyCapabilityKind): CindyMediaCatalogConf
// (PR #1707 review)。滤掉后按既有语义降级:被滤条目不占 first-wins,
// 目录默认指向它时回落清单首项;整份清单都不认识才是空清单 → NO_CANDIDATE。
// 执行侧那道防御保留 —— 它管的是这里与执行层之间的窗口。
- (kind === 'embed' && !isKnownEmbeddingModel(modelId)),
+ (kind === 'embed' && !isKnownEmbeddingModel(modelId)) ||
+ // 视频目录可能比当前客户端通道先热更。执行 registry 不认识的型号
+ // 必须先过滤,不能把“目录有”冒充成“这版客户端能下单”。
+ (kind === 'video' && !(getVideoProviderRegistry()?.hasAlias(modelId) ?? false)),
// 执行通道凭证就绪过滤(未就绪的来源整段不进白名单,见 imageChannelRegistry
- // 头注)。图像走 registry;视频通道今天只有 xd 一家、不经 registry,但同样要求
- // 网关能力在场 —— 未登录本地模式(canUseCindyGateway=false)下 xd 的视频型号
- // 不能进清单,否则用户在本地模式钉选/点名视频型号就是"可选但必失败"
- // (2026-07 review:与图像的就绪语义对齐)。
- // 向量与视频同口径:通道只有 xd 一家、不经 registry,但要求账号网关能力与
- // model-access 随凭据成对下发的 endpoint 同时在场。登录同步完成前 / 存量
- // 手填 key 没有配套 endpoint 时,那种型号不该出现在清单里让用户钉选。
+ // 头注)。视频按目录 provider 归属分别检查:xd 要求账号网关能力与 endpoint
+ // 同时在场,xai 要求 SuperGrok OAuth 已连接;未知来源 fail closed。
+ // 向量仍只有 xd 一家执行通道。
kind === 'image'
? (providerId) => getImageChannelRegistry().isProviderReady(providerId)
- : isXdGatewayProviderReady,
+ : kind === 'video'
+ ? isVideoCatalogProviderReady
+ : isXdGatewayProviderReady,
// 编辑就绪过滤:仅支持生成的来源(supportsEdit: false)的模型不进编辑清单,
// 防用户把该型号钉到 image.edit 偏好后在 editImage 路径拿到确定性 400。
kind === 'image'
@@ -3168,7 +3208,7 @@ async function runGhostVideo(
refMode?: GhostVideoRefMode;
} & CindyVideoParams,
): Promise<{ buffer: Buffer; mimeType: string; videoParams: GhostVideoResultParams }> {
- const registry = getCindyProxyMediaService().backend.videoRegistry;
+ const registry = getVideoProviderRegistry();
if (!registry || !registry.hasAny()) {
throw new Error('视频能力不可用:主机未配置视频通道');
}
@@ -3197,7 +3237,7 @@ async function runGhostVideo(
*/
function getGhostVideoCapabilities(model: string): CindyVideoCapabilities | null {
try {
- const registry = getCindyProxyMediaService().backend.videoRegistry;
+ const registry = getVideoProviderRegistry();
if (!registry || !registry.hasAny()) return null;
const caps = registry.resolveByAlias(model).provider.capabilities;
return {
@@ -3267,6 +3307,7 @@ function getImageChannelRegistry(): ImageChannelRegistry {
createXaiImageChannel({
hasOAuthLogin: () => hasGrokOAuthLogin(),
getAccessToken: () => getGrokAccessToken(),
+ getCredentialGeneration: () => getGrokOAuthCredentialGeneration(),
getOwnerScopeKey: () => activeOwnerScopeKey(),
isOwnerBoundaryPending: () => isGhostBoundaryPending(),
fetchImplementation: ((url, init) => outboundFetch(url as string, init)) as typeof fetch,
@@ -3597,7 +3638,7 @@ export function getGhostCindySlot(): GhostCindySlot {
// registry 缺席/型号查无 → null,cindySlot 用自己的缺省。
videoExpectedSeconds: (model) => {
try {
- const registry = getCindyProxyMediaService().backend.videoRegistry;
+ const registry = getVideoProviderRegistry();
if (!registry || !registry.hasAny()) return null;
return registry.resolveByAlias(model).expectedSeconds;
} catch {
diff --git a/apps/desktop/src/main/cindy-brain/xaiImageClient.ts b/apps/desktop/src/main/cindy-brain/xaiImageClient.ts
index 2b0977f4ea..0a1249f7eb 100644
--- a/apps/desktop/src/main/cindy-brain/xaiImageClient.ts
+++ b/apps/desktop/src/main/cindy-brain/xaiImageClient.ts
@@ -15,6 +15,7 @@ import type { ImageChannel, ImageChannelResult } from './imageChannelRegistry.js
const XAI_API_BASE = 'https://api.x.ai/v1';
const MAX_EDIT_SOURCES = 3;
const MAX_IMAGE_DOWNLOAD_BYTES = 25 * 1024 * 1024;
+const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
interface XaiImageResponse {
data?: Array<{
@@ -28,6 +29,7 @@ interface XaiImageResponse {
export interface CreateXaiImageChannelOptions {
hasOAuthLogin(): boolean;
getAccessToken(): Promise<string>;
+ getCredentialGeneration(): number;
getOwnerScopeKey(): string;
isOwnerBoundaryPending(): boolean;
fetchImplementation?: typeof fetch;
@@ -69,12 +71,37 @@ function assertXaiImageUrl(raw: string): string {
} catch {
throw new Error('xAI 图像通道返回了不可信的图片地址');
}
- if (url.protocol !== 'https:' || !(url.hostname === 'x.ai' || url.hostname.endsWith('.x.ai'))) {
+ if (
+ url.protocol !== 'https:' ||
+ url.username ||
+ url.password ||
+ !(url.hostname === 'x.ai' || url.hostname.endsWith('.x.ai'))
+ ) {
throw new Error('xAI 图像通道返回了不可信的图片地址');
}
return url.toString();
}
+async function fetchXaiImageDownload(
+ doFetch: typeof fetch,
+ sourceUrl: string,
+ assertStillCurrent: () => void,
+): Promise<Response> {
+ assertStillCurrent();
+ const response = await doFetch(sourceUrl, { redirect: 'manual' });
+ assertStillCurrent();
+ if (!REDIRECT_STATUSES.has(response.status)) return response;
+
+ const location = response.headers.get('location');
+ await response.body?.cancel().catch(() => undefined);
+ assertStillCurrent();
+ if (!location) throw new Error('xAI 图片下载重定向缺少 Location');
+ const redirectUrl = assertXaiImageUrl(new URL(location, sourceUrl).toString());
+ const redirected = await doFetch(redirectUrl, { redirect: 'manual' });
+ assertStillCurrent();
+ return redirected;
+}
+
function captureOwnerScope(opts: CreateXaiImageChannelOptions): string {
if (opts.isOwnerBoundaryPending()) {
throw new Error('xAI 图片请求期间账号正在切换,请稍后重试');
@@ -88,6 +115,17 @@ function assertOwnerScopeCurrent(opts: CreateXaiImageChannelOptions, expected: s
}
}
+function assertRequestScopeCurrent(
+ opts: CreateXaiImageChannelOptions,
+ ownerScopeKey: string,
+ credentialGeneration: number,
+): void {
+ assertOwnerScopeCurrent(opts, ownerScopeKey);
+ if (opts.getCredentialGeneration() !== credentialGeneration) {
+ throw new Error('xAI 图片请求期间 SuperGrok 凭证已切换,请重试');
+ }
+}
+
async function readBoundedImageResponse(
response: Response,
maxBytes: number,
@@ -150,6 +188,10 @@ export function createXaiImageChannel(opts: CreateXaiImageChannelOptions): Image
// OAuth token 与源图都属于当前数据 owner。任务跨 await 后必须仍在同一稳定
// owner scope,不能把 A 的 token 或图片派发进 B 的运行时。
const ownerScopeKey = captureOwnerScope(opts);
+ const credentialGeneration = opts.getCredentialGeneration();
+ const assertStillCurrent = (): void =>
+ assertRequestScopeCurrent(opts, ownerScopeKey, credentialGeneration);
+ assertStillCurrent();
const [token, images] = await Promise.all([
opts.getAccessToken(),
Promise.all(paths.map(sourceImage)),
@@ -168,7 +210,7 @@ export function createXaiImageChannel(opts: CreateXaiImageChannelOptions): Image
}
opts.beforeDispatch?.(params.model);
- assertOwnerScopeCurrent(opts, ownerScopeKey);
+ assertStillCurrent();
const response = await doFetch(`${XAI_API_BASE}/images/${isEdit ? 'edits' : 'generations'}`, {
method: 'POST',
headers: {
@@ -179,7 +221,7 @@ export function createXaiImageChannel(opts: CreateXaiImageChannelOptions): Image
body: JSON.stringify(body),
});
const responseText = await response.text();
- assertOwnerScopeCurrent(opts, ownerScopeKey);
+ assertStillCurrent();
if (!response.ok) {
if ((response.status === 401 || response.status === 403) && opts.onAuthRejected) {
await opts
@@ -204,6 +246,7 @@ export function createXaiImageChannel(opts: CreateXaiImageChannelOptions): Image
const parsed = parseResponse(responseText);
const first = parsed.data?.[0];
if (first?.b64_json) {
+ assertStillCurrent();
return {
data: [{ b64_json: first.b64_json }],
output_format: first.mime_type?.split('/')[1] ?? 'png',
@@ -211,18 +254,24 @@ export function createXaiImageChannel(opts: CreateXaiImageChannelOptions): Image
}
if (first?.url) {
// Imagine URLs are short-lived. Materialize immediately so the shared media
- // pipeline receives stable bytes instead of persisting an expiring URL.
- const imageResponse = await doFetch(assertXaiImageUrl(first.url), { redirect: 'manual' });
+ // pipeline receives stable bytes instead of persisting an expiring URL. The
+ // initial URL and at most one redirect must both remain trusted x.ai targets.
+ const imageResponse = await fetchXaiImageDownload(
+ doFetch,
+ assertXaiImageUrl(first.url),
+ assertStillCurrent,
+ );
if (!imageResponse.ok) {
throw new Error(`xAI 图片下载失败(HTTP ${imageResponse.status})`);
}
const bytes = await readBoundedImageResponse(
imageResponse,
maxImageDownloadBytes,
- () => assertOwnerScopeCurrent(opts, ownerScopeKey),
+ assertStillCurrent,
);
const mime = sniffMediaMime(bytes);
if (!mime?.startsWith('image/')) throw new Error('xAI 图片下载结果不是有效图片');
+ assertStillCurrent();
return { data: [{ b64_json: bytes.toString('base64') }], output_format: mime.split('/')[1] };
}
throw new Error('xAI 图像通道未返回图片');
diff --git a/apps/desktop/src/main/cindy-proxy-media/video/__tests__/registry.test.ts b/apps/desktop/src/main/cindy-proxy-media/video/__tests__/registry.test.ts
index 9cf80ae7b8..65fa0e1ed1 100644
--- a/apps/desktop/src/main/cindy-proxy-media/video/__tests__/registry.test.ts
+++ b/apps/desktop/src/main/cindy-proxy-media/video/__tests__/registry.test.ts
@@ -61,6 +61,7 @@ describe('VideoProviderRegistry', () => {
it('starts empty', () => {
const r = new VideoProviderRegistry();
expect(r.hasAny()).toBe(false);
+ expect(r.hasAlias('missing')).toBe(false);
expect(r.collectAllAliases()).toEqual([]);
});
@@ -73,6 +74,7 @@ describe('VideoProviderRegistry', () => {
}),
);
expect(r.hasAny()).toBe(true);
+ expect(r.hasAlias('fast')).toBe(true);
const resolved = r.resolveByAlias('fast');
expect(resolved.provider.id).toBe('fakeprov');
expect(resolved.internalModel).toBe('fp-fast');
@@ -113,6 +115,20 @@ describe('VideoProviderRegistry', () => {
).toThrow(/duplicate alias/);
});
+ it('extends a provider with newly discovered aliases without removing in-flight aliases', () => {
+ const r = new VideoProviderRegistry();
+ r.register(
+ makeFakeProvider({ id: 'xai-video', aliases: [{ alias: 'xai/old', internalModel: 'old' }] }),
+ );
+ r.registerOrExtend(
+ makeFakeProvider({ id: 'xai-video', aliases: [{ alias: 'xai/new', internalModel: 'new' }] }),
+ );
+
+ expect(r.resolveByAlias('xai/old').internalModel).toBe('old');
+ expect(r.resolveByAlias('xai/new').internalModel).toBe('new');
+ expect(r.collectAllAliases().map((alias) => alias.alias)).toEqual(['xai/new']);
+ });
+
it('preserves registration order in collectAllAliases (first alias = default)', () => {
const r = new VideoProviderRegistry();
r.register(
diff --git a/apps/desktop/src/main/cindy-proxy-media/video/__tests__/run.test.ts b/apps/desktop/src/main/cindy-proxy-media/video/__tests__/run.test.ts
index d3271f3a72..7c507ce93c 100644
--- a/apps/desktop/src/main/cindy-proxy-media/video/__tests__/run.test.ts
+++ b/apps/desktop/src/main/cindy-proxy-media/video/__tests__/run.test.ts
@@ -202,6 +202,36 @@ describe('submitAndAwaitVideo · 画面参数', () => {
expect('audio' in r.effectiveParams).toBe(false);
});
+ it('型号固定有声但没有开关:不写请求字段,回执仍报告真实默认', async () => {
+ const submitted: VideoGenerationRequest[] = [];
+ const registry = makeRegistry(
+ makeProvider({ submitted, supportsAudio: false, audioDefault: true }),
+ );
+ const result = await submitAndAwaitVideo(registry, { alias: 'fake-fast', prompt: 'p' });
+ expect('audio' in submitted[0]).toBe(false);
+ expect(result.effectiveParams.audio).toBe(true);
+ });
+
+ it('保留 ratio 是否由调用方显式选择,供图生视频决定是否覆盖源图比例', async () => {
+ const submitted: VideoGenerationRequest[] = [];
+ const registry = makeRegistry(makeProvider({ submitted }));
+ await submitAndAwaitVideo(registry, {
+ alias: 'fake-fast',
+ prompt: 'p',
+ imageDataUris: ['data:image/png;base64,AAAA'],
+ });
+ await submitAndAwaitVideo(registry, {
+ alias: 'fake-fast',
+ prompt: 'p',
+ ratio: '9:16',
+ imageDataUris: ['data:image/png;base64,AAAA'],
+ });
+ expect(submitted[0].ratio).toBe('16:9');
+ expect(submitted[0].ratioWasExplicit).toBe(false);
+ expect(submitted[1].ratio).toBe('9:16');
+ expect(submitted[1].ratioWasExplicit).toBe(true);
+ });
+
it('参考图超出型号上限 → 抛错且不提交', async () => {
const submitted: VideoGenerationRequest[] = [];
const registry = makeRegistry(makeProvider({ submitted, maxImagesByRefMode: { first_and_last_frame: 1 } }));
diff --git a/apps/desktop/src/main/cindy-proxy-media/video/__tests__/videoModelsSync.test.ts b/apps/desktop/src/main/cindy-proxy-media/video/__tests__/videoModelsSync.test.ts
index 8f2a268794..d64c0fe18c 100644
--- a/apps/desktop/src/main/cindy-proxy-media/video/__tests__/videoModelsSync.test.ts
+++ b/apps/desktop/src/main/cindy-proxy-media/video/__tests__/videoModelsSync.test.ts
@@ -10,6 +10,7 @@
*/
import { describe, expect, it } from 'vitest';
+import { BUNDLED_CATALOG } from '@cindy/model-providers';
import {
GHOST_VIDEO_MAX_SOURCES_BY_REF_MODE,
@@ -23,8 +24,9 @@ import {
createSeedanceProvider,
} from '../providers/seedance.js';
import { createHappyhorseProvider } from '../providers/happyhorse.js';
+import { createXaiVideoProvider } from '../providers/xai.js';
-function buildRealRegistry(): VideoProviderRegistry {
+function buildXdRegistry(): VideoProviderRegistry {
// 与 desktop mcp-integrations/cindyProxyMedia.ts 同一装配顺序(seedance 先注册,
// seedance-fast 是全局默认)。这份 fixture 必须跟着真实装配走 —— 它就是本文件
// 那几条同源守卫的被测对象。
@@ -36,21 +38,35 @@ function buildRealRegistry(): VideoProviderRegistry {
return registry;
}
+function buildFullRegistry(): VideoProviderRegistry {
+ const registry = buildXdRegistry();
+ registry.register(
+ createXaiVideoProvider({
+ hasOAuthLogin: () => true,
+ getAccessToken: async () => 'test-token',
+ getCredentialGeneration: () => 1,
+ getOwnerScopeKey: () => 'owner-a',
+ isOwnerBoundaryPending: () => false,
+ }),
+ );
+ return registry;
+}
+
describe('GATEWAY_VIDEO_MODELS ↔ provider alias 同源', () => {
it('常量里的每个 id 都能在真实 provider 注册表里解析', () => {
- const registry = buildRealRegistry();
+ const registry = buildXdRegistry();
for (const m of GATEWAY_VIDEO_MODELS) {
expect(() => registry.resolveByAlias(m.id), m.id).not.toThrow();
}
});
it('常量首项 = 注册序首别名(出厂默认对齐)', () => {
- const registry = buildRealRegistry();
+ const registry = buildXdRegistry();
expect(GATEWAY_VIDEO_MODELS[0].id).toBe(registry.collectAllAliases()[0].alias);
});
it('常量无遗漏:注册表的全部别名都在常量里(下拉/白名单不缺项)', () => {
- const registry = buildRealRegistry();
+ const registry = buildXdRegistry();
const constantIds = new Set<string>(GATEWAY_VIDEO_MODELS.map((m) => m.id));
for (const a of registry.collectAllAliases()) {
expect(constantIds.has(a.alias), a.alias).toBe(true);
@@ -58,6 +74,17 @@ describe('GATEWAY_VIDEO_MODELS ↔ provider alias 同源', () => {
});
});
+describe('providers.json 视频清单 ↔ 完整 provider registry 同源', () => {
+ it('xAI 目录中的每个视频型号都有客户端执行通道', () => {
+ const registry = buildFullRegistry();
+ const xai = BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xai');
+ expect(xai?.videoModels?.length).toBeGreaterThan(0);
+ for (const model of xai?.videoModels ?? []) {
+ expect(registry.hasAlias(model.id), model.id).toBe(true);
+ }
+ });
+});
+
/**
* 同源守卫之二:协议层的参考图张数粗筛上界(shared/ghost.ts,插件协议面)
* 与 provider 实际声明的上限。
@@ -73,7 +100,7 @@ describe('GATEWAY_VIDEO_MODELS ↔ provider alias 同源', () => {
*/
describe('参考图张数上界 ↔ provider capabilities 同源', () => {
it('协议层上界 ≥ 各 provider 的实际上限(调高 provider 忘改协议层就在这炸)', () => {
- const registry = buildRealRegistry();
+ const registry = buildFullRegistry();
const union = registry.collectUnionParams().maxImagesUpperBoundByRefMode;
for (const [mode, providerMax] of Object.entries(union)) {
const protocolMax =
@@ -89,7 +116,7 @@ describe('参考图张数上界 ↔ provider capabilities 同源', () => {
});
it('provider 不得声明协议层不认识的 refMode(否则插件永远传不进来)', () => {
- const registry = buildRealRegistry();
+ const registry = buildFullRegistry();
const known = new Set<string>(GHOST_VIDEO_REF_MODES);
const union = registry.collectUnionParams().maxImagesUpperBoundByRefMode;
for (const mode of Object.keys(union)) {
@@ -116,7 +143,7 @@ describe('参考图张数上界 ↔ provider capabilities 同源', () => {
*/
describe('画幅值域 ↔ 协议层枚举同源', () => {
it('每个 alias 报出的画幅都在协议层枚举内(公布了插件也传不进来)', () => {
- const registry = buildRealRegistry();
+ const registry = buildFullRegistry();
const known = new Set<string>(GHOST_VIDEO_RATIOS);
// 按 alias 遍历而不是按 provider:这正是插件的视角 —— cindySlot 拿到型号名后
// 经 getGhostVideoCapabilities 解析出的就是该 alias 背后 provider 的 caps。
diff --git a/apps/desktop/src/main/cindy-proxy-media/video/__tests__/xaiProvider.test.ts b/apps/desktop/src/main/cindy-proxy-media/video/__tests__/xaiProvider.test.ts
new file mode 100644
index 0000000000..2cdd2fa400
--- /dev/null
+++ b/apps/desktop/src/main/cindy-proxy-media/video/__tests__/xaiProvider.test.ts
@@ -0,0 +1,713 @@
+/**
+ * xAI video provider contract: SuperGrok OAuth stays in Main, Cindy's normalized
+ * video params map to the async xAI API, and account switches fail closed across
+ * submit/poll/download.
+ */
+
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ createXaiVideoProvider,
+ XAI_VIDEO_CATALOG_MODEL_ID,
+} from '../providers/xai.js';
+
+const MP4_BYTES = Buffer.from('00000010667479706d70343200000000', 'hex');
+
+interface HarnessOptions {
+ fetchImplementation: typeof fetch;
+ owner?: { value: string; pending: boolean };
+ credential?: { value: number };
+ getAccessToken?: () => Promise<string>;
+ onAuthRejected?: ReturnType<typeof vi.fn>;
+ maxVideoDownloadBytes?: number;
+}
+
+function makeProvider(options: HarnessOptions) {
+ const owner = options.owner ?? { value: 'owner-a', pending: false };
+ const credential = options.credential ?? { value: 1 };
+ return createXaiVideoProvider({
+ hasOAuthLogin: () => true,
+ getAccessToken: options.getAccessToken ?? (async () => 'oauth-token'),
+ getCredentialGeneration: () => credential.value,
+ getOwnerScopeKey: () => owner.value,
+ isOwnerBoundaryPending: () => owner.pending,
+ fetchImplementation: options.fetchImplementation,
+ onAuthRejected: options.onAuthRejected,
+ maxVideoDownloadBytes: options.maxVideoDownloadBytes,
+ });
+}
+
+describe('xAI video provider · capabilities', () => {
+ const provider = makeProvider({ fetchImplementation: vi.fn() as unknown as typeof fetch });
+
+ it('exposes the catalog alias and the API-supported common value ranges', () => {
+ expect(provider.capabilities.modelAliases.map((item) => item.alias)).toEqual([
+ XAI_VIDEO_CATALOG_MODEL_ID,
+ ]);
+ expect(provider.capabilities.supportedDurations).toEqual(
+ Array.from({ length: 15 }, (_, index) => index + 1),
+ );
+ expect(provider.capabilities.supportedResolutions).toEqual(['480p', '720p', '1080p']);
+ expect(provider.capabilities.supportedRatios).toEqual([
+ '16:9',
+ '9:16',
+ '1:1',
+ '4:3',
+ '3:4',
+ ]);
+ expect(provider.capabilities.maxImagesByRefMode).toEqual({ first_and_last_frame: 1 });
+ expect(provider.capabilities.supportsAudio).toBe(false);
+ expect(provider.capabilities.audioDefault).toBe(true);
+ });
+
+ it('accepts future catalog aliases without a model-name whitelist', async () => {
+ const fetchMock = vi.fn(
+ async () => new Response(JSON.stringify({ request_id: 'future-task' }), { status: 200 }),
+ ) as unknown as typeof fetch;
+ const future = 'xai/future-video-model';
+ const dynamicProvider = createXaiVideoProvider({
+ modelAliases: [future],
+ hasOAuthLogin: () => true,
+ getAccessToken: async () => 'oauth-token',
+ getCredentialGeneration: () => 1,
+ getOwnerScopeKey: () => 'owner-a',
+ isOwnerBoundaryPending: () => false,
+ fetchImplementation: fetchMock,
+ });
+
+ await expect(dynamicProvider.submit({ prompt: 'future' }, future)).resolves.toMatchObject({
+ modelUsed: 'future-video-model',
+ });
+ const init = (fetchMock as unknown as ReturnType<typeof vi.fn>).mock.calls[0][1] as RequestInit;
+ expect(JSON.parse(init.body as string).model).toBe('future-video-model');
+ });
+});
+
+describe('xAI video provider · submit', () => {
+ it('maps text-to-video params without inventing unsupported fps/audio fields', async () => {
+ const fetchMock = vi.fn(async () =>
+ new Response(JSON.stringify({ request_id: 'video-1' }), { status: 200 }),
+ ) as unknown as typeof fetch;
+ const provider = makeProvider({ fetchImplementation: fetchMock });
+
+ const handle = await provider.submit(
+ {
+ prompt: 'A paper dragon takes flight',
+ duration: 8,
+ resolution: '1080p',
+ ratio: '9:16',
+ fps: 24,
+ },
+ XAI_VIDEO_CATALOG_MODEL_ID,
+ );
+
+ expect(handle).toMatchObject({
+ providerId: 'xai-video',
+ taskId: 'video-1',
+ modelUsed: 'grok-imagine-video',
+ ownerScopeKey: 'owner-a',
+ credentialGeneration: 1,
+ });
+ const [url, init] = (fetchMock as unknown as ReturnType<typeof vi.fn>).mock.calls[0];
+ expect(url).toBe('https://api.x.ai/v1/videos/generations');
+ expect((init.headers as Record<string, string>).Authorization).toBe('Bearer oauth-token');
+ const body = JSON.parse(init.body as string);
+ expect(body).toEqual({
+ model: 'grok-imagine-video',
+ prompt: 'A paper dragon takes flight',
+ duration: 8,
+ aspect_ratio: '9:16',
+ resolution: '1080p',
+ });
+ expect(body).not.toHaveProperty('fps');
+ expect(body).not.toHaveProperty('audio');
+ });
+
+ it('maps one reference image to xAI image-to-video', async () => {
+ const fetchMock = vi.fn(async () =>
+ new Response(JSON.stringify({ request_id: 'video-2' }), { status: 200 }),
+ ) as unknown as typeof fetch;
+ const provider = makeProvider({ fetchImplementation: fetchMock });
+
+ await provider.submit(
+ {
+ prompt: 'Make the portrait blink',
+ duration: 4,
+ resolution: '720p',
+ ratio: '1:1',
+ ratioWasExplicit: true,
+ fps: 24,
+ images: ['data:image/png;base64,AAAA'],
+ },
+ XAI_VIDEO_CATALOG_MODEL_ID,
+ );
+
+ const init = (fetchMock as unknown as ReturnType<typeof vi.fn>).mock.calls[0][1] as RequestInit;
+ expect(JSON.parse(init.body as string).image).toEqual({
+ url: 'data:image/png;base64,AAAA',
+ });
+ expect(JSON.parse(init.body as string).aspect_ratio).toBe('1:1');
+ });
+
+ it('keeps the source image ratio when the caller did not select one', async () => {
+ const fetchMock = vi.fn(async () =>
+ new Response(JSON.stringify({ request_id: 'video-native-ratio' }), { status: 200 }),
+ ) as unknown as typeof fetch;
+ const provider = makeProvider({ fetchImplementation: fetchMock });
+
+ await provider.submit(
+ {
+ prompt: 'Animate without cropping',
+ duration: 6,
+ resolution: '720p',
+ ratio: '16:9',
+ ratioWasExplicit: false,
+ fps: 24,
+ images: ['data:image/png;base64,AAAA'],
+ },
+ XAI_VIDEO_CATALOG_MODEL_ID,
+ );
+
+ const init = (fetchMock as unknown as ReturnType<typeof vi.fn>).mock.calls[0][1] as RequestInit;
+ const body = JSON.parse(init.body as string);
+ expect(body.image).toEqual({ url: 'data:image/png;base64,AAAA' });
+ expect(body).not.toHaveProperty('aspect_ratio');
+ });
+
+ it('forwards 401/403 to the shared xAI auth invalidator', async () => {
+ const onAuthRejected = vi.fn(async () => 'refreshed');
+ const fetchMock = vi.fn(async () =>
+ new Response(JSON.stringify({ error: { message: 'expired' } }), { status: 401 }),
+ ) as unknown as typeof fetch;
+ const provider = makeProvider({ fetchImplementation: fetchMock, onAuthRejected });
+
+ await expect(
+ provider.submit({ prompt: 'test' }, XAI_VIDEO_CATALOG_MODEL_ID),
+ ).rejects.toThrow(/HTTP 401.*expired/);
+ expect(onAuthRejected).toHaveBeenCalledWith({
+ status: 401,
+ body: JSON.stringify({ error: { message: 'expired' } }),
+ failedAccessToken: 'oauth-token',
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('discards a late submit response after the SuperGrok credential changes', async () => {
+ const credential = { value: 1 };
+ const fetchMock = vi.fn(async () => {
+ credential.value = 2;
+ return new Response(JSON.stringify({ request_id: 'late-submit' }), { status: 200 });
+ }) as unknown as typeof fetch;
+ const provider = makeProvider({ fetchImplementation: fetchMock, credential });
+
+ await expect(
+ provider.submit({ prompt: 'late submit' }, XAI_VIDEO_CATALOG_MODEL_ID),
+ ).rejects.toThrow(/SuperGrok 凭证已切换/);
+ });
+});
+
+describe('xAI video provider · poll and download', () => {
+ it('polls the task and downloads content with the originating owner OAuth', async () => {
+ const responses = [
+ new Response(JSON.stringify({ request_id: 'video-3' }), { status: 200 }),
+ new Response(JSON.stringify({ status: 'pending' }), { status: 200 }),
+ new Response(
+ JSON.stringify({
+ status: 'done',
+ video: {
+ url: 'https://vidgen.x.ai/tasks/video-3.mp4',
+ duration: 7,
+ resolution: '720p',
+ aspect_ratio: '16:9',
+ fps: 24,
+ },
+ }),
+ { status: 200 },
+ ),
+ new Response(MP4_BYTES, {
+ status: 200,
+ headers: { 'content-type': 'video/mp4' },
+ }),
+ ];
+ const fetchMock = vi.fn(async () => responses.shift()!) as unknown as typeof fetch;
+ const provider = makeProvider({ fetchImplementation: fetchMock });
+ const handle = await provider.submit(
+ { prompt: 'waves', duration: 7, resolution: '720p', ratio: '16:9', fps: 24 },
+ XAI_VIDEO_CATALOG_MODEL_ID,
+ );
+
+ await expect(provider.poll(handle)).resolves.toMatchObject({ state: 'pending' });
+ const done = await provider.poll(handle);
+ expect(done).toMatchObject({
+ state: 'succeeded',
+ meta: { durationSec: 7, resolution: '720p', ratio: '16:9', fps: 24 },
+ });
+ if (done.state !== 'succeeded') throw new Error('expected succeeded');
+ const downloaded = await provider.download(done.videoUrl);
+ expect(downloaded).toEqual({ buffer: MP4_BYTES, mimeType: 'video/mp4' });
+
+ const calls = (fetchMock as unknown as ReturnType<typeof vi.fn>).mock.calls;
+ expect(calls[1][0]).toBe('https://api.x.ai/v1/videos/video-3');
+ expect(calls[2][0]).toBe('https://api.x.ai/v1/videos/video-3');
+ expect(calls[3][0]).toBe('https://vidgen.x.ai/tasks/video-3.mp4');
+ expect(calls[3][1]).toMatchObject({ method: 'GET', redirect: 'manual' });
+ expect(calls[3][1].headers).toBeUndefined();
+ });
+
+ it('follows one trusted download redirect and validates the final video bytes', async () => {
+ const fetchMock = vi.fn(async (url: string | URL | Request) =>
+ String(url) === 'https://vidgen.x.ai/tasks/redirect.mp4'
+ ? new Response(null, { status: 302, headers: { Location: '/cdn/final.mp4' } })
+ : new Response(MP4_BYTES, { status: 200, headers: { 'content-type': 'text/plain' } }),
+ ) as unknown as typeof fetch;
+ const provider = makeProvider({ fetchImplementation: fetchMock });
+ const videoUrl =
+ 'xai-video://content/task?owner=owner-a&credential=1&source=https%3A%2F%2Fvidgen.x.ai%2Ftasks%2Fredirect.mp4';
+
+ await expect(provider.download(videoUrl)).resolves.toEqual({
+ buffer: MP4_BYTES,
+ mimeType: 'video/mp4',
+ });
+ expect((fetchMock as unknown as ReturnType<typeof vi.fn>).mock.calls).toEqual([
+ ['https://vidgen.x.ai/tasks/redirect.mp4', { method: 'GET', redirect: 'manual' }],
+ ['https://vidgen.x.ai/cdn/final.mp4', { method: 'GET', redirect: 'manual' }],
+ ]);
+ });
+
+ it('rejects unsafe video redirects and keeps owner and credential generation current', async () => {
+ const videoUrl =
+ 'xai-video://content/task?owner=owner-a&credential=1&source=https%3A%2F%2Fvidgen.x.ai%2Ftasks%2Fredirect.mp4';
+ for (const location of [undefined, 'https://example.com/final.mp4']) {
+ const fetchMock = vi.fn(async () =>
+ new Response(null, {
+ status: 302,
+ ...(location ? { headers: { Location: location } } : {}),
+ }),
+ ) as unknown as typeof fetch;
+ await expect(
+ makeProvider({ fetchImplementation: fetchMock }).download(videoUrl),
+ ).rejects.toThrow(location ? /不可信/ : /缺少 Location/);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ }
+
+ const repeated = vi.fn(async () =>
+ new Response(null, { status: 307, headers: { Location: 'https://cdn.x.ai/again.mp4' } }),
+ ) as unknown as typeof fetch;
+ await expect(
+ makeProvider({ fetchImplementation: repeated }).download(videoUrl),
+ ).rejects.toThrow(/下载失败\(HTTP 307\)/);
+ expect(repeated).toHaveBeenCalledTimes(2);
+
+ const owner = { value: 'owner-a', pending: false };
+ const ownerSwitch = vi.fn(async () => {
+ owner.value = 'owner-b';
+ return new Response(null, { status: 302, headers: { Location: 'https://cdn.x.ai/final.mp4' } });
+ }) as unknown as typeof fetch;
+ await expect(
+ makeProvider({ fetchImplementation: ownerSwitch, owner }).download(videoUrl),
+ ).rejects.toThrow(/账号已切换/);
+
+ owner.value = 'owner-a';
+ const credential = { value: 1 };
+ const credentialSwitch = vi.fn(async (url: string | URL | Request) => {
+ if (String(url).includes('vidgen.x.ai')) {
+ return new Response(null, { status: 302, headers: { Location: 'https://cdn.x.ai/final.mp4' } });
+ }
+ credential.value = 2;
+ return new Response(MP4_BYTES, { status: 200 });
+ }) as unknown as typeof fetch;
+ await expect(
+ makeProvider({ fetchImplementation: credentialSwitch, credential }).download(videoUrl),
+ ).rejects.toThrow(/SuperGrok 凭证已切换/);
+ });
+
+ it('fails closed when the active account changes after submit', async () => {
+ const owner = { value: 'owner-a', pending: false };
+ const fetchMock = vi.fn(async () =>
+ new Response(JSON.stringify({ request_id: 'video-owner' }), { status: 200 }),
+ ) as unknown as typeof fetch;
+ const provider = makeProvider({ fetchImplementation: fetchMock, owner });
+ const handle = await provider.submit(
+ { prompt: 'owner test' },
+ XAI_VIDEO_CATALOG_MODEL_ID,
+ );
+ owner.value = 'owner-b';
+
+ await expect(provider.poll(handle)).rejects.toThrow(/账号已切换/);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it.each(['refreshed', 'superseded'] as const)(
+ 'retries one poll when auth recovery is %s without resubmitting the paid task',
+ async (recovery) => {
+ const tokens = ['account-a-old-token', 'account-a-old-token', 'account-a-fresh-token'];
+ const getAccessToken = vi.fn(async () => tokens.shift()!);
+ const badCredentialBody = JSON.stringify({
+ code: 'unauthenticated:bad-credentials',
+ error: 'The OAuth2 access token could not be validated.',
+ });
+ const responses = [
+ new Response(JSON.stringify({ request_id: 'video-auth-recovery' }), { status: 200 }),
+ new Response(badCredentialBody, { status: 403 }),
+ new Response(JSON.stringify({ status: 'pending' }), { status: 200 }),
+ ];
+ const fetchMock = vi.fn(async () => responses.shift()!) as unknown as typeof fetch;
+ const onAuthRejected = vi.fn(async () => recovery);
+ const provider = makeProvider({
+ fetchImplementation: fetchMock,
+ getAccessToken,
+ onAuthRejected,
+ });
+ const handle = await provider.submit({ prompt: 'recover poll' }, XAI_VIDEO_CATALOG_MODEL_ID);
+
+ await expect(provider.poll(handle)).resolves.toMatchObject({ state: 'pending' });
+ expect(onAuthRejected).toHaveBeenCalledTimes(1);
+ expect(onAuthRejected).toHaveBeenCalledWith({
+ status: 403,
+ body: badCredentialBody,
+ failedAccessToken: 'account-a-old-token',
+ });
+ const calls = (fetchMock as unknown as ReturnType<typeof vi.fn>).mock.calls;
+ expect(calls).toHaveLength(3);
+ expect(calls.filter(([, init]) => (init as RequestInit).method === 'POST')).toHaveLength(1);
+ expect(calls[1][0]).toBe('https://api.x.ai/v1/videos/video-auth-recovery');
+ expect(calls[2][0]).toBe('https://api.x.ai/v1/videos/video-auth-recovery');
+ expect((calls[1][1].headers as Record<string, string>).Authorization).toBe(
+ 'Bearer account-a-old-token',
+ );
+ expect((calls[2][1].headers as Record<string, string>).Authorization).toBe(
+ 'Bearer account-a-fresh-token',
+ );
+ },
+ );
+
+ it('does not retry a poll when credential recovery fails', async () => {
+ const badCredentialBody = JSON.stringify({
+ code: 'unauthenticated:bad-credentials',
+ error: 'The OAuth2 access token could not be validated.',
+ });
+ const responses = [
+ new Response(JSON.stringify({ request_id: 'video-auth-failed' }), { status: 200 }),
+ new Response(badCredentialBody, { status: 401 }),
+ ];
+ const fetchMock = vi.fn(async () => responses.shift()!) as unknown as typeof fetch;
+ const onAuthRejected = vi.fn(async () => 'unchanged');
+ const provider = makeProvider({ fetchImplementation: fetchMock, onAuthRejected });
+ const handle = await provider.submit({ prompt: 'failed recovery' }, XAI_VIDEO_CATALOG_MODEL_ID);
+
+ await expect(provider.poll(handle)).rejects.toThrow(/HTTP 401/);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(onAuthRejected).toHaveBeenCalledTimes(1);
+ });
+
+ it('limits a recovered poll to one retry', async () => {
+ const responses = [
+ new Response(JSON.stringify({ request_id: 'video-auth-retry-limit' }), { status: 200 }),
+ new Response(JSON.stringify({ code: 'unauthenticated:bad-credentials' }), { status: 403 }),
+ new Response(JSON.stringify({ code: 'unauthenticated:bad-credentials' }), { status: 403 }),
+ ];
+ const fetchMock = vi.fn(async () => responses.shift()!) as unknown as typeof fetch;
+ const onAuthRejected = vi.fn(async () => 'refreshed');
+ const provider = makeProvider({ fetchImplementation: fetchMock, onAuthRejected });
+ const handle = await provider.submit({ prompt: 'retry limit' }, XAI_VIDEO_CATALOG_MODEL_ID);
+
+ await expect(provider.poll(handle)).rejects.toThrow(/HTTP 403/);
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ expect(onAuthRejected).toHaveBeenCalledTimes(1);
+ });
+
+ it('rejects recovery when logout changes the credential generation', async () => {
+ const credential = { value: 1 };
+ const responses = [
+ new Response(JSON.stringify({ request_id: 'video-auth-generation' }), { status: 200 }),
+ new Response(JSON.stringify({ code: 'unauthenticated:bad-credentials' }), { status: 403 }),
+ ];
+ const fetchMock = vi.fn(async () => responses.shift()!) as unknown as typeof fetch;
+ const onAuthRejected = vi.fn(async () => {
+ credential.value = 2;
+ return 'logged_out';
+ });
+ const provider = makeProvider({ fetchImplementation: fetchMock, credential, onAuthRejected });
+ const handle = await provider.submit(
+ { prompt: 'generation changed' },
+ XAI_VIDEO_CATALOG_MODEL_ID,
+ );
+
+ await expect(provider.poll(handle)).rejects.toThrow(/SuperGrok 凭证已切换/);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('rejects recovery when the owner changes', async () => {
+ const owner = { value: 'owner-a', pending: false };
+ const responses = [
+ new Response(JSON.stringify({ request_id: 'video-auth-owner' }), { status: 200 }),
+ new Response(JSON.stringify({ code: 'unauthenticated:bad-credentials' }), { status: 403 }),
+ ];
+ const fetchMock = vi.fn(async () => responses.shift()!) as unknown as typeof fetch;
+ const onAuthRejected = vi.fn(async () => {
+ owner.value = 'owner-b';
+ return 'refreshed';
+ });
+ const provider = makeProvider({ fetchImplementation: fetchMock, owner, onAuthRejected });
+ const handle = await provider.submit({ prompt: 'owner changed' }, XAI_VIDEO_CATALOG_MODEL_ID);
+
+ await expect(provider.poll(handle)).rejects.toThrow(/账号已切换/);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('discards a late retry response after the credential generation changes', async () => {
+ const credential = { value: 1 };
+ let calls = 0;
+ const fetchMock = vi.fn(async () => {
+ calls += 1;
+ if (calls === 1) {
+ return new Response(JSON.stringify({ request_id: 'video-auth-late-retry' }), {
+ status: 200,
+ });
+ }
+ if (calls === 2) {
+ return new Response(JSON.stringify({ code: 'unauthenticated:bad-credentials' }), {
+ status: 403,
+ });
+ }
+ credential.value = 2;
+ return new Response(JSON.stringify({ status: 'pending' }), { status: 200 });
+ }) as unknown as typeof fetch;
+ const onAuthRejected = vi.fn(async () => 'refreshed');
+ const provider = makeProvider({ fetchImplementation: fetchMock, credential, onAuthRejected });
+ const handle = await provider.submit({ prompt: 'late retry' }, XAI_VIDEO_CATALOG_MODEL_ID);
+
+ await expect(provider.poll(handle)).rejects.toThrow(/SuperGrok 凭证已切换/);
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ });
+
+ it('rejects an old task before reading a replacement SuperGrok credential', async () => {
+ const credential = { value: 1 };
+ const getAccessToken = vi.fn(async () => 'account-a-token');
+ const fetchMock = vi.fn(async () =>
+ new Response(JSON.stringify({ request_id: 'video-credential' }), { status: 200 }),
+ ) as unknown as typeof fetch;
+ const provider = makeProvider({ fetchImplementation: fetchMock, credential, getAccessToken });
+ const handle = await provider.submit(
+ { prompt: 'credential test' },
+ XAI_VIDEO_CATALOG_MODEL_ID,
+ );
+ credential.value = 2;
+
+ await expect(provider.poll(handle)).rejects.toThrow(/SuperGrok 凭证已切换/);
+ expect(getAccessToken).toHaveBeenCalledTimes(1);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('rejects a poll when the credential changes while the token is being read', async () => {
+ const credential = { value: 1 };
+ let tokenReads = 0;
+ const getAccessToken = vi.fn(async () => {
+ tokenReads += 1;
+ if (tokenReads === 2) credential.value = 2;
+ return tokenReads === 1 ? 'account-a-token' : 'account-b-token';
+ });
+ const fetchMock = vi.fn(async () =>
+ new Response(JSON.stringify({ request_id: 'video-token-race' }), { status: 200 }),
+ ) as unknown as typeof fetch;
+ const provider = makeProvider({ fetchImplementation: fetchMock, credential, getAccessToken });
+ const handle = await provider.submit(
+ { prompt: 'token race' },
+ XAI_VIDEO_CATALOG_MODEL_ID,
+ );
+
+ await expect(provider.poll(handle)).rejects.toThrow(/SuperGrok 凭证已切换/);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('discards a late poll response from the old credential generation', async () => {
+ const credential = { value: 1 };
+ let calls = 0;
+ const fetchMock = vi.fn(async () => {
+ calls += 1;
+ if (calls === 1) {
+ return new Response(JSON.stringify({ request_id: 'video-late-poll' }), { status: 200 });
+ }
+ credential.value = 2;
+ return new Response(JSON.stringify({ status: 'pending' }), { status: 200 });
+ }) as unknown as typeof fetch;
+ const provider = makeProvider({ fetchImplementation: fetchMock, credential });
+ const handle = await provider.submit(
+ { prompt: 'late poll' },
+ XAI_VIDEO_CATALOG_MODEL_ID,
+ );
+
+ await expect(provider.poll(handle)).rejects.toThrow(/SuperGrok 凭证已切换/);
+ });
+
+ it('rejects an old completed-task download after logout or reconnect', async () => {
+ const credential = { value: 1 };
+ const responses = [
+ new Response(JSON.stringify({ request_id: 'video-old-download' }), { status: 200 }),
+ new Response(
+ JSON.stringify({
+ status: 'done',
+ video: { url: 'https://vidgen.x.ai/tasks/video-old-download.mp4' },
+ }),
+ { status: 200 },
+ ),
+ ];
+ const fetchMock = vi.fn(async () => responses.shift()!) as unknown as typeof fetch;
+ const provider = makeProvider({ fetchImplementation: fetchMock, credential });
+ const handle = await provider.submit(
+ { prompt: 'old download' },
+ XAI_VIDEO_CATALOG_MODEL_ID,
+ );
+ const done = await provider.poll(handle);
+ if (done.state !== 'succeeded') throw new Error('expected succeeded');
+ credential.value = 2;
+
+ await expect(provider.download(done.videoUrl)).rejects.toThrow(/SuperGrok 凭证已切换/);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('trusts verified video bytes instead of the Content-Type header', async () => {
+ const owner = { value: 'owner-a', pending: false };
+ const validWithoutHeader = makeProvider({
+ owner,
+ fetchImplementation: vi.fn(
+ async () => new Response(MP4_BYTES, { status: 200 }),
+ ) as unknown as typeof fetch,
+ });
+ const videoUrl =
+ 'xai-video://content/task?owner=owner-a&credential=1&source=https%3A%2F%2Fvidgen.x.ai%2Ftask.mp4';
+
+ await expect(validWithoutHeader.download(videoUrl)).resolves.toEqual({
+ buffer: MP4_BYTES,
+ mimeType: 'video/mp4',
+ });
+
+ for (const contentType of [undefined, 'video/mp4', 'text/html']) {
+ const invalid = makeProvider({
+ owner,
+ fetchImplementation: vi.fn(
+ async () =>
+ new Response(Buffer.from('<html>cdn error</html>'), {
+ status: 200,
+ ...(contentType ? { headers: { 'content-type': contentType } } : {}),
+ }),
+ ) as unknown as typeof fetch,
+ });
+ await expect(invalid.download(videoUrl)).rejects.toThrow(/不是受支持的视频/);
+ }
+ });
+
+ it('does not run OAuth recovery for unauthenticated CDN downloads', async () => {
+ const onAuthRejected = vi.fn(async () => 'refreshed');
+ const fetchMock = vi.fn(
+ async () => new Response('expired download', { status: 403 }),
+ ) as unknown as typeof fetch;
+ const provider = makeProvider({ fetchImplementation: fetchMock, onAuthRejected });
+ const videoUrl =
+ 'xai-video://content/task?owner=owner-a&credential=1&source=https%3A%2F%2Fvidgen.x.ai%2Ftask.mp4';
+
+ await expect(provider.download(videoUrl)).rejects.toThrow(/下载失败\(HTTP 403\)/);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(
+ (fetchMock as unknown as ReturnType<typeof vi.fn>).mock.calls[0][1].headers,
+ ).toBeUndefined();
+ expect(onAuthRejected).not.toHaveBeenCalled();
+ });
+
+ it('rechecks the owner after the download body is complete', async () => {
+ const owner = { value: 'owner-a', pending: false };
+ const responseBody = new Response(MP4_BYTES).body;
+ const fetchMock = vi.fn(async () => {
+ const response = {
+ ok: true,
+ status: 200,
+ body: responseBody,
+ headers: {
+ get(name: string) {
+ if (name.toLowerCase() === 'content-type') {
+ owner.value = 'owner-b';
+ return 'video/mp4';
+ }
+ return null;
+ },
+ },
+ };
+ return response as unknown as Response;
+ }) as unknown as typeof fetch;
+ const provider = makeProvider({ fetchImplementation: fetchMock, owner });
+ const videoUrl =
+ 'xai-video://content/task?owner=owner-a&credential=1&source=https%3A%2F%2Fvidgen.x.ai%2Ftask.mp4';
+
+ await expect(provider.download(videoUrl)).rejects.toThrow(/账号已切换/);
+ });
+
+ it('rejects when the credential changes during the download stream', async () => {
+ const credential = { value: 1 };
+ const body = new ReadableStream<Uint8Array>({
+ pull(controller) {
+ credential.value = 2;
+ controller.enqueue(MP4_BYTES);
+ controller.close();
+ },
+ });
+ const fetchMock = vi.fn(async () =>
+ new Response(body, { status: 200, headers: { 'content-type': 'video/mp4' } }),
+ ) as unknown as typeof fetch;
+ const provider = makeProvider({ fetchImplementation: fetchMock, credential });
+ const videoUrl =
+ 'xai-video://content/task?owner=owner-a&credential=1&source=https%3A%2F%2Fvidgen.x.ai%2Ftask.mp4';
+
+ await expect(provider.download(videoUrl)).rejects.toThrow(/SuperGrok 凭证已切换/);
+ });
+
+ it('rechecks the credential after download bytes are verified', async () => {
+ const credential = { value: 1 };
+ const responseBody = new Response(MP4_BYTES).body;
+ const fetchMock = vi.fn(async () => {
+ const response = {
+ ok: true,
+ status: 200,
+ body: responseBody,
+ headers: {
+ get(name: string) {
+ if (name.toLowerCase() === 'content-type') {
+ credential.value = 2;
+ return 'video/mp4';
+ }
+ return null;
+ },
+ },
+ };
+ return response as unknown as Response;
+ }) as unknown as typeof fetch;
+ const provider = makeProvider({ fetchImplementation: fetchMock, credential });
+ const videoUrl =
+ 'xai-video://content/task?owner=owner-a&credential=1&source=https%3A%2F%2Fvidgen.x.ai%2Ftask.mp4';
+
+ await expect(provider.download(videoUrl)).rejects.toThrow(/SuperGrok 凭证已切换/);
+ });
+
+ it('rejects oversized video content before materializing it', async () => {
+ const fetchMock = vi.fn(async (url: string) => {
+ if (url.endsWith('/generations')) {
+ return new Response(JSON.stringify({ request_id: 'video-big' }), { status: 200 });
+ }
+ if (url.endsWith('/video-big')) {
+ return new Response(
+ JSON.stringify({ status: 'done', video: { url: 'https://vidgen.x.ai/video-big.mp4' } }),
+ { status: 200 },
+ );
+ }
+ return new Response(Buffer.from('12345'), {
+ status: 200,
+ headers: { 'content-length': '5', 'content-type': 'video/mp4' },
+ });
+ }) as unknown as typeof fetch;
+ const provider = makeProvider({ fetchImplementation: fetchMock, maxVideoDownloadBytes: 4 });
+ const handle = await provider.submit({ prompt: 'big' }, XAI_VIDEO_CATALOG_MODEL_ID);
+ const status = await provider.poll(handle);
+ if (status.state !== 'succeeded') throw new Error('expected succeeded');
+
+ await expect(provider.download(status.videoUrl)).rejects.toThrow(/超过大小上限/);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-proxy-media/video/providers/xai.ts b/apps/desktop/src/main/cindy-proxy-media/video/providers/xai.ts
new file mode 100644
index 0000000000..d7dfebc60d
--- /dev/null
+++ b/apps/desktop/src/main/cindy-proxy-media/video/providers/xai.ts
@@ -0,0 +1,537 @@
+/**
+ * xAI Grok Imagine video provider backed by the existing SuperGrok OAuth login.
+ *
+ * The shared video runner owns parameter validation and polling cadence. This
+ * adapter translates Cindy's normalized request into xAI's async video API and
+ * keeps the originating account scope attached to the opaque in-memory handle,
+ * so an account switch cannot continue or download another owner's task.
+ */
+
+import { Buffer } from 'node:buffer';
+
+import type {
+ VideoGenerationRequest,
+ VideoProvider,
+ VideoProviderCapabilities,
+ VideoTaskHandle,
+ VideoTaskStatus,
+} from '../types.js';
+import { sniffMediaMime } from '../../../cindy-media/sniffMediaMime.js';
+
+const XAI_API_BASE = 'https://api.x.ai/v1';
+export const XAI_VIDEO_CATALOG_MODEL_ID = 'xai/grok-imagine-video';
+const INTERNAL_CONTENT_PROTOCOL = 'xai-video:';
+const INTERNAL_CONTENT_HOST = 'content';
+const MAX_VIDEO_DOWNLOAD_BYTES = 256 * 1024 * 1024;
+const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
+
+const SUPPORTED_DURATIONS = Array.from({ length: 15 }, (_, index) => index + 1);
+
+const BASE_CAPABILITIES: Omit<
+ VideoProviderCapabilities,
+ 'modelAliases' | 'expectedSecondsByAlias'
+> = {
+ supportedDurations: SUPPORTED_DURATIONS,
+ supportedResolutions: ['480p', '720p', '1080p'],
+ // xAI 还支持 3:2 / 2:3,但当前插件视频协议没有这两个枚举,不能公布
+ // 一个调用方永远传不进来的值。
+ supportedRatios: ['16:9', '9:16', '1:1', '4:3', '3:4'],
+ // xAI API 没有 fps 入参;24 只用于现有统一能力面与结果回执。
+ supportedFps: [24],
+ maxImagesByRefMode: {
+ // xAI image-to-video 接收一张起始图,不支持现有协议里的尾帧语义。
+ first_and_last_frame: 1,
+ },
+ // Imagine 会生成同步音频,但当前 API 没有开关。显式传 audio 时应早拒,
+ // 不能让调用方以为自己控制了静音或出声。
+ supportsAudio: false,
+ audioDefault: true,
+ defaults: {
+ duration: 6,
+ resolution: '720p',
+ ratio: '16:9',
+ fps: 24,
+ },
+};
+
+interface XaiVideoErrorBody {
+ error?: { message?: string };
+ message?: string;
+}
+
+interface XaiVideoSubmitResponse extends XaiVideoErrorBody {
+ request_id?: string;
+}
+
+interface XaiVideoStatusResponse extends XaiVideoErrorBody {
+ status?: 'pending' | 'done' | 'expired' | 'failed';
+ model?: string;
+ video?: {
+ url?: string;
+ duration?: number;
+ aspect_ratio?: string;
+ resolution?: string;
+ fps?: number;
+ };
+}
+
+export interface CreateXaiVideoProviderOptions {
+ hasOAuthLogin(): boolean;
+ getAccessToken(): Promise<string>;
+ getCredentialGeneration(): number;
+ getOwnerScopeKey(): string;
+ isOwnerBoundaryPending(): boolean;
+ fetchImplementation?: typeof fetch;
+ /** 测试可收紧上限,但不能放宽生产硬顶。 */
+ maxVideoDownloadBytes?: number;
+ beforeDispatch?(model: string): void;
+ /** 当前 active catalog 里经类型发现/静态兜底确认可执行的 xAI alias。 */
+ modelAliases?: readonly string[];
+ onAuthRejected?(failure: {
+ status: number;
+ body: string;
+ failedAccessToken: string;
+ }): Promise<unknown>;
+}
+
+function parseJson<T>(text: string, phase: string): T {
+ try {
+ return JSON.parse(text) as T;
+ } catch {
+ throw new Error(`xAI 视频${phase}返回了无效响应`);
+ }
+}
+
+function errorDetail(text: string): string {
+ try {
+ const parsed = JSON.parse(text) as XaiVideoErrorBody;
+ return parsed.error?.message ?? parsed.message ?? text.slice(0, 500) ?? '未知错误';
+ } catch {
+ return text.slice(0, 500) || '未知错误';
+ }
+}
+
+function captureOwnerScope(opts: CreateXaiVideoProviderOptions): string {
+ if (opts.isOwnerBoundaryPending()) {
+ throw new Error('xAI 视频请求期间账号正在切换,请稍后重试');
+ }
+ return opts.getOwnerScopeKey();
+}
+
+function assertOwnerScopeCurrent(
+ opts: CreateXaiVideoProviderOptions,
+ expected: string,
+): void {
+ if (opts.isOwnerBoundaryPending() || opts.getOwnerScopeKey() !== expected) {
+ throw new Error('xAI 视频请求期间账号已切换,请重试');
+ }
+}
+
+function assertCredentialGenerationCurrent(
+ opts: CreateXaiVideoProviderOptions,
+ expected: number,
+): void {
+ if (opts.getCredentialGeneration() !== expected) {
+ throw new Error('xAI 视频请求期间 SuperGrok 凭证已切换,请重试');
+ }
+}
+
+function assertRequestScopeCurrent(
+ opts: CreateXaiVideoProviderOptions,
+ ownerScopeKey: string,
+ credentialGeneration: number,
+): void {
+ assertOwnerScopeCurrent(opts, ownerScopeKey);
+ assertCredentialGenerationCurrent(opts, credentialGeneration);
+}
+
+async function notifyAuthRejected(
+ opts: CreateXaiVideoProviderOptions,
+ response: Response,
+ body: string,
+ failedAccessToken: string,
+): Promise<unknown> {
+ if ((response.status !== 401 && response.status !== 403) || !opts.onAuthRejected) {
+ return undefined;
+ }
+ return await opts
+ .onAuthRejected({
+ status: response.status,
+ body: body.slice(0, 8 * 1024),
+ failedAccessToken,
+ })
+ .catch(() => undefined);
+}
+
+function assertXaiVideoUrl(raw: string): string {
+ let url: URL;
+ try {
+ url = new URL(raw);
+ } catch {
+ throw new Error('xAI 视频任务返回了不可信的下载地址');
+ }
+ if (
+ url.protocol !== 'https:' ||
+ url.username ||
+ url.password ||
+ !(url.hostname === 'x.ai' || url.hostname.endsWith('.x.ai'))
+ ) {
+ throw new Error('xAI 视频任务返回了不可信的下载地址');
+ }
+ return url.toString();
+}
+
+async function fetchXaiVideoDownload(
+ doFetch: typeof fetch,
+ sourceUrl: string,
+ signal: AbortSignal | undefined,
+ assertStillCurrent: () => void,
+): Promise<Response> {
+ assertStillCurrent();
+ const response = await doFetch(sourceUrl, { method: 'GET', redirect: 'manual', signal });
+ assertStillCurrent();
+ if (!REDIRECT_STATUSES.has(response.status)) return response;
+
+ const location = response.headers.get('location');
+ await response.body?.cancel().catch(() => undefined);
+ assertStillCurrent();
+ if (!location) throw new Error('xAI 视频下载重定向缺少 Location');
+ const redirectUrl = assertXaiVideoUrl(new URL(location, sourceUrl).toString());
+ const redirected = await doFetch(redirectUrl, { method: 'GET', redirect: 'manual', signal });
+ assertStillCurrent();
+ return redirected;
+}
+
+function internalContentRef(
+ taskId: string,
+ ownerScopeKey: string,
+ credentialGeneration: number,
+ sourceUrl: string,
+): string {
+ const url = new URL(`${INTERNAL_CONTENT_PROTOCOL}//${INTERNAL_CONTENT_HOST}`);
+ url.pathname = `/${encodeURIComponent(taskId)}`;
+ url.searchParams.set('owner', ownerScopeKey);
+ url.searchParams.set('credential', String(credentialGeneration));
+ url.searchParams.set('source', assertXaiVideoUrl(sourceUrl));
+ return url.toString();
+}
+
+function parseInternalContentRef(raw: string): {
+ taskId: string;
+ ownerScopeKey: string;
+ credentialGeneration: number;
+ sourceUrl: string;
+} {
+ let url: URL;
+ try {
+ url = new URL(raw);
+ } catch {
+ throw new Error('xAI 视频下载引用无效');
+ }
+ if (
+ url.protocol !== INTERNAL_CONTENT_PROTOCOL ||
+ url.hostname !== INTERNAL_CONTENT_HOST ||
+ url.username ||
+ url.password ||
+ url.hash
+ ) {
+ throw new Error('xAI 视频下载引用无效');
+ }
+ const encodedTaskId = url.pathname.slice(1);
+ const ownerScopeKey = url.searchParams.get('owner');
+ const credentialGenerationRaw = url.searchParams.get('credential');
+ const sourceUrl = url.searchParams.get('source');
+ const credentialGeneration = Number(credentialGenerationRaw);
+ if (
+ !encodedTaskId ||
+ !ownerScopeKey ||
+ credentialGenerationRaw === null ||
+ !Number.isSafeInteger(credentialGeneration) ||
+ credentialGeneration < 0 ||
+ !sourceUrl ||
+ [...url.searchParams.keys()].some(
+ (key) => key !== 'owner' && key !== 'credential' && key !== 'source',
+ )
+ ) {
+ throw new Error('xAI 视频下载引用无效');
+ }
+ let taskId: string;
+ try {
+ taskId = decodeURIComponent(encodedTaskId);
+ } catch {
+ throw new Error('xAI 视频下载引用无效');
+ }
+ if (!taskId) throw new Error('xAI 视频下载引用无效');
+ return {
+ taskId,
+ ownerScopeKey,
+ credentialGeneration,
+ sourceUrl: assertXaiVideoUrl(sourceUrl),
+ };
+}
+
+async function readBoundedVideo(
+ response: Response,
+ maxBytes: number,
+ assertStillCurrent: () => void,
+): Promise<Buffer> {
+ const declared = Number(response.headers.get('content-length') ?? Number.NaN);
+ if (Number.isFinite(declared) && declared > maxBytes) {
+ await response.body?.cancel().catch(() => undefined);
+ throw new Error(`xAI 视频下载超过大小上限(${maxBytes} 字节)`);
+ }
+ const body = response.body;
+ if (!body) return Buffer.alloc(0);
+ const reader = body.getReader();
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ try {
+ for (;;) {
+ const { done, value } = await reader.read();
+ assertStillCurrent();
+ if (done) break;
+ if (!value || value.byteLength === 0) continue;
+ total += value.byteLength;
+ if (total > maxBytes) {
+ throw new Error(`xAI 视频下载超过大小上限(${maxBytes} 字节)`);
+ }
+ chunks.push(value);
+ }
+ } finally {
+ await reader.cancel().catch(() => undefined);
+ reader.releaseLock();
+ }
+ return Buffer.concat(chunks, total);
+}
+
+export function createXaiVideoProvider(opts: CreateXaiVideoProviderOptions): VideoProvider {
+ const doFetch = opts.fetchImplementation ?? fetch;
+ const requestedLimit = opts.maxVideoDownloadBytes;
+ const maxVideoDownloadBytes =
+ typeof requestedLimit === 'number' &&
+ Number.isSafeInteger(requestedLimit) &&
+ requestedLimit > 0
+ ? Math.min(requestedLimit, MAX_VIDEO_DOWNLOAD_BYTES)
+ : MAX_VIDEO_DOWNLOAD_BYTES;
+ const aliases = [...new Set(opts.modelAliases ?? [XAI_VIDEO_CATALOG_MODEL_ID])];
+ const upstreamByAlias = new Map<string, string>();
+ for (const alias of aliases) {
+ if (!alias.startsWith('xai/') || alias.length <= 'xai/'.length) {
+ throw new Error(`xAI 视频模型 alias 无效: ${alias}`);
+ }
+ upstreamByAlias.set(alias, alias.slice('xai/'.length));
+ }
+ const expectedSecondsByAlias = Object.fromEntries(aliases.map((alias) => [alias, 180]));
+ const capabilities: VideoProviderCapabilities = {
+ ...BASE_CAPABILITIES,
+ modelAliases: aliases.map((alias) => ({
+ alias,
+ internalModel: upstreamByAlias.get(alias)!,
+ summary: 'Grok Imagine Video(最长 15 秒,支持单图生视频)',
+ })),
+ expectedSecondsByAlias,
+ };
+
+ async function authorizedJson<T>(
+ url: string,
+ phase: string,
+ ownerScopeKey: string,
+ credentialGeneration: number,
+ init: RequestInit,
+ options?: { retryAfterAuthRefresh?: boolean },
+ ): Promise<T> {
+ const retryAfterAuthRefresh = options?.retryAfterAuthRefresh === true;
+ const maxAttempts = retryAfterAuthRefresh ? 2 : 1;
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
+ assertRequestScopeCurrent(opts, ownerScopeKey, credentialGeneration);
+ const token = await opts.getAccessToken();
+ assertRequestScopeCurrent(opts, ownerScopeKey, credentialGeneration);
+ const response = await doFetch(url, {
+ ...init,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ Accept: 'application/json',
+ ...(init.headers ?? {}),
+ },
+ });
+ const text = await response.text();
+ assertRequestScopeCurrent(opts, ownerScopeKey, credentialGeneration);
+ if (response.ok) return parseJson<T>(text, phase);
+
+ // 只让第一次失败进入恢复器。轮询可在凭证刷新成功后补发一次同一个 GET;
+ // 第二次仍失败就如实抛出,不能形成内部重试环。submit 不打开此选项,
+ // 因而绝不会因认证恢复重复创建付费任务。
+ const recovery =
+ attempt === 0 ? await notifyAuthRejected(opts, response, text, token) : undefined;
+ // superseded 可能是同一登录的 token 已被并发请求先一步刷新;下面这道
+ // owner + credential generation 复核会先排除登出、换号与数据 owner 切换。
+ assertRequestScopeCurrent(opts, ownerScopeKey, credentialGeneration);
+ if (
+ retryAfterAuthRefresh &&
+ attempt === 0 &&
+ (recovery === 'refreshed' || recovery === 'superseded')
+ ) {
+ continue;
+ }
+ throw new Error(`xAI 视频${phase}失败(HTTP ${response.status}):${errorDetail(text)}`);
+ }
+ throw new Error(`xAI 视频${phase}失败:认证恢复重试耗尽`);
+ }
+
+ async function submit(
+ req: VideoGenerationRequest,
+ alias: string,
+ signal?: AbortSignal,
+ ): Promise<VideoTaskHandle> {
+ const upstreamModelId = upstreamByAlias.get(alias);
+ if (!upstreamModelId) {
+ throw new Error(`xAI 视频通道不认识模型 '${alias}'`);
+ }
+ if (!opts.hasOAuthLogin()) {
+ throw new Error('xAI 视频能力不可用:请先在设置中连接 SuperGrok');
+ }
+ opts.beforeDispatch?.(alias);
+ const ownerScopeKey = captureOwnerScope(opts);
+ const credentialGeneration = opts.getCredentialGeneration();
+ assertRequestScopeCurrent(opts, ownerScopeKey, credentialGeneration);
+ const images = req.images ?? [];
+ const body: Record<string, unknown> = {
+ model: upstreamModelId,
+ prompt: req.prompt,
+ duration: req.duration,
+ resolution: req.resolution,
+ };
+ if (images[0]) {
+ body.image = { url: images[0] };
+ // xAI preserves the source image's aspect ratio when this field is
+ // omitted. Do not turn Cindy's receipt/default value into a destructive
+ // 16:9 override unless the user actually selected a ratio.
+ if (req.ratioWasExplicit !== false) body.aspect_ratio = req.ratio;
+ } else {
+ body.aspect_ratio = req.ratio;
+ }
+ opts.beforeDispatch?.(alias);
+ const response = await authorizedJson<XaiVideoSubmitResponse>(
+ `${XAI_API_BASE}/videos/generations`,
+ '提交',
+ ownerScopeKey,
+ credentialGeneration,
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ signal,
+ },
+ );
+ if (!response.request_id) {
+ throw new Error('xAI 视频提交响应缺少 request_id');
+ }
+ assertRequestScopeCurrent(opts, ownerScopeKey, credentialGeneration);
+ return {
+ providerId: 'xai-video',
+ taskId: response.request_id,
+ modelUsed: upstreamModelId,
+ submittedAt: Date.now(),
+ ownerScopeKey,
+ credentialGeneration,
+ };
+ }
+
+ async function poll(
+ handle: VideoTaskHandle,
+ signal?: AbortSignal,
+ ): Promise<VideoTaskStatus> {
+ if (
+ handle.providerId !== 'xai-video' ||
+ !handle.ownerScopeKey ||
+ !Number.isSafeInteger(handle.credentialGeneration) ||
+ handle.credentialGeneration! < 0
+ ) {
+ return { state: 'failed', error: 'xAI 视频任务句柄无效' };
+ }
+ const credentialGeneration = handle.credentialGeneration!;
+ const data = await authorizedJson<XaiVideoStatusResponse>(
+ `${XAI_API_BASE}/videos/${encodeURIComponent(handle.taskId)}`,
+ '查询',
+ handle.ownerScopeKey,
+ credentialGeneration,
+ { method: 'GET', signal },
+ { retryAfterAuthRefresh: true },
+ );
+ if (data.status === 'pending' || data.status === undefined) {
+ return { state: data.status === 'pending' ? 'pending' : 'running', raw: data };
+ }
+ if (data.status === 'expired' || data.status === 'failed') {
+ return {
+ state: 'failed',
+ error: data.error?.message ?? `xAI 视频任务状态为 ${data.status}`,
+ raw: data,
+ };
+ }
+ if (data.status !== 'done') return { state: 'running', raw: data };
+ if (!data.video?.url) {
+ return { state: 'failed', error: 'xAI 视频任务完成但未返回 video.url', raw: data };
+ }
+ assertRequestScopeCurrent(opts, handle.ownerScopeKey, credentialGeneration);
+ return {
+ state: 'succeeded',
+ // 下载只接受本 provider 生成的内部引用,避免把上游自报 URL 变成任意出网入口。
+ videoUrl: internalContentRef(
+ handle.taskId,
+ handle.ownerScopeKey,
+ credentialGeneration,
+ data.video.url,
+ ),
+ meta: {
+ durationSec: data.video?.duration,
+ resolution: data.video?.resolution,
+ ratio: data.video?.aspect_ratio,
+ fps: data.video?.fps,
+ },
+ raw: data,
+ };
+ }
+
+ async function download(
+ videoUrl: string,
+ signal?: AbortSignal,
+ ): Promise<{ buffer: Buffer; mimeType: string }> {
+ const { ownerScopeKey, credentialGeneration, sourceUrl } = parseInternalContentRef(videoUrl);
+ const assertStillCurrent = () =>
+ assertRequestScopeCurrent(opts, ownerScopeKey, credentialGeneration);
+ assertStillCurrent();
+ // 完成态给的是 xAI 临时托管 URL。下载及至多一跳重定向都必须重新验证
+ // 为可信 *.x.ai 目标;手动跟随确保任何不可信 Location 都会 fail closed。
+ const response = await fetchXaiVideoDownload(doFetch, sourceUrl, signal, assertStillCurrent);
+ assertStillCurrent();
+ if (!response.ok) {
+ const text = await response.text();
+ assertStillCurrent();
+ throw new Error(`xAI 视频下载失败(HTTP ${response.status}):${errorDetail(text)}`);
+ }
+ const buffer = await readBoundedVideo(
+ response,
+ maxVideoDownloadBytes,
+ assertStillCurrent,
+ );
+ if (buffer.byteLength === 0) throw new Error('xAI 视频下载结果为空');
+ const declaredMime =
+ response.headers.get('content-type')?.split(';')[0].trim().toLowerCase() ?? '';
+ const mimeType = sniffMediaMime(buffer, declaredMime);
+ if (!mimeType?.startsWith('video/')) {
+ throw new Error('xAI 视频下载结果不是受支持的视频');
+ }
+ // 流读取中的逐块检查覆盖下载过程;这里再封住最后一个分块读完到结果交给
+ // cindy-media 之间的同步窗口,旧账号产物绝不跨 owner 边界返回。
+ assertStillCurrent();
+ return { buffer, mimeType };
+ }
+
+ return {
+ id: 'xai-video',
+ capabilities,
+ submit,
+ poll,
+ download,
+ };
+}
diff --git a/apps/desktop/src/main/cindy-proxy-media/video/registry.ts b/apps/desktop/src/main/cindy-proxy-media/video/registry.ts
index 13d27ed59a..277e4e3373 100644
--- a/apps/desktop/src/main/cindy-proxy-media/video/registry.ts
+++ b/apps/desktop/src/main/cindy-proxy-media/video/registry.ts
@@ -44,12 +44,47 @@ export class VideoProviderRegistry {
this.providers.set(provider.id, provider);
}
+ /**
+ * 用同一 provider 的新能力快照补充/更新 alias。旧 alias 索引不删除:目录热更
+ * 期间已经提交的长视频任务仍要能继续 poll/download;新请求是否可用由当前目录
+ * 白名单在提交前重查。其它 provider 已占用的 alias 仍严格拒绝。
+ */
+ registerOrExtend(provider: VideoProvider): void {
+ const existing = this.providers.get(provider.id);
+ if (!existing) {
+ this.register(provider);
+ return;
+ }
+ for (const alias of provider.capabilities.modelAliases) {
+ const occupied = this.aliasIndex.get(alias.alias);
+ if (occupied && occupied.provider.id !== provider.id) {
+ throw new Error(
+ `[videoRegistry] duplicate alias: ${alias.alias} (already registered by ${occupied.provider.id})`,
+ );
+ }
+ }
+ for (const alias of provider.capabilities.modelAliases) {
+ this.aliasIndex.set(alias.alias, {
+ provider,
+ internalModel: alias.internalModel,
+ summary: alias.summary,
+ expectedSeconds: provider.capabilities.expectedSecondsByAlias[alias.alias] ?? 120,
+ });
+ }
+ this.providers.set(provider.id, provider);
+ }
+
/** True if at least one provider is registered. Tools should be omitted
* from the catalog when this is false (no models = no callable tools). */
hasAny(): boolean {
return this.aliasIndex.size > 0;
}
+ /** 目录热更可能先于客户端通道代码;未知 alias 必须从可选清单中过滤。 */
+ hasAlias(alias: string): boolean {
+ return this.aliasIndex.has(alias);
+ }
+
/** Throws on unknown alias — handler converts that to INVALID_ARGS. */
resolveByAlias(alias: string): ResolvedAlias {
const r = this.aliasIndex.get(alias);
diff --git a/apps/desktop/src/main/cindy-proxy-media/video/run.ts b/apps/desktop/src/main/cindy-proxy-media/video/run.ts
index e31abc82c7..757af60aeb 100644
--- a/apps/desktop/src/main/cindy-proxy-media/video/run.ts
+++ b/apps/desktop/src/main/cindy-proxy-media/video/run.ts
@@ -187,11 +187,11 @@ export async function submitAndAwaitVideo(
* 默认(没登记就说不上来)。**刻意不放进 `submitted`**——那个对象会整体摊进
* 请求体,推定值一旦漏进去就等于替插件表了态,存量产出的兼容也就破了。
*/
- const effectiveAudio =
- params.audio ?? (caps.supportsAudio ? caps.audioDefault : undefined);
+ const effectiveAudio = params.audio ?? caps.audioDefault;
const req: VideoGenerationRequest = {
prompt: params.prompt,
...submitted,
+ ratioWasExplicit: params.ratio !== undefined,
// 三态:只有插件显式表态才写这个键,否则请求体里连键都没有。
...(params.audio !== undefined ? { audio: params.audio } : {}),
images: images.length > 0 ? images : undefined,
diff --git a/apps/desktop/src/main/cindy-proxy-media/video/types.ts b/apps/desktop/src/main/cindy-proxy-media/video/types.ts
index 82da523237..4645553cde 100644
--- a/apps/desktop/src/main/cindy-proxy-media/video/types.ts
+++ b/apps/desktop/src/main/cindy-proxy-media/video/types.ts
@@ -51,6 +51,13 @@ export interface VideoGenerationRequest {
resolution?: string;
/** 'W:H' aspect ratio string. Provider declares supported set. */
ratio?: string;
+ /**
+ * Whether the caller explicitly selected `ratio`. The shared runner still
+ * resolves a concrete ratio for receipts/default-capable providers, while
+ * image-to-video adapters may omit an implicit default so the source image
+ * keeps its native aspect ratio.
+ */
+ ratioWasExplicit?: boolean;
/** Frames per second. Provider declares supported set. */
fps?: number;
/**
@@ -81,6 +88,17 @@ export interface VideoTaskHandle {
modelUsed: string;
/** ms since epoch when submit completed. */
submittedAt: number;
+ /**
+ * Optional non-secret owner scope captured at submit time. Account-backed
+ * providers use it to reject poll/download after the active account changes.
+ */
+ ownerScopeKey?: string;
+ /**
+ * Optional provider-owned credential generation captured at submit time.
+ * Long-running account-backed providers use it in addition to ownerScopeKey
+ * so logout/relogin within the same app session invalidates the old task.
+ */
+ credentialGeneration?: number;
}
export interface VideoResultMeta {
@@ -145,7 +163,8 @@ export interface VideoProviderCapabilities {
*/
supportsAudio: boolean;
/**
- * 不传 `audio` 时上游自己的音轨默认(仅 `supportsAudio` 为 true 时有意义)。
+ * 不传 `audio` 时上游自己的音轨默认。即使没有音频开关也可登记真实默认,
+ * 让回执表达“固定有声/无声”,而不是把“不可切换”误写成“说不上来”。
* **只用于回执**,不参与请求组装——请求侧缺省必须保持"一个字段都不写"。
* 例:Seedance 2.0 的 `generate_audio` 默认 true(原生音画同生),所以
* 不传音频开关的单子本来就是有声的,回执要如实这么报。
diff --git a/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts b/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
index a1f5e9429c..402d4872f5 100644
--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
@@ -22,6 +22,7 @@ import {
setActiveCatalog,
setAnthropicDiscoveredModels,
setDiscoveredCodexModels,
+ setDiscoveredProviderMediaModels,
} from '../active-catalog.js';
function openaiIds(agent: 'claude-code' | 'codex' | 'pi'): string[] {
@@ -89,6 +90,7 @@ describe('active-catalog discovered augment', () => {
// 复位全局状态,避免测试间串扰
setActiveCatalog(BUNDLED_CATALOG);
setDiscoveredCodexModels([]);
+ setDiscoveredProviderMediaModels('xai', null);
});
it('新 discovered id 同时进入 openai.codex 与 Claude/Pi bridge', () => {
@@ -107,6 +109,69 @@ describe('active-catalog discovered augment', () => {
expect(xai?.models.pi).toEqual(xai?.models['claude-code']);
});
+ it('xAI 媒体发现按官方存在性收敛,静态同 id 保持 first-wins', () => {
+ setActiveCatalog(BUNDLED_CATALOG);
+ setDiscoveredProviderMediaModels('xai', {
+ imageModels: [
+ { id: 'xai/grok-imagine-image', name: 'Remote Rename Must Not Win' },
+ { id: 'xai/future-image', name: 'Future Image' },
+ ],
+ videoModels: [{ id: 'xai/future-video', name: 'Future Video' }],
+ });
+ const xai = getActiveCatalog().providers.find((provider) => provider.id === 'xai');
+ expect(xai?.imageModels).toContainEqual({
+ id: 'xai/grok-imagine-image',
+ name: 'Grok Imagine Image',
+ });
+ expect(xai?.imageModels).toContainEqual({ id: 'xai/future-image', name: 'Future Image' });
+ expect(xai?.videoModels).toContainEqual({ id: 'xai/future-video', name: 'Future Video' });
+ expect(xai?.imageModels?.some((model) => model.id === 'xai/grok-imagine-image-quality')).toBe(
+ false,
+ );
+ expect(xai?.videoModels?.some((model) => model.id === 'xai/grok-imagine-video')).toBe(false);
+ });
+
+ it('xAI 媒体发现不复活远端显式空清单', () => {
+ const catalog = bundledWithoutRegistry();
+ const xai = catalog.providers.find((provider) => provider.id === 'xai');
+ if (!xai) throw new Error('fixture missing xai');
+ xai.imageModels = [];
+ xai.videoModels = [];
+ setActiveCatalog(catalog);
+ setDiscoveredProviderMediaModels('xai', {
+ imageModels: [{ id: 'xai/future-image', name: 'Future Image' }],
+ videoModels: [{ id: 'xai/future-video', name: 'Future Video' }],
+ });
+ const active = getActiveCatalog().providers.find((provider) => provider.id === 'xai');
+ expect(active?.imageModels).toEqual([]);
+ expect(active?.videoModels).toEqual([]);
+ });
+
+ it('xAI 媒体分类型更新时保留另一类上次成功快照', () => {
+ setActiveCatalog(BUNDLED_CATALOG);
+ setDiscoveredProviderMediaModels('xai', {
+ imageModels: [{ id: 'xai/first-image', name: 'First Image' }],
+ videoModels: [{ id: 'xai/first-video', name: 'First Video' }],
+ });
+ setDiscoveredProviderMediaModels('xai', {
+ videoModels: [{ id: 'xai/second-video', name: 'Second Video' }],
+ });
+ const xai = getActiveCatalog().providers.find((provider) => provider.id === 'xai');
+ expect(xai?.imageModels).toEqual([{ id: 'xai/first-image', name: 'First Image' }]);
+ expect(xai?.videoModels).toEqual([{ id: 'xai/second-video', name: 'Second Video' }]);
+ });
+
+ it('xAI 官方成功返回空清单时清掉该类旧型号', () => {
+ setActiveCatalog(BUNDLED_CATALOG);
+ setDiscoveredProviderMediaModels('xai', {
+ imageModels: [],
+ videoModels: [],
+ });
+ const xai = getActiveCatalog().providers.find((provider) => provider.id === 'xai');
+ expect(xai?.imageModels).toEqual([]);
+ expect(xai?.videoModels).toEqual([]);
+ });
+
it('bridge 投影剔除 max/ultra:codex 侧保留、claude-code 侧封顶 xhigh(issue #352)', () => {
setActiveCatalog(bundledWithoutRegistry());
setDiscoveredCodexModels([
diff --git a/apps/desktop/src/main/maker-host/__tests__/grokAuthRejectionRecovery.test.ts b/apps/desktop/src/main/maker-host/__tests__/grokAuthRejectionRecovery.test.ts
index 32ab813f3d..24fbf650ca 100644
--- a/apps/desktop/src/main/maker-host/__tests__/grokAuthRejectionRecovery.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/grokAuthRejectionRecovery.test.ts
@@ -51,6 +51,7 @@ vi.mock('../outbound-fetch.js', () => ({
}));
import {
+ getGrokOAuthCredentialGeneration,
logoutGrok,
recoverGrokAuthAfterRejection,
resetGrokOAuthMemoryCache,
@@ -100,8 +101,22 @@ afterEach(() => {
});
describe('recoverGrokAuthAfterRejection', () => {
+ it('凭证边界代际单调推进,重复清理或登出不会复活旧任务', () => {
+ const initial = getGrokOAuthCredentialGeneration();
+ resetGrokOAuthMemoryCache();
+ const afterReset = getGrokOAuthCredentialGeneration();
+ logoutGrok();
+ const afterLogout = getGrokOAuthCredentialGeneration();
+ logoutGrok();
+
+ expect(afterReset).toBeGreaterThan(initial);
+ expect(afterLogout).toBeGreaterThan(afterReset);
+ expect(getGrokOAuthCredentialGeneration()).toBeGreaterThan(afterLogout);
+ });
+
it('刷新成功即自愈,凭证换成新 token 且不登出', async () => {
seedCredentials();
+ const generation = getGrokOAuthCredentialGeneration();
vi.stubGlobal(
'fetch',
vi.fn(async () =>
@@ -115,6 +130,7 @@ describe('recoverGrokAuthAfterRejection', () => {
await expect(recoverGrokAuthAfterRejection(REJECTED_TOKEN)).resolves.toBe('refreshed');
expect(readStored()?.access_token).toBe('fresh-access-token');
+ expect(getGrokOAuthCredentialGeneration()).toBe(generation);
});
it('refresh_token 被服务端作废时清空凭证', async () => {
diff --git a/apps/desktop/src/main/maker-host/__tests__/nativeProviderConnectionClaim.test.ts b/apps/desktop/src/main/maker-host/__tests__/nativeProviderConnectionClaim.test.ts
index bf603a0442..a131feac58 100644
--- a/apps/desktop/src/main/maker-host/__tests__/nativeProviderConnectionClaim.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/nativeProviderConnectionClaim.test.ts
@@ -21,6 +21,7 @@ const h = vi.hoisted(() => ({
claudeCredentialPresent: true,
grokCredentialPresent: true,
refreshAnthropicModels: vi.fn(),
+ refreshXaiMediaModels: vi.fn(async () => true),
loadAnthropicDiskCache: vi.fn(async () => {}),
codexLoginWithSideEffects: vi.fn(async () => false),
codexLoginReadOnly: vi.fn(() => false),
@@ -67,6 +68,10 @@ vi.mock('../model-discovery/anthropic.js', () => ({
refreshAnthropicModelsFromHttp: h.refreshAnthropicModels,
getAnthropicModelDiscoveryFailure: () => h.anthropicDiscoveryFailure,
}));
+vi.mock('../model-discovery/xai-media.js', () => ({
+ refreshXaiMediaModels: h.refreshXaiMediaModels,
+ clearXaiMediaModels: vi.fn(),
+}));
vi.mock('../active-catalog.js', async () => {
const actual =
@@ -131,6 +136,7 @@ beforeEach(() => {
h.grokCredentialPresent = true;
h.anthropicDiscoveryFailure = null;
h.refreshAnthropicModels.mockClear();
+ h.refreshXaiMediaModels.mockClear();
h.loadAnthropicDiskCache.mockClear();
h.codexLoginWithSideEffects.mockClear();
h.codexLoginReadOnly.mockClear();
@@ -312,9 +318,10 @@ describe('native provider connection claim on read', () => {
expect(secondProviders.find((provider) => provider.id === 'anthropic')?.connected).toBe(true);
});
- it('认领本机 xai 凭证(清单不走动态发现,不触发拉取)', async () => {
+ it('认领本机 xai 凭证后后台补拉媒体模型', async () => {
expect((await connectedMap()).xai).toBe(true);
expect(isNativeProviderAuthBound('xai')).toBe(true);
+ expect(h.refreshXaiMediaModels).toHaveBeenCalledTimes(1);
});
it('认领成功要广播:其它窗口与 device-link 对端只认这条推送来失效快照', async () => {
diff --git a/apps/desktop/src/main/maker-host/__tests__/providerModelAutoRefresh.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerModelAutoRefresh.test.ts
index 979cdd945a..da06709cf1 100644
--- a/apps/desktop/src/main/maker-host/__tests__/providerModelAutoRefresh.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/providerModelAutoRefresh.test.ts
@@ -61,7 +61,7 @@ describe('provider model auto-refresh coordinator', () => {
expect(refreshCatalog).toHaveBeenCalledOnce();
});
- it('does not repeat the shared Catalog refresh through the connected xAI provider hook', async () => {
+ it('refreshes connected xAI media separately from the shared Catalog', async () => {
let now = 1_000;
const refreshCatalog = vi.fn(async () => undefined);
const refreshProvider = vi.fn(async () => undefined);
@@ -73,20 +73,22 @@ describe('provider model auto-refresh coordinator', () => {
log: { debug: vi.fn(), warn: vi.fn() },
});
- // Splash already loaded the public Catalog; startup must not immediately fetch it again via
- // xAI's provider-level hook.
+ // Splash already loaded the public Catalog, but account-scoped media discovery still runs.
await coordinator.requestAutoRefresh('startup');
expect(refreshCatalog).not.toHaveBeenCalled();
- expect(refreshProvider).not.toHaveBeenCalled();
+ expect(refreshProvider).toHaveBeenCalledOnce();
+ expect(refreshProvider).toHaveBeenCalledWith('xai');
now += PROVIDER_MODEL_AUTO_REFRESH_FAILURE_COOLDOWN_MS;
await coordinator.requestAutoRefresh('foreground');
expect(refreshCatalog).toHaveBeenCalledOnce();
- expect(refreshProvider).not.toHaveBeenCalled();
+ // provider 自己的上次成功快照仍在 30 分钟冷却内,不重复打 xAI 账号端点。
+ expect(refreshProvider).toHaveBeenCalledOnce();
- // An explicit manual refresh remains available and executes the provider hook once.
+ // Manual xAI refresh updates both the shared Catalog and account-scoped media snapshot.
await coordinator.refreshManually('xai');
- expect(refreshProvider).toHaveBeenCalledOnce();
+ expect(refreshCatalog).toHaveBeenCalledTimes(2);
+ expect(refreshProvider).toHaveBeenCalledTimes(2);
});
it('refreshes only connected built-ins and applies a per-provider cooldown', async () => {
diff --git a/apps/desktop/src/main/maker-host/__tests__/providerModelRefresh.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerModelRefresh.test.ts
index 3a79789515..9234abfe4a 100644
--- a/apps/desktop/src/main/maker-host/__tests__/providerModelRefresh.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/providerModelRefresh.test.ts
@@ -12,7 +12,7 @@ function deps(
refreshXd: vi.fn(async () => {}),
refreshAnthropic: vi.fn(async () => true),
refreshOpenAi: vi.fn(async () => true),
- refreshXaiCatalog: vi.fn(async () => {}),
+ refreshXaiMedia: vi.fn(async () => true),
...overrides,
};
}
@@ -22,7 +22,7 @@ describe('refreshBuiltinProviderModels', () => {
['xd', 'refreshXd'],
['anthropic', 'refreshAnthropic'],
['openai', 'refreshOpenAi'],
- ['xai', 'refreshXaiCatalog'],
+ ['xai', 'refreshXaiMedia'],
] as const)('dispatches %s to its existing refresh source', async (providerId, method) => {
const d = deps();
await refreshBuiltinProviderModels(providerId, d);
@@ -36,5 +36,8 @@ describe('refreshBuiltinProviderModels', () => {
await expect(
refreshBuiltinProviderModels('openai', deps({ refreshOpenAi: async () => false })),
).rejects.toThrow(/OpenAI model discovery/);
+ await expect(
+ refreshBuiltinProviderModels('xai', deps({ refreshXaiMedia: async () => false })),
+ ).rejects.toThrow(/xAI media model discovery/);
});
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/xaiMediaDiscovery.test.ts b/apps/desktop/src/main/maker-host/__tests__/xaiMediaDiscovery.test.ts
new file mode 100644
index 0000000000..541401a543
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/xaiMediaDiscovery.test.ts
@@ -0,0 +1,386 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ createXaiMediaDiscovery,
+ mapXaiMediaModels,
+ type XaiMediaDiscoverySnapshot,
+} from '../model-discovery/xai-media.js';
+import type { XaiBridgeAuthInvalidationResult } from '../xai-bridge-auth-invalidation.js';
+
+function payload(id: string, input: string[], output: string[]): string {
+ return JSON.stringify({
+ models: [
+ {
+ id,
+ aliases: [],
+ input_modalities: input,
+ output_modalities: output,
+ },
+ ],
+ });
+}
+
+describe('mapXaiMediaModels', () => {
+ it('classifies by modalities instead of model-name patterns', () => {
+ expect(
+ mapXaiMediaModels(
+ JSON.parse(payload('anything-the-api-adds-next', ['text', 'image'], ['video'])),
+ 'video',
+ ['text', 'image'],
+ ),
+ ).toEqual([{ id: 'xai/anything-the-api-adds-next', name: 'Anything The Api Adds Next' }]);
+ });
+
+ it('hides models whose modalities cannot satisfy the current common adapter', () => {
+ expect(
+ mapXaiMediaModels(JSON.parse(payload('image-only-video', ['image'], ['video'])), 'video', [
+ 'text',
+ 'image',
+ ]),
+ ).toEqual([]);
+ });
+});
+
+describe('xAI media discovery lifecycle', () => {
+ function harness(
+ fetchImplementation: typeof fetch,
+ onAuthRejectedImplementation?: () => Promise<XaiBridgeAuthInvalidationResult>,
+ ) {
+ const owner = { value: 'owner-a', pending: false, connected: true };
+ const auth = { token: 'oauth-token', credentialGeneration: 0 };
+ const applied: Array<XaiMediaDiscoverySnapshot | null> = [];
+ const onAuthRejected = vi.fn(async (): Promise<XaiBridgeAuthInvalidationResult> =>
+ onAuthRejectedImplementation ? await onAuthRejectedImplementation() : 'unchanged',
+ );
+ const discovery = createXaiMediaDiscovery({
+ hasOAuthLogin: () => owner.connected,
+ getAccessToken: async () => auth.token,
+ getCredentialGeneration: () => auth.credentialGeneration,
+ getOwnerScopeKey: () => owner.value,
+ isOwnerBoundaryPending: () => owner.pending,
+ fetchImplementation,
+ applySnapshot: (snapshot) => applied.push(snapshot),
+ onAuthRejected,
+ log: { info: vi.fn(), warn: vi.fn() },
+ });
+ return { discovery, owner, auth, applied, onAuthRejected };
+ }
+
+ it('atomically applies image and video snapshots from the typed endpoints', async () => {
+ const fetchMock = vi.fn(async (url: string | URL | Request) => {
+ const href = String(url);
+ return new Response(
+ href.endsWith('/image-generation-models')
+ ? payload('future-image', ['text', 'image'], ['image'])
+ : payload('future-video', ['text', 'image'], ['video']),
+ { status: 200 },
+ );
+ }) as unknown as typeof fetch;
+ const h = harness(fetchMock);
+
+ await expect(h.discovery.refresh()).resolves.toBe(true);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(h.applied).toEqual([
+ {
+ imageModels: [{ id: 'xai/future-image', name: 'Future Image' }],
+ videoModels: [{ id: 'xai/future-video', name: 'Future Video' }],
+ },
+ ]);
+ });
+
+ it('updates the successful kind while preserving the failed kind in active catalog', async () => {
+ let failVideo = false;
+ const fetchMock = vi.fn(async (url: string | URL | Request) => {
+ const href = String(url);
+ if (href.endsWith('/video-generation-models') && failVideo) {
+ return new Response('{"error":"temporary"}', { status: 503 });
+ }
+ return new Response(
+ href.endsWith('/image-generation-models')
+ ? payload('future-image', ['text', 'image'], ['image'])
+ : payload('future-video', ['text', 'image'], ['video']),
+ { status: 200 },
+ );
+ }) as unknown as typeof fetch;
+ const h = harness(fetchMock);
+ await expect(h.discovery.refresh()).resolves.toBe(true);
+ failVideo = true;
+ await expect(h.discovery.refresh()).resolves.toBe(true);
+ expect(h.applied).toHaveLength(2);
+ expect(h.applied[1]).toEqual({
+ imageModels: [{ id: 'xai/future-image', name: 'Future Image' }],
+ });
+ });
+
+ it('does not let image discovery failure block a new video model', async () => {
+ const fetchMock = vi.fn(async (url: string | URL | Request) => {
+ if (String(url).endsWith('/image-generation-models')) {
+ return new Response('{"error":"image unavailable"}', { status: 503 });
+ }
+ return new Response(payload('future-video', ['text', 'image'], ['video']), { status: 200 });
+ }) as unknown as typeof fetch;
+ const h = harness(fetchMock);
+
+ await expect(h.discovery.refresh()).resolves.toBe(true);
+ expect(h.applied).toEqual([
+ { videoModels: [{ id: 'xai/future-video', name: 'Future Video' }] },
+ ]);
+ });
+
+ it('treats a valid empty list as an authoritative successful snapshot', async () => {
+ const fetchMock = vi.fn(
+ async () => new Response('{"models":[]}', { status: 200 }),
+ ) as unknown as typeof fetch;
+ const h = harness(fetchMock);
+
+ await expect(h.discovery.refresh()).resolves.toBe(true);
+ expect(h.applied).toEqual([{ imageModels: [], videoModels: [] }]);
+ });
+
+ it('does not replace the fallback when both endpoint payloads are malformed', async () => {
+ const fetchMock = vi.fn(
+ async () => new Response('{"data":[]}', { status: 200 }),
+ ) as unknown as typeof fetch;
+ const h = harness(fetchMock);
+
+ await expect(h.discovery.refresh()).resolves.toBe(false);
+ expect(h.applied).toEqual([]);
+ });
+
+ it('rejects oversized model-list responses before reading the body', async () => {
+ const cancel = vi.fn(async () => undefined);
+ const fetchMock = vi.fn(
+ async () =>
+ ({
+ ok: true,
+ status: 200,
+ headers: new Headers({ 'content-length': String(512 * 1024 + 1) }),
+ body: { cancel },
+ }) as unknown as Response,
+ ) as unknown as typeof fetch;
+ const h = harness(fetchMock);
+
+ await expect(h.discovery.refresh()).resolves.toBe(false);
+ expect(cancel).toHaveBeenCalledTimes(2);
+ expect(h.applied).toEqual([]);
+ });
+
+ it('clears on auth boundary and discards the old account late result', async () => {
+ let resolveImage!: (response: Response) => void;
+ let resolveVideo!: (response: Response) => void;
+ const image = new Promise<Response>((resolve) => {
+ resolveImage = resolve;
+ });
+ const video = new Promise<Response>((resolve) => {
+ resolveVideo = resolve;
+ });
+ const fetchMock = vi.fn((url: string | URL | Request) =>
+ String(url).endsWith('/image-generation-models') ? image : video,
+ ) as unknown as typeof fetch;
+ const h = harness(fetchMock);
+
+ const refresh = h.discovery.refresh();
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+ h.owner.value = 'owner-b';
+ h.discovery.clear();
+ resolveImage(new Response(payload('old-image', ['text', 'image'], ['image']), { status: 200 }));
+ resolveVideo(new Response(payload('old-video', ['text', 'image'], ['video']), { status: 200 }));
+
+ await expect(refresh).resolves.toBe(false);
+ expect(h.applied).toEqual([null]);
+ });
+
+ it('forwards 401 to the shared xAI invalidator without clearing the fallback itself', async () => {
+ const fetchMock = vi.fn(
+ async () => new Response('expired', { status: 401 }),
+ ) as unknown as typeof fetch;
+ const h = harness(fetchMock);
+
+ await expect(h.discovery.refresh()).resolves.toBe(false);
+ expect(h.onAuthRejected).toHaveBeenCalledWith({
+ status: 401,
+ body: 'expired',
+ failedAccessToken: 'oauth-token',
+ });
+ expect(h.applied).toEqual([]);
+ });
+
+ it('retries both image and video list GETs once with a refreshed token', async () => {
+ const calls: Array<{ path: string; authorization: string | null }> = [];
+ const fetchMock = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
+ const path = new URL(String(url)).pathname;
+ const authorization = new Headers(init?.headers).get('authorization');
+ calls.push({ path, authorization });
+ if (authorization === 'Bearer oauth-token') {
+ return new Response('expired', { status: 401 });
+ }
+ return new Response(
+ path.endsWith('/image-generation-models')
+ ? payload('recovered-image', ['text', 'image'], ['image'])
+ : payload('recovered-video', ['text', 'image'], ['video']),
+ { status: 200 },
+ );
+ }) as unknown as typeof fetch;
+ const h = harness(fetchMock, async () => {
+ h.auth.token = 'refreshed-token';
+ return 'refreshed';
+ });
+
+ await expect(h.discovery.refresh()).resolves.toBe(true);
+ expect(calls).toHaveLength(4);
+ expect(calls).toEqual(
+ expect.arrayContaining([
+ { path: '/v1/image-generation-models', authorization: 'Bearer oauth-token' },
+ { path: '/v1/video-generation-models', authorization: 'Bearer oauth-token' },
+ { path: '/v1/image-generation-models', authorization: 'Bearer refreshed-token' },
+ { path: '/v1/video-generation-models', authorization: 'Bearer refreshed-token' },
+ ]),
+ );
+ expect(h.applied).toEqual([
+ {
+ imageModels: [{ id: 'xai/recovered-image', name: 'Recovered Image' }],
+ videoModels: [{ id: 'xai/recovered-video', name: 'Recovered Video' }],
+ },
+ ]);
+ });
+
+ it('retries a safely superseded list GET with the replacement token', async () => {
+ const fetchMock = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
+ const authorization = new Headers(init?.headers).get('authorization');
+ if (
+ String(url).endsWith('/image-generation-models') &&
+ authorization === 'Bearer oauth-token'
+ ) {
+ return new Response('expired', { status: 403 });
+ }
+ return new Response(
+ String(url).endsWith('/image-generation-models')
+ ? payload('superseded-image', ['text', 'image'], ['image'])
+ : payload('current-video', ['text', 'image'], ['video']),
+ { status: 200 },
+ );
+ }) as unknown as typeof fetch;
+ const h = harness(fetchMock, async () => {
+ h.auth.token = 'replacement-token';
+ return 'superseded';
+ });
+
+ await expect(h.discovery.refresh()).resolves.toBe(true);
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ expect(h.applied[0]?.imageModels?.[0]?.id).toBe('xai/superseded-image');
+ });
+
+ it('does not retry again when the recovered GET is still unauthorized', async () => {
+ const fetchMock = vi.fn(
+ async () => new Response('expired', { status: 401 }),
+ ) as unknown as typeof fetch;
+ const h = harness(fetchMock, async () => {
+ h.auth.token = 'refreshed-token';
+ return 'refreshed';
+ });
+
+ await expect(h.discovery.refresh()).resolves.toBe(false);
+ expect(fetchMock).toHaveBeenCalledTimes(4);
+ expect(h.onAuthRejected).toHaveBeenCalledTimes(2);
+ expect(h.applied).toEqual([]);
+ });
+
+ it('keeps the fallback and does not retry when auth recovery fails', async () => {
+ const fetchMock = vi.fn(
+ async () => new Response('expired', { status: 401 }),
+ ) as unknown as typeof fetch;
+ const h = harness(fetchMock, async () => {
+ throw new Error('refresh unavailable');
+ });
+
+ await expect(h.discovery.refresh()).resolves.toBe(false);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(h.onAuthRejected).toHaveBeenCalledTimes(2);
+ expect(h.applied).toEqual([]);
+ });
+
+ it('does not retry or apply when auth recovery changes the credential generation', async () => {
+ const fetchMock = vi.fn(async (url: string | URL | Request) =>
+ String(url).endsWith('/image-generation-models')
+ ? new Response('expired', { status: 401 })
+ : new Response(payload('late-video', ['text', 'image'], ['video']), { status: 200 }),
+ ) as unknown as typeof fetch;
+ const h = harness(fetchMock, async () => {
+ h.owner.connected = false;
+ h.auth.credentialGeneration += 1;
+ return 'logged_out';
+ });
+
+ await expect(h.discovery.refresh()).resolves.toBe(false);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(h.applied).toEqual([]);
+ });
+
+ it('does not retry or apply when auth recovery crosses the owner boundary', async () => {
+ const fetchMock = vi.fn(async (url: string | URL | Request) =>
+ String(url).endsWith('/image-generation-models')
+ ? new Response('expired', { status: 401 })
+ : new Response(payload('late-video', ['text', 'image'], ['video']), { status: 200 }),
+ ) as unknown as typeof fetch;
+ const h = harness(fetchMock, async () => {
+ h.owner.value = 'owner-b';
+ h.auth.token = 'owner-b-token';
+ return 'superseded';
+ });
+
+ await expect(h.discovery.refresh()).resolves.toBe(false);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(h.applied).toEqual([]);
+ });
+
+ it('discards a retried response whose credential generation changes while streaming', async () => {
+ let releaseBody!: () => void;
+ let retryStarted!: () => void;
+ const retryStartedPromise = new Promise<void>((resolve) => {
+ retryStarted = resolve;
+ });
+ const releaseBodyPromise = new Promise<void>((resolve) => {
+ releaseBody = resolve;
+ });
+ const encoder = new TextEncoder();
+ const fetchMock = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
+ const isImage = String(url).endsWith('/image-generation-models');
+ const authorization = new Headers(init?.headers).get('authorization');
+ if (isImage && authorization === 'Bearer oauth-token') {
+ return new Response('expired', { status: 401 });
+ }
+ if (isImage) {
+ return new Response(
+ new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(encoder.encode('{"models":['));
+ retryStarted();
+ void releaseBodyPromise.then(() => {
+ controller.enqueue(
+ encoder.encode(
+ '{"id":"late-image","input_modalities":["text","image"],"output_modalities":["image"]}]}',
+ ),
+ );
+ controller.close();
+ });
+ },
+ }),
+ { status: 200 },
+ );
+ }
+ return new Response(payload('current-video', ['text', 'image'], ['video']), { status: 200 });
+ }) as unknown as typeof fetch;
+ const h = harness(fetchMock, async () => {
+ h.auth.token = 'refreshed-token';
+ return 'refreshed';
+ });
+
+ const refresh = h.discovery.refresh();
+ await retryStartedPromise;
+ h.auth.credentialGeneration += 1;
+ releaseBody();
+
+ await expect(refresh).resolves.toBe(false);
+ expect(h.applied).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/active-catalog.ts b/apps/desktop/src/main/maker-host/active-catalog.ts
index e89a0191d4..71e12d1784 100644
--- a/apps/desktop/src/main/maker-host/active-catalog.ts
+++ b/apps/desktop/src/main/maker-host/active-catalog.ts
@@ -70,6 +70,18 @@ let discoveredCodex: CatalogModel[] = [];
* 空/坏数据绝不抹掉静态兜底。由 generic-oauth 的 models 发现流程写入。
*/
const discoveredByProvider = new Map<string, Partial<Record<AgentKind, CatalogModel[]>>>();
+/**
+ * 供应商媒体模型动态发现快照。成功快照决定当前账号的型号存在性,静态/远端
+ * 同 id 条目只提供 first-wins 展示元数据;发现失败不写本 Map,完整回落静态目录。
+ * 媒体字段显式 `[]` 是服务端停用信号,合并时不得被本快照复活。
+ */
+const discoveredMediaByProvider = new Map<
+ string,
+ {
+ imageModels?: NonNullable<Provider['imageModels']>;
+ videoModels?: NonNullable<Provider['videoModels']>;
+ }
+>();
/** 单 tab 能力覆盖块(shared/modelAccess ModelAccessAgentOverride 同形)。 */
export interface XdGatewayAgentOverride {
contextWindow?: number;
@@ -293,6 +305,26 @@ function augmentModels(
return { ...p, models: { ...p.models, [agent]: models } };
}
+function applyMediaDiscovery(
+ provider: Provider,
+ key: 'imageModels' | 'videoModels',
+ discovered: NonNullable<Provider['imageModels']>,
+): Provider {
+ const existing = provider[key];
+ // undefined = 这份原始目录没有声明能力;正常加载路径会先由 source 用 bundled
+ // 补旧目录。[] 则是明确停用。两种情况都不能仅凭账号发现把能力凭空复活。
+ if (!existing || existing.length === 0) return provider;
+ // 官方端点成功返回空清单 = 当前账号此类媒体没有可执行型号。它与请求失败不同,
+ // 必须清掉旧快照/静态兜底,不能继续展示一个账号实际不可用的型号。
+ if (discovered.length === 0) return { ...provider, [key]: [] };
+ const discoveredById = new Map(discovered.map((model) => [model.id, model]));
+ const retained = existing.filter((model) => discoveredById.delete(model.id));
+ const next = [...retained, ...discoveredById.values()];
+ const unchanged =
+ next.length === existing.length && next.every((model, index) => model === existing[index]);
+ return unchanged ? provider : { ...provider, [key]: next };
+}
+
/**
* 以生效 Codex 列表校正 bridge 的展示名称 / 排序,同时保留 bridge 自己的 context、effort、
* defaultEnabled 等 runtime 能力。这样旧远端目录里曾固化的本地化后缀也不会继续泄漏。
@@ -557,6 +589,20 @@ function computeMerged(): Catalog {
return next;
});
}
+ if (discoveredMediaByProvider.size > 0) {
+ providers = providers.map((provider) => {
+ const snapshot = discoveredMediaByProvider.get(provider.id);
+ if (!snapshot) return provider;
+ let next = provider;
+ if (snapshot.imageModels) {
+ next = applyMediaDiscovery(next, 'imageModels', snapshot.imageModels);
+ }
+ if (snapshot.videoModels) {
+ next = applyMediaDiscovery(next, 'videoModels', snapshot.videoModels);
+ }
+ return next;
+ });
+ }
// ── root 装配 + 投影(2026-08-02 模型平面收敛,拓扑见 model-plane/modelPlanePolicy.ts)。
// 每个 allowlist 供应商:registry presence 实体化/overlay + retired 标记 → 本地
// override(local 永远最高)→ 派生端(bridge/Pi)从最终 root 统一重算。
@@ -822,6 +868,30 @@ export function setDiscoveredProviderModels(
markChanged();
}
+/**
+ * 原子注入供应商图片/视频发现快照。成功快照决定存在性,同 id 静态元数据优先;
+ * 传 null 清空该供应商账号态快照,回到当前
+ * 静态/远端目录;失败路径不应调用,以保留同账号上次成功结果。
+ */
+export function setDiscoveredProviderMediaModels(
+ providerId: string,
+ snapshot: {
+ imageModels?: NonNullable<Provider['imageModels']>;
+ videoModels?: NonNullable<Provider['videoModels']>;
+ } | null,
+): void {
+ if (snapshot === null) discoveredMediaByProvider.delete(providerId);
+ else {
+ const previous = discoveredMediaByProvider.get(providerId) ?? {};
+ discoveredMediaByProvider.set(providerId, {
+ ...previous,
+ ...(snapshot.imageModels ? { imageModels: [...snapshot.imageModels] } : {}),
+ ...(snapshot.videoModels ? { videoModels: [...snapshot.videoModels] } : {}),
+ });
+ }
+ markChanged();
+}
+
/**
* 注入 XD 网关权威模型清单(model-access 拉取流程写入,重建逻辑见 computeMerged)。
* 传空数组 = 实时清单不可用,此时 XD 供应商保留但不暴露任何模型。
diff --git a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
index 34e8eebe3f..98605e47eb 100644
--- a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
+++ b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
@@ -88,6 +88,7 @@ import {
hasGrokOAuthLoginUnbound,
resetGrokOAuthMemoryCache,
} from './grok-oauth-login.js';
+import { clearXaiMediaModels, refreshXaiMediaModels } from './model-discovery/xai-media.js';
import { getAuthState } from '../authManager.js';
import { getActiveAppSession } from '../appSessionState.js';
import {
@@ -384,6 +385,13 @@ let endpointReloadInflight: {
promise: Promise<Catalog>;
} | null = null;
+/** Set 用稳定函数引用去重,ensureActiveCatalogLoaded 的幂等调用不会重复注册清理副作用。 */
+function handleProviderSecretsCleared(): void {
+ resetGenericOAuthMemoryCache();
+ resetGrokOAuthMemoryCache();
+ clearXaiMediaModels();
+}
+
/**
* 启动期(splash)await 一次:加载远端目录写入 active-catalog。幂等 + 并发去重。
* loadCatalog 永不抛(最差回落 bundled),故本函数也不会抛。
@@ -416,10 +424,7 @@ export function ensureActiveCatalogLoaded(): Promise<Catalog> {
});
// 账号切换清空本机密钥后,同步失效 generic-oauth 的内存缓存——
// 不失效的话磁盘 blob 已删但缓存还热,B 账号会继续用 A 的 token 路由(串号)。
- addProviderSecretsClearedListener(() => {
- resetGenericOAuthMemoryCache();
- resetGrokOAuthMemoryCache();
- });
+ addProviderSecretsClearedListener(handleProviderSecretsCleared);
const readOAuthToken = (providerId: string): string | null => {
const provider = getActiveCatalog().providers.find((p) => p.id === providerId);
return readCachedGenericOAuthAccessToken(providerId, provider?.auth.oauth);
@@ -740,15 +745,13 @@ async function claimNativeProviderAuthOnRead(
return;
}
if (claimedWork) {
- // Ordinary provider reads retain low latency. Discovery still runs in the background and
- // its completion invalidates other snapshots, while explicit routing callers opt into the
- // await above. Keep the rejection contained so a refresh failure cannot become an
- // unhandled rejection on the connection-status path.
- void Promise.resolve(claimedWork)
- .then(notifyIfClaimStillCurrent)
- .catch((err) => {
- log.warn('native provider post-claim work failed', { provider, error: String(err) });
- });
+ // 连接态已经在本次读里从 false 翻成 true,必须立即广播;媒体/模型发现可以继续
+ // 在后台跑,成功时 active-catalog revision 会再广播清单变化。不能让慢上游把
+ // “已连接”本身拖到超时以后才出现在其它窗口。
+ notifyIfClaimStillCurrent();
+ void Promise.resolve(claimedWork).catch((err) => {
+ log.warn('native provider post-claim work failed', { provider, error: String(err) });
+ });
return;
}
// 认领成功 = 这家供应商刚从「未连接」翻成「已连接」,但只有触发这次读取的那个调用方
@@ -884,7 +887,11 @@ export function getDesktopProviderService(): ProviderService {
? desktopCodexAuthAdapter.hasCodexOAuthLogin()
: desktopCodexAuthAdapter.hasCodexOAuthLoginReadOnly(),
xai: async ({ allowSideEffects }) => {
- if (allowSideEffects) await claimNativeProviderAuthOnRead('xai', hasGrokOAuthLoginUnbound);
+ if (allowSideEffects) {
+ await claimNativeProviderAuthOnRead('xai', hasGrokOAuthLoginUnbound, () =>
+ refreshXaiMediaModels().then(() => undefined),
+ );
+ }
return hasGrokOAuthLogin();
},
},
diff --git a/apps/desktop/src/main/maker-host/grok-oauth-login.ts b/apps/desktop/src/main/maker-host/grok-oauth-login.ts
index 98601ef8b2..ebeb046803 100644
--- a/apps/desktop/src/main/maker-host/grok-oauth-login.ts
+++ b/apps/desktop/src/main/maker-host/grok-oauth-login.ts
@@ -84,8 +84,23 @@ interface GrokTokenBlob {
// writeBlob / logoutGrok 时更新。undefined = 尚未从磁盘读过。
let _blobCache: GrokTokenBlob | null | undefined;
+// 视频任务会跨越数分钟轮询。仅靠 Cindy app-session owner 无法识别同一 owner
+// 内的 SuperGrok 登出/换号,所以用进程内单调代际把任务绑定到“提交时那次登录”。
+// 常规 access_token 刷新不推进代际:它仍属于同一登录,不能误杀正常在途任务。
+let _credentialGeneration = 0;
+
+function advanceGrokOAuthCredentialGeneration(): void {
+ _credentialGeneration += 1;
+}
+
+/** 当前 SuperGrok 登录代际;只用于比较,不包含任何凭证材料。 */
+export function getGrokOAuthCredentialGeneration(): number {
+ return _credentialGeneration;
+}
+
/** Drop the process-local xAI OAuth blob cache after an owner boundary. */
export function resetGrokOAuthMemoryCache(): void {
+ advanceGrokOAuthCredentialGeneration();
_blobCache = undefined;
_refreshChain = Promise.resolve();
_lastForcedRefreshAt = 0;
@@ -125,6 +140,9 @@ export function hasGrokOAuthLoginUnbound(): boolean {
/** 登出:清掉本机 xAI 凭证。 */
export function logoutGrok(): void {
+ // 用户一旦发起登出,旧视频任务就必须立即失效;即使后续存储/解绑异常让
+ // UI 报错,也不能继续拿登出前的任务跨凭证边界执行。
+ advanceGrokOAuthCredentialGeneration();
// remove() 的失败结果这里不阻断登出(用户意图优先),但正因为凭证可能没删掉,解绑必须
// 带撤销标记 —— 否则下一次读连接态会把残留凭证自动认领回来(PR #548 review)。
getProviderSecretStore().remove(SECRET_ID);
@@ -562,6 +580,7 @@ export async function runGrokOAuthLogin(opts?: {
if (abort.signal.aborted) throw new Error('login_cancelled');
writeBlob(blobFromTokenResponse(tok));
bindNativeProviderAuth('xai');
+ advanceGrokOAuthCredentialGeneration();
listener.succeed();
log.info('xai oauth login success', { scope: tok.scope });
return { ok: true };
diff --git a/apps/desktop/src/main/maker-host/model-discovery/xai-media.ts b/apps/desktop/src/main/maker-host/model-discovery/xai-media.ts
new file mode 100644
index 0000000000..8b240ed663
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/model-discovery/xai-media.ts
@@ -0,0 +1,377 @@
+/**
+ * xAI 图片/视频模型发现。
+ *
+ * xAI 为两类媒体分别提供类型化模型端点;这里只依据 modalities 接纳当前通用
+ * 执行通道能完整兑现的型号,不依据型号名字做正则白名单。成功快照决定账号态存在性,
+ * 失败保留同账号上次成功结果;登出/换号则先清快照并让旧请求失效。
+ */
+
+import type { Provider } from '@cindy/model-providers';
+
+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../../appSessionState.js';
+import { createLogger, type Logger } from '../../logger.js';
+import { setDiscoveredProviderMediaModels } from '../active-catalog.js';
+import {
+ getGrokAccessToken,
+ getGrokOAuthCredentialGeneration,
+ hasGrokOAuthLogin,
+} from '../grok-oauth-login.js';
+import { outboundFetch } from '../outbound-fetch.js';
+import { invalidateXaiBridgeAuth } from '../xai-auth-invalidation-host.js';
+import type { XaiBridgeAuthInvalidationResult } from '../xai-bridge-auth-invalidation.js';
+
+const XAI_API_BASE = 'https://api.x.ai/v1';
+const HTTP_TIMEOUT_MS = 15_000;
+const MAX_RESPONSE_BYTES = 512 * 1024;
+const MAX_MODELS_PER_KIND = 200;
+const MAX_MODEL_ID_CHARS = 256;
+
+type MediaModel = NonNullable<Provider['imageModels']>[number];
+
+export interface XaiMediaDiscoverySnapshot {
+ imageModels?: MediaModel[];
+ videoModels?: MediaModel[];
+}
+
+interface XaiMediaDiscoveryDeps {
+ hasOAuthLogin(): boolean;
+ getAccessToken(): Promise<string>;
+ getCredentialGeneration(): number;
+ getOwnerScopeKey(): string;
+ isOwnerBoundaryPending(): boolean;
+ fetchImplementation: typeof fetch;
+ applySnapshot(snapshot: XaiMediaDiscoverySnapshot | null): void;
+ onAuthRejected?(failure: {
+ status: number;
+ body: string;
+ failedAccessToken: string;
+ }): Promise<XaiBridgeAuthInvalidationResult>;
+ log: Pick<Logger, 'info' | 'warn'>;
+}
+
+function asModalities(value: unknown): Set<string> | null {
+ if (!Array.isArray(value)) return null;
+ const out = new Set<string>();
+ for (const entry of value) {
+ if (typeof entry !== 'string' || entry.length === 0 || entry.length > 64) return null;
+ out.add(entry.toLowerCase());
+ }
+ return out;
+}
+
+function displayName(id: string): string {
+ return id
+ .split('-')
+ .filter(Boolean)
+ .map((part) => (part.length > 0 ? `${part[0]!.toUpperCase()}${part.slice(1)}` : part))
+ .join(' ');
+}
+
+/**
+ * 官方 models[] 条目 → Cindy 媒体目录条目。requiredInputs 是当前执行适配器承诺
+ * 的完整调用面;缺一项就保守隐藏,避免“能选但下单必失败”。
+ */
+export function mapXaiMediaModels(
+ raw: unknown,
+ outputModality: 'image' | 'video',
+ requiredInputs: readonly ('text' | 'image')[],
+): MediaModel[] {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return [];
+ const models = (raw as { models?: unknown }).models;
+ if (!Array.isArray(models) || models.length > MAX_MODELS_PER_KIND) return [];
+ const seen = new Set<string>();
+ const out: MediaModel[] = [];
+ for (const entry of models) {
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue;
+ const item = entry as {
+ id?: unknown;
+ input_modalities?: unknown;
+ output_modalities?: unknown;
+ inputModalities?: unknown;
+ outputModalities?: unknown;
+ };
+ if (
+ typeof item.id !== 'string' ||
+ item.id.length === 0 ||
+ item.id.length > MAX_MODEL_ID_CHARS ||
+ /[\u0000-\u001f\u007f]/.test(item.id)
+ ) {
+ continue;
+ }
+ const inputs = asModalities(item.input_modalities ?? item.inputModalities);
+ const outputs = asModalities(item.output_modalities ?? item.outputModalities);
+ if (
+ !inputs ||
+ !outputs?.has(outputModality) ||
+ requiredInputs.some((input) => !inputs.has(input))
+ ) {
+ continue;
+ }
+ const id = item.id.startsWith('xai/') ? item.id : `xai/${item.id}`;
+ if (seen.has(id)) continue;
+ seen.add(id);
+ out.push({ id, name: displayName(item.id.replace(/^xai\//, '')) || item.id });
+ }
+ return out;
+}
+
+async function readBoundedResponseText(
+ response: Response,
+ kind: '图片' | '视频',
+ assertStillCurrent: () => void,
+): Promise<string> {
+ assertStillCurrent();
+ const declared = Number(response.headers.get('content-length') ?? Number.NaN);
+ if (Number.isFinite(declared) && declared > MAX_RESPONSE_BYTES) {
+ await response.body?.cancel().catch(() => undefined);
+ assertStillCurrent();
+ throw new Error(`xAI ${kind}模型列表响应过大`);
+ }
+ if (!response.body) {
+ assertStillCurrent();
+ return '';
+ }
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ try {
+ for (;;) {
+ const { done, value } = await reader.read();
+ assertStillCurrent();
+ if (done) break;
+ if (!value || value.byteLength === 0) continue;
+ total += value.byteLength;
+ if (total > MAX_RESPONSE_BYTES) {
+ throw new Error(`xAI ${kind}模型列表响应过大`);
+ }
+ chunks.push(value);
+ }
+ } finally {
+ await reader.cancel().catch(() => undefined);
+ reader.releaseLock();
+ }
+ assertStillCurrent();
+ return Buffer.concat(chunks, total).toString('utf8');
+}
+
+function parsePayload(text: string, kind: '图片' | '视频'): unknown {
+ try {
+ return JSON.parse(text) as unknown;
+ } catch {
+ throw new Error(`xAI ${kind}模型列表返回了无效 JSON`);
+ }
+}
+
+function hasValidModelsArray(value: unknown): boolean {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
+ const models = (value as { models?: unknown }).models;
+ return Array.isArray(models) && models.length <= MAX_MODELS_PER_KIND;
+}
+
+export function createXaiMediaDiscovery(deps: XaiMediaDiscoveryDeps): {
+ refresh(): Promise<boolean>;
+ clear(): void;
+} {
+ const staleDiscovery = Symbol('stale xAI media discovery');
+ let generation = 0;
+ let appliedScopeKey: string | null = null;
+ let inflight: {
+ generation: number;
+ ownerScopeKey: string;
+ credentialGeneration: number;
+ promise: Promise<boolean>;
+ } | null = null;
+
+ function syncScope(): string {
+ const next = deps.getOwnerScopeKey();
+ if (appliedScopeKey !== null && next !== appliedScopeKey) {
+ generation += 1;
+ inflight = null;
+ deps.applySnapshot(null);
+ }
+ appliedScopeKey = next;
+ return next;
+ }
+
+ function canApply(
+ expectedGeneration: number,
+ expectedScope: string,
+ expectedCredentialGeneration: number,
+ ): boolean {
+ return (
+ generation === expectedGeneration &&
+ deps.getOwnerScopeKey() === expectedScope &&
+ deps.getCredentialGeneration() === expectedCredentialGeneration &&
+ !deps.isOwnerBoundaryPending() &&
+ deps.hasOAuthLogin()
+ );
+ }
+
+ function assertCurrent(
+ expectedGeneration: number,
+ expectedScope: string,
+ expectedCredentialGeneration: number,
+ ): void {
+ if (!canApply(expectedGeneration, expectedScope, expectedCredentialGeneration)) {
+ throw staleDiscovery;
+ }
+ }
+
+ async function fetchList(
+ path: '/image-generation-models' | '/video-generation-models',
+ label: '图片' | '视频',
+ initialToken: string,
+ signal: AbortSignal,
+ assertStillCurrent: () => void,
+ ): Promise<unknown> {
+ let token = initialToken;
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ assertStillCurrent();
+ const response = await deps.fetchImplementation(`${XAI_API_BASE}${path}`, {
+ method: 'GET',
+ headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
+ redirect: 'error',
+ signal,
+ });
+ assertStillCurrent();
+ const text = await readBoundedResponseText(response, label, assertStillCurrent);
+ if (response.ok) return parsePayload(text, label);
+
+ const recovery =
+ attempt === 0 && (response.status === 401 || response.status === 403) && deps.onAuthRejected
+ ? await deps
+ .onAuthRejected({
+ status: response.status,
+ body: text.slice(0, 8 * 1024),
+ failedAccessToken: token,
+ })
+ .catch(() => undefined)
+ : undefined;
+ assertStillCurrent();
+ if (recovery === 'refreshed' || recovery === 'superseded') {
+ token = await deps.getAccessToken();
+ assertStillCurrent();
+ continue;
+ }
+ throw new Error(`xAI ${label}模型发现失败(HTTP ${response.status})`);
+ }
+ throw new Error(`xAI ${label}模型发现失败:认证恢复重试耗尽`);
+ }
+
+ function refresh(): Promise<boolean> {
+ const ownerScopeKey = syncScope();
+ if (deps.isOwnerBoundaryPending() || !deps.hasOAuthLogin()) return Promise.resolve(false);
+ const expectedGeneration = generation;
+ const expectedCredentialGeneration = deps.getCredentialGeneration();
+ if (
+ inflight?.generation === expectedGeneration &&
+ inflight.ownerScopeKey === ownerScopeKey &&
+ inflight.credentialGeneration === expectedCredentialGeneration
+ ) {
+ return inflight.promise;
+ }
+ const flight = (async () => {
+ try {
+ const token = await deps.getAccessToken();
+ assertCurrent(expectedGeneration, ownerScopeKey, expectedCredentialGeneration);
+ const assertStillCurrent = (): void =>
+ assertCurrent(expectedGeneration, ownerScopeKey, expectedCredentialGeneration);
+ const signal = AbortSignal.timeout(HTTP_TIMEOUT_MS);
+ const [imageResult, videoResult] = await Promise.allSettled([
+ fetchList('/image-generation-models', '图片', token, signal, assertStillCurrent),
+ fetchList('/video-generation-models', '视频', token, signal, assertStillCurrent),
+ ]);
+ assertStillCurrent();
+ // 当前 xAI 图片通道同时承担生成与编辑,视频通道同时承担文生与单图生;
+ // 所以动态条目必须覆盖各自完整输入面。以后若目录支持 per-model 能力,
+ // 可在这里放宽为按条目声明,而不是靠名称猜测。
+ const snapshot: XaiMediaDiscoverySnapshot = {};
+ const failures: string[] = [];
+ if (imageResult.status === 'fulfilled') {
+ if (hasValidModelsArray(imageResult.value)) {
+ snapshot.imageModels = mapXaiMediaModels(imageResult.value, 'image', ['text', 'image']);
+ } else {
+ failures.push('xAI 图片模型列表结构无效');
+ }
+ } else {
+ failures.push(
+ imageResult.reason instanceof Error
+ ? imageResult.reason.message
+ : String(imageResult.reason),
+ );
+ }
+ if (videoResult.status === 'fulfilled') {
+ if (hasValidModelsArray(videoResult.value)) {
+ snapshot.videoModels = mapXaiMediaModels(videoResult.value, 'video', ['text', 'image']);
+ } else {
+ failures.push('xAI 视频模型列表结构无效');
+ }
+ } else {
+ failures.push(
+ videoResult.reason instanceof Error
+ ? videoResult.reason.message
+ : String(videoResult.reason),
+ );
+ }
+ if (!snapshot.imageModels && !snapshot.videoModels) {
+ throw new Error(failures.join('; ') || 'xAI 媒体模型响应不可用');
+ }
+ assertStillCurrent();
+ deps.applySnapshot(snapshot);
+ if (failures.length > 0) {
+ deps.log.warn(
+ 'xAI media discovery partially succeeded; preserving previous failed kind',
+ {
+ failures,
+ },
+ );
+ }
+ deps.log.info('xAI media models refreshed', {
+ imageModels: snapshot.imageModels?.length,
+ videoModels: snapshot.videoModels?.length,
+ });
+ return true;
+ } catch (error) {
+ if (error === staleDiscovery) return false;
+ deps.log.warn('xAI media model discovery failed; keeping current catalog fallback', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return false;
+ }
+ })().finally(() => {
+ if (inflight?.promise === flight) inflight = null;
+ });
+ inflight = {
+ generation: expectedGeneration,
+ ownerScopeKey,
+ credentialGeneration: expectedCredentialGeneration,
+ promise: flight,
+ };
+ return flight;
+ }
+
+ function clear(): void {
+ generation += 1;
+ appliedScopeKey = deps.getOwnerScopeKey();
+ inflight = null;
+ deps.applySnapshot(null);
+ }
+
+ return { refresh, clear };
+}
+
+const log = createLogger('model-discovery:xai-media');
+const discovery = createXaiMediaDiscovery({
+ hasOAuthLogin: () => hasGrokOAuthLogin(),
+ getAccessToken: () => getGrokAccessToken(),
+ getCredentialGeneration: () => getGrokOAuthCredentialGeneration(),
+ getOwnerScopeKey: () => activeOwnerScopeKey(),
+ isOwnerBoundaryPending: () => isAppSessionBoundaryPending(),
+ fetchImplementation: ((url, init) => outboundFetch(url as string, init)) as typeof fetch,
+ applySnapshot: (snapshot) => setDiscoveredProviderMediaModels('xai', snapshot),
+ onAuthRejected: (failure) => invalidateXaiBridgeAuth(failure),
+ log,
+});
+
+export const refreshXaiMediaModels = (): Promise<boolean> => discovery.refresh();
+export const clearXaiMediaModels = (): void => discovery.clear();
diff --git a/apps/desktop/src/main/maker-host/provider-model-auto-refresh.ts b/apps/desktop/src/main/maker-host/provider-model-auto-refresh.ts
index 88c629bb21..ada68f3471 100644
--- a/apps/desktop/src/main/maker-host/provider-model-auto-refresh.ts
+++ b/apps/desktop/src/main/maker-host/provider-model-auto-refresh.ts
@@ -292,15 +292,7 @@ export function createProviderModelRefreshCoordinator(
}
const requestedIds = providerIds ?? BUILTIN_REFRESHABLE_PROVIDER_IDS;
- const ids = requestedIds.filter(
- (id) =>
- connectedIds.has(id) &&
- // xAI's provider refresh reads the same public Catalog as refreshCatalog. The shared
- // refresh already ran (or was intentionally skipped because splash/cooldown made its
- // snapshot current), so running the provider hook would fetch the identical source a
- // second time. Manual xAI refresh still uses refreshProvider and bypasses this path.
- !(id === 'xai' && deps.refreshCatalog),
- );
+ const ids = requestedIds.filter((id) => connectedIds.has(id));
// 启动期无视冷却(见 `'startup'` trigger 注释);in-flight 合并仍生效,所以并发的
// 启动触发与手动刷新不会各起一次 codex app-server。
const force = isForcedProviderModelAutoRefreshTrigger(trigger);
@@ -318,8 +310,11 @@ export function createProviderModelRefreshCoordinator(
});
},
- refreshManually(providerId): Promise<void> {
- return refresh(providerId, true);
+ async refreshManually(providerId): Promise<void> {
+ // xAI 同时有公共静态目录与账号态媒体发现。手动刷新要把两层都刷新;自动路径
+ // 已在上方统一先刷新公共目录,再调用 provider hook,因此不会重复拉 Catalog。
+ if (providerId === 'xai' && deps.refreshCatalog) await deps.refreshCatalog();
+ await refresh(providerId, true);
},
resetCooldowns,
};
diff --git a/apps/desktop/src/main/maker-host/provider-model-refresh.ts b/apps/desktop/src/main/maker-host/provider-model-refresh.ts
index 668abb34e8..331c4a0776 100644
--- a/apps/desktop/src/main/maker-host/provider-model-refresh.ts
+++ b/apps/desktop/src/main/maker-host/provider-model-refresh.ts
@@ -11,7 +11,7 @@ export interface BuiltinProviderModelRefreshDeps {
refreshXd(): Promise<void>;
refreshAnthropic(): Promise<boolean>;
refreshOpenAi(): Promise<boolean>;
- refreshXaiCatalog(): Promise<void>;
+ refreshXaiMedia(): Promise<boolean>;
}
export async function refreshBuiltinProviderModels(
@@ -33,6 +33,8 @@ export async function refreshBuiltinProviderModels(
}
return;
case 'xai':
- await deps.refreshXaiCatalog();
+ if (!(await deps.refreshXaiMedia())) {
+ throw new Error('xAI media model discovery did not produce a current snapshot');
+ }
}
}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 6db63db91e..a94c41c1cd 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -690,6 +690,7 @@ import {
setSessionProvider,
} from '../maker-host/session-provider-store.js';
import { getActiveCatalog, setDiscoveredProviderModels } from '../maker-host/active-catalog.js';
+import { refreshXaiMediaModels } from '../maker-host/model-discovery/xai-media.js';
import { testProviderConnection } from '../maker-host/provider-diagnostics.js';
import { fetchProviderModels } from '../maker-host/provider-model-fetch.js';
import {
@@ -5671,9 +5672,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
refreshAnthropic: refreshAnthropicModelsFromHttp,
refreshOpenAi: () =>
maker.refreshAgentLocalModels('codex', { credentialMode: 'oauth-bearer' }),
- refreshXaiCatalog: async () => {
- await refreshActiveCatalogFromSource();
- },
+ refreshXaiMedia: refreshXaiMediaModels,
}),
});
options.onProviderModelAutoRefreshConfigured();
diff --git a/packages/model-providers/catalog/providers.json b/packages/model-providers/catalog/providers.json
index 067e5889a1..bcb7a3b1c1 100644
--- a/packages/model-providers/catalog/providers.json
+++ b/packages/model-providers/catalog/providers.json
@@ -23,6 +23,12 @@
"name": "Grok Imagine Image (Quality)"
}
],
+ "videoModels": [
+ {
+ "id": "xai/grok-imagine-video",
+ "name": "Grok Imagine Video"
+ }
+ ],
"routing": {
"claude-code": {
"upstream": "https://api.x.ai/v1",
diff --git a/packages/model-providers/src/__tests__/catalog.test.ts b/packages/model-providers/src/__tests__/catalog.test.ts
index 919653acb4..14a4222b17 100644
--- a/packages/model-providers/src/__tests__/catalog.test.ts
+++ b/packages/model-providers/src/__tests__/catalog.test.ts
@@ -150,6 +150,12 @@ describe('bundled catalog validity (dynamic-first contract)', () => {
]);
});
+ it('xai ships the Grok Imagine subscription video model', () => {
+ expect(provider('xai').videoModels).toEqual([
+ { id: 'xai/grok-imagine-video', name: 'Grok Imagine Video' },
+ ]);
+ });
+
it('provides routing + a models[agent] array for every agent the provider declares', () => {
for (const p of BUNDLED_CATALOG.providers) {
for (const a of p.agents) {
diff --git a/packages/model-providers/src/__tests__/source-registry.test.ts b/packages/model-providers/src/__tests__/source-registry.test.ts
index 26f8213c1e..b27495e5cb 100644
--- a/packages/model-providers/src/__tests__/source-registry.test.ts
+++ b/packages/model-providers/src/__tests__/source-registry.test.ts
@@ -225,19 +225,23 @@ describe('mergeWithBundled', () => {
expect(merged.providers.find((provider) => provider.id === 'xai')?.name).toBe('REMOTE-XAI');
});
- it('旧远端未声明媒体能力时继承 bundled;显式空清单仍可停用', () => {
+ it('旧远端未声明 xAI 媒体能力时继承 bundled;显式空清单仍可停用', () => {
const bundledXai = BUNDLED_CATALOG.providers.find((p) => p.id === 'xai')!;
const oldRemoteXai = JSON.parse(JSON.stringify(bundledXai)) as Provider;
delete oldRemoteXai.imageModels;
+ delete oldRemoteXai.videoModels;
const inherited = mergeWithBundled({ version: '2', providers: [oldRemoteXai] });
expect(inherited.providers.find((p) => p.id === 'xai')?.imageModels)
.toEqual(bundledXai.imageModels);
+ expect(inherited.providers.find((p) => p.id === 'xai')?.videoModels)
+ .toEqual(bundledXai.videoModels);
const explicitlyDisabled = mergeWithBundled({
version: '2',
- providers: [{ ...oldRemoteXai, imageModels: [] }],
+ providers: [{ ...oldRemoteXai, imageModels: [], videoModels: [] }],
});
expect(explicitlyDisabled.providers.find((p) => p.id === 'xai')?.imageModels).toEqual([]);
+ expect(explicitlyDisabled.providers.find((p) => p.id === 'xai')?.videoModels).toEqual([]);
});
it('旧远端未声明向量清单时继承 bundled;显式空清单仍是停用语义', () => {
@@ -268,6 +272,7 @@ describe('mergeWithBundled', () => {
const bundledXai = BUNDLED_CATALOG.providers.find((p) => p.id === 'xai')!;
const oldRemoteXai = JSON.parse(JSON.stringify(bundledXai)) as Provider;
delete oldRemoteXai.imageModels;
+ delete oldRemoteXai.videoModels;
const apiKeyXai: Provider = {
...oldRemoteXai,
@@ -289,17 +294,28 @@ describe('mergeWithBundled', () => {
(p) => p.id === 'xai',
)?.imageModels,
).toBeUndefined();
+ expect(
+ mergeWithBundled({ version: '2', providers: [apiKeyXai] }).providers.find(
+ (p) => p.id === 'xai',
+ )?.videoModels,
+ ).toBeUndefined();
expect(
mergeWithBundled({ version: '2', providers: [alternateRouteXai] }).providers.find(
(p) => p.id === 'xai',
)?.imageModels,
).toBeUndefined();
+ expect(
+ mergeWithBundled({ version: '2', providers: [alternateRouteXai] }).providers.find(
+ (p) => p.id === 'xai',
+ )?.videoModels,
+ ).toBeUndefined();
});
it('旧 xAI 条目仅在 access 缺省或仍为同一订阅时继承 bundled 图像能力', () => {
const bundledXai = BUNDLED_CATALOG.providers.find((p) => p.id === 'xai')!;
const oldRemoteXai = JSON.parse(JSON.stringify(bundledXai)) as Provider;
delete oldRemoteXai.imageModels;
+ delete oldRemoteXai.videoModels;
for (const access of [
{ kind: 'api' as const },
@@ -312,6 +328,12 @@ describe('mergeWithBundled', () => {
providers: [{ ...oldRemoteXai, access }],
}).providers.find((p) => p.id === 'xai')?.imageModels,
).toBeUndefined();
+ expect(
+ mergeWithBundled({
+ version: '2',
+ providers: [{ ...oldRemoteXai, access }],
+ }).providers.find((p) => p.id === 'xai')?.videoModels,
+ ).toBeUndefined();
}
expect(
@@ -320,6 +342,12 @@ describe('mergeWithBundled', () => {
providers: [{ ...oldRemoteXai, access: bundledXai.access }],
}).providers.find((p) => p.id === 'xai')?.imageModels,
).toEqual(bundledXai.imageModels);
+ expect(
+ mergeWithBundled({
+ version: '2',
+ providers: [{ ...oldRemoteXai, access: bundledXai.access }],
+ }).providers.find((p) => p.id === 'xai')?.videoModels,
+ ).toEqual(bundledXai.videoModels);
});
it('非 xAI 远端条目缺少媒体字段时不从 bundled 恢复已撤下能力', () => {
diff --git a/packages/model-providers/src/source.ts b/packages/model-providers/src/source.ts
index b524d0e1ef..a7c276668a 100644
--- a/packages/model-providers/src/source.ts
+++ b/packages/model-providers/src/source.ts
@@ -202,8 +202,8 @@ function backfillPresetContextWindows(
/**
* 把远端 / 本地目录与内置 bundled 合并:以输入目录为主,bundled 补它缺失的
- * provider(按 id),并给旧目录中同 id provider 补缺失的 access 与图像能力元数据。
- * primary 明确提供的值(包括显式空图像清单)永远优先,不被 bundled 覆盖。
+ * provider(按 id),并给旧目录中同 id provider 补缺失的 access 与媒体能力元数据。
+ * primary 明确提供的值(包括显式空媒体清单)永远优先,不被 bundled 覆盖。
*
* **顺序契约**:结果按 bundled 数组序稳定排列(anthropic → openai → xai → xd),
* bundled 之外的远端新增供应商按远端原序追加在后。v2 远端目录只承载 xai 段,
@@ -221,6 +221,12 @@ export function mergeWithBundled(primary: Catalog): Catalog {
bundled.imageModels !== undefined &&
bundledAccess !== undefined &&
allowsBundledImageInheritance(p.access, bundledAccess);
+ const inheritVideo =
+ p.id === 'xai' &&
+ p.videoModels === undefined &&
+ bundled.videoModels !== undefined &&
+ bundledAccess !== undefined &&
+ allowsBundledImageInheritance(p.access, bundledAccess);
// 向量清单与 xai 的图像清单同一个道理(PR #1707 review):xd 段的向量能力是
// 客户端新增的 bundled 元数据,而远端 / 本地目录里同 id 的 xd 可能还是升级前
// 的结构、根本没有 embeddingModels 这个字段。primary 整体优先的规则会让那份
@@ -238,6 +244,7 @@ export function mergeWithBundled(primary: Catalog): Catalog {
if (
!(p.access === undefined && bundledAccess !== undefined) &&
!inheritImage &&
+ !inheritVideo &&
!inheritEmbedding
) {
return p;
@@ -253,6 +260,14 @@ export function mergeWithBundled(primary: Catalog): Catalog {
: {}),
}
: {}),
+ ...(inheritVideo
+ ? {
+ videoModels: bundled.videoModels,
+ ...(p.videoDefaults === undefined && bundled.videoDefaults !== undefined
+ ? { videoDefaults: bundled.videoDefaults }
+ : {}),
+ }
+ : {}),
...(inheritEmbedding
? {
embeddingModels: bundled.embeddingModels,