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(providers): restore explicit Fast updates and save feedback

yanb826186171c7
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
index ecf8af0e64..bf670885f0 100644
--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
@@ -3,6 +3,9 @@ import { resolve } from 'node:path';
import ts from 'typescript';
import { describe, expect, it, vi } from 'vitest';
import { createEffortChangeCoordinator, enqueueEffortChange } from '../../renderer/components/new-chat/effortChangeQueue';
+import { supportsSubscriptionFastPolicy, type ProviderView } from '@cindy/model-providers';
+import { withFastModePolicy } from '../../../../../packages/maker-core/src/agents/shared/fast-mode-policy';
+import { commitRuntimeAxisAfterPersistence } from '../maker-ipc/runtimeSelectionAxes';
const mainRoot = resolve(__dirname, '..');
const bootstrapSource = readFileSync(resolve(mainRoot, 'bootstrap-electron.ts'), 'utf8').replace(
@@ -100,6 +103,9 @@ describe.each([
sessionId: 'archived-task', effort: 'high', enabled: true,
sessions: {}, eq: vi.fn(), getDbClient: () => ({ drizzle: { select: () => query } }),
remoteResponse: response, persistSessionFields: persist, agentSwitchPending: pending,
+ readSessionRuntimeProfiles: async () => ({ effective: { providerId: 'next-provider', agentDeviceId: null } }),
+ getSessionProvider: () => 'next-provider',
+ createSubscriptionFastPolicy: () => ({ isAllowed: () => true }),
// These archived fixtures have no saved automation model scope.
updateSavedScheduledAxis: vi.fn(async () => false),
updateScheduledPreference: vi.fn(async () => {}),
@@ -203,6 +209,71 @@ describe.each([
});
});
+// Review R11: run the production IPC closure with the real runtime policy
+// wrapper. Policy-only tests cannot catch an IPC branch that bypasses it.
+// Guard tier shares this file's compiled Electron closure fixture; the minimal
+// sequence is deny -> allow -> explicit enable on an active Claude task.
+describe('active Claude subscription Fast setting', () => {
+ it.each([
+ { id: 'anthropic', auth: { method: 'oauth', native: 'claude' } },
+ { id: 'openai', auth: { method: 'oauth', native: 'codex' } },
+ { id: 'custom-api', auth: { method: 'apiKey' } },
+ ])('updates the live subscription handle while preserving API behavior ($id)', async provider => {
+ let allowed = true;
+ let fast: boolean | 'ultrafast' = true;
+ let enforce!: () => Promise<void>;
+ const onFastModeChanged = vi.fn();
+ const handle = withFastModePolicy({
+ setFastMode: async (next: boolean | 'ultrafast') => { fast = next; },
+ getFastMode: () => fast,
+ close: async () => {},
+ } as Parameters<typeof withFastModePolicy>[0], {
+ isAllowed: () => allowed,
+ subscribe: listener => { enforce = listener; return () => {}; },
+ onFastModeChanged,
+ });
+ const profile = { providerId: provider.id, agentDeviceId: null };
+ const query = { from: () => query, where: () => query, limit: async () => [{ status: 'active' }] };
+ const persistFastMode = vi.fn(async () => {});
+ const bindings = {
+ sessionId: 'active-claude-task', enabled: true, sessions: {}, eq: vi.fn(),
+ getDbClient: () => ({ drizzle: { select: () => query } }),
+ agentSwitchPending: new Map(), readSessionRuntimeProfiles: async () => ({ effective: profile }),
+ createSubscriptionFastPolicy: () => ({ isAllowed: () => allowed }), supportsSubscriptionFastPolicy,
+ getSessionProvider: () => provider.id,
+ getActiveCatalog: () => ({ providers: [provider as ProviderView] }),
+ assertOwnerCurrent: vi.fn(), assertSharedTaskCurrent: { admit: vi.fn() },
+ isUserPendingAgentSwitchIntent, updateSavedScheduledAxis: async () => false,
+ resolvePendingRuntimeAxisPatch: async (_id: string, patch: object) => ({ ...patch }),
+ recordUserSessionRuntimeAxisMutation: vi.fn(), setSessionFastMode: vi.fn(),
+ maker: { getSession: () => ({ agentKind: 'claude-code', setFastMode: handle.setFastMode, getFastMode: handle.getFastMode }) },
+ persistFastMode, commitRuntimeAxisAfterPersistence, pendingCredentialSwitchHolder: null,
+ remoteResponse: undefined, log: { debug: vi.fn() },
+ };
+ const run = new Function(...Object.keys(bindings), axisHandlers.get('applyFastMode')!)(...Object.values(bindings));
+ try {
+ allowed = false;
+ await enforce();
+ expect(handle.getFastMode!()).toBe(false);
+ allowed = true;
+ await enforce();
+ expect(handle.getFastMode!()).toBe(false); // relaxation alone must never enable
+ onFastModeChanged.mockClear();
+ await run();
+ expect(persistFastMode).toHaveBeenCalledOnce();
+ if (provider.auth.method === 'oauth') {
+ expect(handle.getFastMode!()).toBe(true);
+ expect(onFastModeChanged).toHaveBeenCalledWith(true);
+ } else {
+ expect(handle.getFastMode!()).toBe(false);
+ expect(onFastModeChanged).not.toHaveBeenCalled();
+ }
+ } finally {
+ await handle.close();
+ }
+ });
+});
+
describe('session runtime control wiring', () => {
it('replays Windows attention after the main window is shown independently of inventory loading', () => {
const body = handlerBody(
diff --git a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
index 296f541bac..1555f0643e 100644
--- a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
+++ b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
@@ -201,6 +201,12 @@ vi.mock('../../maker-host/anthropic-responses-bridge-host.js', () => ({
getResponsesBridgeHandler: () => ({ handle: h.bridgeHandle }),
getPiNativeSubscriptionHandler: vi.fn(),
}));
+// The bridge preferences fixture uses the default allowing policy and must not
+// read Electron's owner/config files. Restriction behavior is exercised through
+// the real policy and async handler in subscription-fast-policy/Bridge tests.
+vi.mock('../../maker-host/subscription-fast-policy.js', () => ({
+ createSubscriptionFastPolicy: () => ({ isAllowed: () => true, isRequestAllowed: () => true }),
+}));
vi.mock('../../maker-host/claude-fast-mode-log.js', () => ({
createClaudeFastModeRequestTransform: () => () => null,
createClaudeFastModeResponseObserver: () => () => undefined,
@@ -543,7 +549,8 @@ describe('hook task model selection on next send', () => {
}));
return makeFakeSession(opts.id ?? req.sessionId);
});
- expect((await createMakerHookSessionRunner({ log }).run(req)).status).toBe('ok');
+ const outcome = await createMakerHookSessionRunner({ log }).run(req);
+ expect(outcome.status, outcome.errorMessage ?? undefined).toBe('ok');
expect(h.bridgeHandle).toHaveBeenCalledOnce();
});
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index c5b562597d..3c4a355a7d 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -182,6 +182,7 @@ import {
storedCustomProviderId,
isLocalOnlyProviderForAgent,
isOrganizationManagedProvider,
+ supportsSubscriptionFastPolicy,
type ProviderView,
} from '@cindy/model-providers';
import { createId } from '@paralleldrive/cuid2';
@@ -24062,7 +24063,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
log.debug('set-fast-mode: session not found, no-op', { sessionId });
return remoteResponse;
}
- if (sess.agentKind !== 'codex' && sess.agentKind !== 'pi' && !(sess.agentKind === 'claude-code' && subscriptionForbidsFast)) {
+ // An explicit enable after relaxation must reach the policy wrapper as
+ // well as native Claude, otherwise its request suppression stays latched.
+ // Custom API connections retain their existing persistence-only path.
+ const claudeSubscription = sess.agentKind === 'claude-code' && !fastProfile?.agentDeviceId &&
+ supportsSubscriptionFastPolicy(getActiveCatalog().providers.find(
+ provider => provider.id === (fastProfile?.providerId ?? getSessionProvider(sessionId)),
+ ));
+ if (sess.agentKind !== 'codex' && sess.agentKind !== 'pi' && !claudeSubscription) {
await commitRuntimeAxisAfterPersistence({
persist: persistFastMode,
commit: commitFastMode,
diff --git a/apps/desktop/src/renderer/__tests__/providerShareFavoritesSync.test.ts b/apps/desktop/src/renderer/__tests__/providerShareFavoritesSync.test.ts
index ebbcf28887..ee4f5c3a9b 100644
--- a/apps/desktop/src/renderer/__tests__/providerShareFavoritesSync.test.ts
+++ b/apps/desktop/src/renderer/__tests__/providerShareFavoritesSync.test.ts
@@ -12,7 +12,11 @@ import {
resetProviderShareStoreForTests,
} from '@/features/provider-share/providerShareStore';
-vi.mock('@/hooks/useDeviceProviders', () => ({ getCachedDeviceProviders: () => null }));
+vi.mock('@/hooks/useDeviceProviders', () => ({
+ getCachedDeviceProviders: () => null,
+ // This favorites fixture has no cached subscription catalog to refresh.
+ isSubscriptionShareCatalogStale: () => false,
+}));
vi.mock('@/lib/remoteCatalogSnapshot', () => ({ refreshRemoteCatalogSnapshot: vi.fn(async () => {}) }));
const share: ProviderShareReceived = {
shareId: 's1', memberId: 'm1', providerId: 'anthropic', providerLabel: 'Anthropic', hostDeviceId: 'host',
diff --git a/apps/desktop/src/renderer/features/provider-share/SubscriptionFastSetting.tsx b/apps/desktop/src/renderer/features/provider-share/SubscriptionFastSetting.tsx
index 62200824e0..dd13c1025f 100644
--- a/apps/desktop/src/renderer/features/provider-share/SubscriptionFastSetting.tsx
+++ b/apps/desktop/src/renderer/features/provider-share/SubscriptionFastSetting.tsx
@@ -32,11 +32,15 @@ export function SubscriptionFastSetting({
useEffect(() => {
alive.current = true;
sequence.current++;
- setAllowed(provider.subscriptionFastPolicy?.allowFast !== false);
return () => {
alive.current = false;
sequence.current++;
};
+ }, [provider.id, deviceId]);
+ useEffect(() => {
+ // A committed catalog push can precede a native-update failure. Refresh the
+ // value without invalidating that same provider's pending save feedback.
+ setAllowed(provider.subscriptionFastPolicy?.allowFast !== false);
}, [provider.id, deviceId, provider.subscriptionFastPolicy?.allowFast]);
if (!provider.subscriptionFastPolicy) return null;
const change = async (allowFast: boolean) => {
diff --git a/apps/desktop/src/renderer/features/provider-share/__tests__/ProviderShareManagePage.test.tsx b/apps/desktop/src/renderer/features/provider-share/__tests__/ProviderShareManagePage.test.tsx
index 04e9f01249..a2cf852cde 100644
--- a/apps/desktop/src/renderer/features/provider-share/__tests__/ProviderShareManagePage.test.tsx
+++ b/apps/desktop/src/renderer/features/provider-share/__tests__/ProviderShareManagePage.test.tsx
@@ -4,12 +4,14 @@ import type { ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { ProviderView } from '@cindy/model-providers';
import { toast } from '@/lib/toast';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
import type { ProviderGroupConfig } from '../../../../shared/providerGroup';
import type { ProviderOwnUsageView, ProviderShareOwnerState, ProviderUsageHistoryView } from '../../../../shared/providerShare';
import { __testing as localGroupsTesting } from '../../provider-group/useLocalProviderGroups';
import { ProviderShareVisibilitySection } from '../ProviderShareVisibilitySection';
import { ProviderShareManagePage } from '../ProviderShareManagePage';
+import { SubscriptionFastSetting } from '../SubscriptionFastSetting';
import {
getProviderSharePendingRequests,
getProviderSharePendingReshares,
@@ -240,6 +242,46 @@ beforeEach(() => {
afterEach(() => cleanup());
+// Review R12: real setting + management IPC adapter, using this page's host
+// fixture. Prior page cases do not interleave a catalog push with save failure.
+// Unit tier: defer the IPC, refresh allowFast, then reject; the warning must
+// survive value refresh while identity/owner/unmount boundaries still discard it.
+describe('SubscriptionFastSetting save feedback', () => {
+ const subscription = (id = 'openai', allowFast = true) => ({
+ id, subscriptionFastPolicy: { allowFast },
+ } as ProviderView);
+
+ it('keeps the native failure warning after the committed catalog value arrives', async () => {
+ vi.mocked(toast.error).mockClear();
+ let reject!: (error: Error) => void;
+ command.mockImplementationOnce(() => new Promise((_resolve, fail) => { reject = fail; }));
+ const view = render(<SubscriptionFastSetting provider={subscription()} />);
+ expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('true');
+ fireEvent.click(screen.getByRole('switch'));
+ expect(command).toHaveBeenCalledWith({ action: 'set-fast-policy', providerId: 'openai', allowFast: false });
+ view.rerender(<SubscriptionFastSetting provider={subscription('openai', false)} />);
+ await act(async () => { reject(new Error('native busy')); });
+ expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('false');
+ expect(vi.mocked(toast.error)).toHaveBeenCalledExactlyOnceWith('subscriptionFastPolicy.saveFailed');
+ expect((screen.getByRole('switch') as HTMLButtonElement).disabled).toBe(false);
+ });
+
+ it.each(['provider', 'device', 'owner', 'unmount'])('discards a late failure across the %s boundary', async boundary => {
+ vi.mocked(toast.error).mockClear();
+ setDataOwnerGeneration('fast-owner-a');
+ let reject!: (error: Error) => void;
+ command.mockImplementationOnce(() => new Promise((_resolve, fail) => { reject = fail; }));
+ const view = render(<SubscriptionFastSetting provider={subscription()} />);
+ fireEvent.click(screen.getByRole('switch'));
+ if (boundary === 'provider') view.rerender(<SubscriptionFastSetting provider={subscription('anthropic')} />);
+ if (boundary === 'device') view.rerender(<SubscriptionFastSetting provider={subscription()} deviceId="other-computer" />);
+ if (boundary === 'owner') setDataOwnerGeneration('fast-owner-b');
+ if (boundary === 'unmount') view.unmount();
+ await act(async () => { reject(new Error('old native busy')); });
+ expect(vi.mocked(toast.error)).not.toHaveBeenCalled();
+ });
+});
+
/** 「你自己」一行先出来;分享的人等分享读到后才有。 */
async function findMemberRow(memberId = 'mem-1'): Promise<HTMLElement> {
return waitFor(() => {
diff --git a/docs/subscription-fast-policy-review.md b/docs/subscription-fast-policy-review.md
index 1691d78107..bb8f7aeed5 100644
--- a/docs/subscription-fast-policy-review.md
+++ b/docs/subscription-fast-policy-review.md
@@ -183,3 +183,35 @@ pnpm --filter desktop run typecheck
- 24 个改动测试文件分别运行通过,独立计时在 `artifacts/fast-rebase/standalone-timings.json`。桥接回归保留真实路由和 handler,直接加载实际速度钳制函数,减少无关 Agent 初始化;优化后单文件 8.15 秒、测试体 66 毫秒,尚高于 5 秒目标,如实登记。
机器报告与日志在忽略目录 `artifacts/fast-rebase/`。macOS、Claude 原生真实付费请求和不同物理机仍未补测;之前隔离 dev 的真实分享记录不代替最终 rebase 后的实机证据。
+
+## PR #6894 首次自动跟进(2026-10-23)
+
+以下为提交 PR 后的增量复核,不计入提交前十项发现。没有新增 Orca 委托,也没有重启正式版或发送真实付费请求。
+
+### R11 / P1:解除限制后,运行中的 Claude 无法显式恢复 Fast
+
+- GitHub 原线程:`discussion_r4356434669`。独立确认 `SET_FAST_MODE` 仅在仍被禁止时才调用 Claude 的运行句柄;恢复允许后只保存偏好,原生 Fast 状态和请求抑制没有解除。
+- 修复:真实本机 OAuth 订阅上的 Claude 显式开关始终经过运行句柄和已有策略包装器;仅放宽账号/组限制仍不自动启用。自定义 API 仍走原来的偏好保存路径,没有增加原生控制请求。
+- 回归:在既有 `sessionRuntimeControlWiring.test.ts` 复用编译后的生产 IPC 闭包并连接真实 `withFastModePolicy`,执行「禁止 → 允许 → 手动开启」;Anthropic 和 OpenAI 订阅均在旧实现失败、修复后通过,自定义 API 对照保持原样。现有策略/原生设置测试单独覆盖抑制回调与 flag 更新,这个入口用例补齐此前无法发现的 IPC 提前返回。
+
+### R12 / P2:目录先刷新时,原生保存失败提示被吞掉
+
+- GitHub 原线程:`discussion_r4356434675`。独立确认同一供应商 `allowFast` 变化会递增保存代次,使后到的原生更新失败提示被当成陈旧请求。
+- 修复:供应商/电脑身份生命周期与目录值刷新分开。相同身份的新目录只刷新开关值,继续显示该次保存失败;换供应商、换电脑、换号和卸载仍丢弃旧响应。
+- 回归:在已有 `ProviderShareManagePage.test.tsx` 使用真实 `SubscriptionFastSetting` 和管理 IPC 适配器;延迟保存,先更新 props 再拒绝,旧实现没有提示、修复后有提示;四类失效边界继续通过。复用原页面夹具,没有拆分小测试文件或复制组件实现。
+
+### CI 失败分诊与测试夹具适配
+
+- 初始 `client-ci` run `39905324909` 的 verify job `120255848292`:生产 Fast 闭包新增策略依赖后,归档设置夹具缺少 `readSessionRuntimeProfiles` 等绑定,九项报 `ReferenceError`。补齐该夹具的缺省允许订阅依赖,原有归档/删除/持久化失败断言保留。
+- Linux 分片 job `120255848377`:hook bridge 偏好用例开始读取真实宿主策略,旧 Electron mock 无 `app`,创建任务返回错误。明确注入缺省允许策略以隔离宿主配置,不读取账号文件;仍通过真实 runner、路由变换检查 effort/Fast,禁止场景继续由独立真实策略与 bridge handler 回归验证。失败断言增加原错误信息以便诊断。
+- Linux 分片 job `120255848463`:收藏同步的无目录夹具缺少 `isSubscriptionShareCatalogStale` 导出,补齐「无已缓存订阅目录」的返回值;没有更改收藏同步源码或断言。
+- 上述失败均在本地重现后修复,属于本 PR 新依赖与既有夹具的适配遗漏;没有按 flaky 处理、空提交、弱化断言或因 main 普通前进而 rebase。
+
+### 本轮增量验证
+
+- 10 个不同文件共 384 项通过:IPC/页面 119,策略与 runtime axis 33,Core 包装器/Claude flag 14,hook/收藏/持久策略 218。重复计时不重复计数;IPC 单文件 79 项、3.68 秒。
+- `register.ts` 全文件 ESLint 仍有 15 个既有 unused 错误,hook 测试仍有六个既有 unused 参数错误;分别对照上游基线 `70b32d7` 的完整消息集合,新增错误均为零。不把全文件 lint 写成通过,也不跨范围删除别人的代码。
+- UI 完整 `--changed --theme all --engine chromium` 矩阵为 376/382 通过(665.8 秒),Fast 的八个明暗主题场景全部通过,已查看总览及开关实图。六个失败均在 `plugin-install-mail` 的多视图/编辑/刷新场景,报 `ResizeObserver loop completed with undelivered notifications`。随后 `--compare 70b32d7` 在上游基线也复现同类失败;没有据此修改插件或掩盖整批失败。`ProvidersSection.tsx` 仍为 UNCOVERED。没有再次发布新截图,PR 保留已获用户授权的原有模拟图。
+- 独立单文件耗时:IPC 3.68 秒、收藏同步 3.85 秒、管理页面 30.60 秒、hook runner 15.94 秒。后两项复用已有大入口夹具:页面同时加载真实页面、账号/成员/用量组件,hook 加载真实 runner、路由和 Core 事件判定;没有逐项 resetModules、增加真实等待或拆分机械小文件。测试体分别为 17.51 秒、1.49 秒,重收集成本与 Windows 并行类型/UI 扫描负载均保留记录,不将其宣称满足五秒目标。
+- 最后代码的 Desktop 全量 `typecheck` 退出码 0;过程中诊断断言的 nullable message 类型错误已修复后重跑,未记失败批次为通过。最终 `check:test-hygiene` 通过(363 个文件在原基线内),开发文档合同 10 项通过;除上述两处已有 lint 基线外,其余四个改动源码/测试文件的定向 ESLint 通过。
+- 历史 3114 项结果保持属于提交前快照,不能代替这次新增代码的验证。原 Core 独立 build、macOS/真实 Claude 付费/跨物理机限制继续保留,不由本轮模拟测试替代。