Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(providers): 统一供应商管理和登录文案并修复本机断开 (#4246)
Dashebdd9049ccec
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex b114e47c8d..e1a733ad28 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -1,3 +1,4 @@+import { retainProviderPresentationAfterAuthChange } from './maker-host/provider-presentation-store.js';import { codexAccountState } from './maker-host/codex-account-auth.js';import { syncSubscriptionAccountUsage } from './usage/subscriptionAccountUsage.js';import { clearSubscriptionAccountDiscoveredModels, setSubscriptionAccountInvalidatedHandler } from './maker-host/subscription-account-auth.js';@@ -699,8 +700,8 @@ import {writeImDefaultSettingsPatch,} from './im/defaultSettingsStore.js';import { hasClaudeAiOAuth } from './maker-host/claude-credentials-store.js';-import { disconnectClaudeAiOAuth } from './maker-host/claude-oauth-refresh.js';-import { runClaudeOAuthLogin, cancelClaudeOAuthLogin } from './maker-host/claude-oauth-login.js';+import { disconnectClaudeAiOAuth, reconnectClaudeAiOAuth } from './maker-host/claude-oauth-refresh.js';+import { beginClaudeLocalLogin, cancelClaudeOAuthLogin } from './maker-host/claude-oauth-login.js';import {runGrokOAuthLogin,cancelGrokOAuthLogin,@@ -4826,7 +4827,7 @@ const registerIpcHandlers = () => {}});- // ── Claude.ai 订阅 OAuth 登录(浏览器流程,凭证落系统 ~/.claude) ────────────────+ // ── 本机 Claude Code 订阅:只管理 Cindy 的使用许可 ─────────────────────────// 与鉴权模式开关正交:管理订阅凭证本身(像 Codex 的 OAuth 登录独立于 API 模式)。// Anthropic 模型清单动态发现接线(2026-07-19 统一重构):// - active-catalog 统一收口 capabilities 刷新 + revision 广播;@@ -4835,34 +4836,35 @@ const registerIpcHandlers = () => {ipcMain.handle(MAKER_IPC_INVOKE.CLAUDE_OAUTH_STATUS, async () => {return { authorized: hasClaudeAiOAuth() };});- ipcMain.handle(MAKER_IPC_INVOKE.CLAUDE_OAUTH_LOGIN, async () => {- // 拉浏览器 OAuth;成功写凭证。失败 reason(cancelled/timeout/...)是 renderer 决定提示用的结构化- // 数据,不抛 throwIpcError(符合规则 13 查询型例外:renderer 需要 reason 做不同 UI)。- const result = await runClaudeOAuthLogin();- if (result.ok) {- resetProviderModelAutoRefreshCooldowns('anthropic');- // 登录可直接覆盖旧账号凭证,不一定先走登出。先跨授权世代清掉旧清单 / 缓存并- // 等待旧 SDK 持久化收尾;即使后续 proxy 初始化失败也绝不保留 A 账号清单。- await clearAnthropicDiscoveredModels();- // oauth 模式 per-model 路由依赖本地 proxy,确保 ready,再广播鉴权态让 Connections 行刷新。- await ensureAnthropicCompatProxyReady();- await broadcastClaudeAuthStateChanged();- // 订阅余量同步: 换号时清旧账号快照 + 拉新账号余量(内部指纹校验), chip 随 push 更新。- syncClaudeSubscriptionUsageForAuthChange();- // 模型清单动态发现:登录成功即后台拉 /v1/models(完成后经 active-catalog 广播刷新,- // 设置页无需等下次会话就能看到清单;失败保留现值,SDK 通道随后仍会精化)。- void refreshAnthropicModelsFromHttp();- return { ok: true, authorized: true };- }- return { ok: false, reason: result.reason ?? 'unknown', authorized: hasClaudeAiOAuth() };+ ipcMain.handle(MAKER_IPC_INVOKE.CLAUDE_OAUTH_LOGIN, async (event, loginKey?: string) => {+ assertTrustedAppRendererEvent(event);+ const owner = activeOwnerScopeKey();+ if (isAppSessionBoundaryPending() || !getActiveAppSession().dataOwnerId) return { ok: false, reason: 'login_cancelled', authorized: false };+ const signal = beginClaudeLocalLogin(loginKey);+ resetProviderModelAutoRefreshCooldowns('anthropic');+ await clearAnthropicDiscoveredModels();+ if (signal.aborted || owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return { ok: false, reason: 'login_cancelled', authorized: false };+ await ensureAnthropicCompatProxyReady();+ if (signal.aborted || owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return { ok: false, reason: 'login_cancelled', authorized: false };+ if (!reconnectClaudeAiOAuth()) return { ok: false, reason: 'local_unavailable', authorized: false };+ // Binding is the commit point; auxiliary refresh must not prolong the cancellable login.+ void broadcastClaudeAuthStateChanged();+ syncClaudeSubscriptionUsageForAuthChange();+ void refreshAnthropicModelsFromHttp();+ return { ok: true, authorized: hasClaudeAiOAuth() };});- ipcMain.handle(MAKER_IPC_INVOKE.CLAUDE_OAUTH_LOGOUT, async () => {- // disconnect = 先失效 host 刷新器(在途刷新不写回、预续期撤销)再清凭证 —— 直接- // clearClaudeAiOAuth 会让「已断开」后的在途刷新回写复活凭证(review 2026-07-04 P2)。- // 清除自带写后校验:写入被截断 / 校验不过会抛 —— 此时**不**广播「已断开」假成功,- // 如实抛 IPC 错误让 renderer 提示失败(规则 13)。+ ipcMain.handle(MAKER_IPC_INVOKE.CLAUDE_OAUTH_LOGOUT, async (event, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }) => {+ assertTrustedAppRendererEvent(event);+ const active = getActiveAppSession();+ const owner = activeOwnerScopeKey();+ if (isAppSessionBoundaryPending() || (ownerScope && (ownerScope.dataOwnerId !== active.dataOwnerId || ownerScope.ownerGeneration !== active.generation))) {+ throwIpcError('INVALID_PARAMS', 'Provider owner changed');+ }+ // Cancel pending Cindy login/refresh before revoking the binding; keep native credentials.try {- disconnectClaudeAiOAuth();+ cancelClaudeOAuthLogin();+ await disconnectClaudeAiOAuth();+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return { authorized: false };resetProviderModelAutoRefreshCooldowns('anthropic');} catch (err) {throwIpcError(@@ -4871,14 +4873,16 @@ const registerIpcHandlers = () => {);}await broadcastClaudeAuthStateChanged();- // 订阅余量同步: 凭证已清, read() 会清快照并广播 null, chip 立即回占位态。+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return { authorized: false };+ // Binding revoked: read() clears the Cindy quota snapshot and broadcasts null.syncClaudeSubscriptionUsageForAuthChange();// 模型清单动态发现:登出完成前清空清单 + 删磁盘缓存,并等待旧 SDK 写盘收尾。await clearAnthropicDiscoveredModels();return { authorized: hasClaudeAiOAuth() };});- ipcMain.handle(MAKER_IPC_INVOKE.CLAUDE_OAUTH_CANCEL, async () => {- cancelClaudeOAuthLogin();+ ipcMain.handle(MAKER_IPC_INVOKE.CLAUDE_OAUTH_CANCEL, async (event, loginKey?: string) => {+ assertTrustedAppRendererEvent(event);+ cancelClaudeOAuthLogin(loginKey);return { authorized: hasClaudeAiOAuth() };});@@ -4912,19 +4916,25 @@ const registerIpcHandlers = () => {// xAI(SuperGrok 订阅)OAuth —— 与 claude-oauth 同形态。登录成功后 bridge 的 xai provider 立即可用// (buildHeaders 每请求现取 token);连接态由 renderer refetch listProviders 时现读 hasGrokOAuthLogin。- ipcMain.handle(MAKER_IPC_INVOKE.XAI_OAUTH_LOGIN, async () => {+ ipcMain.handle(MAKER_IPC_INVOKE.XAI_OAUTH_LOGIN, async (event) => {+ assertTrustedAppRendererEvent(event);+ const owner = activeOwnerScopeKey();// reason 是 renderer 决定提示用的结构化数据,不抛 throwIpcError(规则 13 查询型例外)。// 登录成功即生效:订阅直连 handler 每请求经 buildHeaders 现取凭证,无需任何"就绪"步骤。const result = await runGrokOAuthLogin();+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return { ok: false, reason: 'login_cancelled', authorized: false };if (result.ok) {+ void retainProviderPresentationAfterAuthChange('xai');resetProviderModelAutoRefreshCooldowns('xai');// 新凭证在 runGrokOAuthLogin 返回前已经落盘。先同步关掉旧周用量读取窗口,// 再去做模型磁盘清理等 await,避免换号间隙里 IPC read 仍返回账号 A 的快照。await clearXaiSubscriptionUsageSnapshot();+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return { ok: false, reason: 'login_cancelled', authorized: false };// 登录可直接覆盖旧 SuperGrok 账号:先清旧世代内存,再直接读新账号官方清单。// 这里不能先恢复同一 Cindy owner 的磁盘 LKG,否则 A→B 重登会短暂展示 A 的成员。clearXaiDiscoveredModels();await discardXaiModelsDiskCache();+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return { ok: false, reason: 'login_cancelled', authorized: false };// 登录可直接覆盖旧账号凭证。先跨授权边界清掉旧账号发现快照,再补拉新账号;// 旧在途请求由 discovery generation + owner scope 双重守卫作废。clearXaiMediaModels();@@ -4933,6 +4943,7 @@ const registerIpcHandlers = () => {// 限流快照是账号级的:重登可能换账号,旧快照一并清掉(等新账号首个 xai/ 轮自然补上)。clearXaiRateLimitSnapshot();await syncXaiSubscriptionUsageForAuthChange();+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return { ok: false, reason: 'login_cancelled', authorized: false };broadcastXaiAuthStateChanged();void refreshXaiModelsFromHttp();void refreshProviderModelsManually('xai').catch((error) => {@@ -4944,11 +4955,21 @@ const registerIpcHandlers = () => {}return { ok: false, reason: result.reason ?? 'unknown', authorized: hasGrokOAuthLogin() };});- ipcMain.handle(MAKER_IPC_INVOKE.XAI_OAUTH_LOGOUT, async () => {+ ipcMain.handle(MAKER_IPC_INVOKE.XAI_OAUTH_LOGOUT, async (event, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }) => {+ assertTrustedAppRendererEvent(event);+ const active = getActiveAppSession();+ const owner = activeOwnerScopeKey();+ if (isAppSessionBoundaryPending() || (ownerScope && (ownerScope.dataOwnerId !== active.dataOwnerId || ownerScope.ownerGeneration !== active.generation))) {+ throwIpcError('INVALID_PARAMS', 'Provider owner changed');+ }try {+ cancelGrokOAuthLogin();logoutGrok();+ const presentation = retainProviderPresentationAfterAuthChange('xai');resetProviderModelAutoRefreshCooldowns('xai');await clearXaiSubscriptionUsageSnapshot();+ await presentation;+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return { ok: false, reason: 'login_cancelled', authorized: false };clearXaiDiscoveredModels();clearXaiMediaModels();} catch (err) {@@ -4961,6 +4982,7 @@ const registerIpcHandlers = () => {// 并清掉账号级限流快照 —— 登出后没有下一个成功响应来覆盖,不清会一直挂着旧账号余量。clearXaiRateLimitSnapshot();await syncXaiSubscriptionUsageForAuthChange();+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return { ok: false, reason: 'login_cancelled', authorized: false };broadcastXaiAuthStateChanged();return { authorized: hasGrokOAuthLogin() };});@@ -5557,14 +5579,18 @@ const registerIpcHandlers = () => {): Promise<void> => {assertTrustedAppRendererEvent(event);builtinApiKeyStore(builtinApiKeyDeps, providerId, value);+ await retainProviderPresentationAfterAuthChange(providerId as string);},);ipcMain.handle('builtin-api-key-remove',- async (event: Electron.IpcMainInvokeEvent, providerId: unknown): Promise<void> => {+ async (event: Electron.IpcMainInvokeEvent, providerId: unknown, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }): Promise<void> => {assertTrustedAppRendererEvent(event);+ const active = getActiveAppSession();+ if (isAppSessionBoundaryPending() || (ownerScope && (ownerScope.dataOwnerId !== active.dataOwnerId || ownerScope.ownerGeneration !== active.generation))) throwIpcError('INVALID_PARAMS', 'Provider owner changed');builtinApiKeyRemove(builtinApiKeyDeps, providerId);+ await retainProviderPresentationAfterAuthChange(providerId as string);},);diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.tsindex 918668f0a6..f8b8f04f3e 100644--- a/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts@@ -16,8 +16,11 @@ const h = vi.hoisted(() => ({oauth: null as Record<string, unknown> | null,gatewayKey: 'sk-xd-gateway' as string | null,cleared: 0,+ revoked: false,+ revocationFails: false,refresherInvalidated: 0,- invalidGrantHandler: null as (() => void) | null,+ invalidGrantHandler: null as ((digest: string) => void) | null,+ rejectedDigest: undefined as string | undefined,/** getValidClaudeAiOAuth 的可注入延迟(测回调超时用)。 */refreshDelayMs: 0,lastRefreshOpts: null as { staleToken?: string; forceRefresh?: boolean } | null,@@ -26,6 +29,12 @@ const h = vi.hoisted(() => ({canUseGateway: true,accounts: new Map<string, Record<string, unknown> | null>(),refreshAccount: vi.fn(),+ retainPresentation: vi.fn(),+}));++vi.mock('../provider-presentation-store.js', () => ({+ retainInvalidatedProviderPresentation: h.retainPresentation,+ retainProviderPresentationAfterAuthChange: vi.fn(),}));vi.mock('electron', () => ({@@ -43,6 +52,16 @@ vi.mock('../../appCapabilities.js', () => ({getAppCapabilities: () => ({ canUseCindyGateway: h.canUseGateway }),}));+vi.mock('../nativeProviderAuthBinding.js', async (original) => ({+ ...(await original<typeof import('../nativeProviderAuthBinding.js')>()),+ isNativeProviderAuthRevoked: () => h.revoked,+ unbindNativeProviderAuth: (_provider: string, opts?: { rejectedCredentialDigest?: string }) => {+ if (h.revocationFails) throw new Error('binding write failed');+ h.revoked = true;+ h.rejectedDigest = opts?.rejectedCredentialDigest;+ },+}));+vi.mock('../claude-credentials-store.js', () => ({hasClaudeAiOAuth: () => h.hasOAuth,clearClaudeAiOAuth: () => {@@ -63,9 +82,9 @@ vi.mock('../claude-oauth-refresh.js', () => ({// disconnect = invalidate → clear(唯一断开入口,logout/IPC 都必须走它)disconnectClaudeAiOAuth: () => {h.refresherInvalidated += 1;- h.cleared += 1;+ h.revoked = true;},- setClaudeOAuthInvalidGrantHandler: (handler: (() => void) | null) => {+ setClaudeOAuthInvalidGrantHandler: (handler: ((digest: string) => void) | null) => {h.invalidGrantHandler = handler;},}));@@ -107,6 +126,8 @@ describe('DesktopClaudeAuthAdapter.getAuthEnv — 订阅 OAuth env 注入', () =};h.gatewayKey = 'sk-xd-gateway';h.cleared = 0;+ h.revoked = false;+ h.revocationFails = false;h.refresherInvalidated = 0;h.refreshDelayMs = 0;h.encryptionAvailable = true;@@ -259,26 +280,58 @@ describe('DesktopClaudeAuthAdapter.getAuthEnv — 订阅 OAuth env 注入', () =}});- it('invalidate:清凭证 + 失效刷新器 + 广播重登', async () => {+ it('invalidate preserves native credentials and retains the provider before broadcasting', async () => {const mod = await import('../auth-adapters.js');const adapter = new mod.DesktopClaudeAuthAdapter();const broadcasts: string[] = [];adapter.setOnInvalidatedBroadcast((reason) => broadcasts.push(reason));await adapter.invalidate('claude_oauth_refresh_invalid_grant');- expect(h.cleared).toBe(1);+ expect(h.cleared).toBe(0);+ expect(h.revoked).toBe(true);+ expect(h.retainPresentation).toHaveBeenCalledWith('anthropic');expect(h.refresherInvalidated).toBe(1);expect(broadcasts).toEqual(['claude_oauth_refresh_invalid_grant']);});+ it('broadcasts revocation before waiting for auxiliary presentation persistence', async () => {+ const adapter = await makeAdapter();+ let release!: () => void;+ h.retainPresentation.mockReturnValueOnce(new Promise<void>((resolve) => { release = resolve; }));+ const broadcast = vi.fn();+ adapter.setOnInvalidatedBroadcast(broadcast);+ const pending = adapter.invalidate('old-credential-rejected');+ expect(broadcast).toHaveBeenCalledWith('old-credential-rejected');+ h.revoked = false;+ release();+ await pending;+ expect(broadcast).toHaveBeenCalledTimes(1);+ expect(h.revoked).toBe(false);+ });+it('构造期接线 invalid_grant handler(刷新模块通知 → invalidate 链路可达)', async () => {await makeAdapter();expect(typeof h.invalidGrantHandler).toBe('function');+ h.invalidGrantHandler?.('a'.repeat(64));+ expect(h.rejectedDigest).toBe('a'.repeat(64));+ expect(h.cleared).toBe(0);});- it('logout(订阅在连):清凭证同时失效刷新器,防在途刷新复活凭证', async () => {+ it('logout preserves native credentials and revokes Cindy access', async () => {const adapter = await makeAdapter();await adapter.logout();- expect(h.cleared).toBe(1);+ expect(h.cleared).toBe(0);+ expect(h.revoked).toBe(true);expect(h.refresherInvalidated).toBe(1);});++ it('still retains and broadcasts automatic invalidation when persistence fails', async () => {+ const adapter = await makeAdapter();+ const broadcast = vi.fn();+ adapter.setOnInvalidatedBroadcast(broadcast);+ h.revocationFails = true;+ h.invalidGrantHandler?.('c'.repeat(64));+ await vi.waitFor(() => expect(broadcast).toHaveBeenCalledWith('claude_oauth_refresh_invalid_grant'));+ expect(h.retainPresentation).toHaveBeenCalledWith('anthropic');+ expect(h.cleared).toBe(0);+ });});diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeLocalLoginCancellation.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeLocalLoginCancellation.test.tsnew file mode 100644index 0000000000..8b6a79ccb0--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/claudeLocalLoginCancellation.test.ts@@ -0,0 +1,54 @@+import { readFileSync } from 'node:fs';+import { ScriptTarget, transpileModule } from 'typescript';+import { expect, it, vi } from 'vitest';++vi.mock('electron', () => ({ shell: { openExternal: vi.fn() }, app: { getPath: () => '/unused-test-path' } }));+import { beginClaudeLocalLogin, cancelClaudeOAuthLogin } from '../claude-oauth-login.js';++const source = readFileSync(new URL('../../bootstrap-electron.ts', import.meta.url), 'utf8');+const start = source.indexOf(' ipcMain.handle(MAKER_IPC_INVOKE.CLAUDE_OAUTH_LOGIN,');+const end = source.indexOf(' ipcMain.handle(MAKER_IPC_INVOKE.CLAUDE_OAUTH_LOGOUT,', start);+const compiled = transpileModule(source.slice(start, end), { compilerOptions: { target: ScriptTarget.ES2022 } }).outputText;++it.each(['scan', 'proxy'] as const)('does not bind a cancelled local login while waiting for %s', async (stage) => {+ let resume!: () => void;+ const pending = new Promise<void>(resolve => { resume = resolve; });+ let handler!: () => Promise<{ ok: boolean; reason?: string }>;+ const bind = vi.fn(() => true);+ const proxy = vi.fn(() => stage === 'proxy' ? pending : Promise.resolve());+ const deps = {+ ipcMain: { handle: (_channel: string, callback: typeof handler) => { handler = callback; } },+ MAKER_IPC_INVOKE: { CLAUDE_OAUTH_LOGIN: 'login' },+ assertTrustedAppRendererEvent: vi.fn(),+ activeOwnerScopeKey: () => 'owner',+ isAppSessionBoundaryPending: () => false,+ getActiveAppSession: () => ({ dataOwnerId: 'owner' }),+ beginClaudeLocalLogin,+ resetProviderModelAutoRefreshCooldowns: vi.fn(),+ clearAnthropicDiscoveredModels: () => stage === 'scan' ? pending : Promise.resolve(),+ ensureAnthropicCompatProxyReady: proxy,+ reconnectClaudeAiOAuth: bind,+ broadcastClaudeAuthStateChanged: vi.fn(),+ syncClaudeSubscriptionUsageForAuthChange: vi.fn(),+ refreshAnthropicModelsFromHttp: vi.fn(),+ hasClaudeAiOAuth: () => true,+ };+ new Function(...Object.keys(deps), compiled)(...Object.values(deps));+ const run = handler();+ if (stage === 'proxy') await vi.waitFor(() => expect(proxy).toHaveBeenCalled());+ cancelClaudeOAuthLogin();+ resume();+ await expect(run).resolves.toMatchObject({ ok: false, reason: 'login_cancelled' });+ expect(bind).not.toHaveBeenCalled();+});++it('reuses cancellation for a replacement local login without aborting the replacement', () => {+ const first = beginClaudeLocalLogin('old');+ const second = beginClaudeLocalLogin('new');+ expect(first.aborted).toBe(true);+ expect(second.aborted).toBe(false);+ cancelClaudeOAuthLogin('old');+ expect(second.aborted).toBe(false);+ cancelClaudeOAuthLogin('new');+ expect(second.aborted).toBe(true);+});diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeNativeConnection.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeNativeConnection.test.tsnew file mode 100644index 0000000000..5afd0f7643--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/claudeNativeConnection.test.ts@@ -0,0 +1,90 @@+import { beforeEach, expect, it, vi } from 'vitest';+const h = vi.hoisted(() => ({+ available: true,+ token: 'native-test-token',+ rejected: null as string | null,+ bind: vi.fn(),+ unbind: vi.fn(),+ presentation: vi.fn(),+ write: vi.fn(),+ clear: vi.fn(),+}));+vi.mock('../claude-credentials-store.js', async (original) => ({+ ...(await original<typeof import('../claude-credentials-store.js')>()),+ readClaudeAiOAuthUnbound: () => h.available ? { accessToken: h.token } : null,+ readClaudeAiOAuth: () => null,+ writeClaudeAiOAuth: h.write,+ clearClaudeAiOAuth: h.clear,+}));+vi.mock('../nativeProviderAuthBinding.js', () => ({+ bindNativeProviderAuth: h.bind,+ unbindNativeProviderAuth: h.unbind,+ isNativeProviderCredentialRejected: (_provider: string, digest: string) => digest === h.rejected,+}));+vi.mock('../override-settings-file.js', () => ({ createOverrideSettingsFile: () => ({+ invalidateIfChanged: vi.fn(), read: () => ({}), updateAtomic: async (updater: (state: { value: object }) => object) => h.presentation(updater({ value: {} })),+}) }));+import { claudeOAuthCredentialDigest, disconnectClaudeAiOAuth, reconnectClaudeAiOAuth } from '../claude-oauth-refresh.js';+beforeEach(() => {+ vi.clearAllMocks();+ h.available = true;+ h.token = 'native-test-token';+ h.rejected = null;+});+it('rejects the revoked credential after disconnect but allows changed native credentials', async () => {+ h.rejected = claudeOAuthCredentialDigest({ accessToken: h.token });+ await disconnectClaudeAiOAuth();+ expect(await reconnectClaudeAiOAuth()).toBe(false);+ expect(h.bind).not.toHaveBeenCalled();+ h.token = 'different-account-token';+ expect(await reconnectClaudeAiOAuth()).toBe(true);+ expect(h.write).not.toHaveBeenCalled();+ expect(h.clear).not.toHaveBeenCalled();+});+it('disconnect and reconnect only change the Cindy binding, never native credentials', async () => {+ await disconnectClaudeAiOAuth();+ expect(h.unbind).toHaveBeenCalledWith('anthropic', { revoked: true });+ expect(await reconnectClaudeAiOAuth()).toBe(true);+ expect(h.bind).toHaveBeenCalledWith('anthropic', { sharedSystem: true });+ expect(h.presentation).toHaveBeenCalledWith({ providers: { anthropic: { removed: false } } });+ expect(h.write).not.toHaveBeenCalled();+ expect(h.clear).not.toHaveBeenCalled();+});+it('cannot attach a native source with no credentials', async () => {+ h.available = false;+ expect(await reconnectClaudeAiOAuth()).toBe(false);+ expect(h.bind).not.toHaveBeenCalled();+});+it('completes login synchronously while auxiliary presentation persistence is blocked', async () => {+ let release!: () => void;+ const pending = new Promise<void>((resolve) => { release = resolve; });+ h.presentation.mockReturnValueOnce(pending);+ expect(reconnectClaudeAiOAuth()).toBe(true);+ expect(h.bind).toHaveBeenCalledWith('anthropic', { sharedSystem: true });+ expect(h.presentation).toHaveBeenCalled();+ expect(h.unbind).not.toHaveBeenCalled();+ release();+ await pending;+});+it('preserves successful authentication if restoring the entry fails', async () => {+ h.presentation.mockImplementationOnce(() => {+ throw new Error('disk full');+ });+ expect(await reconnectClaudeAiOAuth()).toBe(true);+ expect(h.unbind).not.toHaveBeenCalled();+ expect(h.write).not.toHaveBeenCalled();+ expect(h.clear).not.toHaveBeenCalled();+});+it('completes disconnect when display persistence fails without clearing native credentials', async () => {+ h.presentation.mockImplementationOnce(() => { throw new Error('disk full'); });+ await expect(disconnectClaudeAiOAuth()).resolves.toBeUndefined();+ expect(h.unbind).toHaveBeenCalledWith('anthropic', { revoked: true });+ expect(h.presentation).toHaveBeenCalled();+ expect(h.write).not.toHaveBeenCalled();+ expect(h.clear).not.toHaveBeenCalled();+});+it('still reports failure when the binding cannot be revoked', async () => {+ h.unbind.mockImplementationOnce(() => { throw new Error('binding write failed'); });+ await expect(disconnectClaudeAiOAuth()).rejects.toThrow('binding write failed');+ expect(h.presentation).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeOauthRefresh.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeOauthRefresh.test.tsindex 1eec73a116..65367a00f0 100644--- a/apps/desktop/src/main/maker-host/__tests__/claudeOauthRefresh.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/claudeOauthRefresh.test.ts@@ -18,6 +18,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import {createClaudeOAuthRefresher,+ claudeOAuthCredentialDigest,EXPIRY_MARGIN_MS,type ClaudeOAuthRefresherDeps,} from '../claude-oauth-refresh.js';@@ -528,7 +529,7 @@ describe('claude-oauth-refresh — 收尾语义', () => {expect(written).toHaveLength(0); // 「已断开」状态凭证不复活});- it('invalid_grant 但库已被换账号 → 采信新凭证,不触发 invalidate', async () => {+ it.each([false, true])('invalid_grant after account replacement or lost binding does not invalidate the new owner (%s)', async (lostBinding) => {// review P2:旧账号刷新失败(invalid_grant)不能 invalidate 掉在途换号登录的新账号。const stale = fixtureOAuth({ expiresAt: NOW - 1 });const switched = fixtureOAuth({@@ -543,7 +544,7 @@ describe('claude-oauth-refresh — 收尾语义', () => {});const onInvalidGrant = vi.fn();const { deps } = makeDeps({- readOAuth: () => (swapped ? switched : stale),+ readOAuth: () => (swapped ? (lostBinding ? null : switched) : stale),onInvalidGrant,fetchFn: (() => gate) as unknown as typeof fetch,});@@ -553,7 +554,7 @@ describe('claude-oauth-refresh — 收尾语义', () => {swapped = true; // HTTP 在途期间换账号登录resolveFetch(jsonResponse(400, { error: 'invalid_grant' }));const out = await pending;- expect(out?.accessToken).toBe('at-new-account');+ expect(out?.accessToken).toBe(lostBinding ? undefined : 'at-new-account');expect(onInvalidGrant).not.toHaveBeenCalled();});@@ -569,6 +570,7 @@ describe('claude-oauth-refresh — 收尾语义', () => {const r = createClaudeOAuthRefresher(deps);expect(await r.getValidOAuth({ forceRefresh: true })).toBeNull();expect(onInvalidGrant).toHaveBeenCalledTimes(1);+ expect(onInvalidGrant).toHaveBeenCalledWith(claudeOAuthCredentialDigest(current));const onInvalidGrant2 = vi.fn();const { deps: deps2 } = makeDeps({diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeRevocationPersistence.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeRevocationPersistence.test.tsnew file mode 100644index 0000000000..0ceb547577--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/claudeRevocationPersistence.test.ts@@ -0,0 +1,48 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++const h = vi.hoisted(() => ({ directory: '', blob: '', failWrite: false }));+vi.mock('electron', () => ({ app: { getPath: () => h.directory } }));+vi.mock('node:child_process', () => ({ execFileSync: vi.fn(() => h.blob) }));+vi.mock('../../appSessionState.js', () => ({+ getActiveAppSession: () => ({ dataOwnerId: 'test-owner', generation: 1 }),+ isAppSessionBoundaryPending: () => false,+}));+vi.mock('../../utils/atomicWriteFile.js', async (original) => {+ const actual = await original<typeof import('../../utils/atomicWriteFile.js')>();+ return { ...actual, atomicWriteFileSync: (...args: Parameters<typeof actual.atomicWriteFileSync>) => {+ if (h.failWrite) throw new Error('test disk full');+ return actual.atomicWriteFileSync(...args);+ } };+});+import { bindNativeProviderAuth, unbindNativeProviderAuth, isNativeProviderCredentialRejected } from '../nativeProviderAuthBinding.js';+import { claudeOAuthCredentialDigest, readClaudeAiOAuth, readClaudeAiOAuthUnbound } from '../claude-credentials-store.js';++function credential(token: string) {+ h.blob = JSON.stringify({ claudeAiOauth: { accessToken: token } });+ fs.writeFileSync(path.join(h.directory, '.credentials.json'), h.blob);+}+beforeEach(() => {+ h.directory = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-revocation-'));+ h.failWrite = false;+ vi.stubEnv('CLAUDE_CONFIG_DIR', h.directory);+});+afterEach(() => {+ vi.unstubAllEnvs();+ fs.rmSync(h.directory, { recursive: true, force: true });+});+it('stops bound reads after a failed revocation write without changing native credentials', () => {+ credential('test-rejected');+ bindNativeProviderAuth('anthropic', { sharedSystem: true });+ const digest = claudeOAuthCredentialDigest({ accessToken: 'test-rejected' });+ h.failWrite = true;+ expect(() => unbindNativeProviderAuth('anthropic', { revoked: true, rejectedCredentialDigest: digest })).toThrow();+ expect(isNativeProviderCredentialRejected('anthropic', digest)).toBe(true);+ expect(readClaudeAiOAuth()).toBeNull();+ expect(readClaudeAiOAuthUnbound()?.accessToken).toBe('test-rejected');+ expect(fs.readFileSync(path.join(h.directory, '.credentials.json'), 'utf8')).toBe(h.blob);+ credential('test-new-account');+ expect(readClaudeAiOAuth()?.accessToken).toBe('test-new-account');+});diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.tsindex bf0842caab..28aeabcc86 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts@@ -115,7 +115,7 @@ it('compares Codex hard-link identities without Windows number precision collisiexpect(haveSameStableFileIdentity({ dev: 7n, ino: 11n }, { dev: 7n, ino: 11n })).toBe(true);});-it('does not chmod a system-shared auth file while finalizing login', async () => {+it.each([false, true])('preserves successful shared login and native files when presentation write fails=%s', async (failPresentation) => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-shared-mode-'));dirs.push(root);h.userDataDir = path.join(root, 'user-data');@@ -132,6 +132,16 @@ it('does not chmod a system-shared auth file while finalizing login', async () =JSON.stringify({ tokens: { access_token: 'shared-token', account_id: 'acct-1' } }),);fs.linkSync(systemAuth, localAuth);+ const { setProviderPresentation, readProviderPresentation } = await import('../provider-presentation-store.js');+ await setProviderPresentation('openai', { name: 'My OpenAI', removed: true });+ const nativeBefore = fs.readFileSync(systemAuth, 'utf8');+ if (failPresentation) {+ const write = fs.writeFileSync;+ vi.spyOn(fs, 'writeFileSync').mockImplementation((...args: Parameters<typeof fs.writeFileSync>) => {+ if (String(args[0]).includes('local-codex-provider-prefs.json')) throw new Error('test disk full');+ return write(...args);+ });+ }const chmod = vi.spyOn(fs.promises, 'chmod');const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');const adapter = new DesktopCodexAuthAdapter();@@ -142,6 +152,8 @@ it('does not chmod a system-shared auth file while finalizing login', async () =).finishSuccessfulCodexLogin.bind(adapter);await expect(finishSuccessfulCodexLogin()).resolves.toMatchObject({ authenticated: true });+ expect(readProviderPresentation('openai')).toEqual({ name: 'My OpenAI', removed: failPresentation });+ expect(fs.readFileSync(systemAuth, 'utf8')).toBe(nativeBefore);expect(chmod).not.toHaveBeenCalled();expect(fs.statSync(systemAuth).ino).toBe(fs.statSync(localAuth).ino);});@@ -204,6 +216,59 @@ afterEach(() => {});describe('Codex system credential suppression marker', () => {+ it.each(['pending-login', 'host-cleanup', 'cache-cleanup', 'owner-generation', 'new-owner-logout'])(+ 'does not revoke a replacement owner binding after %s yields', async (phase) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-codex-logout-owner-'));+ dirs.push(root);+ h.userDataDir = path.join(root, 'user-data');+ h.dataOwnerId = 'owner-a';+ vi.spyOn(os, 'homedir').mockReturnValue(path.join(root, 'empty-home'));+ const codexHome = path.join(h.userDataDir, 'codex-home');+ const localAuth = path.join(codexHome, 'auth.json');+ const bindingFile = path.join(h.userDataDir, 'native-provider-auth.json');+ fs.mkdirSync(codexHome, { recursive: true });+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'fixture-token' } }));+ fs.writeFileSync(bindingFile, JSON.stringify({ openai: 'owner-a' }));+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');+ const adapter = new DesktopCodexAuthAdapter();+ const gate = deferred();+ const entered = deferred();+ if (phase === 'pending-login') {+ Object.defineProperty(adapter, 'pendingLogin', { value: { promise: gate.promise, cancelled: false } });+ vi.spyOn(adapter, 'cancelLogin').mockImplementation(() => entered.resolve());+ } else if (phase === 'cache-cleanup') {+ const remove = fs.promises.rm.bind(fs.promises);+ vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, options) => {+ await remove(target, options);+ if (String(target) === path.join(codexHome, 'models_cache.json')) {+ entered.resolve();+ await gate.promise;+ }+ });+ } else {+ adapter.setOnLogoutSuccess(() => { entered.resolve(); return gate.promise; });+ }+ const logout = adapter.logout();+ await entered.promise;+ h.dataOwnerId = phase === 'owner-generation' ? 'owner-a' : 'owner-b';+ h.sessionGeneration += 1;+ const replacement = JSON.stringify({ openai: h.dataOwnerId, selfAuthorized: { openai: h.dataOwnerId } });+ fs.writeFileSync(bindingFile, replacement);+ const nextLogout = phase === 'new-owner-logout' ? adapter.logout() : null;+ gate.resolve();+ await logout;+ if (nextLogout) {+ await nextLogout;+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({ revoked: { openai: h.dataOwnerId } });+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8')).openai).toBeUndefined();+ } else {+ expect(fs.readFileSync(bindingFile, 'utf8')).toBe(replacement);+ }+ expect(JSON.parse(fs.readFileSync(localAuth, 'utf8')).tokens.access_token).toBe('fixture-token');+ if (phase === 'pending-login') expect(fs.existsSync(getCodexAuthInvalidationMarkerPath(codexHome))).toBe(false);+ },+ );+it('qualifies the Windows ACL principal when the machine and user names can collide', async () => {const { resolveWindowsAclPrincipal } = await import('../auth-adapters.js');@@ -297,7 +362,7 @@ describe('Codex system credential suppression marker', () => {});});- it('cleans a matching local credential left by a crash after the disconnect marker committed', () => {+ it('preserves a matching credential while restoring a committed disconnect', () => {const { codexHome, systemAuth, localAuth } = fixture();fs.mkdirSync(codexHome, { recursive: true });fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'old-local-token' } }));@@ -315,7 +380,7 @@ describe('Codex system credential suppression marker', () => {suppressReconcile: true,invalidatedReason: null,});- expect(fs.existsSync(localAuth)).toBe(false);+ expect(fs.existsSync(localAuth)).toBe(true);});it('suppresses a matching local credential after server-side token invalidation', () => {@@ -992,9 +1057,7 @@ describe('Codex system credential suppression marker', () => {const adapter = new DesktopCodexAuthAdapter();const onLogoutSuccess = vi.fn().mockResolvedValue(undefined);adapter.setOnLogoutSuccess(onLogoutSuccess);- const rmSpy = vi- .spyOn(fs.promises, 'rm')- .mockRejectedValueOnce(new Error('EPERM: file is locked'));+ const rmSpy = vi.spyOn(fs.promises, 'rm');await expect(adapter.logout()).resolves.toBeUndefined();expect(onLogoutSuccess).toHaveBeenCalledTimes(1);@@ -1582,11 +1645,13 @@ describe('Codex system credential suppression marker', () => {const adapter = new DesktopCodexAuthAdapter();const cleanupGate = deferred();const broadcast = vi.fn().mockResolvedValue(undefined);- adapter.setOnLogoutSuccess(() => cleanupGate.promise);+ const cleanup = vi.fn(() => cleanupGate.promise);+ adapter.setOnLogoutSuccess(cleanup);adapter.setOnInvalidatedBroadcast(broadcast);const explicitLogout = adapter.logout();- await vi.waitFor(() => expect(fs.existsSync(localAuth)).toBe(false));+ await vi.waitFor(() => expect(cleanup).toHaveBeenCalled());+ expect(fs.existsSync(localAuth)).toBe(true);const invalidation = adapter.invalidate('token_invalidated');cleanupGate.resolve();diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.tsindex 0ebe401ca4..8824eea250 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.ts@@ -23,6 +23,7 @@ const dirs: string[] = [];const h = vi.hoisted(() => ({userDataDir: '',appDataDir: '',+ isPackaged: false,dataOwnerId: null as string | null,}));@@ -30,7 +31,7 @@ vi.mock('electron', () => ({app: {getPath: (name: string) => (name === 'appData' ? h.appDataDir : h.userDataDir),getAppPath: () => h.userDataDir,- isPackaged: false,+ get isPackaged() { return h.isPackaged; },},safeStorage: { isEncryptionAvailable: () => false },}));@@ -122,6 +123,7 @@ function trustIsolatedAuthSandbox(): void {}afterEach(() => {+ h.isPackaged = false;vi.restoreAllMocks();vi.unstubAllEnvs();h.dataOwnerId = null;@@ -279,13 +281,13 @@ describe('dev 沙箱凭证隔离(XDT_ISOLATED_AUTH)', () => {});await adapter.logout();await expect(adapter.getState()).resolves.toMatchObject({- authenticated: true,+ authenticated: false,oauthWritesBlocked: true,});expect(fs.readFileSync(releaseAuth)).toEqual(releaseBytes);expect(fs.statSync(releaseAuth).ino).toBe(releaseStat.ino);expect(fs.readFileSync(releaseBinding)).toEqual(releaseBindingBytes);- expect(fs.existsSync(getCodexAuthInvalidationMarkerPath(codexHome))).toBe(false);+ expect(fs.existsSync(getCodexAuthInvalidationMarkerPath(codexHome))).toBe(true);});it('共享 Dev 直接使用 Release 登录态,不重链接或改 binding', async () => {@@ -411,7 +413,7 @@ describe('dev 沙箱凭证隔离(XDT_ISOLATED_AUTH)', () => {expect(fs.readFileSync(localAuth)).not.toEqual(releaseBytes);});- it('dev 默认只读共享:登录和登出不可改,失效只阻断当前进程', async () => {+ it('dev 默认只读共享:断开只停用 Cindy,重启不复活,显式本机连接可恢复', async () => {const { codexHome, localAuth, systemAuth } = fixture();h.dataOwnerId = 'owner-a';const { DesktopCodexAuthAdapter, readCodexOneShotCreds } = await import('../auth-adapters.js');@@ -440,26 +442,21 @@ describe('dev 沙箱凭证隔离(XDT_ISOLATED_AUTH)', () => {oauthWritesBlocked: true,});await adapter.logout();- await expect(adapter.getState()).resolves.toMatchObject({- authenticated: true,- oauthWritesBlocked: true,- });- await expect(adapter.getAccessToken()).resolves.toBe('system-token');- await expect(adapter.getAccountId()).resolves.toBe('acct-1');- await expect(adapter.hasCodexOAuthLogin()).resolves.toBe(true);- await expect(adapter.getAuthEnv({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({- CODEX_HOME: codexHome,- });- expect(readCodexOneShotCreds(adapter)).toEqual({- accessToken: 'system-token',- accountId: 'acct-1',- });- expect(onLogout).not.toHaveBeenCalled();+ await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({ authenticated: false });+ await expect(adapter.getAccessToken()).resolves.toBeNull();+ await expect(adapter.getAccountId()).resolves.toBeNull();+ expect(readCodexOneShotCreds(adapter)).toBeNull();+ expect(onLogout).toHaveBeenCalledTimes(1);expect(fs.readFileSync(systemAuth, 'utf8')).toBe(beforeSystem);expect(fs.readFileSync(localAuth, 'utf8')).toBe(beforeLocal);expect(fs.statSync(systemAuth).ino).toBe(beforeSystemStat.ino);expect(fs.statSync(localAuth).ino).toBe(beforeLocalStat.ino);- expect(fs.existsSync(getCodexAuthInvalidationMarkerPath(codexHome))).toBe(false);+ expect(fs.existsSync(getCodexAuthInvalidationMarkerPath(codexHome))).toBe(true);+ const restarted = new DesktopCodexAuthAdapter();+ await expect(restarted.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({ authenticated: false });+ await expect(restarted.triggerLogin({ mode: 'local' })).resolves.toMatchObject({ authenticated: true, credentialScope: 'system-shared' });+ await expect(restarted.getAccessToken()).resolves.toBe('system-token');+ expect(fs.readFileSync(systemAuth, 'utf8')).toBe(beforeSystem);const invalidatedAdapter = new DesktopCodexAuthAdapter();invalidatedAdapter.setOnInvalidatedBroadcast(onInvalidated);@@ -474,6 +471,197 @@ describe('dev 沙箱凭证隔离(XDT_ISOLATED_AUTH)', () => {expect(fs.existsSync(getCodexAuthInvalidationMarkerPath(codexHome))).toBe(false);});+ it.each([false, true].flatMap(packaged => [false, true].map(failPresentation => ({ packaged, failPresentation }))))('preserves native credentials across reconnect (packaged=$packaged, display write fails=$failPresentation)', async ({ packaged, failPresentation }) => {+ const { codexHome, systemAuth, localAuth } = fixture();+ h.isPackaged = packaged;+ h.dataOwnerId = 'owner-a';+ fs.mkdirSync(codexHome, { recursive: true });+ fs.linkSync(systemAuth, localAuth);+ const before = fs.readFileSync(systemAuth);+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');+ const adapter = new DesktopCodexAuthAdapter();+ await expect(adapter.triggerLogin({ mode: 'local' })).resolves.toMatchObject({ authenticated: true });+ await adapter.logout();+ const restarted = new DesktopCodexAuthAdapter();+ await expect(restarted.getAccessToken()).resolves.toBeNull();+ const onLoginSuccess = vi.fn(() => restarted.getAccessToken().then(() => undefined));+ restarted.setOnLoginSuccess(onLoginSuccess);+ expect(fs.readFileSync(systemAuth)).toEqual(before);+ expect(fs.readFileSync(localAuth)).toEqual(before);+ if (failPresentation) {+ const write = fs.writeFileSync;+ vi.spyOn(fs, 'writeFileSync').mockImplementation((...args: Parameters<typeof fs.writeFileSync>) => {+ if (String(args[0]).includes('local-codex-provider-prefs.json')) throw new Error('test disk full');+ return write(...args);+ });+ }+ await expect(restarted.triggerLogin({ mode: 'local' })).resolves.toMatchObject({ authenticated: true });+ expect(onLoginSuccess).toHaveBeenCalledOnce();+ await expect(restarted.getAccessToken()).resolves.toBe('system-token');+ expect(fs.readFileSync(systemAuth)).toEqual(before);+ const bindings = JSON.parse(fs.readFileSync(path.join(h.userDataDir, 'native-provider-auth.json'), 'utf8'));+ expect(bindings.sources.openai).toBe('native-harness-inherited');+ expect(bindings.selfAuthorized?.openai).toBeUndefined();+ });++ it('retires the implicit gateway host before local login returns and rebuilds for OAuth', async () => {+ fixture();+ h.isPackaged = true;+ h.dataOwnerId = 'owner-a';+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');+ const { CodexAgent } = await import('../../../../../../packages/maker-core/src/agents/codex/index.js');+ const adapter = new DesktopCodexAuthAdapter();+ await adapter.logout();+ const logger: any = { trace: vi.fn(), debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(), fatal: vi.fn() };+ logger.child = () => logger;+ const agent = new CodexAgent({ auth: adapter, runtimeConfig: {}, binaryPath: process.execPath, logger } as any);+ const runtime = agent as any;+ // Keep real Host reuse/retirement bookkeeping; only the process boundary is stubbed.+ const create = vi.spyOn(runtime, 'createHost').mockImplementation(async (...args: unknown[]) => {+ const key = args[1] as string;+ const mode = await adapter.getAccessToken() ? 'oauth-bearer' : 'gateway-key';+ const host = { activeSubscriptions: 0, getSubagentRoutingProfile: () => 'default',+ isCodexProxyActive: () => true, retire: vi.fn(async () => undefined) };+ runtime.hosts.set(key, host);+ runtime.hostCredentialModes.set(key, undefined);+ runtime.hostEffectiveCredentialModes.set(key, mode);+ return host;+ });+ const oldHost = await runtime.getHost();+ expect(runtime.hostEffectiveCredentialModes.get('local')).toBe('gateway-key');+ const dispose = vi.spyOn(agent, 'forceDisposeLocalHostForAuthChange');+ adapter.setOnLoginSuccess(() => agent.forceDisposeLocalHostForAuthChange('Codex desktop auth login'));+ try {+ await expect(adapter.triggerLogin({ mode: 'local' })).resolves.toMatchObject({ authenticated: true });+ expect(dispose).toHaveBeenCalledOnce();+ expect(oldHost.retire).toHaveBeenCalledOnce();+ const newHost = await runtime.getHost();+ expect(newHost).not.toBe(oldHost);+ expect(create).toHaveBeenCalledTimes(2);+ expect(runtime.hostEffectiveCredentialModes.get('local')).toBe('oauth-bearer');+ } finally {+ await agent.forceDisposeLocalHostForAuthChange('test cleanup');+ }+ });++ it.each(['success', 'failure', 'owner-change', 'cancel', 'cancel-cleanup-failure'] as const)('settles local runtime refresh with the correct credential boundary (%s)', async (outcome) => {+ const { systemAuth } = fixture();+ h.isPackaged = true;+ h.dataOwnerId = 'owner-a';+ const before = fs.readFileSync(systemAuth);+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');+ const adapter = new DesktopCodexAuthAdapter();+ let release!: () => void;+ const gate = new Promise<void>(resolve => { release = resolve; });+ const callback = vi.fn(async () => {+ await gate;+ if (outcome === 'failure') throw new Error('test host retirement failure');+ });+ adapter.setOnLoginSuccess(callback);+ const settled = vi.fn();+ const login = adapter.triggerLogin({ mode: 'local' }).then(state => { settled(); return state; });+ await vi.waitFor(() => expect(callback).toHaveBeenCalledOnce());+ expect(settled).not.toHaveBeenCalled();+ await expect(adapter.getAccessToken()).resolves.toBe('system-token');+ if (outcome === 'owner-change') h.dataOwnerId = 'owner-b';+ if (outcome === 'cancel' || outcome === 'cancel-cleanup-failure') adapter.cancelLogin();+ if (outcome === 'cancel-cleanup-failure') {+ const error = new Error('test disconnect persistence failure');+ vi.spyOn(adapter as unknown as { disconnectCodexOAuth(): Promise<void> }, 'disconnectCodexOAuth').mockRejectedValueOnce(error);+ const rejected = expect(login).rejects.toBe(error);+ release();+ await rejected;+ expect(settled).not.toHaveBeenCalled();+ expect(fs.readFileSync(systemAuth)).toEqual(before);+ return;+ }+ release();+ await expect(login).resolves.toMatchObject(outcome === 'owner-change' || outcome === 'cancel'+ ? { authenticated: false, errorReason: 'login_cancelled' }+ : { authenticated: true });+ h.dataOwnerId = 'owner-a';+ await expect(adapter.getAccessToken()).resolves.toBe(outcome === 'cancel' ? null : 'system-token');+ await expect(new DesktopCodexAuthAdapter().getAccessToken()).resolves.toBe(outcome === 'cancel' ? null : 'system-token');+ expect(fs.readFileSync(systemAuth)).toEqual(before);+ });++ it.each([false, true])('local reconnect shares native refresh writes instead of copying (existing=%s)', async (existing) => {+ const { codexHome, systemAuth, localAuth } = fixture();+ h.isPackaged = true;+ h.dataOwnerId = 'owner-a';+ fs.mkdirSync(codexHome, { recursive: true });+ if (existing) fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'old-copy' } }));+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');+ const adapter = new DesktopCodexAuthAdapter();+ await expect(adapter.triggerLogin({ mode: 'local' })).resolves.toMatchObject({ authenticated: true });+ const renewed = JSON.stringify({ tokens: { access_token: 'renewed-native-token', account_id: 'acct-1' } });+ fs.writeFileSync(localAuth, renewed);+ expect(fs.readFileSync(systemAuth, 'utf8')).toBe(renewed);+ await adapter.logout();+ expect(fs.readFileSync(systemAuth, 'utf8')).toBe(renewed);+ });++ it('disconnects shared Dev when its credential path is also the Release path', async () => {+ const { releaseAuth } = fixture();+ h.dataOwnerId = 'owner-a';+ h.userDataDir = path.dirname(path.dirname(releaseAuth));+ fs.mkdirSync(path.dirname(releaseAuth), { recursive: true });+ fs.writeFileSync(releaseAuth, JSON.stringify({ tokens: { access_token: 'release-token', account_id: 'release-account' } }));+ bindReleaseOpenAi(releaseAuth);+ const before = fs.readFileSync(releaseAuth);+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');+ const adapter = new DesktopCodexAuthAdapter();+ await adapter.logout();+ expect(fs.readFileSync(releaseAuth)).toEqual(before);+ const restarted = new DesktopCodexAuthAdapter();+ await expect(restarted.getAccessToken()).resolves.toBeNull();+ await expect(restarted.triggerLogin({ mode: 'local' })).resolves.toMatchObject({ authenticated: true });+ expect(fs.readFileSync(releaseAuth)).toEqual(before);+ });++ it('keeps a user disconnect durable when read-only invalidation cleanup is already running', async () => {+ const { systemAuth } = fixture();+ h.dataOwnerId = 'owner-a';+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');+ const adapter = new DesktopCodexAuthAdapter();+ await adapter.getState();+ const before = fs.readFileSync(systemAuth);+ let release!: () => void;+ const gate = new Promise<void>((resolve) => { release = resolve; });+ const cleanup = vi.fn(() => gate);+ adapter.setOnLogoutSuccess(cleanup);+ const invalidation = adapter.logout({ preserveInvalidatedReason: true });+ await vi.waitFor(() => expect(cleanup).toHaveBeenCalled());+ const disconnect = adapter.logout();+ release();+ await Promise.all([invalidation, disconnect]);+ await expect(new DesktopCodexAuthAdapter().getAccessToken()).resolves.toBeNull();+ expect(fs.readFileSync(systemAuth)).toEqual(before);+ });++ it('cancel before local reconnect leaves the durable disconnect intact', async () => {+ const { systemAuth } = fixture();+ h.dataOwnerId = 'owner-a';+ const before = fs.readFileSync(systemAuth);+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');+ const adapter = new DesktopCodexAuthAdapter();+ await adapter.getState();+ let release!: () => void;+ const gate = new Promise<void>((resolve) => { release = resolve; });+ adapter.setOnLogoutSuccess(() => gate);+ const onLoginSuccess = vi.fn();+ adapter.setOnLoginSuccess(onLoginSuccess);+ const disconnect = adapter.logout();+ const reconnect = adapter.triggerLogin({ mode: 'local' });+ adapter.cancelLogin();+ release();+ await disconnect;+ await expect(reconnect).resolves.toMatchObject({ authenticated: false, errorReason: 'login_cancelled' });+ expect(onLoginSuccess).not.toHaveBeenCalled();+ await expect(new DesktopCodexAuthAdapter().getAccessToken()).resolves.toBeNull();+ expect(fs.readFileSync(systemAuth)).toEqual(before);+ });+it('dev 默认只读的 unproven 失效只保留内存边界', async () => {const { codexHome, localAuth, systemAuth } = fixture();h.dataOwnerId = 'owner-a';diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthLoginConcurrency.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthLoginConcurrency.test.tsindex 67632b7b1c..1a24bd90ab 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthLoginConcurrency.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthLoginConcurrency.test.ts@@ -1,7 +1,15 @@import type { AgentLoginMode, AuthLoginOptions, AuthState } from '@cindy/maker-core';import { describe, expect, it, vi } from 'vitest';-const h = vi.hoisted(() => ({ userDataDir: '/tmp/cindy-codex-login-concurrency' }));+const h = vi.hoisted(() => ({+ userDataDir: '/tmp/cindy-codex-login-concurrency',+ setLocalCodexProviderRemoved: vi.fn(),+}));++vi.mock('../provider-presentation-store.js', () => ({+ retainProviderPresentationAfterAuthChange: h.setLocalCodexProviderRemoved,+ retainInvalidatedProviderPresentation: vi.fn(),+}));vi.mock('electron', () => ({app: {@@ -61,6 +69,7 @@ describe('DesktopCodexAuthAdapter login single-flight', () => {errorReason: 'login_cancelled',});expect(disconnectCodexOAuth).toHaveBeenCalledOnce();+ expect(h.setLocalCodexProviderRemoved).not.toHaveBeenCalled();});it('coalesces the same mode but cancels and serializes a different mode', async () => {diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.tsindex 38398b3a16..2179e77f93 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts@@ -73,6 +73,8 @@ vi.mock('../../logger.js', () => ({getLogDir: () => mockState.logDir,}));+vi.mock('../grok-oauth-login.js', async (importOriginal) => ({ ...await importOriginal<typeof import('../grok-oauth-login.js')>(), peekGrokAccessToken: () => 'fixture-xai-token' }));+vi.mock('../../usageBroadcaster.js', () => ({recordXaiRateLimitSnapshot: mockState.recordXaiRateLimitSnapshot,}));@@ -6417,6 +6419,9 @@ describe('codex proxy host', () => {it('records xAI rate-limit headers from Codex proxy upstream responses', async () => {const host = await freshCodexProxyHost();+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');+ host.registerComposed('session-rate-xai', 'thread-xai', 'PRODUCT_PROMPT');+ setSessionProvider('session-rate-xai', 'xai');mockState.createAnthropicCompatProxy.mockResolvedValueOnce({url: 'http://127.0.0.1:43210',dispose: vi.fn(async () => undefined),@@ -6432,6 +6437,7 @@ describe('codex proxy host', () => {upstreamBase: 'https://api.x.ai/v1',status: 200,requestHeaders: { 'thread-id': 'thread-xai' },+ outboundHeaders: { authorization: 'Bearer fixture-xai-token' },responseHeaders: {'content-type': 'application/json','x-ratelimit-limit-requests': '100',@@ -6447,7 +6453,8 @@ describe('codex proxy host', () => {remainingRequests: 88,limitTokens: 1000000,remainingTokens: 900000,- });+ }, 'xai');+ clearSessionProvider('session-rate-xai');});it('observes streaming provider service_tier from response.completed SSE', async () => {diff --git a/apps/desktop/src/main/maker-host/__tests__/grokAuthRejectionRecovery.test.ts b/apps/desktop/src/main/maker-host/__tests__/grokAuthRejectionRecovery.test.tsindex 46950baea0..faf4d3f673 100644--- a/apps/desktop/src/main/maker-host/__tests__/grokAuthRejectionRecovery.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/grokAuthRejectionRecovery.test.ts@@ -11,6 +11,11 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+const retainPresentation = vi.hoisted(() => vi.fn());+vi.mock('../provider-presentation-store.js', () => ({+ retainInvalidatedProviderPresentation: retainPresentation,+}));+vi.mock('electron', () => ({shell: { openExternal: vi.fn() },app: {@@ -100,6 +105,7 @@ function tokenResponse(status: number, body: unknown): Response {}beforeEach(() => {+ retainPresentation.mockClear();store.clear();bound = true;resetGrokOAuthMemoryCache();@@ -111,6 +117,16 @@ afterEach(() => {});describe('recoverGrokAuthAfterRejection', () => {+ it('does not report stale logout after credentials change during presentation persistence', async () => {+ seedCredentials({ refresh_token: undefined });+ retainPresentation.mockImplementationOnce(async () => {+ bound = true;+ seedCredentials({ access_token: 'new-login-token' });+ resetGrokOAuthMemoryCache();+ });+ await expect(recoverGrokAuthAfterRejection(REJECTED_TOKEN)).resolves.toBe('superseded');+ expect(peekGrokAccessToken()).toBe('new-login-token');+ });it('refresh and logout affect only the selected account', async () => {seedCredentials();store.set('xai-second', JSON.stringify({ access_token: 'second-token', refresh_token: 'second-refresh', expires_at: Date.now() + 3600_000 }));@@ -164,6 +180,7 @@ describe('recoverGrokAuthAfterRejection', () => {await expect(recoverGrokAuthAfterRejection(REJECTED_TOKEN)).resolves.toBe('logged_out');expect(readStored()).toBeNull();+ expect(retainPresentation).toHaveBeenCalledWith('xai');});it('收口开始时凭证已换成别的账号 —— 不拿新凭证承担旧 token 的失败', async () => {@@ -177,6 +194,7 @@ describe('recoverGrokAuthAfterRejection', () => {await expect(recoverGrokAuthAfterRejection(REJECTED_TOKEN)).resolves.toBe('superseded');expect(fetchMock).not.toHaveBeenCalled();expect(readStored()?.access_token).toBe('another-account-token');+ expect(retainPresentation).not.toHaveBeenCalled();});it('本地没有 refresh_token 时无从自愈,登出但不消耗冷却', async () => {diff --git a/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts b/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.tsindex 7440dcf456..9360af427d 100644--- a/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts@@ -28,6 +28,7 @@ import {getNativeProviderAuthSource,isNativeProviderAuthBound,isNativeProviderAuthRevoked,+ isNativeProviderCredentialRejected,isNativeProviderAuthSelfAuthorized,isNativeProviderAuthSharedSystemCredential,markNativeProviderAuthSharedSystemCredential,@@ -55,6 +56,59 @@ afterEach(() => {});describe('native provider auth legacy binding', () => {+ it('persists only the rejected digest and retains it across disconnect and unrelated binding writes', async () => {+ const digest = 'a'.repeat(64);+ bindNativeProviderAuth('anthropic', { sharedSystem: true });+ unbindNativeProviderAuth('anthropic', { revoked: true, rejectedCredentialDigest: digest });+ unbindNativeProviderAuth('anthropic', { revoked: true });+ bindNativeProviderAuth('openai');+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8')).rejectedCredentialDigests).toEqual({ anthropic: digest });+ vi.resetModules();+ const restarted = await import('../nativeProviderAuthBinding.js');+ expect(restarted.isNativeProviderCredentialRejected('anthropic', digest)).toBe(true);+ expect(restarted.isNativeProviderCredentialRejected('anthropic', 'b'.repeat(64))).toBe(false);+ expect(restarted.isNativeProviderAuthBound('openai')).toBe(true);+ });++ it('does not interpret malformed rejection metadata as permission to reconnect', () => {+ fs.mkdirSync(userDataDir, { recursive: true });+ fs.writeFileSync(bindingFile, JSON.stringify({ rejectedCredentialDigests: { anthropic: 42 } }));+ expect(isNativeProviderCredentialRejected('anthropic', 'a'.repeat(64))).toBe(true);+ });+ it.each([false, true])('repairs damaged digest metadata explicitly while preserving other bindings (bad revoked: %s)', (badRevoked) => {+ fs.mkdirSync(userDataDir, { recursive: true });+ const digest = 'c'.repeat(64);+ fs.writeFileSync(bindingFile, JSON.stringify({+ anthropic: 'owner-a', openai: 'owner-b',+ sharedSystemCredential: { openai: 'owner-b' },+ revoked: badRevoked ? 42 : { openai: 'owner-b' },+ rejectedCredentialDigests: { anthropic: digest, openai: 42 },+ }));+ const before = fs.readFileSync(bindingFile, 'utf8');+ expect(isNativeProviderAuthBound('anthropic')).toBe(false);+ expect(isNativeProviderCredentialRejected('anthropic', 'd'.repeat(64))).toBe(true);+ expect(isNativeProviderCredentialRejected('anthropic', digest, { explicitReconnect: true })).toBe(true);+ expect(isNativeProviderCredentialRejected('anthropic', 'd'.repeat(64), { explicitReconnect: true })).toBe(false);+ expect(fs.readFileSync(bindingFile, 'utf8')).toBe(before);+ bindNativeProviderAuth('anthropic', { sharedSystem: true });+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({+ anthropic: 'owner-a', openai: 'owner-b',+ sharedSystemCredential: { openai: 'owner-b', anthropic: 'owner-a' },+ rejectedCredentialDigests: { anthropic: digest },+ });+ expect(isNativeProviderAuthBound('anthropic')).toBe(true);+ expect(isNativeProviderAuthRevoked('openai')).toBe(true);+ expect(isNativeProviderCredentialRejected('anthropic', digest)).toBe(true);+ });+ it('allows explicit recovery of unreadable binding state without enabling unrelated inheritance', () => {+ fs.mkdirSync(userDataDir, { recursive: true });+ fs.writeFileSync(bindingFile, '{broken');+ expect(isNativeProviderCredentialRejected('anthropic', 'e'.repeat(64))).toBe(true);+ expect(isNativeProviderCredentialRejected('anthropic', 'e'.repeat(64), { explicitReconnect: true })).toBe(false);+ bindNativeProviderAuth('anthropic', { sharedSystem: true });+ expect(isNativeProviderAuthBound('anthropic')).toBe(true);+ expect(isNativeProviderAuthRevoked('openai')).toBe(true);+ });it('claims available legacy credentials for the first owner only', () => {migrateLegacyNativeProviderAuthBindings('owner-a', {anthropic: true,diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.tsindex ff268c5909..5c7bc7d689 100644--- a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts@@ -81,6 +81,7 @@ function deps(overrides: Partial<PiNativeSubscriptionHandlerDeps> = {}): PiNativ})) as PiNativeSubscriptionHandlerDeps['fetch'],getChatgptAuth: vi.fn(async () => ({ accessToken: 'host-openai-token', accountId: 'account-1' })),getGrokToken: vi.fn(async () => 'host-xai-token'),+ peekGrokToken: vi.fn(() => 'host-xai-token'),invalidateChatgpt: vi.fn(async () => false),invalidateXai: vi.fn(async () => 'ignored' as const),recordXaiRateLimit: vi.fn(),@@ -787,7 +788,7 @@ describe('PI native subscription forwarding', () => {remainingRequests: 9,limitTokens: undefined,remainingTokens: undefined,- });+ }, 'xai');});it('labels pre-response xAI failures with the real provider and endpoint', async () => {@@ -912,3 +913,21 @@ describe('PI native subscription forwarding', () => {expect(res.status).toBe(404);});});++it.each([false, true])('scopes independent Grok limits and drops stale token pushes without failing streaming (stale=%s)', async stale => {+ const { setCustomProviderConfigs } = await import('../active-catalog.js');+ setCustomProviderConfigs([{ id: 'xai-work', name: 'Work', auth: { method: 'oauth', native: 'xai' }, runtimes: {} }]);+ try {+ const injected = deps({+ fetch: vi.fn(async () => new Response('stream ok', { status: 200, headers: { 'x-ratelimit-remaining-requests': '7' } })),+ peekGrokToken: vi.fn(() => stale ? 'replacement-token' : 'host-xai-token'),+ });+ const handler = getPiNativeSubscriptionHandler('xai-work', 'session-work', injected);+ const res = responseRecorder();+ await handler({ rawBody: Buffer.from('{}'), parsedBody: {}, ctx: { method: 'POST', url: '/v1/responses', headers: {} }, res } as never);+ expect(res.status).toBe(200);+ expect(Buffer.concat(res.chunks).toString()).toBe('stream ok');+ if (stale) expect(injected.recordXaiRateLimit).not.toHaveBeenCalled();+ else expect(injected.recordXaiRateLimit).toHaveBeenCalledWith(expect.objectContaining({ remainingRequests: 7 }), 'xai-work');+ } finally { setCustomProviderConfigs([]); }+});diff --git a/apps/desktop/src/main/maker-host/__tests__/provider-presentation-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/provider-presentation-store.test.tsnew file mode 100644index 0000000000..627b8557a4--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/provider-presentation-store.test.ts@@ -0,0 +1,133 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterAll, expect, it, vi } from 'vitest';++const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'provider-presentation-test-'));+let owner = 'first';+let generation = 0;+vi.mock('electron', () => ({ app: { getPath: () => '/tmp/never-used-here' } }));+vi.mock('../logger-adapter.js', () => ({+ desktopMakerLogger: { child: () => ({ info: () => {}, warn: () => {}, error: () => {} }) },+}));+vi.mock('../../appSessionState.js', () => ({+ activeOwnerScopeKey: () => `${owner}:${generation}`,+ ownerScopedUserDataPath: (name: string) => path.join(tmpDir, owner, name),+}));+const {+ readProviderPresentation,+ setProviderPresentation,+ readLocalCodexPresentation,+ renameLocalCodexProvider,+ setLocalCodexProviderRemoved,+ retainInvalidatedProviderPresentation,+ retainProviderPresentationAfterAuthChange,+} = await import('../provider-presentation-store.js');+const { withCrossProcessLock } = await import('../../device-link/crossProcessLock.js');+afterAll(() => fs.rmSync(tmpDir, { recursive: true, force: true }));++it.each(['openai', 'anthropic', 'xai', 'google', 'generic-oauth'])('does not fail committed %s authentication when presentation cannot be written', async (id) => {+ owner = `failed-presentation-${id}`;+ const write = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => { throw new Error('test readonly disk'); });+ try {+ await expect(retainProviderPresentationAfterAuthChange(id)).resolves.toBeUndefined();+ expect(write).toHaveBeenCalled();+ } finally {+ write.mockRestore();+ owner = 'first';+ }+});++it('persists generic OAuth restoration after a removed connection logs in again', async () => {+ owner = 'generic-restoration';+ await setProviderPresentation('generic-oauth', { name: 'Work', removed: true });+ await retainProviderPresentationAfterAuthChange('generic-oauth');+ expect(JSON.parse(fs.readFileSync(path.join(tmpDir, owner, 'local-codex-provider-prefs.json'), 'utf8')).providers['generic-oauth']).toEqual({ name: 'Work', removed: false });+ owner = 'first';+});++it('persists the name across removal and reconnect, isolated by Cindy owner', async () => {+ expect(readLocalCodexPresentation()).toEqual({});+ await renameLocalCodexProvider(' My OpenAI ');+ await setLocalCodexProviderRemoved(true);+ expect(readLocalCodexPresentation()).toEqual({ name: 'My OpenAI', removed: true });+ owner = 'second';+ expect(readLocalCodexPresentation()).toEqual({});+ await renameLocalCodexProvider('Other OpenAI');+ owner = 'first';+ expect(readLocalCodexPresentation()).toEqual({ name: 'My OpenAI', removed: true });+ await setLocalCodexProviderRemoved(false);+ expect(readLocalCodexPresentation()).toEqual({ name: 'My OpenAI', removed: false });+ expect(+ JSON.parse(+ fs.readFileSync(path.join(tmpDir, owner, 'local-codex-provider-prefs.json'), 'utf8'),+ ),+ ).toEqual({ name: 'My OpenAI', removed: false });+});+it('rejects empty or oversized names without changing the saved name', async () => {+ await expect(renameLocalCodexProvider(' ')).rejects.toThrow();+ await expect(renameLocalCodexProvider('a'.repeat(129))).rejects.toThrow();+ expect(readLocalCodexPresentation()).toEqual({ name: 'My OpenAI', removed: false });+});++it('keeps each native connection and local service name separate', async () => {+ await setProviderPresentation('anthropic', { name: 'Work Claude', removed: false });+ await setProviderPresentation('xai', { name: 'Grok', removed: true });+ await setProviderPresentation('ollama', { name: 'My machine' });+ expect(readProviderPresentation('anthropic')).toEqual({ name: 'Work Claude', removed: false });+ expect(readProviderPresentation('xai')).toEqual({ name: 'Grok', removed: true });+ expect(readProviderPresentation('ollama')).toEqual({ name: 'My machine' });+ expect(readLocalCodexPresentation()).toEqual({ name: 'My OpenAI', removed: false });+});++it.each(['anthropic', 'xai'])('retains invalidated legacy %s without reviving deleted entries', async (id) => {+ owner = `legacy-${id}`;+ expect(readProviderPresentation(id)).toEqual({});+ await retainInvalidatedProviderPresentation(id);+ expect(readProviderPresentation(id)).toEqual({ removed: false });+ await setProviderPresentation(id, { name: 'My account', removed: true });+ await retainInvalidatedProviderPresentation(id);+ expect(readProviderPresentation(id)).toEqual({ name: 'My account', removed: true });+ owner = `other-${id}`;+ expect(readProviderPresentation(id)).toEqual({});+});++it('merges queued edits with the latest disk snapshot instead of the cached providers', async () => {+ owner = 'concurrent-edit';+ await setProviderPresentation('anthropic', { name: 'Original' });+ const file = path.join(tmpDir, owner, 'local-codex-provider-prefs.json');+ let pending!: Promise<void>;+ await withCrossProcessLock(`${file}.lock`, { label: 'test-presentation-writer' }, async (status) => {+ expect(status.held).toBe(true);+ pending = setProviderPresentation('anthropic', { removed: true });+ fs.writeFileSync(file, JSON.stringify({ name: 'Native', providers: {+ anthropic: { name: 'Renamed elsewhere' }, xai: { name: 'Other provider' },+ } }));+ });+ await pending;+ expect(readProviderPresentation('anthropic')).toEqual({ name: 'Renamed elsewhere', removed: true });+ expect(readProviderPresentation('xai')).toEqual({ name: 'Other provider' });+ expect(readProviderPresentation('openai')).toEqual({ name: 'Native' });+});++it('does not revive a provider deleted while background retention waits for the lock', async () => {+ owner = 'concurrent-delete';+ const file = path.join(tmpDir, owner, 'local-codex-provider-prefs.json');+ fs.mkdirSync(path.dirname(file), { recursive: true });+ let pending!: Promise<void>;+ await withCrossProcessLock(`${file}.lock`, { label: 'test-presentation-delete' }, async (status) => {+ expect(status.held).toBe(true);+ pending = retainInvalidatedProviderPresentation('anthropic');+ fs.writeFileSync(file, JSON.stringify({ providers: { anthropic: { removed: true } } }));+ });+ await pending;+ expect(readProviderPresentation('anthropic')).toEqual({ removed: true });+});++it('rejects an old owner generation even if the owner returns before lock acquisition', async () => {+ owner = 'owner-aba';+ const pending = setProviderPresentation('openai', { name: 'Stale edit' });+ generation += 2;+ await expect(pending).rejects.toThrow('scope changed');+ expect(readProviderPresentation('openai')).toEqual({});+});diff --git a/apps/desktop/src/main/maker-host/__tests__/providerService.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerService.test.tsindex f3761541b3..b6798127ec 100644--- a/apps/desktop/src/main/maker-host/__tests__/providerService.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/providerService.test.ts@@ -9,6 +9,45 @@ import { createProviderService } from '../provider-service.js';const bundledCatalog = () => BUNDLED_CATALOG;describe('createProviderService', () => {+ it('uses managed provider configuration names instead of stale presentation overrides', async () => {+ const provider = buildUserProvider({+ id: 'cindy-local-ollama', name: 'Ollama', auth: { method: 'none' },+ runtimes: { codex: { baseUrl: 'http://localhost:11434/v1', models: [] } },+ }, { modelRegistry: BUNDLED_CATALOG.modelRegistry });+ const svc = createProviderService({+ getCatalog: () => ({ ...BUNDLED_CATALOG, providers: [provider] }),+ connection: { xd: () => false, anthropic: () => false, openai: () => false, xai: () => false },+ getProviderPresentation: () => ({ name: 'Deleted name', removed: true }),+ });+ expect((await svc.listProviders())[0]).toMatchObject({ id: 'cindy-local-ollama', name: 'Ollama' });+ });+ it('keeps authenticated accounts visible despite a stale removal preference', async () => {+ let connected = true;+ const svc = createProviderService({+ getCatalog: bundledCatalog,+ connection: { xd: () => false, anthropic: () => connected, openai: () => connected, xai: () => false },+ getProviderPresentation: (id) => ({ name: `My ${id}`, removed: true }),+ });+ for (const id of ['openai', 'anthropic']) {+ expect((await svc.listProviders()).find(p => p.id === id)).toMatchObject({ id, name: `My ${id}`, connected: true, removed: false });+ }+ connected = false;+ for (const id of ['openai', 'anthropic']) {+ expect((await svc.listProviders()).find(p => p.id === id)).toMatchObject({ connected: false, removed: true });+ }+ });+ it('applies local presentation without changing provider identity or catalog', async () => {+ const svc = createProviderService({+ getCatalog: bundledCatalog,+ connection: { xd: () => false, anthropic: () => false, openai: () => false, xai: () => false },+ getProviderPresentation: (id) => id === 'openai' ? { name: 'Personal OpenAI', removed: true } : {},+ });+ const providers = await svc.listProviders();+ expect(providers.find((p) => p.id === 'openai')).toMatchObject({ id: 'openai', name: 'Personal OpenAI', removed: true });+ expect(providers.find((p) => p.id === 'anthropic')?.removed).toBeUndefined();+ expect(providers.map((p) => p.id)).toEqual(BUNDLED_CATALOG.providers.map((p) => p.id));+ });+it('keeps media readiness separate from subscription authorization and scopes it by provider', async () => {let media = [{ providerId: 'openai', id: 'gpt-image-2' }];const svc = createProviderService({diff --git a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.tsindex 8ae6598b6e..5e95c7c1b0 100644--- a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts+++ b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts@@ -34,7 +34,7 @@ import { createResponsesHandler, type BridgeProviderConfig, type ResponsesBridgeimport { createMakerLogger } from './logger-adapter.js';import { getActiveCatalog } from './active-catalog.js';import { outboundFetch } from './outbound-fetch.js';-import { getGrokAccessToken } from './grok-oauth-login.js';+import { getGrokAccessToken, peekGrokAccessToken } from './grok-oauth-login.js';import { invalidateXaiBridgeAuth } from './xai-auth-invalidation-host.js';import { chatgptAccountIdFromIdToken, desktopCodexAuthAdapter } from './auth-adapters.js';import { codexAccountHome, codexAccountState, invalidateCodexAccount, isOpenAiSubscriptionProviderId } from './codex-account-auth.js';@@ -356,7 +356,10 @@ function xaiProviderConfig(providerId = 'xai'): BridgeProviderConfig {}),// 周用量走 cli-chat-proxy billing,不在这条推理链上。这里只尽力抓 x-ratelimit-*// 作为 RPM/TPM 瞬时值;拿不到不影响账号周用量 chip。- onRateLimit: (info) => { if (providerId === 'xai') recordXaiRateLimitSnapshot(info); },+ onRateLimit: (info, requestHeaders) => {+ const token = bearerAccessTokenFromHeaders(requestHeaders);+ if (!isAppSessionBoundaryPending() && token && token === peekGrokAccessToken(providerId)) recordXaiRateLimitSnapshot(info, providerId);+ },// 上游判定 OAuth 凭证失效时收口本地登录态。缺这一步的话:token 被服务端提前作废后// 本地 expires_at 仍未到期 → 永不刷新 → 每次请求都 403,而「设置 → 模型供应商」还// 一直显示已连接,用户没有任何线索该去重连。@@ -416,6 +419,7 @@ export interface PiNativeSubscriptionHandlerDeps {fetch: typeof outboundFetch;getChatgptAuth: typeof getChatgptBridgeAuth;getGrokToken: typeof getGrokAccessToken;+ peekGrokToken: typeof peekGrokAccessToken;invalidateChatgpt: typeof invalidateChatgptBridgeAuth;invalidateXai: typeof invalidateXaiBridgeAuth;recordXaiRateLimit: typeof recordXaiRateLimitSnapshot;@@ -425,6 +429,7 @@ const defaultPiNativeSubscriptionHandlerDeps: PiNativeSubscriptionHandlerDeps =fetch: outboundFetch,getChatgptAuth: getChatgptBridgeAuth,getGrokToken: getGrokAccessToken,+ peekGrokToken: peekGrokAccessToken,invalidateChatgpt: invalidateChatgptBridgeAuth,invalidateXai: invalidateXaiBridgeAuth,recordXaiRateLimit: recordXaiRateLimitSnapshot,@@ -487,6 +492,7 @@ function finiteRateLimitHeader(headers: Headers, name: string): number | undefinfunction recordNativeXaiRateLimit(headers: Headers,record: typeof recordXaiRateLimitSnapshot,+ providerId: string,): void {const info = {limitRequests: finiteRateLimitHeader(headers, 'x-ratelimit-limit-requests'),@@ -495,7 +501,7 @@ function recordNativeXaiRateLimit(remainingTokens: finiteRateLimitHeader(headers, 'x-ratelimit-remaining-tokens'),};if (Object.values(info).some((value) => value !== undefined)) {- record(info);+ record(info, providerId);}}@@ -795,8 +801,10 @@ export function getPiNativeSubscriptionHandler(body: new Uint8Array(outboundBody),signal: controller.signal,});- if (providerId === 'xai' && response.ok) {- recordNativeXaiRateLimit(response.headers, deps.recordXaiRateLimit);+ if (isXaiSubscriptionProviderId(providerId) && response.ok && !isAppSessionBoundaryPending() && scopeAtStart === activeOwnerScopeKey()) {+ try {+ if (accessToken === deps.peekGrokToken(providerId)) recordNativeXaiRateLimit(response.headers, deps.recordXaiRateLimit, providerId);+ } catch { /* Display-only; never interrupt successful forwarding. */ }}if (!response.ok) {const errorBody = Buffer.from(await response.arrayBuffer());diff --git a/apps/desktop/src/main/maker-host/auth-adapters.ts b/apps/desktop/src/main/maker-host/auth-adapters.tsindex 0c24fa2a81..202f95b92a 100644--- a/apps/desktop/src/main/maker-host/auth-adapters.ts+++ b/apps/desktop/src/main/maker-host/auth-adapters.ts@@ -1,3 +1,4 @@+import { retainInvalidatedProviderPresentation, retainProviderPresentationAfterAuthChange } from './provider-presentation-store.js';import { subscriptionAccountKind, subscriptionAccountState, readClaudeAccountOAuth, getValidClaudeAccountOAuth } from './subscription-account-auth.js';/*** apps/desktop/src/main/maker-host/auth-adapters.ts@@ -44,7 +45,7 @@ import {relinkSharedCodexAuth,resolveWindowsAclPrincipal,} from './codex-auth-link.js';-import { getPreferredSharedCodexAuthPath, getReleaseCodexAuthPath } from './codex-shared-auth.js';+import { getCodexCliAuthPath, getPreferredSharedCodexAuthPath, getReleaseCodexAuthPath } from './codex-shared-auth.js';export { resolveWindowsAclPrincipal } from './codex-auth-link.js';import { claudeOAuthSpawnEnv } from './claude-oauth-spawn-env.js';@@ -79,9 +80,7 @@ import {} from './codex-gateway-config.js';import { CLAUDE_PROVIDER_AUTH_PLACEHOLDER_KEY } from './claude-gateway-config.js';import {- clearClaudeAiOAuth,hasClaudeAiOAuth,- hasClaudeAiOAuthUnbound,} from './claude-credentials-store.js';import {disconnectClaudeAiOAuth,@@ -550,8 +549,10 @@ export class DesktopClaudeAuthAdapter implements AuthAdapter {// 订阅 refresh token 被服务端作废(锁内确认的 invalid_grant)→ 清态 + 广播重登提示,// 不让用户停在「显示已连接、会话连环 401」的假状态。纯内存接线,构造期零文件系统// 副作用(authAdaptersImportPurity 约定)。- setClaudeOAuthInvalidGrantHandler(() => {- void this.invalidate('claude_oauth_refresh_invalid_grant');+ setClaudeOAuthInvalidGrantHandler((digest) => {+ void this.invalidateNativeCredential('claude_oauth_refresh_invalid_grant', digest).catch((error) => {+ log.warn('claude invalidation cleanup failed', { error: error instanceof Error ? error.message : String(error) });+ });});}@@ -561,31 +562,22 @@ export class DesktopClaudeAuthAdapter implements AuthAdapter {}/**- * 订阅凭证被服务端作废时的收尾:清系统凭证(cc 对 invalid_grant 同样清盘)+ 失效- * 刷新器 + 广播 UI 重登。对齐 DesktopCodexAuthAdapter.invalidate 模式。+ * 订阅凭证被服务端作废时:停止刷新、撤销 Cindy 使用许可并广播重新登录提示。+ * 保留系统 Claude Code 凭证。*/- async invalidate(reason: string): Promise<void> {+ invalidate(reason: string): Promise<void> {+ return this.invalidateNativeCredential(reason);+ }++ private async invalidateNativeCredential(reason: string, rejectedCredentialDigest?: string): Promise<void> {log.warn('claude auth invalidated', { reason });invalidateClaudeOAuthRefresh();try {- if (hasClaudeAiOAuth()) clearClaudeAiOAuth();- // 凭证删除是 best-effort 的(clearClaudeAiOAuth 的 unlink 失败静默吞掉)。删干净了就- // **不**留抑制标记 —— 服务端作废不是用户意图,本机 CLI 重新登录后仍应享有设计内的自动- // 继承;可一旦没删掉,slot 空 + 凭证还在,下一次可信读取就会把这份刚被作废的凭证认领- // 回来、拿它重启发现,再 401、再 invalidate,在「已连接 / 失效」之间打转- // (PR #548 review)。所以按残留与否分流。- const residual = hasClaudeAiOAuthUnbound();- unbindNativeProviderAuth('anthropic', residual ? { revoked: true } : undefined);- if (residual) {- log.warn('claude credential still present after invalidate; suppressing auto-claim', {- reason,- });- }- } catch (e) {- log.warn('clear claude oauth on invalidate failed', {- error: e instanceof Error ? e.message : String(e),- });+ unbindNativeProviderAuth('anthropic', { revoked: true, ...(rejectedCredentialDigest ? { rejectedCredentialDigest } : {}) });+ } catch (error) {+ log.warn('claude credential revocation could not be persisted', { error: error instanceof Error ? error.message : String(error) });}+ const presentation = retainInvalidatedProviderPresentation('anthropic');if (this.onInvalidatedBroadcast) {try {this.onInvalidatedBroadcast(reason);@@ -593,6 +585,7 @@ export class DesktopClaudeAuthAdapter implements AuthAdapter {log.warn('onInvalidatedBroadcast threw', { error: (e as Error).message });}}+ await presentation;}async ensureSharedGlobalSkills(): Promise<void> {@@ -671,15 +664,9 @@ export class DesktopClaudeAuthAdapter implements AuthAdapter {}async logout(): Promise<void> {- // 连了订阅时,logout 清系统 Claude.ai OAuth 凭证(⚠️ 会同时登出本地 claude),- // **不动** gateway api_key(它是 XD 托管 key,网关来源 + oneShot 都还要用)。- if (hasClaudeAiOAuth()) {- // disconnect = 先失效刷新器再清凭证(唯一正确入口,见 claude-oauth-refresh 文档)- // —— 否则「已断开」状态下在途刷新回写会让凭证复活。- disconnectClaudeAiOAuth();- // 用户显式登出:留撤销标记。凭证删除是 best-effort(文件删除吞错),残留凭证不该在- // 下一次读连接态时被自动认领回来(PR #548 review)。- unbindNativeProviderAuth('anthropic', { revoked: true });+ // Only disconnect Cindy's native subscription binding; keep system and Gateway credentials.+ if (hasClaudeAiOAuth() || isNativeProviderAuthRevoked('anthropic')) {+ await disconnectClaudeAiOAuth();return;}// 经统一 store 移除本机 XD 网关 key。store.remove 把"文件本不存在"视为成功@@ -806,6 +793,7 @@ type PendingCodexLogin = {};type CodexDisconnectIntent = {+ ownerScopeKey: string;/** 显式 logout / 用户取消是单调升级意图;后到的 server invalidation 不能把它降级。 */explicitRequested: boolean;/** 当前磁盘 marker 已足以抑制残留 local auth;unlink 失败时仍可继续安全收口。 */@@ -1790,7 +1778,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {}triggerLogin(opts?: AuthLoginOptions): Promise<AuthState> {- if (this.devOAuthWritesBlocked()) {+ if (opts?.mode !== 'local' && this.devOAuthWritesBlocked()) {return Promise.resolve({authenticated: false,errorReason: 'dev_oauth_write_blocked',@@ -1878,6 +1866,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {opts?: AuthLoginOptions,isCancelled: () => boolean = () => false,): Promise<AuthState> {+ const loginOwner = getActiveAppSession();this.ensureInvalidationMarkerLoaded();this.loginAborted = false;this.loginCancellationOpen = true;@@ -1900,6 +1889,78 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {return { authenticated: false, errorReason: 'isolated_auth_cleanup_failed' };}}+ if (opts?.mode === 'local') {+ const owner = getActiveAppSession();+ const systemAuth = getSystemCodexAuthPath();+ const localAuth = path.join(this.codexHome, 'auth.json');+ const ownerCurrent = () => {+ const current = getActiveAppSession();+ return !isAppSessionBoundaryPending() &&+ !!owner.dataOwnerId && current.generation === loginOwner.generation &&+ current.dataOwnerId === loginOwner.dataOwnerId;+ };+ const stillCurrent = () => ownerCurrent() && !this.loginAborted && !isCancelled();+ try {+ if (!stillCurrent()) {+ return { authenticated: false, errorReason: 'login_cancelled' };+ }+ const invalidated = getActiveInvalidatedSystemCodexAuthMarker(this.codexHome, systemAuth, localAuth);+ if (invalidated && invalidated.reason !== CODEX_USER_DISCONNECT_REASON) {+ return { authenticated: false, errorReason: invalidated.reason };+ }+ const raw = fs.readFileSync(systemAuth, 'utf8');+ const identity = parseCodexAccountIdentity(raw);+ const tokens = JSON.parse(raw).tokens;+ if (typeof tokens?.access_token !== 'string' || !tokens.access_token) return { authenticated: false, errorReason: 'no_oauth' };+ if (!existsSync(localAuth) || !pathsReferToSameFileSync(localAuth, systemAuth)) {+ fs.mkdirSync(this.codexHome, { recursive: true, mode: 0o700 });+ // Retain the existing read-only Dev exception; writable runtimes must share+ // the native credential rather than rotate an independent refresh-token copy.+ if (this.shouldSnapshotReleaseCodexAuth(systemAuth, localAuth)) {+ const result = await copyCodexAuthSnapshot(systemAuth, localAuth);+ if (result.kind !== 'copied') throw new Error('Local auth snapshot failed');+ } else {+ await relinkSharedCodexAuth(systemAuth, localAuth);+ if (!pathsReferToSameFileSync(localAuth, systemAuth)) throw new Error('Local auth link failed');+ }+ }+ if (!stillCurrent()) {+ return { authenticated: false, errorReason: 'login_cancelled' };+ }+ bindNativeProviderAuth('openai', { sharedSystem: true });+ if (!clearInvalidatedSystemCodexAuthMarker(this.codexHome)) {+ unbindNativeProviderAuth('openai', { revoked: true });+ return { authenticated: false, errorReason: 'auth_boundary_clear_failed' };+ }+ this.devReadOnlyDetached = false;+ this.suppressSystemCodexReconcile = false;+ this.oauthInvalidatedReason = null;+ this.oauthInvalidatedCredentialScope = undefined;+ this.oauthRecoveryRequiredReason = null;+ this.oauthRecoveryCredentialScope = undefined;+ this.memoryOnlyInvalidatedSystemCredential = null;+ this.lastKnownCodexCredentialScope = 'system-shared';+ this.loginCancellationOpen = false;+ await retainProviderPresentationAfterAuthChange('openai');+ if (!ownerCurrent()) return { authenticated: false, errorReason: 'login_cancelled' };+ if (!stillCurrent()) return this.disconnectCodexOAuth().then(() => ({+ authenticated: false, errorReason: 'login_cancelled',+ }));+ await this.notifyCodexLoginSuccess();+ if (!ownerCurrent()) return { authenticated: false, errorReason: 'login_cancelled' };+ // Match browser finalization: a late Cancel must revoke Cindy's committed binding.+ // Return the promise so failed cleanup is not swallowed by the local setup catch.+ if (!stillCurrent()) return this.disconnectCodexOAuth().then(() => ({+ authenticated: false, errorReason: 'login_cancelled',+ }));+ return { authenticated: true, authSource: 'oauth', identity: identity?.label, credentialScope: 'system-shared' };+ } catch {+ if (!stillCurrent()) return { authenticated: false, errorReason: 'login_cancelled' };+ this.suppressSystemCodexReconcile = true;+ writeInvalidatedSystemCodexAuthMarker(this.codexHome, systemAuth, CODEX_USER_DISCONNECT_REASON, localAuth);+ return { authenticated: false, errorReason: 'local_auth_unavailable' };+ }+ }await this.ensureGlobalCodexAssets();// Binary 必须在应用启动时就绪 (bootstrap-electron 的 ready 钩子会阻塞预下载)。@@ -1933,7 +1994,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {// spawn codex login。POSIX 建独立进程组,取消/超时时连同回调 server 一起收割。return new Promise<AuthState>((resolve) => {- const mode: AgentLoginMode = opts?.mode ?? 'browser';+ const mode = opts?.mode === 'device-code' ? 'device-code' : 'browser';const proc = spawn(binaryPath, codexLoginArgs(mode), {shell: false,env: { ...process.env, CODEX_HOME: this.codexHome },@@ -2132,7 +2193,17 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {if (cancelledAfterStateRead) return cancelledAfterStateRead;if (!state.authenticated) return state;- // 真正拿到 OAuth 后才重启本地 codex host;失败只记日志,不翻转登录结果。+ await this.notifyCodexLoginSuccess();+ const cancelledAfterHostRestart = cancelFinalization();+ if (cancelledAfterHostRestart) return cancelledAfterHostRestart;+ await retainProviderPresentationAfterAuthChange('openai');+ const cancelledAfterPresentation = cancelFinalization();+ if (cancelledAfterPresentation) return cancelledAfterPresentation;+ return state;+ }++ /** All explicit OAuth entry points retire the old host after committing credentials. */+ private async notifyCodexLoginSuccess(): Promise<void> {if (this.onLoginSuccess) {try {await this.onLoginSuccess();@@ -2140,9 +2211,6 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {log.warn('onLoginSuccess threw', { error: (e as Error).message });}}- const cancelledAfterHostRestart = cancelFinalization();- if (cancelledAfterHostRestart) return cancelledAfterHostRestart;- return state;}/** Codex OAuth 子进程 abort —— 用户在浏览器授权流半路反悔时调。 */@@ -2160,11 +2228,14 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {invalidationMarkerCommitted?: boolean;}): Promise<void> {const explicitRequested = !opts?.preserveInvalidatedReason;- if (explicitRequested && this.devOAuthWritesBlocked()) {- log.info('dev read-only Codex disconnect blocked; shared login remains connected');- return Promise.resolve();- }if (this.logoutOperation) {+ if (this.logoutIntent && !this.isCodexDisconnectCurrent(this.logoutIntent)) {+ const requestedOwner = activeOwnerScopeKey();+ // 新 owner 的显式断开不能合并进旧 owner 的操作,也不能假报成功。+ return this.logoutOperation.catch(() => undefined).then(() => {+ if (!isAppSessionBoundaryPending() && activeOwnerScopeKey() === requestedOwner) return this.logout(opts);+ });+ }// 登录可能在第一次 logout 之后排队、等待同一个 barrier。后来的 logout 仍代表更新的// 用户意图,必须把这份 queued login 标成 cancelled,不能只复用旧 Promise 后让它启动。this.cancelLogin();@@ -2186,6 +2257,8 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {}if (!this.logoutIntent.acceptingIntent && this.logoutIntent.explicitRequested) {if (this.logoutIntent.devReadOnly) {+ this.commitExplicitCodexDisconnectBoundary(this.logoutIntent);+ unbindNativeProviderAuth('openai', { revoked: true });this.oauthInvalidatedReason = null;this.oauthInvalidatedCredentialScope = undefined;this.oauthRecoveryRequiredReason = null;@@ -2210,11 +2283,12 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {return this.logoutOperation;}const intent: CodexDisconnectIntent = {+ ownerScopeKey: activeOwnerScopeKey(),explicitRequested,invalidationMarkerCommitted: opts?.invalidationMarkerCommitted === true,explicitBoundaryCommitted: false,acceptingIntent: true,- devReadOnly: this.devOAuthWritesBlocked(),+ devReadOnly: !explicitRequested && this.devOAuthWritesBlocked(),};this.logoutIntent = intent;if (!intent.devReadOnly) this.warnDevOAuthWriteOverride('logout');@@ -2232,6 +2306,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {}private async runLogout(intent: CodexDisconnectIntent): Promise<void> {+ if (!this.isCodexDisconnectCurrent(intent)) return;this.ensureInvalidationMarkerLoaded();// 登出与在途登录串行:先取消并等它完全收口,防迟到的 auth.json 在登出后复活账号。const pendingLogin = this.pendingLogin?.promise;@@ -2239,18 +2314,23 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {this.cancelLogin();await pendingLogin.catch(() => undefined);}+ if (!this.isCodexDisconnectCurrent(intent)) return;await this.disconnectCodexOAuth(intent);}private async runDevReadOnlyLogout(intent: CodexDisconnectIntent): Promise<void> {+ if (!this.isCodexDisconnectCurrent(intent)) return;const pendingLogin = this.pendingLogin?.promise;if (pendingLogin) {this.cancelLogin();await pendingLogin.catch(() => undefined);}+ if (!this.isCodexDisconnectCurrent(intent)) return;this.devReadOnlyDetached = true;this.suppressSystemCodexReconcile = true;if (intent.explicitRequested) {+ this.commitExplicitCodexDisconnectBoundary(intent);+ unbindNativeProviderAuth('openai', { revoked: true });this.oauthInvalidatedReason = null;this.oauthInvalidatedCredentialScope = undefined;this.oauthRecoveryRequiredReason = null;@@ -2266,8 +2346,11 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {});}}+ if (!this.isCodexDisconnectCurrent(intent)) return;intent.acceptingIntent = false;if (intent.explicitRequested) {+ this.commitExplicitCodexDisconnectBoundary(intent);+ unbindNativeProviderAuth('openai', { revoked: true });this.oauthInvalidatedReason = null;this.oauthInvalidatedCredentialScope = undefined;this.oauthRecoveryRequiredReason = null;@@ -2277,7 +2360,12 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {log.info('dev read-only Codex auth detached in memory; durable credentials unchanged');}+ private isCodexDisconnectCurrent(intent: CodexDisconnectIntent): boolean {+ return !isAppSessionBoundaryPending() && intent.ownerScopeKey === activeOwnerScopeKey();+ }+private commitExplicitCodexDisconnectBoundary(intent: CodexDisconnectIntent): boolean {+ if (!this.isCodexDisconnectCurrent(intent)) return false;if (!intent.explicitRequested || intent.explicitBoundaryCommitted) return false;const persisted = writeInvalidatedSystemCodexAuthMarker(this.codexHome,@@ -2305,16 +2393,20 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {*/private async disconnectCodexOAuth(intent?: CodexDisconnectIntent): Promise<void> {const activeIntent: CodexDisconnectIntent = intent ?? {+ ownerScopeKey: activeOwnerScopeKey(),explicitRequested: true,invalidationMarkerCommitted: false,explicitBoundaryCommitted: false,acceptingIntent: true,devReadOnly: false,};+ if (!this.isCodexDisconnectCurrent(activeIntent)) return;this.commitExplicitCodexDisconnectBoundary(activeIntent);const authPath = path.join(this.codexHome, 'auth.json');try {- await fsp.rm(authPath, { force: true });+ if (!activeIntent.explicitRequested && path.resolve(authPath) !== path.resolve(getCodexCliAuthPath())) {+ await fsp.rm(authPath, { force: true });+ }} catch (err) {// 显式 logout 已在 durable marker 处完成线性化:即使 Windows 文件锁让旧文件// 暂时删不掉,所有 token 读取也会被 marker 抑制。继续做 host/cache/broadcast@@ -2330,13 +2422,14 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {},);}+ if (!this.isCodexDisconnectCurrent(activeIntent)) return;// ⚠️ 不删 sessions/ —— 历史上这里会 `rm -rf sessions/` 清空所有 thread 的 rollout// .jsonl(那是 resume 功能还不存在的年代留下的"登出即清本地状态"清理)。后来加了// 「从磁盘 rollout 续聊」(CodexAgent thread/resume) 和外部会话导入,xdt-maker 的会话// 续聊**依赖** rollout 文件存在。继续在登出/换账号时删 sessions/ 会让所有老会话// thread/resume 撞 "no rollout found" 永久坏掉(state DB 里 threads 行还在 → 留下指向// 已删文件的孤儿),且用户无法在多个 codex 账号间切换还各自保留会话历史。logout 只负责- // 撤销登录态(删 auth.json)即可,rollout 是用户数据,保留。+ // 显式断开只停用 Cindy;凭证及 rollout 均保留。// 不删 config.toml (MCP 配置由 Boss 5 管)// 收割 app-server 子进程 (它内存里仍持有旧 token; 不杀的话切账号会用旧 token 撞 401,// 或泄露老账号会话给新账号)。dispose 幂等: host 没起过就 no-op。失败仅 stderr 告警。@@ -2350,22 +2443,13 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {// models_cache.json 没有账号 ID,必须与 auth 边界一起失效。先 dispose host 再删,// 降低 Windows 文件锁概率;删失败仍由 disconnect marker + 内存快照清空保证 fail-closed,// 下次登录前会再次清理并在锁未释放时拒绝继续。+ if (!this.isCodexDisconnectCurrent(activeIntent)) return;await removeDesktopCodexModelsCache(this.codexHome);+ if (!this.isCodexDisconnectCurrent(activeIntent)) return;// invalidation 可能在显式 logout 进行中改写 marker;结束前再提交一次显式边界,保证// 后到的用户意图永久胜出。该 helper 无 await,因此这里之后不会再接受竞态升级。activeIntent.acceptingIntent = false;- const explicitBoundaryCommittedNow = this.commitExplicitCodexDisconnectBoundary(activeIntent);- if (explicitBoundaryCommittedNow && existsSync(authPath)) {- try {- await fsp.rm(authPath, { force: true });- } catch (err) {- // 升级后的 durable marker 已记录当前残留 local fingerprint;锁住时 token reads 仍被- // 抑制,删除可以继续 fail-soft。- log.warn('remove Codex auth.json after late explicit disconnect upgrade failed', {- error: err instanceof Error ? err.message : String(err),- });- }- }+ this.commitExplicitCodexDisconnectBoundary(activeIntent);// 只有用户显式登出才留下跨 provider 的 revoked 标记。服务端 token invalidation 只是// 清掉当前坏凭证,不能阻止用户在 ChatGPT App 重新登录后被 Cindy 自动认领。try {diff --git a/apps/desktop/src/main/maker-host/claude-credentials-store.ts b/apps/desktop/src/main/maker-host/claude-credentials-store.tsindex ca2486abd4..e13fd17e20 100644--- a/apps/desktop/src/main/maker-host/claude-credentials-store.ts+++ b/apps/desktop/src/main/maker-host/claude-credentials-store.ts@@ -20,6 +20,7 @@import os from 'node:os';import path from 'node:path';import fs from 'node:fs';+import { createHash } from 'node:crypto';import { execFileSync } from 'node:child_process';import { desktopMakerLogger } from './logger-adapter.js';@@ -28,7 +29,7 @@ import {decideKeychainWriteMode,planClaudeAiOAuthClear,} from './claude-credentials-blob.js';-import { isNativeProviderAuthBound } from './nativeProviderAuthBinding.js';+import { isNativeProviderAuthBound, isNativeProviderCredentialRejected } from './nativeProviderAuthBinding.js';const log = desktopMakerLogger.child('claude-credentials-store');@@ -175,6 +176,17 @@ function writeBlob(blob: Record<string, unknown>): void {*/export function readClaudeAiOAuth(): ClaudeAiOAuth | null {if (!isNativeProviderAuthBound('anthropic')) return null;+ const oauth = readClaudeAiOAuthUnbound();+ return oauth && !isNativeProviderCredentialRejected('anthropic', claudeOAuthCredentialDigest(oauth)) ? oauth : null;+}++/** Only token identity matters; profile and expiry metadata may change independently. */+export function claudeOAuthCredentialDigest(oauth: ClaudeAiOAuth): string {+ return createHash('sha256').update(JSON.stringify([oauth.accessToken, oauth.refreshToken ?? null])).digest('hex');+}++/** Read native credentials for an explicit reattachment without changing their owner. */+export function readClaudeAiOAuthUnbound(): ClaudeAiOAuth | null {const blob = readBlob();const oauth = blob?.claudeAiOauth as ClaudeAiOAuth | undefined;if (oauth && typeof oauth.accessToken === 'string' && oauth.accessToken.length > 0) {@@ -190,9 +202,7 @@ export function hasClaudeAiOAuth(): boolean {/** Legacy upgrade probe; intentionally bypasses owner binding once at migration time. */export function hasClaudeAiOAuthUnbound(): boolean {- const blob = readBlob();- const oauth = blob?.claudeAiOauth as ClaudeAiOAuth | undefined;- return typeof oauth?.accessToken === 'string' && oauth.accessToken.length > 0;+ return readClaudeAiOAuthUnbound() !== null;}/**diff --git a/apps/desktop/src/main/maker-host/claude-oauth-login.ts b/apps/desktop/src/main/maker-host/claude-oauth-login.tsindex 284307e959..4277363d5b 100644--- a/apps/desktop/src/main/maker-host/claude-oauth-login.ts+++ b/apps/desktop/src/main/maker-host/claude-oauth-login.ts@@ -269,6 +269,15 @@ let _currentListener: CallbackListener | null = null;let _currentAbort: AbortController | null = null;let _currentLoginKey: string | undefined;+/** Local attachment uses the same cancellation boundary as browser login. */+export function beginClaudeLocalLogin(loginKey?: string): AbortSignal {+ cancelClaudeOAuthLogin();+ _currentListener = null;+ _currentLoginKey = loginKey;+ _currentAbort = new AbortController();+ return _currentAbort.signal;+}+export interface ClaudeOAuthLoginResult {ok: boolean;/** 失败原因(reason)— 'login_cancelled' / 'timeout' / 具体错误信息。 */diff --git a/apps/desktop/src/main/maker-host/claude-oauth-refresh.ts b/apps/desktop/src/main/maker-host/claude-oauth-refresh.tsindex c80318d4fd..de992a6847 100644--- a/apps/desktop/src/main/maker-host/claude-oauth-refresh.ts+++ b/apps/desktop/src/main/maker-host/claude-oauth-refresh.ts@@ -47,11 +47,14 @@ import os from 'node:os';import path from 'node:path';import {- clearClaudeAiOAuth,+ claudeOAuthCredentialDigest,+ readClaudeAiOAuthUnbound,readClaudeAiOAuth,writeClaudeAiOAuth,type ClaudeAiOAuth,} from './claude-credentials-store.js';+import { bindNativeProviderAuth, isNativeProviderCredentialRejected, unbindNativeProviderAuth } from './nativeProviderAuthBinding.js';+import { retainProviderPresentationAfterAuthChange } from './provider-presentation-store.js';import { desktopMakerLogger } from './logger-adapter.js';import { outboundFetch } from './outbound-fetch.js';@@ -163,7 +166,7 @@ export interface ClaudeOAuthRefresherDeps {/** 锁冲突退避 sleep(测试注入 0 延迟)。 */sleep?: (ms: number) => Promise<void>;/** refresh token 被服务端作废(invalid_grant)时通知 —— adapter 接 invalidate 广播。 */- onInvalidGrant?: () => void;+ onInvalidGrant?: (credentialDigest: string) => void;/** 预续期开关(测试关掉避免悬挂 timer)。默认开。 */proactiveRenewal?: boolean;}@@ -522,6 +525,8 @@ export function createClaudeOAuthRefresher(deps: ClaudeOAuthRefresherDeps): {// refresh token;若 HTTP 在途期间凭证库已被换账号登录替换,invalidate 会把// 刚登录的新账号一并清掉 —— 先重读比对,库已换则采信新凭证、不触发失效。const postFail = deps.readOAuth();+ // Owner switch or unbinding removed access while the request was in flight.+ if (!postFail?.accessToken) return null;if (postFail?.accessToken &&(postFail.accessToken !== fresh.accessToken ||@@ -533,7 +538,7 @@ export function createClaudeOAuthRefresher(deps: ClaudeOAuthRefresherDeps): {// 库仍是失败那套凭证且服务端明确作废 → 刷新无望,通知 UI 重登。log.error('claude oauth refresh token revoked by server (invalid_grant)');try {- deps.onInvalidGrant?.();+ deps.onInvalidGrant?.(claudeOAuthCredentialDigest(fresh));} catch (e) {log.warn('onInvalidGrant handler threw', {error: e instanceof Error ? e.message : String(e),@@ -691,7 +696,7 @@ function defaultLockDir(): string {}let defaultRefresher: ReturnType<typeof createClaudeOAuthRefresher> | null = null;-let invalidGrantHandler: (() => void) | null = null;+let invalidGrantHandler: ((credentialDigest: string) => void) | null = null;function getDefaultRefresher(): ReturnType<typeof createClaudeOAuthRefresher> {if (!defaultRefresher) {@@ -702,7 +707,7 @@ function getDefaultRefresher(): ReturnType<typeof createClaudeOAuthRefresher> {fetchFn: outboundFetch,now: Date.now,lockDir: defaultLockDir,- onInvalidGrant: () => invalidGrantHandler?.(),+ onInvalidGrant: (digest) => invalidGrantHandler?.(digest),});}return defaultRefresher;@@ -737,21 +742,27 @@ export function backfillClaudeSubscriptionProfile(accessToken: string): Promise<return getDefaultRefresher().backfillSubscriptionProfile(accessToken);}-/**- * 断开 Claude.ai 订阅的唯一正确入口:先失效刷新器(generation++,在途刷新不写回、- * 预续期 timer 撤销),再清系统凭证。**所有**清除订阅凭证的调用点(adapter.logout、- * 设置页 CLAUDE_OAUTH_LOGOUT IPC、未来新增入口)必须走本函数而不是直接- * clearClaudeAiOAuth —— 否则「已断开」状态下在途刷新回写会让凭证复活- * (review 2026-07-04 P2:IPC 路径曾绕过失效联动)。- * 顺序约束:invalidate 必须先于 clear,防 clear 与在途写回的窗口竞态;clear 抛错- * (写后校验失败)原样上抛由调用方决定 UI 反馈,多 bump 的 generation 幂等无害。- */-export function disconnectClaudeAiOAuth(): void {+/** Stop Cindy refreshes and revoke only Cindy's use of the native subscription. */+export async function disconnectClaudeAiOAuth(): Promise<void> {+ invalidateClaudeOAuthRefresh();+ unbindNativeProviderAuth('anthropic', { revoked: true });+ await retainProviderPresentationAfterAuthChange('anthropic');+}++/** Reattach the existing native login; never write or remove system credentials. */+export function reconnectClaudeAiOAuth(): boolean {+ const oauth = readClaudeAiOAuthUnbound();+ if (!oauth || isNativeProviderCredentialRejected('anthropic', claudeOAuthCredentialDigest(oauth), { explicitReconnect: true })) return false;invalidateClaudeOAuthRefresh();- clearClaudeAiOAuth();+ bindNativeProviderAuth('anthropic', { sharedSystem: true });+ // Binding commits login synchronously; auxiliary disk contention must not keep Cancel open.+ void retainProviderPresentationAfterAuthChange('anthropic');+ return true;}/** refresh token 被服务端作废时的通知接线(auth-adapters 装配,内存操作零副作用)。 */-export function setClaudeOAuthInvalidGrantHandler(handler: (() => void) | null): void {+export function setClaudeOAuthInvalidGrantHandler(handler: ((credentialDigest: string) => void) | null): void {invalidGrantHandler = handler;}++export { claudeOAuthCredentialDigest } from './claude-credentials-store.js';diff --git a/apps/desktop/src/main/maker-host/codex-auth-invalidation.ts b/apps/desktop/src/main/maker-host/codex-auth-invalidation.tsindex 3f0e80b569..7d416f8d02 100644--- a/apps/desktop/src/main/maker-host/codex-auth-invalidation.ts+++ b/apps/desktop/src/main/maker-host/codex-auth-invalidation.ts@@ -504,18 +504,8 @@ export function restoreInvalidationStateOnStartup(: { recoveryRequiredReason: persistedMarker.reason }),};}- // marker 是 logout 的提交点。若进程在「写 marker → unlink auth」之间崩溃,启动时按- // local fingerprint 识别并清掉旧凭证;即使删除失败,readLocalCodexAuthState 也会忽略它。- if (- isDurableDisconnectMarker(marker) &&- localFileMatchesInvalidatedMarker(marker, localAuthPath)- ) {- try {- fs.unlinkSync(localAuthPath);- } catch {- /* read path 仍会按 marker fingerprint 抑制,不能让残留文件复活登录态。 */- }- }+ // A user disconnect only disables Cindy's use. Keep the credential intact,+ // including when localAuthPath is the native/shared login file itself.const localExists = fs.existsSync(localAuthPath);const hasReplacementLocalCredential =localExists &&diff --git a/apps/desktop/src/main/maker-host/codex-proxy-host.ts b/apps/desktop/src/main/maker-host/codex-proxy-host.tsindex 087eb3e308..35e3389c06 100644--- a/apps/desktop/src/main/maker-host/codex-proxy-host.ts+++ b/apps/desktop/src/main/maker-host/codex-proxy-host.ts@@ -1,4 +1,7 @@-import { isClaudeSubscriptionProviderId } from './subscription-account-auth.js';+import { peekGrokAccessToken } from './grok-oauth-login.js';+import { bearerAccessTokenFromHeaders } from './chatgpt-bridge-auth-invalidation.js';+import { isAppSessionBoundaryPending } from '../appSessionState.js';+import { isClaudeSubscriptionProviderId, isXaiSubscriptionProviderId } from './subscription-account-auth.js';/*** Desktop 端 codex-proxy 生命周期管理 ——*@@ -2570,7 +2573,11 @@ function isXaiUpstream(upstreamBase: string): boolean {function maybeRecordXaiRateLimit(ctx: ResponseObserverCtx): void {if (ctx.status < 200 || ctx.status >= 300) return;- if (!isXaiUpstream(ctx.upstreamBase)) return;+ if (!isXaiUpstream(ctx.upstreamBase) || isAppSessionBoundaryPending()) return;+ const { providerId } = providerContextForRequest(ctx.requestHeaders, readRequestMeta(ctx.requestBody).model ?? '');+ if (!providerId || !isXaiSubscriptionProviderId(providerId)) return;+ const token = bearerAccessTokenFromHeaders(ctx.outboundHeaders ?? ctx.requestHeaders);+ if (!token || token !== peekGrokAccessToken(providerId)) return;const info = {limitRequests: numericHeader(ctx.responseHeaders, 'x-ratelimit-limit-requests'),remainingRequests: numericHeader(ctx.responseHeaders, 'x-ratelimit-remaining-requests'),@@ -2578,7 +2585,7 @@ function maybeRecordXaiRateLimit(ctx: ResponseObserverCtx): void {remainingTokens: numericHeader(ctx.responseHeaders, 'x-ratelimit-remaining-tokens'),};if (Object.values(info).every((v) => v === undefined)) return;- recordXaiRateLimitSnapshot(info);+ recordXaiRateLimitSnapshot(info, providerId);}function tryReadSseEvent(line: string): { event: string | null; data: Record<string, unknown> | null } | null {@@ -2597,7 +2604,7 @@ function tryReadSseEvent(line: string): { event: string | null; data: Record<strfunction createCodexResponseObserver(): ResponseObserver {return (ctx) => {- maybeRecordXaiRateLimit(ctx);+ try { maybeRecordXaiRateLimit(ctx); } catch { /* Display-only; preserve successful responses. */ }if (ctx.method !== 'POST') return null;const path = ctx.url.split('?', 1)[0] ?? ctx.url;if (!path.endsWith('/responses') && path !== '/responses') return null;diff --git a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts b/apps/desktop/src/main/maker-host/createDesktopProviderService.tsindex cd11bf243a..3323745466 100644--- a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts+++ b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts@@ -1,3 +1,4 @@+import { readProviderPresentation } from './provider-presentation-store.js';import { filterLegacyGptContextProfiles } from './legacy-context-profiles.js';import { subscriptionAccountKind, subscriptionAccountState, isXaiSubscriptionProviderId, getValidClaudeAccountOAuth, resetSubscriptionAccountCaches } from './subscription-account-auth.js';/**@@ -990,6 +991,7 @@ export function getDesktopProviderService(): ProviderService {}if (singleton) return singleton;singleton = createProviderService({+ getProviderPresentation: readProviderPresentation,getCatalog: getDesktopSelectableCatalog,connection: {xd: () => getAppCapabilities().canUseCindyGateway && readClaudeApiKey() != null,diff --git a/apps/desktop/src/main/maker-host/grok-oauth-login.ts b/apps/desktop/src/main/maker-host/grok-oauth-login.tsindex 7bb1f0484a..3e73b9e5cc 100644--- a/apps/desktop/src/main/maker-host/grok-oauth-login.ts+++ b/apps/desktop/src/main/maker-host/grok-oauth-login.ts@@ -30,6 +30,7 @@ import {type OAuthResultPageLang,} from '../oauthResultPage.js';import { desktopMakerLogger } from './logger-adapter.js';+import { retainInvalidatedProviderPresentation } from './provider-presentation-store.js';import { outboundFetch } from './outbound-fetch.js';import { genericOAuthSecretIo, getProviderSecretStore } from '../secrets/providerSecretStore.js';import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';@@ -939,6 +940,9 @@ function createGrokAccount(providerId: string) {log.warn('xai refresh_token 已被服务端作废,清空本机凭证并回落未登录');}logoutGrok();+ const loggedOutGeneration = getGrokOAuthCredentialGeneration();+ if (providerId === 'xai') await retainInvalidatedProviderPresentation(providerId);+ if (!currentScope() || loggedOutGeneration !== getGrokOAuthCredentialGeneration()) return 'superseded';return 'logged_out';}default:diff --git a/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts b/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.tsindex 96cc244c8f..0c8dd94f7c 100644--- a/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts+++ b/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts@@ -23,6 +23,8 @@ import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFil// Windows topology semantics. Durability capabilities belong to the actual// host filesystem, so capture them before any such override can occur.const NATIVE_BINDING_HOST_PLATFORM = hostPlatform();+// Preserve the same rejection check in this process when durable revocation cannot be written.+const rejectedCredentialFallback = new Map<string, string>();const NATIVE_PROVIDER_IDS = ['anthropic',@@ -33,18 +35,19 @@ type BindingFile = Partial<Record<NativeProviderId, string>> & {legacyClaimOwner?: string;legacyClaimToken?: string;/**- * 被**显式登出**过、且尚未重新授权的 provider(值 = 执行登出的 owner,仅供诊断)。+ * 已撤销 Cindy 使用许可、且尚未重新连接的 provider(值 = 操作 owner,仅供诊断)。*- * 登出会先删凭证再解绑,但删除是 best-effort 的(Anthropic 的文件删除吞 ENOENT 之外的- * 错误、`logoutGrok` 忽略 secret store 的失败返回)。删除失败时 slot 已空、凭证却还在,- * 自动认领会立刻把它绑回来——等于悄悄撤销用户刚做的登出。+ * 本机 Codex/Claude 保留系统凭证;其它来源清理凭证也可能失败。slot 已空但凭证还在时,+ * 不能让自动认领悄悄恢复刚断开的连接。** 判定**不比对 owner**:标记说的是「这份残留凭证已被弃用」,而凭证存在共享的系统* keychain / CLI 里,换个账号它也还是登出那个账号的凭证——按 owner 比对等于给下一个* 账号开了继承别人凭证的口子(PR #548 review)。解除只有一条路:用户再次显式授权- * (`bindNativeProviderAuth` 清除),那时凭证已由本人重新写入。+ * (`bindNativeProviderAuth` 清除);本机重连须先核对服务端拒绝摘要。*/revoked?: Partial<Record<NativeProviderId, string>>;+ /** SHA-256 of a server-rejected credential; retained across manual disconnects. */+ rejectedCredentialDigests?: Partial<Record<NativeProviderId, string>>;/*** 由**用户在 Cindy 里亲自完成授权**而绑定的 provider(值 = 执行授权的 owner)。*@@ -111,6 +114,7 @@ type BindingRead =| { ok: true; bindings: BindingFile }/** 文件本身读不出来 / 根不是对象:整份归属都无从判断,没有可挽救的部分。 */| { ok: false; reason: 'unreadable' }+ | { ok: false; reason: 'badDigests'; bindings: BindingFile }/** 根有效、各 provider 归属可信,只有 revoked 这个字段被改坏。 */| { ok: false; reason: 'badRevoked'; bindings: Omit<BindingFile, 'revoked'> };@@ -174,6 +178,18 @@ function readBindingsOrFail(): BindingRead {// 只修 revoked、保住其余归属 —— 否则一次「修复」会把别人的 owner 抹掉,反倒开出新的// 误认领口子(PR #548 review)。const revoked = (value as { revoked?: unknown }).revoked;+ const digests = (value as BindingFile).rejectedCredentialDigests;+ const badDigests = digests !== undefined && (+ !digests || typeof digests !== 'object' || Array.isArray(digests) ||+ Object.values(digests).some(digest => typeof digest !== 'string' || !/^[a-f0-9]{64}$/.test(digest))+ );+ if (badDigests) {+ // Explicit repair preserves valid rejection evidence and unrelated owner metadata.+ (value as BindingFile).rejectedCredentialDigests = Object.fromEntries(+ Object.entries(digests && typeof digests === 'object' && !Array.isArray(digests) ? digests : {})+ .filter(([, digest]) => typeof digest === 'string' && /^[a-f0-9]{64}$/.test(digest)),+ );+ }if (revoked !== undefined &&(typeof revoked !== 'object' || revoked === null || Array.isArray(revoked))@@ -182,7 +198,9 @@ function readBindingsOrFail(): BindingRead {delete rest.revoked;return { ok: false, reason: 'badRevoked', bindings: rest };}- return { ok: true, bindings: value as BindingFile };+ return badDigests+ ? { ok: false, reason: 'badDigests', bindings: value as BindingFile }+ : { ok: true, bindings: value as BindingFile };} catch {return { ok: false, reason: 'unreadable' };}@@ -469,19 +487,31 @@ export function isNativeProviderAuthRevoked(provider: NativeProviderId): booleanreturn Boolean(read.ok && read.bindings.revoked && provider in read.bindings.revoked);}+/** Unreadable binding state cannot prove that reusing a native credential is safe. */+export function isNativeProviderCredentialRejected(provider: NativeProviderId, digest: string, opts?: { explicitReconnect: true }): boolean {+ if (rejectedCredentialFallback.get(`${bindingPath()}:${provider}`) === digest) return true;+ const read = readBindingsOrFail();+ if (!read.ok && !opts?.explicitReconnect) return true;+ // An explicit reconnect can reach bindNativeProviderAuth's conservative repair path.+ return read.ok || read.reason !== 'unreadable'+ ? read.bindings.rejectedCredentialDigests?.[provider] === digest+ : false;+}+/** Bind newly completed native OAuth to the current data owner. */export function bindNativeProviderAuth(provider: NativeProviderId,- opts?: { instanceIsolated?: boolean },+ opts?: { instanceIsolated?: boolean; sharedSystem?: boolean },): void {const owner = getActiveAppSession().dataOwnerId;if (!owner) throw new Error('cannot bind native provider auth without an active data owner');const written = withNativeBindingMutationLock(false, () => {const read = readBindingsOrFail();- if (read.ok) {+ if (read.ok || read.reason === 'badDigests') {const bindings = read.bindings;const sharedSystemCredential = sharedSystemCredentialOwners(bindings);- delete sharedSystemCredential[provider];+ if (opts?.sharedSystem) sharedSystemCredential[provider] = owner;+ else delete sharedSystemCredential[provider];const instanceIsolatedCredential = instanceIsolatedCredentialOwners(bindings);if (opts?.instanceIsolated) instanceIsolatedCredential[provider] = owner;else delete instanceIsolatedCredential[provider];@@ -494,10 +524,10 @@ export function bindNativeProviderAuth(// 记下「这是用户自己在 Cindy 里授权的」——继承类文案据此不再对它成立。writeBindings({...bindings,- selfAuthorized: { ...bindings.selfAuthorized, [provider]: owner },+ selfAuthorized: { ...bindings.selfAuthorized, [provider]: opts?.sharedSystem ? undefined : owner },sources: {...bindings.sources,- [provider]: 'explicit-provider-oauth',+ [provider]: opts?.sharedSystem ? 'native-harness-inherited' : 'explicit-provider-oauth',},sharedSystemCredential,instanceIsolatedCredential,@@ -519,7 +549,8 @@ export function bindNativeProviderAuth(// 授权即可恢复。const salvaged = read.reason === 'badRevoked' ? read.bindings : {};const sharedSystemCredential = sharedSystemCredentialOwners(salvaged);- delete sharedSystemCredential[provider];+ if (opts?.sharedSystem) sharedSystemCredential[provider] = owner;+ else delete sharedSystemCredential[provider];const instanceIsolatedCredential = instanceIsolatedCredentialOwners(salvaged);if (opts?.instanceIsolated) instanceIsolatedCredential[provider] = owner;else delete instanceIsolatedCredential[provider];@@ -530,10 +561,10 @@ export function bindNativeProviderAuth(writeBindings({...salvaged,revoked: suppressed,- selfAuthorized: { ...salvaged.selfAuthorized, [provider]: owner },+ selfAuthorized: { ...salvaged.selfAuthorized, [provider]: opts?.sharedSystem ? undefined : owner },sources: {...salvaged.sources,- [provider]: 'explicit-provider-oauth',+ [provider]: opts?.sharedSystem ? 'native-harness-inherited' : 'explicit-provider-oauth',},sharedSystemCredential,instanceIsolatedCredential,@@ -686,14 +717,19 @@ export function getNativeProviderAuthSource(/*** Remove the current owner binding after logout/invalidation.*- * `revoked: true` 只用于**用户显式登出**:它会留下一个持久标记,挡住后续的自动认领。- * 服务端作废凭证(401 invalidate)不传——那不是用户意图,凭证也已被清掉,用户之后在本机- * CLI 重新登录时仍应享有设计内的自动继承。+ * `revoked: true` 阻止自动认领,适用于用户断开及仍保留原生凭证的服务端失效。+ * 已确认服务端拒绝时可附凭证摘要;它与撤销标记原子落盘,手动断开不清除摘要。*/export function unbindNativeProviderAuth(provider: NativeProviderId,- opts?: { revoked?: boolean },+ opts?: { revoked?: boolean; rejectedCredentialDigest?: string },): void {+ if (opts?.rejectedCredentialDigest !== undefined && (+ !opts.revoked || !/^[a-f0-9]{64}$/.test(opts.rejectedCredentialDigest)+ )) throw new Error('Invalid rejected credential digest');+ if (opts?.rejectedCredentialDigest) {+ rejectedCredentialFallback.set(`${bindingPath()}:${provider}`, opts.rejectedCredentialDigest);+ }// 归属读不出来时放弃写入。用户的意图是「登出这一个 provider」,不是「把其余 provider 的// 归属清空」—— 而把损坏文件覆盖成一份只剩撤销标记的新文件正是后者,其余 provider 从此// 无主,下一次可信读取就会把它们的残留凭证认领给当前账号(PR #548 review)。@@ -767,6 +803,12 @@ export function unbindNativeProviderAuth(bindings.instanceIsolatedCredential = instanceIsolatedCredential;}if (marking) bindings.revoked = { ...(bindings.revoked ?? {}), [provider]: owner as string };+ if (marking && opts?.rejectedCredentialDigest) {+ bindings.rejectedCredentialDigests = {+ ...bindings.rejectedCredentialDigests,+ [provider]: opts.rejectedCredentialDigest,+ };+ }writeBindings(bindings);});}diff --git a/apps/desktop/src/main/maker-host/provider-presentation-store.ts b/apps/desktop/src/main/maker-host/provider-presentation-store.tsnew file mode 100644index 0000000000..190f10e2d2--- /dev/null+++ b/apps/desktop/src/main/maker-host/provider-presentation-store.ts@@ -0,0 +1,91 @@+import { activeOwnerScopeKey, ownerScopedUserDataPath } from '../appSessionState.js';+import { desktopMakerLogger } from './logger-adapter.js';+import { createOverrideSettingsFile } from './override-settings-file.js';++export interface ProviderPresentation {+ name?: string;+ removed?: boolean;+}+interface PresentationFile extends ProviderPresentation {+ providers?: Record<string, ProviderPresentation>;+}+function normalizePresentation(raw: unknown): ProviderPresentation {+ if (!raw || typeof raw !== 'object') return {};+ const value = raw as ProviderPresentation;+ return {+ ...(typeof value.name === 'string' && value.name.trim() && value.name.length <= 128+ ? { name: value.name.trim() }+ : {}),+ ...(typeof value.removed === 'boolean' ? { removed: value.removed } : {}),+ };+}+const log = desktopMakerLogger.child('provider-presentation');+const store = createOverrideSettingsFile<PresentationFile>({+ // Preserve the original OpenAI preferences without a migration or duplicate source of truth.+ filePath: () => ownerScopedUserDataPath('local-codex-provider-prefs.json'),+ scopeKey: activeOwnerScopeKey,+ defaults: {},+ normalize: (raw) => {+ const root = normalizePresentation(raw);+ const providers = (raw as PresentationFile | null)?.providers;+ if (!providers || typeof providers !== 'object' || Array.isArray(providers)) return root;+ return {+ ...root,+ providers: Object.fromEntries(+ Object.entries(providers)+ .filter(([id]) => /^[a-zA-Z0-9._-]{1,128}$/.test(id) && id !== 'openai')+ .map(([id, value]) => [id, normalizePresentation(value)]),+ ),+ };+ },+ log,+ label: 'provider-presentation',+});+export function readProviderPresentation(providerId: string): ProviderPresentation {+ store.invalidateIfChanged();+ const { name, removed, providers } = store.read();+ return providerId === 'openai'+ ? { ...(name ? { name } : {}), ...(removed !== undefined ? { removed } : {}) }+ : (providers?.[providerId] ?? {});+}+export async function setProviderPresentation(providerId: string, patch: ProviderPresentation): Promise<void> {+ if (!/^[a-zA-Z0-9._-]{1,128}$/.test(providerId)) throw new Error('Invalid provider id');+ if (patch.name !== undefined && (!patch.name.trim() || patch.name.length > 128))+ throw new Error('Invalid provider name');+ const normalized = normalizePresentation(patch);+ await store.updateAtomic(({ value }) => {+ if (providerId === 'openai') return normalized;+ const providers = value.providers ?? {};+ return {+ providers: { ...providers, [providerId]: { ...providers[providerId], ...normalized } },+ };+ });+}+export const readLocalCodexPresentation = () => readProviderPresentation('openai');+/** Login or disconnect is already committed; display preferences cannot reverse its result. */+export async function retainProviderPresentationAfterAuthChange(providerId: string): Promise<void> {+ try {+ await setProviderPresentation(providerId, { removed: false });+ } catch (error) {+ log.warn('Failed to retain provider presentation after authentication change', { providerId, error: String(error) });+ }+}+/** Retain upgrade-era connections without resurrecting explicitly deleted rows. */+export async function retainInvalidatedProviderPresentation(providerId: string): Promise<void> {+ try {+ await store.updateAtomic(({ value }) => {+ const current = providerId === 'openai' ? value : value.providers?.[providerId];+ if (current?.removed !== undefined) return {};+ return providerId === 'openai' ? { removed: false } : {+ providers: { ...value.providers, [providerId]: { ...current, removed: false } },+ };+ });+ } catch (error) {+ // Display preferences must not prevent credential invalidation or its broadcast.+ log.warn('Failed to retain invalidated provider', { providerId, error: String(error) });+ }+}+export const renameLocalCodexProvider = (name: string) =>+ setProviderPresentation('openai', { name });+export const setLocalCodexProviderRemoved = (removed: boolean) =>+ setProviderPresentation('openai', { removed });diff --git a/apps/desktop/src/main/maker-host/provider-service.ts b/apps/desktop/src/main/maker-host/provider-service.tsindex 1f54932c2d..516e7e778f 100644--- a/apps/desktop/src/main/maker-host/provider-service.ts+++ b/apps/desktop/src/main/maker-host/provider-service.ts@@ -72,6 +72,7 @@ export interface ProviderConnectionReaders {}export interface ProviderServiceDeps {+ getProviderPresentation?: (providerId: string) => { name?: string; removed?: boolean };/** 返回当前生效目录(同步)。桌面端注入 active-catalog 的 getActiveCatalog。 */getCatalog: () => Catalog;/** 连接状态判定器。 */@@ -205,7 +206,10 @@ export function createProviderService(deps: ProviderServiceDeps): ProviderServic.map(async p => subscriptionInfo.set(p.id, await deps.subscriptionAccountInfo!(p.id))));return buildRegistry(catalog, connected, discoveryFailures, deps.getModelAccess?.()).map((provider) => ({...(subscriptionInfo.get(provider.id) ? { subscriptionAccount: subscriptionInfo.get(provider.id) } : {}),- ...provider, ...(accountInfo.get(provider.id) ? { openAiAccount: accountInfo.get(provider.id) } : {}),+ ...provider, ...(provider.source === 'builtin' ? deps.getProviderPresentation?.(provider.id) ?? {} : {}), ...(accountInfo.get(provider.id) ? { openAiAccount: accountInfo.get(provider.id) } : {}),+ // Deletion disconnects first. A live binding wins over a stale removed flag if+ // restoring display preferences failed after authentication was committed.+ ...(provider.connected ? { removed: false } : {}),})).map((provider) =>media === undefineddiff --git a/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.tsindex 58323106ca..4b124536cd 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts@@ -7,12 +7,48 @@ import { registerMakerUsageHandlers, toLegacyUsdModelPricing } from '../usageHanimport { CodexRateLimitResetRejectedError } from '../../usage/codexRateLimitReset';import { IpcHarness } from './helpers/ipcHarness';import { zeroUsageMoney } from '../../../shared/regionalMoney';+import * as appSessionState from '../../appSessionState';function createMakerStub(methods: Partial<Maker>): Maker {return methods as Maker;}describe('maker auth IPC handlers', () => {+ it.each(['logout', 'auth-change'])('does not broadcast an old owner logout after %s yields', async (phase) => {+ const owner = vi.spyOn(appSessionState, 'activeOwnerScopeKey').mockReturnValue('owner-a:1');+ try {+ let finish!: () => void;+ const gate = new Promise<void>((resolve) => { finish = resolve; });+ const harness = new IpcHarness();+ const broadcast = vi.fn();+ const logoutAgent = vi.fn(() => phase === 'logout' ? gate : Promise.resolve());+ const onCodexAuthChange = vi.fn(() => phase === 'auth-change' ? gate : Promise.resolve());+ registerMakerAuthHandlers(harness, createMakerStub({ logoutAgent }), broadcast, () => null, onCodexAuthChange);+ const result = harness.invoke(MAKER_INVOKE.AUTH_LOGOUT, 'codex');+ await vi.waitFor(() => expect(phase === 'logout' ? logoutAgent : onCodexAuthChange).toHaveBeenCalledOnce());+ owner.mockReturnValue('owner-b:2');+ finish();+ await result;+ expect(broadcast).not.toHaveBeenCalled();+ if (phase === 'logout') expect(onCodexAuthChange).not.toHaveBeenCalled();+ } finally {+ owner.mockRestore();+ }+ });++ it('rejects a stale owner before disconnecting any account', async () => {+ const harness = new IpcHarness();+ const logoutAgent = vi.fn();+ registerMakerAuthHandlers(harness, createMakerStub({ logoutAgent }), vi.fn(), () => null);+ await expect(+ harness.invoke(MAKER_INVOKE.AUTH_LOGOUT, 'codex', {+ dataOwnerId: 'stale-owner',+ ownerGeneration: -1,+ }),+ ).rejects.toThrow();+ expect(logoutAgent).not.toHaveBeenCalled();+ });+it('delegates auth state lookup to Maker', async () => {const harness = new IpcHarness();const getAgentAuthState = vi.fn().mockResolvedValue({ authenticated: true });diff --git a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.tsindex 954780c71c..3a28bd7476 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts@@ -8,7 +8,7 @@ import { BUILTIN_REFRESHABLE_PROVIDER_IDS } from '../../../shared/providerModelRimport type { DbClient } from '../../localDb/client/DbClient.js';import { clearCurrentDbClient, setCurrentDbClient } from '../../localDb/client/current.js';import * as schema from '../../localDb/schema.js';-import { getCustomProvider, listCustomProviders } from '../../maker-host/custom-provider-store.js';+import { createCustomProvider, getCustomProvider, listCustomProviders } from '../../maker-host/custom-provider-store.js';import { codexCustomProviderConfigSignature } from '../../maker-host/codex-custom-provider-route.js';import {beginProviderRouteMutation,@@ -1529,6 +1529,7 @@ describe('provider:custom:* CRUD handlers', () => {mountDb();const harness = new IpcHarness();const finalize = vi.fn(async () => {});+ const broadcastChanged = vi.fn();const refreshCatalog = vi.fn<() => Promise<void>>().mockResolvedValueOnce(undefined)@@ -1538,6 +1539,7 @@ describe('provider:custom:* CRUD handlers', () => {makeDeps({beginRouteMutation: beginProviderRouteMutation,refreshCatalog,+ broadcastChanged,finalizeCodexCustomProviderHostChange: finalize,}),);@@ -1553,12 +1555,13 @@ describe('provider:custom:* CRUD handlers', () => {codex: { ...config.runtimes.codex!, requestPath: '/replacement-responses' },},}),- ).rejects.toThrow('catalog refresh failed');+ ).resolves.toEqual({ ok: true });expect((await getCustomProvider(config.id))?.runtimes.codex?.requestPath).toBe('/replacement-responses',);expect(getProviderRouteCredentialRevision(config.id)).not.toBe(oldRevision);expect(finalize).toHaveBeenCalledTimes(2);+ expect(broadcastChanged).toHaveBeenCalledTimes(2);});it('never revives an old dispatch generation after deleting and recreating the same Provider id', async () => {@@ -2124,6 +2127,17 @@ describe('provider:custom:* CRUD handlers', () => {).resolves.toEqual({ ok: true });expect((await listCustomProviders())[0]?.name).toBe('Legacy custom xAI edited');+ const beforeDisconnect = await getCustomProvider('xai');+ await expect(+ harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_DISCONNECT, 'custom:xai'),+ ).resolves.toEqual({ ok: true });+ expect(await getCustomProvider('xai')).toEqual(beforeDisconnect);+ for (const agent of ['claude-code', 'codex', 'pi']) {+ expect(deps.removeCustomProviderKey).toHaveBeenCalledWith('xai', agent);+ expect(deps.removeCustomProviderHeaders).toHaveBeenCalledWith('xai', agent);+ expect(deps.removeCustomProviderKey).not.toHaveBeenCalledWith('custom:xai', agent);+ }+await expect(harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_DELETE, 'xai'),).resolves.toEqual({ ok: true });@@ -3428,6 +3442,23 @@ describe('provider:oauth mutation ordering', () => {expect(calls).toEqual(['cancel', 'logout']);});+ it('does not invalidate an ongoing login when logout only asks for busy confirmation', async () => {+ const harness = new IpcHarness();+ let finish!: (result: { ok: boolean }) => void;+ const login = vi.fn(() => new Promise<{ ok: boolean }>(resolve => { finish = resolve; }));+ const deps = makeDeps({ oauthLogin: login,+ hasAppliedCodexCustomProviderImageGeneration: () => true,+ listBusyLocalCodexSessionIds: () => ['busy-task'],+ });+ registerProviderHandlers(harness, deps);+ const pending = harness.invoke(MAKER_INVOKE.PROVIDER_OAUTH_LOGIN, 'openrouter');+ await vi.waitFor(() => expect(login).toHaveBeenCalledOnce());+ await expect(harness.invoke(MAKER_INVOKE.PROVIDER_OAUTH_LOGOUT, 'openrouter', undefined, { source: 'manual-settings' })).resolves.toMatchObject({ ok: false, confirmationRequired: 'codex-image-generation-reload' });+ expect(deps.oauthCancel).not.toHaveBeenCalled();+ finish({ ok: true });+ await expect(pending).resolves.toEqual({ ok: true });+ });+it('encodes credential deletion failures as an IPC INTERNAL error', async () => {const harness = new IpcHarness();registerProviderHandlers(@@ -3811,3 +3842,145 @@ describe('model context limit IPC', () => {expect(deps.writeModelContextLimit).not.toHaveBeenCalled();});});+++describe('provider connection management', () => {+ it.each(['private-provider', 'cindy-local-ollama'])('broadcasts committed %s rename despite catalog failure without changing credentials or Host', async (id) => {+ mountDb();+ const harness = new IpcHarness();+ const config = { ...validConfig, id };+ await createCustomProvider(config);+ const before = await getCustomProvider(id);+ const deps = makeDeps({+ listProviders: async () => [{ id, source: 'user' } as ProviderView],+ currentOwnerSession: () => ({ dataOwnerId: 'owner-a', generation: 1 }),+ refreshCatalog: vi.fn(async () => { throw new Error('catalog unavailable'); }),+ });+ registerProviderHandlers(harness, deps);+ await expect(harness.invoke(MAKER_INVOKE.PROVIDER_PRESENTATION_SET, {+ providerId: id, action: 'rename', name: 'New name', dataOwnerId: 'owner-a', ownerGeneration: 1,+ })).resolves.toBeUndefined();+ expect(await getCustomProvider(id)).toEqual({ ...before, name: 'New name' });+ expect(deps.broadcastChanged).toHaveBeenCalledOnce();+ expect(deps.oauthCancel).not.toHaveBeenCalled();+ expect(deps.removeCustomProviderKey).not.toHaveBeenCalled();+ expect(deps.prepareCodexCustomProviderHostChange).not.toHaveBeenCalled();+ expect(deps.finalizeCodexCustomProviderHostChange).not.toHaveBeenCalled();+ });+ it('stores managed Ollama rename with its configuration and drops it when deleting and readding', async () => {+ mountDb();+ const harness = new IpcHarness();+ const config = { ...validConfig, id: 'cindy-local-ollama', name: 'Ollama' };+ await createCustomProvider(config);+ registerProviderHandlers(harness, makeDeps({+ listProviders: async () => [{ id: config.id, source: 'user' } as ProviderView],+ currentOwnerSession: () => ({ dataOwnerId: 'owner-a', generation: 1 }),+ }));+ await harness.invoke(MAKER_INVOKE.PROVIDER_PRESENTATION_SET, { providerId: config.id, action: 'rename', name: 'My local models', dataOwnerId: 'owner-a', ownerGeneration: 1 });+ expect((await getCustomProvider(config.id))?.name).toBe('My local models');+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_DELETE, config.id);+ await createCustomProvider(config);+ expect((await getCustomProvider(config.id))?.name).toBe('Ollama');+ });+ it('renames only the stored name and preserves runtimes, models and credentials', async () => {+ mountDb();+ const harness = new IpcHarness();+ const config: CustomProviderConfig = { ...validConfig };+ const deps = makeDeps({ listProviders: async () => [{ id: config.id, source: 'user' } as ProviderView],+ currentOwnerSession: () => ({ dataOwnerId: 'owner-a', generation: 1 }) });+ registerProviderHandlers(harness, deps);+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, config);+ const before = await getCustomProvider(config.id);+ vi.mocked(deps.oauthCancel).mockClear();+ await harness.invoke(MAKER_INVOKE.PROVIDER_PRESENTATION_SET, { providerId: config.id, action: 'rename', name: 'Work account', dataOwnerId: 'owner-a', ownerGeneration: 1 });+ expect(await getCustomProvider(config.id)).toEqual({ ...before, name: 'Work account' });+ expect(deps.oauthCancel).not.toHaveBeenCalled();+ expect(deps.removeCustomProviderKey).not.toHaveBeenCalled();+ });++ it.each([MAKER_INVOKE.PROVIDER_CUSTOM_DISCONNECT, MAKER_INVOKE.PROVIDER_CUSTOM_DELETE, MAKER_INVOKE.PROVIDER_OAUTH_LOGOUT])('requires busy Host confirmation before %s changes credentials', async (channel) => {+ mountDb();+ const harness = new IpcHarness();+ const deps = makeDeps({+ listBusyLocalCodexSessionIds: () => ['busy-task'],+ hasAppliedCodexCustomProviderImageGeneration: () => true,+ });+ registerProviderHandlers(harness, deps);+ const config = imageProviderConfig('disconnect-image-provider');+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, config, { codex: 'fixture-key' });+ vi.mocked(deps.prepareCodexCustomProviderHostChange!).mockClear();+ vi.mocked(deps.oauthCancel).mockClear();+ vi.mocked(deps.removeCustomProviderKey).mockClear();+ await expect(harness.invoke(channel, config.id, undefined, { source: 'manual-settings' })).resolves.toEqual({+ ok: false, confirmationRequired: 'codex-image-generation-reload', busyCount: 1,+ });+ expect(deps.prepareCodexCustomProviderHostChange).not.toHaveBeenCalled();+ expect(deps.oauthCancel).not.toHaveBeenCalled();+ expect(deps.removeCustomProviderKey).not.toHaveBeenCalled();+ expect(await getCustomProvider(config.id)).not.toBeNull();+ await expect(harness.invoke(channel, config.id, undefined, {+ source: 'manual-settings', codexImageGenerationRestartPolicy: 'interrupt',+ })).resolves.toEqual({ ok: true });+ expect(deps.prepareCodexCustomProviderHostChange).toHaveBeenCalledOnce();+ });++ it.each([MAKER_INVOKE.PROVIDER_CUSTOM_DISCONNECT, MAKER_INVOKE.PROVIDER_CUSTOM_DELETE, MAKER_INVOKE.PROVIDER_OAUTH_LOGOUT])('reports committed %s and broadcasts despite catalog refresh failure', async (channel) => {+ mountDb();+ const harness = new IpcHarness();+ const deps = makeDeps({+ beginRouteMutation: beginProviderRouteMutation,+ hasAppliedCodexCustomProviderImageGeneration: () => true,+ });+ registerProviderHandlers(harness, deps);+ const config = imageProviderConfig('committed-catalog-failure');+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, config, { codex: 'fixture-key' });+ const oldRevision = getProviderRouteCredentialRevision(config.id);+ vi.mocked(deps.refreshCatalog).mockRejectedValueOnce(new Error('catalog refresh failed'));+ vi.mocked(deps.broadcastChanged).mockClear();+ vi.mocked(deps.finalizeCodexCustomProviderHostChange!).mockClear();++ await expect(harness.invoke(channel, config.id)).resolves.toEqual({ ok: true });+ expect(getProviderRouteCredentialRevision(config.id)).not.toBe(oldRevision);+ expect(deps.broadcastChanged).toHaveBeenCalledOnce();+ expect(deps.finalizeCodexCustomProviderHostChange).toHaveBeenCalledOnce();+ if (channel === MAKER_INVOKE.PROVIDER_CUSTOM_DELETE) {+ expect(await getCustomProvider(config.id)).toBeNull();+ } else {+ expect(await getCustomProvider(config.id)).not.toBeNull();+ }+ if (channel === MAKER_INVOKE.PROVIDER_OAUTH_LOGOUT) {+ expect(deps.oauthLogout).toHaveBeenCalledWith(config.id);+ } else {+ expect(deps.removeCustomProviderKey).toHaveBeenCalledWith(config.id, 'codex');+ }+ });++ it('disconnects all API runtime credentials while retaining connection configuration', async () => {+ mountDb();+ const harness = new IpcHarness();+ const deps = makeDeps();+ registerProviderHandlers(harness, deps);+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, validConfig, { codex: 'fixture-key' });+ const before = await getCustomProvider(validConfig.id);+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_DISCONNECT, validConfig.id);+ expect(await getCustomProvider(validConfig.id)).toEqual(before);+ for (const agent of ['claude-code', 'codex', 'pi']) {+ expect(deps.removeCustomProviderKey).toHaveBeenCalledWith(validConfig.id, agent);+ expect(deps.removeCustomProviderHeaders).toHaveBeenCalledWith(validConfig.id, agent);+ }+ expect(deps.oauthLogout).not.toHaveBeenCalled();+ });++ it.each([MAKER_INVOKE.PROVIDER_CUSTOM_DISCONNECT, MAKER_INVOKE.PROVIDER_CUSTOM_DELETE, MAKER_INVOKE.PROVIDER_OAUTH_LOGOUT])('rejects stale confirmation owner before %s mutates anything', async (channel) => {+ mountDb();+ const harness = new IpcHarness();+ const deps = makeDeps({ currentOwnerSession: () => ({ dataOwnerId: 'owner-b', generation: 2 }) });+ registerProviderHandlers(harness, deps);+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, validConfig);+ const before = await getCustomProvider(validConfig.id);+ await expect(harness.invoke(channel, validConfig.id, { dataOwnerId: 'owner-a', ownerGeneration: 1 }, { source: 'manual-settings', codexImageGenerationRestartPolicy: 'interrupt' })).rejects.toThrow('active account changed');+ expect(await getCustomProvider(validConfig.id)).toEqual(before);+ expect(deps.oauthLogout).not.toHaveBeenCalled();+ expect(deps.removeCustomProviderKey).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/maker-ipc/authHandlers.ts b/apps/desktop/src/main/maker-ipc/authHandlers.tsindex f7e4a2799c..8daaf530f7 100644--- a/apps/desktop/src/main/maker-ipc/authHandlers.ts+++ b/apps/desktop/src/main/maker-ipc/authHandlers.ts@@ -8,6 +8,7 @@import type { AgentKind, AgentLoginMode, AuthState, Maker } from '@cindy/maker-core';import { optionalEnum, requireEnum, requireObject, throwIpcError } from '../utils/ipcValidate.js';+import { activeOwnerScopeKey, getActiveAppSession, isAppSessionBoundaryPending } from '../appSessionState.js';import { createLogger } from '../logger.js';import { MAKER_INVOKE, MAKER_PUSH } from './channels.js';import type { IpcHandlerRegistry } from './ipcHandlerRegistry.js';@@ -19,7 +20,7 @@ export type MakerIpcBroadcast = (channel: string, payload: unknown) => void;/** IPC 允许的 agent 种类;运行时枚举校验不能靠 TypeScript 强转替代。 */const AGENT_KINDS = ['claude-code', 'codex', 'pi'] as const satisfies readonly AgentKind[];-const AGENT_LOGIN_MODES = ['browser', 'device-code'] as const satisfies readonly AgentLoginMode[];+const AGENT_LOGIN_MODES = ['browser', 'device-code', 'local'] as const satisfies readonly AgentLoginMode[];const MAX_LOGIN_PROGRESS_CHARS = 16_384;const LOGIN_OWNER_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;const ANSI_SEQUENCE = new RegExp(@@ -512,13 +513,22 @@ export function registerMakerAuthHandlers(await cancelLoginOperation(kind, activeOperation);});- registry.handle(MAKER_INVOKE.AUTH_LOGOUT, async (_e, agentKind: unknown): Promise<void> => {+ registry.handle(MAKER_INVOKE.AUTH_LOGOUT, async (_e, agentKind: unknown, ownerScope: unknown): Promise<void> => {+ if (ownerScope !== undefined) {+ const scope = requireObject(ownerScope, 'ownerScope');+ const current = getActiveAppSession();+ if (isAppSessionBoundaryPending() || scope.dataOwnerId !== current.dataOwnerId || scope.ownerGeneration !== current.generation) {+ throwIpcError('INVALID_PARAMS', 'Provider owner changed');+ }+ }const kind = requireAgentKind(agentKind);const activeOperation = activeLoginOperations.get(kind);if (activeOperation) activeOperation.acceptingOwners = false;clearOwnersForKind(kind);const generation = beginMutation(kind);- const isCurrent = (): boolean => isMutationCurrent(kind, generation);+ const capturedOwner = activeOwnerScopeKey();+ const isCurrent = (): boolean => isMutationCurrent(kind, generation)+ && !isAppSessionBoundaryPending() && activeOwnerScopeKey() === capturedOwner;const finalization = (async (): Promise<void> => {try {await maker.logoutAgent(kind);@@ -560,8 +570,8 @@ function requireLoginOptions(): { mode: AgentLoginMode; ownerId?: string } {const options = value === undefined ? {} : requireObject(value, 'options');const mode = optionalEnum(options.mode, AGENT_LOGIN_MODES, 'login mode') ?? 'browser';- if (agentKind !== 'codex' && mode === 'device-code') {- throwIpcError('INVALID_PARAMS', 'device-code login is only supported by codex');+ if (agentKind !== 'codex' && mode !== 'browser') {+ throwIpcError('INVALID_PARAMS', 'This login mode is only supported by codex');}const ownerId = requireLoginOwnerId(options.ownerId);if (agentKind !== 'codex' && ownerId) {diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.tsindex 1a143fe47f..42e8e74970 100644--- a/apps/desktop/src/main/maker-ipc/channels.ts+++ b/apps/desktop/src/main/maker-ipc/channels.ts@@ -248,6 +248,8 @@ export const MAKER_INVOKE = {* Settings mutation: local trusted renderer only; deliberately excluded from the* device-link allowlist.*/+ PROVIDER_CUSTOM_DISCONNECT: 'maker:provider:custom:disconnect',+ PROVIDER_PRESENTATION_SET: 'maker:provider:presentation:set',PROVIDER_ORDER_SET: 'maker:provider:order:set',/** Visual Settings UI only: read/write/reset a per-provider × runtime × model price estimate. */MODEL_PRICE_OVERRIDE_GET: 'maker:model-price-override:get',diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.tsindex 828fb1fe43..429d9738d9 100644--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts@@ -1,3 +1,4 @@+import { setProviderPresentation } from '../maker-host/provider-presentation-store.js';/*** provider:* IPC handlers。*@@ -19,6 +20,7 @@ import {isLoopbackProviderUrl,isProviderRequestPath,runtimeCustomProviderId,+ storedCustomProviderId,type AgentKind,type CustomProviderConfig,type ProviderModelDiscoveryFailure,@@ -1000,6 +1002,14 @@ export function registerProviderHandlers(}};+ const assertOptionalRequestedOwner = (input: unknown): void => {+ if (input === undefined) return;+ if (!input || typeof input !== 'object' || Array.isArray(input)) throwIpcError('INVALID_PARAMS', 'Invalid owner scope');+ const scope = input as Record<string, unknown>;+ if ((scope.dataOwnerId !== null && typeof scope.dataOwnerId !== 'string') || !Number.isSafeInteger(scope.ownerGeneration)) throwIpcError('INVALID_PARAMS', 'Invalid owner scope');+ assertRequestedProviderOwner(scope.dataOwnerId as string | null, scope.ownerGeneration as number);+ };+// 只读聚合:远端还需等待当前账号的模型开关就绪;失败不可伪装为全部关闭。registry.handle(MAKER_INVOKE.PROVIDER_LIST,@@ -1085,6 +1095,15 @@ export function registerProviderHandlers(},);+ async function refreshCatalogAfterCommit(): Promise<void> {+ try {+ await deps.refreshCatalog();+ } catch {+ // Configuration/credentials have committed; catalog enrichment cannot reverse success.+ log.warn('provider catalog refresh failed after committed configuration change');+ }+ }+// CRUD 成功后统一收尾:发布 dispatch generation、刷新目录,再释放写前已完成硬停的// shared Host guard。新 Host 由下一次本地 Codex start 按新快照惰性创建。async function afterChange(@@ -1093,7 +1112,7 @@ export function registerProviderHandlers(): Promise<void> {commitRouteMutation?.();try {- await deps.refreshCatalog();+ await refreshCatalogAfterCommit();} finally {// 持久化一旦成功,即使 catalog refresh 报错也不能让旧 Host 留在新凭证代次旁继续跑。if (codexHostPrepared) {@@ -1142,6 +1161,48 @@ export function registerProviderHandlers(// 供应商显示顺序是 owner-scoped 设置。Renderer 只提交当前左栏可见项;store 会// 保留曾出现但当前隐藏的项,并把第一次出现的项追加到末尾。+ registry.handle(MAKER_INVOKE.PROVIDER_PRESENTATION_SET, async (event, input: unknown) => {+ assertTrustedProviderMutationSender(event);+ if (!input || typeof input !== 'object' || Array.isArray(input)) throwIpcError('INVALID_PARAMS', 'Invalid presentation');+ const value = input as Record<string, unknown>;+ if (typeof value.ownerGeneration !== 'number' || !Number.isSafeInteger(value.ownerGeneration) || (value.dataOwnerId !== null && typeof value.dataOwnerId !== 'string')) {+ throwIpcError('INVALID_PARAMS', 'Owner required');+ }+ const providerId = value.providerId ?? 'openai';+ if (typeof providerId !== 'string') throwIpcError('INVALID_PARAMS', 'Invalid provider');+ assertRequestedProviderOwner(value.dataOwnerId as string | null, value.ownerGeneration);+ const provider = (await deps.listProviders()).find((p) => p.id === providerId);+ assertRequestedProviderOwner(value.dataOwnerId as string | null, value.ownerGeneration);+ if (!provider || provider.id === 'xd') {+ throwIpcError('INVALID_PARAMS', 'Provider does not support presentation overrides');+ }+ if (value.action === 'rename' && typeof value.name === 'string' && value.name.trim() && value.name.length <= 128) {+ if (provider.source === 'builtin') {+ await setProviderPresentation(providerId, { name: value.name });+ } else {+ const id = storedCustomProviderId(providerId);+ const name = value.name.trim();+ await withProviderConfigMutation(id, async () => {+ assertOptionalRequestedOwner(value);+ const current = await getCustomProvider(id);+ assertOptionalRequestedOwner(value);+ if (!current || !await updateCustomProvider(id, { ...current, name })) throwIpcError('NOT_FOUND', 'Provider not found');+ assertOptionalRequestedOwner(value);+ await refreshCatalogAfterCommit();+ });+ }+ } else if (value.action === 'remove' && provider.source === 'builtin') {+ if (provider.connected) throwIpcError('INVALID_PARAMS', 'Disconnect the provider first');+ await setProviderPresentation(providerId, { removed: true });+ } else if (value.action === 'restore' && provider.source === 'builtin') {+ await setProviderPresentation(providerId, { removed: false });+ } else {+ throwIpcError('INVALID_PARAMS', 'Invalid presentation action');+ }+ assertRequestedProviderOwner(value.dataOwnerId as string | null, value.ownerGeneration);+ deps.broadcastChanged();+ });+registry.handle(MAKER_INVOKE.PROVIDER_ORDER_SET, (event, input: unknown) => {assertTrustedProviderMutationSender(event);if (!input || typeof input !== 'object' || Array.isArray(input)) {@@ -1806,8 +1867,11 @@ export function registerProviderHandlers(},);- registry.handle(MAKER_INVOKE.PROVIDER_CUSTOM_DELETE, async (event, providerId: unknown) => {+ registry.handle(MAKER_INVOKE.PROVIDER_CUSTOM_DELETE, async (event, providerId: unknown, ownerScope?: unknown, optionsInput?: unknown) => {assertTrustedProviderMutationSender(event);+ assertOptionalRequestedOwner(ownerScope);+ const options = parseCustomProviderUpdateOptions(optionsInput);+ if (!options) throwIpcError('INVALID_PARAMS', 'Invalid provider change options');if (typeof providerId !== 'string' || providerId.length === 0) {throwIpcError('INVALID_PARAMS', 'providerId required');}@@ -1819,21 +1883,22 @@ export function registerProviderHandlers(assertProviderMutationOwner(ownerAtIngress);const previous = await getCustomProvider(providerId);assertProviderMutationOwner(ownerAtIngress);- if (previous?.auth?.native === 'codex') {- await deps.retireCodexAccount?.(providerId);- assertProviderMutationOwner(ownerAtIngress);- }const codexHostChangeRequired = Boolean(previous && (deps.codexCustomProviderConfigSignature?.(previous) ?? '').length > 0,);const preparation = await prepareCodexCustomProviderChange(codexHostChangeRequired,- {},+ options,ownerAtIngress,);+ if (preparation.confirmation) return preparation.confirmation;codexHostPrepared = preparation.prepared;const generation = beginOAuthMutation(providerId);try {+ if (previous?.auth?.native === 'codex') {+ await deps.retireCodexAccount?.(providerId);+ assertProviderMutationOwner(ownerAtIngress);+ }deps.oauthCancel(providerId);const credentialSnapshots = stageProviderCredentials(providerId,@@ -1893,9 +1958,8 @@ export function registerProviderHandlers(}throw err;}- // 刷目录也在队列内:队列释放的那一刻 listProviders() 必须已看不到该- // provider。afterChange 失败时配置已删,凭证/override 不回写(与改动前- // 语义一致 —— 恢复只覆盖删除本身失败的场景)。+ // 在队列内尝试刷新目录;刷新失败不撤销已经提交的删除。+ // 凭证/override 的恢复只覆盖删除本身失败的场景。assertProviderMutationOwner(ownerAtIngress);await afterChange(codexHostPrepared, commitRouteMutation);assertProviderMutationOwner(ownerAtIngress);@@ -2093,20 +2157,57 @@ export function registerProviderHandlers(}},);- registry.handle(MAKER_INVOKE.PROVIDER_OAUTH_LOGOUT, async (event, providerId: unknown) => {+ registry.handle(MAKER_INVOKE.PROVIDER_CUSTOM_DISCONNECT, async (event, providerId: unknown, ownerScope?: unknown, optionsInput?: unknown) => {+ assertTrustedProviderMutationSender(event);+ assertOptionalRequestedOwner(ownerScope);+ const options = parseCustomProviderUpdateOptions(optionsInput);+ if (!options) throwIpcError('INVALID_PARAMS', 'Invalid provider change options');+ const id = storedCustomProviderId(requireProviderId(providerId));+ const owner = captureProviderOwnerSession();+ return withProviderConfigMutation(id, async (commitRouteMutation) => {+ assertProviderMutationOwner(owner);+ const config = await getCustomProvider(id);+ assertProviderMutationOwner(owner);+ if (!config || (config.auth && config.auth.method !== 'apiKey')) throwIpcError('INVALID_PARAMS', 'API connection required');+ const preparation = await prepareCodexCustomProviderChange(+ deps.hasAppliedCodexCustomProviderImageGeneration?.(id) === true, options, owner,+ );+ if (preparation.confirmation) return preparation.confirmation;+ try {+ assertProviderMutationOwner(owner);+ stageProviderCredentials(id,+ (VALID_AGENTS as readonly AgentKind[]).map((agent) => ({ agent, replacement: null })),+ (VALID_AGENTS as readonly AgentKind[]).map((agent) => ({ agent, replacement: null })),+ commitRouteMutation);+ // Configuration and stable route ID remain available for reconnect. Publish even when+ // a later catalog refresh fails: the disconnected credential must never be reused.+ commitRouteMutation();+ await afterChange(preparation.prepared, commitRouteMutation);+ return { ok: true };+ } finally {+ if (preparation.prepared) deps.cancelCodexCustomProviderHostChange?.();+ }+ });+ });+ registry.handle(MAKER_INVOKE.PROVIDER_OAUTH_LOGOUT, async (event, providerId: unknown, ownerScope?: unknown, optionsInput?: unknown) => {assertTrustedProviderMutationSender(event);+ assertOptionalRequestedOwner(ownerScope);+ const options = parseCustomProviderUpdateOptions(optionsInput);+ if (!options) throwIpcError('INVALID_PARAMS', 'Invalid provider change options');const id = requireProviderId(providerId);const ownerAtIngress = captureProviderOwnerSession();- const generation = beginOAuthMutation(id);+ let generation: symbol | null = null;try {return await withProviderConfigMutation(id, async (commitRouteMutation) => {let codexHostPrepared = false;try {const preparation = await prepareCodexCustomProviderChange(deps.hasAppliedCodexCustomProviderImageGeneration?.(id) === true,- {},+ options,ownerAtIngress,);+ if (preparation.confirmation) return preparation.confirmation;+ generation = beginOAuthMutation(id);codexHostPrepared = preparation.prepared;// Do not alter OAuth flow or credential state until the local Codex Host has crossed the// hard-stop boundary. Failed Host retirement must leave the old generation usable.@@ -2135,7 +2236,7 @@ export function registerProviderHandlers(}});} finally {- finishOAuthMutation(id, generation);+ if (generation !== null) finishOAuthMutation(id, generation);}});registry.handle(diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex d8fe89bd0f..f000635911 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -1,10 +1,12 @@import type { TurnUsageContext } from './turnUsageContext.js';+import { retainProviderPresentationAfterAuthChange } from '../maker-host/provider-presentation-store.js';import { registerPluginListHandler } from './pluginListHandler.js';import { initializeBotAuthorizationHost } from './botAuthorizationHost.js';import { resolveBotAuthorizationDelivery, buildBotAuthorizationContinuation, commitBotAuthorizationInput, type BotAuthorizationInputGuard, getBotAuthorizationService } from './botAuthorizationService.js';import { registerSessionSetModelHandler } from './sessionSetModelHandler.js';import { refreshSubscriptionAccountModels } from '../maker-host/subscription-account-models.js';import { syncSubscriptionAccountUsage } from '../usage/subscriptionAccountUsage.js';+import { clearXaiRateLimitSnapshot } from '../usageBroadcaster.js';import { subscriptionAccountKind, subscriptionAccountState, loginSubscriptionAccount, logoutSubscriptionAccount, cancelSubscriptionAccountLogin, removeSubscriptionAccountCredentialsReversibly } from '../maker-host/subscription-account-auth.js';import { isCodexAccountProvider, codexAccountState, loginCodexAccount, logoutCodexAccount, cancelCodexAccountLogin, removeCodexAccountCredentialsReversibly, retireCodexAccount } from '../maker-host/codex-account-auth.js';import { projectRemoteBotDelegations } from './remoteBotDelegations.js';@@ -5479,6 +5481,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (subscriptionAccountKind(providerId)) {const result = await loginSubscriptionAccount(providerId, isCurrent);if (result.ok && isCurrent()) {+ if (subscriptionAccountKind(providerId) === 'xai') clearXaiRateLimitSnapshot(providerId);try { await refreshSubscriptionAccountModels(providerId); } catch { /* Static catalog remains usable. */ }if (!isCurrent()) return result;const previous = await getCustomProvider(providerId);@@ -5602,7 +5605,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)} catch {/* 发现失败保持纯静态目录,不影响登录结果 */}- if (isCurrent()) broadcastToAllWindows(MAKER_PUSH.PROVIDER_CHANGED, {});+ if (isCurrent()) {+ if (provider.source === 'builtin') await retainProviderPresentationAfterAuthChange(providerId);+ if (isCurrent()) broadcastToAllWindows(MAKER_PUSH.PROVIDER_CHANGED, {});+ }}return { ...result, ...(rollbackCredentials ? { rollbackCredentials } : {}) };},@@ -5621,11 +5627,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (isCodexAccountProvider(providerId)) cancelCodexAccountLogin(providerId);else cancelGenericOAuthLogin(storedCustomProviderId(providerId));},- removeOAuthCredentials: (providerId) => subscriptionAccountKind(providerId)- ? removeSubscriptionAccountCredentialsReversibly(providerId)- : isCodexAccountProvider(providerId)- ? removeCodexAccountCredentialsReversibly(providerId)- : removeGenericOAuthCredentialsReversibly(storedCustomProviderId(providerId)),+ removeOAuthCredentials: (providerId) => {+ if (subscriptionAccountKind(providerId)) {+ const restore = removeSubscriptionAccountCredentialsReversibly(providerId);+ if (subscriptionAccountKind(providerId) === 'xai') clearXaiRateLimitSnapshot(providerId);+ return restore;+ }+ return isCodexAccountProvider(providerId)+ ? removeCodexAccountCredentialsReversibly(providerId)+ : removeGenericOAuthCredentialsReversibly(storedCustomProviderId(providerId));+ },});// 自定义 MCP 服务器 CRUD —— CRUD 成功后刷新三个 agent 的 mcpProviders 数组diff --git a/apps/desktop/src/main/maker-ipc/usage.ts b/apps/desktop/src/main/maker-ipc/usage.tsindex 99e0b56932..01fc326b47 100644--- a/apps/desktop/src/main/maker-ipc/usage.ts+++ b/apps/desktop/src/main/maker-ipc/usage.ts@@ -8,7 +8,7 @@import { scryptSync } from 'node:crypto';import { readSubscriptionAccountUsage, triggerSubscriptionAccountUsage, syncSubscriptionAccountUsage, setSubscriptionAccountUsageBroadcaster } from '../usage/subscriptionAccountUsage.js';-import { broadcastSubscriptionAccountUsage } from '../usageBroadcaster.js';+import { broadcastSubscriptionAccountUsage, clearXaiRateLimitSnapshot } from '../usageBroadcaster.js';import { subscriptionAccountKind } from '../maker-host/subscription-account-auth.js';import path from 'node:path';@@ -309,7 +309,7 @@ export function registerMakerUsageIpc(maker: Maker): void {return service;}- setSubscriptionAccountUsageBroadcaster(broadcastSubscriptionAccountUsage);+ setSubscriptionAccountUsageBroadcaster(broadcastSubscriptionAccountUsage, clearXaiRateLimitSnapshot);registerMakerUsageHandlers(createElectronIpcHandlerRegistry(), {readAgentTodayUsage,readCodexAccountUsageSnapshot: readCodexAccountUsageSnapshotWithWebRefresh,diff --git a/apps/desktop/src/main/secrets/builtinApiKeyBridge.ts b/apps/desktop/src/main/secrets/builtinApiKeyBridge.tsindex 7c99af9224..daa3f9d77b 100644--- a/apps/desktop/src/main/secrets/builtinApiKeyBridge.ts+++ b/apps/desktop/src/main/secrets/builtinApiKeyBridge.ts@@ -11,26 +11,10 @@* - has 是查询:失败回 false 供 UI 按未配置渲染,只回存在性布尔。*/-import type { ProviderSecretId } from '../../shared/providerSecrets.js';+import { isBuiltinApiKeyProviderId, type ProviderSecretId } from '../../shared/providerSecrets.js';+export { isBuiltinApiKeyProviderId } from '../../shared/providerSecrets.js';import { throwIpcError } from '../utils/ipcValidate.js';-/**- * 允许经本桥访问的内置 API-key 供应商(新增供应商时在此扩展)。- * 模块私有:这是权限白名单,不导出可变引用(ReadonlySet 只是编译期约束,- * 挡不住运行时 .add());外部只能经 isBuiltinApiKeyProviderId 查询。- */-const BUILTIN_API_KEY_PROVIDER_IDS: ReadonlySet<ProviderSecretId> = new Set<ProviderSecretId>([- 'gemini',- 'openai-images',-]);--/** 白名单查询(只读语义,供测试与未来调用方使用,不暴露集合本体)。 */-export function isBuiltinApiKeyProviderId(providerId: unknown): providerId is ProviderSecretId {- return (- typeof providerId === 'string' && BUILTIN_API_KEY_PROVIDER_IDS.has(providerId as ProviderSecretId)- );-}-/*** 真实 API key 远短于此(gemini ~39 / OpenAI 平台 ~200 字符);上限挡的是被攻陷* renderer 塞超大字符串让 main 同步加密落盘耗资源(副作用前验证 payload 长度)。diff --git a/apps/desktop/src/main/usage/__tests__/subscriptionAccountUsage.test.ts b/apps/desktop/src/main/usage/__tests__/subscriptionAccountUsage.test.tsindex 095a2e9de2..c6688da463 100644--- a/apps/desktop/src/main/usage/__tests__/subscriptionAccountUsage.test.ts+++ b/apps/desktop/src/main/usage/__tests__/subscriptionAccountUsage.test.ts@@ -64,6 +64,8 @@ describe('subscription provider quota isolation', () => {async (kind) => {const a = `${kind}-a`,b = `${kind}-b`;+ const clearInstant = vi.fn();+ setSubscriptionAccountUsageBroadcaster(() => {}, clearInstant);state.tokens.set(a, 'test-token-a');state.tokens.set(b, 'test-token-b');const fetch = kind === 'claude' ? state.fetchClaude : state.fetchXai;@@ -76,6 +78,8 @@ describe('subscription provider quota isolation', () => {expect(await readSubscriptionAccountUsage(b)).toMatchObject({ updatedAt: 2 });state.tokens.delete(a);await syncSubscriptionAccountUsage(a);+ if (kind === 'xai') expect(clearInstant).toHaveBeenCalledExactlyOnceWith(a);+ else expect(clearInstant).not.toHaveBeenCalled();expect(await readSubscriptionAccountUsage(a)).toBeNull();expect(await readSubscriptionAccountUsage(b)).toMatchObject({ updatedAt: 2 });},diff --git a/apps/desktop/src/main/usage/subscriptionAccountUsage.ts b/apps/desktop/src/main/usage/subscriptionAccountUsage.tsindex b1a67ef26d..3c26b9f77a 100644--- a/apps/desktop/src/main/usage/subscriptionAccountUsage.ts+++ b/apps/desktop/src/main/usage/subscriptionAccountUsage.ts@@ -26,8 +26,13 @@ import type { XaiSubscriptionUsageSnapshot } from '../../shared/xaiSubscriptionUtype Snapshot = ClaudeSubscriptionUsageSnapshot | XaiSubscriptionUsageSnapshot;let broadcast: (providerId: string, snapshot: Snapshot | null) => void = () => {};-export function setSubscriptionAccountUsageBroadcaster(handler: typeof broadcast): void {+let clearInstantUsage: (providerId: string) => void = () => {};+export function setSubscriptionAccountUsageBroadcaster(+ handler: typeof broadcast,+ clear?: typeof clearInstantUsage,+): void {broadcast = handler;+ clearInstantUsage = clear ?? (() => {});}// These are display caches. Credentials stay in the host credential store, and@@ -115,5 +120,6 @@ export function triggerSubscriptionAccountUsage(providerId: string): void {if (!isProviderRouteMutationInProgress(providerId)) reader(providerId)?.triggerRefresh();}export async function syncSubscriptionAccountUsage(providerId: string): Promise<void> {+ if (subscriptionAccountKind(providerId) === 'xai') clearInstantUsage(providerId);await reader(providerId)?.syncForCredentialChange();}diff --git a/apps/desktop/src/main/usageBroadcaster.ts b/apps/desktop/src/main/usageBroadcaster.tsindex 0df941ad3c..dbf096ec94 100644--- a/apps/desktop/src/main/usageBroadcaster.ts+++ b/apps/desktop/src/main/usageBroadcaster.ts@@ -786,11 +786,12 @@ function createCodexUsageStore(providerId: string) {export type { XaiRateLimitSnapshot } from '../shared/xaiRateLimit';/** bridge onRateLimit 回调入口:广播 renderer(renderer 侧 hook 自带模块级缓存,无拉取端点)。 */-export function recordXaiRateLimitSnapshot(info: Omit<XaiRateLimitSnapshot, 'updatedAt'>): void {+export function recordXaiRateLimitSnapshot(info: Omit<XaiRateLimitSnapshot, 'updatedAt'>, providerId = 'xai'): void {const snapshot: XaiRateLimitSnapshot = { ...info, updatedAt: Date.now() };for (const win of BrowserWindow.getAllWindows()) {- if (!win.isDestroyed()) {- win.webContents.send(USAGE_XAI_RATE_LIMIT_CHANGED, snapshot);+ if (isTrustedAppRendererWindow(win)) {+ if (providerId === 'xai') win.webContents.send(USAGE_XAI_RATE_LIMIT_CHANGED, snapshot);+ else win.webContents.send('usage:xai-provider-rate-limit-changed', { providerId, snapshot });}}}@@ -799,10 +800,11 @@ export function recordXaiRateLimitSnapshot(info: Omit<XaiRateLimitSnapshot, 'upd* 清空 xAI 限流快照(广播 null)。xAI 登出 / 重新登录(可能换账号)时调用 ——* 快照是账号级的,登出后没有下一个成功响应来覆盖,不清会让旧账号的余量一直挂在 chip 上。*/-export function clearXaiRateLimitSnapshot(): void {+export function clearXaiRateLimitSnapshot(providerId = 'xai'): void {for (const win of BrowserWindow.getAllWindows()) {- if (!win.isDestroyed()) {- win.webContents.send(USAGE_XAI_RATE_LIMIT_CHANGED, null);+ if (isTrustedAppRendererWindow(win)) {+ if (providerId === 'xai') win.webContents.send(USAGE_XAI_RATE_LIMIT_CHANGED, null);+ else win.webContents.send('usage:xai-provider-rate-limit-changed', { providerId, snapshot: null });}}}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 50d147aa3b..7df31d3bb6 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -778,6 +778,7 @@ const fanOutMakerUsageClaudeAccount = createIpcFanOut('usage:claude-account-chanconst fanOutMakerUsageCodexProviderAccount = createIpcFanOut('usage:codex-provider-account-changed');const fanOutSubscriptionProviderAccount = createIpcFanOut('usage:subscription-provider-account-changed');const fanOutMakerUsageCodexAccount = createIpcFanOut('usage:codex-account-changed'); // Codex 订阅用量+const fanOutMakerUsageXaiProviderRateLimit = createIpcFanOut('usage:xai-provider-rate-limit-changed');const fanOutMakerUsageXaiRateLimit = createIpcFanOut('usage:xai-rate-limit-changed'); // xAI bridge 限流快照const fanOutMakerUsageClaudeSubscription = createIpcFanOut('usage:claude-subscription-changed'); // Claude 订阅余量const fanOutMakerUsageXaiSubscription = createIpcFanOut('usage:xai-subscription-changed'); // SuperGrok 周用量@@ -1977,8 +1978,8 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('builtin-api-key-has', providerId),builtinApiKeyStore: (providerId: string, value: string): Promise<void> =>ipcRenderer.invoke('builtin-api-key-store', providerId, value),- builtinApiKeyRemove: (providerId: string): Promise<void> =>- ipcRenderer.invoke('builtin-api-key-remove', providerId),+ builtinApiKeyRemove: (providerId: string, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }): Promise<void> =>+ ipcRenderer.invoke('builtin-api-key-remove', providerId, ownerScope),// ── 网关凭据自动下发(model-access,shared/modelAccess.ts) ──modelAccess: {@@ -5605,6 +5606,7 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('maker:get-workflow-progress', sessionId, taskId),// 模型供应商目录(只读)—— 内置目录元数据 + 各供应商实时连接状态。+ setProviderPresentation: (input: { providerId?: string; action: 'rename' | 'remove' | 'restore'; name?: string; dataOwnerId: string | null; ownerGeneration: number }): Promise<void> => ipcRenderer.invoke('maker:provider:presentation:set', input),listProviders: (): Promise<{dataOwnerId: string | null;ownerGeneration: number;@@ -5635,8 +5637,9 @@ contextBridge.exposeInMainWorld('electronAPI', {options?: CustomProviderUpdateOptions,): Promise<CustomProviderUpdateResult> =>ipcRenderer.invoke('maker:provider:custom:update', config, keys, options),- deleteCustomProvider: (providerId: string): Promise<{ ok: true }> =>- ipcRenderer.invoke('maker:provider:custom:delete', providerId),+ disconnectCustomProvider: (providerId: string, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }, options?: CustomProviderUpdateOptions): Promise<CustomProviderUpdateResult> => ipcRenderer.invoke('maker:provider:custom:disconnect', providerId, ownerScope, options),+ deleteCustomProvider: (providerId: string, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }, options?: CustomProviderUpdateOptions): Promise<CustomProviderUpdateResult> =>+ ipcRenderer.invoke('maker:provider:custom:delete', providerId, ownerScope, options),/** 自定义供应商创建模板(目录 presets 段,纯 UI 模板数据)。 */listProviderPresets: (): Promise<{presets: import('@cindy/model-providers').ProviderPreset[];@@ -5823,8 +5826,8 @@ contextBridge.exposeInMainWorld('electronAPI', {options?: { ownerId?: string },): Promise<{ ok: boolean; reason?: string }> =>ipcRenderer.invoke('maker:provider:oauth:login', providerId, options),- providerOAuthLogout: (providerId: string): Promise<{ ok: true }> =>- ipcRenderer.invoke('maker:provider:oauth:logout', providerId),+ providerOAuthLogout: (providerId: string, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }, options?: CustomProviderUpdateOptions): Promise<CustomProviderUpdateResult> =>+ ipcRenderer.invoke('maker:provider:oauth:logout', providerId, ownerScope, options),providerOAuthCancel: (providerId: string,options?: { releaseOwner?: boolean; ownerId?: string },@@ -6808,23 +6811,22 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('maker:claude-session-route:get', sessionId),onClaudeSessionRouteChanged: fanOutMakerClaudeSessionRouteChanged,- // Claude.ai 订阅 OAuth 登录(浏览器流程,凭证落系统 ~/.claude,与本地 claude 共用)。- // 与鉴权模式开关正交。LOGIN 拉浏览器、成功写凭证;LOGOUT 清凭证(同时登出本地 claude);- // CANCEL 取消进行中登录;STATUS 回 { authorized }。+ // 本机 Claude 连接只管理 Cindy 使用许可,不修改系统凭证。+ // 可选 loginKey 将取消限定到对应尝试;省略时兼容已有调用。claudeOAuthStatus: (): Promise<{ authorized: boolean }> =>ipcRenderer.invoke('maker:claude-oauth:status'),- claudeOAuthLogin: (): Promise<{ ok: boolean; authorized: boolean; reason?: string }> =>- ipcRenderer.invoke('maker:claude-oauth:login'),- claudeOAuthLogout: (): Promise<{ authorized: boolean }> =>- ipcRenderer.invoke('maker:claude-oauth:logout'),- claudeOAuthCancel: (): Promise<{ authorized: boolean }> =>- ipcRenderer.invoke('maker:claude-oauth:cancel'),+ claudeOAuthLogin: (loginKey?: string): Promise<{ ok: boolean; authorized: boolean; reason?: string }> =>+ ipcRenderer.invoke('maker:claude-oauth:login', loginKey),+ claudeOAuthLogout: (ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }): Promise<{ authorized: boolean }> =>+ ipcRenderer.invoke('maker:claude-oauth:logout', ownerScope),+ claudeOAuthCancel: (loginKey?: string): Promise<{ authorized: boolean }> =>+ ipcRenderer.invoke('maker:claude-oauth:cancel', loginKey),// xAI(SuperGrok 订阅)OAuth —— 与 claudeOAuth* 同形态。xaiOAuthLogin: (): Promise<{ ok: boolean; authorized: boolean; reason?: string }> =>ipcRenderer.invoke('maker:xai-oauth:login'),- xaiOAuthLogout: (): Promise<{ authorized: boolean }> =>- ipcRenderer.invoke('maker:xai-oauth:logout'),+ xaiOAuthLogout: (ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }): Promise<{ authorized: boolean }> =>+ ipcRenderer.invoke('maker:xai-oauth:logout', ownerScope),xaiOAuthCancel: (): Promise<{ authorized: boolean }> =>ipcRenderer.invoke('maker:xai-oauth:cancel'),@@ -7056,14 +7058,14 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('maker:auth:get-state', agentKind),triggerLogin: (agentKind: 'claude-code' | 'codex' | 'pi',- options?: { mode?: 'browser' | 'device-code'; ownerId?: string },+ options?: { mode?: 'browser' | 'device-code' | 'local'; ownerId?: string },): Promise<unknown> => ipcRenderer.invoke('maker:auth:trigger-login', agentKind, options),cancelLogin: (agentKind: 'claude-code' | 'codex' | 'pi',options?: { releaseOwner?: boolean; ownerId?: string },): Promise<void> => ipcRenderer.invoke('maker:auth:cancel-login', agentKind, options),- logout: (agentKind: 'claude-code' | 'codex' | 'pi'): Promise<void> =>- ipcRenderer.invoke('maker:auth:logout', agentKind),+ logout: (agentKind: 'claude-code' | 'codex' | 'pi', ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }): Promise<void> =>+ ipcRenderer.invoke('maker:auth:logout', agentKind, ownerScope),onStateChanged: fanOutMakerAuthStateChanged,onLoginProgress: fanOutMakerAuthLoginProgress,},@@ -7124,7 +7126,11 @@ contextBridge.exposeInMainWorld('electronAPI', {if (scoped?.providerId === providerId) cb(scoped.snapshot);}),/** xAI(SuperGrok bridge)限流快照推送 (bridge 每个成功上游响应解析 x-ratelimit-* 后推送)。 */- onXaiRateLimitChanged: fanOutMakerUsageXaiRateLimit,+ onXaiRateLimitChanged: (cb: (payload: unknown) => void, providerId = 'xai') =>+ providerId === 'xai' ? fanOutMakerUsageXaiRateLimit(cb) : fanOutMakerUsageXaiProviderRateLimit((payload: unknown) => {+ const scoped = payload as { providerId?: string; snapshot?: unknown };+ if (scoped?.providerId === providerId) cb(scoped.snapshot);+ }),/** Claude 订阅余量推送 (端点后台刷新 / proxy 旁路 headers 更新时推送)。 */onClaudeSubscriptionChanged: (cb: (payload: unknown) => void, providerId = 'anthropic') =>providerId === 'anthropic' ? fanOutMakerUsageClaudeSubscription(cb) : fanOutSubscriptionProviderAccount((payload: unknown) => {diff --git a/apps/desktop/src/renderer/__tests__/addProviderWizardOpenAiAuth.test.tsx b/apps/desktop/src/renderer/__tests__/addProviderWizardOpenAiAuth.test.tsxindex efb6123e86..71d852f73a 100644--- a/apps/desktop/src/renderer/__tests__/addProviderWizardOpenAiAuth.test.tsx+++ b/apps/desktop/src/renderer/__tests__/addProviderWizardOpenAiAuth.test.tsx@@ -70,6 +70,7 @@ vi.mock('@/components/icons/ProviderLogoMark', () => ({}));import { AddProviderWizard } from '@/components/settings/AddProviderWizard';+import { invalidatePendingCodexLogin } from '@/hooks/codexAuthLogin';const OPENAI_PROVIDER = {id: 'openai',@@ -141,6 +142,7 @@ type ProviderOAuthProgress = {let providerOAuthProgressListener: ((progress: ProviderOAuthProgress) => void) | null = null;beforeEach(() => {+ invalidatePendingCodexLogin();triggerLogin.mockReset();cancelLogin.mockReset();createAccount.mockReset().mockResolvedValue(undefined);@@ -156,6 +158,9 @@ beforeEach(() => {});(window as unknown as { electronAPI: unknown }).electronAPI = {maker: {+ auth: { triggerLogin, cancelLogin },+ claudeOAuthLogin: triggerLogin,+ claudeOAuthCancel: cancelLogin,listProviderPresets: vi.fn(async () => ({ presets: [] })),localModelList: vi.fn(async () => ({status: { runtime: 'ollama', kind: 'absent', appInstalled: false },@@ -181,6 +186,30 @@ afterEach(() => {});describe('AddProviderWizard — OpenAI 授权边界', () => {+ it.each(['openai', 'anthropic'].flatMap(id => ['cancel', 'unmount'].map(exit => ({ id, exit }))))('discards local $id completion after $exit', async ({ id, exit }) => {+ let finish!: (value: unknown) => void;+ triggerLogin.mockReturnValue(new Promise(resolve => { finish = resolve; }));+ cancelLogin.mockResolvedValue({});+ const onDone = vi.fn();+ const { unmount } = render(<AddProviderWizard providers={[{ ...OPENAI_PROVIDER, id }]}+ entry={{ kind: 'builtin', providerId: id }} onOpenCustomForm={vi.fn()} onClose={vi.fn()} onDone={onDone} />);+ fireEvent.click(await screen.findByText(id === 'openai' ? 'settings.providers.openai.useLocalAccount' : 'settings.providers.localAccount.useClaude'));+ await waitFor(() => expect(triggerLogin).toHaveBeenCalledTimes(1));+ if (exit === 'unmount') unmount();+ else fireEvent.click(screen.getByText('settings.providers.wizard.cancel'));+ expect(cancelLogin).toHaveBeenCalledTimes(1);+ await act(async () => { finish({ ok: true, authenticated: true, authSource: 'oauth', credentialScope: 'system-shared' }); });+ expect(onDone).not.toHaveBeenCalled();+ });++ it('completes a successful local OpenAI login even if CLI scanning fails', async () => {+ triggerLogin.mockResolvedValue({ authenticated: true, authSource: 'oauth', credentialScope: 'system-shared' });+ vi.mocked(window.electronAPI.maker.scanLocalCli).mockRejectedValue(new Error('EACCES'));+ const onDone = vi.fn();+ render(<AddProviderWizard providers={[OPENAI_PROVIDER]} entry={{ kind: 'builtin', providerId: 'openai' }} onOpenCustomForm={vi.fn()} onClose={vi.fn()} onDone={onDone} />);+ fireEvent.click(await screen.findByText('settings.providers.openai.useLocalAccount'));+ await waitFor(() => expect(onDone).toHaveBeenCalledExactlyOnceWith('openai'));+ });it.each(['openai', 'anthropic', 'xai'].flatMap(id =>['cancel', 'unmount'].map(exit => ({ id, exit })),))('removes $id when login succeeds after $exit', async ({ id, exit }) => {@@ -189,9 +218,7 @@ describe('AddProviderWizard — OpenAI 授权边界', () => {const onDone = vi.fn();const { unmount } = render(<AddProviderWizard providers={[{ ...OPENAI_PROVIDER, id, name: id }]}entry={{ kind: 'builtin', providerId: id }} onOpenCustomForm={vi.fn()} onClose={vi.fn()} onDone={onDone} />);- fireEvent.click(screen.getByText(id === 'openai'- ? 'settings.providers.openai.addIndependentAccount'- : 'settings.providers.button.authorize'));+ fireEvent.click(screen.getByText('settings.providers.openai.addIndependentAccount'));await waitFor(() => expect(providerOAuthLogin).toHaveBeenCalledTimes(1));const [accountId, options] = providerOAuthLogin.mock.calls[0];if (exit === 'unmount') unmount();@@ -226,7 +253,7 @@ describe('AddProviderWizard — OpenAI 授权边界', () => {const onDone = vi.fn();render(<AddProviderWizard providers={[{ ...OPENAI_PROVIDER, id, name: id, connected: true }]}entry={{ kind: 'builtin', providerId: id }} onOpenCustomForm={vi.fn()} onClose={vi.fn()} onDone={onDone} />);- fireEvent.click(screen.getByText('settings.providers.button.authorize'));+ fireEvent.click(screen.getByText('settings.providers.openai.addIndependentAccount'));await waitFor(() => expect(providerOAuthLogin).toHaveBeenCalledTimes(1));const [accountId, options] = providerOAuthLogin.mock.calls[0];fireEvent.click(screen.getByText('settings.providers.wizard.cancel'));@@ -240,7 +267,7 @@ describe('AddProviderWizard — OpenAI 授权边界', () => {render(<AddProviderWizard providers={[{ ...OPENAI_PROVIDER, id, name: id, connected: true }]}onOpenCustomForm={vi.fn()} onClose={vi.fn()} onDone={onDone} />);fireEvent.click(await screen.findByText(id));- fireEvent.click(await screen.findByText('settings.providers.button.authorize'));+ fireEvent.click(await screen.findByText('settings.providers.openai.addIndependentAccount'));await waitFor(() => expect(providerOAuthLogin).toHaveBeenCalledTimes(1));const accountId = providerOAuthLogin.mock.calls[0][0];expect(accountId).toMatch(new RegExp(`^${id}-`));diff --git a/apps/desktop/src/renderer/__tests__/addProviderWizardOpenaiEntry.test.tsx b/apps/desktop/src/renderer/__tests__/addProviderWizardOpenaiEntry.test.tsxindex 1f1f5bf479..8b9656f733 100644--- a/apps/desktop/src/renderer/__tests__/addProviderWizardOpenaiEntry.test.tsx+++ b/apps/desktop/src/renderer/__tests__/addProviderWizardOpenaiEntry.test.tsx@@ -96,6 +96,7 @@ beforeEach(() => {delete codexState.authSource;(window as unknown as { electronAPI: unknown }).electronAPI = {maker: {+ auth: { triggerLogin: vi.fn(async () => ({ authenticated: true, authSource: 'oauth', credentialScope: 'system-shared' })) },listProviderPresets: vi.fn(async () => ({ presets: [] })),localModelList: vi.fn(async () => ({status: { runtime: 'ollama', kind: 'absent', appInstalled: false },@@ -127,6 +128,15 @@ describe('AddProviderWizard — OpenAI 检测建议直达', () => {expect(screen.getByText('settings.providers.openai.useLocalAccount')).not.toBeNull();});+ it('explicitly reconnects the existing local account without browser authorization', async () => {+ const onDone = vi.fn();+ renderWizard('openai', onDone);+ fireEvent.click(screen.getByText('settings.providers.openai.useLocalAccount'));+ await waitFor(() => expect(onDone).toHaveBeenCalledWith('openai'));+ expect(window.electronAPI.maker.auth.triggerLogin).toHaveBeenCalledWith('codex', { mode: 'local', ownerId: expect.any(String) });+ expect(window.electronAPI.maker.providerOAuthLogin).not.toHaveBeenCalled();+ });+it.each([{ connected: true },{ connected: true, suspended: true },@@ -160,7 +170,8 @@ describe('AddProviderWizard — OpenAI 检测建议直达', () => {renderWizard('anthropic', onDone);expect(screen.getByText('settings.providers.wizard.titleWith')).not.toBeNull();- expect(screen.getByText('settings.providers.button.authorize')).not.toBeNull();+ expect(screen.getByText('settings.providers.openai.addIndependentAccount')).not.toBeNull();+ expect(screen.getByText('settings.providers.localAccount.useClaude')).not.toBeNull();expect(onDone).not.toHaveBeenCalled();});});diff --git a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsxindex 5153c71138..6f95067c8e 100644--- a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx+++ b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx@@ -925,6 +925,26 @@ describe('AddProviderWizard — preset 直达', () => {});});+it.each(['apiKey', 'oauth'] as const)('keeps retained single-instance %s connections out of the add list across disconnect and delete', async (method) => {+ const provider = {+ ...anthropicProvider, id: 'gemini', name: 'Single Connection', agents: [], models: {},+ auth: { method, oauth: { kind: 'native' } },+ audioModels: [{ id: 'media', name: 'Media' }],+ } as unknown as ProviderView;+ const props = { onOpenCustomForm: vi.fn(), onClose: vi.fn(), onDone: vi.fn() };+ const view = render(<AddProviderWizard {...props} providers={[provider]} />);+ expect(await screen.findByText('Single Connection')).toBeTruthy();+ for (const state of [+ { connected: true, removed: false },+ { connected: false, removed: false },+ { connected: false, removed: true },+ { connected: true, removed: false },+ ]) {+ view.rerender(<AddProviderWizard {...props} providers={[{ ...provider, ...state }]} />);+ expect(screen.queryByText('Single Connection') !== null).toBe(state.removed);+ }+});+it.each(['audioModels', 'embeddingModels'] as const)('opens key setup for a disconnected media-only builtin with %s', async (field) => {const mediaProvider = {...anthropicProvider, id: 'gemini', name: 'Media Only', agents: [], models: {},diff --git a/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsx b/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsxindex bef80bbf34..06742a3c58 100644--- a/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsx+++ b/apps/desktop/src/renderer/__tests__/providersSectionAssetModule.test.tsx@@ -251,7 +251,7 @@ describe('ProvidersSection — Cindy AI 账户资产模块', () => {expect(badge.textContent).toBe('settings.providers.xd.accountTier.free');const assetModule = screen.getByTestId('cindy-ai-asset-module');expect(assetModule.contains(badge)).toBe(false);- expect(badge.previousElementSibling?.textContent).toBe('Cindy AI');+ expect(badge.previousElementSibling?.textContent).toBe('settings.providers.xd.title');expect(screen.getByTestId('provider-detail-metadata').textContent).not.toContain('settings.providers.models.modelCount');expect(screen.getByTestId('provider-detail-metadata').contains(badge)).toBe(true);diff --git a/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx b/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsxindex 423770cbbb..0840ce2500 100644--- a/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx+++ b/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx@@ -77,8 +77,9 @@ vi.mock('@/hooks/useModelAccessStatus', () => ({useModelAccessStatus: () => ({ state: 'failed', source: null, endpoint: null }),}));+const confirmSpy = vi.hoisted(() => vi.fn(async () => true));vi.mock('@/components/ui/confirm-dialog-provider', () => ({- useConfirmDialog: () => ({ confirm: vi.fn() }),+ useConfirmDialog: () => ({ confirm: confirmSpy }),}));vi.mock('@/lib/toast', () => ({@@ -127,15 +128,19 @@ vi.mock('@/components/settings/AddProviderWizard', () => ({},}));+import { updateCustomProvider } from '@/lib/customProviders';+import { ProvidersSection } from '@/components/settings/ProvidersSection';+vi.mock('@/components/settings/OllamaProviderDetail', () => ({ OllamaProviderDetail: () => null }));+function makeProvider(id: string, over?: Partial<ProviderView>): ProviderView {return {id,name: id,source: 'builtin',agents: ['claude-code'],- auth: { method: 'oauth' },+ auth: { method: 'oauth', oauth: { authorizeUrl: 'https://auth.example.test/authorize', tokenUrl: 'https://auth.example.test/token', clientId: 'fixture', scopes: 'openid' } },routing: {},models: { 'claude-code': [] },connected: false,@@ -167,6 +172,7 @@ function renderAt(search: string) {}beforeEach(() => {+ confirmSpy.mockReset().mockResolvedValue(true);codexAuthState.state = { kind: 'unauthenticated' };codexAuthState.reconnectCredentialScope = undefined;codexAuthState.recoveryCheck = 'idle';@@ -182,11 +188,18 @@ beforeEach(() => {];(window as unknown as { electronAPI: unknown }).electronAPI = {maker: {+ listProviders: vi.fn(async () => ({ providers: providersState.providers, dataOwnerId: 'owner', ownerGeneration: 1 })),+ setProviderPresentation: vi.fn(async () => ({ ok: true })),+ providerOAuthLogout: vi.fn(async () => ({ ok: true })),+ auth: { logout: codexAuthActions.logout },scanLocalCli: vi.fn(async () => ({ detections: [] })),+ localModelStatus: vi.fn(async () => ({ kind: 'ready' })),+ onLocalModelStatus: vi.fn(() => () => undefined),requestProviderModelsAutoRefresh: vi.fn(async () => ({ ok: true })),setProviderOrder: vi.fn(async () => ({ ok: true })),},openChatGPTApp: vi.fn(async () => ({ success: true })),+ builtinApiKeyRemove: vi.fn(async () => undefined),};});@@ -196,6 +209,18 @@ afterEach(() => {});describe('ProvidersSection — 深链定位', () => {+ it('does not rediscover a deleted local Codex provider into the settings list', async () => {+ providersState.providers.push(makeProvider('openai', {+ name: 'Deleted local account', removed: true, imageModels: [{ id: 'image', name: 'Image' }],+ }));+ vi.mocked(window.electronAPI.maker.scanLocalCli).mockResolvedValue({ detections: [{+ cli: 'codex-cli', providerId: 'openai', installed: true, loggedIn: true, sharedWithCindy: false,+ }] });+ renderAt('?tab=providers');+ await waitFor(() => expect(window.electronAPI.maker.scanLocalCli).toHaveBeenCalled());+ expect(screen.queryByText('Deleted local account')).toBeNull();+ });+it.each([true, false])('keeps a native Codex account without models visible (connected=%s)',async (connected) => {@@ -222,6 +247,15 @@ describe('ProvidersSection — 深链定位', () => {},);+ it.each(['anthropic', 'xai', 'cindy-local-ollama'])('shows the saved name in both sidebar and detail header for %s', async (id) => {+ providersState.providers = [makeProvider(id, {+ name: 'My renamed provider', connected: true,+ source: id === 'cindy-local-ollama' ? 'user' : 'builtin',+ })];+ renderAt(`?tab=providers&connect=${id}`);+ await waitFor(() => expect(screen.getAllByText('My renamed provider').length).toBeGreaterThanOrEqual(2));+ });+it('added OpenAI shares status and moves rename/delete into the single menu', async () => {providersState.providers = [makeProvider('openai-work', {@@ -256,10 +290,11 @@ describe('ProvidersSection — 深链定位', () => {'settings.providers.custom.deleteAria',]);fireEvent.click(within(menu).getByText('settings.providers.pill.rename'));- expect(await screen.findByTestId('custom-provider-dialog-stub')).toBeTruthy();- expect(customDialogSpy).toHaveBeenLastCalledWith(- expect.objectContaining({ initial: expect.objectContaining({ id: 'openai-work' }) }),- );+ await waitFor(() => expect(window.electronAPI.maker.setProviderPresentation).toHaveBeenCalledWith(+ { providerId: 'openai-work', action: 'rename', name: 'Work account', dataOwnerId: 'owner', ownerGeneration: 1 },+ ));+ expect(updateCustomProvider).not.toHaveBeenCalled();+ expect(customDialogSpy).not.toHaveBeenCalled();});it('API key presence is configured rather than authenticated', async () => {@@ -285,7 +320,7 @@ describe('ProvidersSection — 深链定位', () => {const actions = await screen.findByTestId('provider-detail-actions');expect(within(actions).getByText('settings.providers.pill.configured')).toBeTruthy();expect(within(actions).queryByText('settings.providers.pill.connected')).toBeNull();- expect(within(actions).queryByRole('button')).toBeNull();+ expect(within(actions).getByRole('button', { name: 'settings.providers.button.disconnect' })).toBeTruthy();});it('added OpenAI recovery overrides a stale connected snapshot', async () => {@@ -344,7 +379,7 @@ describe('ProvidersSection — 深链定位', () => {).toBeTruthy();});- it('Dev 只读复用 OpenAI 登录态时保持已连接且不能断开', async () => {+ it('Dev 只读复用 OpenAI 登录态允许只断开 Cindy', async () => {codexAuthState.state = {kind: 'authenticated',authSource: 'oauth',@@ -364,9 +399,96 @@ describe('ProvidersSection — 深链定位', () => {const disconnect = await screen.findByRole('button', {name: 'settings.providers.button.disconnect',});- expect((disconnect as HTMLButtonElement).disabled).toBe(true);+ expect((disconnect as HTMLButtonElement).disabled).toBe(false);fireEvent.click(disconnect);- expect(codexAuthActions.logout).not.toHaveBeenCalled();+ await waitFor(() => expect(codexAuthActions.logout).toHaveBeenCalled());+ expect(window.electronAPI.builtinApiKeyRemove).not.toHaveBeenCalled();+ });++ it.each(['none', 'restore', 'subscription', 'image-key'])('OpenAI deletion disconnects before revoking the legacy image key (failure=%s)', async (failure) => {+ codexAuthState.state = { kind: 'authenticated', authSource: 'oauth' };+ providersState.providers = [makeProvider('openai', {+ name: 'OpenAI', connected: true, agents: ['codex'], models: { codex: [] },+ })];+ const events: string[] = [];+ vi.mocked(window.electronAPI.builtinApiKeyRemove).mockImplementationOnce(async () => {+ events.push('image-key');+ if (failure === 'image-key') throw new Error('remove failed');+ });+ codexAuthActions.logout.mockImplementation(async () => {+ events.push('subscription');+ if (failure === 'subscription') throw new Error('disconnect failed');+ });+ vi.mocked(window.electronAPI.maker.setProviderPresentation).mockImplementation(async (input) => {+ if (input.action === 'restore' && failure === 'restore') throw new Error('restore failed');+ if (input.action === 'remove') events.push('hide');+ });+ renderAt('?tab=providers&connect=openai');+ fireEvent.keyDown(await screen.findByRole('button', { name: 'settings.providers.detail.moreActionsAria' }), { key: 'ArrowDown' });+ fireEvent.click(await screen.findByRole('menuitem', { name: 'settings.providers.custom.deleteAria' }));+ if (failure !== 'none') {+ await waitFor(() => expect(toastError).toHaveBeenCalledWith('settings.providers.custom.toast.deleteFailed'));+ expect(events).toEqual(failure === 'restore' ? [] : failure === 'subscription' ? ['subscription'] : ['subscription', 'image-key']);+ } else {+ await waitFor(() => expect(events).toEqual(['subscription', 'image-key', 'hide']));+ }+ if (failure === 'restore' || failure === 'subscription') {+ expect(window.electronAPI.builtinApiKeyRemove).not.toHaveBeenCalled();+ } else {+ expect(window.electronAPI.builtinApiKeyRemove).toHaveBeenCalledWith(+ 'openai-images', expect.objectContaining({ dataOwnerId: 'owner', ownerGeneration: 1 }),+ );+ }+ });++ it.each([false, true])('busy disconnect retries only after explicit task interruption confirmation (%s)', async (interrupt) => {+ providersState.providers = [makeProvider('fixture-oauth', { name: 'Fixture OAuth', connected: true })];+ confirmSpy.mockResolvedValueOnce(true).mockResolvedValueOnce(interrupt);+ vi.mocked(window.electronAPI.maker.providerOAuthLogout)+ .mockResolvedValueOnce({ ok: false, confirmationRequired: 'codex-image-generation-reload', busyCount: 1 })+ .mockResolvedValueOnce({ ok: true });+ renderAt('?tab=providers&connect=fixture-oauth');+ fireEvent.click(await screen.findByRole('button', { name: 'settings.providers.button.disconnect' }));+ await waitFor(() => expect(confirmSpy).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(window.electronAPI.maker.providerOAuthLogout).toHaveBeenCalledTimes(interrupt ? 2 : 1));+ expect(confirmSpy).toHaveBeenLastCalledWith(expect.objectContaining({ description: 'settings.providers.custom.imageGenerationReload.description' }));+ if (interrupt) expect(window.electronAPI.maker.providerOAuthLogout).toHaveBeenLastCalledWith('fixture-oauth', expect.objectContaining({ dataOwnerId: 'owner', ownerGeneration: 1 }), { source: 'manual-settings', codexImageGenerationRestartPolicy: 'interrupt' });+ });++ it.each(['none', 'managed', 'apiKey', 'oauth'] as const)('unsupported builtin %s has no connection or delete action', async (method) => {+ providersState.providers = [makeProvider('unsupported-provider', { name: 'Unsupported', connected: true, auth: { method } as ProviderView['auth'] })];+ renderAt('?tab=providers&connect=unsupported-provider');+ fireEvent.keyDown(await screen.findByRole('button', { name: 'settings.providers.detail.moreActionsAria' }), { key: 'ArrowDown' });+ expect(screen.queryByRole('menuitem', { name: 'settings.providers.custom.deleteAria' })).toBeNull();+ expect(screen.queryByRole('button', { name: 'settings.providers.button.disconnect' })).toBeNull();+ expect(await screen.findByRole('menuitem', { name: 'settings.providers.pill.rename' })).toBeTruthy();+ expect(window.electronAPI.builtinApiKeyRemove).not.toHaveBeenCalled();+ });++ it.each(['disconnect', 'delete', 'delete-failed'])('generic builtin OAuth uses the OAuth bridge for %s', async (action) => {+ providersState.providers = [makeProvider('fixture-oauth', { name: 'Fixture OAuth', connected: true })];+ const events: string[] = [];+ vi.mocked(window.electronAPI.maker.setProviderPresentation).mockImplementation(async (input) => {+ events.push(input.action);+ });+ vi.mocked(window.electronAPI.maker.providerOAuthLogout).mockImplementation(async () => {+ events.push('oauth-logout');+ if (action === 'delete-failed') throw new Error('fixture failure');+ return { ok: true };+ });+ renderAt('?tab=providers&connect=fixture-oauth');+ if (action === 'disconnect') {+ fireEvent.click(await screen.findByRole('button', { name: 'settings.providers.button.disconnect' }));+ } else {+ fireEvent.keyDown(await screen.findByRole('button', { name: 'settings.providers.detail.moreActionsAria' }), { key: 'ArrowDown' });+ fireEvent.click(await screen.findByRole('menuitem', { name: 'settings.providers.custom.deleteAria' }));+ }+ if (action === 'delete-failed') {+ await waitFor(() => expect(toastError).toHaveBeenCalledWith('settings.providers.custom.toast.deleteFailed'));+ }+ await waitFor(() => expect(events).toEqual(action === 'delete' ? ['restore', 'oauth-logout', 'remove'] : ['restore', 'oauth-logout']));+ expect(window.electronAPI.maker.providerOAuthLogout).toHaveBeenCalledWith('fixture-oauth', expect.objectContaining({ dataOwnerId: 'owner', ownerGeneration: 1 }), { source: 'manual-settings' });+ expect(window.electronAPI.builtinApiKeyRemove).not.toHaveBeenCalled();});it('invalidated OpenAI auth blocks model selection even before the catalog reports disconnection', async () => {@@ -426,6 +548,22 @@ describe('ProvidersSection — 深链定位', () => {expect(codexAuthActions.triggerLogin).not.toHaveBeenCalled();});+ it.each(['instance-isolated', 'unknown', undefined])('ChatGPT 非共享失效凭证通过浏览器重新登录 (%s)', async (credentialScope) => {+ codexAuthState.state = { kind: 'reconnect-required', reason: 'token_revoked', credentialScope };+ providersState.providers = [makeProvider('openai', { name: 'OpenAI', connected: false })];+ renderAt('?tab=providers&connect=openai');+ fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.relogin' }));+ await waitFor(() => expect(codexAuthActions.triggerLogin).toHaveBeenCalledWith('browser'));+ expect(window.electronAPI.openChatGPTApp).not.toHaveBeenCalled();+ });++ it('ChatGPT 主动断开后仍使用本机账号连接', async () => {+ providersState.providers = [makeProvider('openai', { name: 'OpenAI', connected: false, removed: false })];+ renderAt('?tab=providers&connect=openai');+ fireEvent.click(await screen.findByRole('button', { name: 'settings.providers.openai.connect' }));+ await waitFor(() => expect(codexAuthActions.triggerLogin).toHaveBeenCalledWith('local'));+ });+it('ChatGPT 系统共享打开 App 后保留恢复入口', async () => {codexAuthState.state = {kind: 'reconnect-required',@@ -651,7 +789,10 @@ describe('ProvidersSection — 深链定位', () => {];(window as unknown as { electronAPI: unknown }).electronAPI = {maker: {- scanLocalCli: vi.fn(async () => ({ detections: [] })),+ listProviders: vi.fn(async () => ({ providers: providersState.providers, dataOwnerId: 'owner', ownerGeneration: 1 })),+ setProviderPresentation: vi.fn(async () => ({ ok: true })),+ auth: { logout: codexAuthActions.logout },+ scanLocalCli: vi.fn(async () => ({ detections: [] })),requestProviderModelsAutoRefresh: vi.fn(async () => ({ ok: true })),providerOAuthLogin,providerOAuthCancel,diff --git a/apps/desktop/src/renderer/__tests__/subscriptionUsageCache.test.tsx b/apps/desktop/src/renderer/__tests__/subscriptionUsageCache.test.tsxindex 5bdc29f34c..aabef69d59 100644--- a/apps/desktop/src/renderer/__tests__/subscriptionUsageCache.test.tsx+++ b/apps/desktop/src/renderer/__tests__/subscriptionUsageCache.test.tsx@@ -180,3 +180,23 @@ describe('OpenAI quota during a deferred account switch', () => {expect(hook.result.current).toBeNull();});});++it('isolates Grok instantaneous limits per connection and clears an unmounted account only', () => {+ const pushes = new Map<string, (value: unknown) => void>();+ vi.stubGlobal('electronAPI', { maker: { usage: {+ onXaiRateLimitChanged: (cb: (value: unknown) => void, id: string) => { pushes.set(id, cb); return vi.fn(); },+ } } });+ const hook = renderHook(({ id }) => useXaiRateLimit(true, id), { initialProps: { id: 'xai-a' } });+ const a = { remainingRequests: 12 };+ act(() => pushes.get('xai-a')?.(a));+ hook.rerender({ id: 'xai-b' });+ expect(hook.result.current).toBeNull();+ const b = { remainingRequests: 3 };+ act(() => pushes.get('xai-b')?.(b));+ act(() => pushes.get('xai-a')?.(null));+ expect(hook.result.current).toBe(b);+ hook.rerender({ id: 'xai-a' });+ expect(hook.result.current).toBeNull();+ hook.rerender({ id: 'xai-b' });+ expect(hook.result.current).toBe(b);+});diff --git a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsxindex ad3604b206..ee0063f8bb 100644--- a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx+++ b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx@@ -22,7 +22,7 @@ import { cn } from '@/lib/utils';import { toast } from '@/lib/toast';import { Spinner } from '@/components/ui/spinner';import { createCustomProvider, deleteCustomProvider, type RuntimeKeys } from '@/lib/customProviders';-import { PROVIDER_SECRET_IDS } from '../../../shared/providerSecrets';+import { isBuiltinApiKeyProviderId } from '../../../shared/providerSecrets';import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';import { configuredPresetAgents } from '../../../shared/piRuntimeInitialization';import { uniqueCustomProviderId } from '@/lib/customProviderId';@@ -38,6 +38,7 @@ import { pickWizardRecommend, type WizardRecommend } from './wizardRecommend';import { localCliDisplayName, type LocalCliDetection } from '../../../shared/localCliDetect';import { providerMonogram } from '@/lib/providerModels';import { useProviderOAuthDeviceCode } from '@/hooks/useProviderOAuthDeviceCode';+import { acquireCodexLogin, type CodexLoginLease } from '@/hooks/codexAuthLogin';import { hasProviderLogo, ProviderLogoMark } from '@/components/icons/ProviderLogoMark';import { LocalOllamaInstall, offersManagedOllamaInstall } from './LocalOllamaInstall';import { OAuthDeviceCodeCard } from './OAuthDeviceCodeCard';@@ -322,6 +323,10 @@ function GroupLabel({ children }: { children: React.ReactNode }) {);}+function hasRetainedBuiltinConnection(provider: ProviderView): boolean {+ return !provider.removed && (provider.connected || provider.removed === false);+}+export function AddProviderWizard({providers,entry,@@ -335,7 +340,7 @@ export function AddProviderWizard({// connection. Keep the slot occupied when suspended or awaiting reconnection.const localOpenAiAlreadyAdded = providers.some(provider => provider.id === 'openai' &&- (provider.connected || provider.openAiAccount?.reconnectRequired === true),+ !provider.removed && (provider.connected || provider.removed === false || provider.openAiAccount?.reconnectRequired === true),);const [presets, setPresets] = useState<ProviderPreset[]>([]);@@ -473,21 +478,22 @@ export function AddProviderWizard({(p) =>p.id !== 'xd' &&p.source === 'builtin' &&- (!p.connected || ['anthropic', 'openai', 'xai'].includes(p.id)) &&+ (!hasRetainedBuiltinConnection(p) || ['anthropic', 'openai', 'xai'].includes(p.id)) &&(['anthropic', 'openai', 'xai'].includes(p.id) ||(p.auth.method === 'oauth' && !!p.auth.oauth)),),[providers],);// 内置 API-key 渠道(auth.method 'apiKey' 的 builtin 条目):- // 已连接的不再进向导;声明了媒体清单才展示(纯占位条目没有可配置的能力面)。+ // 已添加(包括断开后保留)的连接不再进向导;声明了媒体清单才展示。const builtinApiKeyChoices = useMemo(() =>providers.filter((p) =>p.source === 'builtin' &&p.auth.method === 'apiKey' &&- !p.connected &&+ isBuiltinApiKeyProviderId(p.id) &&+ !hasRetainedBuiltinConnection(p) &&PROVIDER_MEDIA_FIELDS.some((field) => (p[field]?.length ?? 0) > 0),),[providers],@@ -671,7 +677,11 @@ export function AddProviderWizard({}, [entry, presets, pickPreset]);const accountLoginRef = useRef<{ providerId: string; ownerId: string } | null>(null);+ const localLoginRef = useRef<{ cancel: () => void } | null>(null);useEffect(() => () => {+ const localLogin = localLoginRef.current;+ localLoginRef.current = null;+ localLogin?.cancel();const login = accountLoginRef.current;accountLoginRef.current = null;if (login) void window.electronAPI.maker.providerOAuthCancel(login.providerId, { ownerId: login.ownerId, releaseOwner: true });@@ -679,18 +689,46 @@ export function AddProviderWizard({const useLocalOpenAiAccount = useCallback(async () => {setLoggingIn(true);+ let lease: CodexLoginLease | undefined;+ const login = { cancel: () => lease?.release({ cancelIfLastOwner: true }) };+ localLoginRef.current = login;try {- const state = await window.electronAPI.maker.auth.getState('codex');- const detected = await window.electronAPI.maker.scanLocalCli();- setCliDetections(detected.detections);+ lease = acquireCodexLogin('local');+ const state = await lease.promise;+ if (localLoginRef.current !== login) return;if (state.authenticated && state.authSource === 'oauth' && state.credentialScope === 'system-shared') {onDone('openai');- } else {+ } else if (state.errorReason !== 'login_cancelled') {toast.error(t('settings.providers.openai.localUnavailable'));}} catch {- toast.error(t('settings.providers.openai.localUnavailable'));- } finally { setLoggingIn(false); }+ if (localLoginRef.current === login) toast.error(t('settings.providers.openai.localUnavailable'));+ } finally {+ lease?.release();+ if (localLoginRef.current === login) {+ localLoginRef.current = null;+ setLoggingIn(false);+ }+ }+ }, [onDone, t]);++ const useLocalClaudeAccount = useCallback(async () => {+ setLoggingIn(true);+ const loginKey = crypto.randomUUID();+ const login = { cancel: () => { void window.electronAPI.maker.claudeOAuthCancel(loginKey).catch(() => undefined); } };+ localLoginRef.current = login;+ try {+ const result = await window.electronAPI.maker.claudeOAuthLogin(loginKey);+ if (localLoginRef.current !== login) return;+ if (result.ok) onDone('anthropic');+ else if (result.reason !== 'login_cancelled') toast.error(t('settings.providers.localAccount.unavailable'));+ } catch { if (localLoginRef.current === login) toast.error(t('settings.providers.localAccount.unavailable')); }+ finally {+ if (localLoginRef.current === login) {+ localLoginRef.current = null;+ setLoggingIn(false);+ }+ }}, [onDone, t]);// ── OAuth 授权(复用既有鉴权流;成功即完成,无第 3 步)────────────────────@@ -760,6 +798,9 @@ export function AddProviderWizard({* 都必须能中止 main 侧 login runner,否则浏览器流挂起时用户无法重试。*/const cancelAuthorize = useCallback(() => {+ const localLogin = localLoginRef.current;+ localLoginRef.current = null;+ localLogin?.cancel();if (!sel || sel.kind !== 'oauth') return;const id = sel.provider.id;if (id === 'openai' || id === 'anthropic' || id === 'xai') {@@ -1067,7 +1108,7 @@ export function AddProviderWizard({const handleSaveBuiltinApiKey = useCallback(async () => {if (!sel || sel.kind !== 'builtinApiKey') return;const id = sel.provider.id;- if (!(PROVIDER_SECRET_IDS as readonly string[]).includes(id)) {+ if (!isBuiltinApiKeyProviderId(id)) {// 目录出现了未在 providerSecrets 登记的内置 API-key 供应商 = 数据/代码脱节,// 明确报错让问题在配置期暴露,不静默写错键。toast.error(t('settings.providers.wizard.authorizeFailed', { name: sel.provider.name }));@@ -1615,6 +1656,13 @@ export function AddProviderWizard({{t('settings.providers.openai.useLocalAccount')}</button>)}+ {sel.provider.id === 'anthropic' && !providers.some(p => p.id === 'anthropic' && !p.removed && (p.connected || p.removed === false)) && (+ <button type="button" onClick={() => void useLocalClaudeAccount()}+ className="flex h-9 items-center justify-center rounded-full border px-6 text-13 font-medium hover:bg-[var(--surface-hover)]"+ style={{ backgroundColor: 'var(--settings-btn-secondary-bg)', borderColor: 'var(--settings-btn-secondary-border)', color: 'var(--settings-btn-secondary-text)' }}>+ {t('settings.providers.localAccount.useClaude')}+ </button>+ )}<buttontype="button"onClick={() => void handleAuthorize()}@@ -1626,7 +1674,7 @@ export function AddProviderWizard({}}>{t(- sel.provider.id === 'openai'+ ['openai', 'anthropic', 'xai'].includes(sel.provider.id)? 'settings.providers.openai.addIndependentAccount': sel.provider.auth.oauth?.flow === 'device-code'? 'settings.providers.wizard.authorizeWithDeviceCode'diff --git a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsxindex 49a0d71ce1..9ab7c049ec 100644--- a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx+++ b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx@@ -59,8 +59,10 @@ import {readCustomProviderKey,updateCustomProvider,} from '@/lib/customProviders';+import { providerDisplayName } from '@/lib/providerDisplayName';import { providerMonogram } from '@/lib/providerModels';-import { PROVIDER_SECRET_IDS } from '../../../shared/providerSecrets';+import { isBuiltinApiKeyProviderId } from '../../../shared/providerSecrets';+import type { CustomProviderUpdateOptions, CustomProviderUpdateResult } from '../../../shared/customProviderUpdate';import {customProviderSubtitleForDisplay,@@ -239,6 +241,137 @@ function BetaTag({ label }: { label: string }) {// (重构前的 ProviderCell 去掉展开逻辑;模型列表由详情容器统一渲染。)// ---------------------------------------------------------------------------+type ProviderOwnerScope = { dataOwnerId: string | null; ownerGeneration: number };+function supportsBuiltinConnectionManagement(provider: ProviderView): boolean {+ return provider.source === 'builtin' && provider.id !== 'xd' && (+ ['openai', 'anthropic', 'xai'].includes(provider.id) ||+ (provider.auth.method === 'oauth' && !!provider.auth.oauth) ||+ (provider.auth.method === 'apiKey' && isBuiltinApiKeyProviderId(provider.id))+ );+}+/** Reuse the image Host restart confirmation for settings mutations that remove its source. */+function useProviderChangeConfirmation() {+ const { t } = useTranslation();+ const { confirm } = useConfirmDialog();+ return useCallback(async (change: (options: CustomProviderUpdateOptions) => Promise<CustomProviderUpdateResult | void>) => {+ const result = await change({ source: 'manual-settings' });+ if (!result || result.ok) return true;+ if (!(await confirm({+ title: t('settings.providers.custom.imageGenerationReload.title'),+ description: t('settings.providers.custom.imageGenerationReload.description'),+ confirmText: t('settings.providers.custom.imageGenerationReload.interrupt'),+ cancelText: t('settings.providers.custom.imageGenerationReload.cancel'),+ }))) return false;+ const retry = await change({ source: 'manual-settings', codexImageGenerationRestartPolicy: 'interrupt' });+ return !retry || retry.ok;+ }, [confirm, t]);+}+async function disconnectProvider(+ provider: ProviderView,+ scope: ProviderOwnerScope,+ options?: CustomProviderUpdateOptions,+): Promise<CustomProviderUpdateResult | void> {+ if (provider.source === 'builtin') {+ if (!supportsBuiltinConnectionManagement(provider)) throw new Error('Provider connection management is unavailable');+ // Keep the entry available for reconnect, even when the original source was auto-detected.+ await window.electronAPI.maker.setProviderPresentation({+ providerId: provider.id,+ action: 'restore',+ ...scope,+ });+ if (provider.id === 'openai') await window.electronAPI.maker.auth.logout('codex', scope);+ else if (provider.id === 'anthropic') await window.electronAPI.maker.claudeOAuthLogout(scope);+ else if (provider.id === 'xai') await window.electronAPI.maker.xaiOAuthLogout(scope);+ else if (provider.auth.method === 'oauth') return window.electronAPI.maker.providerOAuthLogout(provider.id, scope, options);+ else await window.electronAPI.builtinApiKeyRemove(provider.id, scope);+ } else if (provider.auth.method === 'oauth') {+ return window.electronAPI.maker.providerOAuthLogout(provider.id, scope, options);+ } else {+ return window.electronAPI.maker.disconnectCustomProvider(provider.id, scope, options);+ }+}++function useProviderManagement(provider?: ProviderView) {+ const { t } = useTranslation();+ const { confirm } = useConfirmDialog();+ const confirmProviderChange = useProviderChangeConfirmation();+ const { refetch } = useProviders();+ const [busy, setBusy] = useState(false);+ const rename = async () => {+ if (!provider || busy) return;+ try {+ const scope = await window.electronAPI.maker.listProviders();+ let name = provider.name;+ if (+ !(await confirm({+ title: t('settings.providers.pill.rename'),+ content: (+ <LocalProviderNameInput+ initialName={name}+ onChange={(next) => {+ name = next;+ }}+ />+ ),+ confirmText: t('settings.providers.custom.save'),+ cancelText: t('settings.providers.custom.cancel'),+ }))+ )+ return;+ setBusy(true);+ await window.electronAPI.maker.setProviderPresentation({+ providerId: provider.id,+ action: 'rename',+ name,+ dataOwnerId: scope.dataOwnerId,+ ownerGeneration: scope.ownerGeneration,+ });+ refetch();+ } catch {+ toast.error(t('settings.providers.custom.toast.saveFailed'));+ } finally {+ setBusy(false);+ }+ };+ const removeBuiltin = async () => {+ if (!provider || busy) return;+ try {+ const scope = await window.electronAPI.maker.listProviders();+ if (+ !(await confirm({+ title: t('settings.providers.custom.deleteConfirm.title'),+ description: t('settings.providers.custom.deleteConfirm.description', {+ name: provider.name,+ }),+ confirmText: t('settings.providers.custom.deleteConfirm.confirm'),+ cancelText: t('settings.providers.custom.cancel'),+ }))+ )+ return;+ setBusy(true);+ if (!(await confirmProviderChange(options => disconnectProvider(provider, scope, options)))) return;+ // Deleting the whole provider also revokes its legacy image API connection.+ // Keep this separate from disconnecting only the ChatGPT subscription.+ if (provider.id === 'openai') {+ await window.electronAPI.builtinApiKeyRemove('openai-images', scope);+ }+ await window.electronAPI.maker.setProviderPresentation({+ providerId: provider.id,+ action: 'remove',+ dataOwnerId: scope.dataOwnerId,+ ownerGeneration: scope.ownerGeneration,+ });+ toast.success(t('settings.providers.custom.toast.deleted'));+ } catch {+ toast.error(t('settings.providers.custom.toast.deleteFailed'));+ } finally {+ setBusy(false);+ refetch();+ }+ };+ return { busy, rename, removeBuiltin };+}+function DetailHeader({icon,title,@@ -278,6 +411,16 @@ function DetailHeader({assetModule?: ReactNode;}) {const { t } = useTranslation();+ const management = useProviderManagement(provider);+ const canRename = !!provider && provider.id !== 'xd';+ const resolvedDelete =+ deleteAction ??+ (provider && supportsBuiltinConnectionManagement(provider)+ ? {+ label: t('settings.providers.custom.deleteAria'),+ onClick: () => void management.removeBuiltin(),+ }+ : undefined);const subscription = useProviderSubscriptionCard(provider);const subscriptionProduct =provider?.access?.kind === 'subscription' ? provider.access.product : null;@@ -324,16 +467,22 @@ function DetailHeader({className="min-w-0 truncate text-14 font-medium leading-tight"style={{ color: 'var(--settings-section-title)' }}>- {provider?.name ?? title}+ {provider ? providerDisplayName(provider, t) : title}</span>{identityBadge}{subscriptionProduct && (<CustomTag- label={subscription?.planLabel- ? subscription.planLabel.toLowerCase().startsWith(subscriptionProduct.toLowerCase())+ label={+ subscription?.planLabel? subscription.planLabel- : `${subscriptionProduct} ${subscription.planLabel}`- : t('settings.providers.models.subscriptionProduct', { product: subscriptionProduct })}+ .toLowerCase()+ .startsWith(subscriptionProduct.toLowerCase())+ ? subscription.planLabel+ : `${subscriptionProduct} ${subscription.planLabel}`+ : t('settings.providers.models.subscriptionProduct', {+ product: subscriptionProduct,+ })+ }/>)}{provider?.suspended && (@@ -384,7 +533,16 @@ function DetailHeader({</Tip></DropdownMenuTrigger><DropdownMenuContent align="end">- {editAction && (+ {canRename && (+ <DropdownMenuItem+ onClick={() => void management.rename()}+ disabled={management.busy}+ >+ <Pencil size={18} className="mr-2.5" />+ {t('settings.providers.pill.rename')}+ </DropdownMenuItem>+ )}+ {editAction && !provider?.auth.native && (<DropdownMenuItem onClick={editAction.onClick} disabled={editAction.disabled}><Pencil size={18} className="mr-2.5" />{editAction.label}@@ -407,12 +565,12 @@ function DetailHeader({)}</DropdownMenuItem>{menuFooter}- {deleteAction && (+ {resolvedDelete && (<><DropdownMenuSeparator />- <DropdownMenuItem onClick={deleteAction.onClick}>+ <DropdownMenuItem onClick={resolvedDelete.onClick} disabled={management.busy}><Trash2 size={18} className="mr-2.5" />- {deleteAction.label}+ {resolvedDelete.label}</DropdownMenuItem></>)}@@ -424,16 +582,33 @@ function DetailHeader({{detail}</div>- {assetModule ?? (subscription && (- <div data-testid="provider-usage-module" className="border-t px-1 py-2" style={{ borderColor: 'var(--settings-theme-card-border)' }}>- <QuotaHoverCard- variant="embedded"- account={subscription}- dashboardLabel={provider?.id === 'anthropic' ? t('settings.providers.usage.openClaudeUsage') : provider?.id === 'xai' ? t('settings.providers.xai.asset.openUsage') : undefined}- onOpenDashboard={provider?.id === 'anthropic' ? () => void window.electronAPI.openExternal('https://claude.ai/settings/usage') : provider?.id === 'xai' ? () => void window.electronAPI.openExternal('https://grok.com') : undefined}- />- </div>- ))}+ {assetModule ??+ (subscription && (+ <div+ data-testid="provider-usage-module"+ className="border-t px-1 py-2"+ style={{ borderColor: 'var(--settings-theme-card-border)' }}+ >+ <QuotaHoverCard+ variant="embedded"+ account={subscription}+ dashboardLabel={+ provider?.id === 'anthropic' || provider?.auth.native === 'claude'+ ? t('settings.providers.usage.openClaudeUsage')+ : provider?.id === 'xai' || provider?.auth.native === 'xai'+ ? t('settings.providers.xai.asset.openUsage')+ : undefined+ }+ onOpenDashboard={+ provider?.id === 'anthropic' || provider?.auth.native === 'claude'+ ? () => void window.electronAPI.openExternal('https://claude.ai/settings/usage')+ : provider?.id === 'xai' || provider?.auth.native === 'xai'+ ? () => void window.electronAPI.openExternal('https://grok.com')+ : undefined+ }+ />+ </div>+ ))}</div>);}@@ -454,39 +629,56 @@ function AnthropicHeader({const [busy, setBusy] = useState(false);const [loggingIn, setLoggingIn] = useState(false);const connected = provider?.connected ?? false;+ const loginRef = useRef<string | null>(null);+ const cancelLogin = useCallback(() => {+ if (!loginRef.current) return;+ const loginKey = loginRef.current;+ loginRef.current = null;+ void window.electronAPI.maker.claudeOAuthCancel(loginKey).catch(() => undefined);+ }, []);+ useEffect(() => cancelLogin, [cancelLogin]);const handleLogin = useCallback(async () => {+ const login = crypto.randomUUID();+ loginRef.current = login;setLoggingIn(true);try {- const r = await window.electronAPI.maker.claudeOAuthLogin();+ const r = await window.electronAPI.maker.claudeOAuthLogin(login);+ if (loginRef.current !== login) return;if (r.ok) {toast.success(t('settings.connections.claude.toast.loggedIn'));onChanged();} else if (r.reason === 'login_cancelled') {/* 用户取消,不弹错 */+ } else if (r.reason === 'local_unavailable') {+ toast.error(t('settings.providers.localAccount.unavailable'));} else if (r.reason === 'not_a_subscription') {toast.error(t('settings.connections.claude.toast.notSubscription'));} else {toast.error(t('settings.connections.claude.toast.loginFailed'));}} catch {- toast.error(t('settings.connections.claude.toast.loginFailed'));+ if (loginRef.current === login) toast.error(t('settings.connections.claude.toast.loginFailed'));} finally {- setLoggingIn(false);+ if (loginRef.current === login) {+ loginRef.current = null;+ setLoggingIn(false);+ }}}, [onChanged, t]);const handleLogout = useCallback(async () => {- const confirmed = await confirm({- title: t('settings.connections.claude.logoutConfirm.title'),- description: t('settings.connections.claude.logoutConfirm.description'),- confirmText: t('settings.connections.claude.logoutConfirm.confirm'),- cancelText: t('settings.connections.claude.logoutConfirm.cancel'),- });- if (!confirmed) return;- setBusy(true);try {- await window.electronAPI.maker.claudeOAuthLogout();+ const scope = await window.electronAPI.maker.listProviders();+ const confirmed = await confirm({+ title: t('settings.connections.claude.logoutConfirm.title'),+ description: t('settings.connections.claude.logoutConfirm.description'),+ confirmText: t('settings.connections.claude.logoutConfirm.confirm'),+ cancelText: t('settings.connections.claude.logoutConfirm.cancel'),+ });+ if (!confirmed) return;+ setBusy(true);+ if (provider) await disconnectProvider(provider, scope);toast.success(t('settings.connections.claude.toast.loggedOut'));onChanged();} catch {@@ -494,7 +686,7 @@ function AnthropicHeader({} finally {setBusy(false);}- }, [confirm, onChanged, t]);+ }, [confirm, provider, onChanged, t]);const status = {kind: connected ? 'connected' : 'neutral',@@ -510,11 +702,13 @@ function AnthropicHeader({}: {label: t(- loggingIn ? 'settings.providers.button.cancel' : 'settings.providers.button.authorize',+ loggingIn+ ? 'settings.providers.button.cancel'+ : 'settings.providers.localAccount.useClaude',),onClick: () => {if (loggingIn) {- void window.electronAPI.maker.claudeOAuthCancel();+ cancelLogin();setLoggingIn(false);} else {void handleLogin();@@ -525,7 +719,7 @@ function AnthropicHeader({return (<DetailHeadericon={<AnthropicMark size={18} />}- title={t('settings.providers.anthropic.title')}+ title={provider?.name ?? t('settings.providers.anthropic.title')}subtitle={providerSubtitleForDisplay(provider, t('settings.providers.anthropic.modelLabel'), {fallback: t('settings.providers.anthropic.subtitle'),})}@@ -540,6 +734,29 @@ function AnthropicHeader({// OpenAI —— OAuth(ChatGPT 订阅 / Codex),复用 useCodexAuth()。// ---------------------------------------------------------------------------+function LocalProviderNameInput({+ initialName,+ onChange,+}: {+ initialName: string;+ onChange: (name: string) => void;+}) {+ const { t } = useTranslation();+ const [name, setName] = useState(initialName);+ return (+ <SettingsTextInput+ aria-label={t('settings.providers.pill.rename')}+ value={name}+ maxLength={128}+ autoFocus+ onChange={(value) => {+ setName(value);+ onChange(value);+ }}+ />+ );+}+function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChanged: () => void }) {const { t } = useTranslation();const { confirm } = useConfirmDialog();@@ -560,25 +777,26 @@ function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChan: (reconnectCredentialScope ?? 'unknown');const oauthWritesBlocked = state.oauthWritesBlocked === true;const handleLogout = useCallback(async () => {- const confirmed = await confirm({- title: t('settings.connections.codex.logoutConfirm.title'),- description: t('settings.connections.codex.logoutConfirm.description'),- confirmText: t('settings.connections.codex.logoutConfirm.confirm'),- cancelText: t('settings.connections.codex.logoutConfirm.cancel'),- });- if (!confirmed) return;try {- await logout();+ const scope = await window.electronAPI.maker.listProviders();+ const confirmed = await confirm({+ title: t('settings.connections.codex.logoutConfirm.title'),+ description: t('settings.connections.codex.logoutConfirm.description'),+ confirmText: t('settings.connections.codex.logoutConfirm.confirm'),+ cancelText: t('settings.connections.codex.logoutConfirm.cancel'),+ });+ if (!confirmed) return;+ if (provider) await disconnectProvider(provider, scope);toast.success(t('settings.connections.codex.toast.loggedOut'));} catch {toast.error(t('settings.connections.codex.toast.logoutFailed'));} finally {onChanged();}- }, [confirm, logout, onChanged, t]);+ }, [confirm, provider, onChanged, t]);const handleLogin = useCallback(async () => {- const outcome = await triggerLogin();+ const outcome = await triggerLogin(reconnectRequired && credentialScope !== 'system-shared' ? 'browser' : 'local');if (outcome === 'authenticated') {onChanged();} else if (outcome === 'unverified') {@@ -588,7 +806,7 @@ function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChan} else if (outcome === 'failed') {toast.error(t('settings.connections.codex.toast.loginFailed'));}- }, [triggerLogin, onChanged, t]);+ }, [triggerLogin, reconnectRequired, credentialScope, onChanged, t]);const handleRecovery = useCallback(async () => {if (recoveryCheck === 'checking' || loggingIn) return;@@ -624,7 +842,6 @@ function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChan? {label: t('settings.providers.button.disconnect'),onClick: () => void handleLogout(),- disabled: oauthWritesBlocked,}: reconnectRequired? {@@ -636,12 +853,9 @@ function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChan(oauthWritesBlocked && credentialScope !== 'system-shared'),}: {- label: oauthWritesBlocked- ? t('chatgptAuthRecovery.devReadOnly')- : loggingIn- ? t('settings.providers.openai.cancelConnect')- : t('settings.providers.openai.connect'),- disabled: oauthWritesBlocked,+ label: loggingIn+ ? t('settings.providers.openai.cancelConnect')+ : t('settings.providers.openai.connect'),onClick: () => {if (loggingIn) void cancelLogin();else void handleLogin();@@ -651,7 +865,7 @@ function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChanreturn (<DetailHeadericon={<OpenAIMark size={18} />}- title={t('settings.providers.openai.title')}+ title={provider?.name ?? t('settings.providers.openai.title')}subtitle={provider?.openAiAccount? [@@ -697,16 +911,17 @@ function XaiHeader({ provider, onChanged }: { provider?: ProviderView; onChanged}, [onChanged, t]);const handleLogout = useCallback(async () => {- const confirmed = await confirm({- title: t('settings.connections.xai.logoutConfirm.title'),- description: t('settings.connections.xai.logoutConfirm.description'),- confirmText: t('settings.connections.xai.logoutConfirm.confirm'),- cancelText: t('settings.connections.xai.logoutConfirm.cancel'),- });- if (!confirmed) return;- setBusy(true);try {- await window.electronAPI.maker.xaiOAuthLogout();+ const scope = await window.electronAPI.maker.listProviders();+ const confirmed = await confirm({+ title: t('settings.connections.xai.logoutConfirm.title'),+ description: t('settings.connections.xai.logoutConfirm.description'),+ confirmText: t('settings.connections.xai.logoutConfirm.confirm'),+ cancelText: t('settings.connections.xai.logoutConfirm.cancel'),+ });+ if (!confirmed) return;+ setBusy(true);+ if (provider) await disconnectProvider(provider, scope);toast.success(t('settings.connections.xai.toast.loggedOut'));onChanged();} catch {@@ -714,7 +929,7 @@ function XaiHeader({ provider, onChanged }: { provider?: ProviderView; onChanged} finally {setBusy(false);}- }, [confirm, onChanged, t]);+ }, [confirm, provider, onChanged, t]);const status = {kind: connected ? 'connected' : 'neutral',@@ -745,7 +960,7 @@ function XaiHeader({ provider, onChanged }: { provider?: ProviderView; onChangedreturn (<DetailHeadericon={<ProviderLogoMark providerId="xai" size={18} />}- title={t('settings.providers.xai.title')}+ title={provider?.name ?? t('settings.providers.xai.title')}subtitle={providerSubtitleForDisplay(provider, t('settings.providers.xai.modelLabel'), {fallback: t('settings.providers.xai.subtitle'),})}@@ -773,6 +988,7 @@ function GenericOAuthHeader({}) {const { t } = useTranslation();const { confirm } = useConfirmDialog();+ const confirmProviderChange = useProviderChangeConfirmation();const [busy, setBusy] = useState(false);const [loggingIn, setLoggingIn] = useState(false);const connected = provider.connected;@@ -819,18 +1035,19 @@ function GenericOAuthHeader({}, [beginOwnedLogin, clearDeviceCode, onChanged, provider.id, provider.name, t]);const handleLogout = useCallback(async () => {- const confirmed = await confirm({- title: t('settings.providers.genericOAuth.logoutConfirm.title', { name: provider.name }),- description: t('settings.providers.genericOAuth.logoutConfirm.description', {- name: provider.name,- }),- confirmText: t('settings.providers.genericOAuth.logoutConfirm.confirm'),- cancelText: t('settings.providers.genericOAuth.logoutConfirm.cancel'),- });- if (!confirmed) return;- setBusy(true);try {- await window.electronAPI.maker.providerOAuthLogout(provider.id);+ const scope = await window.electronAPI.maker.listProviders();+ const confirmed = await confirm({+ title: t('settings.providers.genericOAuth.logoutConfirm.title', { name: provider.name }),+ description: t('settings.providers.genericOAuth.logoutConfirm.description', {+ name: provider.name,+ }),+ confirmText: t('settings.providers.genericOAuth.logoutConfirm.confirm'),+ cancelText: t('settings.providers.genericOAuth.logoutConfirm.cancel'),+ });+ if (!confirmed) return;+ setBusy(true);+ if (!(await confirmProviderChange(options => disconnectProvider(provider, scope, options)))) return;toast.success(t('settings.providers.genericOAuth.toast.loggedOut', { name: provider.name }));onChanged();} catch {@@ -838,7 +1055,7 @@ function GenericOAuthHeader({} finally {setBusy(false);}- }, [confirm, onChanged, provider.id, provider.name, t]);+ }, [confirm, confirmProviderChange, onChanged, provider, t]);const reconnectRequired = provider.openAiAccount?.reconnectRequired === true;const status = {@@ -892,7 +1109,12 @@ function GenericOAuthHeader({.filter(Boolean).join(' · '): provider.subscriptionAccount- ? [t('settings.providers.openai.accountSource.oauth'), provider.subscriptionAccount.identity].filter(Boolean).join(' · ')+ ? [+ t('settings.providers.openai.accountSource.oauth'),+ provider.subscriptionAccount.identity,+ ]+ .filter(Boolean)+ .join(' · '): t('settings.providers.genericOAuth.subtitle')}status={status}@@ -961,18 +1183,21 @@ function BuiltinApiKeyHeader({}, [draftKey, onChanged, provider.id, provider.name, t]);const handleDisconnect = useCallback(async () => {- const confirmed = await confirm({- title: t('settings.providers.builtinApiKey.disconnectConfirm.title', { name: provider.name }),- description: t('settings.providers.builtinApiKey.disconnectConfirm.description', {- name: provider.name,- }),- confirmText: t('settings.providers.builtinApiKey.disconnectConfirm.confirm'),- cancelText: t('settings.providers.builtinApiKey.disconnectConfirm.cancel'),- });- if (!confirmed) return;- setBusy(true);try {- await window.electronAPI.builtinApiKeyRemove(provider.id);+ const scope = await window.electronAPI.maker.listProviders();+ const confirmed = await confirm({+ title: t('settings.providers.builtinApiKey.disconnectConfirm.title', {+ name: provider.name,+ }),+ description: t('settings.providers.builtinApiKey.disconnectConfirm.description', {+ name: provider.name,+ }),+ confirmText: t('settings.providers.builtinApiKey.disconnectConfirm.confirm'),+ cancelText: t('settings.providers.builtinApiKey.disconnectConfirm.cancel'),+ });+ if (!confirmed) return;+ setBusy(true);+ if (provider) await disconnectProvider(provider, scope);toast.success(t('settings.providers.builtinApiKey.toast.disconnected', { name: provider.name }),);@@ -1039,7 +1264,7 @@ function BuiltinApiKeyHeader({label: t(provider.connected? 'settings.providers.pill.configured'- : 'settings.providers.pill.disconnected',+ : 'settings.providers.pill.unconfigured',),}}primaryAction={primaryAction}@@ -1156,7 +1381,7 @@ function XdGatewayHeader({} finally {setRotating(false);}- }, [confirm, onChanged, t]);+ }, [confirm, provider, onChanged, t]);const maskedKey = useMemo(() => maskKey(hasSavedKey ? key : ''), [hasSavedKey, key]);@@ -1399,7 +1624,7 @@ function OllamaHeader({ provider, onDelete }: { provider: ProviderView; onDeletereturn (<DetailHeadericon={providerIcon(provider, 18)}- title={t('settings.providers.local.title')}+ title={provider.name || t('settings.providers.local.title')}subtitle={t('settings.providers.local.subtitle')}status={{kind: provider.connected ? 'connected' : 'neutral',@@ -1428,6 +1653,32 @@ function CustomProviderHeader({onChanged: () => void;}) {const { t } = useTranslation();+ const { confirm } = useConfirmDialog();+ const confirmProviderChange = useProviderChangeConfirmation();+ const [disconnecting, setDisconnecting] = useState(false);+ const disconnect = async () => {+ try {+ const scope = await window.electronAPI.maker.listProviders();+ if (+ !(await confirm({+ title: t('settings.providers.genericOAuth.logoutConfirm.title', { name: provider.name }),+ description: t('settings.providers.genericOAuth.logoutConfirm.description', {+ name: provider.name,+ }),+ confirmText: t('settings.providers.button.disconnect'),+ cancelText: t('settings.providers.custom.cancel'),+ }))+ )+ return;+ setDisconnecting(true);+ if (!(await confirmProviderChange(options => disconnectProvider(provider, scope, options)))) return;+ } catch {+ toast.error(t('settings.providers.genericOAuth.toast.logoutFailed', { name: provider.name }));+ } finally {+ setDisconnecting(false);+ onChanged();+ }+ };const isOAuth =provider.auth.method === 'oauth' && (!!provider.auth.oauth || !!provider.auth.native);if (isOAuth)@@ -1451,13 +1702,19 @@ function CustomProviderHeader({label: t(provider.connected? 'settings.providers.pill.configured'- : 'settings.providers.pill.disconnected',+ : 'settings.providers.pill.unconfigured',),}}primaryAction={!provider.connected? { label: t('settings.providers.custom.editAria'), onClick: onEdit }- : undefined+ : provider.auth.method === 'apiKey'+ ? {+ label: t('settings.providers.button.disconnect'),+ onClick: () => void disconnect(),+ disabled: disconnecting,+ }+ : undefined}editAction={{ label: t('settings.providers.custom.editAria'), onClick: onEdit }}deleteAction={{ label: t('settings.providers.custom.deleteAria'), onClick: onDelete }}@@ -1723,6 +1980,7 @@ export function ProvidersSection() {const signInToCindy = useSignInToCindy();const { dataOwnerId } = useAuth();const { confirm } = useConfirmDialog();+ const confirmProviderChange = useProviderChangeConfirmation();const { providers, providerOrder, ownerGeneration, loading, refetch } = useProviders();// OpenAI 的 reconnect-required 是 useCodexAuth 独有状态(目录 connected 此时为 false):// 该状态下 OpenAI 行必须留在左栏,否则「重新连接」入口不可达,用户被迫从向导重发现。@@ -1821,6 +2079,7 @@ export function ProvidersSection() {const visibleProviders = useMemo(() => {const rows: ProviderView[] = [];for (const p of providers) {+ if (p.removed) continue;if (p.source === 'builtin') {// reconnect-required 视同占行:凭证失效 ≠ 用户断开,重连入口必须保留。// OpenAI 图像 key 与 ChatGPT OAuth 两套凭证解耦:imageModels 已声明时,@@ -1829,6 +2088,7 @@ export function ProvidersSection() {if (p.id === 'xd' ||p.connected ||+ p.removed === false ||(p.id === 'openai' && openaiReconnectRequired) ||openaiHasImageCap) {@@ -1986,7 +2246,7 @@ export function ProvidersSection() {.map((d) => ({ detection: d, provider: byId.get(d.providerId) })).filter((s): s is { detection: LocalCliDetection; provider: ProviderView } =>- !!s.provider && !s.provider.connected,+ !!s.provider && !s.provider.connected && !s.provider.removed,);}, [detections, byId, listProviders]);@@ -2070,34 +2330,36 @@ export function ProvidersSection() {const handleDelete = useCallback(async (p: ProviderView) => {- const ok = await confirm({- presentation: 'standard',- title: t('settings.providers.custom.deleteConfirm.title'),- description: t('settings.providers.custom.deleteConfirm.description', { name: p.name }),- confirmText: t('settings.providers.custom.deleteConfirm.confirm'),- cancelText: t('settings.providers.custom.deleteConfirm.cancel'),- });- if (!ok) return;try {- await deleteCustomProvider(p.id);+ const scope = await window.electronAPI.maker.listProviders();+ const ok = await confirm({+ presentation: 'standard',+ title: t('settings.providers.custom.deleteConfirm.title'),+ description: t('settings.providers.custom.deleteConfirm.description', { name: p.name }),+ confirmText: t('settings.providers.custom.deleteConfirm.confirm'),+ cancelText: t('settings.providers.custom.deleteConfirm.cancel'),+ });+ if (!ok) return;+ if (!(await confirmProviderChange(options => deleteCustomProvider(p.id, scope, options)))) return;toast.success(t('settings.providers.custom.toast.deleted'));} catch {toast.error(t('settings.providers.custom.toast.deleteFailed'));}},- [confirm, t],+ [confirm, confirmProviderChange, t],);const handleDeleteOllama = useCallback(async () => {- const ok = await confirm({- title: t('settings.providers.local.deleteConfirmTitle'),- description: t('settings.providers.local.deleteConfirmBody'),- confirmText: t('settings.providers.custom.deleteConfirm.confirm'),- cancelText: t('settings.providers.custom.deleteConfirm.cancel'),- });- if (!ok) return;try {- await deleteCustomProvider(MANAGED_OLLAMA_PROVIDER_ID);+ const scope = await window.electronAPI.maker.listProviders();+ const ok = await confirm({+ title: t('settings.providers.local.deleteConfirmTitle'),+ description: t('settings.providers.local.deleteConfirmBody'),+ confirmText: t('settings.providers.custom.deleteConfirm.confirm'),+ cancelText: t('settings.providers.custom.deleteConfirm.cancel'),+ });+ if (!ok) return;+ await deleteCustomProvider(MANAGED_OLLAMA_PROVIDER_ID, scope);toast.success(t('settings.providers.custom.toast.deleted'));} catch {toast.error(t('settings.providers.custom.toast.deleteFailed'));@@ -2227,12 +2489,14 @@ export function ProvidersSection() {if (p.source === 'builtin' &&p.auth.method === 'apiKey' &&- (PROVIDER_SECRET_IDS as readonly string[]).includes(p.id)+ isBuiltinApiKeyProviderId(p.id)) {return <BuiltinApiKeyHeader key={p.id} provider={p} onChanged={refetch} />;}- if (p.source === 'builtin')- return <GenericOAuthHeader key={p.id} provider={p} onChanged={refetch} />;+ if (p.source === 'builtin') {+ if (supportsBuiltinConnectionManagement(p)) return <GenericOAuthHeader key={p.id} provider={p} onChanged={refetch} />;+ return <DetailHeader icon={providerIcon(p, 18)} title={p.name} subtitle={providerSubtitleForDisplay(p, '')} provider={p} />;+ }if (p.id === MANAGED_OLLAMA_PROVIDER_ID) {return <OllamaHeader provider={p} onDelete={() => void handleDeleteOllama()} />;}diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsxindex 09b83a6963..3f9ebc08a2 100644--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx@@ -883,7 +883,7 @@ export function TodaySpendChip({providerId ?? 'openai',);// xAI 限流快照同为本机 main 抓的 —— 远程会话(SSH / device-link)同样抑制,回落价值估算。- const xaiRateLimit = useXaiRateLimit(usesXaiQuotaForm && !isAnyRemoteSession && (!providerId || providerId === 'xai'));+ const xaiRateLimit = useXaiRateLimit(usesXaiQuotaForm && !isAnyRemoteSession, providerId ?? 'xai');const xaiSubscriptionUsage = useXaiSubscriptionUsage(usesXaiQuotaForm && !isAnyRemoteSession, providerId ?? 'xai');// 只有实际 Gateway 会话读取同一把 XD key 的 LiteLLM quota。订阅与自定义供应商// 均只展示各自的额度/本地会话统计,不读取 Model Access 账号配额。diff --git a/apps/desktop/src/renderer/hooks/__tests__/useCodexAuth.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useCodexAuth.test.tsindex ffd768ffd9..525caa2cdb 100644--- a/apps/desktop/src/renderer/hooks/__tests__/useCodexAuth.test.ts+++ b/apps/desktop/src/renderer/hooks/__tests__/useCodexAuth.test.ts@@ -157,7 +157,7 @@ describe('useCodexAuth lifecycle', () => {expect(result.current.state).toEqual({ kind: 'unauthenticated' });});- it('blocks Dev logout without hiding the shared OpenAI login', async () => {+ it('disconnects Cindy in Dev while retaining the browser login write guard', async () => {const auth = installAuthApi(async () => undefined);auth.getState.mockResolvedValueOnce({authenticated: true,@@ -176,9 +176,9 @@ describe('useCodexAuth lifecycle', () => {await act(async () => {await result.current.logout();});- expect(auth.logout).not.toHaveBeenCalled();+ expect(auth.logout).toHaveBeenCalledWith('codex');expect(result.current.state).toMatchObject({- kind: 'authenticated',+ kind: 'unauthenticated',oauthWritesBlocked: true,});@@ -193,6 +193,18 @@ describe('useCodexAuth lifecycle', () => {});await expect(result.current.triggerLogin()).resolves.toBe('blocked');expect(auth.triggerLogin).not.toHaveBeenCalled();+ auth.triggerLogin.mockResolvedValueOnce({+ authenticated: true,+ authSource: 'oauth',+ credentialScope: 'system-shared',+ });+ await act(async () => {+ await expect(result.current.triggerLogin('local')).resolves.toBe('authenticated');+ });+ expect(auth.triggerLogin).toHaveBeenCalledWith(+ 'codex',+ expect.objectContaining({ mode: 'local' }),+ );});it('refreshes to disconnected when cleanup fails after the marker committed', async () => {diff --git a/apps/desktop/src/renderer/hooks/codexAuthLogin.ts b/apps/desktop/src/renderer/hooks/codexAuthLogin.tsindex 87c0a20a69..790421851b 100644--- a/apps/desktop/src/renderer/hooks/codexAuthLogin.ts+++ b/apps/desktop/src/renderer/hooks/codexAuthLogin.ts@@ -27,7 +27,7 @@ export type CodexLoginResult = {type CodexLoginStartedListener = () => void;type PendingCodexLogin = {- mode: 'browser' | 'device-code';+ mode: 'browser' | 'device-code' | 'local';ownerId: string;promise: Promise<CodexLoginResult>;};@@ -91,12 +91,12 @@ export function onCodexLoginStarted(listener: CodexLoginStartedListener): () =>}function invokeCodexLogin(- mode: 'browser' | 'device-code',+ mode: 'browser' | 'device-code' | 'local',ownerId: string,): Promise<CodexLoginResult> {return window.electronAPI.maker.auth.triggerLogin('codex',- mode === 'device-code' ? { mode, ownerId } : { ownerId },+ mode === 'browser' ? { ownerId } : { mode, ownerId },);}@@ -106,7 +106,9 @@ function invokeCodexLogin(* main adapter 也会复用正在运行的 CLI 登录,但在 renderer 先合并可以避免设置页、* 会话横幅等入口重复发 IPC,并避免同一结果重复执行 main handler 的刷新与广播收尾。*/-function getOrStartCodexLogin(mode: 'browser' | 'device-code' = 'browser'): PendingCodexLogin {+function getOrStartCodexLogin(+ mode: 'browser' | 'device-code' | 'local' = 'browser',+): PendingCodexLogin {if (pendingCodexLogin) {if (pendingCodexLogin.mode === mode) return pendingCodexLogin;@@ -146,7 +148,7 @@ function getOrStartCodexLogin(mode: 'browser' | 'device-code' = 'browser'): Pend}export function triggerCodexLoginOnce(- mode: 'browser' | 'device-code' = 'browser',+ mode: 'browser' | 'device-code' | 'local' = 'browser',): Promise<CodexLoginResult> {return getOrStartCodexLogin(mode).promise;}@@ -157,7 +159,9 @@ export function triggerCodexLoginOnce(* 同一 renderer 内多个显式入口会复用一个登录 promise;组件卸载时只有最后一个 owner* 才能取消它。lease 绑定具体 promise,因此旧模式的 cleanup 不会误杀已排队的新模式。*/-export function acquireCodexLogin(mode: 'browser' | 'device-code' = 'browser'): CodexLoginLease {+export function acquireCodexLogin(+ mode: 'browser' | 'device-code' | 'local' = 'browser',+): CodexLoginLease {const pending = getOrStartCodexLogin(mode);const { ownerId, promise } = pending;let ownership = loginOwnership.get(promise);diff --git a/apps/desktop/src/renderer/hooks/useCodexAuth.ts b/apps/desktop/src/renderer/hooks/useCodexAuth.tsindex 28570503af..f9ffa9fd1f 100644--- a/apps/desktop/src/renderer/hooks/useCodexAuth.ts+++ b/apps/desktop/src/renderer/hooks/useCodexAuth.ts@@ -25,7 +25,7 @@ export type CodexUiState = (| { kind: 'unauthenticated' }| {kind: 'login-pending';- mode: 'browser' | 'device-code';+ mode: 'browser' | 'device-code' | 'local';deviceCode?: { verificationUrl: string; userCode: string };}| {@@ -73,7 +73,7 @@ type CodexAuthMachineEvent =| { type: 'state-changed'; result: CodexLoginResult }| {type: 'login-pending';- mode: 'browser' | 'device-code';+ mode: 'browser' | 'device-code' | 'local';deviceCode?: { verificationUrl: string; userCode: string };}| { type: 'login-progress-error'; message: string }@@ -434,7 +434,7 @@ export function verifyCodexAuthRecovery(* 观察型 useCodexAuth 实例不会获得 lease,因此卸载时不会取消别的窗口发起的登录。*/export function useOwnedCodexLogin(): (- mode?: 'browser' | 'device-code',+ mode?: 'browser' | 'device-code' | 'local',) => Promise<CodexLoginResult> {const leasesRef = useRef(new Set<CodexLoginLease>());const mountedRef = useRef(true);@@ -450,7 +450,7 @@ export function useOwnedCodexLogin(): (};}, []);- return useCallback((mode: 'browser' | 'device-code' = 'browser') => {+ return useCallback((mode: 'browser' | 'device-code' | 'local' = 'browser') => {if (!mountedRef.current) {return Promise.resolve({authenticated: false,@@ -777,10 +777,10 @@ export function useCodexAuth(options?: {}, [enabled, machine.ui.kind, refresh]);const triggerLogin = useCallback(- async (mode: 'browser' | 'device-code' = 'browser'): Promise<CodexLoginOutcome> => {+ async (mode: 'browser' | 'device-code' | 'local' = 'browser'): Promise<CodexLoginOutcome> => {const observerEpoch = observerEpochRef.current;if (!isObserverActive(observerEpoch)) return 'cancelled';- if (machineRef.current.ui.oauthWritesBlocked) return 'blocked';+ if (mode !== 'local' && machineRef.current.ui.oauthWritesBlocked) return 'blocked';transition({ type: 'login-pending', mode });try {const result = await triggerOwnedLogin(mode);@@ -838,10 +838,6 @@ export function useCodexAuth(options?: {}, [transition, verifyRecoveredState]);const logout = useCallback(async () => {- // Dev read-only means the shared OpenAI login remains usable but cannot be- // disconnected from this process. Avoid sending a no-op logout to Main and- // then incorrectly projecting the local UI as unauthenticated.- if (machineRef.current.ui.oauthWritesBlocked) return;invalidatePendingCodexLogin();try {await window.electronAPI.maker.auth.logout(AGENT_KIND);diff --git a/apps/desktop/src/renderer/hooks/useXaiRateLimit.ts b/apps/desktop/src/renderer/hooks/useXaiRateLimit.tsindex acb20c3155..7d07cd5298 100644--- a/apps/desktop/src/renderer/hooks/useXaiRateLimit.ts+++ b/apps/desktop/src/renderer/hooks/useXaiRateLimit.ts@@ -18,10 +18,20 @@ import type { XaiRateLimitSnapshot } from '../../shared/xaiRateLimit';import { createSubscriptionUsageCache } from './subscriptionUsageCache';export type { XaiRateLimitSnapshot };-// Push-only: keep the upstream RPM/TPM lifetime; no polling or persistence.-const usageCache = createSubscriptionUsageCache<XaiRateLimitSnapshot>(() => ({- subscribe: window.electronAPI?.maker?.usage?.onXaiRateLimitChanged,-}));-export function useXaiRateLimit(enabled: boolean): XaiRateLimitSnapshot | null {- return usageCache.useSnapshot(enabled);+// Push-only, scoped exactly like the subscription quota cache; no polling or persistence.+const caches = new Map<+ string,+ ReturnType<typeof createSubscriptionUsageCache<XaiRateLimitSnapshot>>+>();+export function useXaiRateLimit(enabled: boolean, providerId = 'xai'): XaiRateLimitSnapshot | null {+ let cache = caches.get(providerId);+ if (!cache) {+ cache = createSubscriptionUsageCache<XaiRateLimitSnapshot>(() => ({+ subscribe: window.electronAPI?.maker?.usage?.onXaiRateLimitChanged+ ? (cb) => window.electronAPI.maker.usage.onXaiRateLimitChanged(cb, providerId)+ : undefined,+ }));+ caches.set(providerId, cache);+ }+ return cache.useSnapshot(enabled);}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 4d3b195fae..ccf9c3a1fe 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1395,7 +1395,7 @@"codex": {"logoutConfirm": {"title": "Disconnect ChatGPT Account?",- "description": "{{appName}} will stop using this ChatGPT subscription in Codex and Claude. Your system Codex CLI sign-in stays unchanged.",+ "description": "After disconnecting, {{appName}} will no longer be able to use this ChatGPT subscription.","confirm": "Disconnect ChatGPT","cancel": "Cancel"},@@ -1410,7 +1410,7 @@"description": "When on, Codex uses the Cindy AI key from Model Providers instead of your subscription.","noKey": "No Cindy AI key configured — connect Cindy AI in Model Providers","noKeyDialog": {- "title": "API Key not configured",+ "title": "API key not configured","description": "API mode reuses the Cindy AI key, which is not set yet. Connect Cindy AI in Model Providers to enable API mode."},"badge": {@@ -1428,25 +1428,25 @@"xai": {"logoutConfirm": {"title": "Disconnect xAI (SuperGrok)?",- "description": "Disconnecting clears the xAI credentials stored on this machine; sessions using Grok models won't work until you re-authorize.",+ "description": "Cindy will no longer use this Grok subscription.","confirm": "Disconnect","cancel": "Cancel"},"toast": {- "loggedIn": "Signed in to xAI (SuperGrok)",- "loggedOut": "Disconnected from xAI",- "loginFailed": "Authorization failed, please retry",- "logoutFailed": "Disconnect failed, please retry"+ "loggedIn": "Signed in to Grok",+ "loggedOut": "Disconnected Grok",+ "loginFailed": "Could not sign in to Grok. Try again.",+ "logoutFailed": "Could not disconnect Grok. Try again."}},"claude": {"subtitle": {- "authorizing": "Authorizing (browser)…",- "authorized": "Claude.ai subscription · Authorized",- "unauthorized": "Not authorized (click Authorize to sign in to Claude.ai)"+ "authorizing": "Signing in…",+ "authorized": "Claude subscription · Connected",+ "unauthorized": "Not connected"},"button": {- "authorize": "Authorize"+ "authorize": "Sign in"},"badge": {"api": "● API",@@ -1454,17 +1454,17 @@},"logoutConfirm": {"title": "Disconnect Claude.ai subscription?",- "description": "Disconnecting clears this machine's Claude Code login credential (your local `claude` CLI is signed out too); if you're currently in subscription mode it falls back to Cindy AI. You'll need to authorize again to restore it.",+ "description": "Cindy will no longer use this Claude subscription.","confirm": "Disconnect","cancel": "Cancel"},"toast": {- "loggedIn": "Signed in to Claude.ai subscription",- "loggedOut": "Claude.ai subscription disconnected",- "loginFailed": "Authorization failed, please retry",- "logoutFailed": "Disconnect failed, please retry",+ "loggedIn": "Signed in to Claude",+ "loggedOut": "Disconnected Claude",+ "loginFailed": "Could not sign in to Claude. Try again.",+ "logoutFailed": "Could not disconnect Claude. Try again.","notSubscription": "This account has no Claude subscription (Pro/Max); subscription mode is unavailable",- "needAuth": "Authorize and sign in to Claude.ai first"+ "needAuth": "Sign in to Claude first"},"apiMode": {"label": "API mode (via Cindy AI)",@@ -1472,7 +1472,7 @@"toggleAria": "Toggle Claude API mode","sharedKeyWarning": "Shares one key with Cindy AI — with API mode off, non-Claude models still need Cindy AI","noKeyDialog": {- "title": "No API Key configured",+ "title": "No API key configured","description": "With API mode off (subscription), non-Claude models (gpt / deepseek, etc.) still reuse the Cindy AI key, which is not configured yet. Connect Cindy AI in Model Providers to continue."},"toast": {@@ -1496,11 +1496,12 @@"disconnected": "Not connected","connecting": "Connecting…","rename": "Rename",- "suspended": "Disabled"+ "suspended": "Disabled",+ "unconfigured": "Not configured"},"button": {- "authorize": "Authorize",- "logout": "Sign out",+ "authorize": "Sign in",+ "logout": "Disconnect","connect": "Connect","disconnect": "Disconnect","cancel": "Cancel",@@ -1517,13 +1518,13 @@"title": "OpenAI","subtitle": "Connect one ChatGPT account for both Codex and Claude","modelLabel": "GPT models",- "reconnectRequired": "Reconnect Needed",- "connect": "Connect ChatGPT",- "reconnect": "Reconnect ChatGPT",- "cancelConnect": "Cancel Connection",+ "reconnectRequired": "Sign in again",+ "connect": "Use local Codex account",+ "reconnect": "Sign in again",+ "cancelConnect": "Cancel","accountSource": {"local": "Local Codex account",- "oauth": "Independently signed-in account",+ "oauth": "Separate account","unknown": "Existing OpenAI connection"},"useLocalAccount": "Use local Codex account",@@ -1593,19 +1594,19 @@},"custom": {"tag": "Custom",- "editAria": "Edit",+ "editAria": "Edit connection settings","deleteAria": "Delete","save": "Save","cancel": "Cancel","dialog": {"createTitle": "Add a custom provider",- "editTitle": "Edit custom provider",+ "editTitle": "Edit connection settings","desc": "Configure an OpenAI / Anthropic-compatible provider."},"imageGenerationReload": {"title": "Reload Codex",- "description": "Saving this image generation configuration requires reloading Codex and will interrupt the Codex tasks currently in progress.",- "interrupt": "Save and stop",+ "description": "Applying this change requires reloading Codex and will interrupt the Codex tasks currently in progress.",+ "interrupt": "Continue and stop tasks","cancel": "Cancel","close": "Close"},@@ -1699,8 +1700,8 @@"deleteFailed": "Delete failed"},"deleteConfirm": {- "title": "Delete custom provider?",- "description": "This removes the config for \"{{name}}\" and its locally stored key. Sessions using it fall back to the default source.",+ "title": "Delete provider?",+ "description": "Cindy will no longer use “{{name}}”. Message history is kept, and you can add the provider again later.","confirm": "Delete","cancel": "Cancel"},@@ -1731,10 +1732,10 @@"authMode": {"label": "Authentication","apiKey": "API key",- "oauth": "OAuth subscription",+ "oauth": "Subscription account","none": "No authentication","noneHelp": "For local or trusted self-hosted proxies. Cindy removes the CLI's subscription credentials and account headers before forwarding requests.",- "oauthHelp": "For providers offering OAuth sign-in. Choose a browser callback or device code flow, then authorize from the provider list. Credentials are stored encrypted on this device only.",+ "oauthHelp": "For providers that support OAuth sign-in. Choose a browser or device-code flow, then sign in from the provider list after saving. Credentials stay on this device.","flowLabel": "OAuth flow","flow": {"authorization-code": "Browser callback (PKCE)",@@ -1747,7 +1748,7 @@"clientId": "Client ID","scopes": "Scopes (space-separated)"},- "modelsAutoNote": "The model list is fetched automatically after you authorize — no manual entry needed."+ "modelsAutoNote": "Available models are discovered after sign-in"},"advanced": {"label": "Advanced (models / headers)"@@ -1976,24 +1977,24 @@}},"genericOAuth": {- "subtitle": "Subscription sign-in (OAuth)",+ "subtitle": "Subscription account","toast": {"loggedIn": "Signed in to {{name}}",- "loginFailed": "Failed to sign in to {{name}}. Please try again",- "loggedOut": "Signed out of {{name}}",- "logoutFailed": "Failed to sign out of {{name}}"+ "loginFailed": "Could not sign in to {{name}}. Try again.",+ "loggedOut": "Disconnected {{name}}",+ "logoutFailed": "Could not disconnect {{name}}. Try again."},"logoutConfirm": {- "title": "Sign out of {{name}}?",- "description": "Models from this source will be unavailable after signing out. You can sign in again anytime.",- "confirm": "Sign out",+ "title": "Disconnect “{{name}}”?",+ "description": "Cindy will no longer use “{{name}}”. The provider is kept so you can reconnect later.",+ "confirm": "Disconnect","cancel": "Cancel"}},"addProvider": "Add provider","detail": {"singleAgentNote": "{{agent}} only",- "emptyModels": "Models are discovered automatically after you authorize",+ "emptyModels": "Available models are discovered after sign-in","emptyList": "Click \"Add provider\" below to connect your first model source","emptyModelsConnected": "Connected — discovering available models. If it stays empty, try again shortly.","discoveryFailed": {@@ -2001,7 +2002,7 @@"timeout": "Connection to this provider timed out, so its model list is unavailable. Check your network, then retry.","upstream": "This provider can't return its model list right now. Try again later.","regionBlocked": "This provider doesn't offer service in your current region, so its model list is unavailable. You can use a different provider instead.",- "unauthorized": "This provider rejected the current authorization, so its model list is unavailable. Disconnect and connect again.",+ "unauthorized": "This provider rejected the current login or API key, so its model list is unavailable. Sign in again or update the API key.","forbidden": "This provider refused the request, so its model list is unavailable. If you're on a proxy or VPN, switch exits and retry.","rejected": "This provider refused the request, so its model list is unavailable. Try again later, or use a different provider.","empty": "This provider returned no usable models. Check your account's access, then retry."@@ -2011,7 +2012,7 @@"timeout": "Connection to this provider timed out. The list below is from the last successful refresh. Check your network, then retry.","upstream": "This provider can't return its model list right now. The list below is from the last successful refresh. Try again later.","regionBlocked": "This provider doesn't offer service in your current region. The list below is from the last successful refresh. You can use a different provider instead.",- "unauthorized": "This provider rejected the current authorization. The list below is from the last successful refresh. Disconnect and connect again.",+ "unauthorized": "This provider rejected the current login or API key. The last model list is shown below. Sign in again or update the API key.","forbidden": "This provider refused the request. The list below is from the last successful refresh. If you're on a proxy or VPN, switch exits and retry.","rejected": "This provider refused the request. The list below is from the last successful refresh. Try again later, or use a different provider.","empty": "This provider returned no usable models this time. The list below is from the last successful refresh. Check your account's access, then retry."@@ -2021,8 +2022,8 @@},"detect": {"groupLabel": "Detected on this device",- "action": "Authorize",- "hintLoggedIn": "{{cli}} is signed in on this device — authorize to connect",+ "action": "Use local account",+ "hintLoggedIn": "{{cli}} is signed in. You can use the local account.","hintInstalled": "{{cli}} is installed on this device"},"wizard": {@@ -2035,21 +2036,21 @@"searchPlaceholder": "Search providers…","groupRecommend": "Recommended","groupDetectedLocal": "Detected on this computer",- "groupSubscription": "Subscription sign-in",+ "groupSubscription": "Subscription account","recommendReason": {"has-local-models": "Models already on this computer","machine-capable": "This computer can run a local model",- "subscription": "Subscription sign-in"+ "subscription": "Subscription account"},"groupApiKey": "API and self-hosted proxies · presets update with the catalog","groupCustom": "Custom",- "metaOAuth": "Subscription (OAuth)",+ "metaOAuth": "Subscription account","metaApiKey": "API key","metaNoAuth": "Local / self-hosted · no authentication","customTitle": "Custom endpoint","customMeta": "Connect any OpenAI / Anthropic compatible source",- "pickHint": "The sign-in method is defined by each provider; OAuth endpoints and base URLs come from presets — nothing to fill in by hand.",- "oauthDesc": "Authorize your subscription in the browser — no API key needed",+ "pickHint": "Choose the account or service to connect.",+ "oauthDesc": "Sign in through your browser. No API key required.","deviceOAuthDesc": "Authorize on the provider's verification page with a one-time device code","authorizeInBrowser": "Authorize in browser","authorizeWithDeviceCode": "Use device code",@@ -2061,8 +2062,8 @@"deviceCodeCopied": "Device code copied","deviceCodeCopyFailed": "Couldn't copy the device code","verificationPageOpenFailed": "Couldn't open the verification page",- "authorizedToast": "Connected {{name}}",- "authorizeFailed": "Failed to authorize {{name}}. Please try again",+ "authorizedToast": "Signed in to {{name}}",+ "authorizeFailed": "Could not sign in to {{name}}. Try again.","nameLabel": "Display name","onlyAgentNote": "This provider only supports {{agent}}","endpointLabel": "{{agent}} base URL",@@ -2085,7 +2086,7 @@"finish": "Finish","cancel": "Cancel","useApiKey": "API key connection",- "metaOAuthOrApi": "Subscription (OAuth) · API key",+ "metaOAuthOrApi": "Subscription account · API key","builtinApiKey": {"subtitle": "Connect with your own API key","note": "This source provides image generation models and does not join chats. The API key is stored only on this device (encrypted by the system keychain) and never uploaded."@@ -2221,7 +2222,7 @@},"builtinApiKey": {"subtitle": "API key connection",- "replaceKey": "Replace key",+ "replaceKey": "Edit connection settings","saveKey": "Save","keyPlaceholder": "Paste API key","toast": {@@ -2232,7 +2233,7 @@},"disconnectConfirm": {"title": "Disconnect {{name}}?",- "description": "Disconnecting deletes the API key stored on this device. Models from this source become unavailable; you can add it again anytime.",+ "description": "The API key saved for this connection will be cleared. The provider is kept; enter an API key to use it again.","confirm": "Disconnect","cancel": "Cancel"}@@ -2247,6 +2248,10 @@"codexPlanFallback": "ChatGPT subscription","codexSecondary": "Secondary window: {{percent}}% remaining","codexResetCredits": "{{count}} limit reset credits"+ },+ "localAccount": {+ "useClaude": "Use local Claude Code account",+ "unavailable": "No local sign-in is available. Sign in to the source app or add a separate account."}},"experimental": {diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 9071bf34a3..4e135bea8f 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1410,7 +1410,7 @@"description": "オンにすると Codex はサブスクではなく、モデルプロバイダーの Cindy AI Key を使用します。","noKey": "Cindy AI Key が未設定です。モデルプロバイダーで Cindy AI を接続してください","noKeyDialog": {- "title": "API Key が未設定です",+ "title": "API key が未設定です","description": "API モードは Cindy AI Key を再利用しますが、まだ設定されていません。モデルプロバイダーで Cindy AI を接続すると有効化できます。"},"badge": {@@ -1428,25 +1428,25 @@"xai": {"logoutConfirm": {"title": "xAI(SuperGrok)を切断しますか?",- "description": "切断するとこの端末に保存された xAI の認証情報が削除されます。再認証するまで Grok モデルを選択したセッションは利用できません。",- "confirm": "切断",+ "description": "Cindy はこの Grok サブスクリプションを使用できなくなります。",+ "confirm": "接続を解除","cancel": "キャンセル"},"toast": {- "loggedIn": "xAI(SuperGrok)にログインしました",- "loggedOut": "xAI を切断しました",- "loginFailed": "認証に失敗しました。再試行してください",- "logoutFailed": "切断に失敗しました。再試行してください"+ "loggedIn": "Grok にログインしました",+ "loggedOut": "Grok の接続を解除しました",+ "loginFailed": "Grok にログインできませんでした。再試行してください。",+ "logoutFailed": "Grok の接続を解除できませんでした。再試行してください。"}},"claude": {"subtitle": {- "authorizing": "認証中(ブラウザ)…",- "authorized": "Claude.ai サブスクリプション · 認証済み",- "unauthorized": "未認証(「認証」をクリックして Claude.ai にログイン)"+ "authorizing": "ログイン中…",+ "authorized": "Claude サブスクリプション · 接続済み",+ "unauthorized": "未接続"},"button": {- "authorize": "認証"+ "authorize": "ログイン"},"badge": {"api": "● API",@@ -1454,17 +1454,17 @@},"logoutConfirm": {"title": "Claude.ai サブスクリプションを切断しますか?",- "description": "切断するとこの端末の Claude Code のログイン資格情報が削除されます(ローカルの `claude` CLI もログアウトされます)。サブスクリプションモード中の場合は Cindy AI に自動的に戻ります。復元するには再度認証が必要です。",- "confirm": "切断",+ "description": "Cindy はこの Claude サブスクリプションを使用できなくなります。",+ "confirm": "接続を解除","cancel": "キャンセル"},"toast": {- "loggedIn": "Claude.ai サブスクリプションにログインしました",- "loggedOut": "Claude.ai サブスクリプションを切断しました",- "loginFailed": "認証に失敗しました。再試行してください",- "logoutFailed": "切断に失敗しました。再試行してください",+ "loggedIn": "Claude にログインしました",+ "loggedOut": "Claude の接続を解除しました",+ "loginFailed": "Claude にログインできませんでした。再試行してください。",+ "logoutFailed": "Claude の接続を解除できませんでした。再試行してください。","notSubscription": "このアカウントには Claude サブスクリプション(Pro/Max)がありません。サブスクリプションモードは利用できません",- "needAuth": "先に Claude.ai にログイン認証してください"+ "needAuth": "先に Claude にログインしてください"},"apiMode": {"label": "API モード(Cindy AI 経由)",@@ -1472,7 +1472,7 @@"toggleAria": "Claude API モードを切り替え","sharedKeyWarning": "Cindy AI と Key を共有 — API モードをオフにしても Claude 以外のモデルには Cindy AI が必要です","noKeyDialog": {- "title": "API Key が未設定です",+ "title": "API key が未設定です","description": "API モードをオフ(サブスクリプション)にしても、Claude 以外のモデル(gpt / deepseek など)には Cindy AI Key を再利用しますが、まだ設定されていません。モデルプロバイダーで Cindy AI を接続してください。"},"toast": {@@ -1496,11 +1496,12 @@"disconnected": "未接続","connecting": "接続中…","rename": "名前を変更",- "suspended": "無効"+ "suspended": "無効",+ "unconfigured": "未設定"},"button": {- "authorize": "認証",- "logout": "ログアウト",+ "authorize": "ログイン",+ "logout": "接続を解除","connect": "接続","disconnect": "切断","cancel": "キャンセル",@@ -1517,17 +1518,17 @@"title": "OpenAI","subtitle": "1 つの ChatGPT アカウントを Codex と Claude の両方で使用","modelLabel": "GPT モデル",- "reconnectRequired": "再接続が必要",- "connect": "ChatGPT に接続",- "reconnect": "ChatGPT に再接続",- "cancelConnect": "接続をキャンセル",+ "reconnectRequired": "再ログイン",+ "connect": "ローカル Codex アカウントを使う",+ "reconnect": "再ログイン",+ "cancelConnect": "キャンセル","accountSource": {"local": "ローカル Codex アカウント",- "oauth": "個別にログインしたアカウント",+ "oauth": "個別アカウント","unknown": "既存の OpenAI 接続"},"useLocalAccount": "ローカル Codex アカウントを使う",- "addIndependentAccount": "別のアカウントにログイン",+ "addIndependentAccount": "別のアカウントでログイン","accountSourcesDescription": "既存のローカル Codex 接続を使うか、別のアカウントにログインします。どちらも同じ機能を利用できます。","independentAccountDescription": "別途保存する ChatGPT アカウントにログインするか、API キーで接続します。","localUnavailable": "再利用できるローカル接続がありません。既存の接続のアカウントは変更されません。"@@ -1593,19 +1594,19 @@},"custom": {"tag": "カスタム",- "editAria": "編集",+ "editAria": "接続設定を編集","deleteAria": "削除","save": "保存","cancel": "キャンセル","dialog": {"createTitle": "カスタムプロバイダーを追加",- "editTitle": "カスタムプロバイダーを編集",+ "editTitle": "接続設定を編集","desc": "OpenAI / Anthropic 互換のプロバイダーを設定します。"},"imageGenerationReload": {"title": "Codex を再読み込み",- "description": "この画像生成設定を保存するには Codex の再読み込みが必要で、現在実行中の Codex タスクは中断されます。",- "interrupt": "保存して停止",+ "description": "この変更を適用するには Codex の再読み込みが必要で、現在実行中の Codex タスクは中断されます。",+ "interrupt": "続行してタスクを停止","cancel": "キャンセル","close": "閉じる"},@@ -1699,8 +1700,8 @@"deleteFailed": "削除に失敗しました"},"deleteConfirm": {- "title": "カスタムプロバイダーを削除しますか?",- "description": "「{{name}}」の設定とローカルに保存されたキーを削除します。使用中のセッションは既定のソースに戻ります。",+ "title": "プロバイダーを削除しますか?",+ "description": "Cindy は「{{name}}」を使用できなくなります。メッセージ履歴は保持され、後から再追加できます。","confirm": "削除","cancel": "キャンセル"},@@ -1731,10 +1732,10 @@"authMode": {"label": "認証方式","apiKey": "API キー",- "oauth": "OAuth サブスクリプション認証",+ "oauth": "サブスクリプションアカウント","none": "認証なし","noneHelp": "ローカルまたは信頼できるセルフホスト型プロキシ向けです。Cindy は転送前に CLI のサブスクリプション認証情報とアカウントヘッダーを削除します。",- "oauthHelp": "OAuth ログインを提供するプロバイダー向けです。ブラウザコールバックまたはデバイスコード方式を選び、保存後にプロバイダー一覧から認証します。認証情報はこのデバイスにのみ暗号化して保存されます。",+ "oauthHelp": "OAuth ログインに対応したプロバイダー向けです。ブラウザーまたはデバイスコードを選択し、保存後にプロバイダー一覧からログインします。認証情報はこのデバイスに保存されます。","flowLabel": "OAuth フロー","flow": {"authorization-code": "ブラウザコールバック(PKCE)",@@ -1747,7 +1748,7 @@"clientId": "Client ID","scopes": "Scopes(スペース区切り)"},- "modelsAutoNote": "モデル一覧は認可の完了後に自動取得されます。手動入力は不要です。"+ "modelsAutoNote": "ログイン後に利用可能なモデルを自動取得"},"advanced": {"label": "詳細設定(モデル / リクエストヘッダー)"@@ -1975,24 +1976,24 @@}},"genericOAuth": {- "subtitle": "サブスクリプション認証(OAuth)",+ "subtitle": "サブスクリプションアカウント","toast": {"loggedIn": "{{name}} にログインしました",- "loginFailed": "{{name}} へのログインに失敗しました。再試行してください",- "loggedOut": "{{name}} からログアウトしました",- "logoutFailed": "{{name}} からのログアウトに失敗しました"+ "loginFailed": "{{name}} にログインできませんでした。再試行してください。",+ "loggedOut": "{{name}} の接続を解除しました",+ "logoutFailed": "{{name}} の接続を解除できませんでした。再試行してください。"},"logoutConfirm": {- "title": "{{name}} からログアウトしますか?",- "description": "ログアウトするとこのソースのモデルは利用できなくなります。いつでも再ログインできます。",- "confirm": "ログアウト",+ "title": "「{{name}}」の接続を解除しますか?",+ "description": "Cindy は「{{name}}」を使用できなくなります。プロバイダーは保持され、後から再接続できます。",+ "confirm": "接続を解除","cancel": "キャンセル"}},"addProvider": "プロバイダーを追加","detail": {"singleAgentNote": "{{agent}} のみ対応",- "emptyModels": "認証すると利用可能なモデルが自動的に検出されます",+ "emptyModels": "ログイン後に利用可能なモデルを自動取得","emptyList": "左下の「プロバイダーを追加」から最初のモデルソースを接続してください","emptyModelsConnected": "接続済み — 利用可能なモデルを検出中です。空のままの場合は、しばらくしてから再度お試しください。","discoveryFailed": {@@ -2000,7 +2001,7 @@"timeout": "このプロバイダーへの接続がタイムアウトしたため、モデル一覧を取得できません。ネットワークを確認してから再試行してください。","upstream": "このプロバイダーは現在モデル一覧を返せません。しばらくしてから再試行してください。","regionBlocked": "このプロバイダーは現在の地域でサービスを提供していないため、モデル一覧を取得できません。別のプロバイダーをご利用ください。",- "unauthorized": "このプロバイダーが現在の認証を拒否したため、モデル一覧を取得できません。切断してから接続し直してください。",+ "unauthorized": "現在のログインまたは API key が拒否されたため、モデル一覧を取得できません。再ログインするか API key を更新してください。","forbidden": "このプロバイダーがリクエストを拒否したため、モデル一覧を取得できません。プロキシまたは VPN をご利用の場合は、出口を変えてから再試行してください。","rejected": "このプロバイダーがリクエストを拒否したため、モデル一覧を取得できません。しばらくしてから再試行するか、別のプロバイダーをご利用ください。","empty": "このプロバイダーから利用可能なモデルが返されませんでした。アカウントの権限を確認してから再試行してください。"@@ -2010,7 +2011,7 @@"timeout": "このプロバイダーへの接続がタイムアウトしました。以下は前回取得したモデル一覧です。ネットワークを確認してから再試行してください。","upstream": "このプロバイダーは現在モデル一覧を返せません。以下は前回取得した一覧です。しばらくしてから再試行してください。","regionBlocked": "このプロバイダーは現在の地域でサービスを提供していません。以下は前回取得したモデル一覧です。別のプロバイダーをご利用ください。",- "unauthorized": "このプロバイダーが現在の認証を拒否しました。以下は前回取得したモデル一覧です。切断してから接続し直してください。",+ "unauthorized": "現在のログインまたは API key が拒否されました。前回のモデル一覧を表示しています。再ログインするか API key を更新してください。","forbidden": "このプロバイダーがリクエストを拒否しました。以下は前回取得したモデル一覧です。プロキシまたは VPN をご利用の場合は、出口を変えてから再試行してください。","rejected": "このプロバイダーがリクエストを拒否しました。以下は前回取得したモデル一覧です。しばらくしてから再試行するか、別のプロバイダーをご利用ください。","empty": "今回このプロバイダーから利用可能なモデルが返されませんでした。以下は前回取得した一覧です。アカウントの権限を確認してから再試行してください。"@@ -2020,8 +2021,8 @@},"detect": {"groupLabel": "このデバイスで検出",- "action": "認証する",- "hintLoggedIn": "{{cli}} はこのデバイスでログイン済みです。認証してすぐに接続できます",+ "action": "ローカルアカウントを使用",+ "hintLoggedIn": "{{cli}} はログイン済みです。ローカルアカウントを使用できます。","hintInstalled": "このデバイスに {{cli}} がインストールされています"},"wizard": {@@ -2034,21 +2035,21 @@"searchPlaceholder": "プロバイダーを検索…","groupRecommend": "おすすめ","groupDetectedLocal": "このパソコンで検出",- "groupSubscription": "サブスクリプション認証",+ "groupSubscription": "サブスクリプションアカウント","recommendReason": {"has-local-models": "このパソコンにモデルがある","machine-capable": "このパソコンでローカルモデルを動かせる",- "subscription": "サブスクリプション認証"+ "subscription": "サブスクリプションアカウント"},"groupApiKey": "API とセルフホスト型プロキシ · プリセットはカタログと同期","groupCustom": "カスタム",- "metaOAuth": "サブスクリプション認証",- "metaApiKey": "API キー",+ "metaOAuth": "サブスクリプションアカウント",+ "metaApiKey": "API key","metaNoAuth": "ローカル / セルフホスト · 認証なし","customTitle": "カスタムエンドポイント","customMeta": "OpenAI / Anthropic 互換の任意のモデルソースを接続",- "pickHint": "認証方式はプロバイダーの定義で決まります。OAuth エンドポイントとベース URL はプリセットに含まれ、手入力は不要です。",- "oauthDesc": "ブラウザでサブスクリプション認証を完了します。API キーは不要です",+ "pickHint": "接続するアカウントまたはサービスを選択してください。",+ "oauthDesc": "ブラウザーでログインします。API key は不要です。","deviceOAuthDesc": "ワンタイムデバイスコードを使い、プロバイダーの認証ページで認証します","authorizeInBrowser": "ブラウザで認証","authorizeWithDeviceCode": "デバイスコードを使用",@@ -2060,8 +2061,8 @@"deviceCodeCopied": "デバイスコードをコピーしました","deviceCodeCopyFailed": "デバイスコードをコピーできませんでした","verificationPageOpenFailed": "認証ページを開けませんでした",- "authorizedToast": "「{{name}}」に接続しました",- "authorizeFailed": "「{{name}}」の認証に失敗しました。もう一度お試しください",+ "authorizedToast": "{{name}} にログインしました",+ "authorizeFailed": "{{name}} にログインできませんでした。再試行してください。","nameLabel": "表示名","onlyAgentNote": "このプロバイダーは {{agent}} のみ対応です","endpointLabel": "{{agent}} ベース URL",@@ -2084,7 +2085,7 @@"finish": "追加を完了","cancel": "キャンセル","useApiKey": "API キーで接続する",- "metaOAuthOrApi": "サブスク認証 · API キー",+ "metaOAuthOrApi": "サブスクリプションアカウント · API key","builtinApiKey": {"subtitle": "自分の API key で接続","note": "このソースは画像生成モデルを提供し、チャットには参加しません。API key はこの端末のみに保存され(システムキーチェーンで暗号化)、アップロードされません。"@@ -2220,7 +2221,7 @@},"builtinApiKey": {"subtitle": "API key で接続",- "replaceKey": "key を変更",+ "replaceKey": "接続設定を編集","saveKey": "保存","keyPlaceholder": "API key を貼り付け","toast": {@@ -2231,7 +2232,7 @@},"disconnectConfirm": {"title": "{{name}} を切断しますか?",- "description": "切断するとこの端末に保存された API key が削除され、このソースのモデルは利用できなくなります。いつでも再追加できます。",+ "description": "この接続の API key を消去します。プロバイダーは保持され、API key を入力すると再利用できます。","confirm": "切断","cancel": "キャンセル"}@@ -2246,6 +2247,10 @@"codexPlanFallback": "ChatGPT サブスクリプション","codexSecondary": "第2ウィンドウの残り {{percent}}%","codexResetCredits": "上限リセット券 {{count}} 枚"+ },+ "localAccount": {+ "useClaude": "ローカルの Claude Code アカウントを使用",+ "unavailable": "利用できるローカルログインがありません。元のアプリにログインするか、別のアカウントを追加してください。"}},"experimental": {diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex d2a5fce13c..58a4a0d785 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1410,7 +1410,7 @@"description": "켜면 Codex가 구독 대신 모델 제공자의 Cindy AI Key를 사용합니다.","noKey": "Cindy AI Key가 설정되지 않았습니다 — 모델 제공자에서 Cindy AI를 연결하세요","noKeyDialog": {- "title": "API Key가 설정되지 않았습니다",+ "title": "API key가 설정되지 않았습니다","description": "API 모드는 Cindy AI Key를 재사용하지만 아직 설정되지 않았습니다. 모델 제공자에서 Cindy AI를 연결하면 활성화할 수 있습니다."},"badge": {@@ -1428,25 +1428,25 @@"xai": {"logoutConfirm": {"title": "xAI(SuperGrok) 연결을 해제할까요?",- "description": "연결을 해제하면 이 기기에 저장된 xAI 인증 정보가 삭제됩니다. 다시 인증하기 전까지 Grok 모델을 선택한 세션은 사용할 수 없습니다.",+ "description": "Cindy에서 이 Grok 구독을 사용할 수 없게 됩니다.","confirm": "연결 해제","cancel": "취소"},"toast": {- "loggedIn": "xAI(SuperGrok)에 로그인했습니다",- "loggedOut": "xAI 연결을 해제했습니다",- "loginFailed": "인증에 실패했습니다. 다시 시도해 주세요",- "logoutFailed": "연결 해제에 실패했습니다. 다시 시도해 주세요"+ "loggedIn": "Grok에 로그인했습니다",+ "loggedOut": "Grok 연결을 해제했습니다",+ "loginFailed": "Grok에 로그인하지 못했습니다. 다시 시도하세요.",+ "logoutFailed": "Grok 연결을 해제하지 못했습니다. 다시 시도하세요."}},"claude": {"subtitle": {- "authorizing": "인증 중(브라우저)…",- "authorized": "Claude.ai 구독 · 인증됨",- "unauthorized": "미인증 (「인증」을 클릭해 Claude.ai 로그인)"+ "authorizing": "로그인 중…",+ "authorized": "Claude 구독 · 연결됨",+ "unauthorized": "연결 안 됨"},"button": {- "authorize": "인증"+ "authorize": "로그인"},"badge": {"api": "● API",@@ -1454,17 +1454,17 @@},"logoutConfirm": {"title": "Claude.ai 구독을 해제할까요?",- "description": "해제하면 이 기기의 Claude Code 로그인 자격 증명이 삭제됩니다(로컬 `claude` CLI도 함께 로그아웃됩니다). 현재 구독 모드라면 자동으로 Cindy AI로 되돌아갑니다. 복원하려면 다시 인증해야 합니다.",- "confirm": "해제",+ "description": "Cindy에서 이 Claude 구독을 사용할 수 없게 됩니다.",+ "confirm": "연결 해제","cancel": "취소"},"toast": {- "loggedIn": "Claude.ai 구독에 로그인했습니다",- "loggedOut": "Claude.ai 구독을 해제했습니다",- "loginFailed": "인증에 실패했습니다. 다시 시도하세요",- "logoutFailed": "연결 해제에 실패했습니다. 다시 시도하세요",+ "loggedIn": "Claude에 로그인했습니다",+ "loggedOut": "Claude 연결을 해제했습니다",+ "loginFailed": "Claude에 로그인하지 못했습니다. 다시 시도하세요.",+ "logoutFailed": "Claude 연결을 해제하지 못했습니다. 다시 시도하세요.","notSubscription": "이 계정에는 Claude 구독(Pro/Max)이 없어 구독 모드를 사용할 수 없습니다",- "needAuth": "먼저 Claude.ai에 로그인 인증하세요"+ "needAuth": "먼저 Claude에 로그인하세요"},"apiMode": {"label": "API 모드 (Cindy AI 경유)",@@ -1472,7 +1472,7 @@"toggleAria": "Claude API 모드 전환","sharedKeyWarning": "Cindy AI와 Key를 공유 — API 모드를 꺼도 Claude 외 모델에는 Cindy AI가 필요합니다","noKeyDialog": {- "title": "API Key가 설정되지 않음",+ "title": "API key가 설정되지 않음","description": "API 모드를 끄면(구독) Claude 외 모델(gpt / deepseek 등)에는 Cindy AI Key를 재사용하지만 아직 설정되지 않았습니다. 모델 제공자에서 Cindy AI를 연결하세요."},"toast": {@@ -1496,11 +1496,12 @@"disconnected": "연결되지 않음","connecting": "연결 중…","rename": "이름 변경",- "suspended": "비활성화됨"+ "suspended": "비활성화됨",+ "unconfigured": "설정 안 됨"},"button": {- "authorize": "인증",- "logout": "로그아웃",+ "authorize": "로그인",+ "logout": "연결 해제","connect": "연결","disconnect": "연결 해제","cancel": "취소",@@ -1517,13 +1518,13 @@"title": "OpenAI","subtitle": "하나의 ChatGPT 계정을 Codex와 Claude에서 함께 사용","modelLabel": "GPT 모델",- "reconnectRequired": "다시 연결 필요",- "connect": "ChatGPT 연결",- "reconnect": "ChatGPT 다시 연결",- "cancelConnect": "연결 취소",+ "reconnectRequired": "다시 로그인",+ "connect": "로컬 Codex 계정 사용",+ "reconnect": "다시 로그인",+ "cancelConnect": "취소","accountSource": {"local": "로컬 Codex 계정",- "oauth": "별도로 로그인한 계정",+ "oauth": "별도 계정","unknown": "기존 OpenAI 연결"},"useLocalAccount": "로컬 Codex 계정 사용",@@ -1593,19 +1594,19 @@},"custom": {"tag": "사용자 지정",- "editAria": "편집",+ "editAria": "연결 설정 편집","deleteAria": "삭제","save": "저장","cancel": "취소","dialog": {"createTitle": "사용자 지정 제공자 추가",- "editTitle": "사용자 지정 제공자 편집",+ "editTitle": "연결 설정 편집","desc": "OpenAI / Anthropic 호환 제공자를 구성합니다."},"imageGenerationReload": {"title": "Codex 다시 로드",- "description": "이 이미지 생성 설정을 저장하려면 Codex를 다시 로드해야 하며 현재 실행 중인 Codex 작업이 중단됩니다.",- "interrupt": "저장하고 중지",+ "description": "이 변경 사항을 적용하려면 Codex를 다시 로드해야 하며 현재 실행 중인 Codex 작업이 중단됩니다.",+ "interrupt": "계속하고 작업 중지","cancel": "취소","close": "닫기"},@@ -1699,8 +1700,8 @@"deleteFailed": "삭제 실패"},"deleteConfirm": {- "title": "사용자 지정 제공자를 삭제할까요?",- "description": "\"{{name}}\"의 설정과 로컬에 저장된 키를 삭제합니다. 사용 중인 세션은 기본 소스로 되돌아갑니다.",+ "title": "제공자를 삭제할까요?",+ "description": "Cindy에서 “{{name}}”을 사용할 수 없게 됩니다. 메시지 기록은 유지되며 나중에 다시 추가할 수 있습니다.","confirm": "삭제","cancel": "취소"},@@ -1731,10 +1732,10 @@"authMode": {"label": "인증 방식","apiKey": "API 키",- "oauth": "OAuth 구독 인증",+ "oauth": "구독 계정","none": "인증 없음","noneHelp": "로컬 또는 신뢰할 수 있는 자체 호스팅 프록시용입니다. Cindy는 전달 전에 CLI의 구독 자격 증명과 계정 헤더를 제거합니다.",- "oauthHelp": "OAuth 로그인을 제공하는 제공자용입니다. 브라우저 콜백 또는 기기 코드 방식을 선택하고 저장한 뒤 제공자 목록에서 인증하세요. 인증 정보는 이 기기에만 암호화되어 저장됩니다.",+ "oauthHelp": "OAuth 로그인을 지원하는 제공자용입니다. 브라우저 또는 기기 코드 방식을 선택한 후 저장하고 제공자 목록에서 로그인하세요. 자격 증명은 이 기기에 저장됩니다.","flowLabel": "OAuth 흐름","flow": {"authorization-code": "브라우저 콜백 (PKCE)",@@ -1747,7 +1748,7 @@"clientId": "Client ID","scopes": "Scopes(공백 구분)"},- "modelsAutoNote": "모델 목록은 인증 완료 후 자동으로 가져오므로 직접 입력할 필요가 없습니다."+ "modelsAutoNote": "로그인 후 사용 가능한 모델을 자동으로 가져옵니다"},"advanced": {"label": "고급 설정 (모델 / 요청 헤더)"@@ -1975,24 +1976,24 @@}},"genericOAuth": {- "subtitle": "구독 인증 로그인 (OAuth)",+ "subtitle": "구독 계정","toast": {"loggedIn": "{{name}}에 로그인했습니다",- "loginFailed": "{{name}} 로그인에 실패했습니다. 다시 시도하세요",- "loggedOut": "{{name}}에서 로그아웃했습니다",- "logoutFailed": "{{name}} 로그아웃에 실패했습니다"+ "loginFailed": "{{name}}에 로그인하지 못했습니다. 다시 시도하세요.",+ "loggedOut": "{{name}} 연결을 해제했습니다",+ "logoutFailed": "{{name}} 연결을 해제하지 못했습니다. 다시 시도하세요."},"logoutConfirm": {- "title": "{{name}}에서 로그아웃할까요?",- "description": "로그아웃하면 이 공급원의 모델을 사용할 수 없습니다. 언제든지 다시 로그인할 수 있습니다.",- "confirm": "로그아웃",+ "title": "“{{name}}” 연결을 해제할까요?",+ "description": "Cindy에서 “{{name}}”을 사용할 수 없게 됩니다. 제공자는 유지되며 나중에 다시 연결할 수 있습니다.",+ "confirm": "연결 해제","cancel": "취소"}},"addProvider": "제공자 추가","detail": {"singleAgentNote": "{{agent}} 전용",- "emptyModels": "인증하면 사용 가능한 모델이 자동으로 검색됩니다",+ "emptyModels": "로그인 후 사용 가능한 모델을 자동으로 가져옵니다","emptyList": "왼쪽 아래 '제공자 추가'에서 첫 모델 소스를 연결하세요","emptyModelsConnected": "연결됨 — 사용 가능한 모델을 검색하는 중입니다. 계속 비어 있으면 잠시 후 다시 시도해 주세요.","discoveryFailed": {@@ -2000,7 +2001,7 @@"timeout": "이 제공자 연결이 시간 초과되어 모델 목록을 가져오지 못했습니다. 네트워크를 확인한 후 다시 시도하세요.","upstream": "이 제공자가 지금은 모델 목록을 반환할 수 없습니다. 잠시 후 다시 시도하세요.","regionBlocked": "이 제공자는 현재 지역에서 서비스를 제공하지 않아 모델 목록을 가져오지 못했습니다. 다른 제공자를 사용하세요.",- "unauthorized": "이 제공자가 현재 인증을 거부하여 모델 목록을 가져오지 못했습니다. 연결을 해제한 후 다시 연결하세요.",+ "unauthorized": "현재 로그인 또는 API key가 거부되어 모델 목록을 가져올 수 없습니다. 다시 로그인하거나 API key를 업데이트하세요.","forbidden": "이 제공자가 요청을 거부하여 모델 목록을 가져오지 못했습니다. 프록시나 VPN을 사용 중이라면 출구를 바꾼 후 다시 시도하세요.","rejected": "이 제공자가 요청을 거부하여 모델 목록을 가져오지 못했습니다. 잠시 후 다시 시도하거나 다른 제공자를 사용하세요.","empty": "이 제공자가 사용 가능한 모델을 반환하지 않았습니다. 계정 권한을 확인한 후 다시 시도하세요."@@ -2010,7 +2011,7 @@"timeout": "이 제공자 연결이 시간 초과되었습니다. 아래는 마지막으로 가져온 모델 목록입니다. 네트워크를 확인한 후 다시 시도하세요.","upstream": "이 제공자가 지금은 모델 목록을 반환할 수 없습니다. 아래는 마지막으로 가져온 목록입니다. 잠시 후 다시 시도하세요.","regionBlocked": "이 제공자는 현재 지역에서 서비스를 제공하지 않습니다. 아래는 마지막으로 가져온 모델 목록입니다. 다른 제공자를 사용하세요.",- "unauthorized": "이 제공자가 현재 인증을 거부했습니다. 아래는 마지막으로 가져온 모델 목록입니다. 연결을 해제한 후 다시 연결하세요.",+ "unauthorized": "현재 로그인 또는 API key가 거부되었습니다. 아래는 이전 모델 목록입니다. 다시 로그인하거나 API key를 업데이트하세요.","forbidden": "이 제공자가 요청을 거부했습니다. 아래는 마지막으로 가져온 모델 목록입니다. 프록시나 VPN을 사용 중이라면 출구를 바꾼 후 다시 시도하세요.","rejected": "이 제공자가 요청을 거부했습니다. 아래는 마지막으로 가져온 목록입니다. 잠시 후 다시 시도하거나 다른 제공자를 사용하세요.","empty": "이번에는 이 제공자가 사용 가능한 모델을 반환하지 않았습니다. 아래는 마지막으로 가져온 목록입니다. 계정 권한을 확인한 후 다시 시도하세요."@@ -2020,8 +2021,8 @@},"detect": {"groupLabel": "이 기기에서 감지됨",- "action": "인증하기",- "hintLoggedIn": "{{cli}}이(가) 이 기기에 로그인되어 있습니다. 인증하여 바로 연결할 수 있습니다",+ "action": "로컬 계정 사용",+ "hintLoggedIn": "{{cli}}에 로그인되어 있습니다. 로컬 계정을 사용할 수 있습니다.","hintInstalled": "이 기기에 {{cli}}이(가) 설치되어 있습니다"},"wizard": {@@ -2034,21 +2035,21 @@"searchPlaceholder": "제공자 검색…","groupRecommend": "추천","groupDetectedLocal": "이 컴퓨터에서 감지됨",- "groupSubscription": "구독 인증",+ "groupSubscription": "구독 계정","recommendReason": {"has-local-models": "이 컴퓨터에 모델이 있음","machine-capable": "이 컴퓨터에서 로컬 모델을 돌릴 수 있음",- "subscription": "구독 인증"+ "subscription": "구독 계정"},"groupApiKey": "API 및 자체 호스팅 프록시 · 프리셋은 카탈로그와 함께 업데이트","groupCustom": "사용자 지정",- "metaOAuth": "구독 인증",- "metaApiKey": "API 키",+ "metaOAuth": "구독 계정",+ "metaApiKey": "API key","metaNoAuth": "로컬 / 자체 호스팅 · 인증 없음","customTitle": "사용자 지정 엔드포인트","customMeta": "OpenAI / Anthropic 호환 모델 소스를 연결",- "pickHint": "인증 방식은 제공자 정의에 따라 결정됩니다. OAuth 엔드포인트와 기본 URL은 프리셋에 포함되어 직접 입력할 필요가 없습니다.",- "oauthDesc": "브라우저에서 구독 인증을 완료합니다. API 키가 필요 없습니다",+ "pickHint": "연결할 계정이나 서비스를 선택하세요.",+ "oauthDesc": "브라우저에서 로그인합니다. API key는 필요하지 않습니다.","deviceOAuthDesc": "일회용 기기 코드를 사용해 제공자 인증 페이지에서 인증하세요","authorizeInBrowser": "브라우저에서 인증","authorizeWithDeviceCode": "기기 코드 사용",@@ -2060,8 +2061,8 @@"deviceCodeCopied": "기기 코드가 복사되었습니다","deviceCodeCopyFailed": "기기 코드를 복사하지 못했습니다","verificationPageOpenFailed": "인증 페이지를 열지 못했습니다",- "authorizedToast": "{{name}}에 연결되었습니다",- "authorizeFailed": "{{name}} 인증에 실패했습니다. 다시 시도해 주세요",+ "authorizedToast": "{{name}}에 로그인했습니다",+ "authorizeFailed": "{{name}}에 로그인하지 못했습니다. 다시 시도하세요.","nameLabel": "표시 이름","onlyAgentNote": "이 제공자는 {{agent}}만 지원합니다","endpointLabel": "{{agent}} 기본 URL",@@ -2084,7 +2085,7 @@"finish": "추가 완료","cancel": "취소","useApiKey": "API 키로 연결",- "metaOAuthOrApi": "구독 인증 · API 키",+ "metaOAuthOrApi": "구독 계정 · API key","builtinApiKey": {"subtitle": "내 API key로 연결","note": "이 소스는 이미지 생성 모델을 제공하며 대화에는 참여하지 않습니다. API key는 이 기기에만 저장되며(시스템 키체인 암호화) 업로드되지 않습니다."@@ -2220,7 +2221,7 @@},"builtinApiKey": {"subtitle": "API key 연결",- "replaceKey": "key 변경",+ "replaceKey": "연결 설정 편집","saveKey": "저장","keyPlaceholder": "API key 붙여넣기","toast": {@@ -2231,7 +2232,7 @@},"disconnectConfirm": {"title": "{{name}} 연결을 해제할까요?",- "description": "연결을 해제하면 이 기기에 저장된 API key가 삭제되며 이 소스의 모델을 사용할 수 없게 됩니다. 언제든지 다시 추가할 수 있습니다.",+ "description": "이 연결에 저장된 API key를 지웁니다. 제공자는 유지되며 API key를 입력하면 다시 사용할 수 있습니다.","confirm": "연결 해제","cancel": "취소"}@@ -2246,6 +2247,10 @@"codexPlanFallback": "ChatGPT 구독","codexSecondary": "보조 한도 {{percent}}% 남음","codexResetCredits": "한도 초기화 크레딧 {{count}}장"+ },+ "localAccount": {+ "useClaude": "로컬 Claude Code 계정 사용",+ "unavailable": "사용 가능한 로컬 로그인이 없습니다. 해당 앱에 로그인하거나 별도 계정을 추가하세요."}},"experimental": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 545c66712d..b2768c8cce 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1395,7 +1395,7 @@"codex": {"logoutConfirm": {"title": "断开 ChatGPT 账号?",- "description": "断开后,{{appName}} 将无法在 Codex 和 Claude 中使用这份 ChatGPT 订阅。系统 Codex CLI 的登录不受影响。",+ "description": "断开后,{{appName}} 将无法使用这份 ChatGPT 订阅。","confirm": "断开 ChatGPT","cancel": "取消"},@@ -1410,7 +1410,7 @@"description": "开启后 Codex 不走订阅,复用「模型供应商」里的 Cindy AI Key。","noKey": "未配置 Cindy AI Key,请在「模型供应商」里连接 Cindy AI","noKeyDialog": {- "title": "尚未配置 API Key",+ "title": "尚未配置 API key","description": "API 模式需要复用 Cindy AI Key,当前还没有配置。前往「模型供应商」连接 Cindy AI 后即可开启。"},"badge": {@@ -1428,25 +1428,25 @@"xai": {"logoutConfirm": {"title": "断开 xAI(SuperGrok)?",- "description": "断开会清除本机保存的 xAI 登录凭证;已选 Grok 模型的任务将无法调用,直到重新授权。",+ "description": "断开后,Cindy 将无法使用这份 Grok 订阅。","confirm": "断开","cancel": "取消"},"toast": {- "loggedIn": "已登录 xAI(SuperGrok)",- "loggedOut": "已断开 xAI",- "loginFailed": "授权失败,请重试",- "logoutFailed": "断开失败,请重试"+ "loggedIn": "已登录 Grok",+ "loggedOut": "已断开 Grok",+ "loginFailed": "Grok 登录失败,请重试",+ "logoutFailed": "Grok 断开失败,请重试"}},"claude": {"subtitle": {- "authorizing": "授权中(浏览器)…",- "authorized": "Claude.ai 订阅 · 已授权",- "unauthorized": "未授权(点「授权」登录 Claude.ai)"+ "authorizing": "登录中…",+ "authorized": "Claude 订阅 · 已连接",+ "unauthorized": "未连接"},"button": {- "authorize": "授权"+ "authorize": "登录"},"badge": {"api": "● API",@@ -1454,17 +1454,17 @@},"logoutConfirm": {"title": "断开 Claude.ai 订阅?",- "description": "断开会清除本机 Claude Code 的登录凭证(本地 `claude` 命令行也会一起登出);若当前在订阅模式会自动切回 Cindy AI。需要重新授权才能恢复。",+ "description": "断开后,Cindy 将无法使用这份 Claude 订阅。","confirm": "断开","cancel": "取消"},"toast": {- "loggedIn": "已登录 Claude.ai 订阅",- "loggedOut": "已断开 Claude.ai 订阅",- "loginFailed": "授权失败,请重试",- "logoutFailed": "断开失败,请重试",+ "loggedIn": "已登录 Claude",+ "loggedOut": "已断开 Claude",+ "loginFailed": "Claude 登录失败,请重试",+ "logoutFailed": "Claude 断开失败,请重试","notSubscription": "该账号没有 Claude 订阅(Pro/Max),无法走订阅模式",- "needAuth": "请先授权登录 Claude.ai"+ "needAuth": "请先登录 Claude"},"apiMode": {"label": "API 模式(走 Cindy AI)",@@ -1472,7 +1472,7 @@"toggleAria": "切换 Claude API 模式","sharedKeyWarning": "和 Cindy AI 共用一把 Key,关闭 API 模式后非 Claude 模型仍需 Cindy AI","noKeyDialog": {- "title": "尚未配置 API Key",+ "title": "尚未配置 API key","description": "关闭 API 模式(走订阅)后,非 Claude 模型(gpt / deepseek 等)仍需复用 Cindy AI Key,当前还没有配置。前往「模型供应商」连接 Cindy AI 后即可。"},"toast": {@@ -1496,11 +1496,12 @@"disconnected": "未连接","connecting": "正在连接…","rename": "重命名",- "suspended": "已停用"+ "suspended": "已停用",+ "unconfigured": "未配置"},"button": {- "authorize": "授权",- "logout": "登出",+ "authorize": "登录",+ "logout": "断开","connect": "连接","disconnect": "断开","cancel": "取消",@@ -1517,13 +1518,13 @@"title": "OpenAI","subtitle": "连接一个 ChatGPT 账号,同时用于 Codex 和 Claude","modelLabel": "GPT 模型",- "reconnectRequired": "需要重新连接",- "connect": "连接 ChatGPT",- "reconnect": "重新连接 ChatGPT",- "cancelConnect": "取消连接",+ "reconnectRequired": "重新登录",+ "connect": "使用本机 Codex 账号",+ "reconnect": "重新登录",+ "cancelConnect": "取消","accountSource": {"local": "本机 Codex 账号",- "oauth": "独立登录账号",+ "oauth": "独立账号","unknown": "现有 OpenAI 连接"},"useLocalAccount": "使用本机 Codex 账号",@@ -1593,19 +1594,19 @@},"custom": {"tag": "自定义",- "editAria": "编辑",+ "editAria": "编辑连接设置","deleteAria": "删除","save": "保存","cancel": "取消","dialog": {"createTitle": "添加自定义供应商",- "editTitle": "编辑自定义供应商",+ "editTitle": "编辑连接设置","desc": "配置与 OpenAI / Anthropic 兼容的供应商。"},"imageGenerationReload": {"title": "重新加载 Codex",- "description": "保存此图片生成配置需要重新加载 Codex,并会中断当前正在执行的 Codex 任务。",- "interrupt": "保存并停止",+ "description": "应用此更改需要重新加载 Codex,并会中断当前正在执行的 Codex 任务。",+ "interrupt": "继续并停止任务","cancel": "取消","close": "关闭"},@@ -1639,7 +1640,7 @@"runtimeSupportsImageGenerationEndpointsTitle": "接口要求","runtimeSupportsImageGenerationEndpoints": "网关必须处理以下请求:","runtimeSupportsImageGenerationPermissionsTitle": "权限与失败处理",- "runtimeSupportsImageGenerationPermissions": "当前 API Key、账号或用户组需有图片模型权限。此开关只声明网关能力,不会自动开通上游权限。调用失败时会显示真实上游错误,不会切换到其他图片服务。",+ "runtimeSupportsImageGenerationPermissions": "当前 API key、账号或用户组需有图片模型权限。此开关只声明网关能力,不会自动开通上游权限。调用失败时会显示真实上游错误,不会切换到其他图片服务。","modelSupportsReasoning": "支持推理","modelSupportsReasoningHelp": "仅在该模型接受推理强度时开启,并勾选它实际支持的所有档位。保存后,下一个 Pi Agent 会话生效。","modelReasoningEfforts": "支持的推理强度",@@ -1699,8 +1700,8 @@"deleteFailed": "删除失败"},"deleteConfirm": {- "title": "删除自定义供应商?",- "description": "将删除「{{name}}」的配置和本机保存的密钥,正在使用它的任务会回退到默认来源。",+ "title": "删除供应商?",+ "description": "删除后,Cindy 将无法再使用「{{name}}」。历史消息会保留,之后可以重新添加。","confirm": "删除","cancel": "取消"},@@ -1731,10 +1732,10 @@"authMode": {"label": "鉴权方式","apiKey": "API 密钥",- "oauth": "OAuth 订阅授权",+ "oauth": "订阅账号","none": "无需鉴权","noneHelp": "适用于本机或受信任的自托管 Proxy。Cindy 会移除 CLI 自带的订阅凭证和账号头,再把请求发往该端点。",- "oauthHelp": "适用于提供 OAuth 登录的供应商。可选择浏览器回调或设备码流程,保存后从供应商列表发起授权。凭证仅加密存储在本机。",+ "oauthHelp": "适用于支持 OAuth 登录的供应商。可选择浏览器或设备码登录,保存后从供应商列表发起登录。凭证保存在本机。","flowLabel": "OAuth 流程","flow": {"authorization-code": "浏览器回调(PKCE)",@@ -1747,7 +1748,7 @@"clientId": "Client ID","scopes": "Scopes(空格分隔)"},- "modelsAutoNote": "模型清单将在授权成功后自动获取,无需手动填写。"+ "modelsAutoNote": "登录后自动获取可用模型"},"advanced": {"label": "高级配置(模型 / 请求头)"@@ -1975,24 +1976,24 @@}},"genericOAuth": {- "subtitle": "订阅授权登录(OAuth)",+ "subtitle": "订阅账号","toast": {- "loggedIn": "{{name}} 登录成功",+ "loggedIn": "已登录 {{name}}","loginFailed": "{{name}} 登录失败,请重试",- "loggedOut": "已退出 {{name}}",- "logoutFailed": "退出 {{name}} 失败"+ "loggedOut": "已断开 {{name}}",+ "logoutFailed": "{{name}} 断开失败,请重试"},"logoutConfirm": {- "title": "退出 {{name}}?",- "description": "退出后该来源的模型将不可用,可随时重新登录。",- "confirm": "退出登录",+ "title": "断开「{{name}}」?",+ "description": "断开后,Cindy 将无法使用「{{name}}」。供应商会保留,之后可以重新连接。",+ "confirm": "断开","cancel": "取消"}},"addProvider": "添加供应商","detail": {"singleAgentNote": "仅支持 {{agent}}",- "emptyModels": "授权后自动发现可用模型",+ "emptyModels": "登录后自动获取可用模型","emptyList": "点击左下角「添加供应商」接入你的第一个模型来源","emptyModelsConnected": "已连接,正在自动发现可用模型;若持续为空,请稍后重试。","discoveryFailed": {@@ -2000,7 +2001,7 @@"timeout": "连接该供应商超时,因此拿不到模型列表。请检查网络后重试。","upstream": "该供应商暂时无法返回模型列表。请稍后重试。","regionBlocked": "该供应商未在你当前所在地区提供服务,因此拿不到模型列表。你可以改用其它供应商。",- "unauthorized": "该供应商拒绝了当前授权,因此拿不到模型列表。请断开后重新连接。",+ "unauthorized": "当前登录或 API key 已被供应商拒绝,无法获取模型列表。请重新登录或更新 API key。","forbidden": "该供应商拒绝了这次请求,因此拿不到模型列表。若你正在使用 Proxy 或 VPN,请更换出口后重试。","rejected": "该供应商拒绝了这次请求,因此拿不到模型列表。请稍后重试或改用其它供应商。","empty": "该供应商没有返回任何可用模型。请确认账号权限后重试。"@@ -2010,7 +2011,7 @@"timeout": "连接该供应商超时,下面是上次获取的模型列表。请检查网络后重试。","upstream": "该供应商暂时无法返回模型列表,下面是上次获取的结果。请稍后重试。","regionBlocked": "该供应商未在你当前所在地区提供服务,下面是上次获取的模型列表。你可以改用其它供应商。",- "unauthorized": "该供应商拒绝了当前授权,下面是上次获取的模型列表。请断开后重新连接。",+ "unauthorized": "当前登录或 API key 已被供应商拒绝,下面是上次获取的模型列表。请重新登录或更新 API key。","forbidden": "该供应商拒绝了这次请求,下面是上次获取的模型列表。若你正在使用 Proxy 或 VPN,请更换出口后重试。","rejected": "该供应商拒绝了这次请求,下面是上次获取的模型列表。请稍后重试或改用其它供应商。","empty": "该供应商这次没有返回任何可用模型,下面是上次获取的列表。请确认账号权限后重试。"@@ -2020,8 +2021,8 @@},"detect": {"groupLabel": "检测到本机 CLI",- "action": "去授权",- "hintLoggedIn": "检测到 {{cli}} 已登录,可直接授权接入",+ "action": "使用本机账号",+ "hintLoggedIn": "检测到 {{cli}} 已登录,可使用本机账号接入","hintInstalled": "检测到本机已安装 {{cli}}"},"wizard": {@@ -2034,21 +2035,21 @@"searchPlaceholder": "搜索供应商…","groupRecommend": "推荐","groupDetectedLocal": "检测到本机服务",- "groupSubscription": "订阅授权",+ "groupSubscription": "订阅账号","recommendReason": {"has-local-models": "本机已有模型","machine-capable": "这台电脑适合跑本机模型",- "subscription": "订阅授权"+ "subscription": "订阅账号"},"groupApiKey": "API 与自托管 Proxy · 预设随目录更新","groupCustom": "自定义",- "metaOAuth": "订阅授权",- "metaApiKey": "API Key",+ "metaOAuth": "订阅账号",+ "metaApiKey": "API key","metaNoAuth": "本机 / 自托管 · 无需鉴权","customTitle": "自定义端点","customMeta": "接入任意 OpenAI / Anthropic 兼容的模型来源",- "pickHint": "鉴权方式由供应商定义决定;OAuth 端点与基础 URL 由预设携带,无需手填。",- "oauthDesc": "通过浏览器完成订阅授权,无需 API Key",+ "pickHint": "选择你要连接的账号或服务。",+ "oauthDesc": "在浏览器中登录账号,无需 API key。","deviceOAuthDesc": "使用一次性设备码,在供应商验证页面完成授权","authorizeInBrowser": "在浏览器中授权","authorizeWithDeviceCode": "使用设备码",@@ -2060,8 +2061,8 @@"deviceCodeCopied": "设备码已复制","deviceCodeCopyFailed": "设备码复制失败","verificationPageOpenFailed": "无法打开验证页面",- "authorizedToast": "已连接「{{name}}」",- "authorizeFailed": "「{{name}}」授权失败,请重试",+ "authorizedToast": "已登录 {{name}}",+ "authorizeFailed": "{{name}} 登录失败,请重试","nameLabel": "显示名称","onlyAgentNote": "此供应商仅支持 {{agent}}","endpointLabel": "{{agent}} 基础 URL",@@ -2084,7 +2085,7 @@"finish": "完成添加","cancel": "取消","useApiKey": "API key 接入",- "metaOAuthOrApi": "订阅授权 · API Key",+ "metaOAuthOrApi": "订阅账号 · API key","builtinApiKey": {"subtitle": "用你自己的 API key 连接","note": "此来源提供图像生成模型,不参与对话。API key 仅保存在本机(系统钥匙串加密),不会上传。"@@ -2220,7 +2221,7 @@},"builtinApiKey": {"subtitle": "API key 连接",- "replaceKey": "更换 key",+ "replaceKey": "编辑连接设置","saveKey": "保存","keyPlaceholder": "粘贴 API key","toast": {@@ -2231,7 +2232,7 @@},"disconnectConfirm": {"title": "断开 {{name}}?",- "description": "断开会删除本机保存的 API key,该来源的模型将不可用,可随时重新添加。",+ "description": "断开会清除这份连接保存的 API key。供应商会保留,重新填写 API key 后即可使用。","confirm": "断开","cancel": "取消"}@@ -2246,6 +2247,10 @@"codexPlanFallback": "ChatGPT 订阅","codexSecondary": "次级窗口剩余 {{percent}}%","codexResetCredits": "限额重置券 {{count}} 张"+ },+ "localAccount": {+ "useClaude": "使用本机 Claude Code 账号",+ "unavailable": "未找到可用的本机登录,请先在对应应用中登录,或添加独立账号。"}},"experimental": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 0685371c84..e8778024cc 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -1410,7 +1410,7 @@"description": "開啟後 Codex 不走訂閱,複用「模型供應商」裡的 Cindy AI Key。","noKey": "未配置 Cindy AI Key,請在「模型供應商」裡連線 Cindy AI","noKeyDialog": {- "title": "尚未配置 API Key",+ "title": "尚未配置 API key","description": "API 模式需要複用 Cindy AI Key,當前還沒有配置。前往「模型供應商」連線 Cindy AI 後即可開啟。"},"badge": {@@ -1428,25 +1428,25 @@"xai": {"logoutConfirm": {"title": "斷開 xAI(SuperGrok)?",- "description": "斷開會清除本機儲存的 xAI 登入憑證;已選 Grok 模型的任務將無法呼叫,直到重新授權。",- "confirm": "斷開",+ "description": "中斷後,Cindy 將無法使用這份 Grok 訂閱。",+ "confirm": "中斷連線","cancel": "取消"},"toast": {- "loggedIn": "已登入 xAI(SuperGrok)",- "loggedOut": "已斷開 xAI",- "loginFailed": "授權失敗,請重試",- "logoutFailed": "斷開失敗,請重試"+ "loggedIn": "已登入 Grok",+ "loggedOut": "已中斷 Grok 的連線",+ "loginFailed": "Grok 登入失敗,請重試",+ "logoutFailed": "Grok 中斷連線失敗,請重試"}},"claude": {"subtitle": {- "authorizing": "授權中(瀏覽器)…",- "authorized": "Claude.ai 訂閱 · 已授權",- "unauthorized": "未授權(點「授權」登入 Claude.ai)"+ "authorizing": "登入中…",+ "authorized": "Claude 訂閱 · 已連線",+ "unauthorized": "未連線"},"button": {- "authorize": "授權"+ "authorize": "登入"},"badge": {"api": "● API",@@ -1454,17 +1454,17 @@},"logoutConfirm": {"title": "斷開 Claude.ai 訂閱?",- "description": "斷開會清除本機 Claude Code 的登入憑證(本地 `claude` 命令列也會一起登出);若當前在訂閱模式會自動切回 Cindy AI。需要重新授權才能恢復。",- "confirm": "斷開",+ "description": "中斷後,Cindy 將無法使用這份 Claude 訂閱。",+ "confirm": "中斷連線","cancel": "取消"},"toast": {- "loggedIn": "已登入 Claude.ai 訂閱",- "loggedOut": "已斷開 Claude.ai 訂閱",- "loginFailed": "授權失敗,請重試",- "logoutFailed": "斷開失敗,請重試",+ "loggedIn": "已登入 Claude",+ "loggedOut": "已中斷 Claude 的連線",+ "loginFailed": "Claude 登入失敗,請重試",+ "logoutFailed": "Claude 中斷連線失敗,請重試","notSubscription": "該帳號沒有 Claude 訂閱(Pro/Max),無法走訂閱模式",- "needAuth": "請先授權登入 Claude.ai"+ "needAuth": "請先登入 Claude"},"apiMode": {"label": "API 模式(走 Cindy AI)",@@ -1472,7 +1472,7 @@"toggleAria": "切換 Claude API 模式","sharedKeyWarning": "和 Cindy AI 共用一把 Key,關閉 API 模式後非 Claude 模型仍需 Cindy AI","noKeyDialog": {- "title": "尚未配置 API Key",+ "title": "尚未配置 API key","description": "關閉 API 模式(走訂閱)後,非 Claude 模型(gpt / deepseek 等)仍需複用 Cindy AI Key,當前還沒有配置。前往「模型供應商」連線 Cindy AI 後即可。"},"toast": {@@ -1496,11 +1496,12 @@"disconnected": "未連線","connecting": "正在連線…","rename": "重新命名",- "suspended": "已停用"+ "suspended": "已停用",+ "unconfigured": "未設定"},"button": {- "authorize": "授權",- "logout": "登出",+ "authorize": "登入",+ "logout": "中斷連線","connect": "連線","disconnect": "斷開","cancel": "取消",@@ -1517,13 +1518,13 @@"title": "OpenAI","subtitle": "連線一個 ChatGPT 帳號,同時用於 Codex 和 Claude","modelLabel": "GPT 模型",- "reconnectRequired": "需要重新連線",- "connect": "連線 ChatGPT",- "reconnect": "重新連線 ChatGPT",- "cancelConnect": "取消連線",+ "reconnectRequired": "重新登入",+ "connect": "使用本機 Codex 帳號",+ "reconnect": "重新登入",+ "cancelConnect": "取消","accountSource": {"local": "本機 Codex 帳號",- "oauth": "獨立登入帳號",+ "oauth": "獨立帳號","unknown": "現有 OpenAI 連線"},"useLocalAccount": "使用本機 Codex 帳號",@@ -1593,19 +1594,19 @@},"custom": {"tag": "自定義",- "editAria": "編輯",+ "editAria": "編輯連線設定","deleteAria": "刪除","save": "儲存","cancel": "取消","dialog": {"createTitle": "新增自定義供應商",- "editTitle": "編輯自定義供應商",+ "editTitle": "編輯連線設定","desc": "配置與 OpenAI / Anthropic 相容的供應商。"},"imageGenerationReload": {"title": "重新載入 Codex",- "description": "儲存此圖片生成設定需要重新載入 Codex,並會中斷目前正在執行的 Codex 任務。",- "interrupt": "儲存並停止",+ "description": "套用此變更需要重新載入 Codex,並會中斷目前正在執行的 Codex 任務。",+ "interrupt": "繼續並停止任務","cancel": "取消","close": "關閉"},@@ -1639,7 +1640,7 @@"runtimeSupportsImageGenerationEndpointsTitle": "介面要求","runtimeSupportsImageGenerationEndpoints": "閘道必須處理以下請求:","runtimeSupportsImageGenerationPermissionsTitle": "權限與失敗處理",- "runtimeSupportsImageGenerationPermissions": "目前的 API Key、帳號或使用者群組需有圖片模型權限。此開關只宣告閘道能力,不會自動開通上游權限。呼叫失敗時會顯示真實的上游錯誤,不會切換到其他圖片服務。",+ "runtimeSupportsImageGenerationPermissions": "目前的 API key、帳號或使用者群組需有圖片模型權限。此開關只宣告閘道能力,不會自動開通上游權限。呼叫失敗時會顯示真實的上游錯誤,不會切換到其他圖片服務。","modelSupportsReasoning": "支援推理","modelSupportsReasoningHelp": "僅在該模型接受推理強度時開啟,並勾選它實際支援的所有檔位。儲存後,下一個 Pi Agent 會話生效。","modelReasoningEfforts": "支援的推理強度",@@ -1699,8 +1700,8 @@"deleteFailed": "刪除失敗"},"deleteConfirm": {- "title": "刪除自定義供應商?",- "description": "將刪除「{{name}}」的配置和本機儲存的金鑰,正在使用它的任務會回退到預設來源。",+ "title": "刪除供應商?",+ "description": "刪除後,Cindy 將無法再使用「{{name}}」。歷史訊息會保留,之後可以重新新增。","confirm": "刪除","cancel": "取消"},@@ -1731,10 +1732,10 @@"authMode": {"label": "鑑權方式","apiKey": "API 金鑰",- "oauth": "OAuth 訂閱授權",+ "oauth": "訂閱帳號","none": "無需鑑權","noneHelp": "適用於本機或受信任的自託管 Proxy。Cindy 會移除 CLI 自帶的訂閱憑證和帳號頭,再把請求發往該端點。",- "oauthHelp": "適用於提供 OAuth 登入的供應商。可選擇瀏覽器回撥或裝置碼流程,儲存後從供應商列表發起授權。憑證僅加密儲存在本機。",+ "oauthHelp": "適用於支援 OAuth 登入的供應商。可選擇瀏覽器或裝置碼登入,儲存後從供應商清單登入。憑證保存在本機。","flowLabel": "OAuth 流程","flow": {"authorization-code": "瀏覽器回撥(PKCE)",@@ -1747,7 +1748,7 @@"clientId": "Client ID","scopes": "Scopes(空格分隔)"},- "modelsAutoNote": "模型清單將在授權成功後自動獲取,無需手動填寫。"+ "modelsAutoNote": "登入後自動取得可用模型"},"advanced": {"label": "高階配置(模型 / 請求頭)"@@ -1975,24 +1976,24 @@}},"genericOAuth": {- "subtitle": "訂閱授權登入(OAuth)",+ "subtitle": "訂閱帳號","toast": {- "loggedIn": "{{name}} 登入成功",+ "loggedIn": "已登入 {{name}}","loginFailed": "{{name}} 登入失敗,請重試",- "loggedOut": "已退出 {{name}}",- "logoutFailed": "退出 {{name}} 失敗"+ "loggedOut": "已中斷 {{name}} 的連線",+ "logoutFailed": "{{name}} 中斷連線失敗,請重試"},"logoutConfirm": {- "title": "退出 {{name}}?",- "description": "退出後該來源的模型將不可用,可隨時重新登入。",- "confirm": "退出登入",+ "title": "中斷「{{name}}」的連線?",+ "description": "中斷後,Cindy 將無法使用「{{name}}」。供應商會保留,之後可以重新連線。",+ "confirm": "中斷連線","cancel": "取消"}},"addProvider": "新增供應商","detail": {"singleAgentNote": "僅支援 {{agent}}",- "emptyModels": "授權後自動發現可用模型",+ "emptyModels": "登入後自動取得可用模型","emptyList": "點選左下角「新增供應商」接入你的第一個模型來源","emptyModelsConnected": "已連線,正在自動發現可用模型;若持續為空,請稍後重試。","discoveryFailed": {@@ -2000,7 +2001,7 @@"timeout": "連線該供應商超時,因此拿不到模型列表。請檢查網路後重試。","upstream": "該供應商暫時無法返回模型列表。請稍後重試。","regionBlocked": "該供應商未在你當前所在地區提供服務,因此拿不到模型列表。你可以改用其它供應商。",- "unauthorized": "該供應商拒絕了當前授權,因此拿不到模型列表。請斷開後重新連線。",+ "unauthorized": "目前登入或 API key 已遭供應商拒絕,無法取得模型清單。請重新登入或更新 API key。","forbidden": "該供應商拒絕了這次請求,因此拿不到模型列表。若你正在使用 Proxy 或 VPN,請更換出口後重試。","rejected": "該供應商拒絕了這次請求,因此拿不到模型列表。請稍後重試或改用其它供應商。","empty": "該供應商沒有返回任何可用模型。請確認帳號權限後重試。"@@ -2010,7 +2011,7 @@"timeout": "連線該供應商超時,下面是上次獲取的模型列表。請檢查網路後重試。","upstream": "該供應商暫時無法返回模型列表,下面是上次獲取的結果。請稍後重試。","regionBlocked": "該供應商未在你當前所在地區提供服務,下面是上次獲取的模型列表。你可以改用其它供應商。",- "unauthorized": "該供應商拒絕了當前授權,下面是上次獲取的模型列表。請斷開後重新連線。",+ "unauthorized": "目前登入或 API key 已遭供應商拒絕,下方為上次取得的模型清單。請重新登入或更新 API key。","forbidden": "該供應商拒絕了這次請求,下面是上次獲取的模型列表。若你正在使用 Proxy 或 VPN,請更換出口後重試。","rejected": "該供應商拒絕了這次請求,下面是上次獲取的模型列表。請稍後重試或改用其它供應商。","empty": "該供應商這次沒有返回任何可用模型,下面是上次獲取的列表。請確認帳號權限後重試。"@@ -2020,8 +2021,8 @@},"detect": {"groupLabel": "檢測到本機 CLI",- "action": "去授權",- "hintLoggedIn": "檢測到 {{cli}} 已登入,可直接授權接入",+ "action": "使用本機帳號",+ "hintLoggedIn": "偵測到 {{cli}} 已登入,可使用本機帳號連線","hintInstalled": "檢測到本機已安裝 {{cli}}"},"wizard": {@@ -2034,21 +2035,21 @@"searchPlaceholder": "搜尋供應商…","groupRecommend": "推薦","groupDetectedLocal": "偵測到本機服務",- "groupSubscription": "訂閱授權",+ "groupSubscription": "訂閱帳號","recommendReason": {"has-local-models": "本機已有模型","machine-capable": "這台電腦適合跑本機模型",- "subscription": "訂閱授權"+ "subscription": "訂閱帳號"},"groupApiKey": "API 與自託管 Proxy · 預設隨目錄更新","groupCustom": "自定義",- "metaOAuth": "訂閱授權",- "metaApiKey": "API Key",+ "metaOAuth": "訂閱帳號",+ "metaApiKey": "API key","metaNoAuth": "本機 / 自託管 · 無需鑑權","customTitle": "自定義端點","customMeta": "接入任意 OpenAI / Anthropic 相容的模型來源",- "pickHint": "鑑權方式由供應商定義決定;OAuth 端點與基礎 URL 由預設攜帶,無需手填。",- "oauthDesc": "透過瀏覽器完成訂閱授權,無需 API Key",+ "pickHint": "選擇要連線的帳號或服務。",+ "oauthDesc": "在瀏覽器中登入帳號,無需 API key。","deviceOAuthDesc": "使用一次性裝置碼,在供應商驗證頁面完成授權","authorizeInBrowser": "在瀏覽器中授權","authorizeWithDeviceCode": "使用裝置碼",@@ -2060,8 +2061,8 @@"deviceCodeCopied": "裝置碼已複製","deviceCodeCopyFailed": "裝置碼複製失敗","verificationPageOpenFailed": "無法開啟驗證頁面",- "authorizedToast": "已連線「{{name}}」",- "authorizeFailed": "「{{name}}」授權失敗,請重試",+ "authorizedToast": "已登入 {{name}}",+ "authorizeFailed": "{{name}} 登入失敗,請重試","nameLabel": "顯示名稱","onlyAgentNote": "此供應商僅支援 {{agent}}","endpointLabel": "{{agent}} 基礎 URL",@@ -2084,7 +2085,7 @@"finish": "完成新增","cancel": "取消","useApiKey": "API key 接入",- "metaOAuthOrApi": "訂閱授權 · API Key",+ "metaOAuthOrApi": "訂閱帳號 · API key","builtinApiKey": {"subtitle": "用你自己的 API key 連線","note": "此來源提供影像生成模型,不參與對話。API key 僅儲存在本機(系統鑰匙串加密),不會上傳。"@@ -2220,7 +2221,7 @@},"builtinApiKey": {"subtitle": "API key 連線",- "replaceKey": "更換 key",+ "replaceKey": "編輯連線設定","saveKey": "儲存","keyPlaceholder": "貼上 API key","toast": {@@ -2231,7 +2232,7 @@},"disconnectConfirm": {"title": "斷開 {{name}}?",- "description": "斷開會刪除本機儲存的 API key,該來源的模型將不可用,可隨時重新新增。",+ "description": "中斷會清除此連線儲存的 API key。供應商會保留,重新填寫 API key 後即可使用。","confirm": "斷開","cancel": "取消"}@@ -2246,6 +2247,10 @@"codexPlanFallback": "ChatGPT 訂閱","codexSecondary": "次級窗口剩餘 {{percent}}%","codexResetCredits": "限額重設券 {{count}} 張"+ },+ "localAccount": {+ "useClaude": "使用本機 Claude Code 帳號",+ "unavailable": "找不到可用的本機登入,請先在對應應用程式登入,或新增獨立帳號。"}},"experimental": {diff --git a/apps/desktop/src/renderer/lib/__tests__/providerDisplayName.test.ts b/apps/desktop/src/renderer/lib/__tests__/providerDisplayName.test.tsindex 1785655e10..409fb2513c 100644--- a/apps/desktop/src/renderer/lib/__tests__/providerDisplayName.test.ts+++ b/apps/desktop/src/renderer/lib/__tests__/providerDisplayName.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from 'vitest';import type { ProviderView } from '@cindy/model-providers';-import { providerDisplayNameById } from '../providerDisplayName';+import { providerDisplayName, providerDisplayNameById } from '../providerDisplayName';const t = (key: string) =>({@@ -27,3 +27,9 @@ describe('providerDisplayNameById', () => {expect(providerDisplayNameById('gone', catalog, t)).toBe('gone');});});++it('uses the renamed connection in both selector and history display', () => {+ const provider = { id: 'openai', name: 'Personal ChatGPT' } as ProviderView;+ expect(providerDisplayName(provider, t)).toBe('Personal ChatGPT');+ expect(providerDisplayNameById('openai', [provider], t)).toBe('Personal ChatGPT');+});diff --git a/apps/desktop/src/renderer/lib/customProviders.ts b/apps/desktop/src/renderer/lib/customProviders.tsindex 024dbf65ad..6abe20067a 100644--- a/apps/desktop/src/renderer/lib/customProviders.ts+++ b/apps/desktop/src/renderer/lib/customProviders.ts@@ -332,6 +332,8 @@ export async function updateCustomProvider(}/** 删除:main 在同一 provider mutation queue 内清配置与所有凭证。 */-export async function deleteCustomProvider(providerId: string): Promise<void> {- await window.electronAPI.maker.deleteCustomProvider(storedCustomProviderId(providerId));+export async function deleteCustomProvider(providerId: string, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }, options?: CustomProviderUpdateOptions): Promise<CustomProviderUpdateResult> {+ if (options !== undefined) return window.electronAPI.maker.deleteCustomProvider(storedCustomProviderId(providerId), ownerScope, options);+ if (ownerScope === undefined) return window.electronAPI.maker.deleteCustomProvider(storedCustomProviderId(providerId));+ return window.electronAPI.maker.deleteCustomProvider(storedCustomProviderId(providerId), ownerScope);}diff --git a/apps/desktop/src/renderer/lib/providerDisplayName.ts b/apps/desktop/src/renderer/lib/providerDisplayName.tsindex 8c02f3b09a..bb9971e4ee 100644--- a/apps/desktop/src/renderer/lib/providerDisplayName.ts+++ b/apps/desktop/src/renderer/lib/providerDisplayName.ts@@ -1,6 +1,6 @@/**- * 供应商展示名 —— 三个内置 id 复用设置页 i18n 标题 (settings.providers.<id>.title),- * 自定义供应商回退目录里的 provider.name, 都拿不到时才回退裸 id。+ * 所有可改名连接优先显示目录中的名称;Cindy AI 保留统一的本地化产品名。+ * 缺少目录时才回退内置名称或连接 ID。** 从 ModelSelector 提取到这里: 用量历史的任务表也要把 Session.providerId 渲染成人话,* 两处必须同源, 否则同一个 'xd' 在模型选择器里是「Cindy AI」、在用量页却是「xd」。@@ -18,7 +18,7 @@ type TFunc = (key: string) => string;export function providerDisplayName(provider: ProviderView, t: TFunc): string {const key = PROVIDER_TITLE_KEY[provider.id];- return key ? t(key) : provider.name;+ return provider.id === 'xd' && key ? t(key) : provider.name || (key ? t(key) : provider.id);}/**@@ -30,7 +30,8 @@ export function providerDisplayNameById(providers: readonly ProviderView[],t: TFunc,): string {+ const provider = providers.find((item) => item.id === providerId);+ if (provider) return providerDisplayName(provider, t);const key = PROVIDER_TITLE_KEY[providerId];- if (key) return t(key);- return providers.find((provider) => provider.id === providerId)?.name ?? providerId;+ return key ? t(key) : providerId;}diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 4272a1e3cc..5080675676 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -2112,7 +2112,7 @@ interface ElectronAPI {/** 内置 API-key 供应商专用 IPC(查/写/删,永不回读明文;对应 MAIN_ONLY 键)。mutation 失败抛统一 IPC 错误。 */builtinApiKeyHas: (providerId: string) => Promise<boolean>;builtinApiKeyStore: (providerId: string, value: string) => Promise<void>;- builtinApiKeyRemove: (providerId: string) => Promise<void>;+ builtinApiKeyRemove: (providerId: string, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }) => Promise<void>;/** CC 网络调试日志开关 (admin experimental). main 端 mutate process.env.XDT_CC_DEBUG_NET。 */ccSetDebugNet: (enabled: boolean) => Promise<{ ok: true }>;/** 网关凭据自动下发(model-access,类型见 shared/modelAccess.ts)。 */@@ -5076,6 +5076,7 @@ interface ElectronAPI {) => Promise<import('../shared/workflow-progress').WorkflowProgress | null>;// 模型供应商目录(只读)—— 内置目录元数据 + 各供应商实时连接状态。+ setProviderPresentation: (input: { providerId?: string; action: 'rename' | 'remove' | 'restore'; name?: string; dataOwnerId: string | null; ownerGeneration: number }) => Promise<void>;listProviders: () => Promise<{dataOwnerId: string | null;ownerGeneration: number;@@ -5102,7 +5103,8 @@ interface ElectronAPI {keys: Partial<Record<'claude-code' | 'codex' | 'pi', string>>,options?: CustomProviderUpdateOptions,) => Promise<CustomProviderUpdateResult>;- deleteCustomProvider: (providerId: string) => Promise<{ ok: true }>;+ disconnectCustomProvider: (providerId: string, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }, options?: CustomProviderUpdateOptions) => Promise<CustomProviderUpdateResult>;+ deleteCustomProvider: (providerId: string, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }, options?: CustomProviderUpdateOptions) => Promise<CustomProviderUpdateResult>;localModelStatus: () => Promise<import('../shared/localModelRuntime').LocalRuntimeStatus>;localModelStart: () => Promise<import('../shared/localModelRuntime').LocalRuntimeStatus>;localModelList: () => Promise<{@@ -5230,7 +5232,7 @@ interface ElectronAPI {providerId: string,options?: { ownerId?: string },) => Promise<{ ok: boolean; reason?: string }>;- providerOAuthLogout: (providerId: string) => Promise<{ ok: true }>;+ providerOAuthLogout: (providerId: string, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }, options?: CustomProviderUpdateOptions) => Promise<CustomProviderUpdateResult>;providerOAuthCancel: (providerId: string,options?: { releaseOwner?: boolean; ownerId?: string },@@ -6168,16 +6170,16 @@ interface ElectronAPI {/** Claude.ai 订阅 OAuth 登录状态(系统 ~/.claude 凭证库是否有 OAuth 登录) */claudeOAuthStatus: () => Promise<{ authorized: boolean }>;- /** 拉起浏览器 OAuth 登录 Claude.ai 订阅;成功写凭证。reason 在失败时给出(cancelled/timeout/...) */- claudeOAuthLogin: () => Promise<{ ok: boolean; authorized: boolean; reason?: string }>;- /** 登出 Claude.ai 订阅(⚠️ 同时清本地 claude 的登录凭证) */- claudeOAuthLogout: () => Promise<{ authorized: boolean }>;- /** 取消进行中的浏览器 OAuth 登录流 */- claudeOAuthCancel: () => Promise<{ authorized: boolean }>;+ /** 连接本机 Claude 订阅;loginKey 用于限定取消范围。 */+ claudeOAuthLogin: (loginKey?: string) => Promise<{ ok: boolean; authorized: boolean; reason?: string }>;+ /** 断开 Cindy 使用许可,保留本机 Claude 凭证。 */+ claudeOAuthLogout: (ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }) => Promise<{ authorized: boolean }>;+ /** 取消对应登录尝试。 */+ claudeOAuthCancel: (loginKey?: string) => Promise<{ authorized: boolean }>;/** 拉起浏览器 OAuth 登录 xAI(SuperGrok 订阅);成功写 safeStorage。reason 在失败时给出 */xaiOAuthLogin: () => Promise<{ ok: boolean; authorized: boolean; reason?: string }>;/** 登出 xAI(清本机 safeStorage 的 xai 凭证) */- xaiOAuthLogout: () => Promise<{ authorized: boolean }>;+ xaiOAuthLogout: (ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }) => Promise<{ authorized: boolean }>;/** 取消进行中的 xAI 浏览器 OAuth 登录流 */xaiOAuthCancel: () => Promise<{ authorized: boolean }>;@@ -6299,13 +6301,13 @@ interface ElectronAPI {getState: (agentKind: 'claude-code' | 'codex' | 'pi') => Promise<CodexAuthState>;triggerLogin: (agentKind: 'claude-code' | 'codex' | 'pi',- options?: { mode?: 'browser' | 'device-code'; ownerId?: string },+ options?: { mode?: 'browser' | 'device-code' | 'local'; ownerId?: string },) => Promise<CodexAuthState>;cancelLogin: (agentKind: 'claude-code' | 'codex' | 'pi',options?: { releaseOwner?: boolean; ownerId?: string },) => Promise<void>;- logout: (agentKind: 'claude-code' | 'codex' | 'pi') => Promise<void>;+ logout: (agentKind: 'claude-code' | 'codex' | 'pi', ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }) => Promise<void>;onStateChanged: (cb: (s: { agentKind: 'claude-code' | 'codex' | 'pi' } & CodexAuthState) => void,) => () => void;@@ -6313,7 +6315,7 @@ interface ElectronAPI {cb: (p: {agentKind: 'claude-code' | 'codex' | 'pi';phase: string;- mode?: 'browser' | 'device-code';+ mode?: 'browser' | 'device-code' | 'local';detail?: string;verificationUrl?: string;userCode?: string;@@ -6430,6 +6432,7 @@ interface ElectronAPI {updatedAt: number;} | null,) => void,+ providerId?: string,) => () => void;/** Existing native Anthropic subscription snapshot (null means cleared). */getClaudeSubscription: (providerId?: string) => Promise<import('../shared/claudeSubscriptionUsage').ClaudeSubscriptionUsageSnapshot | null>;diff --git a/apps/desktop/src/shared/providerSecrets.ts b/apps/desktop/src/shared/providerSecrets.tsindex f422652c6d..fa5b305ec9 100644--- a/apps/desktop/src/shared/providerSecrets.ts+++ b/apps/desktop/src/shared/providerSecrets.ts@@ -28,6 +28,11 @@ export type ProviderSecretId =| 'gemini'| 'openai-images';+/** The dedicated builtin key bridge and its UI must expose the same supported IDs. */+export function isBuiltinApiKeyProviderId(providerId: unknown): providerId is ProviderSecretId {+ return providerId === 'gemini' || providerId === 'openai-images';+}+/*** providerId → safeStorage 存储键名(.enc 文件名,不含后缀)。* 改动须谨慎:键名变了等于"换文件",会让用户本机已存的 key 读不到。diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.mdindex b01c170034..1221ccf943 100644--- a/docs/design-rules/design-inventory.md+++ b/docs/design-rules/design-inventory.md@@ -38,7 +38,7 @@| `desktop.overlay.toast` | desktop | Toast | App 常驻 ToastContainer(用户可见出口,不展开业务逻辑) | Toast, ToastContainer | apps/desktop/src/renderer/components/ui/toast/Toast.tsx, apps/desktop/src/renderer/components/ui/toast/ToastContainer.tsx, apps/desktop/src/renderer/components/ui/toast/index.ts | 7 | 4 | 3 || `desktop.plugins.app-main` | desktop | 插件主视图 | hash `/apps/:ghostId`(GhostMainViewFeatureLayout) | GhostMainViewFeatureLayout, GhostMainViewHost | apps/desktop/src/renderer/features/plugin/GhostMainViewFeatureLayout.tsx, apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx | 0 | 0 | 0 || `desktop.plugins.installed` | desktop | 已装插件 | hash `/plugins`(GhostPluginPage) | AddMarketplaceDialog, GhostPluginDetailView, GhostPluginPage, MarketPluginDetailView, MyPublishesSection, PluginManagementLayout, PluginScopePicker, UpdateAllDialog | apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx, apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx, apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx, apps/desktop/src/renderer/features/plugin/plugin-motion.css | 49 | 0 | 82 |-| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSegmentedControl.tsx, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/cindyMakeVisibility.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/modelManagementPresentation.ts, apps/desktop/src/renderer/components/settings/modelManagementState.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageCharts.css, apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/useProviderSubscriptionCard.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 155 | 109 | 732 |+| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSegmentedControl.tsx, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/cindyMakeVisibility.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/modelManagementPresentation.ts, apps/desktop/src/renderer/components/settings/modelManagementState.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageCharts.css, apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/useProviderSubscriptionCard.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 155 | 109 | 733 || `desktop.shell.main-layout` | desktop | 主窗口壳(标题栏 / 左右栏 / 内容区) | main BrowserWindow → renderer/index.tsx → main-entry.tsx → App → MainLayout (`#/` 受保护壳) | ChromeActions, FeishuConflictDialogHost, GhostMediaLightboxHost, MainLayout, RightSidebar, RightSidebarShell, SessionShareImportWizard, Sidebar, UpdateNoticeDialog, WindowControls | apps/desktop/src/renderer/cindy-brain/GhostMediaLightboxHost.tsx, apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx, apps/desktop/src/renderer/components/layout/BrowserWebviewPool.tsx, apps/desktop/src/renderer/components/layout/ChromeActions.tsx, apps/desktop/src/renderer/components/layout/ContentHeader.tsx, apps/desktop/src/renderer/components/layout/CredentialStoreBanner.tsx, apps/desktop/src/renderer/components/layout/FadeSwitcher.tsx, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx, apps/desktop/src/renderer/components/layout/MainLayout.tsx, apps/desktop/src/renderer/components/layout/RightSidebar.tsx, apps/desktop/src/renderer/components/layout/RightSidebarDetach.tsx, apps/desktop/src/renderer/components/layout/RightSidebarMaximize.tsx, apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/components/layout/chromeActionsGeometry.ts, apps/desktop/src/renderer/components/layout/chromeActionsLayout.ts, apps/desktop/src/renderer/components/layout/railChromeActions.ts, apps/desktop/src/renderer/components/layout/windowDrag.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx, apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx, apps/desktop/src/renderer/components/sidebar/DatabaseSizeWarningBanner.tsx, apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx, apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx, apps/desktop/src/renderer/components/sidebar/Sidebar.tsx, apps/desktop/src/renderer/components/sidebar/SidebarIconButton.tsx, apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx, apps/desktop/src/renderer/components/sidebar/SortableList.tsx, apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx, apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx, apps/desktop/src/renderer/components/sidebar/VendorIcon.tsx, apps/desktop/src/renderer/components/sidebar/VendorReadinessBadge.tsx, apps/desktop/src/renderer/components/sidebar/WorktreeBadge.tsx, apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx, apps/desktop/src/renderer/components/title-bar/MenuButton.tsx, apps/desktop/src/renderer/components/title-bar/WindowControls.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/layout/LayoutRoot.tsx, apps/desktop/src/renderer/layout/PanelDragController.tsx, apps/desktop/src/renderer/layout/PanelDragPrototype.tsx, apps/desktop/src/renderer/layout/collapsePrefs.ts, apps/desktop/src/renderer/layout/layoutDevTools.ts, apps/desktop/src/renderer/layout/panePlacement.tsx, apps/desktop/src/renderer/layout/paneWidths.tsx, apps/desktop/src/renderer/layout/panelMaximize.tsx, apps/desktop/src/renderer/styles/globals.css | 146 | 58 | 291 || `desktop.skillhub.local` | desktop | SkillHub 本地技能 | hash `/skillhub/local` 及详情 `/skillhub/local/:kind/global/:name`、`/skillhub/local/:kind/project/:projectHash/:name` | InstallTargetPicker, PluginManagementLayout, SkillhubDetailView, SkillhubFeatureLayout, SkillhubHomeView, SkillhubMarketPreviewPanel | apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx | 41 | 0 | 66 || `desktop.skillhub.market` | desktop | SkillHub 市场 | hash `/skillhub/market`(SkillhubMarketListView) | InstallTargetPicker, MarketCard, MarketInfoEditDialog, SkillhubMarketListView, SkillhubMarketPreviewPanel, VisibilityEditorDialog | apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx, apps/desktop/src/renderer/features/skillhub/components/HomeMarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInfoEditDialog.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketLocalSkills.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketPreviewTree.tsx, apps/desktop/src/renderer/features/skillhub/components/PlatformTagSelector.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillIcon.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillTagList.tsx, apps/desktop/src/renderer/features/skillhub/components/TeamScopePicker.tsx, apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsx | 47 | 0 | 63 |diff --git a/docs/product-rules/provider-settings.md b/docs/product-rules/provider-settings.mdindex 60fb9d98ec..db5f47460b 100644--- a/docs/product-rules/provider-settings.md+++ b/docs/product-rules/provider-settings.md@@ -1,6 +1,6 @@# 供应商设置:统一身份、状态与操作-制定日期:2026-09-09。适用于现有与未来新增供应商,包括本机登录、独立授权、+制定日期:2026-09-09。适用于现有与未来新增供应商,包括本机登录、独立登录、API 接入、Cindy AI 与本地模型服务。本文定义统一合同;当前实现与验证边界见末节。视觉正本见 [DESIGN §4 Provider detail header](../design-rules/DESIGN.md#provider-detail-header)。@@ -18,7 +18,7 @@ API 接入、Cindy AI 与本地模型服务。本文定义统一合同;当前- 接入类型说明实际使用方式,例如 ChatGPT 订阅、API、本地服务;不是程序内部的存储分类。已取得实际套餐时,订阅标签显示 ChatGPT Pro、ChatGPT Plus 等套餐名;仅在套餐未知时回退到通用订阅名称。- 新增官方账号不因为存入自定义配置而显示“自定义”标签;Beta 等产品状态另有明确依据才显示。-- 副标题优先提供账号识别信息,并说明本机登录或独立授权来源;无账号信息时仅显示来源。+- 副标题优先提供账号识别信息,并说明本机登录或独立登录来源;无账号信息时仅显示来源。API 连接显示去除凭证、用户信息及敏感查询参数的服务地址。本地服务显示可识别的运行位置。- 品牌根据可信品牌资料或已有域名解析规则确定,不从用户可编辑的显示名猜测;兼容 OpenAI协议的第三方不自动视为 OpenAI 官方。@@ -30,11 +30,11 @@ API 接入、Cindy AI 与本地模型服务。本文定义统一合同;当前| 连接状态 | 顶部主要操作 | 规则 ||---|---|---|-| 未连接/未配置 | 连接/配置 | 授权或 API 表单由连接方式决定,入口位置不变 |+| 未连接/未配置 | 连接/配置 | 登录或 API 表单由连接方式决定,入口位置不变 || 连接中 | 取消(支持时) | 明示进行中;不支持取消时显示进行状态,防止重复提交 || 已连接 | 断开(支持时) | 状态和动作分开显示;不支持断开的来源不伪造按钮 || 已配置但未验证 | 验证(支持时) | 保存 API key 成功不能单独证明已连接;无验证能力时如实显示已配置 |-| 需要重新授权 | 重新连接或来源对应恢复入口 | 本机共享授权可能需要打开来源 App;说明原因与实际影响 |+| 需要重新登录 | 重新登录或使用本机账号 | 本机共享授权可能需要打开来源 App;说明原因与实际影响 || 状态读取失败 | 重试(支持时) | 保留最后已知状态并注明未更新,不能直接改成未连接 |以上为语义名称;实际界面文案沿用术语表和本地化体系,不直接输出状态枚举。@@ -51,10 +51,10 @@ API 接入、Cindy AI 与本地模型服务。本文定义统一合同;当前- 停用只阻止该连接被用于后续路由,保留凭证与配置;启用恢复该连接,不替换账号。- 断开解除当前连接的授权使用,保留供应商条目与可恢复配置;不能将删除条目称为断开。- 删除移除可删除的用户连接及其专属配置;不删除历史内容,也不静默转绑其他同品牌账号。-- 断开、删除的确认规则取决于真实影响,不取决于 builtin/custom。确认说明要点名当前连接。- 共享本机凭证若会被清除并影响其他 App,必须明确说明;只读来源不应提供无法执行的登出。-- 这次视觉收敛不修改底层凭证归属、断开范围或现有授权边界;适配前核实实际行为,不以- 更换按钮文案掩盖差异,也不额外实现系统全局登出。+- 断开、删除的确认规则取决于真实影响,不取决于 builtin/custom。确认说明点名当前连接,+ 只说明在 Cindy 中不能再使用这份订阅或 API key。Cindy 不提供退出系统 Codex 或 Claude Code 账号的操作。+- 断开的来源保留原连接 ID 与条目,原位置可以再次登录或配置;删除的来源不被后台发现自动恢复。+- 改名、断开与删除的确认绑定打开确认框时的 Cindy 账号,账号切换后旧确认不得修改新账号。## 4. 用量与扩展区域@@ -76,12 +76,13 @@ Grok 产品消耗是共享池贡献,不是独立限额,不反算成产品余在同一组内布局,长名称压缩或换行时更多按钮不会单独掉到下一行。- OpenAI 本机登录与新增账号共用顶部;独立账号和其他 OAuth 复用 `GenericOAuthHeader`,- 各自保留真实登录、取消和恢复适配。新增 OpenAI 的重命名复用既有仅修改名称的弹窗。+ 各自保留真实登录、取消和恢复适配。所有可改名来源共用名称弹窗,Main 只更新最新配置的名称。- Anthropic、xAI、API、本地服务和 Cindy AI 使用同一状态/动作槽位。API key 的存在仅显示已配置;更换 key 收入菜单。Cindy AI 按既有资产模块合同保留凭据操作在菜单中的位置。-- 可编辑自定义连接提供编辑入口(含名称);不可编辑的内置来源不新增改名存储或伪造操作。+- 本机 Codex、Claude、旧 Grok、API 连接支持改名和删除;本地模型服务支持改名及已有删除行为。+ Cindy AI 仍按托管账号规则管理,不提供改名或删除。显示名在设置、选择器、提示和用量历史中同源。- 身份、资产与授权说明保留原适配。没有权威状态来源的读取失败/验证状态不在前端编造,- 不因此次布局统一新增 IPC、数据库字段或授权检测请求。+ 不通过额外登录探测推断连接是否有效。- 回归覆盖原有深链、只读本机凭证、恢复、资产和模型列表,以及新增 OAuth 菜单、API 已配置、恢复覆盖旧连接状态、取消后的迟到授权结果。真实账号操作与双模式目检需单独记录,不以组件测试或复用主题样式代替。@@ -93,3 +94,20 @@ Grok 产品消耗是共享池贡献,不是独立限额,不反算成产品余OpenAI、Claude 和 Grok 都允许新增独立登录账号。每次新增生成唯一连接 ID,凭证、刷新、模型发现、用量和断开操作始终绑定这份连接;任务不能凭品牌或显示名选择账号。同品牌连接共用模型定义和已有 Harness 能力,账号发现只约束该连接的可用模型。重命名只修改显示名,断开或删除一份连接不影响同品牌其他账号及历史消息。已有本机连接继续保留;新增 Claude 和 Grok 登录写入 Cindy 的账号专属凭证存储,不覆盖本机 Claude Code 或旧 Grok 连接。远程执行沿用各 Harness 已有能力边界,Grok 的 Pi 远程请求经主机代理使用所选连接,凭证不写到远端。++本机 Codex 连接的「断开」只停止 Cindy 使用该账号,保留本机登录凭证与历史记录;开发版与正式版一致。断开状态跨重启保留,自动发现不能重新启用。用户再次选择使用本机账号时恢复连接,无需网页授权。Cindy 不提供退出本机 Codex 账号的操作。++本机 Codex 供应商支持改名和删除:名称只用于展示,内部连接 ID 不变;删除先断开 Cindy 对该订阅的使用,再从供应商列表移除。显示名称与删除状态按 Cindy 数据所有者保存。添加供应商仍提供本机账号入口,重新添加后恢复显示;本机凭证与历史消息不删除。++## 7. 登录与管理文案++- 新增独立订阅账号:统一「登录独立账号」。已存在的连接用「登录」,失效后用「重新登录」。+- 复用系统登录:明确「使用本机 Codex 账号」或「使用本机 Claude Code 账号」。+- API 入口统一「API key 接入」。保存成功表示「已配置」,不能声称已经验证。+- 「授权」只用于浏览器权限确认、设备授权码和 OAuth 端点等确实涉及授权的步骤。+- 状态统一「已连接/未连接/连接中」;管理动作统一「重命名/编辑连接设置/停用/启用/断开/删除」。+- 断开保留连接以便恢复;删除不删除历史,也不承诺自动把原任务改用其他供应商。+- 本机 Claude 与 Codex 均只撤销 Cindy 的使用许可;重新使用本机账号直接读取现有登录,无需新开浏览器。+- 本机 Claude 刷新被服务端明确拒绝时,仅在现有绑定文件记录该次凭证的 SHA-256 摘要。+ 重启或手动断开不清除这个标记;同一凭证不能重新连接,来源工具更新凭证或更换账号后可重新连接。+ 不删除系统凭证,不新增凭证明文副本,不为正常手动断开后的恢复增加网络验证。diff --git a/packages/anthropic-responses-bridge/src/handler.ts b/packages/anthropic-responses-bridge/src/handler.tsindex 96c0a9ab55..531722df19 100644--- a/packages/anthropic-responses-bridge/src/handler.ts+++ b/packages/anthropic-responses-bridge/src/handler.ts@@ -458,7 +458,7 @@ export function createResponsesHandler(opts: ResponsesHandlerOptions): Responsesconst rateLimit = parseRateLimitHeaders(upstream.headers);if (rateLimit) {try {- provider.onRateLimit(rateLimit);+ provider.onRateLimit(rateLimit, providerHeaders);} catch {/* 回调异常不影响流转发 */}diff --git a/packages/anthropic-responses-bridge/src/types.ts b/packages/anthropic-responses-bridge/src/types.tsindex 0dc0982dff..34b830c755 100644--- a/packages/anthropic-responses-bridge/src/types.ts+++ b/packages/anthropic-responses-bridge/src/types.ts@@ -226,7 +226,7 @@ export interface BridgeProviderConfig {* 上游响应头里的 `x-ratelimit-*` 限流信息(标准 OpenAI 风格,api.x.ai 返回;codex 后端不返)。* 每个成功上游响应解析后回调一次;缺头 → 不回调。回调抛错被吞(不影响流转发)。*/- onRateLimit?: (info: UpstreamRateLimitInfo) => void;+ onRateLimit?: (info: UpstreamRateLimitInfo, requestHeaders: Readonly<Record<string, string>>) => void;}/** 上游 `x-ratelimit-*` 响应头解析结果(仅数值可解析的字段;全 undefined 时不回调)。 */diff --git a/packages/maker-core/src/interfaces/auth-adapter.ts b/packages/maker-core/src/interfaces/auth-adapter.tsindex 26922d4231..cc7d70c967 100644--- a/packages/maker-core/src/interfaces/auth-adapter.ts+++ b/packages/maker-core/src/interfaces/auth-adapter.ts@@ -9,7 +9,7 @@import type { AuthState } from '../types/common.js';export type AgentCredentialMode = 'gateway-key' | 'oauth-bearer' | 'provider-oauth';-export type AgentLoginMode = 'browser' | 'device-code';+export type AgentLoginMode = 'browser' | 'device-code' | 'local';export interface AuthLoginOptions {mode?: AgentLoginMode;diff --git a/packages/model-providers/src/registry.ts b/packages/model-providers/src/registry.tsindex 9aca8b31dd..7d2dbf6072 100644--- a/packages/model-providers/src/registry.ts+++ b/packages/model-providers/src/registry.ts@@ -94,6 +94,8 @@ export type ModelDiscoveryFailureState = Partial</** 供应商 + 连接状态。 */export interface ProviderView extends Provider {+ /** Definition remains available for adding a removed local connection again. */+ removed?: boolean;subscriptionAccount?: { source: 'local' | 'oauth' | 'unknown'; identity?: string; reconnectRequired?: boolean };/** Public account identity and credential origin, never credential material. */openAiAccount?: { source: 'local' | 'oauth' | 'unknown'; identity?: string; reconnectRequired?: boolean };