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): 只读通道不再触发 codex reconcile,退化快照清掉过期失败态

Dash1ca21d7db0a3
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 003406de0a..b9dc146f5f 100644
--- a/apps/desktop/src/main/maker-host/__tests__/anthropicModelDiscovery.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/anthropicModelDiscovery.test.ts
@@ -1246,6 +1246,52 @@ describe('HTTP 发现失败的归因与选择性重试', () => {
}
});
+ it('快照被退化守卫拒绝 = 上游已经答了,过期的失败理由必须一起清掉', async () => {
+ // 有旧清单 + 上一轮记了 network:此刻上游其实已经能连上,只是这次回来的快照太短被守卫
+ // 挡下、旧清单原样留用 —— 用户手里明明有模型可选,UI 却还挂着「连不上」;而这条早退路径
+ // 既不记新失败也不排重试,过期理由会一直挂到下次成功发现(PR #548 review)。
+ const model = (id: string) => ({ id, display_name: id, type: 'model' });
+ const wide = {
+ ok: true,
+ json: async () => ({
+ data: ['claude-opus-4-8', 'claude-sonnet-4-8', 'claude-haiku-4-8', 'claude-opus-4-7'].map(model),
+ has_more: false,
+ }),
+ };
+ const shrunk = {
+ ok: true,
+ json: async () => ({ data: [model('claude-opus-4-8')], has_more: false }),
+ };
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(wide)
+ .mockRejectedValueOnce(new TypeError('fetch failed'))
+ .mockResolvedValue(shrunk);
+ vi.stubGlobal('fetch', fetchMock);
+
+ await refreshAnthropicModelsFromHttp();
+ expect(anthropicIds()).toHaveLength(4);
+
+ await refreshAnthropicModelsFromHttp();
+ expect(getAnthropicModelDiscoveryFailure()?.kind).toBe('network');
+
+ const onFailureChanged = vi.fn();
+ setAnthropicDiscoveryFailureListener(onFailureChanged);
+ try {
+ // network 排的重试到点 —— 这次上游答了,但快照退化被拒。
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(anthropicIds()).toHaveLength(4); // 旧清单保住
+ expect(getAnthropicModelDiscoveryFailure()).toBeNull();
+ expect(onFailureChanged).toHaveBeenCalled();
+ } finally {
+ setAnthropicDiscoveryFailureListener(null);
+ }
+ // 失败态已清 = 重试链也停了,不再按退避空转打网络。
+ const callsSoFar = fetchMock.mock.calls.length;
+ await vi.advanceTimersByTimeAsync(600_000);
+ expect(fetchMock).toHaveBeenCalledTimes(callsSoFar);
+ });
+
it('登出 / 换号清掉失败态与待执行的重试', async () => {
const fetchMock = vi.fn().mockRejectedValue(new TypeError('fetch failed'));
vi.stubGlobal('fetch', fetchMock);
diff --git a/apps/desktop/src/main/maker-host/__tests__/nativeProviderConnectionClaim.test.ts b/apps/desktop/src/main/maker-host/__tests__/nativeProviderConnectionClaim.test.ts
index 60cd46900b..afcbb3e9e9 100644
--- a/apps/desktop/src/main/maker-host/__tests__/nativeProviderConnectionClaim.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/nativeProviderConnectionClaim.test.ts
@@ -19,6 +19,8 @@ const h = vi.hoisted(() => ({
grokCredentialPresent: true,
refreshAnthropicModels: vi.fn(),
loadAnthropicDiskCache: vi.fn(async () => {}),
+ codexLoginWithSideEffects: vi.fn(async () => false),
+ codexLoginReadOnly: vi.fn(() => false),
anthropicDiscoveryFailure: null as {
kind: string;
at: string;
@@ -60,9 +62,15 @@ vi.mock('../model-discovery/anthropic.js', () => ({
getAnthropicModelDiscoveryFailure: () => h.anthropicDiscoveryFailure,
}));
+// hasCodexOAuthLogin 在真实实现里会经 getAccessToken 触发 reconcile(建硬链 + 写绑定);
+// ReadOnly 变体是它的纯读同侪。这里用计数区分两条路径分别被谁调用。
vi.mock('../auth-adapters.js', () => ({
readClaudeApiKey: () => null,
- desktopCodexAuthAdapter: { hasCodexOAuthLogin: () => false, hasCodexOAuthLoginUnbound: () => false },
+ desktopCodexAuthAdapter: {
+ hasCodexOAuthLogin: h.codexLoginWithSideEffects,
+ hasCodexOAuthLoginReadOnly: h.codexLoginReadOnly,
+ hasCodexOAuthLoginUnbound: () => false,
+ },
}));
vi.mock('../../authManager.js', () => ({ getAuthState: () => ({ mode: 'local' as const, user: null }) }));
@@ -100,6 +108,8 @@ beforeEach(() => {
h.anthropicDiscoveryFailure = null;
h.refreshAnthropicModels.mockClear();
h.loadAnthropicDiskCache.mockClear();
+ h.codexLoginWithSideEffects.mockClear();
+ h.codexLoginReadOnly.mockClear();
});
afterEach(() => {
@@ -144,6 +154,18 @@ describe('native provider connection claim on read', () => {
expect(h.refreshAnthropicModels).toHaveBeenCalledTimes(1);
});
+ it('openai 同样按 sender 分流:不受信只读,不触发 reconcile 的硬链与绑定写入', async () => {
+ // hasCodexOAuthLogin 会经 getAccessToken 走 reconcileWithSystemCodex —— 建凭证硬链 +
+ // 为首个 owner 补写绑定。判据不是「有没有发上游请求」,而是「不受信 sender 能不能引发
+ // 特权状态变更」(PR #548 review)。
+ await connectedMap(false);
+ expect(h.codexLoginReadOnly).toHaveBeenCalled();
+ expect(h.codexLoginWithSideEffects).not.toHaveBeenCalled();
+
+ await connectedMap(true);
+ expect(h.codexLoginWithSideEffects).toHaveBeenCalled();
+ });
+
it('凭证不在本机时既不认领也不误报已连接', async () => {
h.claudeCredentialPresent = false;
h.grokCredentialPresent = false;
diff --git a/apps/desktop/src/main/maker-host/auth-adapters.ts b/apps/desktop/src/main/maker-host/auth-adapters.ts
index 9d226e3481..bdf61971fd 100644
--- a/apps/desktop/src/main/maker-host/auth-adapters.ts
+++ b/apps/desktop/src/main/maker-host/auth-adapters.ts
@@ -1244,6 +1244,25 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
return (await this.getAccessToken()) != null;
}
+ /**
+ * 纯读版连接态 —— 不触发 reconcile,因此不建硬链、不写绑定文件、不碰 invalidation marker。
+ *
+ * 给 `maker:provider:list` 里「sender 不可信」的那条降级路径用:hasCodexOAuthLogin() 会经
+ * getAccessToken 走一次 reconcileWithSystemCodex,那里既会把本机 CLI 凭证硬链进 codex-home,
+ * 又会为首个 owner 补写 openai 绑定 —— 一个本该只读的查询,不该被子 frame / WebView 或
+ * device-link 合成 event 用来触发这种特权变更(PR #548 review)。
+ *
+ * 判定只会比自愈版**更保守**:durable 登出标记、内存 invalidation、未绑定当前 owner 一律
+ * 返回 false;差别仅在于「本来会被这次 reconcile 补上的绑定」这里看不到,于是显示未连接。
+ */
+ hasCodexOAuthLoginReadOnly(): boolean {
+ if (this.oauthInvalidatedReason) return false;
+ if (!isNativeProviderAuthBound('openai')) return false;
+ const authPath = path.join(this.codexHome, 'auth.json');
+ if (shouldSuppressLocalCodexAuth(this.codexHome, authPath)) return false;
+ return this.hasCodexOAuthLoginUnbound();
+ }
+
/** Legacy upgrade probe; only used while claiming the first verified owner. */
hasCodexOAuthLoginUnbound(): boolean {
try {
diff --git a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
index 0d3909b72e..c85b177a70 100644
--- a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
+++ b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
@@ -360,9 +360,14 @@ export function getDesktopProviderService(): ProviderService {
});
return hasClaudeAiOAuth();
},
- // openai 的自愈挂在 adapter 的 reconcile 收口里(#294 既有形态,不经这里的开关):
- // 它只做本机凭证文件的硬链协调 + 绑定写入,不发起任何带凭证的上游请求。
- openai: () => desktopCodexAuthAdapter.hasCodexOAuthLogin(),
+ // openai 的自愈挂在 adapter 的 reconcile 收口里(#294 既有形态),这里同样要受开关约束:
+ // hasCodexOAuthLogin() 经 getAccessToken 触发 reconcileWithSystemCodex,它会把本机 CLI
+ // 凭证硬链进 codex-home 并为首个 owner 补写绑定 —— 判据不是「有没有发上游请求」,而是
+ // 「不受信 sender 能不能引发特权状态变更」,建硬链和写绑定都在其内(PR #548 review)。
+ openai: ({ allowSideEffects }) =>
+ allowSideEffects
+ ? desktopCodexAuthAdapter.hasCodexOAuthLogin()
+ : desktopCodexAuthAdapter.hasCodexOAuthLoginReadOnly(),
xai: ({ allowSideEffects }) => {
if (allowSideEffects) claimNativeProviderAuthOnRead('xai', hasGrokOAuthLoginUnbound);
return hasGrokOAuthLogin();
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 bf768c6744..10c8bc20f9 100644
--- a/apps/desktop/src/main/maker-host/model-discovery/anthropic.ts
+++ b/apps/desktop/src/main/maker-host/model-discovery/anthropic.ts
@@ -848,6 +848,21 @@ function noteDiscoveryFailure(
cancelHttpRetry();
}
+/**
+ * 清掉失败态与待执行的重试 —— 用于「上游已经答了、且用户手里确有可用清单」的所有出口,
+ * 不只是清单被成功替换的那一条。
+ *
+ * 失败态**由有变无也要通知**:applyModels 只在清单真的变了时才 markChanged 广播,而
+ * 「上次失败、这次成功且清单与上次一致」正好落在它的 early return 里;快照被 shrink 守卫
+ * 拒绝时更是连 applyModels 都不会走到。不在这里通知,UI 会继续显示已经不成立的失败理由。
+ */
+function clearDiscoveryFailure(): void {
+ const hadFailure = lastFailure !== null;
+ lastFailure = null;
+ cancelHttpRetry();
+ if (hadFailure) notifyFailureChanged();
+}
+
/**
* 注册失败态变化的收口(desktop host 装配时接广播;传 null 解绑)。监听器不可抛 ——
* 广播失败不该反过来打断发现流程。
@@ -1000,6 +1015,10 @@ export function refreshAnthropicModelsFromHttp(options?: {
log.warn(
`anthropic /v1/models response looks degenerate (${lastApplied.length} -> ${mapped.length}); keeping current list (streak ${httpShrinkStreak}/${CONFIRMED_SHRINK_STREAK})`,
);
+ // 快照被拒 ≠ 发现失败:上游确确实实答了,而且旧清单原样留用 —— 此刻供应商对用户是可用的。
+ // 若还挂着上一次的 network / timeout 理由,UI 就会对着一个有模型可选的供应商说「连不上」;
+ // 而这条早退路径既不记新失败也不排重试,那个过期理由会一直挂到下次成功发现(PR #548 review)。
+ clearDiscoveryFailure();
return;
}
for (const { model, explicitContextWindow } of mapped) {
@@ -1011,14 +1030,7 @@ export function refreshAnthropicModelsFromHttp(options?: {
log.info(`anthropic models refreshed via HTTP: ${models.length}`);
// 拿到有效清单 = 发现已恢复,清掉失败态与待执行的重试(放在 apply 之前:apply 只负责
// 生效,它因世代变化被 gate 掉时新世代会带着自己的触发重来)。
- //
- // 失败态由有变无也要通知:apply 只在**清单真的变了**时才 markChanged 广播,而「上次
- // 失败、这次成功且清单与上次一致」正好落在它的 early return 里 —— 不在这里通知,UI 会
- // 继续显示已经不成立的失败理由。
- const hadFailure = lastFailure !== null;
- lastFailure = null;
- cancelHttpRetry();
- if (hadFailure) notifyFailureChanged();
+ clearDiscoveryFailure();
await applyModels(models, true, gen, explicitEffortIds, explicitFastModeIds);
})().finally(() => {
// 只清自己的登记:世代变化后可能已有新 flight 顶替,不能误清。
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
index e333436660..25293d2465 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
@@ -66,6 +66,9 @@ function makeDeps(over: Partial<ProviderHandlerDeps> = {}): ProviderHandlerDeps
testConnection: vi.fn(async () => ({ ok: true, latencyMs: 1 })),
fetchModels: vi.fn(async () => ({ ok: true, models: [{ id: 'm1', name: 'M1' }] })),
rediscoverModels: vi.fn(async () => null),
+ // 生产恒定接线(register.ts)。默认桩 = 已接线且信任,好让其余用例只关心自己的分支;
+ // 「漏接线」是独立用例,显式不传这个 dep。
+ assertTrustedSender: vi.fn(() => {}),
oauthLogin: vi.fn(async () => ({ ok: true })),
oauthLogout: vi.fn(async () => {}),
oauthCancel: vi.fn(() => {}),
@@ -128,6 +131,19 @@ describe('provider:models-rediscover handler', () => {
expect(deps.rediscoverModels).not.toHaveBeenCalled();
});
+ it('守卫未接线时 fail-closed,不靠可选链静默放行', async () => {
+ // 可选依赖漏接是没有任何信号的退化:`deps.assertTrustedSender?.()` 会让这条带凭证的
+ // 通道退回无守卫状态。缺守卫即拒绝(PR #548 review)。
+ const harness = new IpcHarness();
+ const deps = makeDeps({ assertTrustedSender: undefined });
+ registerProviderHandlers(harness, deps);
+
+ await expect(
+ harness.invoke(MAKER_INVOKE.PROVIDER_MODELS_REDISCOVER, 'anthropic'),
+ ).rejects.toThrow(/PERMISSION_DENIED/);
+ expect(deps.rediscoverModels).not.toHaveBeenCalled();
+ });
+
it('成功时返回 ok 且不重复广播(发现流程自己收口)', async () => {
const harness = new IpcHarness();
const deps = makeDeps();
diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
index cec01bdfa3..a1f5b75921 100644
--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
@@ -81,6 +81,8 @@ export interface ProviderHandlerDeps {
* sender 归属校验(生产 = security/trustedAppRenderer 的 assertTrustedAppRendererEvent,
* 不通过时抛 PERMISSION_DENIED)。经 deps 注入而非直接 import:本文件的 handler body
* 刻意不依赖 Electron,好让内存 registry 直接 invoke 单测(规则 14)。
+ *
+ * 类型上可选、语义上必需:未注入时 rediscover 直接拒绝,而不是放行。
*/
assertTrustedSender?(event: unknown): void;
/**
@@ -297,7 +299,14 @@ export function registerProviderHandlers(
// sender 归属校验:这条通道会用订阅凭证发起真实上游请求并重启退避,不该被子 frame /
// WebView 触发。经 deps 注入(生产 = assertTrustedAppRendererEvent),既保住本文件
// 「不依赖 Electron、可用内存 registry 直测」的设计,又不让新通道继承既有缺口。
- deps.assertTrustedSender?.(event);
+ //
+ // 守卫缺席按拒绝处理:可选依赖用 `?.()` 调用时,漏接线会静默退化成「无守卫」,而这种
+ // 退化没有任何编译期或运行期信号。宁可在接线回归时把功能打死,也不要让它悄悄敞开
+ // (PR #548 review)。
+ if (!deps.assertTrustedSender) {
+ throwIpcError('PERMISSION_DENIED', 'sender trust guard unavailable');
+ }
+ deps.assertTrustedSender(event);
const providerId = requireProviderId(input);
let failure: ProviderModelDiscoveryFailure | null;
try {
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index e128e13ce8..22e6f64be6 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -155,7 +155,7 @@ import {
deriveModelsFromProviders,
filterChatBridgedCodexProviders,
} from '@/lib/providerModels';
-import { effectiveSourceIdForModel, getModel, providerOffersModel, sessionModelSupportsFastMode, connectedProvidersForAgent, type CatalogModel, type ProviderView } from '@cindy/model-providers';
+import { effectiveSourceIdForModel, getModel, providerOffersModel, sessionModelSupportsFastMode, connectedProvidersForAgent, type ProviderView } from '@cindy/model-providers';
import { isSubscriptionDirectModel } from '../../../shared/subscriptionModels';
import {
resolveDeviceLinkDraftDefaults,
@@ -932,11 +932,31 @@ export function NewMakerDraftRoute() {
// 来源恰好提供同一个 model id 时,校准会原样保留模型 id(它确实可用),相等条件因此成立,
// 却把已经失效的来源一起带了下去 —— 而 effectiveSourceId 早已解析到另一个来源。送出去
// 就是一对 model / provider 错配,首条请求会打到不服务该模型的上游(PR #548 review)。
- // 不一致时置 null = 交回默认路由,由 main 按模型选可用来源。
- const localProviderIdForDraft =
- chatPrefs.providerId && chatPrefs.providerId === effectiveSourceId
- ? chatPrefs.providerId
- : null;
+ //
+ // 但「置 null = 交回默认路由」只在两边会解析到同一个来源时才成立:main 的默认解析吃的是
+ // **未过滤**的目录,被用户隐藏、被 SSH 订阅直连排除、被 chat-bridge 排除掉的来源在那边
+ // 依然是候选。此时 UI 高亮 B、main 却路由到 A,会话就从一个用户看不见的来源发出去。所以
+ // 只在默认路由确实落回 effectiveSourceId 时才省略它,不一致时显式带上(PR #548 review)。
+ const localProviderIdForDraft = useMemo<string | null>(() => {
+ if (chatPrefs.providerId && chatPrefs.providerId === effectiveSourceId) {
+ return chatPrefs.providerId;
+ }
+ if (!effectiveSourceId) return null;
+ // 用与 main 同源的解析函数 + 未过滤目录复算一次默认路由,比较的是同一口径。
+ const defaultRouted = effectiveSourceIdForModel(
+ localProviders,
+ null,
+ calibratedDraftModel,
+ capabilityAgentKind,
+ );
+ return defaultRouted === effectiveSourceId ? null : effectiveSourceId;
+ }, [
+ chatPrefs.providerId,
+ effectiveSourceId,
+ localProviders,
+ calibratedDraftModel,
+ capabilityAgentKind,
+ ]);
const chatInitialProviderId = isDeviceLinkDraft
? (deviceLinkInitial?.providerId ?? null)
: localProviderIdForDraft;
diff --git a/apps/desktop/src/renderer/lib/draftModelCalibration.ts b/apps/desktop/src/renderer/lib/draftModelCalibration.ts
index b4d0da8607..dfe2486b8a 100644
--- a/apps/desktop/src/renderer/lib/draftModelCalibration.ts
+++ b/apps/desktop/src/renderer/lib/draftModelCalibration.ts
@@ -14,7 +14,6 @@
import {
connectedProvidersForAgent,
type AgentKind,
- type CatalogModel,
type ProviderView,
} from '@cindy/model-providers';