Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): 修 revoked 不丢别人的归属,刷新故障不误判授权失效,失败态不进自动校准

Dash3ab8ba6375cc
diff --git a/apps/desktop/src/main/im/discord/sessionAuth.ts b/apps/desktop/src/main/im/discord/sessionAuth.ts
index 5d28410d38..0dab401f35 100644
--- a/apps/desktop/src/main/im/discord/sessionAuth.ts
+++ b/apps/desktop/src/main/im/discord/sessionAuth.ts
@@ -6,6 +6,7 @@ import type { ProviderView } from '@cindy/model-providers';
import { createLogger } from '../../logger';
import { getMaker } from '../../maker-host';
import { getDesktopProviderService } from '../../maker-host/createDesktopProviderService';
+import { assertTrustedAppRendererEvent } from '../../security/trustedAppRenderer';
import { hasCustomProviderKey } from '../../maker-host/provider-route';
import {
resolveImSessionDefaults,
@@ -75,7 +76,13 @@ export async function checkDiscordSessionAuth(
export function registerDiscordSessionAuthIpc(config: ImOrchestratorConfig): void {
if (registered) return;
registered = true;
- ipcMain.handle(DISCORD_SESSION_AUTH_CHECK_CHANNEL, async () => checkDiscordSessionAuth(config));
+ ipcMain.handle(DISCORD_SESSION_AUTH_CHECK_CHANNEL, async (event) => {
+ // 这条通道读连接态时会放行本机绑定自愈(写绑定文件、协调 Codex 凭证硬链、发起带凭证的
+ // Anthropic 清单发现),不该被子 frame / WebView 触发。只有设置页会调它,不在 device-link
+ // allowlist 里,可以直接用会抛的守卫(PR #548 review)。
+ assertTrustedAppRendererEvent(event);
+ return checkDiscordSessionAuth(config);
+ });
}
function createDefaultAuthDeps(): ImAuthCheckDeps {
diff --git a/apps/desktop/src/main/maker-host/__tests__/anthropicModelDiscovery.test.ts b/apps/desktop/src/main/maker-host/__tests__/anthropicModelDiscovery.test.ts
index 1b8fc7085f..db921a23a9 100644
--- a/apps/desktop/src/main/maker-host/__tests__/anthropicModelDiscovery.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/anthropicModelDiscovery.test.ts
@@ -1057,6 +1057,26 @@ describe('HTTP 发现失败的归因与选择性重试', () => {
expect(getAnthropicModelDiscoveryFailure()).toBeNull();
});
+ it('401 后强制刷新自身故障归 upstream(不是 unauthorized),重试链继续', async () => {
+ // token 端点超时 / 5xx / 拿不到刷新锁 ≠ 授权被拒。归 unauthorized 会取消全部重试、
+ // 还叫用户去断开重连,而 refresh token 很可能完全有效(PR #548 review)。
+ const fetchMock = vi.fn().mockResolvedValueOnce(errorResponse(401)).mockResolvedValue(okResponse);
+ vi.stubGlobal('fetch', fetchMock);
+ oauthRefreshMock.getValidClaudeAiOAuth
+ .mockResolvedValueOnce({ accessToken: 'test-token' }) // 首次取 token
+ .mockRejectedValueOnce(new Error('token endpoint 503')) // 强制刷新失败
+ .mockResolvedValue({ accessToken: 'test-token-2' });
+
+ await refreshAnthropicModelsFromHttp();
+ const failure = getAnthropicModelDiscoveryFailure();
+ expect(failure?.kind).toBe('upstream');
+ expect(failure?.detail).toContain('token refresh failed');
+
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(anthropicIds()).toEqual(['claude-opus-4-8']);
+ expect(getAnthropicModelDiscoveryFailure()).toBeNull();
+ });
+
it('暂时性失败(连不上)自动重试,成功即生效并清失败态', async () => {
const fetchMock = vi
.fn()
diff --git a/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts b/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts
index cf2bd6352a..104a9aeadf 100644
--- a/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts
@@ -232,6 +232,26 @@ describe('claimDetectedNativeProviderAuth', () => {
expect(isNativeProviderAuthBound('anthropic')).toBe(true);
});
+ it('修 revoked 时保住别人的归属,并对其余 provider 保守抑制', () => {
+ // 直接重写成「只有本次授权的这家」会抹掉 openai 的 owner-b,那份残留凭证下一次就会被
+ // 认领给 owner-a —— 用一次修复换来一个新的越权口子(PR #548 review)。
+ fs.mkdirSync(userDataDir, { recursive: true });
+ fs.writeFileSync(bindingFile, JSON.stringify({ openai: 'owner-b', revoked: 1 }));
+
+ bindNativeProviderAuth('anthropic');
+ const after = JSON.parse(fs.readFileSync(bindingFile, 'utf8'));
+ expect(after.openai).toBe('owner-b'); // 别人的归属原样保留
+ expect(after.anthropic).toBe('owner-a');
+
+ // 坏掉的 revoked 无从得知谁被撤销过,不能直接丢弃(丢弃 = 给所有残留凭证放行)。
+ expect(after.revoked).toMatchObject({ openai: 'owner-a', xai: 'owner-a' });
+ expect(after.revoked).not.toHaveProperty('anthropic');
+ expect(claimDetectedNativeProviderAuth('xai', () => true)).toBe(false);
+ // 本次授权的这家不受抑制,且 owner-b 的 openai 依然轮不到 owner-a。
+ expect(isNativeProviderAuthBound('anthropic')).toBe(true);
+ expect(isNativeProviderAuthBound('openai')).toBe(false);
+ });
+
it('文件确实不存在 = 合法首次状态,照常认领', () => {
// 与「读失败」必须分开:ENOENT 是全新安装的正常形态,挡掉它等于把自动继承整条废掉。
expect(fs.existsSync(bindingFile)).toBe(false);
diff --git a/apps/desktop/src/main/maker-host/auth-adapters.ts b/apps/desktop/src/main/maker-host/auth-adapters.ts
index bdf61971fd..5ff8954bb8 100644
--- a/apps/desktop/src/main/maker-host/auth-adapters.ts
+++ b/apps/desktop/src/main/maker-host/auth-adapters.ts
@@ -46,7 +46,11 @@ import {
terminateCodexLoginProcess,
} from './codex-auth-state.js';
import { CODEX_GATEWAY_ENV_KEY, CODEX_PROVIDER_OAUTH_PLACEHOLDER_KEY } from './codex-gateway-config.js';
-import { clearClaudeAiOAuth, hasClaudeAiOAuth } from './claude-credentials-store.js';
+import {
+ clearClaudeAiOAuth,
+ hasClaudeAiOAuth,
+ hasClaudeAiOAuthUnbound,
+} from './claude-credentials-store.js';
import {
disconnectClaudeAiOAuth,
getClaudeAiOAuthForSpawn,
@@ -303,7 +307,18 @@ export class DesktopClaudeAuthAdapter implements AuthAdapter {
invalidateClaudeOAuthRefresh();
try {
if (hasClaudeAiOAuth()) clearClaudeAiOAuth();
- unbindNativeProviderAuth('anthropic');
+ // 凭证删除是 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),
diff --git a/apps/desktop/src/main/maker-host/model-discovery/anthropic.ts b/apps/desktop/src/main/maker-host/model-discovery/anthropic.ts
index 94ce245dc5..f756b140e3 100644
--- a/apps/desktop/src/main/maker-host/model-discovery/anthropic.ts
+++ b/apps/desktop/src/main/maker-host/model-discovery/anthropic.ts
@@ -974,10 +974,27 @@ export function refreshAnthropicModelsFromHttp(options?: {
// 一次就能恢复 —— 否则用户明明只需静默续期,却被告知要断开重连,而且清单为空时他
// 连个能用的模型都挑不出来(PR #548 review;运行时 401 回调走的也是这条路)。
if (kind === 'unauthorized' && !options?.afterForcedRefresh) {
+ let refreshError: unknown = null;
const refreshed = await getValidClaudeAiOAuth({
forceRefresh: true,
staleToken: oauth.accessToken,
- }).catch(() => null);
+ }).catch((err: unknown) => {
+ refreshError = err;
+ return null;
+ });
+ // 刷新链路自己出故障(token 端点超时 / 5xx / 拿不到刷新锁)不等于「授权被拒」。归
+ // unauthorized 会取消全部重试、并叫用户去断开重连,可 refresh token 很可能完全有效,
+ // 过一会儿再刷就成了 —— 那期间用户白白守着一份空清单(PR #548 review)。
+ if (refreshError !== null) {
+ noteDiscoveryFailure(
+ gen,
+ 'upstream',
+ `401 then forced token refresh failed: ${
+ refreshError instanceof Error ? refreshError.message : String(refreshError)
+ }`,
+ );
+ return;
+ }
if (
refreshed?.accessToken &&
refreshed.accessToken !== oauth.accessToken &&
diff --git a/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts b/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts
index 949c8ff944..614a59d704 100644
--- a/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts
+++ b/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts
@@ -5,6 +5,7 @@ import path from 'node:path';
import { getActiveAppSession, isAppSessionBoundaryPending } from '../appSessionState.js';
type NativeProviderId = 'anthropic' | 'openai' | 'xai';
+const NATIVE_PROVIDER_IDS = ['anthropic', 'openai', 'xai'] as const satisfies readonly NativeProviderId[];
type BindingFile = Partial<Record<NativeProviderId, string>> & {
legacyClaimOwner?: string;
/**
@@ -34,7 +35,14 @@ function bindingPath(): string {
* 把共享 keychain 里的凭证判给当前账号,而且随后的 writeBindings 会把损坏文件连同
* 里面原有的归属一起覆盖掉,永久失去恢复依据(PR #548 review)。
*/
-function readBindingsOrFail(): { ok: true; bindings: BindingFile } | { ok: false } {
+type BindingRead =
+ | { ok: true; bindings: BindingFile }
+ /** 文件本身读不出来 / 根不是对象:整份归属都无从判断,没有可挽救的部分。 */
+ | { ok: false; reason: 'unreadable' }
+ /** 根有效、各 provider 归属可信,只有 revoked 这个字段被改坏。 */
+ | { ok: false; reason: 'badRevoked'; bindings: Omit<BindingFile, 'revoked'> };
+
+function readBindingsOrFail(): BindingRead {
let raw: string;
try {
raw = fs.readFileSync(bindingPath(), 'utf8');
@@ -42,22 +50,29 @@ function readBindingsOrFail(): { ok: true; bindings: BindingFile } | { ok: false
// 文件不存在 = 合法的首次状态(还没有任何人绑定过);其它读失败(EACCES / EIO 等)
// 说明归属不明,不能当成空。
if ((err as NodeJS.ErrnoException | null)?.code === 'ENOENT') return { ok: true, bindings: {} };
- return { ok: false };
+ return { ok: false, reason: 'unreadable' };
}
try {
const value = JSON.parse(raw) as unknown;
- if (!value || typeof value !== 'object' || Array.isArray(value)) return { ok: false };
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ return { ok: false, reason: 'unreadable' };
+ }
// revoked 也要验型:下游用 `provider in bindings.revoked` 判定,而 `in` 的右操作数是
// 原始值时直接抛 TypeError —— 一个被手工修坏的字段会让认领、迁移、登出乃至重新授权
- // 全部炸在这里(PR #548 review)。同样按不可读处理:只读判定退到 fail-closed,用户再次
- // 显式授权时 bindNativeProviderAuth 会重写整份文件,自然修好。
+ // 全部炸在这里(PR #548 review)。
+ //
+ // 但坏的只是这一个字段:同一份文件里各 provider 的归属仍然是可信的,要单独交出来。
+ // 认领 / 迁移 / 登出照样得 fail-closed(不知道谁被撤销过就不能认领),而显式授权可以
+ // 只修 revoked、保住其余归属 —— 否则一次「修复」会把别人的 owner 抹掉,反倒开出新的
+ // 误认领口子(PR #548 review)。
const revoked = (value as { revoked?: unknown }).revoked;
if (revoked !== undefined && (typeof revoked !== 'object' || revoked === null || Array.isArray(revoked))) {
- return { ok: false };
+ const { revoked: _bad, ...rest } = value as BindingFile;
+ return { ok: false, reason: 'badRevoked', bindings: rest };
}
return { ok: true, bindings: value as BindingFile };
} catch {
- return { ok: false };
+ return { ok: false, reason: 'unreadable' };
}
}
@@ -88,14 +103,35 @@ export function isNativeProviderAuthBound(provider: NativeProviderId): boolean {
export function bindNativeProviderAuth(provider: NativeProviderId): void {
const owner = getActiveAppSession().dataOwnerId;
if (!owner) throw new Error('cannot bind native provider auth without an active data owner');
- const bindings = readBindings();
- // 显式授权 = 用户重新表达了「我要连它」,撤销标记就此作废。
- if (bindings.revoked && provider in bindings.revoked) {
- const revoked = { ...bindings.revoked };
- delete revoked[provider];
- bindings.revoked = revoked;
+ const read = readBindingsOrFail();
+ if (read.ok) {
+ const bindings = read.bindings;
+ // 显式授权 = 用户重新表达了「我要连它」,撤销标记就此作废。
+ if (bindings.revoked && provider in bindings.revoked) {
+ const revoked = { ...bindings.revoked };
+ delete revoked[provider];
+ bindings.revoked = revoked;
+ }
+ writeBindings({ ...bindings, [provider]: owner });
+ return;
}
- writeBindings({ ...bindings, [provider]: owner });
+ if (read.reason === 'badRevoked') {
+ // 只有 revoked 坏掉:各 provider 的归属仍然可信,必须原样保留 —— 直接重写成「只有本次
+ // 授权的这一家」会抹掉别人的 owner,那份凭证下一次就会被自动认领给当前账号,等于用一次
+ // 修复换来一个新的越权口子(PR #548 review)。
+ //
+ // 坏掉的 revoked 无法得知谁被撤销过,不能简单丢弃(丢弃 = 给所有残留凭证放行)。保守重建:
+ // 除本次显式授权的这家外,其余 native provider 一律按「撤销过」对待,自动继承就此关闭,
+ // 用户对它们各自显式授权即可恢复。
+ const rebuilt: Partial<Record<NativeProviderId, string>> = {};
+ for (const other of NATIVE_PROVIDER_IDS) {
+ if (other !== provider) rebuilt[other] = owner;
+ }
+ writeBindings({ ...read.bindings, revoked: rebuilt, [provider]: owner });
+ return;
+ }
+ // 整份都读不出来:没有可保留的归属,只能重写。用户此刻正显式授权,不写等于连不上。
+ writeBindings({ [provider]: owner });
}
/**
@@ -144,7 +180,7 @@ export function migrateLegacyNativeProviderAuthBindings(
if (bindings.legacyClaimOwner) return;
const next: BindingFile = { ...bindings, legacyClaimOwner: ownerId };
- for (const provider of ['anthropic', 'openai', 'xai'] as const) {
+ for (const provider of NATIVE_PROVIDER_IDS) {
// 显式登出过的 provider 一律跳过:这条一次性迁移同样不能把用户弃用掉的残留凭证
// 认领回来(PR #548 review)。
if (bindings.revoked && provider in bindings.revoked) continue;
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index 6ca2697fb6..c1d8903006 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -582,22 +582,39 @@ export function NewMakerDraftRoute() {
effectiveRemoteHostId,
modelVisibilityVersion,
]);
+ /**
+ * **自动**选择用的候选:再剔掉清单发现失败的供应商。
+ *
+ * 失败时我们刻意保留上次成功的清单(设置页也已改口径,明说那是上次获取的结果),但那份
+ * 清单只适合「用户自己点进去选」,不适合当成默认值送人:unauthorized / regionBlocked 这
+ * 类确定性失败下,把从没选过模型的用户自动落到这个来源,首条消息必然失败 —— 正是这套
+ * 校准要消灭的状态(PR #548 review)。
+ *
+ * 用户显式表达过(选过模型、或存了显式来源)时不做这层剔除:他选的就该生效,而且来源解析
+ * 也必须还能指到那个供应商。全部供应商都在失败态时同样退回完整候选 —— 那时没有更好的
+ * 选择,给个陈旧清单也好过一个都挑不出来。
+ */
+ const draftModelChosenByUser = draft.modelChosenByVendor[draft.vendor] === true;
+ const autoCalibrationProviders = useMemo(() => {
+ if (draftModelChosenByUser || chatPrefs.providerId) return calibrationProviders;
+ const healthy = calibrationProviders.filter((p) => !p.modelDiscoveryFailure);
+ return healthy.length > 0 ? healthy : calibrationProviders;
+ }, [calibrationProviders, draftModelChosenByUser, chatPrefs.providerId]);
const calibratedDraftModel = useMemo(() => {
if (isDeviceLinkDraft) return chatPrefs.model;
return calibrateDraftModel({
- providers: calibrationProviders,
+ providers: autoCalibrationProviders,
agent: capabilityAgentKind,
model: chatPrefs.model,
- chosenByUser: draft.modelChosenByVendor[draft.vendor] === true,
+ chosenByUser: draftModelChosenByUser,
providersLoading: localProvidersLoading,
});
}, [
isDeviceLinkDraft,
- calibrationProviders,
+ autoCalibrationProviders,
capabilityAgentKind,
chatPrefs.model,
- draft.modelChosenByVendor,
- draft.vendor,
+ draftModelChosenByUser,
localProvidersLoading,
]);
@@ -607,7 +624,11 @@ export function NewMakerDraftRoute() {
// 于是 providerId 落 null、main 挑到被排除的原生默认,而 ChatInput 看到的是允许的
// 那个来源、Send 照常放行,最后在远端失败(PR #548 review)。
// device-link 草稿以被控端目录为准,不参与本地过滤。
- const source = isDeviceLinkDraft ? providers : calibrationProviders;
+ //
+ // 用与挑模型同一份候选:自动路径已剔除失败态供应商,来源解析若还看得见它们,就会把刚
+ // 挑好的健康模型重新指回那个已知失败的原生默认来源(PR #548 review)。用户显式表达过时
+ // autoCalibrationProviders 本身就等于完整候选,不受影响。
+ const source = isDeviceLinkDraft ? providers : autoCalibrationProviders;
return effectiveSourceIdForModel(
source,
chatPrefs.providerId ?? null,
@@ -617,7 +638,7 @@ export function NewMakerDraftRoute() {
}, [
isDeviceLinkDraft,
providers,
- calibrationProviders,
+ autoCalibrationProviders,
capabilityAgentKind,
chatPrefs.providerId,
calibratedDraftModel,