Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
完善认证域路由与凭证同步
DavidShenee7348fd3fe9
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 386f56dbb0..5d7924c700 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -162,6 +162,7 @@ import {storeGhostSecret,} from '../secrets/providerSecretStore.js';import { getActiveCatalog } from '../maker-host/active-catalog.js';+import { projectProviderCatalogForBuildRegion } from '../maker-host/provider-access-policy.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';@@ -1675,8 +1676,12 @@ function getCatalogMediaConfig(kind: 'image' | 'video'): CindyMediaCatalogConfig// 停用过滤:用户在 设置 → 模型供应商 停用的媒体模型 / 供应商不进候选清单// (与对话模型的准入口径同源,见 model-disable-store)。const access = readModelDisableOverrides();+ const catalog = projectProviderCatalogForBuildRegion(+ getActiveCatalog(),+ CURRENT_CINDY_REGION,+ );return deriveCindyMediaConfig(- getActiveCatalog().providers,+ catalog.providers,kind,(providerId, modelId) =>isProviderDisabled(access, providerId) ||diff --git a/apps/desktop/src/main/maker-host/__tests__/providerAccessPolicy.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerAccessPolicy.test.tsindex 6e857ebda8..7093276b5a 100644--- a/apps/desktop/src/main/maker-host/__tests__/providerAccessPolicy.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/providerAccessPolicy.test.ts@@ -6,6 +6,7 @@ import { deriveAvailableModels } from '../catalog-to-descriptors.js';import {filterProviderCatalogForAccount,isProviderSelectable,+ projectProviderCatalogForBuildRegion,} from '../provider-access-policy.js';function model(id: string): CatalogModel {@@ -31,11 +32,27 @@ function provider(id: string, models: CatalogModel[]): Provider {}function catalog(): Catalog {+ const xd = provider('xd', [model('shared-model'), model('xd-only-model')]);+ xd.imageModels = [+ { id: 'gpt-image-2', name: 'GPT Image 2' },+ { id: 'gemini-image', name: 'Gemini Image' },+ ];+ xd.imageDefaults = { standard: 'gpt-image-2', draft: 'gemini-image' };+ xd.videoModels = [+ { id: 'seedance-fast', name: 'Seedance Fast' },+ { id: 'seedance-pro', name: 'Seedance Pro' },+ { id: 'happyhorse', name: 'HappyHorse' },+ ];+ xd.videoDefaults = {+ standard: 'seedance-fast',+ draft: 'happyhorse',+ best: 'seedance-pro',+ };return {version: 'test',providers: [provider('anthropic', [model('shared-model')]),- provider('xd', [model('shared-model'), model('xd-only-model')]),+ xd,],};}@@ -62,4 +79,28 @@ describe('provider access policy', () => {expect(filterProviderCatalogForAccount(input, { canUseCindyGateway: true })).toBe(input);expect(filterProviderCatalogForAccount(input, {})).toBe(input);});++ it('preserves the full media catalog and object identity for Global', () => {+ const input = catalog();+ expect(projectProviderCatalogForBuildRegion(input, 'global')).toBe(input);+ });++ it.each(['cn', 'dev'] as const)(+ 'projects the Cindy AI media catalog to Mainland capabilities for %s',+ (region) => {+ const projected = projectProviderCatalogForBuildRegion(catalog(), region);+ const xd = projected.providers.find((item) => item.id === 'xd');++ expect(xd?.imageModels).toEqual([]);+ expect(xd?.imageDefaults).toBeUndefined();+ expect(xd?.videoModels?.map((item) => item.id)).toEqual([+ 'seedance-fast',+ 'seedance-pro',+ ]);+ expect(xd?.videoDefaults).toEqual({+ standard: 'seedance-fast',+ best: 'seedance-pro',+ });+ },+ );});diff --git a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts b/apps/desktop/src/main/maker-host/createDesktopProviderService.tsindex 7771b6c389..eb1a4c798a 100644--- a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts+++ b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts@@ -72,8 +72,12 @@ import {} from './grok-oauth-login.js';import { getAuthState } from '../authManager.js';import { getActiveAppSession } from '../appSessionState.js';-import { filterProviderCatalogForAccount } from './provider-access-policy.js';+import {+ filterProviderCatalogForAccount,+ projectProviderCatalogForBuildRegion,+} from './provider-access-policy.js';import { getAppCapabilities } from '../appCapabilities.js';+import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';import {claimDetectedNativeProviderAuth,migrateLegacyNativeProviderAuthBindings,@@ -432,7 +436,11 @@ let singleton: ProviderService | null = null;* Cindy account session keeps the full active catalog.*/export function getDesktopSelectableCatalog(): Catalog {- return filterProviderCatalogForAccount(getActiveCatalog(), {+ const regionCatalog = projectProviderCatalogForBuildRegion(+ getActiveCatalog(),+ CURRENT_CINDY_REGION,+ );+ return filterProviderCatalogForAccount(regionCatalog, {canUseCindyGateway: getAppCapabilities().canUseCindyGateway,});}diff --git a/apps/desktop/src/main/maker-host/provider-access-policy.ts b/apps/desktop/src/main/maker-host/provider-access-policy.tsindex aefeae61b5..73e2545d37 100644--- a/apps/desktop/src/main/maker-host/provider-access-policy.ts+++ b/apps/desktop/src/main/maker-host/provider-access-policy.ts@@ -5,7 +5,8 @@* providers and models exposed as selectable capabilities to product surfaces.*/-import type { Catalog } from '@cindy/model-providers';+import type { Catalog, Provider } from '@cindy/model-providers';+import type { CindyRegion } from '@cindy/maker-shared/brand-identity';export interface ProviderAccessContext {/** False for account-free local sessions, in every build flavor. */@@ -13,6 +14,57 @@ export interface ProviderAccessContext {}const CINDY_AI_PROVIDER_ID = 'xd';+const MAINLAND_VIDEO_MODEL_IDS: ReadonlySet<string> = new Set([+ 'seedance-fast',+ 'seedance-pro',+]);++function projectVideoDefaults(+ defaults: Provider['videoDefaults'],+ allowedIds: ReadonlySet<string>,+): Provider['videoDefaults'] | undefined {+ if (!defaults || !allowedIds.has(defaults.standard)) return undefined;+ return {+ standard: defaults.standard,+ ...(defaults.draft && allowedIds.has(defaults.draft) ? { draft: defaults.draft } : {}),+ ...(defaults.best && allowedIds.has(defaults.best) ? { best: defaults.best } : {}),+ };+}++/**+ * Build-region projection for the Cindy AI media catalog. Global keeps the+ * catalog source verbatim; Mainland China and dev share the Mainland product+ * semantics and expose only the media capabilities supported there.+ */+export function projectProviderCatalogForBuildRegion(+ catalog: Catalog,+ region: CindyRegion,+): Catalog {+ if (region === 'global') return catalog;++ let changed = false;+ const providers = catalog.providers.map((provider) => {+ if (provider.id !== CINDY_AI_PROVIDER_ID) return provider;+ changed = true;++ const videoModels = (provider.videoModels ?? []).filter((model) =>+ MAINLAND_VIDEO_MODEL_IDS.has(model.id),+ );+ const videoIds = new Set(videoModels.map((model) => model.id));+ const videoDefaults = projectVideoDefaults(provider.videoDefaults, videoIds);+ const projected: Provider = {+ ...provider,+ imageModels: [],+ videoModels,+ };+ delete projected.imageDefaults;+ delete projected.videoDefaults;+ if (videoDefaults) projected.videoDefaults = videoDefaults;+ return projected;+ });++ return changed ? { ...catalog, providers } : catalog;+}/** Cindy AI requires a Cindy account session; every membership kind may select it. */export function isProviderSelectable(providerId: string, context: ProviderAccessContext): boolean {diff --git a/apps/desktop/src/main/model-access/__tests__/authSessionIdentity.test.ts b/apps/desktop/src/main/model-access/__tests__/authSessionIdentity.test.tsnew file mode 100644index 0000000000..a102540965--- /dev/null+++ b/apps/desktop/src/main/model-access/__tests__/authSessionIdentity.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';++import { hasAuthSessionIdentityChanged } from '../authSessionIdentity';++describe('hasAuthSessionIdentityChanged', () => {+ it('treats user or realm changes as an authentication boundary', () => {+ expect(+ hasAuthSessionIdentityChanged(+ { userId: 'user-a', realm: 'cn' },+ { userId: 'user-b', realm: 'cn' },+ ),+ ).toBe(true);+ expect(+ hasAuthSessionIdentityChanged(+ { userId: 'user-a', realm: 'cn' },+ { userId: 'user-a', realm: 'global' },+ ),+ ).toBe(true);+ });++ it('does not treat the first known identity or an unchanged identity as a switch', () => {+ expect(+ hasAuthSessionIdentityChanged(+ { userId: null, realm: null },+ { userId: 'user-a', realm: 'cn' },+ ),+ ).toBe(false);+ expect(+ hasAuthSessionIdentityChanged(+ { userId: 'user-a', realm: 'cn' },+ { userId: 'user-a', realm: 'cn' },+ ),+ ).toBe(false);+ });+});diff --git a/apps/desktop/src/main/model-access/__tests__/credentialsSync.test.ts b/apps/desktop/src/main/model-access/__tests__/credentialsSync.test.tsindex fe6092b498..6d7933b4c2 100644--- a/apps/desktop/src/main/model-access/__tests__/credentialsSync.test.ts+++ b/apps/desktop/src/main/model-access/__tests__/credentialsSync.test.ts@@ -284,6 +284,34 @@ describe('credentialsSync', () => {expect(h.store.getServerEndpoint()).toBe('https://tenant-b.test.invalid');});+ it('同账号跨区作废旧 realm 的在途响应,并从新 realm 重新同步', async () => {+ const h = makeHarness();+ const resolvers: Array<(v: CredentialsPayload) => void> = [];+ h.fetchMock.mockImplementation(+ () => new Promise<CredentialsPayload>((resolve) => resolvers.push(resolve)),+ );++ h.sync.handleAuthChange({ isAuthenticated: true, userId: 'user-a', realm: 'cn' });+ await Promise.resolve();+ expect(h.fetchMock).toHaveBeenCalledTimes(1);++ h.sync.handleAuthChange({ isAuthenticated: true, userId: 'user-a', realm: 'global' });+ await Promise.resolve();+ expect(h.fetchMock).toHaveBeenCalledTimes(2);++ resolvers[0]({ endpoint: 'https://cn.test.invalid', apiKey: 'sk-cn' });+ await Promise.resolve();+ await Promise.resolve();+ expect(h.written).toEqual([]);++ resolvers[1]({ endpoint: 'https://global.test.invalid', apiKey: 'sk-global' });+ await vi.waitFor(() => {+ expect(h.sync.getStatus().state).toBe('ok');+ });+ expect(h.written).toEqual(['sk-global']);+ expect(h.store.getServerEndpoint()).toBe('https://global.test.invalid');+ });+it('登录触发 handleAuthChange(true) 自动同步', async () => {const h = makeHarness();h.fetchMock.mockResolvedValue({ endpoint: 'https://laxa.test.invalid', apiKey: 'sk-u1' });diff --git a/apps/desktop/src/main/model-access/authSessionIdentity.ts b/apps/desktop/src/main/model-access/authSessionIdentity.tsnew file mode 100644index 0000000000..23ccee910a--- /dev/null+++ b/apps/desktop/src/main/model-access/authSessionIdentity.ts@@ -0,0 +1,20 @@+import type { AuthRegion } from '@cindy/auth-client';++export interface AuthSessionIdentity {+ userId: string | null;+ realm: AuthRegion | null;+}++/**+ * 已建立身份的 userId 或 realm 任一变化都跨越认证边界。首次获知身份不算切换,+ * 避免初始化订阅与补读当前状态时重复作废同一轮请求。+ */+export function hasAuthSessionIdentityChanged(+ previous: AuthSessionIdentity,+ next: AuthSessionIdentity,+): boolean {+ return (+ (previous.userId !== null && next.userId !== null && previous.userId !== next.userId) ||+ (previous.realm !== null && next.realm !== null && previous.realm !== next.realm)+ );+}diff --git a/apps/desktop/src/main/model-access/credentialsSync.ts b/apps/desktop/src/main/model-access/credentialsSync.tsindex fc1bf06e33..fd0f1ed0d9 100644--- a/apps/desktop/src/main/model-access/credentialsSync.ts+++ b/apps/desktop/src/main/model-access/credentialsSync.ts@@ -1,4 +1,7 @@+import type { AuthRegion } from '@cindy/auth-client';+import type { ModelAccessStatus } from '../../shared/modelAccess.js';+import { hasAuthSessionIdentityChanged } from './authSessionIdentity.js';import type { ModelAccessCredentialsStore } from './credentialsStore.js';/**@@ -94,11 +97,14 @@ export interface CredentialsSync {rotate(): Promise<ModelAccessStatus>;/*** 登录/登出/切账号入口(authManager.onAuthStateChange)。- * userId 用于账号边界:runtime refresh 换号**不经过** isAuthenticated:false,- * 只有携带身份才能作废旧账号的在途请求(PR review P1:A 的在途凭据请求- * 不得在切到 B 后写回)。+ * userId + realm 构成身份边界:runtime refresh 换号或同账号跨区都可能+ * **不经过** isAuthenticated:false,只有携带完整身份才能作废旧请求。*/- handleAuthChange(state: { isAuthenticated: boolean; userId?: string | null }): void;+ handleAuthChange(state: {+ isAuthenticated: boolean;+ userId?: string | null;+ realm?: AuthRegion | null;+ }): void;/** 手填保存成功(safe-storage IPC 层通知):source 翻 manual。 */noteManualKeySaved(): void;/** 手填 key 被删除:清来源标记。 */@@ -114,15 +120,15 @@ export function createCredentialsSync(deps: CredentialsSyncDeps): CredentialsSynlet status: ModelAccessStatus = snapshot('idle');let inflight: Promise<ModelAccessStatus> | null = null;/**- * 认证世代号:登出/**换账号**(userId 变化)自增。所有写盘(key/endpoint/状态)- * 都以发起时捕获的世代为闸——旧账号的在途请求在世代变更后一律作废,绝不写回- * (PR review P1:runtime refresh 换号不经过 isAuthenticated:false)。+ * 认证世代号:登出、换账号或同账号跨区时自增。所有写盘(key/endpoint/状态)+ * 都以发起时捕获的世代为闸——旧身份的在途请求在世代变更后一律作废。*/let epoch = 0;/** 在途同步所属的世代;世代变更后旧 inflight 不再被复用。 */let inflightEpoch = -1;/** 当前登录身份(handleAuthChange 维护),null = 未登录/未知。 */let currentUserId: string | null = null;+ let currentRealm: AuthRegion | null = null;function snapshot(state: ModelAccessStatus['state'],@@ -269,16 +275,24 @@ export function createCredentialsSync(deps: CredentialsSyncDeps): CredentialsSynhandleAuthChange(state) {if (state.isAuthenticated) {const userId = state.userId ?? null;- if (userId !== null && currentUserId !== null && userId !== currentUserId) {- // runtime refresh 换号(A→B 不经过登出):作废 A 的在途请求与终态。+ const realm = state.realm ?? null;+ if (+ hasAuthSessionIdentityChanged(+ { userId: currentUserId, realm: currentRealm },+ { userId, realm },+ )+ ) {+ // runtime refresh 换号或同账号跨区(均可能不经过登出):作废旧请求与终态。epoch++;}if (userId !== null) currentUserId = userId;+ if (realm !== null) currentRealm = realm;void startSync().catch(() => undefined);} else {// 登出/会话失效:复位状态机(含 unsupported 终态),不动本地 key/元数据。epoch++;currentUserId = null;+ currentRealm = null;setStatus('idle');}},diff --git a/apps/desktop/src/main/model-access/index.ts b/apps/desktop/src/main/model-access/index.tsindex bbbdccdf2e..d964a9ebe2 100644--- a/apps/desktop/src/main/model-access/index.ts+++ b/apps/desktop/src/main/model-access/index.ts@@ -39,6 +39,7 @@ import {waitForModelsSyncRefresh,} from './modelsSyncRefresh.js';import { getGhostSetupChangeBus } from '../cindy-brain/ghostSetupChangeBus.js';+import { hasAuthSessionIdentityChanged } from './authSessionIdentity.js';export { isModelAccessReady } from './readiness.js';const log = createLogger('modelAccess');@@ -141,12 +142,13 @@ let modelsSyncGen = -1;/** 旧世代请求在途时新账号的补发标记。 */let modelsSyncRerunQueued = false;/**- * 认证世代:登出或 userId 变化时自增(与 credentialsSync 的 epoch 同语义)。- * 目录请求以发起时世代为闸——A 账号的在途 /models 响应在切到 B 后一律丢弃,- * 且 B 会补发自己的请求(PR review P1:旧账号目录不得覆盖新账号)。+ * 认证世代:登出或 userId / realm 变化时自增(与 credentialsSync 的 epoch 同语义)。+ * 目录请求以发起时世代为闸——旧身份的在途 /models 响应在换号或同账号跨区后+ * 一律丢弃,且新身份会补发自己的请求。*/let authGeneration = 0;let lastAuthUserId: string | null = null;+let lastAuthRealm: ReturnType<typeof authManager.getActiveAuthRealm> | null = null;function applyGatewayModels(models: ModelAccessGatewayModel[],@@ -353,24 +355,39 @@ function mapServerError(err: unknown): never {export function initModelAccess(): void {const sync = getSync();- const noteAuthState = (isAuthenticated: boolean, userId: string | null) => {- // 认证世代:登出或换号自增,作废旧账号在途的目录请求(runModelsSync 世代闸)。- if (!isAuthenticated || (userId !== null && lastAuthUserId !== null && userId !== lastAuthUserId)) {+ const noteAuthState = (+ isAuthenticated: boolean,+ userId: string | null,+ realm: ReturnType<typeof authManager.getActiveAuthRealm> | null,+ ) => {+ // 认证世代:登出、换号或同账号跨区均自增,作废旧身份在途的目录请求。+ if (+ !isAuthenticated ||+ hasAuthSessionIdentityChanged(+ { userId: lastAuthUserId, realm: lastAuthRealm },+ { userId, realm },+ )+ ) {authGeneration++;- // 旧账号模型清单不能跨账号继续显示;新账号凭据 / 模型拉取成功后再注入。+ // 旧身份模型清单不能跨账号/区域继续显示;新身份拉取成功后再注入。applyGatewayModels([]);}lastAuthUserId = isAuthenticated ? (userId ?? lastAuthUserId) : null;- sync.handleAuthChange({ isAuthenticated, userId });+ lastAuthRealm = isAuthenticated ? (realm ?? lastAuthRealm) : null;+ sync.handleAuthChange({ isAuthenticated, userId, realm });};authManager.onAuthStateChange((state) => {- noteAuthState(state.isAuthenticated, state.user?.id ?? null);+ noteAuthState(+ state.isAuthenticated,+ state.user?.id ?? null,+ state.isAuthenticated ? authManager.getActiveAuthRealm() : null,+ );});// 订阅挂载时可能已错过冷启动的首次 notify(初始化顺序取决于 bootstrap),补一次。const initial = authManager.getAuthState();if (initial.isAuthenticated) {- noteAuthState(true, initial.user?.id ?? null);+ noteAuthState(true, initial.user?.id ?? null, authManager.getActiveAuthRealm());}ipcMain.handle('model-access:get-status', () => sync.getStatus());@@ -403,5 +420,6 @@ export function resetModelAccessForTest(): void {lastModelsSyncSucceededAttempt = 0;authGeneration = 0;lastAuthUserId = null;+ lastAuthRealm = null;applyGatewayModels([]);}diff --git a/docs/auth-realm-routing.md b/docs/auth-realm-routing.mdindex c9cbf897f0..10f5ae9078 100644--- a/docs/auth-realm-routing.md+++ b/docs/auth-realm-routing.md@@ -68,6 +68,17 @@ session 被拒绝时,Desktop 仍把轮换后的 refresh token 写回原 realmMobile 的 Pending OAuth 同时保存 `realm`,但 redirect scheme 始终使用当前安装包的scheme。个人验证码和社交登录不做跨区域发现,也不合并两区 passport。+## 模型访问与媒体目录边界++Desktop 的 model-access 身份由 `(userId, sessionRealm)` 共同确定。登出、换账号或+同账号切换 realm 时,客户端立即清空旧 XD 动态模型清单,作废旧身份在途的凭据与+`/models` 响应,并从当前 realm 重新同步;迟到响应不得写回凭据或覆盖新区域模型。++XD 静态媒体能力属于 `buildRegion` 产品能力,不随组织 `sessionRealm` 跨区扩张。+Global 构建保留目录中的完整图像与视频清单;中国大陆和 dev 构建不暴露图像模型,+视频仅暴露 `seedance-fast` 与 `seedance-pro`。设置页、模型停用成员校验和 Cindy+媒体运行时都消费 main 侧同一投影策略,Renderer 不另做隐藏。+## Mobile 推送撤销Mobile 按 `sessionRealm` 分别保存推送注册与待注销状态。登出、换账号或换区域时,