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): 复用 SuperGrok 订阅账号生成图片 (#1250)

Chris Zhange31f1d63c6c9
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts
index 894baa14de..50307090e8 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts
@@ -98,6 +98,7 @@ function makeSlot(overrides: Partial<CindySlotDeps> = {}): {
}
: null,
);
+ const imageCapabilities = vi.fn(() => null);
const resolveOwnedMedia = vi.fn(async (_ghostId: string, hash: string) => `/disk/${hash}.png`);
const getOverride = vi.fn((_ghostId: string, _capability: string) => null as string | null);
const getImageConfig = vi.fn(() => ({
@@ -136,6 +137,8 @@ function makeSlot(overrides: Partial<CindySlotDeps> = {}): {
const releaseDeposit = vi.fn(async () => true);
const slot = new GhostCindySlot({
getGhost: () => fakeGhost(),
+ getOwnerScopeKey: () => 'cloud:test-owner:1',
+ isOwnerBoundaryPending: () => false,
generateImage,
editImage,
generateVideo,
@@ -144,6 +147,7 @@ function makeSlot(overrides: Partial<CindySlotDeps> = {}): {
getOverride,
getImageConfig,
getVideoConfig,
+ imageCapabilities,
videoCapabilities,
saveGhostMedia,
sniffDepositMime,
@@ -493,7 +497,7 @@ describe('视频代办(gen_video / edit_video)', () => {
hashes: [HASH_S],
});
expect(r).toMatchObject({ ok: true });
- expect(resolveOwnedMedia).toHaveBeenCalledWith('art', HASH_S);
+ expect(resolveOwnedMedia).toHaveBeenCalledWith('art', HASH_S, 'cloud:test-owner:1');
expect(editVideo).toHaveBeenCalledWith({
prompt: '让它动起来',
model: 'seedance-fast',
@@ -670,10 +674,56 @@ describe('代办链路', () => {
});
expect(generateImage).toHaveBeenCalledWith({ prompt: '一只猫', model: 'gpt-image-2' });
expect(saveGhostMedia).toHaveBeenCalledWith(
- expect.objectContaining({ ghostId: 'art', mimeType: 'image/png' }),
+ expect.objectContaining({
+ ghostId: 'art',
+ mimeType: 'image/png',
+ ownerScopeKey: 'cloud:test-owner:1',
+ }),
);
});
+ it('生成期间切换账号时不保存旧作用域产物', async () => {
+ let ownerScopeKey = 'cloud:owner-a:1';
+ const saveGhostMedia = vi.fn();
+ const { slot } = makeSlot({
+ getOwnerScopeKey: () => ownerScopeKey,
+ generateImage: vi.fn(async () => {
+ ownerScopeKey = 'cloud:owner-b:2';
+ return { buffer: new Uint8Array([1, 2, 3]), mimeType: 'image/png' };
+ }),
+ saveGhostMedia,
+ });
+
+ const result = await slot.handleModelRequest('art', REQ);
+
+ expect(result).toMatchObject({ ok: false });
+ expect((result as { message: string }).message).toContain('账号已切换');
+ expect(saveGhostMedia).not.toHaveBeenCalled();
+ });
+
+ it('保存期间切换账号时不向新作用域返回旧产物', async () => {
+ let ownerScopeKey = 'cloud:owner-a:1';
+ const saveGhostMedia = vi.fn(async (params: { ownerScopeKey: string }) => {
+ expect(params.ownerScopeKey).toBe('cloud:owner-a:1');
+ ownerScopeKey = 'cloud:owner-b:2';
+ return {
+ url: 'cindy-media://blobs/abc.png',
+ hash: 'a'.repeat(64),
+ ext: '.png',
+ };
+ });
+ const { slot } = makeSlot({
+ getOwnerScopeKey: () => ownerScopeKey,
+ saveGhostMedia: saveGhostMedia as unknown as CindySlotDeps['saveGhostMedia'],
+ });
+
+ const result = await slot.handleModelRequest('art', REQ);
+
+ expect(result).toMatchObject({ ok: false });
+ expect((result as { message: string }).message).toContain('账号已切换');
+ expect(saveGhostMedia).toHaveBeenCalledOnce();
+ });
+
it('图片代办附带像素宽高(字节头可解析时);探测不出则缺省', async () => {
// 最小 PNG 头(1024×1536):签名 + IHDR。
const png = new Uint8Array(24);
@@ -806,7 +856,7 @@ describe('改图代办(edit_image)', () => {
const { slot, editImage, resolveOwnedMedia, saveGhostMedia } = makeSlot();
const r = await slot.handleModelRequest('art', EDIT_REQ);
expect(r).toMatchObject({ ok: true, hash: 'a'.repeat(64) });
- expect(resolveOwnedMedia).toHaveBeenCalledWith('art', HASH_S);
+ expect(resolveOwnedMedia).toHaveBeenCalledWith('art', HASH_S, 'cloud:test-owner:1');
expect(editImage).toHaveBeenCalledWith({
prompt: '加顶帽子',
model: 'gpt-image-2',
@@ -828,6 +878,40 @@ describe('改图代办(edit_image)', () => {
expect(editImage).not.toHaveBeenCalled();
});
+ it('通用契约允许四图;provider 上限更低时按选中型号在读图前明拒', async () => {
+ const generic = makeSlot();
+ const four = await generic.slot.handleModelRequest('art', {
+ ...EDIT_REQ,
+ hashes: Array(4).fill(HASH_S),
+ });
+ expect(four).toMatchObject({ ok: true });
+ expect(generic.editImage).toHaveBeenCalledWith(expect.objectContaining({
+ imagePaths: Array(4).fill(`/disk/${HASH_S}.png`),
+ }));
+
+ const xaiConfig = vi.fn(() => ({
+ models: [{ id: 'xai/grok-imagine-image', label: 'Grok Imagine Image' }],
+ defaults: {
+ standard: 'xai/grok-imagine-image',
+ draft: 'xai/grok-imagine-image',
+ best: 'xai/grok-imagine-image',
+ },
+ }));
+ const xai = makeSlot({
+ getImageConfig: xaiConfig,
+ imageCapabilities: vi.fn(() => ({ maxEditImages: 3 })),
+ });
+ const rejected = await xai.slot.handleModelRequest('art', {
+ ...EDIT_REQ,
+ hashes: Array(4).fill(HASH_S),
+ });
+ expect(rejected).toMatchObject({ ok: false });
+ expect((rejected as { message: string }).message).toContain('Grok Imagine Image');
+ expect((rejected as { message: string }).message).toContain('最多支持 3 张源图');
+ expect(xai.resolveOwnedMedia).not.toHaveBeenCalled();
+ expect(xai.editImage).not.toHaveBeenCalled();
+ });
+
it('任一源图不在本意识名下 → 整单拒(统一话术)', async () => {
const { slot, editImage } = makeSlot({
resolveOwnedMedia: vi.fn(async (_g: string, hash: string) =>
@@ -842,6 +926,30 @@ describe('改图代办(edit_image)', () => {
expect((r as { message: string }).message).toContain('名下');
expect(editImage).not.toHaveBeenCalled();
});
+
+ it('解析源图期间切换账号时丢弃任务,且解析器收到受理时的稳定作用域', async () => {
+ let ownerScopeKey = 'cloud:owner-a:1';
+ const resolveOwnedMedia = vi.fn(
+ async (_ghostId: string, hash: string, taskOwnerScopeKey: string) => {
+ expect(taskOwnerScopeKey).toBe('cloud:owner-a:1');
+ ownerScopeKey = 'cloud:owner-b:2';
+ return `/disk/${hash}.png`;
+ },
+ );
+ const editImage = vi.fn();
+ const { slot } = makeSlot({
+ getOwnerScopeKey: () => ownerScopeKey,
+ resolveOwnedMedia,
+ editImage,
+ } as Partial<CindySlotDeps>);
+
+ const result = await slot.handleModelRequest('art', EDIT_REQ);
+
+ expect(result).toMatchObject({ ok: false });
+ expect((result as { message: string }).message).toContain('账号已切换');
+ expect(resolveOwnedMedia).toHaveBeenCalledWith('art', HASH_S, 'cloud:owner-a:1');
+ expect(editImage).not.toHaveBeenCalled();
+ });
});
describe('管子续命挂钩(同步视频代办 hold/release)', () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/xaiImageClient.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/xaiImageClient.test.ts
new file mode 100644
index 0000000000..f464f076ec
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/xaiImageClient.test.ts
@@ -0,0 +1,277 @@
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { createXaiImageChannel } from '../xaiImageClient.js';
+
+const tempPaths: string[] = [];
+
+afterEach(async () => {
+ await Promise.all(tempPaths.splice(0).map((path) => fs.rm(path, { force: true })));
+});
+
+function channel(fetchImplementation: typeof fetch, overrides: Record<string, unknown> = {}) {
+ return createXaiImageChannel({
+ hasOAuthLogin: () => true,
+ getAccessToken: async () => 'grok-oauth-token',
+ getOwnerScopeKey: () => 'cloud:owner-a:1',
+ isOwnerBoundaryPending: () => false,
+ fetchImplementation,
+ ...overrides,
+ });
+}
+
+describe('xaiImageClient', () => {
+ it('复用 SuperGrok OAuth 调 Imagine generation 并保留原生画幅', async () => {
+ const doFetch = vi.fn<typeof fetch>(
+ async () =>
+ new Response(
+ JSON.stringify({
+ data: [{ b64_json: 'aW1hZ2U=', mime_type: 'image/jpeg' }],
+ }),
+ { status: 200 },
+ ),
+ );
+ const result = await channel(doFetch).generateImage({
+ model: 'xai/grok-imagine-image',
+ prompt: '一只猫',
+ aspectRatio: '3:2',
+ });
+
+ expect(result).toEqual({ data: [{ b64_json: 'aW1hZ2U=' }], output_format: 'jpeg' });
+ const [url, init] = doFetch.mock.calls[0]!;
+ expect(String(url)).toBe('https://api.x.ai/v1/images/generations');
+ expect((init?.headers as Record<string, string>).Authorization).toBe('Bearer grok-oauth-token');
+ expect(JSON.parse(String(init?.body))).toMatchObject({
+ model: 'grok-imagine-image',
+ prompt: '一只猫',
+ aspect_ratio: '3:2',
+ resolution: '1k',
+ response_format: 'b64_json',
+ });
+ });
+
+ it('改图把最多三张本地图片编码为 xAI JSON image fields', async () => {
+ const paths = await Promise.all(
+ [0, 1].map(async (index) => {
+ const imagePath = path.join(
+ os.tmpdir(),
+ `cindy-xai-image-test-${process.pid}-${index}.png`,
+ );
+ tempPaths.push(imagePath);
+ await fs.writeFile(imagePath, Buffer.from('89504e470d0a1a0a0000000d49484452', 'hex'));
+ return imagePath;
+ }),
+ );
+ const doFetch = vi.fn<typeof fetch>(
+ async () =>
+ new Response(
+ JSON.stringify({
+ data: [{ b64_json: 'aW1hZ2U=' }],
+ }),
+ { status: 200 },
+ ),
+ );
+ await channel(doFetch).editImage({
+ model: 'xai/grok-imagine-image-quality',
+ prompt: '合成一张图',
+ imagePaths: paths,
+ aspectRatio: '2:3',
+ });
+
+ const [url, init] = doFetch.mock.calls[0]!;
+ expect(String(url)).toBe('https://api.x.ai/v1/images/edits');
+ const body = JSON.parse(String(init?.body)) as { images: Array<{ type: string; url: string }> };
+ expect(body.images).toHaveLength(2);
+ expect(body.images.every((image) => image.type === 'image_url')).toBe(true);
+ expect(body.images.every((image) => image.url.startsWith('data:image/png;base64,'))).toBe(true);
+ });
+
+ it('短效 URL 响应会立刻有界下载成字节;非 xAI URL 被拒绝', async () => {
+ const png = Buffer.from('89504e470d0a1a0a0000000d49484452', 'hex');
+ const doFetch = 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,
+ })
+ : new Response(png, { status: 200 }),
+ );
+ const result = await channel(doFetch).generateImage({
+ model: 'xai/grok-imagine-image',
+ prompt: 'p',
+ });
+ expect(result.data[0]?.b64_json).toBe(png.toString('base64'));
+ expect(doFetch).toHaveBeenCalledTimes(2);
+ expect(doFetch.mock.calls[1]?.[1]).toMatchObject({ redirect: 'manual' });
+
+ const declaredOversize = 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,
+ })
+ : new Response(png, { status: 200, headers: { 'Content-Length': '17' } }),
+ );
+ await expect(
+ channel(declaredOversize, { maxImageDownloadBytes: 16 }).generateImage({
+ model: 'xai/grok-imagine-image',
+ prompt: 'p',
+ }),
+ ).rejects.toThrow('超过大小上限');
+
+ const cancel = vi.fn();
+ const streamedOversize = 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,
+ })
+ : new Response(new ReadableStream({
+ start(controller) {
+ controller.enqueue(png.subarray(0, 8));
+ controller.enqueue(png.subarray(8));
+ },
+ cancel,
+ }), { status: 200 }),
+ );
+ await expect(
+ channel(streamedOversize, { maxImageDownloadBytes: 15 }).generateImage({
+ model: 'xai/grok-imagine-image',
+ prompt: 'p',
+ }),
+ ).rejects.toThrow('超过大小上限');
+ expect(cancel).toHaveBeenCalled();
+
+ const untrusted = vi.fn<typeof fetch>(
+ async () =>
+ new Response(
+ JSON.stringify({
+ data: [{ url: 'https://example.com/output.png' }],
+ }),
+ { status: 200 },
+ ),
+ );
+ await expect(
+ channel(untrusted).generateImage({ model: 'xai/grok-imagine-image', prompt: 'p' }),
+ ).rejects.toThrow('不可信');
+
+ const malformed = vi.fn<typeof fetch>(
+ async () =>
+ new Response(
+ JSON.stringify({
+ data: [{ url: 'not a URL' }],
+ }),
+ { status: 200 },
+ ),
+ );
+ await expect(
+ channel(malformed).generateImage({ model: 'xai/grok-imagine-image', prompt: 'p' }),
+ ).rejects.toThrow('不可信');
+
+ const redirected = 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,
+ })
+ : new Response(null, {
+ status: 302,
+ headers: { Location: 'https://example.com/output.png' },
+ }),
+ );
+ 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' });
+ });
+
+ it('账号作用域在准备请求或等待响应期间改变时 fail closed', async () => {
+ let ownerScope = 'cloud:owner-a:1';
+ const beforeFetch = vi.fn<typeof fetch>();
+ const switchesDuringTokenRead = channel(beforeFetch, {
+ getOwnerScopeKey: () => ownerScope,
+ getAccessToken: async () => {
+ ownerScope = 'cloud:owner-b:2';
+ return 'owner-a-token';
+ },
+ });
+
+ await expect(
+ switchesDuringTokenRead.generateImage({ model: 'xai/grok-imagine-image', prompt: 'p' }),
+ ).rejects.toThrow('账号已切换');
+ expect(beforeFetch).not.toHaveBeenCalled();
+
+ ownerScope = 'cloud:owner-a:3';
+ const responseFetch = vi.fn<typeof fetch>(async () => {
+ ownerScope = 'cloud:owner-b:4';
+ return new Response(JSON.stringify({ data: [{ b64_json: 'aW1hZ2U=' }] }), { status: 200 });
+ });
+ await expect(
+ channel(responseFetch, { getOwnerScopeKey: () => ownerScope }).generateImage({
+ model: 'xai/grok-imagine-image',
+ prompt: 'p',
+ }),
+ ).rejects.toThrow('账号已切换');
+ expect(responseFetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('登录态决定 ready;派发拦截、源图上限与 OAuth 拒绝均在出网边界处理', async () => {
+ const doFetch = vi.fn<typeof fetch>();
+ const unavailable = channel(doFetch, { hasOAuthLogin: () => false });
+ expect(unavailable.ready()).toBe(false);
+
+ const getAccessToken = vi.fn(async () => 'grok-oauth-token');
+ const blocked = channel(doFetch, {
+ getAccessToken,
+ beforeDispatch: () => {
+ throw new Error('模型已停用');
+ },
+ });
+ await expect(
+ blocked.generateImage({ model: 'xai/grok-imagine-image', prompt: 'p' }),
+ ).rejects.toThrow('模型已停用');
+ expect(doFetch).not.toHaveBeenCalled();
+ expect(getAccessToken).not.toHaveBeenCalled();
+
+ const boundaryBlocked = channel(doFetch, {
+ getAccessToken,
+ isOwnerBoundaryPending: () => true,
+ });
+ await expect(
+ boundaryBlocked.generateImage({ model: 'xai/grok-imagine-image', prompt: 'p' }),
+ ).rejects.toThrow('账号正在切换');
+ expect(getAccessToken).not.toHaveBeenCalled();
+
+ await expect(
+ channel(doFetch).editImage({
+ model: 'xai/grok-imagine-image',
+ prompt: 'p',
+ imagePaths: ['1', '2', '3', '4'],
+ }),
+ ).rejects.toThrow('最多支持 3 张');
+ expect(doFetch).not.toHaveBeenCalled();
+
+ const onAuthRejected = vi.fn(async () => 'refreshed');
+ const rejectedFetch = vi.fn<typeof fetch>(
+ async () =>
+ new Response(
+ JSON.stringify({
+ code: 'unauthenticated:bad-credentials',
+ error: { message: 'rejected' },
+ }),
+ { status: 403 },
+ ),
+ );
+ await expect(
+ channel(rejectedFetch, { onAuthRejected }).generateImage({
+ model: 'xai/grok-imagine-image',
+ prompt: 'p',
+ }),
+ ).rejects.toThrow('HTTP 403');
+ expect(onAuthRejected).toHaveBeenCalledWith(
+ expect.objectContaining({
+ status: 403,
+ failedAccessToken: 'grok-oauth-token',
+ }),
+ );
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/cindySlot.ts b/apps/desktop/src/main/cindy-brain/cindySlot.ts
index 1d952f7cbb..e18da9e0fd 100644
--- a/apps/desktop/src/main/cindy-brain/cindySlot.ts
+++ b/apps/desktop/src/main/cindy-brain/cindySlot.ts
@@ -105,8 +105,17 @@ export interface CindyVideoCapabilities {
maxImagesByRefMode?: Readonly<Partial<Record<GhostVideoRefMode, number>>>;
}
+/** 某个图像型号的 provider 实际编辑能力,用于通用 1–4 图契约的二次校验。 */
+export interface CindyImageCapabilities {
+ maxEditImages?: number;
+}
+
export interface CindySlotDeps {
getGhost(id: string): InstalledGhost | null;
+ /** 当前账号作用域;跨 await 的媒体任务必须捕获并持续复核。 */
+ getOwnerScopeKey(): string;
+ /** true 表示账号运行时正在 teardown / replacement,所有新旧任务均 fail closed。 */
+ isOwnerBoundaryPending(): boolean;
/** 主机统一图片通道(art 底层客户端);返回图片字节与 mime。
* aspectRatio 是意识的画幅意图,注入实现负责翻译成后端具体尺寸。 */
generateImage(params: {
@@ -122,6 +131,11 @@ export interface CindySlotDeps {
imagePaths: string[];
aspectRatio?: GhostImageAspectRatio;
}): Promise<{ buffer: Uint8Array; mimeType: string }>;
+ /**
+ * 该图像型号的 provider 实际能力。缺席/查无 = 只执行通用 1–4 图粗筛;
+ * provider 上限更低时,slot 在读源图与出网前给出型号级明确拒绝。
+ */
+ imageCapabilities?(model: string): CindyImageCapabilities | null;
/**
* 主机统一视频通道·文生视频(art 视频 provider 层复用,submit→
* 轮询→下载一条龙在注入实现里完成);返回视频字节与 mime,外加实际
@@ -154,8 +168,10 @@ export interface CindySlotDeps {
/**
* 指纹 → 磁盘路径,且仅当该媒体在此意识名下(出生或画廊,查账本);
* 不属于它 / 查无此账 / 文件缺失一律 null(不区分,不给探测空间)。
+ * ownerScopeKey 是任务受理时捕获的稳定作用域;宿主须锁定同一 DB,并在
+ * 每个查询 await 边界复核,禁止通过动态 defaultDb 跨到新账号。
*/
- resolveOwnedMedia(ghostId: string, hash: string): Promise<string | null>;
+ resolveOwnedMedia(ghostId: string, hash: string, ownerScopeKey: string): Promise<string | null>;
/**
* 意识专属后端覆盖(解析表第②层,用户在意识详情页钉的);无覆盖返回
* null。capability 为能力键(image.generate / video.edit …);返回值仍过
@@ -181,6 +197,8 @@ export interface CindySlotDeps {
ghostId: string;
buffer: Uint8Array;
mimeType: string;
+ /** 任务受理时捕获的账号作用域;宿主须在每个持久化 await 边界复核。 */
+ ownerScopeKey: string;
/** 人类可读备注(记进账本 label,画廊 caption 用)。 */
label?: string;
/** tool-call callId(记入 ghostMediaLedger 供 ghost_call 收口带回)。 */
@@ -670,6 +688,17 @@ export class GhostCindySlot {
hashes = p.hashes as string[];
}
+ if (kind === 'edit_image') {
+ const perModelMax = this.deps.imageCapabilities?.(model)?.maxEditImages;
+ if (perModelMax !== undefined && hashes.length > perModelMax) {
+ const label = cfg.models.find((m) => m.id === model)?.label ?? model;
+ return {
+ ok: false,
+ message: `模型「${label}」最多支持 ${perModelMax} 张源图(本次 ${hashes.length} 张)`,
+ };
+ }
+ }
+
// 参考图用法与张数按**解析出的型号**二次校验:两种用法在不同型号上是
// 不同的上游模型(如 happyhorse 首尾帧走 i2v、参考图走 r2v),支持集和
// 张数上限都不一样。不支持即明拒,不降级成另一种用法——降级会出一条
@@ -707,6 +736,18 @@ export class GhostCindySlot {
// 异步受理成功后名额转交后台任务,由它的收尾释放;其余路径 finally 释放。
let backgrounded = false;
try {
+ if (this.deps.isOwnerBoundaryPending()) {
+ throw new Error('媒体任务期间账号正在切换,请稍后重试');
+ }
+ const ownerScopeKey = this.deps.getOwnerScopeKey();
+ const assertOwnerScopeCurrent = (): void => {
+ if (
+ this.deps.isOwnerBoundaryPending() ||
+ this.deps.getOwnerScopeKey() !== ownerScopeKey
+ ) {
+ throw new Error('媒体任务期间账号已切换,本次结果已丢弃');
+ }
+ };
// 日志口径:发生的事件是"一单 cindy 代办"(kind = 代办类型),槽只是
// 资格概念不进文案;归因三件套 ghostId / kind / callId 三处日志一致。
this.deps.log?.info(`ghost cindy-request ${kind} start`, {
@@ -720,7 +761,8 @@ export class GhostCindySlot {
// (统一话术不泄露细节)。异步模式也在受理期同步校验,拒绝立即可见。
const imagePaths: string[] = [];
for (const hash of hashes) {
- const abs = await this.deps.resolveOwnedMedia(ghostId, hash);
+ const abs = await this.deps.resolveOwnedMedia(ghostId, hash, ownerScopeKey);
+ assertOwnerScopeCurrent();
if (!abs) {
return { ok: false, message: '源图不在本意识名下(仅能改自己生成或画廊里的媒体)' };
}
@@ -739,6 +781,7 @@ export class GhostCindySlot {
height?: number;
videoParams?: GhostVideoResultParams;
}> => {
+ assertOwnerScopeCurrent();
// 可选参数一律条件展开:不传时载荷里连键都没有,与老协议逐字节同形
// (videoParams 本身就是按此规则组装的,直接摊开即可)。
let generated: { buffer: Uint8Array; mimeType: string; videoParams?: GhostVideoResultParams };
@@ -760,16 +803,19 @@ export class GhostCindySlot {
} else {
generated = await this.deps.generateVideo({ prompt, model, ...videoParams });
}
+ assertOwnerScopeCurrent();
const saved = await this.deps.saveGhostMedia({
ghostId,
buffer: generated.buffer,
mimeType: generated.mimeType,
+ ownerScopeKey,
label: prompt.slice(0, 200),
// 模型代办产物记账(ghostMediaLedger),随 ghost_call 收口带回;
// 未署名('unattributed')不记,与 networkSlot 同契约防并发串账
...(callId !== 'unattributed' ? { callId } : {}),
});
+ assertOwnerScopeCurrent();
this.deps.log?.info(`ghost cindy-request ${kind} done`, {
ghostId,
model,
diff --git a/apps/desktop/src/main/cindy-brain/imageChannelRegistry.ts b/apps/desktop/src/main/cindy-brain/imageChannelRegistry.ts
index 88fba94551..4f8ad470da 100644
--- a/apps/desktop/src/main/cindy-brain/imageChannelRegistry.ts
+++ b/apps/desktop/src/main/cindy-brain/imageChannelRegistry.ts
@@ -52,6 +52,12 @@ export function decodeImageResponse(res: ImageChannelResult): { buffer: Buffer;
export interface ImageChannel {
/** 执行凭证是否就绪。false ⇒ 该来源整段不进 cindy 白名单。 */
ready(): boolean;
+ /**
+ * 单次图像编辑可接收的源图上限。省略 = 沿用 cindy slot 的通用上限;
+ * provider 上限更低时在这里声明,让 slot 在读文件、取凭证、出网前按
+ * 已选模型明拒,而不是等深层客户端报错。
+ */
+ maxEditImages?: number;
/**
* 该来源是否支持图像编辑(editImage)。
* 省略视为 true;仅生成来源(xAI 等)显式设为 false 以从编辑清单排除,
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 730f36b7f0..681b14653d 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -29,6 +29,7 @@ import {
} from '../../shared/ghost.js';
import { getAppCapabilities } from '../appCapabilities.js';
import {
+ activeOwnerScopeKey,
getActiveAppSession,
isAppSessionBoundaryPending,
ownerScopedUserDataPath,
@@ -137,6 +138,7 @@ import { submitAndAwaitVideo } from '../cindy-proxy-media/video/run.js';
import { deriveCindyMediaConfig, type CindyMediaCatalogConfig } from './cindyMediaCatalog.js';
import {
GhostCindySlot,
+ type CindyImageCapabilities,
type CindyVideoCapabilities,
type CindyVideoParams,
} from './cindySlot.js';
@@ -180,6 +182,8 @@ 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 { 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';
import { outboundFetch } from '../maker-host/outbound-fetch.js';
@@ -203,6 +207,7 @@ import {
loadGhostRecentIds,
markGhostRecentlyUsed,
} from './ghostRecentUsageStore.js';
+import { createXaiImageChannel } from './xaiImageClient.js';
import { getCindyProxyMediaService } from '../mcp-integrations/cindyProxyMedia.js';
import { ImageChannelRegistry, decodeImageResponse } from './imageChannelRegistry.js';
import { createGeminiImageChannel } from './geminiImageClient.js';
@@ -1910,6 +1915,15 @@ function getGhostVideoCapabilities(model: string): CindyVideoCapabilities | null
}
}
+/** 图像 provider 的型号级编辑上限;slot 用它在文件 IO / 凭证读取前早拒。 */
+function getGhostImageCapabilities(model: string): CindyImageCapabilities | null {
+ try {
+ return { maxEditImages: resolveImageChannelForModel(model, 'edit').maxEditImages };
+ } catch {
+ return null;
+ }
+}
+
/**
* 意识画幅意图 → XD Gateway size。三档尺寸是 gpt-image 系的原生枚举
* (1024x1024 / 1536x1024 / 1024x1536,比例即枚举名);Gemini 系由网关按
@@ -1950,6 +1964,15 @@ function getImageChannelRegistry(): ImageChannelRegistry {
...(aspectRatio ? { size: GHOST_ASPECT_TO_GATEWAY_SIZE[aspectRatio] } : {}),
}),
});
+ registry.register('xai', createXaiImageChannel({
+ hasOAuthLogin: () => hasGrokOAuthLogin(),
+ getAccessToken: () => getGrokAccessToken(),
+ getOwnerScopeKey: () => activeOwnerScopeKey(),
+ isOwnerBoundaryPending: () => isAppSessionBoundaryPending(),
+ fetchImplementation: ((url, init) => outboundFetch(url as string, init)) as typeof fetch,
+ beforeDispatch: (model) => assertMediaModelStillEnabled('image', model),
+ onAuthRejected: (failure) => invalidateXaiBridgeAuth(failure),
+ }));
// Gemini(BYO API key,generateContent wire):ready = key 已配置。停用轴
// 派发前重查经 beforeDispatch 注入(与 xd 通道的 cindyProxyMedia beforeDispatch
// 同语义 —— xd 的挂在网关客户端装配处,gemini 的挂在这里)。
@@ -2041,6 +2064,8 @@ export function getGhostCindySlot(): GhostCindySlot {
if (!cindySlotSingleton) {
cindySlotSingleton = new GhostCindySlot({
getGhost: (id) => findAvailableGhost(id),
+ getOwnerScopeKey: () => activeOwnerScopeKey(),
+ isOwnerBoundaryPending: () => isAppSessionBoundaryPending(),
// model 已在 modelSlot 按白名单校验;归属来源(providerId)按白名单条目
// 定位,经 imageChannelRegistry 取对应执行通道(2026-07 图像多来源)。
generateImage: async ({ prompt, model, aspectRatio }) => {
@@ -2099,6 +2124,7 @@ export function getGhostCindySlot(): GhostCindySlot {
}
},
// 画面参数按型号二次校验的数据源(registry capabilities)。
+ imageCapabilities: getGhostImageCapabilities,
videoCapabilities: getGhostVideoCapabilities,
getOverride: (ghostId, capability) => {
return readGhostCindyOverrides(ghostId)[capability as CindyCapabilityKey] ?? null;
@@ -2158,38 +2184,68 @@ export function getGhostCindySlot(): GhostCindySlot {
return null;
}
},
- resolveOwnedMedia: async (ghostId, hash) => {
+ resolveOwnedMedia: async (ghostId, hash, ownerScopeKey) => {
+ const assertOwnerScopeCurrent = (): void => {
+ if (
+ isAppSessionBoundaryPending() ||
+ activeOwnerScopeKey() !== ownerScopeKey
+ ) {
+ throw new Error('媒体任务期间账号已切换,本次结果已丢弃');
+ }
+ };
// 归属(账本)→ 落盘元数据(账本)→ 磁盘路径(指纹仓校验),
- // 任一环查无即 null;modelSlot 对外统一话术不泄露差异。
- if (!(await ledger.ghostCanRead(hash, ghostId))) return null;
- const info = await ledger.getBlobInfo(hash);
+ // 任一环查无即 null;modelSlot 对外统一话术不泄露差异。defaultDb
+ // 会随账号动态变化,因此先在稳定 scope 下捕获一次 DB,并让两次查询
+ // 始终复用它;每个 await 后再 fail closed,绝不读取新账号账本。
+ assertOwnerScopeCurrent();
+ const db = getDbClient().drizzle;
+ const canRead = await ledger.ghostCanRead(hash, ghostId, db);
+ assertOwnerScopeCurrent();
+ if (!canRead) return null;
+ const info = await ledger.getBlobInfo(hash, db);
+ assertOwnerScopeCurrent();
if (!info) return null;
+ let absPath: string;
try {
- return blobStore.resolveHashRef(hash, info.ext).absPath;
+ absPath = blobStore.resolveHashRef(hash, info.ext).absPath;
} catch {
return null;
}
+ assertOwnerScopeCurrent();
+ return absPath;
},
- saveGhostMedia: async ({ ghostId, buffer, mimeType, label, callId }) => {
- const written = await blobStore.writeBlob({ buffer, mimeType });
- await ledger.recordBlob({
- hash: written.hash,
- ext: written.ext,
- mimeType: written.mimeType,
- bytes: written.bytes,
- isCache: false,
- });
- // 意识产物挂自己画廊 ref(出生=该意识)——面板归属校验与
- // "不被回收"同时成立;消息级引用由消息落库链路维护,
- // 配额上限由权限策略负责。
- await ledger.addRef({
- hash: written.hash,
- refKind: 'ghost-gallery',
- refId: ghostId,
- originKind: 'ghost',
- originId: ghostId,
- ...(label ? { label } : {}),
- });
+ saveGhostMedia: async ({ ghostId, buffer, mimeType, ownerScopeKey, label, callId }) => {
+ const assertOwnerScopeCurrent = (): void => {
+ if (
+ isAppSessionBoundaryPending() ||
+ activeOwnerScopeKey() !== ownerScopeKey
+ ) {
+ throw new Error('媒体任务期间账号已切换,本次结果已丢弃');
+ }
+ };
+ // defaultDb 会在每次 ledger 调用时现取当前账号 DB。先在稳定 scope 下
+ // 捕获同一个句柄,再把失效断言交给统一入库助手覆盖所有 await 边界,
+ // 防止旧账号产物在切号窗口被登记到新账号画廊。
+ assertOwnerScopeCurrent();
+ const db = getDbClient().drizzle;
+ const written = await ingestMedia(
+ {
+ buffer,
+ mimeType,
+ isCache: false,
+ refs: [
+ {
+ refKind: 'ghost-gallery',
+ refId: ghostId,
+ originKind: 'ghost',
+ originId: ghostId,
+ ...(label ? { label } : {}),
+ },
+ ],
+ assertStillValid: assertOwnerScopeCurrent,
+ },
+ db,
+ );
recordGhostCallMedia(ghostId, callId, written.url);
return { url: written.url, hash: written.hash, ext: written.ext };
},
diff --git a/apps/desktop/src/main/cindy-brain/xaiImageClient.ts b/apps/desktop/src/main/cindy-brain/xaiImageClient.ts
new file mode 100644
index 0000000000..2b0977f4ea
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/xaiImageClient.ts
@@ -0,0 +1,238 @@
+/**
+ * xAI Imagine image channel backed by the user's existing SuperGrok OAuth login.
+ *
+ * The OAuth bearer used by the xAI agent bridge also works on the OpenAI-compatible
+ * Imagine endpoints. Credentials stay in Main; local source images are sent as data
+ * URIs and the response is normalized to ImageChannelResult.
+ */
+
+import fs from 'node:fs/promises';
+
+import type { GhostImageAspectRatio } from '../../shared/ghost.js';
+import { sniffMediaMime } from '../cindy-media/sniffMediaMime.js';
+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;
+
+interface XaiImageResponse {
+ data?: Array<{
+ b64_json?: string;
+ url?: string;
+ mime_type?: string;
+ }>;
+ error?: { message?: string };
+}
+
+export interface CreateXaiImageChannelOptions {
+ hasOAuthLogin(): boolean;
+ getAccessToken(): Promise<string>;
+ getOwnerScopeKey(): string;
+ isOwnerBoundaryPending(): boolean;
+ fetchImplementation?: typeof fetch;
+ /** 测试/宿主可收紧下载上限,但不能放宽生产硬顶。 */
+ maxImageDownloadBytes?: number;
+ beforeDispatch?(model: string): void;
+ onAuthRejected?(failure: {
+ status: number;
+ body: string;
+ failedAccessToken: string;
+ }): Promise<unknown>;
+}
+
+function upstreamModelId(catalogId: string): string {
+ return catalogId.startsWith('xai/') ? catalogId.slice('xai/'.length) : catalogId;
+}
+
+async function sourceImage(path: string): Promise<{ type: 'image_url'; url: string }> {
+ const bytes = await fs.readFile(path);
+ const mime = sniffMediaMime(bytes);
+ if (!mime || !['image/png', 'image/jpeg', 'image/gif', 'image/webp'].includes(mime)) {
+ throw new Error(`xAI 参考图格式不支持:${mime ?? '未知格式'}`);
+ }
+ return { type: 'image_url', url: `data:${mime};base64,${bytes.toString('base64')}` };
+}
+
+function parseResponse(text: string): XaiImageResponse {
+ try {
+ return JSON.parse(text) as XaiImageResponse;
+ } catch {
+ throw new Error('xAI 图像通道返回了无效响应');
+ }
+}
+
+function assertXaiImageUrl(raw: string): string {
+ let url: URL;
+ try {
+ url = new URL(raw);
+ } catch {
+ throw new Error('xAI 图像通道返回了不可信的图片地址');
+ }
+ if (url.protocol !== 'https:' || !(url.hostname === 'x.ai' || url.hostname.endsWith('.x.ai'))) {
+ throw new Error('xAI 图像通道返回了不可信的图片地址');
+ }
+ return url.toString();
+}
+
+function captureOwnerScope(opts: CreateXaiImageChannelOptions): string {
+ if (opts.isOwnerBoundaryPending()) {
+ throw new Error('xAI 图片请求期间账号正在切换,请稍后重试');
+ }
+ return opts.getOwnerScopeKey();
+}
+
+function assertOwnerScopeCurrent(opts: CreateXaiImageChannelOptions, expected: string): void {
+ if (opts.isOwnerBoundaryPending() || opts.getOwnerScopeKey() !== expected) {
+ throw new Error('xAI 图片请求期间账号已切换,请重试');
+ }
+}
+
+async function readBoundedImageResponse(
+ 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 {
+ // 超限、账号切换或流异常时立即断开上游;正常读完时 cancel 是 no-op。
+ await reader.cancel().catch(() => undefined);
+ reader.releaseLock();
+ }
+ return Buffer.concat(chunks, total);
+}
+
+export function createXaiImageChannel(opts: CreateXaiImageChannelOptions): ImageChannel {
+ const doFetch = opts.fetchImplementation ?? fetch;
+ const requestedDownloadLimit = opts.maxImageDownloadBytes;
+ const maxImageDownloadBytes =
+ typeof requestedDownloadLimit === 'number' &&
+ Number.isSafeInteger(requestedDownloadLimit) &&
+ requestedDownloadLimit > 0
+ ? Math.min(requestedDownloadLimit, MAX_IMAGE_DOWNLOAD_BYTES)
+ : MAX_IMAGE_DOWNLOAD_BYTES;
+
+ async function call(params: {
+ model: string;
+ prompt: string;
+ aspectRatio?: GhostImageAspectRatio;
+ imagePaths?: string[];
+ }): Promise<ImageChannelResult> {
+ const paths = params.imagePaths ?? [];
+ if (paths.length > MAX_EDIT_SOURCES) {
+ throw new Error(`xAI 图像编辑最多支持 ${MAX_EDIT_SOURCES} 张源图`);
+ }
+ // 先在任何凭证刷新或本地文件读取之前拦截已停用模型;后面的二次检查
+ // 继续覆盖准备请求期间发生的配置变化。
+ opts.beforeDispatch?.(params.model);
+ // OAuth token 与源图都属于当前数据 owner。任务跨 await 后必须仍在同一稳定
+ // owner scope,不能把 A 的 token 或图片派发进 B 的运行时。
+ const ownerScopeKey = captureOwnerScope(opts);
+ const [token, images] = await Promise.all([
+ opts.getAccessToken(),
+ Promise.all(paths.map(sourceImage)),
+ ]);
+ const isEdit = images.length > 0;
+ const body: Record<string, unknown> = {
+ model: upstreamModelId(params.model),
+ prompt: params.prompt,
+ response_format: 'b64_json',
+ resolution: '1k',
+ ...(params.aspectRatio ? { aspect_ratio: params.aspectRatio } : {}),
+ };
+ if (isEdit) {
+ if (images.length === 1) body.image = images[0];
+ else body.images = images;
+ }
+
+ opts.beforeDispatch?.(params.model);
+ assertOwnerScopeCurrent(opts, ownerScopeKey);
+ const response = await doFetch(`${XAI_API_BASE}/images/${isEdit ? 'edits' : 'generations'}`, {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ Accept: 'application/json',
+ },
+ body: JSON.stringify(body),
+ });
+ const responseText = await response.text();
+ assertOwnerScopeCurrent(opts, ownerScopeKey);
+ if (!response.ok) {
+ if ((response.status === 401 || response.status === 403) && opts.onAuthRejected) {
+ await opts
+ .onAuthRejected({
+ status: response.status,
+ body: responseText.slice(0, 8 * 1024),
+ failedAccessToken: token,
+ })
+ .catch(() => undefined);
+ }
+ const parsed = (() => {
+ try {
+ return JSON.parse(responseText) as XaiImageResponse;
+ } catch {
+ return null;
+ }
+ })();
+ const detail = parsed?.error?.message ?? (responseText.slice(0, 500) || '未知错误');
+ throw new Error(`xAI 图像请求失败(HTTP ${response.status}):${detail}`);
+ }
+
+ const parsed = parseResponse(responseText);
+ const first = parsed.data?.[0];
+ if (first?.b64_json) {
+ return {
+ data: [{ b64_json: first.b64_json }],
+ output_format: first.mime_type?.split('/')[1] ?? 'png',
+ };
+ }
+ 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' });
+ if (!imageResponse.ok) {
+ throw new Error(`xAI 图片下载失败(HTTP ${imageResponse.status})`);
+ }
+ const bytes = await readBoundedImageResponse(
+ imageResponse,
+ maxImageDownloadBytes,
+ () => assertOwnerScopeCurrent(opts, ownerScopeKey),
+ );
+ const mime = sniffMediaMime(bytes);
+ if (!mime?.startsWith('image/')) throw new Error('xAI 图片下载结果不是有效图片');
+ return { data: [{ b64_json: bytes.toString('base64') }], output_format: mime.split('/')[1] };
+ }
+ throw new Error('xAI 图像通道未返回图片');
+ }
+
+ return {
+ ready: opts.hasOAuthLogin,
+ maxEditImages: MAX_EDIT_SOURCES,
+ generateImage: ({ model, prompt, aspectRatio }) => call({ model, prompt, aspectRatio }),
+ editImage: ({ model, prompt, imagePaths, aspectRatio }) =>
+ call({ model, prompt, imagePaths, aspectRatio }),
+ };
+}
diff --git a/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts b/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts
index 0d46716899..ea2e8648de 100644
--- a/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts
+++ b/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts
@@ -168,6 +168,38 @@ describe('ingestMedia(崩溃语义:先字节后记账)', () => {
).rejects.toThrow();
expect(fs.existsSync(blobPathOf(hash, '.png'))).toBe(true);
});
+
+ it('作用域断言在记账后失效时停止挂引用', async () => {
+ let checks = 0;
+ await expect(
+ ingest.ingestMedia(
+ {
+ buffer: PNG_BYTES,
+ mimeType: 'image/png',
+ refs: [{ refKind: 'ghost-gallery', refId: 'art' }],
+ assertStillValid: () => {
+ checks += 1;
+ if (checks === 3) throw new Error('owner scope changed');
+ },
+ },
+ db,
+ ),
+ ).rejects.toThrow('owner scope changed');
+
+ expect(db.select().from(schema.mediaBlobs).all()).toHaveLength(1);
+ expect(db.select().from(schema.mediaRefs).all()).toHaveLength(0);
+ });
+
+ it('启用作用域断言时必须显式捕获数据库句柄', async () => {
+ await expect(
+ ingest.ingestMedia({
+ buffer: PNG_BYTES,
+ mimeType: 'image/png',
+ refs: [],
+ assertStillValid: () => undefined,
+ }),
+ ).rejects.toThrow('requires an explicit database');
+ });
});
describe('ingestMedia(白名单外拒绝)', () => {
diff --git a/apps/desktop/src/main/cindy-media/ingest.ts b/apps/desktop/src/main/cindy-media/ingest.ts
index 8c7bd1084c..5dcf4f4987 100644
--- a/apps/desktop/src/main/cindy-media/ingest.ts
+++ b/apps/desktop/src/main/cindy-media/ingest.ts
@@ -44,6 +44,12 @@ export interface IngestMediaParams {
* 在同一逻辑事务内尽快 addRef)。
*/
refs: IngestRef[];
+ /**
+ * 跨账号/会话写入的失效闸。调用方可注入同步断言;入库助手会在第一个
+ * 副作用前及每个 await 后调用,失效即停止后续记账/挂引用并向上抛错。
+ * 启用时必须同时显式传入在稳定作用域下捕获的 db,禁止每次记账现取新作用域。
+ */
+ assertStillValid?: () => void;
}
export interface IngestedMedia {
@@ -69,10 +75,15 @@ export async function ingestMedia(
params: IngestMediaParams,
db?: LedgerDb,
): Promise<IngestedMedia> {
+ if (params.assertStillValid && !db) {
+ throw new Error('cindy-media: guarded ingest requires an explicit database');
+ }
+ params.assertStillValid?.();
const written = await blobStore.writeBlob({
buffer: params.buffer,
mimeType: params.mimeType,
});
+ params.assertStillValid?.();
await ledger.recordBlob(
{
hash: written.hash,
@@ -83,9 +94,11 @@ export async function ingestMedia(
},
db,
);
+ params.assertStillValid?.();
const refIds: string[] = [];
for (const ref of params.refs) {
refIds.push(await ledger.addRef({ hash: written.hash, ...ref }, db));
+ params.assertStillValid?.();
}
return { ...written, refIds };
}
diff --git a/packages/model-providers/catalog/providers.json b/packages/model-providers/catalog/providers.json
index 296da969be..1e34c31c39 100644
--- a/packages/model-providers/catalog/providers.json
+++ b/packages/model-providers/catalog/providers.json
@@ -16,6 +16,16 @@
"kind": "subscription",
"product": "SuperGrok"
},
+ "imageModels": [
+ {
+ "id": "xai/grok-imagine-image",
+ "name": "Grok Imagine Image"
+ },
+ {
+ "id": "xai/grok-imagine-image-quality",
+ "name": "Grok Imagine Image (Quality)"
+ }
+ ],
"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 8f3a111800..5532b14bf8 100644
--- a/packages/model-providers/src/__tests__/catalog.test.ts
+++ b/packages/model-providers/src/__tests__/catalog.test.ts
@@ -100,6 +100,13 @@ describe('bundled catalog validity (dynamic-first contract)', () => {
expect((xai.models.codex ?? []).map((m) => m.id)).toEqual(EXPECTED_XAI_IDS);
});
+ it('xai ships both Grok Imagine subscription image models', () => {
+ expect(provider('xai').imageModels).toEqual([
+ { id: 'xai/grok-imagine-image', name: 'Grok Imagine Image' },
+ { id: 'xai/grok-imagine-image-quality', name: 'Grok Imagine Image (Quality)' },
+ ]);
+ });
+
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 2ed4bef027..59e8cf05c5 100644
--- a/packages/model-providers/src/__tests__/source-registry.test.ts
+++ b/packages/model-providers/src/__tests__/source-registry.test.ts
@@ -29,7 +29,7 @@ import {
effectiveSourceIdForModel,
resolveRoute,
} from '../registry.js';
-import type { Catalog, CatalogModel } from '../types.js';
+import type { Catalog, CatalogModel, Provider } from '../types.js';
const MINIMAL: Catalog = {
version: 'test',
@@ -145,6 +145,91 @@ describe('mergeWithBundled', () => {
expect(mergeWithBundled(primary).providers.find((p) => p.id === 'anthropic')?.access).toEqual({ kind: 'api' });
});
+ it('旧远端未声明媒体能力时继承 bundled;显式空清单仍可停用', () => {
+ const bundledXai = BUNDLED_CATALOG.providers.find((p) => p.id === 'xai')!;
+ const oldRemoteXai = JSON.parse(JSON.stringify(bundledXai)) as Provider;
+ delete oldRemoteXai.imageModels;
+ const inherited = mergeWithBundled({ version: '2', providers: [oldRemoteXai] });
+ expect(inherited.providers.find((p) => p.id === 'xai')?.imageModels)
+ .toEqual(bundledXai.imageModels);
+
+ const explicitlyDisabled = mergeWithBundled({
+ version: '2',
+ providers: [{ ...oldRemoteXai, imageModels: [] }],
+ });
+ expect(explicitlyDisabled.providers.find((p) => p.id === 'xai')?.imageModels).toEqual([]);
+ });
+
+ it('旧远端改变鉴权或路由形状时不继承 bundled 图像能力', () => {
+ const bundledXai = BUNDLED_CATALOG.providers.find((p) => p.id === 'xai')!;
+ const oldRemoteXai = JSON.parse(JSON.stringify(bundledXai)) as Provider;
+ delete oldRemoteXai.imageModels;
+
+ const apiKeyXai: Provider = {
+ ...oldRemoteXai,
+ auth: { method: 'apiKey' },
+ };
+ const alternateRouteXai: Provider = {
+ ...oldRemoteXai,
+ routing: {
+ ...oldRemoteXai.routing,
+ codex: {
+ ...oldRemoteXai.routing.codex!,
+ upstream: 'https://oauth-proxy.example.test',
+ },
+ },
+ };
+
+ expect(
+ mergeWithBundled({ version: '2', providers: [apiKeyXai] }).providers.find(
+ (p) => p.id === 'xai',
+ )?.imageModels,
+ ).toBeUndefined();
+ expect(
+ mergeWithBundled({ version: '2', providers: [alternateRouteXai] }).providers.find(
+ (p) => p.id === 'xai',
+ )?.imageModels,
+ ).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;
+
+ for (const access of [
+ { kind: 'api' as const },
+ { kind: 'managed' as const },
+ { kind: 'subscription' as const, product: 'Another subscription' },
+ ]) {
+ expect(
+ mergeWithBundled({
+ version: '2',
+ providers: [{ ...oldRemoteXai, access }],
+ }).providers.find((p) => p.id === 'xai')?.imageModels,
+ ).toBeUndefined();
+ }
+
+ expect(
+ mergeWithBundled({
+ version: '2',
+ providers: [{ ...oldRemoteXai, access: bundledXai.access }],
+ }).providers.find((p) => p.id === 'xai')?.imageModels,
+ ).toEqual(bundledXai.imageModels);
+ });
+
+ it('非 xAI 远端条目缺少媒体字段时不从 bundled 恢复已撤下能力', () => {
+ const bundledOpenai = BUNDLED_CATALOG.providers.find((p) => p.id === 'openai')!;
+ const remoteOpenai = JSON.parse(JSON.stringify(bundledOpenai)) as Provider;
+ delete remoteOpenai.imageModels;
+
+ expect(
+ mergeWithBundled({ version: '2', providers: [remoteOpenai] }).providers.find(
+ (p) => p.id === 'openai',
+ )?.imageModels,
+ ).toBeUndefined();
+ });
+
it('does not infer bundled billing when a same-id primary changes auth or upstream', () => {
const apiKeyPrimary: Catalog = {
...MINIMAL,
diff --git a/packages/model-providers/src/source.ts b/packages/model-providers/src/source.ts
index a19008c6b2..c2fca98608 100644
--- a/packages/model-providers/src/source.ts
+++ b/packages/model-providers/src/source.ts
@@ -97,6 +97,19 @@ function legacyAccessFor(primary: Provider, bundled: Provider): Provider['access
return sameRoutes ? bundled.access : undefined;
}
+/** 图片能力只可沿用到未声明 access,或仍明确属于同一 bundled 订阅的旧条目。 */
+function allowsBundledImageInheritance(
+ primaryAccess: Provider['access'],
+ bundledAccess: Provider['access'],
+): boolean {
+ if (primaryAccess === undefined) return true;
+ if (bundledAccess === undefined || primaryAccess.kind !== bundledAccess.kind) return false;
+ return (
+ primaryAccess.kind !== 'subscription' ||
+ (bundledAccess.kind === 'subscription' && primaryAccess.product === bundledAccess.product)
+ );
+}
+
/**
* 同 id preset 仍以远端为主;bundled 只给远端仍保留的同 runtime / 同 model
* 回填缺失的 contextWindow。这样旧远端不会把已核实的长上下文元数据降级,同时远端
@@ -133,27 +146,47 @@ function backfillPresetContextWindows(
/**
* 把远端 / 本地目录与内置 bundled 合并:以输入目录为主,bundled 补它缺失的
- * provider(按 id),并给旧目录中同 id provider 补缺失的 access 元数据。primary
- * 明确提供的 access 永远优先,不被 bundled 覆盖。
+ * provider(按 id),并给旧目录中同 id provider 补缺失的 access 与图像能力元数据。
+ * primary 明确提供的值(包括显式空图像清单)永远优先,不被 bundled 覆盖。
*
* **顺序契约**:结果按 bundled 数组序稳定排列(anthropic → openai → xai → xd),
* bundled 之外的远端新增供应商按远端原序追加在后。v2 远端目录只承载 xai 段,
* 不排序的话 xai 会窜到首位,选择器分段顺序漂移。
*/
export function mergeWithBundled(primary: Catalog): Catalog {
- const byId = new Map(primary.providers.map((p) => [p.id, p]));
const bundledById = new Map(BUNDLED_CATALOG.providers.map((p) => [p.id, p]));
- const withAccess = primary.providers.map((p) => {
+ const withBundledMetadata = primary.providers.map((p) => {
const bundled = bundledById.get(p.id);
const bundledAccess = bundled ? legacyAccessFor(p, bundled) : undefined;
- return p.access === undefined && bundledAccess !== undefined ? { ...p, access: bundledAccess } : p;
+ if (!bundled) return p;
+ const inheritImage =
+ p.id === 'xai' &&
+ p.imageModels === undefined &&
+ bundled.imageModels !== undefined &&
+ bundledAccess !== undefined &&
+ allowsBundledImageInheritance(p.access, bundledAccess);
+ if (!(p.access === undefined && bundledAccess !== undefined) && !inheritImage) {
+ return p;
+ }
+ return {
+ ...p,
+ ...(p.access === undefined && bundledAccess !== undefined ? { access: bundledAccess } : {}),
+ ...(inheritImage
+ ? {
+ imageModels: bundled.imageModels,
+ ...(p.imageDefaults === undefined && bundled.imageDefaults !== undefined
+ ? { imageDefaults: bundled.imageDefaults }
+ : {}),
+ }
+ : {}),
+ };
});
- const primaryById = new Map(withAccess.map((p) => [p.id, p]));
+ const primaryById = new Map(withBundledMetadata.map((p) => [p.id, p]));
// bundled 序在前(同 id 取 primary 内容),远端独有的追加在后(保持远端原序)。
const merged: Provider[] = BUNDLED_CATALOG.providers.map(
(bundled) => primaryById.get(bundled.id) ?? bundled,
);
- for (const p of withAccess) {
+ for (const p of withBundledMetadata) {
if (!bundledById.has(p.id)) merged.push(p);
}
// presets 与 providers 同样按 id 合并:bundled 保序兜底,同 id 远端内容优先,