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(goal): defer ChatGPT quota admission to the provider

Yecheng Fua0a54e150294
diff --git a/apps/desktop/src/main/goal-host/__tests__/index.test.ts b/apps/desktop/src/main/goal-host/__tests__/index.test.ts
new file mode 100644
index 0000000000..cf47822b71
--- /dev/null
+++ b/apps/desktop/src/main/goal-host/__tests__/index.test.ts
@@ -0,0 +1,173 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { AgentEvent, Maker } from '@cindy/maker-core';
+import type { CodexAccountUsagePayload } from '../../usageBroadcaster';
+import type { GoalState, SessionLike } from '../types';
+import { getActiveCatalog, setCustomProviders } from '../../maker-host/active-catalog';
+
+const host = vi.hoisted(() => ({
+ goals: new Map<string, GoalState>(),
+ row: { providerId: 'openai', model: 'gpt-6-astra', agentDeviceId: null as string | null },
+ codex: vi.fn<() => Promise<CodexAccountUsagePayload | null>>(),
+}));
+
+vi.mock('../../logger.js', () => ({ createLogger: () => ({ info() {}, warn() {}, error() {} }) }));
+vi.mock('../../maker-ipc/register.js', () => ({
+ hasRestoredCodexQuota: vi.fn(),
+ acquirePendingAgentSwitchForDirectSend: async () => () => {},
+ isSessionInTurn: () => false,
+ ensureGoalInputReady: async () => true,
+ isGoalInputBlocked: () => false,
+ stopActiveGoalTurnForClear: async () => {},
+ resolveSessionRuntimeRoute: () => ({ providerId: host.row.providerId, modelId: host.row.model }),
+}));
+vi.mock('../../device-link/sharedTaskDispatch.js', () => ({ isSessionSharedTaskActive: () => false }));
+vi.mock('../../localDb/ipc/messages.js', () => ({ createMessage: async () => {} }));
+vi.mock('../../localDb/ipc/sessions.js', () => ({
+ getSessionRowSnapshot: async () => host.row,
+ touchSessionActivityInDb: async () => {},
+}));
+vi.mock('../../maker-host/goal-settings-store.js', () => ({
+ readGoalSettings: () => ({ maxTurns: null, budgetTokens: null, noProgressLimit: null }),
+ writeGoalSettings: async () => {},
+}));
+vi.mock('../../usageBroadcaster.js', () => ({
+ readCodexAccountUsageSnapshot: host.codex,
+ readClaudeSubscriptionUsageSnapshot: async () => ({ fiveHour: { utilization: 100, resetsAt: RESET / 1000 } }),
+ readXaiSubscriptionUsageSnapshot: async () => null,
+}));
+vi.mock('../../usage/subscriptionAccountUsage.js', () => ({ readSubscriptionAccountUsage: async () => null }));
+vi.mock('../../usage/claudeAccountUsage.js', () => ({ readClaudeAccountUsageSnapshot: () => null }));
+vi.mock('../../maker-ipc/usage.js', () => ({ onCodexAutoResetRestored: () => () => {} }));
+vi.mock('../sessionRestore.js', () => ({
+ restoreSessionForGoal: async (id: string, deps: { maker: Maker }) => deps.maker.getSession(id),
+}));
+vi.mock('../storage', () => ({
+ GoalStorage: class {
+ async get(id: string) { return host.goals.get(id) ?? null; }
+ async upsert(state: GoalState) { host.goals.set(state.sessionId, { ...state }); }
+ async update(id: string, patch: Partial<GoalState>) {
+ const previous = host.goals.get(id);
+ if (!previous) return null;
+ const next = { ...previous, ...patch };
+ host.goals.set(id, next);
+ return next;
+ }
+ async clear(id: string) { host.goals.delete(id); }
+ async listActive() { return [...host.goals.values()].filter(g => g.status === 'active'); }
+ async listUsageLimited() { return [...host.goals.values()].filter(g => g.status === 'usageLimited'); }
+ },
+}));
+
+import { resetGoalController, startGoalController } from '../index';
+
+const NOW = Date.parse('2026-10-29T10:00:00Z');
+const RESET = NOW + 7 * 24 * 60 * 60 * 1000;
+
+async function start(agentKind: SessionLike['agentKind'] = 'codex') {
+ let listener: ((event: AgentEvent) => void) | null = null;
+ const send = vi.fn(async (_message: unknown, options?: {
+ onDispatching?: () => void;
+ onAccepted?: () => void | Promise<void>;
+ }) => {
+ options?.onDispatching?.();
+ await options?.onAccepted?.();
+ return { accepted: true };
+ });
+ const session = {
+ id: 's1', agentKind, send,
+ onEvent(next: (event: AgentEvent) => void) {
+ listener = next;
+ return () => { listener = null; };
+ },
+ isTurnRunning: () => false,
+ abort: async () => {},
+ };
+ const controller = startGoalController({
+ maker: { getSession: () => session } as unknown as Maker,
+ getDb: () => { throw new Error('This test must not access a database'); },
+ broadcastStatus: () => {},
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ await controller.setGoal({ sessionId: 's1', objective: 'Finish the work', agentKind });
+ expect(send).toHaveBeenCalledTimes(1);
+ return {
+ controller, send,
+ finish(error?: Record<string, unknown>) {
+ const emit = (event: unknown) => listener?.(event as AgentEvent);
+ if (error) {
+ emit({ type: 'error', source: agentKind, turnOrigin: { kind: 'goal' }, data: { isTerminal: true, ...error } });
+ } else {
+ emit({ type: 'tool_use', data: { name: 'read_file' } });
+ emit({ type: 'text', data: { text: '{"goal_status":"continue","reason":"Work remains"}', isFinal: true } });
+ emit({ type: 'done', data: {}, turnOrigin: { kind: 'goal' } });
+ }
+ },
+ };
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(NOW);
+ host.goals.clear();
+ host.row = { providerId: 'openai', model: 'gpt-6-astra', agentDeviceId: null };
+ const openai = getActiveCatalog().providers.find(p => p.id === 'openai')!;
+ setCustomProviders([{ ...openai, id: 'work-account', auth: { ...openai.auth, native: 'codex' } }]);
+ host.codex.mockReset();
+ const snapshot = {
+ primary: { usedPercent: 100, resetsAt: RESET / 1000 },
+ credits: { hasCredits: true, unlimited: false, balance: '100' },
+ };
+ host.codex.mockResolvedValue({ ...snapshot, webSnapshot: snapshot });
+});
+
+afterEach(async () => {
+ await resetGoalController();
+ setCustomProviders([]);
+ vi.useRealTimers();
+});
+
+// Regression: the real host wiring used exhausted subscription snapshots as admission
+// decisions after success. Controller-only tests inject a different quota reader.
+// This unit exercises startGoalController -> real controller -> persisted state/send;
+// memory storage/session boundaries prevent live model requests or owner-data access.
+describe('ChatGPT goal admission', () => {
+ it.each([
+ { agent: 'codex', provider: 'openai' },
+ { agent: 'claude-code', provider: 'openai' },
+ { agent: 'pi', provider: 'openai' },
+ { agent: 'codex', provider: 'work-account' },
+ ] as const)('lets the provider admit the next $agent turn on $provider despite advisory quota', async ({ agent, provider }) => {
+ host.row.providerId = provider;
+ const h = await start(agent);
+ h.finish();
+ await vi.advanceTimersByTimeAsync(200);
+ expect(await h.controller.getStatus('s1')).toMatchObject({ status: 'active', usageResetAt: null });
+ expect(h.send).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps a genuine rejection and its exhausted-window reset despite available credits', async () => {
+ const h = await start();
+ h.finish({ codexErrorInfo: 'usageLimitExceeded', message: 'Usage limit reached' });
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(await h.controller.getStatus('s1')).toMatchObject({ status: 'usageLimited', usageResetAt: RESET });
+ expect(h.send).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves a rejection without a trustworthy reset stopped instead of retrying from credit data', async () => {
+ host.codex.mockResolvedValue({ primary: { usedPercent: 10, resetsAt: RESET / 1000 }, credits: { hasCredits: true, unlimited: false } });
+ const h = await start();
+ h.finish({ codexErrorInfo: 'usageLimitExceeded', message: 'Usage limit reached' });
+ await vi.advanceTimersByTimeAsync(86400000);
+ expect(await h.controller.getStatus('s1')).toMatchObject({ status: 'usageLimited', usageResetAt: null });
+ expect(h.send).toHaveBeenCalledTimes(1);
+ });
+
+ it('retains proactive quota handling for other subscription families', async () => {
+ host.row.providerId = 'anthropic';
+ const h = await start('claude-code');
+ h.finish();
+ await vi.advanceTimersByTimeAsync(200);
+ expect(await h.controller.getStatus('s1')).toMatchObject({ status: 'usageLimited', usageResetAt: RESET });
+ expect(h.send).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/desktop/src/main/goal-host/index.ts b/apps/desktop/src/main/goal-host/index.ts
index e63fc72f86..4b4fb71499 100644
--- a/apps/desktop/src/main/goal-host/index.ts
+++ b/apps/desktop/src/main/goal-host/index.ts
@@ -108,12 +108,16 @@ export function startGoalController(deps: StartGoalControllerDeps): GoalControll
agentMeta: { goalCompletion: summary },
});
},
- // 主动配额检测:按会话所用订阅账号读用量快照(ChatGPT 订阅无论跑在 Codex、Claude Code
- // bridge 还是 Pi 上都读同一份额度),判 limited + 取 resetAt(unix ms)。
+ // 按实际订阅账号处理限额错误与重置时刻;其它订阅保留主动配额检测。
getAccountLimit: async (agentKind, sessionId, turnError) => {
const row = await getSessionRowSnapshot(sessionId);
const { providerId, modelId } = resolveSessionRuntimeRoute(sessionId, agentKind, row);
- if (subscriptionFamilyOf(agentKind, providerId)) {
+ const family = subscriptionFamilyOf(agentKind, providerId);
+ // ChatGPT windows do not establish credit-backed admission, and cached credits
+ // may be stale or unknown. Let the next normal turn reach the provider; retain
+ // snapshot reset lookup after an actual rejection instead of retrying on credits.
+ if (family === 'codex' && turnError === undefined) return null;
+ if (family) {
const otherMachineAccount = sessionUsesOtherMachineAccount(row);
// 报错原文写明的重置时刻只对订阅账号可信(非订阅来源的是分钟级请求限流)。
if (turnError !== undefined) {
diff --git a/apps/desktop/src/main/goal-host/types.ts b/apps/desktop/src/main/goal-host/types.ts
index a72701d3c0..56a1879fa5 100644
--- a/apps/desktop/src/main/goal-host/types.ts
+++ b/apps/desktop/src/main/goal-host/types.ts
@@ -238,11 +238,13 @@ export interface GoalControllerDeps {
*/
isSessionShared?: (sessionId: string) => boolean;
/**
- * 读该会话所用账号当前是否受限 + 何时重置(主动检测)。注入端按会话 provider 所属的订阅
- * 家族读对应快照(ChatGPT / Claude / SuperGrok,见 usage/accountUsageLimit.ts);非订阅的
- * Claude Code 会话退回 Cindy 网关预算快照。`turnError` 为本轮限额报错(被动检测时传入):
- * 会话属于订阅账号时优先用报错原文里写明的重置时刻。
- * 返回 null = 拿不到快照(按"未受限"处理)。
+ * 读该会话所用账号当前是否受限 + 何时重置。注入端按会话 provider 所属的订阅家族
+ * 处理(ChatGPT / Claude / SuperGrok,见 usage/accountUsageLimit.ts)。ChatGPT 成功轮次
+ * 不做缓存配额的主动检测,下一轮由上游判断准入;其它订阅仍主动读快照,非订阅的
+ * Claude Code 会话退回 Cindy 网关预算快照。
+ * 被拒路径必须传本轮限额报错 `turnError`,否则 ChatGPT 会跳过重置时刻查询;
+ * 订阅账号优先用报错原文里写明的重置时刻,再回落到实际账号窗口。
+ * 返回 null = 未提供账号限额信息(主动检测不阻止续轮;被动路径仍按限额错误停止)。
*/
getAccountLimit?: (
agentKind: AgentKind,
diff --git a/docs/product-rules/usage-limit-auto-continue.md b/docs/product-rules/usage-limit-auto-continue.md
index c66e246a7e..90ab1b1b23 100644
--- a/docs/product-rules/usage-limit-auto-continue.md
+++ b/docs/product-rules/usage-limit-auto-continue.md
@@ -9,6 +9,10 @@
这个任务。有产出的 turn 发续跑指令,零产出的 turn 重发原文,与人工「重试」同一条路径。
- **目标模式**:沿用 `usageLimited` 状态到点自动续跑(见 `goal-host`),与普通任务共用同一套
「按会话所用账号求重置时刻」的逻辑,两者不会重复续跑。
+ ChatGPT 订阅的成功轮次不因缓存的套餐窗口用满而停止正常续轮:窗口不代表付费 credits
+ 的请求准入,缓存的余额也可能过时或未知,下一轮仍由上游判断。真实上游限额错误照常停止,
+ 并按下文的错误/实际账号窗口确定等待时刻;不因快照显示有 credits 就立即重试。
+ 这按订阅身份生效,覆盖 Codex、Claude Code bridge 与 Pi,不改变其它订阅的主动检测。
- **定时任务**(2026-10-22):真实 Schedule run 的账号限额失败同样保留手动重试并等待重置。
本次运行内自动继续沿用同一个 run;等待期间复用调度器的纯等待状态,不占执行名额,也不按无进展判卡死。
到点重新检查执行名额,暂时无空位时复用限额等待计时器每分钟再检查,不请求模型、不消耗续跑次数。