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(provider-group): 计入冷却时间并保留自动恢复记录

Dash200c6e3ec1d3
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index e9ae0f562a..cab40292c5 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -14242,11 +14242,31 @@ describe('usage-limit wait (ordinary tasks)', () => {
await flush();
expect(h.sendToAgent).toHaveBeenCalledTimes(cancel ? 1 : 2);
if (!cancel) {
- expect(h.sendToAgent.mock.calls[1][3].persistUserMessage?.clientId).toBe('q-original');
+ const persisted = h.sendToAgent.mock.calls[1][3].persistUserMessage;
+ expect(persisted).toMatchObject({ clientId: 'q-original', autoResumeInfo: INFO });
+ expect(persisted?.autoResume, 'the first user input must remain visible and count as a user turn').toBeUndefined();
expect(h.onUserMessagePersisted).toHaveBeenCalledTimes(1);
}
});
+ it('does not keep automatic activity on a manual retry after preparation fails', async () => {
+ const h = createHarness();
+ const sid = 'quota-retry-preparation-failed';
+ h.sendToAgent.mockRejectedValueOnce(new ProviderGroupUsageLimitError({ resetAtMs: 5_000_000 }));
+ h.coordinator.enqueue(sid, makeItem('original', 'original task'));
+ await flush();
+ const candidate = h.onUsageLimitedTurnError.mock.calls.at(-1)?.[3] as number;
+ h.coordinator.armUsageLimitWait(sid, candidate, 9_000_000);
+ h.sendToAgent.mockRejectedValueOnce(new Error('preparation failed'));
+ await h.coordinator.continueAfterUsageLimitReset(sid, candidate, INFO);
+ await flush();
+ expect(h.sendToAgent.mock.calls[1][3].persistUserMessage?.autoResumeInfo).toMatchObject(INFO);
+ await h.coordinator.retryLastError(sid);
+ await flush();
+ expect(h.sendToAgent.mock.calls[2][3].persistUserMessage).toMatchObject({ clientId: 'original' });
+ expect(h.sendToAgent.mock.calls[2][3].persistUserMessage?.autoResumeInfo).toBeUndefined();
+ });
+
it('does not arm a queue wait from an unverified provider error string', async () => {
const h = createHarness();
h.sendToAgent.mockRejectedValueOnce(new Error('usage_limit_reached; resets_at: 5000000'));
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index f7ad1fe384..31f30695cf 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -3330,6 +3330,11 @@ export class AgentInputCoordinator {
if (!opts?.auto) state.autoResumeAttemptToken = null;
state.usageLimitWait = null;
state.recovery = null;
+ if (waitingQueueHead && automaticResumeInfo) {
+ // Keep the original user input/receipt and user-turn accounting. Only the
+ // recovery activity metadata travels with its first durable user row.
+ state.pendingQueue[0].autoResumeInfo = automaticResumeInfo;
+ }
if (recovery.kind === 'active-turn') {
let item = continueItem;
if (!item) {
@@ -5268,6 +5273,10 @@ export class AgentInputCoordinator {
// (persisted path). If no other work is pending, any deferred completion must
// be replayed now; otherwise Agent Island stays in "running" indefinitely.
this.deps.onQueueEmptied?.(sessionId);
+ } finally {
+ // A failed preparation must not label a later manual retry as automatic.
+ // Hidden continuation items retain their existing recovery metadata.
+ if (!active.persisted && !head.autoResume) delete head.autoResumeInfo;
}
}
diff --git a/apps/desktop/src/main/provider-group/__tests__/router.usage.test.ts b/apps/desktop/src/main/provider-group/__tests__/router.usage.test.ts
index ca8a706cbf..43db896225 100644
--- a/apps/desktop/src/main/provider-group/__tests__/router.usage.test.ts
+++ b/apps/desktop/src/main/provider-group/__tests__/router.usage.test.ts
@@ -145,6 +145,21 @@ describe('provider-group quota routing', () => {
expect(await h.pick()).not.toHaveProperty('usageLimit');
});
+ // PR #6611: pick() must not wake a task while its earliest quota-reset member is
+ // still cooling. Unit gap: existing quota and cooldown cases never overlapped.
+ it.each([undefined, OPUS])('waits for both quota reset and the existing cooldown (%s)', async (scope) => {
+ const h = harness();
+ const remote = h.config.members[1].key;
+ h.usage.set('local', { ...snapshot(100, 20), fiveHour: { utilization: 100, resetsAt: (NOW + 300_000) / 1000 } });
+ h.usage.set(remote, { ...snapshot(100, 20), fiveHour: { utilization: 100, resetsAt: (NOW + 600_000) / 1000 } });
+ h.router.markCooling('anthropic', 'local', NOW + 1_800_000, scope);
+ expect(await h.pick()).toMatchObject({ kind: 'unavailable', usageLimit: { resetAtMs: NOW + 600_000 } });
+ h.config.members[1].paused = true;
+ expect(await h.pick()).toMatchObject({ kind: 'unavailable', usageLimit: { resetAtMs: NOW + 1_800_000 } });
+ h.usage.set('local', { ...snapshot(100, 20), fiveHour: { utilization: 100, resetsAt: null } });
+ expect(await h.pick()).toMatchObject({ kind: 'unavailable', usageLimit: { resetAtMs: null } });
+ });
+
it('isolates error cooldowns by model while total quota and account failures still block all models', async () => {
const h = harness();
h.config.strategy = 'order';
diff --git a/apps/desktop/src/main/provider-group/router.ts b/apps/desktop/src/main/provider-group/router.ts
index b1868a6396..bfa0937b65 100644
--- a/apps/desktop/src/main/provider-group/router.ts
+++ b/apps/desktop/src/main/provider-group/router.ts
@@ -250,7 +250,13 @@ export function createProviderGroupRouter(deps: ProviderGroupRouterDeps): Provid
// offline or model-mismatched member must not supply a misleading reset time.
const limited = resolved.filter((r) => !paused(r) && !input.exclude?.has(r.member.key)
&& offersModel(r, input.agentKind, input.model))
- .map((r) => providerGroupMemberUsageState(r, input.model, now, input.agentKind))
+ .map((r) => {
+ const quota = providerGroupMemberUsageState(r, input.model, now, input.agentKind);
+ // A reset is useful only once this member's existing cooldown also ends.
+ // A cooldown alone is not evidence of when an unknown quota resets.
+ return { ...quota, resetAtMs: quota.resetAtMs === null ? null
+ : Math.max(quota.resetAtMs, coolingUntil(input.providerId, r.member.key, input.model) ?? 0) };
+ })
.filter((quota) => quota.limited);
const resets = limited.flatMap((quota) => quota.resetAtMs === null ? [] : [quota.resetAtMs]);
return {
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts
index 4afe4f04ae..822fc98f61 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts
@@ -227,6 +227,23 @@ describe('mapServerMessages auto-resume 分隔线', () => {
expect(row?.content).toBe('');
});
+ // Unit / PR #6611: the first queued input resumes without a hidden clone.
+ // Previously only autoResume=true rows carried an activity, losing this record on reload.
+ it('keeps a quota-resumed first input visible with its activity metadata', async () => {
+ const info = { reason: 'usage-limit-reset', attempt: 1, maxAttempts: 3, sessionTotal: 0 };
+ vi.mocked(messageService.list).mockResolvedValueOnce([
+ serverMessage({ clientId: 'original', role: 'user', content: 'original task',
+ agentMeta: { autoResumeInfo: info } as Message['agentMeta'] }),
+ ]);
+ makerChatStore.ensureInitialMessages(SID);
+ await flush();
+ await flush();
+ const row = makerChatStore.getSnapshot(SID).messages.find((m) => m.clientId === 'original');
+ expect(row).toMatchObject({ content: 'original task', usageLimitAutoResumeInfo: info });
+ expect(row?.isSyntheticTrigger).not.toBe(true);
+ expect(row?.systemCardType).toBeUndefined();
+ });
+
it('人工发的合成指令(无 autoResume)不渲染分隔线,只静默占位', async () => {
vi.mocked(messageService.list).mockResolvedValueOnce([
serverMessage({
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index 4773438ffb..2f673ae763 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -6940,34 +6940,44 @@ const MessageItem = memo(function MessageItem({
switch (message.role) {
case 'user':
return (
- <UserMessage
- sharedAuthorName={message.sharedAuthorName}
- sharedAuthorMemberId={message.sharedAuthorMemberId}
- workingDir={workingDir}
- content={message.content}
- quotesEncoded={message.quotesEncoded}
- agentReferences={message.agentReferences}
- pastedTextRanges={message.pastedTextRanges}
- slashCommandRanges={message.slashCommandRanges}
- images={message.images}
- files={message.files}
- createdAt={message.createdAt}
- sessionId={sessionId}
- agentKind={agentKind}
- remoteHostId={remoteHostId}
- messageClientId={message.clientId}
- sessionRunning={sessionRunning}
- isFirstUserMessage={isFirstUserMessage}
- isLastUserMessage={isLastUserMessage}
- automationOrigin={message.automationOrigin}
- hookSource={message.hookSource}
- sourceDevice={message.sourceDevice}
- sourcePlugin={message.sourcePlugin}
- delivery={message.delivery}
- goalBadge={message.goalBadge}
- blockedByGhost={message.blockedByGhost}
- simplifiedBotConversation={simplifiedBotConversation}
- />
+ <>
+ <UserMessage
+ sharedAuthorName={message.sharedAuthorName}
+ sharedAuthorMemberId={message.sharedAuthorMemberId}
+ workingDir={workingDir}
+ content={message.content}
+ quotesEncoded={message.quotesEncoded}
+ agentReferences={message.agentReferences}
+ pastedTextRanges={message.pastedTextRanges}
+ slashCommandRanges={message.slashCommandRanges}
+ images={message.images}
+ files={message.files}
+ createdAt={message.createdAt}
+ sessionId={sessionId}
+ agentKind={agentKind}
+ remoteHostId={remoteHostId}
+ messageClientId={message.clientId}
+ sessionRunning={sessionRunning}
+ isFirstUserMessage={isFirstUserMessage}
+ isLastUserMessage={isLastUserMessage}
+ automationOrigin={message.automationOrigin}
+ hookSource={message.hookSource}
+ sourceDevice={message.sourceDevice}
+ sourcePlugin={message.sourcePlugin}
+ delivery={message.delivery}
+ goalBadge={message.goalBadge}
+ blockedByGhost={message.blockedByGhost}
+ simplifiedBotConversation={simplifiedBotConversation}
+ />
+ {message.usageLimitAutoResumeInfo && (
+ <SystemCard
+ cardType="auto-resume"
+ data={message.usageLimitAutoResumeInfo}
+ sessionId={sessionId}
+ workingDir={workingDir}
+ />
+ )}
+ </>
);
case 'assistant':
if (message.systemCardType === 'mcp-app') {
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 37612e3189..7fa0136aee 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -611,6 +611,8 @@ export interface ChatMessage {
| 'mcp-app';
mcpAppClientId?: string;
systemCardData?: Record<string, unknown>;
+ /** First input resumed after group quota recovery; its user bubble stays visible. */
+ usageLimitAutoResumeInfo?: Record<string, unknown>;
/** FP-3: plan_review message fields */
planReviewStatus?: 'pending' | 'approved' | 'revised' | 'expired' | 'cancelled';
planReviewRequestId?: string;
@@ -19359,6 +19361,9 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {
role: m.role,
content: parsed.text,
isStreaming: false,
+ ...(m.agentMeta?.autoResumeInfo?.reason === 'usage-limit-reset'
+ ? { usageLimitAutoResumeInfo: { ...m.agentMeta.autoResumeInfo } }
+ : {}),
...(parsed.images.length > 0 && { images: parsed.images }),
...(parsed.files.length > 0 && { files: parsed.files }),
...(parsed.quotesEncoded === true && { quotesEncoded: true }),
diff --git a/apps/desktop/src/shared/agentInputQueue.ts b/apps/desktop/src/shared/agentInputQueue.ts
index 58783369a4..b06a43476f 100644
--- a/apps/desktop/src/shared/agentInputQueue.ts
+++ b/apps/desktop/src/shared/agentInputQueue.ts
@@ -442,6 +442,7 @@ export interface AgentInputQueuedMessage {
/**
* 本次自动续跑的展示信息(中断原因 + 本轮第几次 + 会话累计)。随 `autoResume`
* 一起透传到落库 agentMeta,供「已重新连接」活动行的展开详情用。
+ * 首次派发前的组限额恢复只带 info、不设 autoResume:保留原用户气泡与用户轮记账,另显示恢复活动。
*/
autoResumeInfo?: AutoResumeInfo;
/** Bounded, durable handoff state shared by manual and automatic recovery. */
diff --git a/apps/mobile/src/__tests__/messageNormalize.test.ts b/apps/mobile/src/__tests__/messageNormalize.test.ts
index 7441fb1f47..5c3d113447 100644
--- a/apps/mobile/src/__tests__/messageNormalize.test.ts
+++ b/apps/mobile/src/__tests__/messageNormalize.test.ts
@@ -1529,6 +1529,19 @@ describe('normalizeRemoteMessages', () => {
align: 'agent',
});
});
+
+ // Unit / PR #6611: quota recovery before the first dispatch must keep the
+ // original bubble and add the same activity as an active-turn continuation.
+ it('keeps the original input alongside a quota-reset activity after reload', () => {
+ const info = { reason: 'usage-limit-reset', attempt: 1, maxAttempts: 3, sessionTotal: 0 };
+ const items = normalizeRemoteMessages([
+ message({ id: 'original', role: 'user', content: 'original task', agentMeta: { autoResumeInfo: info } }),
+ ]);
+ expect(items).toHaveLength(2);
+ expect(items[0]).toMatchObject({ key: 'original', body: 'original task', label: 'user' });
+ expect(items[1]).toMatchObject({ key: 'original:usage-limit-resume', kind: 'system',
+ body: '', systemCardType: 'auto-resume', systemCardData: info });
+ });
});
describe('context rebuild boundaries', () => {
diff --git a/apps/mobile/src/session/messageNormalize.ts b/apps/mobile/src/session/messageNormalize.ts
index 5363b01893..f6279e8c04 100644
--- a/apps/mobile/src/session/messageNormalize.ts
+++ b/apps/mobile/src/session/messageNormalize.ts
@@ -622,6 +622,24 @@ export function normalizeRemoteMessages(
...(message.role === 'user' ? readMessageSourceFields(message) : {}),
...(hookSource ? { hookSource } : {}),
});
+ const quotaResumeInfo = readRecord(message.agentMeta?.autoResumeInfo);
+ if (message.role === 'user' && quotaResumeInfo?.reason === 'usage-limit-reset') {
+ // Same durable row, two visible parts: retain the user's original input
+ // and show the existing recovery activity without creating another turn.
+ result.push({
+ key: `${messageNormalizeKey(message)}:usage-limit-resume`,
+ source: message,
+ kind: 'system',
+ role: message.role,
+ label: 'system:auto-resume',
+ body: '',
+ systemCardType: 'auto-resume',
+ systemCardData: quotaResumeInfo,
+ isSyntheticTrigger: true,
+ align: 'agent',
+ createdAt: message.createdAt,
+ });
+ }
}
const pluginInvocations = collectPluginInvocations(sorted, toolResultPairing);
diff --git a/docs/product-rules/usage-limit-auto-continue.md b/docs/product-rules/usage-limit-auto-continue.md
index 0aa105d191..6c597dcdf5 100644
--- a/docs/product-rules/usage-limit-auto-continue.md
+++ b/docs/product-rules/usage-limit-auto-continue.md
@@ -56,10 +56,11 @@
供应商组在首次分配或应用待生效的模型/电脑切换时,若确认所选模型的可用账号额度耗尽,
同样显示限额原因并接入上述等待。组所在电脑只汇总在线、未暂停、支持该模型的成员,
-取已知的最早恢复时间;单个账号仍须等它所有耗尽窗口恢复。没有可信时刻就不自动等待。
+取已知的最早恢复时间;单个账号仍须等它所有耗尽窗口恢复及既有冷却结束。没有可信时刻就不自动等待。
此时保存的任务路线可能还是切换前的账号,不得借用原账号的用量或展示原账号的重置卡,
也不因原账号重置而提前续跑。
尚未发给模型的消息保留原队列项和 clientId,到点重新分配后发送一次;取消或改选仍作废等待。
+原用户气泡保留,随原消息保存恢复活动,桌面与手机均显示「用量已恢复,已自动继续」。
## Codex 重置卡的自动使用