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。

feat(provider-group): 按配额急缓均衡各账号,组设置显示配额进度,发消息前可确认换号

MagicLizida0a9529ebb4
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
index dd4d584a28..5e4e8f48e6 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
@@ -1345,9 +1345,25 @@ describe('远程 Agent:选模型时换 Agent 所在电脑', () => {
resumed: false,
});
expect(boundary.handoff).toContain('Claude Code (on a different computer)');
+ expect(boundary).not.toHaveProperty('switchReason');
expect(h.pending.get('s1')).toBeUndefined();
});
+ it('供应商组按用户确认、为了先用那台的配额换电脑:分隔条写明原因(provider-groups.md §6.2)', async () => {
+ const h = relocationHarness();
+ await performSessionAgentSwitch(h.deps, {
+ ...backToTaskComputer,
+ applyNow: true,
+ providerGroupRelocation: true,
+ providerGroupSwitchReason: 'quota-rebalance',
+ });
+ expect(vi.mocked(h.deps.insertBoundaryMessage).mock.calls[0][1]).toMatchObject({
+ fromAgentDeviceId: 'studio-mac',
+ toAgentDeviceId: null,
+ switchReason: 'quota-rebalance',
+ });
+ });
+
it('挪到另一台电脑:登记前与落地前都按那台的目录校验', async () => {
const h = relocationHarness({ agentDeviceId: null, providerId: 'xd' });
await performSessionAgentSwitch(h.deps, {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index bb6ff84e34..889be1ed58 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -72,8 +72,10 @@ import {
setProviderGroupClaudeUsageReader,
setProviderGroupCodexUsageReader,
setProviderGroupSessionGroupReader,
+ setProviderGroupSessionRebalance,
setProviderGroupTurnProbe,
} from '../provider-group/runtime.js';
+import { readProviderGroupAutoRebalance, writeProviderGroupAutoRebalance } from '../provider-group/sessionPrefs.js';
import { countProviderRunningTurns, type ProviderLocalLoadRoute } from '../provider-group/localLoad.js';
import { remoteAgentHostRunningProviders, resolveRemoteAgentHostClaudeSessionId } from '../remote-agent/host/service.js';
import {
@@ -10493,6 +10495,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
...(switchOptions?.relocate ? { forceRelocation: true } : {}),
// 发送前换电脑:随后的 lazy-create 按任务记录在新电脑上启动,不重复 bootstrap。
...(switchOptions?.beforeSend ? { skipBootstrap: true } : {}),
+ // 用户确认为了先用那台的配额换号:分隔条写明原因。
+ ...(switchOptions?.reason ? { providerGroupSwitchReason: switchOptions.reason } : {}),
// 用户在等锁、读交接素材期间接手:在改动之前停下。
...(isCurrent ? { assertSelectionCurrent: assertCurrent } : {}),
});
@@ -10530,6 +10534,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
fallback: (sessionId, signals, token) => usageLimitAutoResume.onTurnError(sessionId, signals, token),
// 组内电脑的报错用那台机器的本地时间:不带时区的钟点不按本机时区理解。
readResetAt: (signals) => readTurnUsageResetAt(signals, Date.now(), { localTimeZoneTrusted: false }),
+ // 任务里选过「以后自动换」的换号(provider-groups.md §6.2「任务进行中换号」)。
+ readAutoRebalance: readProviderGroupAutoRebalance,
+ writeAutoRebalance: (sessionId) => writeProviderGroupAutoRebalance(sessionId),
now: () => Date.now(),
log,
});
@@ -10537,6 +10544,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 模型列表把归组的任务显示在组那一项下(provider-groups.md §10)。
const sessionGroupService = providerGroupService;
setProviderGroupSessionGroupReader((sessionId) => sessionGroupService.sessionGroup(sessionId));
+ // 电脑与手机发送前问要不要换号、记下用户的决定(provider-groups.md §6.2「任务进行中换号」)。
+ setProviderGroupSessionRebalance({
+ suggest: (sessionId) => sessionGroupService.rebalanceSuggestion(sessionId),
+ decide: (sessionId, memberKey, remember) => sessionGroupService.rebalanceDecision(sessionId, memberKey, remember),
+ });
// 这台电脑上每个供应商正在运行一轮的任务数:组里「本机」这台显示它,同账号电脑读目录时也带上(§5)。
setProviderGroupLocalLoad(() => countProviderRunningTurns({
listTurnRunningSessions: () => maker.listActiveSessions().filter((s) => s.isTurnRunning()).map((s) => s.id),
@@ -17171,6 +17183,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 等的时候进行中行显示「重新连接中 n/5」。
await providerGroupService?.beforeSend(sessionId, {
...(options?.signal ? { signal: options.signal } : {}),
+ ...(options?.scheduled ? { scheduled: true } : {}),
progress: (state) => agentInputCoordinatorHolder?.setProviderGroupSendReconnect(sessionId, state),
}).catch((error) => {
log.warn('provider group: pre-send check failed', {
diff --git a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
index 5fe0cd3460..d6505ea18d 100644
--- a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
@@ -145,6 +145,11 @@ export interface AgentSwitchBoundaryContent {
toAgentDeviceId?: string | null;
fromAgentDeviceName?: string | null;
toAgentDeviceName?: string | null;
+ /**
+ * 只在供应商组换电脑、且原因要告诉用户时出现:`quota-rebalance` = 用户确认为了先用那台的配额换过去
+ * (原电脑没出问题,provider-groups.md §6.2「任务进行中换号」)。旧端忽略,照常显示「Agent 已改到 X 上运行」。
+ */
+ switchReason?: 'quota-rebalance';
}
export interface AgentSwitchSessionRow {
@@ -619,6 +624,11 @@ export async function performSessionAgentSwitch(
* 只在 applyNow 时生效。
*/
providerGroupRelocation?: boolean;
+ /**
+ * 仅限 main 内部:供应商组换电脑的原因写进分隔条。`quota-rebalance` = 用户确认为了先用那台的配额换过去
+ * (provider-groups.md §6.2「任务进行中换号」)。只在真正换了电脑时写。
+ */
+ providerGroupSwitchReason?: 'quota-rebalance';
},
): Promise<SessionAgentSwitchResult> {
const { sessionId, targetAgentKind, model, providerId, signal } = params;
@@ -987,6 +997,7 @@ export async function performSessionAgentSwitch(
// 强制换电脑时实际运行的电脑由对方选,本机不知道是哪台(也不该显示):分隔条写「另一台电脑」。
fromAgentDeviceName: forcedRelocation ? null : deps.describeAgentDevice?.(currentAgentDeviceId) ?? null,
toAgentDeviceName: forcedRelocation ? null : deps.describeAgentDevice?.(targetAgentDeviceId) ?? null,
+ ...(params.providerGroupSwitchReason ? { switchReason: params.providerGroupSwitchReason } : {}),
}
: {}),
};
diff --git a/apps/desktop/src/main/provider-group/__tests__/ipc.test.ts b/apps/desktop/src/main/provider-group/__tests__/ipc.test.ts
index ce0812b7c2..16195ea87b 100644
--- a/apps/desktop/src/main/provider-group/__tests__/ipc.test.ts
+++ b/apps/desktop/src/main/provider-group/__tests__/ipc.test.ts
@@ -10,6 +10,8 @@ vi.mock('../runtime.js', () => ({
getProviderGroupRouter: vi.fn(),
getProviderGroupRemoteClient: vi.fn(),
readProviderGroupOfSession: vi.fn(),
+ readProviderGroupRebalanceSuggestion: vi.fn(),
+ recordProviderGroupRebalanceDecision: vi.fn(),
}));
vi.mock('../store.js', () => ({ readProviderGroup: vi.fn(), writeProviderGroup: vi.fn(), listProviderGroups: vi.fn() }));
vi.mock('../bindings.js', () => ({ pruneProviderGroupBindings: vi.fn() }));
diff --git a/apps/desktop/src/main/provider-group/__tests__/remoteHandler.test.ts b/apps/desktop/src/main/provider-group/__tests__/remoteHandler.test.ts
index 65130c125b..bb45237fb2 100644
--- a/apps/desktop/src/main/provider-group/__tests__/remoteHandler.test.ts
+++ b/apps/desktop/src/main/provider-group/__tests__/remoteHandler.test.ts
@@ -69,6 +69,7 @@ function deps(overrides: Partial<ProviderGroupRemoteHandlerDeps> = {}) {
markTried: vi.fn(() => new Set<string>()),
triedThisTurn: vi.fn(() => new Set<string>()),
resetTurn: vi.fn(),
+ rebalanceCandidates: vi.fn(() => []),
} satisfies ProviderGroupRouter;
const value = {
scope: () => ({ router, externalLoad, isCurrent: () => ownerCurrent }),
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 43db896225..bf12fb1b31 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
@@ -54,7 +54,7 @@ describe('OpenAI subscription group routing', () => {
return { config, usage, router, pick, writeCooling, remote: config.members[1].key };
}
- it.each(PROVIDER_GROUP_STRATEGIES)('excludes exhausted windows, prefers expiring quota then lower usage (%s)', async (strategy) => {
+ it.each(PROVIDER_GROUP_STRATEGIES)('excludes exhausted windows and prefers the most urgent weekly quota (%s)', async (strategy) => {
const h = openaiHarness();
h.config.strategy = strategy;
h.usage.set(h.remote, quota(40, 60));
@@ -66,9 +66,10 @@ describe('OpenAI subscription group routing', () => {
h.usage.set('local', quota(10, 20));
h.usage.set(h.remote, quota(40, 70, NOW + 3 * 3_600_000));
expect(await h.pick()).toMatchObject({ member: { key: h.remote } });
+ // With the same weekly reset, more quota left wins; a busy 5-hour window short of exhaustion does not count.
h.usage.set('local', quota(80, 20));
h.usage.set(h.remote, quota(20, 30));
- expect(await h.pick()).toMatchObject({ member: { key: h.remote } });
+ expect(await h.pick()).toMatchObject({ member: { key: 'local' } });
expect(h.writeCooling).not.toHaveBeenCalled();
});
@@ -212,24 +213,66 @@ describe('provider-group quota routing', () => {
.toMatchObject({ kind: 'member', member: { key: h.config.members[1].key } });
});
- it.each([false, true])('uses quota that is about to reset first (own task=%s)', async (own) => {
+ // 2026-10-21 用户裁决(provider-groups.md §5):快作废的额度最优先,其次各账号平均。Unit: real directory →
+ // router → scheduler. The old fixed "last 5 hours" tier plus raw usage ignored a week with half left a day before
+ // reset (case 1) and preferred a freshly reset account (case 3); case 2 guards against ranking by distance behind
+ // schedule, which would leave the last 3% of an expiring week unused.
+ it.each([false, true])('uses the quota that most needs using before it resets (own task=%s)', async (own) => {
const h = harness();
const remote = h.config.members[1].key;
- const win = (utilization: number, inMs: number) => ({ utilization, resetsAt: (NOW + inMs) / 1000 });
- const pick = () => h.router.pick({
- providerId: 'anthropic', agentKind: 'claude-code', model: OPUS, ...(own ? { localTask: true as const } : {}),
+ const HOUR = 3_600_000;
+ const week = (utilization: number, inMs: number) => ({
+ updatedAt: NOW, fiveHour: { utilization: 10, resetsAt: (NOW + HOUR) / 1000 }, sevenDay: { utilization, resetsAt: (NOW + inMs) / 1000 },
});
- // Weekly quota resetting within 5 hours wins over lower usage elsewhere.
- h.usage.set('local', snapshot(10, 20));
- h.usage.set(remote, { ...snapshot(10, 70), sevenDay: win(70, 3 * 3_600_000) });
- expect(await pick()).toMatchObject({ kind: 'member', member: { key: remote } });
- // Without an expiring weekly window, a 5-hour window in its last hour comes next.
- h.usage.set('local', { updatedAt: NOW, fiveHour: win(30, 20 * 60_000), sevenDay: win(20, 3 * 86_400_000) });
- h.usage.set(remote, { updatedAt: NOW, fiveHour: win(5, 3 * 3_600_000), sevenDay: win(10, 3 * 86_400_000) });
- expect(await pick()).toMatchObject({ kind: 'member', member: { key: 'local' } });
- // Nothing about to reset: back to plain usage balancing.
- h.usage.set('local', { updatedAt: NOW, fiveHour: win(30, 2 * 3_600_000), sevenDay: win(20, 3 * 86_400_000) });
- expect(await pick()).toMatchObject({ kind: 'member', member: { key: remote } });
+ const pick = async () => {
+ const result = await h.router.pick({
+ providerId: 'anthropic', agentKind: 'claude-code', model: OPUS, ...(own ? { localTask: true as const } : {}),
+ });
+ return result.kind === 'member' ? result.member.key : result.kind;
+ };
+ // A week resetting tomorrow with 50% left beats a mid-week account with more left.
+ h.usage.set('local', week(30, 84 * HOUR));
+ h.usage.set(remote, week(50, 24 * HOUR));
+ expect(await pick()).toBe(remote);
+ // The last 3% of a week resetting in 3 hours still goes first, even though the other account is further behind.
+ h.usage.set('local', week(40, 84 * HOUR));
+ h.usage.set(remote, week(97, 3 * HOUR));
+ expect(await pick()).toBe(remote);
+ // A freshly reset week is not urgent.
+ h.usage.set(remote, week(0, 168 * HOUR));
+ expect(await pick()).toBe('local');
+ });
+
+ // 2026-10-21 用户裁决:5 小时配额快满、离重置还早的号先不分新任务(刚开始就撞上限会被迫换电脑、丢上下文);
+ // 1 小时内就重置的照常分,把剩下的用掉。Unit: real directory → router → scheduler. Minimal input: the more
+ // urgent weekly account sits at 90% of its 5-hour window, resetting in 3 hours versus 30 minutes.
+ it.each([[3 * 3_600_000, 'remote'], [30 * 60_000, 'local']] as const)(
+ 'avoids a nearly full 5-hour window unless it resets soon (resets in %i ms → %s)', async (fiveHourResetInMs, expected) => {
+ const h = harness();
+ const remote = h.config.members[1].key;
+ const DAY = 86_400_000;
+ h.usage.set('local', { updatedAt: NOW, fiveHour: { utilization: 90, resetsAt: (NOW + fiveHourResetInMs) / 1000 },
+ sevenDay: { utilization: 50, resetsAt: (NOW + DAY) / 1000 } });
+ h.usage.set(remote, { updatedAt: NOW, fiveHour: { utilization: 10, resetsAt: (NOW + 3_600_000) / 1000 },
+ sevenDay: { utilization: 20, resetsAt: (NOW + 3.5 * DAY) / 1000 } });
+ const result = await h.pick();
+ expect(result.kind === 'member' ? result.member.key : result.kind).toBe(expected === 'remote' ? remote : 'local');
+ },
+ );
+
+ // Unit / provider-groups.md §10 progress bar: the group status must carry the very window the ranking uses
+ // (the less urgent of total and model weekly), and nothing for an account whose quota cannot be read.
+ it('shows each account the weekly window it is ranked by, and nothing when unknown', async () => {
+ const h = harness();
+ const remote = h.config.members[1].key;
+ const sevenDay = { utilization: 30, resetsAt: 80_000 };
+ h.usage.set('local', { updatedAt: NOW, fiveHour: { utilization: 90, resetsAt: 3_000 }, sevenDay,
+ scoped: [{ modelDisplayName: 'Opus', utilization: 95, resetsAt: 80_000 }] });
+ const weekly = (usedPercent: number) => ({ usedPercent, resetAtMs: 80_000_000, windowMs: 7 * 86_400_000 });
+ expect((await h.router.view('anthropic')).members.map((m) => m.quota)).toEqual([weekly(30), undefined]);
+ expect((await h.router.view('anthropic', OPUS)).members[0].quota).toEqual(weekly(95));
+ h.usage.set(remote, snapshot(10, 20));
+ expect((await h.router.view('anthropic')).members[1].quota).toEqual(weekly(20));
});
it.each(PROVIDER_GROUP_STRATEGIES)('applies quota prefiltering to own tasks with the %s strategy', async (strategy) => {
diff --git a/apps/desktop/src/main/provider-group/__tests__/runtime.test.ts b/apps/desktop/src/main/provider-group/__tests__/runtime.test.ts
index f6ac9f2ade..fc850c7a5b 100644
--- a/apps/desktop/src/main/provider-group/__tests__/runtime.test.ts
+++ b/apps/desktop/src/main/provider-group/__tests__/runtime.test.ts
@@ -225,8 +225,8 @@ describe('provider group runtime quota account selection', () => {
await vi.advanceTimersByTimeAsync(PROVIDER_GROUP_USAGE_READ_TIMEOUT_MS);
for (const member of await firstRead) {
expect(providerGroupMemberUsageState(member, 'gpt-5.3-codex', Date.now(), fastKind))
- .toMatchObject({ limited: true, usagePercent: 100 });
- expect(providerGroupMemberUsageState(member, 'gpt-5.3-codex', Date.now(), slowKind).usagePercent).toBeNull();
+ .toMatchObject({ limited: true, urgency: 0 });
+ expect(providerGroupMemberUsageState(member, 'gpt-5.3-codex', Date.now(), slowKind).urgency).toBeNull();
}
const secondRead = h.read();
await vi.advanceTimersByTimeAsync(PROVIDER_GROUP_USAGE_READ_TIMEOUT_MS);
@@ -243,7 +243,7 @@ describe('provider group runtime quota account selection', () => {
for (const member of await h.read()) {
expect(providerGroupMemberUsageState(member, 'gpt-5.3-codex', Date.now(), fastKind).limited).toBe(true);
expect(providerGroupMemberUsageState(member, 'gpt-5.3-codex', Date.now(), slowKind))
- .toMatchObject({ limited: false, usagePercent: 25 });
+ .toMatchObject({ limited: false, urgency: expect.any(Number) });
expect(member.codexUsage?.appServerBuckets?.__default__?.updatedAt).toBe(native ? startedAt : completedAt);
expect(member.codexUsage?.webSnapshot?.updatedAt).toBe(native ? completedAt : startedAt);
}
@@ -288,7 +288,7 @@ describe('provider group runtime quota account selection', () => {
expect(result).toMatchObject({ kind: 'member', member: { key: 'local' } });
if (result.kind === 'member') {
expect(providerGroupMemberUsageState(result.resolved[0], model, Date.now(), native ? 'codex' : 'pi'))
- .toMatchObject({ limited: true, usagePercent: 100 });
+ .toMatchObject({ limited: true, urgency: 0 });
}
await vi.advanceTimersByTimeAsync(PROVIDER_GROUP_USAGE_READ_TIMEOUT_MS);
});
diff --git a/apps/desktop/src/main/provider-group/__tests__/scheduler.test.ts b/apps/desktop/src/main/provider-group/__tests__/scheduler.test.ts
index 1ef81be3f7..0d08d0a2a0 100644
--- a/apps/desktop/src/main/provider-group/__tests__/scheduler.test.ts
+++ b/apps/desktop/src/main/provider-group/__tests__/scheduler.test.ts
@@ -1,16 +1,10 @@
/**
- * 组策略(provider-groups.md §5):只分给可用、未暂停、没试过的电脑;优先未满载。
+ * 组策略(provider-groups.md §5):只分给可用、未暂停、没试过的电脑;优先未满载;最急着用的额度先用。
*/
import { describe, expect, it } from 'vitest';
-import type { ProviderGroupStrategy } from '../../../shared/providerGroup';
-import {
- pickProviderGroupMember,
- PROVIDER_GROUP_FIVE_HOUR_EXPIRING_MS,
- PROVIDER_GROUP_SAME_RESET_MS,
- PROVIDER_GROUP_WEEKLY_EXPIRING_MS,
- type SchedulableMember,
-} from '../scheduler';
+import { PROVIDER_GROUP_STRATEGIES } from '../../../shared/providerGroup';
+import { pickProviderGroupMember, type SchedulableMember } from '../scheduler';
const m = (key: string, patch: Partial<SchedulableMember> = {}): SchedulableMember => ({
key,
@@ -53,114 +47,29 @@ describe('pickProviderGroupMember', () => {
expect(pickProviderGroupMember(members, 'weight', { random: () => 0.5 })).toBe('b');
});
- it('balances current usage and spreads similar usage across idle computers', () => {
- expect(pickProviderGroupMember([m('a', { usagePercent: 85 }), m('b', { usagePercent: 55, running: 2 })], 'usage')).toBe('b');
- expect(pickProviderGroupMember([m('a', { usagePercent: 40, running: 2 }), m('b', { usagePercent: 45 })], 'usage')).toBe('b');
- expect(pickProviderGroupMember([m('a', { usagePercent: 40, running: 2 }), m('b', { usagePercent: 46 })], 'usage')).toBe('a');
- });
-
- it('uses known usage first, with ordinary load balancing when no current usage is known', () => {
- expect(pickProviderGroupMember([m('unknown'), m('known', { usagePercent: 80 })], 'usage')).toBe('known');
- expect(pickProviderGroupMember([m('a', { running: 1 }), m('b', { usagePercent: null })], 'usage')).toBe('b');
- expect(pickProviderGroupMember([m('a', { usagePercent: 10, usable: false })], 'usage')).toBeNull();
- });
-
- it('keeps concurrency limits ahead of usage ranking, including the all-full fallback', () => {
- const full = m('low', { usagePercent: 10, running: 4 });
- expect(pickProviderGroupMember([full, m('high', { usagePercent: 80 })], 'usage')).toBe('high');
- expect(pickProviderGroupMember([full, m('other', { usagePercent: 5, running: 5 })], 'usage')).toBe('low');
+ it('keeps concurrency limits ahead of quota urgency, including the all-full fallback', () => {
+ const urgent = m('urgent', { urgency: 5, running: 4 });
+ expect(pickProviderGroupMember([urgent, m('calm', { urgency: 0.5 })], 'least')).toBe('calm');
+ // 都满了时仍然先用最急的,而不是单看谁更空。
+ expect(pickProviderGroupMember([m('emptier', { urgency: 0.5, running: 4 }), { ...urgent, running: 6 }], 'least')).toBe('urgent');
});
});
-describe('quota about to reset is used first', () => {
- const NOW = 10_000_000_000;
- const HOUR = 60 * 60_000;
- const pick = (members: SchedulableMember[], strategy: ProviderGroupStrategy = 'usage') =>
- pickProviderGroupMember(members, strategy, { now: NOW });
-
- it('prefers weekly quota resetting within 5 hours over lower usage, earliest reset first', () => {
- const idle = m('idle', { usagePercent: 5 });
- expect(pick([idle, m('weekly', { usagePercent: 70, weeklyResetAtMs: NOW + 4 * HOUR })])).toBe('weekly');
- expect(pick([idle, m('weekly', { usagePercent: 70, weeklyResetAtMs: NOW + PROVIDER_GROUP_WEEKLY_EXPIRING_MS + 1 })]))
- .toBe('idle');
- expect(pick([
- idle,
- m('later', { usagePercent: 10, weeklyResetAtMs: NOW + 4 * HOUR }),
- m('sooner', { usagePercent: 90, weeklyResetAtMs: NOW + 2 * HOUR }),
- ])).toBe('sooner');
- });
-
- it('ranks the weekly tier ahead of the 5-hour tier, which only counts its last hour', () => {
- const fiveHour = m('five-hour', { usagePercent: 20, fiveHourResetAtMs: NOW + 10 * 60_000 });
- const weekly = m('weekly', { usagePercent: 60, weeklyResetAtMs: NOW + 3 * HOUR });
- expect(pick([fiveHour, weekly])).toBe('weekly');
- const idle = m('idle', { usagePercent: 5 });
- expect(pick([idle, fiveHour])).toBe('five-hour');
- expect(pick([idle, m('five-hour', { usagePercent: 20, fiveHourResetAtMs: NOW + PROVIDER_GROUP_FIVE_HOUR_EXPIRING_MS + 1 })]))
- .toBe('idle');
- });
-
- it('balances computers that expire at nearly the same time', () => {
- const reset = NOW + 30 * 60_000;
- const sameTime = [
- m('a', { usagePercent: 40, running: 2, fiveHourResetAtMs: reset }),
- m('b', { usagePercent: 42, fiveHourResetAtMs: reset + PROVIDER_GROUP_SAME_RESET_MS }),
- ];
- expect(pick(sameTime)).toBe('b');
- expect(pick([sameTime[0], { ...sameTime[1], fiveHourResetAtMs: reset + PROVIDER_GROUP_SAME_RESET_MS + 1 }])).toBe('a');
- });
-
- it('keeps concurrency limits ahead of expiring quota and ignores past or unknown resets', () => {
- const fullExpiring = m('full', { usagePercent: 10, running: 4, weeklyResetAtMs: NOW + HOUR });
- expect(pick([fullExpiring, m('open', { usagePercent: 80 })])).toBe('open');
- // 都满了时仍然先用快到期的,而不是单看谁更空。
- expect(pick([m('emptier', { usagePercent: 10, running: 4 }), { ...fullExpiring, key: 'expiring', running: 6 }])).toBe('expiring');
- expect(pick([m('past', { usagePercent: 80, weeklyResetAtMs: NOW }), m('low', { usagePercent: 10 })])).toBe('low');
- expect(pickProviderGroupMember([m('low', { usagePercent: 10 }), m('soon', { usagePercent: 80, weeklyResetAtMs: NOW + HOUR })], 'usage'))
- .toBe('low');
+// 2026-10-21 用户裁决:不论选哪种组策略,都先用最急着用的额度(快作废的最优先,其次各账号平均),
+// 组策略只在一样急的几台里挑。
+describe('the most urgent quota comes first for every strategy', () => {
+ it.each(PROVIDER_GROUP_STRATEGIES)('sends %s picks to the most urgent computer', (strategy) => {
+ expect(pickProviderGroupMember([m('calm', { urgency: 1 }), m('urgent', { urgency: 4, running: 3 })], strategy, {
+ lastPicked: 'urgent', random: () => 0,
+ })).toBe('urgent');
});
- it.each(['least', 'order', 'round', 'weight'] as const)('comes before the %s strategy', (strategy) => {
- expect(pick([m('a', { usagePercent: 10 }), m('soon', { usagePercent: 80, running: 1, weeklyResetAtMs: NOW + HOUR })], strategy)).toBe('soon');
- });
-
- it.each(['least', 'usage', 'order', 'round', 'weight'] as const)(
- 'keeps incomplete usage behind known usage before comparing reset times for %s', (strategy) => {
- const members = [
- m('unknown', { usagePercent: null, weeklyResetAtMs: NOW + 2 * HOUR }),
- m('known', { usagePercent: 80, running: 1 }),
- ];
- expect(pick(members, strategy)).toBe('known');
- expect(pick(members.map((member) => ({ ...member, running: member.running + 4 })), strategy)).toBe('known');
- },
- );
-
- it('ignores reset times and keeps the original strategies when every usage reading is incomplete', () => {
- const members = [
- m('first', { usagePercent: null, running: 1 }),
- m('expiring', { weeklyResetAtMs: NOW + 2 * HOUR }),
- ];
- expect(pick(members, 'order')).toBe('first');
- expect(pick(members, 'least')).toBe('expiring');
- expect(pick(members, 'usage')).toBe('expiring');
- expect(pickProviderGroupMember(members, 'round', { now: NOW, lastPicked: 'expiring' })).toBe('first');
- expect(pickProviderGroupMember(members, 'weight', { now: NOW, random: () => 0 })).toBe('first');
- });
-});
-
-describe('quota comes first for every strategy; the strategy picks among similar computers', () => {
- it.each(['least', 'order', 'round', 'weight'] as const)('sends %s picks to the lower-usage computer', (strategy) => {
- expect(pickProviderGroupMember([m('busy-quota', { usagePercent: 80 }), m('spare', { usagePercent: 10, running: 3 })], strategy, {
- lastPicked: 'spare', random: () => 0,
- })).toBe('spare');
- });
-
- it('lets each strategy choose within the 5-point band', () => {
+ it('lets each strategy choose among computers at least 90% as urgent as the most urgent one', () => {
const similar = [
- m('a', { usagePercent: 12, running: 2, weight: 1 }),
- m('b', { usagePercent: 10, running: 1, weight: 3 }),
- m('c', { usagePercent: 14, weight: 1 }),
- m('far', { usagePercent: 40 }),
+ m('far', { urgency: 1.79 }),
+ m('a', { urgency: 1.9, running: 2, weight: 1 }),
+ m('b', { urgency: 2, running: 1, weight: 3 }),
+ m('c', { urgency: 1.8, weight: 1 }),
];
expect(pickProviderGroupMember(similar, 'order')).toBe('a');
expect(pickProviderGroupMember(similar, 'least')).toBe('c');
@@ -171,8 +80,16 @@ describe('quota comes first for every strategy; the strategy picks among similar
});
it('puts computers without readable usage after known ones, and keeps plain strategies when none is known', () => {
- expect(pickProviderGroupMember([m('shared'), m('own', { usagePercent: 90, running: 3 })], 'order')).toBe('own');
- expect(pickProviderGroupMember([m('a', { running: 1 }), m('b')], 'order')).toBe('a');
+ expect(pickProviderGroupMember([m('shared'), m('own', { urgency: 0.2, running: 3 })], 'order')).toBe('own');
+ expect(pickProviderGroupMember([m('a', { running: 1 }), m('b', { urgency: null })], 'order')).toBe('a');
expect(pickProviderGroupMember([m('a', { running: 1 }), m('b')], 'least')).toBe('b');
});
+
+ // 2026-10-21 用户裁决:5 小时配额快满、离重置还早的先不分新任务(刚开始就撞上限会被迫换电脑),都是这样时照常分。
+ it('avoids a nearly full 5-hour window, even ahead of urgency and of unreadable computers, unless all are like that', () => {
+ const tight = m('tight', { urgency: 9, fiveHourTight: true });
+ expect(pickProviderGroupMember([tight, m('calm', { urgency: 1 })], 'order')).toBe('calm');
+ expect(pickProviderGroupMember([tight, m('api')], 'order')).toBe('api');
+ expect(pickProviderGroupMember([tight, m('also', { urgency: 2, fiveHourTight: true })], 'order')).toBe('tight');
+ });
});
diff --git a/apps/desktop/src/main/provider-group/__tests__/service.test.ts b/apps/desktop/src/main/provider-group/__tests__/service.test.ts
index de10fb0c75..92ed71abe5 100644
--- a/apps/desktop/src/main/provider-group/__tests__/service.test.ts
+++ b/apps/desktop/src/main/provider-group/__tests__/service.test.ts
@@ -17,6 +17,8 @@ import { providerGroupCodexUsageSnapshot, type ProviderGroupCodexUsageSnapshot }
import {
createProviderGroupService,
PROVIDER_GROUP_PRE_SEND_FAILED_TTL_MS,
+ PROVIDER_GROUP_REBALANCE_ACCEPT_TTL_MS,
+ PROVIDER_GROUP_REBALANCE_BACKOFF_MS,
PROVIDER_GROUP_RECENT_DROP_MS,
PROVIDER_GROUP_RECONNECT_MAX_ATTEMPTS,
PROVIDER_GROUP_SUPERSEDED_ERROR,
@@ -68,6 +70,8 @@ function harness(options: {
const bindings = new Map<string, ProviderGroupBinding>();
/** 因组内电脑被移出或组被删除而解除过的任务 → 那个组。 */
const released = new Map<string, ProviderGroupRef>();
+ /** 选过「以后自动换号」的任务。 */
+ const autoRebalance = new Set<string>();
// 现读那台的状态:默认与组内电脑状态同一份离线名单,单测按需逐次指定。
const probe = vi.fn(async (agentDeviceId: string, providerId: string): Promise<ResolvedMemberState> => {
const found = config.members.find((m) => m.agentDeviceId === agentDeviceId && m.providerId === providerId);
@@ -144,6 +148,10 @@ function harness(options: {
continueSession: vi.fn(async () => 'resumed' as const),
fallback: vi.fn(),
readResetAt: vi.fn(() => null),
+ readAutoRebalance: vi.fn((id: string) => autoRebalance.has(id)),
+ writeAutoRebalance: vi.fn(async (id: string) => {
+ autoRebalance.add(id);
+ }),
now: () => now,
// 等原电脑恢复时的退避不真等。
sleep: vi.fn(async (_ms: number) => {}),
@@ -1244,6 +1252,94 @@ describe('beforeSend', () => {
});
});
+// 2026-10-21 用户裁决(provider-groups.md §6.2「任务进行中换号」):上一轮结束后用户发下一条消息前,另一个账号的配额明显
+// 更该先用时提议换号;用户确认才换(可选这个任务以后自动换),定时任务的消息不换。确认、等待与失败都在这里决定,
+// 客户端只问与转达选择,所以从服务入口验证。
+describe('switching accounts between messages to balance quota', () => {
+ // 本机:周配额才用 10%,快一周后才重置;mini:一天后重置,还剩 80%(明显更该先用)。时间单位与 harness 的 now 一致。
+ const paceUsage = (updatedAt: number): Record<string, ClaudeSubscriptionUsageSnapshot> => ({
+ local: { updatedAt, fiveHour: { utilization: 0, resetsAt: 3_000 }, sevenDay: { utilization: 10, resetsAt: 600_000 } },
+ [MINI.key]: { updatedAt, fiveHour: { utilization: 0, resetsAt: 3_000 }, sevenDay: { utilization: 20, resetsAt: 87_400 } },
+ });
+ function paced() {
+ const usage = paceUsage(1_000_000);
+ const h = harness({ members: [LOCAL, MINI], usage });
+ h.bindings.set('s1', { providerId: 'anthropic', memberKey: 'local', at: 1_000_000 });
+ return { ...h, usage };
+ }
+
+ it('offers the account to use first and moves there on the next message only after the user confirms', async () => {
+ const h = paced();
+ expect(await h.service.rebalanceSuggestion('s1')).toMatchObject({
+ kind: 'ask',
+ memberKey: MINI.key,
+ quota: { usedPercent: 20, resetAtMs: 87_400_000 },
+ });
+ await h.service.beforeSend('s1');
+ expect(h.deps.switchAgentLocation).not.toHaveBeenCalled();
+
+ expect(await h.service.rebalanceDecision('s1', MINI.key, false)).toBe(true);
+ const progress = vi.fn();
+ await h.service.beforeSend('s1', { progress });
+ expect(progress).toHaveBeenCalledWith('switching');
+ expect(h.deps.switchAgentLocation).toHaveBeenCalledWith(
+ 's1',
+ { agentKind: 'claude-code', model: MODEL, providerId: MINI.providerId, agentDeviceId: 'mini' },
+ { beforeSend: true, isCurrent: expect.any(Function), reason: 'quota-rebalance' },
+ );
+ expect(h.bindings.get('s1')?.memberKey).toBe(MINI.key);
+ // 确认只管那一条消息;到了那台也不再提议换回来。
+ await h.service.beforeSend('s1');
+ expect(h.deps.switchAgentLocation).toHaveBeenCalledTimes(1);
+ expect(await h.service.rebalanceSuggestion('s1')).toBeNull();
+ });
+
+ it('keeps a scheduled message on the current account and saves the confirmation for the user’s own message', async () => {
+ const h = paced();
+ await h.service.rebalanceDecision('s1', MINI.key, false);
+ await h.service.beforeSend('s1', { scheduled: true });
+ expect(h.deps.switchAgentLocation).not.toHaveBeenCalled();
+ await h.service.beforeSend('s1');
+ expect(h.bindings.get('s1')?.memberKey).toBe(MINI.key);
+ });
+
+ it('does not offer while a reply is running and drops a confirmation whose message was never sent', async () => {
+ const h = paced();
+ h.deps.isTurnRunning.mockReturnValue(true);
+ expect(await h.service.rebalanceSuggestion('s1')).toBeNull();
+ h.deps.isTurnRunning.mockReturnValue(false);
+
+ await h.service.rebalanceDecision('s1', MINI.key, false);
+ h.advance(PROVIDER_GROUP_REBALANCE_ACCEPT_TTL_MS + 1);
+ await h.service.beforeSend('s1');
+ expect(h.deps.switchAgentLocation).not.toHaveBeenCalled();
+ expect(await h.service.rebalanceDecision('s1', 'device:elsewhere:anthropic', false)).toBe(false);
+ });
+
+ it('remembers “switch automatically” for that task only', async () => {
+ const h = paced();
+ h.bindings.set('s2', { providerId: 'anthropic', memberKey: 'local', at: 1_000_000 });
+ await h.service.rebalanceDecision('s1', MINI.key, true);
+ expect(h.deps.writeAutoRebalance).toHaveBeenCalledWith('s1');
+ expect(await h.service.rebalanceSuggestion('s1')).toMatchObject({ kind: 'auto', memberKey: MINI.key });
+ expect(await h.service.rebalanceSuggestion('s2')).toMatchObject({ kind: 'ask', memberKey: MINI.key });
+ });
+
+ it('sends on the current account when the move fails and stops offering that account for a while', async () => {
+ const h = paced();
+ h.deps.switchAgentLocation.mockRejectedValueOnce(new Error('handoff failed'));
+ await h.service.rebalanceDecision('s1', MINI.key, false);
+ await h.service.beforeSend('s1');
+ expect(h.deps.switchAgentLocation).toHaveBeenCalledTimes(1);
+ expect(h.bindings.get('s1')?.memberKey).toBe('local');
+ expect(await h.service.rebalanceSuggestion('s1')).toBeNull();
+
+ h.advance(PROVIDER_GROUP_REBALANCE_BACKOFF_MS + 1);
+ Object.assign(h.usage, paceUsage(1_000_000 + PROVIDER_GROUP_REBALANCE_BACKOFF_MS + 1));
+ expect(await h.service.rebalanceSuggestion('s1')).toMatchObject({ memberKey: MINI.key });
+ });
+});
+
describe('onTurnError — one decision for every failure (failurePolicy)', () => {
it('switches when the agent there ends mid-turn without a terminal event (default: switch), without cooling it', async () => {
const h = harness();
diff --git a/apps/desktop/src/main/provider-group/__tests__/usage.test.ts b/apps/desktop/src/main/provider-group/__tests__/usage.test.ts
index 6704ebd3e5..6a1186e5de 100644
--- a/apps/desktop/src/main/provider-group/__tests__/usage.test.ts
+++ b/apps/desktop/src/main/provider-group/__tests__/usage.test.ts
@@ -4,23 +4,26 @@ import type { ProviderGroupMember } from '../../../shared/providerGroup';
import {
createProviderGroupUsageReader, providerGroupUsageSnapshot, providerGroupUsageState,
providerGroupCodexUsageSnapshot, providerGroupMemberUsageState,
- providerGroupCodexUsageFromReads,
+ providerGroupCodexUsageFromReads, providerGroupRebalanceTarget,
PROVIDER_GROUP_USAGE_MAX_AGE_MS, PROVIDER_GROUP_USAGE_READ_TIMEOUT_MS,
} from '../usage';
const NOW = 1_000_000;
+const DAY = 86_400_000;
const snapshot = (fiveHour = 20, sevenDay = 40): ClaudeSubscriptionUsageSnapshot => ({
updatedAt: NOW,
fiveHour: { utilization: fiveHour, resetsAt: (NOW + 3_600_000) / 1000 },
- sevenDay: { utilization: sevenDay, resetsAt: (NOW + 86_400_000) / 1000 },
+ sevenDay: { utilization: sevenDay, resetsAt: (NOW + DAY) / 1000 },
});
+// A weekly window resetting in one day has 1/7 of its time left: urgency = (100 - used) × 0.07.
+const urgencyOneDayLeft = (used: number) => expect.closeTo((100 - used) * 0.07);
// Unit: group routing must not let a different model/harness bucket block or refresh this model's quota.
// Existing Claude cases do not cover Codex's per-bucket timestamps, WHAM slot or variable window durations.
describe('OpenAI group quota snapshots', () => {
const bucket = (usedPercent: number, minutes = 300, resetsAt = 3_000) => ({
updatedAt: NOW, primary: { usedPercent, windowMinutes: minutes, resetsAt },
- secondary: { usedPercent: 20, windowMinutes: 10_080, resetsAt: 80_000 },
+ secondary: { usedPercent: 20, windowMinutes: 10_080, resetsAt: (NOW + DAY) / 1000 },
});
const state = (raw: unknown, model = 'gpt-5.3-codex', agentKind = 'codex') =>
providerGroupMemberUsageState({ codexUsage: providerGroupCodexUsageSnapshot(raw) }, model, NOW, agentKind);
@@ -29,42 +32,46 @@ describe('OpenAI group quota snapshots', () => {
const raw = { appServerBuckets: {
codex: bucket(20), spark: { ...bucket(100), limitName: 'GPT-5.3-Codex-Spark' },
}, webSnapshot: bucket(100) };
- expect(state(raw)).toMatchObject({ limited: false, usagePercent: 20 });
+ expect(state(raw)).toMatchObject({ limited: false, urgency: urgencyOneDayLeft(20) });
expect(state(raw, 'gpt-5.3-codex-spark')).toMatchObject({ limited: true, resetAtMs: 3_000_000 });
expect(state(raw, 'gpt-5.3-codex', 'pi').limited).toBe(true);
expect(state(raw, 'chatgpt/gpt-5.3-codex', 'claude-code').limited).toBe(true);
expect(state({ appServerBuckets: raw.appServerBuckets }, 'gpt-5.3-codex', 'pi'))
- .toMatchObject({ limited: false, usagePercent: null });
+ .toMatchObject({ limited: false, urgency: null });
expect(state({ appServerBuckets: { spark: raw.appServerBuckets.spark } }))
- .toMatchObject({ limited: false, usagePercent: null });
+ .toMatchObject({ limited: false, urgency: null });
});
it.each([NOW - PROVIDER_GROUP_USAGE_MAX_AGE_MS - 1, NOW + 60_001, null])(
'does not refresh a stale/undated model bucket from another bucket (%s)', (updatedAt) => {
const raw = { appServerBuckets: { codex: bucket(5), spark: { ...bucket(100), updatedAt, limitName: 'GPT-5.3-Codex-Spark' } } };
- expect(state(raw, 'gpt-5.3-codex-spark')).toMatchObject({ limited: false, usagePercent: null });
+ expect(state(raw, 'gpt-5.3-codex-spark')).toMatchObject({ limited: false, urgency: null });
},
);
- it('does not invent empty quota for expired/malformed windows, and supports single-window plans', () => {
- expect(state({ ...bucket(100), primary: { usedPercent: 100, resetsAt: NOW / 1000 } }))
- .toMatchObject({ limited: false, usagePercent: null });
- expect(state({ ...bucket(20), primary: { usedPercent: '0' } }))
- .toMatchObject({ limited: false, usagePercent: null });
+ it('ranks by the weekly window, does not invent quota for expired/malformed ones, and supports single-window plans', () => {
+ const weekly = (secondary: unknown) => state({ ...bucket(20), secondary });
+ expect(weekly({ usedPercent: 100, windowMinutes: 10_080, resetsAt: NOW / 1000 }))
+ .toMatchObject({ limited: false, urgency: null });
+ expect(weekly({ usedPercent: '0', windowMinutes: 10_080, resetsAt: (NOW + DAY) / 1000 }))
+ .toMatchObject({ limited: false, urgency: null });
expect(state({ ...bucket(100), primary: { usedPercent: 100 } }))
.toMatchObject({ limited: true, resetAtMs: null });
- expect(state({ ...bucket(100), primary: null }))
- .toMatchObject({ limited: false, usagePercent: 20, weeklyResetAtMs: 80_000_000, fiveHourResetAtMs: null });
- expect(state({ ...bucket(20), primary: { usedPercent: 10, windowMinutes: 60, resetsAt: 3_000 } }))
- .toMatchObject({ usagePercent: 20, fiveHourResetAtMs: null });
+ // A busy 5-hour window short of exhaustion does not change urgency; it is tight only when its reset is over an hour away.
+ expect(state(bucket(90))).toMatchObject({ limited: false, fiveHourTight: false, urgency: urgencyOneDayLeft(20) });
+ expect(state(bucket(90, 300, (NOW + 3 * 3_600_000) / 1000)).fiveHourTight).toBe(true);
+ expect(state({ ...bucket(100), primary: null })).toMatchObject({ limited: false, urgency: urgencyOneDayLeft(20) });
+ // 5-hour-only plan: 20% used, 2,000 s of 18,000 s left → 80 / 11.1 = 7.2.
+ expect(weekly(null)).toMatchObject({ limited: false, urgency: expect.closeTo(7.2) });
});
it('preserves legacy single-bucket/web snapshots while dropping identity and credit offers', () => {
const raw = { ...bucket(35), accountId: 'private', resetOffer: { idempotencyKey: 'private' } };
const parsed = providerGroupCodexUsageSnapshot(raw);
- expect(state(parsed)).toMatchObject({ usagePercent: 35, weeklyResetAtMs: 80_000_000, fiveHourResetAtMs: 3_000_000 });
+ expect(state(parsed)).toMatchObject({ limited: false, urgency: urgencyOneDayLeft(20) });
expect(JSON.stringify(parsed)).not.toContain('private');
- expect(state({ ...bucket(65), source: 'openai-web' }, 'gpt-5', 'pi').usagePercent).toBe(65);
+ const web = { ...bucket(65), secondary: { usedPercent: 50, windowMinutes: 10_080, resetsAt: (NOW + DAY) / 1000 } };
+ expect(state({ ...web, source: 'openai-web' }, 'gpt-5', 'pi').urgency).toEqual(urgencyOneDayLeft(50));
});
it('uses freshly read native quotas without depending on an open task or refreshing stale WHAM data', () => {
@@ -73,9 +80,9 @@ describe('OpenAI group quota snapshots', () => {
rateLimits: { primary: { usedPercent: 25, windowMinutes: 300, resetsAt: 3_000 } },
rateLimitsByLimitId: { codex: { primary: { usedPercent: 25, windowMinutes: 300, resetsAt: 3_000 } } },
}, NOW);
- expect(state(fresh)).toMatchObject({ limited: false, usagePercent: 25 });
- expect(state(fresh, 'gpt-5.3-codex', 'pi')).toMatchObject({ limited: false, usagePercent: null });
- expect(state(providerGroupCodexUsageFromReads(bucket(40), null, NOW)).usagePercent).toBe(40);
+ expect(state(fresh)).toMatchObject({ limited: false, urgency: expect.closeTo(6.75) });
+ expect(state(fresh, 'gpt-5.3-codex', 'pi')).toMatchObject({ limited: false, urgency: null });
+ expect(state(providerGroupCodexUsageFromReads(bucket(40), null, NOW)).urgency).toEqual(urgencyOneDayLeft(20));
});
});
const member = (kind: ProviderGroupMember['kind'], agentDeviceId: string | null, providerId = 'anthropic'): ProviderGroupMember => ({
@@ -90,13 +97,58 @@ describe('provider group quota eligibility', () => {
expect(providerGroupUsageState(snapshot(fiveHour, sevenDay), 'opus', NOW).limited).toBe(true);
});
- it('uses both windows and only the selected model’s weekly window', () => {
+ it('ranks by the total and the selected model’s weekly window, whichever is less urgent', () => {
const value = { ...snapshot(), scoped: [{ modelDisplayName: 'Opus', utilization: 100, resetsAt: 3_000 }] };
expect(providerGroupUsageState(value, 'claude-opus-5-5', NOW).limited).toBe(true);
- expect(providerGroupUsageState(value, 'claude-sonnet-5', NOW)).toMatchObject({ limited: false, usagePercent: 40 });
+ expect(providerGroupUsageState(value, 'claude-sonnet-5', NOW)).toMatchObject({ limited: false, urgency: urgencyOneDayLeft(40) });
expect(providerGroupUsageState(value, null, NOW).limited).toBe(false);
- expect(providerGroupUsageState(snapshot(85, 20), 'opus', NOW).usagePercent).toBe(85);
- expect(providerGroupUsageState(snapshot(20, 85), 'opus', NOW).usagePercent).toBe(85);
+ const fastOpus = { ...snapshot(), scoped: [{ modelDisplayName: 'Opus', utilization: 90, resetsAt: (NOW + DAY) / 1000 }] };
+ expect(providerGroupUsageState(fastOpus, 'claude-opus-5-5', NOW).urgency).toEqual(urgencyOneDayLeft(90));
+ // The 5-hour window never changes urgency; it only excludes or marks the account (see the next tests).
+ expect(providerGroupUsageState(snapshot(85, 20), 'opus', NOW).urgency).toEqual(urgencyOneDayLeft(20));
+ expect(providerGroupUsageState({ ...snapshot(), fiveHour: null }, 'opus', NOW).urgency).toEqual(urgencyOneDayLeft(40));
+ });
+
+ // 2026-10-21 用户裁决(provider-groups.md §5):快作废的额度最优先,其次各账号平均。
+ // Minimal inputs: weekly usage × time left, including an expiring window with little left that must still
+ // outrank a mid-week account that is further behind (a plain "behind schedule" score would not).
+ it.each([
+ ['half the week left, 60% used', 60, 3.5 * DAY, 0.8],
+ ['one day left, 60% used', 60, DAY, 2.8],
+ ['half the week left, 20% used', 20, 3.5 * DAY, 1.6],
+ ['three hours left, 97% used', 97, 3 * 3_600_000, 1.68],
+ ['not started yet', 0, null, 1],
+ ['used without a reset time', 10, null, null],
+ ] as const)('rates urgency as quota left ÷ time left: %s', (_name, used, resetInMs, urgency) => {
+ const value = { updatedAt: NOW, fiveHour: null,
+ sevenDay: { utilization: used, resetsAt: resetInMs === null ? null : (NOW + resetInMs) / 1000 } };
+ expect(providerGroupUsageState(value, 'opus', NOW).urgency).toEqual(urgency === null ? null : expect.closeTo(urgency));
+ });
+
+ // 2026-10-21 用户裁决:5 小时配额快满(85%+)、离重置还早的先不分新任务;1 小时内就重置的照常分,把剩下的用掉。
+ it.each([
+ ['nearly full, resets in 3 hours', 90, 3 * 3_600_000, true],
+ ['nearly full, resets in 30 minutes', 90, 30 * 60_000, false],
+ ['nearly full, reset unknown', 90, null, true],
+ ['already reset, awaiting a new snapshot', 90, 0, false],
+ ['below the line', 80, 3 * 3_600_000, false],
+ ] as const)('marks a tight 5-hour window: %s', (_name, used, resetInMs, tight) => {
+ const value = { ...snapshot(), fiveHour: { utilization: used, resetsAt: resetInMs === null ? null : (NOW + resetInMs) / 1000 } };
+ expect(providerGroupUsageState(value, 'opus', NOW).fiveHourTight).toBe(tight);
+ });
+
+ // 2026-10-21 用户裁决(provider-groups.md §6.2):任务进行中换号会丢一部分上下文,只在明显更该先用另一个账号时提议,
+ // 与新任务排序同一把尺子。Minimal inputs: the 15-point gain line for the same reset, an expiring window, and unknown data.
+ const week = (usedPercent: number, resetInMs: number | null) =>
+ ({ usedPercent, resetAtMs: resetInMs === null ? null : NOW + resetInMs, windowMs: 7 * DAY });
+ it.each([
+ ['same reset, 70% vs 50% used', week(70, DAY), week(50, DAY), 'other'],
+ ['same reset, 60% vs 50% used: too small to be worth it', week(60, DAY), week(50, DAY), null],
+ ['the other expires sooner with as much left', week(40, 3.5 * DAY), week(40, DAY), 'other'],
+ ['this one expires sooner', week(20, DAY), week(0, 3.5 * DAY), null],
+ ['this one has no reset time to compare', week(10, null), week(0, DAY), null],
+ ])('offers switching a running task only when clearly worth it: %s', (_name, current, other, expected) => {
+ expect(providerGroupRebalanceTarget(current, [{ key: 'other', quota: other }], NOW)).toBe(expected);
});
it('waits for the last exhausted window and never borrows another window’s reset', () => {
@@ -105,30 +157,19 @@ describe('provider group quota eligibility', () => {
expect(providerGroupUsageState(unknownReset, 'opus', NOW)).toMatchObject({ limited: true, resetAtMs: null });
});
- it('does not keep blocking a reset window or score it as zero before fresh data arrives', () => {
- const value = { ...snapshot(100, 20), fiveHour: { utilization: 100, resetsAt: NOW / 1000 } };
- expect(providerGroupUsageState(value, 'opus', NOW)).toEqual({
- limited: false, resetAtMs: null, usagePercent: null, weeklyResetAtMs: NOW + 86_400_000, fiveHourResetAtMs: null,
- });
- });
-
- it('reports when unused quota resets, but not for used-up, past or unknown resets', () => {
- expect(providerGroupUsageState(snapshot(20, 40), 'opus', NOW))
- .toMatchObject({ weeklyResetAtMs: NOW + 86_400_000, fiveHourResetAtMs: NOW + 3_600_000 });
- expect(providerGroupUsageState(snapshot(100, 100), 'opus', NOW))
- .toMatchObject({ weeklyResetAtMs: null, fiveHourResetAtMs: null });
- const unknown = { ...snapshot(), fiveHour: { utilization: 0, resetsAt: null }, sevenDay: { utilization: 10, resetsAt: (NOW - 1) / 1000 } };
- expect(providerGroupUsageState(unknown, 'opus', NOW)).toMatchObject({ weeklyResetAtMs: null, fiveHourResetAtMs: null });
- expect(providerGroupUsageState(null, 'opus', NOW)).toMatchObject({ weeklyResetAtMs: null, fiveHourResetAtMs: null });
+ it('does not keep blocking a reset window or rank it as unused before fresh data arrives', () => {
+ const value = { ...snapshot(20, 100), sevenDay: { utilization: 100, resetsAt: NOW / 1000 } };
+ expect(providerGroupUsageState(value, 'opus', NOW))
+ .toEqual({ limited: false, resetAtMs: null, fiveHourTight: false, urgency: null, quota: null });
});
it('keeps unknown and stale data distinct from low usage', () => {
for (const raw of [null, {}, { ...snapshot(), updatedAt: null }, { ...snapshot(), updatedAt: NOW + 120_000 },
- { ...snapshot(), fiveHour: null }, { ...snapshot(), sevenDay: { utilization: '0' } }]) {
- expect(providerGroupUsageState(raw, 'opus', NOW)).toMatchObject({ limited: false, usagePercent: null });
+ { ...snapshot(), sevenDay: null }, { ...snapshot(), sevenDay: { utilization: '0' } }]) {
+ expect(providerGroupUsageState(raw, 'opus', NOW)).toMatchObject({ limited: false, urgency: null });
}
expect(providerGroupUsageState(snapshot(100, 100), 'opus', NOW + PROVIDER_GROUP_USAGE_MAX_AGE_MS + 1))
- .toMatchObject({ limited: false, usagePercent: null });
+ .toMatchObject({ limited: false, urgency: null });
expect(providerGroupUsageState({ ...snapshot(), sevenDay: null, fiveHour: { utilization: 100 } }, 'opus', NOW).limited).toBe(true);
});
diff --git a/apps/desktop/src/main/provider-group/ipc.ts b/apps/desktop/src/main/provider-group/ipc.ts
index ac953f47e5..f04ea59218 100644
--- a/apps/desktop/src/main/provider-group/ipc.ts
+++ b/apps/desktop/src/main/provider-group/ipc.ts
@@ -13,6 +13,7 @@ import {
type ProviderGroupCommand,
type ProviderGroupLocalCommand,
type ProviderGroupConfig,
+ type ProviderGroupRebalanceSuggestion,
type ProviderGroupReshareSummary,
type ProviderGroupSessionGroup,
type ProviderGroupView,
@@ -33,6 +34,8 @@ import {
getProviderGroupRemoteClient,
getProviderGroupRouter,
readProviderGroupOfSession,
+ readProviderGroupRebalanceSuggestion,
+ recordProviderGroupRebalanceDecision,
} from './runtime.js';
import { listProviderGroups, readProviderGroup, writeProviderGroup } from './store.js';
import { invokeProviderManagement } from './managementClient.js';
@@ -57,6 +60,10 @@ export interface ProviderGroupCommandDeps {
listGroups(): Record<string, ProviderGroupConfig>;
/** 这个任务此刻归哪个组(只读本机记录)。 */
sessionGroup(sessionId: string): Promise<ProviderGroupSessionGroup>;
+ /** 用户发下一条消息前要不要提议换号(provider-groups.md §6.2「任务进行中换号」)。 */
+ rebalanceSuggestion(sessionId: string): Promise<ProviderGroupRebalanceSuggestion>;
+ /** 记下用户确认的换号。 */
+ rebalanceDecision(sessionId: string, memberKey: string, remember: boolean): Promise<boolean>;
changed(providerId: string): void;
/**
* 转分享(provider-sharing.md §4.3):分享来的组内电脑的主人对本机分享出去的人逐人同意的结果,设置页据此显示;
@@ -87,6 +94,7 @@ function withReshare(deps: ProviderGroupCommandDeps, view: ProviderGroupView): P
const REMOTE_DEVICE_ID_PATTERN = /^[A-Za-z0-9_.-]{1,128}$/;
const SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
+const MEMBER_KEY_PATTERN = /^[A-Za-z0-9_.:-]{1,300}$/;
export function parseProviderGroupCommand(raw: unknown): ProviderGroupCommand {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throwIpcError('INVALID_PARAMS', 'command required');
@@ -106,6 +114,17 @@ export function parseProviderGroupCommand(raw: unknown): ProviderGroupCommand {
}
return { action: 'session-group', sessionId: value.sessionId as string };
}
+ if (value.action === 'rebalance-suggestion' || value.action === 'rebalance-decision') {
+ if (typeof value.sessionId !== 'string' || !SESSION_ID_PATTERN.test(value.sessionId)) {
+ throwIpcError('INVALID_PARAMS', 'sessionId required');
+ }
+ const sessionId = value.sessionId as string;
+ if (value.action === 'rebalance-suggestion') return { action: 'rebalance-suggestion', sessionId };
+ if (typeof value.memberKey !== 'string' || !MEMBER_KEY_PATTERN.test(value.memberKey) || typeof value.remember !== 'boolean') {
+ throwIpcError('INVALID_PARAMS', 'memberKey and remember required');
+ }
+ return { action: 'rebalance-decision', sessionId, memberKey: value.memberKey as string, remember: value.remember as boolean };
+ }
if (!isProviderGroupProviderId(value.providerId)) throwIpcError('INVALID_PARAMS', 'providerId required');
const providerId = value.providerId as string;
switch (value.action) {
@@ -196,6 +215,10 @@ async function runProviderGroupCommand(
) {
if (command.action === 'list') return deps.listGroups();
if (command.action === 'session-group') return deps.sessionGroup(command.sessionId);
+ if (command.action === 'rebalance-suggestion') return deps.rebalanceSuggestion(command.sessionId);
+ if (command.action === 'rebalance-decision') {
+ return { ok: await deps.rebalanceDecision(command.sessionId, command.memberKey, command.remember) };
+ }
const { providerId } = command;
switch (command.action) {
case 'get': {
@@ -296,6 +319,8 @@ export function createProviderGroupCommandDeps(
localDeviceId: getSelfDeviceId,
listGroups: listProviderGroups,
sessionGroup: readProviderGroupOfSession,
+ rebalanceSuggestion: readProviderGroupRebalanceSuggestion,
+ rebalanceDecision: recordProviderGroupRebalanceDecision,
changed: (providerId) => {
// 组里的电脑变了:重新报转分享(加进来的分享来的电脑要请它的主人同意,移出的不再列着)。
reshare?.kick('group');
diff --git a/apps/desktop/src/main/provider-group/remoteHandler.ts b/apps/desktop/src/main/provider-group/remoteHandler.ts
index 1ff63a749c..a412405f14 100644
--- a/apps/desktop/src/main/provider-group/remoteHandler.ts
+++ b/apps/desktop/src/main/provider-group/remoteHandler.ts
@@ -18,6 +18,7 @@ import {
providerGroupDeviceCount,
providerGroupSummaryForWire,
type ProviderGroupConfig,
+ type ProviderGroupRebalanceSuggestion,
type ProviderGroupRemotePick,
type ProviderGroupRemoteSessionGroup,
type ProviderGroupRemoteUsageRow,
@@ -43,6 +44,10 @@ export interface ProviderGroupRemoteHandlerDeps {
replaceReportedUsage(controller: string, sinceDay: string | null, rows: ProviderGroupRemoteUsageRow[]): void;
/** 这台电脑上的任务此刻归哪个组(只读本机记录,读不到为 null)。 */
sessionGroup(sessionId: string): Promise<ProviderGroupSessionGroup>;
+ /** 手机、远程控制发下一条消息前:这台电脑上的任务要不要提议换号(provider-groups.md §6.2「任务进行中换号」)。 */
+ rebalanceSuggestion?(sessionId: string): Promise<ProviderGroupRebalanceSuggestion>;
+ /** 记下用户确认的换号。 */
+ rebalanceDecision?(sessionId: string, memberKey: string, remember: boolean): Promise<boolean>;
}
/** 每个账号、每台报告来的电脑最近收下的用量报告序号(乱序到达的旧份丢弃)。按账号的负载对象区分账号。 */
@@ -109,10 +114,26 @@ export async function handleProviderGroupRemote(
controller: string,
raw: unknown,
): Promise<
- ProviderGroupRemotePick | ProviderGroupView | ProviderGroupUsagePartAck | ProviderGroupRemoteSessionGroup | Record<string, never>
+ | ProviderGroupRemotePick
+ | ProviderGroupView
+ | ProviderGroupUsagePartAck
+ | ProviderGroupRemoteSessionGroup
+ | ProviderGroupRebalanceSuggestion
+ | { ok: boolean }
+ | Record<string, never>
> {
const request = parseProviderGroupRemoteRequest(raw);
if (request.action === 'session-group') return { group: await deps.sessionGroup(request.sessionId) };
+ if (request.action === 'rebalance-suggestion') {
+ return deps.rebalanceSuggestion ? await deps.rebalanceSuggestion(request.sessionId) : null;
+ }
+ if (request.action === 'rebalance-decision') {
+ return {
+ ok: deps.rebalanceDecision
+ ? await deps.rebalanceDecision(request.sessionId, request.memberKey, request.remember)
+ : false,
+ };
+ }
const scope = deps.scope();
switch (request.action) {
case 'pick': {
diff --git a/apps/desktop/src/main/provider-group/remoteRegistration.ts b/apps/desktop/src/main/provider-group/remoteRegistration.ts
index e50c9b0967..2e3c471920 100644
--- a/apps/desktop/src/main/provider-group/remoteRegistration.ts
+++ b/apps/desktop/src/main/provider-group/remoteRegistration.ts
@@ -15,7 +15,9 @@ import {
import {
getProviderGroupOwnerScope,
readProviderGroupOfSession,
+ readProviderGroupRebalanceSuggestion,
readProviderRunningTurnsByProvider,
+ recordProviderGroupRebalanceDecision,
} from './runtime.js';
import { readProviderGroup } from './store.js';
import { isProviderManagementRequest } from '../../shared/providerManagement.js';
@@ -30,6 +32,8 @@ export function registerProviderGroupRemoteHandler(options: { onGroupChanged?: (
replaceReportedUsage: (controller, sinceDay, rows) =>
currentProviderPartyUsageStore().replaceReported(controller, sinceDay, rows),
sessionGroup: readProviderGroupOfSession,
+ rebalanceSuggestion: readProviderGroupRebalanceSuggestion,
+ rebalanceDecision: recordProviderGroupRebalanceDecision,
};
setProviderGroupRemoteHandler({
handle: (controller, raw) => isProviderManagementRequest(raw)
diff --git a/apps/desktop/src/main/provider-group/router.ts b/apps/desktop/src/main/provider-group/router.ts
index bfa0937b65..666f1e2303 100644
--- a/apps/desktop/src/main/provider-group/router.ts
+++ b/apps/desktop/src/main/provider-group/router.ts
@@ -15,7 +15,13 @@ import { findCatalogModel, isModelSelectableForNewRoute } from '@cindy/model-pro
import type { AgentKind } from '@cindy/maker-core';
import type { RemoteAgentCaps } from '@cindy/device-link';
-import type { ProviderGroupConfig, ProviderGroupMember, ProviderGroupView, ProviderGroupUsageLimit } from '../../shared/providerGroup.js';
+import type {
+ ProviderGroupConfig,
+ ProviderGroupMember,
+ ProviderGroupMemberQuota,
+ ProviderGroupView,
+ ProviderGroupUsageLimit,
+} from '../../shared/providerGroup.js';
import type { ProviderGroupBinding } from './bindings.js';
import type { ProviderGroupDirectory, ResolvedProviderGroupMember } from './directory.js';
import { pickProviderGroupMember, type SchedulableMember } from './scheduler.js';
@@ -93,6 +99,14 @@ export type ProviderGroupPickResult =
export interface ProviderGroupRouter {
pick(input: ProviderGroupPickInput): Promise<ProviderGroupPickResult>;
+ /**
+ * 任务进行中换号能换去的电脑(provider-groups.md §6.2「任务进行中换号」):能接这个模型、未暂停、未满载、读得到配额、
+ * 5 小时配额不紧张,不含 `exclude`。用调用方刚读到的组内电脑状态,不再读一次;不记占用、不动轮询游标。
+ */
+ rebalanceCandidates(
+ input: Pick<ProviderGroupPickInput, 'providerId' | 'agentKind' | 'model' | 'localTask'> & { exclude: ReadonlySet<string> },
+ resolved: readonly ResolvedProviderGroupMember[],
+ ): { key: string; label: string; quota: ProviderGroupMemberQuota }[];
view(providerId: string, options?: string | { model?: string; agentKind?: AgentKind; includeGuestSupport?: boolean }): Promise<ProviderGroupView>;
/** 经本组分到这台、正在运行的任务数。 */
running(providerId: string, memberKey: string): number;
@@ -206,16 +220,24 @@ export function createProviderGroupRouter(deps: ProviderGroupRouterDeps): Provid
&& isModelSelectableForNewRoute(found, { userProvider: resolved.view.source === 'user' });
}
+ /** 能接这个模型的任务:提供模型、不在冷却、配额没用完。 */
+ function usableFor(input: Pick<ProviderGroupPickInput, 'providerId' | 'agentKind' | 'model'>) {
+ return (r: ResolvedProviderGroupMember) =>
+ offersModel(r, input.agentKind, input.model) && coolingUntil(input.providerId, r.member.key, input.model) === null
+ && !providerGroupMemberUsageState(r, input.model, deps.now(), input.agentKind).limited;
+ }
+
+ /** 「暂停对外分配」只拦本机以外的新任务;除此之外本机任务与其他使用方同一套组策略,不另设本机优先。 */
+ function pausedFor(input: Pick<ProviderGroupPickInput, 'localTask'>) {
+ return (r: ResolvedProviderGroupMember) => r.member.paused && !(input.localTask === true && r.member.kind === 'local');
+ }
+
return {
async pick(input) {
const config = deps.readGroup(input.providerId);
if (!config) return { kind: 'none' };
- const usable = (r: ResolvedProviderGroupMember) =>
- offersModel(r, input.agentKind, input.model) && coolingUntil(input.providerId, r.member.key, input.model) === null
- && !providerGroupMemberUsageState(r, input.model, deps.now(), input.agentKind).limited;
- // 「暂停对外分配」只拦本机以外的新任务;除此之外本机任务与其他使用方同一套组策略,不另设本机优先。
- const paused = (r: ResolvedProviderGroupMember) =>
- r.member.paused && !(input.localTask === true && r.member.kind === 'local');
+ const usable = usableFor(input);
+ const paused = pausedFor(input);
const resolved = await deps.directory.resolveMembers(input.providerId, config, {
quickMs: PROVIDER_GROUP_PICK_QUICK_MS,
// 已经有一台能用、可以分的电脑(满载仍可接):不再等慢的那几台。未满优先由调度器决定。
@@ -234,16 +256,14 @@ export function createProviderGroupRouter(deps: ProviderGroupRouterDeps): Provid
running: memberRunning(input.providerId, r),
limit: r.member.limit,
weight: r.member.weight,
- usagePercent: quota.usagePercent,
- weeklyResetAtMs: quota.weeklyResetAtMs,
- fiveHourResetAtMs: quota.fiveHourResetAtMs,
+ urgency: quota.urgency,
+ fiveHourTight: quota.fiveHourTight,
};
});
const key = pickProviderGroupMember(schedulable, config.strategy, {
exclude: input.exclude,
lastPicked: lastPicked.get(input.providerId) ?? null,
random: deps.random,
- now,
});
if (!key) {
// Only members that could take this model after a quota reset count. A paused,
@@ -277,6 +297,25 @@ export function createProviderGroupRouter(deps: ProviderGroupRouterDeps): Provid
return { kind: 'member', member: chosen.member, label: chosen.label, resolved };
},
+ rebalanceCandidates(input, resolved) {
+ const config = deps.readGroup(input.providerId);
+ if (!config) return [];
+ const now = deps.now();
+ const usable = usableFor(input);
+ const paused = pausedFor(input);
+ return resolved.flatMap((r) => {
+ if (input.exclude.has(r.member.key) || !usable(r) || paused(r)) return [];
+ if (memberRunning(input.providerId, r) >= r.member.limit) return [];
+ const state = providerGroupMemberUsageState(r, input.model, now, input.agentKind);
+ if (!state.quota || state.fiveHourTight) return [];
+ // 同一台电脑上有几个账号时带上账号名,提示里看得出是哪个号。
+ const sameComputer = config.members.filter((m) => m.kind === r.member.kind && m.agentDeviceId === r.member.agentDeviceId);
+ const account = r.view?.name || r.member.providerName;
+ const label = sameComputer.length > 1 && account ? `${r.label} · ${account}` : r.label;
+ return [{ key: r.member.key, label, quota: state.quota }];
+ });
+ },
+
async view(providerId, options) {
const config = deps.readGroup(providerId);
if (!config) return { providerId, config: null, members: [] };
@@ -323,6 +362,9 @@ export function createProviderGroupRouter(deps: ProviderGroupRouterDeps): Provid
weight: r.member.weight,
paused: r.member.paused,
...(until !== null ? { coolingUntil: until } : {}),
+ // 与选电脑排序用的同一个窗口(provider-groups.md §10 进度条);分享来的电脑本来就不读配额。
+ ...(quota.quota ? { quota: quota.quota } : {}),
+ ...(quota.quota && quota.fiveHourTight ? { fiveHourTight: true as const } : {}),
};
})),
...(model ? { model } : {}),
diff --git a/apps/desktop/src/main/provider-group/runtime.ts b/apps/desktop/src/main/provider-group/runtime.ts
index df0cd030a9..c89e071f0a 100644
--- a/apps/desktop/src/main/provider-group/runtime.ts
+++ b/apps/desktop/src/main/provider-group/runtime.ts
@@ -12,7 +12,11 @@ import { app } from 'electron';
import type { ClaudeSubscriptionUsageSnapshot } from '../../shared/claudeSubscriptionUsage.js';
import { activeOwnerScopeKey } from '../appSessionState.js';
-import { readProviderGroupSummary, type ProviderGroupSessionGroup } from '../../shared/providerGroup.js';
+import {
+ readProviderGroupSummary,
+ type ProviderGroupRebalanceSuggestion,
+ type ProviderGroupSessionGroup,
+} from '../../shared/providerGroup.js';
import { getReceivedShares } from '../device-link/providerShareGuest.js';
import { handleListDevices, defaultDeps as deviceDirectoryDeps } from '../device-link/ipc.js';
import { remoteBackgroundInvoke } from '../device-link/index.js';
@@ -165,6 +169,7 @@ const directoryFacade: ProviderGroupDirectory = {
const routerFacade: ProviderGroupRouter = {
pick: (input) => runtimeForActiveOwner().router.pick(input),
+ rebalanceCandidates: (input, resolved) => runtimeForActiveOwner().router.rebalanceCandidates(input, resolved),
view: async (providerId, options) => {
const runtime = runtimeForActiveOwner();
const view = await runtime.router.view(providerId, options);
@@ -257,6 +262,38 @@ export async function readProviderGroupOfSession(sessionId: string): Promise<Pro
}
}
+/** register 装配供应商组服务后注入:任务进行中换号的提议与用户的决定(provider-groups.md §6.2「任务进行中换号」)。 */
+export interface ProviderGroupSessionRebalance {
+ suggest(sessionId: string): Promise<ProviderGroupRebalanceSuggestion>;
+ decide(sessionId: string, memberKey: string, remember: boolean): Promise<boolean>;
+}
+
+let sessionRebalance: ProviderGroupSessionRebalance | null = null;
+
+export function setProviderGroupSessionRebalance(value: ProviderGroupSessionRebalance | null): void {
+ sessionRebalance = value;
+}
+
+/** 要不要提议换号;还没装配或读不到时不提议(照常发送)。 */
+export async function readProviderGroupRebalanceSuggestion(sessionId: string): Promise<ProviderGroupRebalanceSuggestion> {
+ if (!sessionRebalance) return null;
+ try {
+ return await sessionRebalance.suggest(sessionId);
+ } catch {
+ return null;
+ }
+}
+
+/** 记下用户确认换号;没记上返回 false,这条消息照常发到原来的号。 */
+export async function recordProviderGroupRebalanceDecision(sessionId: string, memberKey: string, remember: boolean): Promise<boolean> {
+ if (!sessionRebalance) return false;
+ try {
+ return await sessionRebalance.decide(sessionId, memberKey, remember);
+ } catch {
+ return false;
+ }
+}
+
/** register 装配会话表后注入:这台电脑上每个供应商正在运行一轮的任务数(localLoad.ts)。 */
export function setProviderGroupLocalLoad(probe: (() => Promise<ReadonlyMap<string, number>>) | null): void {
localLoad = probe;
diff --git a/apps/desktop/src/main/provider-group/scheduler.ts b/apps/desktop/src/main/provider-group/scheduler.ts
index 12f3cea88b..b02161ca0d 100644
--- a/apps/desktop/src/main/provider-group/scheduler.ts
+++ b/apps/desktop/src/main/provider-group/scheduler.ts
@@ -11,12 +11,12 @@ export interface SchedulableMember {
running: number;
limit: number;
weight: number;
- /** Higher of the current 5-hour / weekly usage percentages; unknown stays null. */
- usagePercent?: number | null;
- /** 总周额度还没用完时的重置时刻(unix ms);未知、已重置或已用完为 null。 */
- weeklyResetAtMs?: number | null;
- /** 5 小时额度还没用完时的重置时刻(unix ms);口径同上。 */
- fiveHourResetAtMs?: number | null;
+ /**
+ * 额度有多急着用(usage.ts:剩下的额度 ÷ 剩下的时间)。1 = 正好按时间用完,越大越该先用;读不到为 null。
+ */
+ urgency?: number | null;
+ /** 5 小时配额快满、离重置还早(usage.ts):先不分新任务,除非别的都不行。 */
+ fiveHourTight?: boolean;
}
export interface PickOptions {
@@ -26,25 +26,10 @@ export interface PickOptions {
lastPicked?: string | null;
/** [0, 1) 随机数,按权重时使用。 */
random?: () => number;
- /** 现在(unix ms),判断配额快到期时使用;不给时跳过快到期优先。 */
- now?: number;
}
-/**
- * 「快到期先用」(2026-10-15 用户裁决):配额一重置,没用完的部分就浪费了。按顺序看两档,
- * 每周的优先,然后是 5 小时的;同一档里先用重置最早的。
- */
-export const PROVIDER_GROUP_WEEKLY_EXPIRING_MS = 5 * 60 * 60_000;
-export const PROVIDER_GROUP_FIVE_HOUR_EXPIRING_MS = 60 * 60_000;
-/** 重置时刻相差不到这么多算同时到期,再比已用百分比,同时开的任务不全压到一台。 */
-export const PROVIDER_GROUP_SAME_RESET_MS = 10 * 60_000;
-/** 已用百分比与最低值相差不超过这么多算用量相近,交给组策略挑。 */
-export const PROVIDER_GROUP_SIMILAR_USAGE_PERCENT = 5;
-
-const EXPIRING_TIERS: ReadonlyArray<readonly [(m: SchedulableMember) => number | null | undefined, number]> = [
- [(m) => m.weeklyResetAtMs, PROVIDER_GROUP_WEEKLY_EXPIRING_MS],
- [(m) => m.fiveHourResetAtMs, PROVIDER_GROUP_FIVE_HOUR_EXPIRING_MS],
-];
+/** 不低于最急那台的这个比例算一样急,交给组策略挑:同时开的几个任务不全压到一台。 */
+export const PROVIDER_GROUP_SIMILAR_URGENCY = 0.9;
/**
* 只分给可用、未暂停、没试过的电脑;优先未满载的,都满了时分给相对最空的一台(并发上限只用来
@@ -59,8 +44,8 @@ export function pickProviderGroupMember(
const eligible = members.filter((m) => m.usable && !m.paused && !options.exclude?.has(m.key));
if (eligible.length === 0) return null;
const open = eligible.filter((m) => m.running < m.limit);
- if (open.length === 0) return leastBusy(byQuota(eligible, options.now)).key;
- const candidates = byQuota(open, options.now);
+ if (open.length === 0) return leastBusy(byQuota(eligible)).key;
+ const candidates = byQuota(open);
switch (strategy) {
case 'order':
return candidates[0].key;
@@ -87,35 +72,17 @@ export function pickProviderGroupMember(
}
/**
- * 配额先比(2026-10-15 用户裁决:目的是尽快把快重置的配额用掉),对所有组策略生效:
- * 先留快到期的那一批,再留已用百分比最低的(相差 5 个百分点以内都算)。读不到用量的电脑(别人分享的、
+ * 配额先比,对所有组策略生效(2026-10-21 用户裁决:快作废的额度最优先,其次各账号平均):先避开 5 小时配额
+ * 快满、离重置还早的(都是这样时不避开),再只留最急的那几台(不低于最急那台的 90%)。读不到用量的电脑(别人分享的、
* 尚未接入用量的订阅或 API 连接)排在读得到的后面;全部读不到时不筛,原样交给组策略。保持组里的顺序。
*/
-function byQuota(open: readonly SchedulableMember[], now: number | undefined): readonly SchedulableMember[] {
- const known = open.filter((member) => typeof member.usagePercent === 'number' && Number.isFinite(member.usagePercent));
- if (known.length === 0) return open;
- const pool = expiringFirst(known, now) ?? known;
- const lowest = Math.min(...pool.map((member) => member.usagePercent!));
- // Small quota differences should not send every simultaneous task to the same computer.
- return pool.filter((member) => member.usagePercent! <= lowest + PROVIDER_GROUP_SIMILAR_USAGE_PERCENT);
-}
-
-/**
- * 未满载的电脑里,额度快到期的那一批:先看每周的,没有再看 5 小时的;只留重置最早的(及与它几乎同时的)。
- * 都不快到期返回 null。
- */
-function expiringFirst(open: readonly SchedulableMember[], now: number | undefined): SchedulableMember[] | null {
- if (now === undefined) return null;
- for (const [resetAt, within] of EXPIRING_TIERS) {
- const soon = open.filter((m) => {
- const at = resetAt(m);
- return typeof at === 'number' && at > now && at - now <= within;
- });
- if (soon.length === 0) continue;
- const earliest = Math.min(...soon.map((m) => resetAt(m)!));
- return soon.filter((m) => resetAt(m)! - earliest <= PROVIDER_GROUP_SAME_RESET_MS);
- }
- return null;
+function byQuota(open: readonly SchedulableMember[]): readonly SchedulableMember[] {
+ const roomy = open.filter((member) => !member.fiveHourTight);
+ const pool = roomy.length > 0 ? roomy : open;
+ const known = pool.filter((member) => typeof member.urgency === 'number' && Number.isFinite(member.urgency));
+ if (known.length === 0) return pool;
+ const top = Math.max(...known.map((member) => member.urgency!));
+ return known.filter((member) => member.urgency! >= top * PROVIDER_GROUP_SIMILAR_URGENCY);
}
/** 正在运行最少的一台;相同时按组里的顺序。 */
diff --git a/apps/desktop/src/main/provider-group/service.ts b/apps/desktop/src/main/provider-group/service.ts
index 536539a4b6..b025c7bdec 100644
--- a/apps/desktop/src/main/provider-group/service.ts
+++ b/apps/desktop/src/main/provider-group/service.ts
@@ -8,6 +8,8 @@
* 恢复:按退避最多重试 5 次,恢复了就留在原电脑继续,都不行再换。别的电脑上的组读不到(常见是任务就在组所在
* 电脑上、它自己断了)时换不了电脑,只等任务所在那台恢复。
* 3. **发送前**:已归组的任务所在那台现在不能用时,先交接到下一台,这条消息直接发到新电脑;离线时同样先等。
+ * 用户自己发消息前确认过换号(电脑与手机的提示,或这个任务选过「以后自动换」)时,先换到那台再发
+ * (2026-10-21 用户裁决:换号会丢一部分上下文,只在用户知情确认时换)。
*
* 没归过组、但正用着组那一项的老任务(建组前就在用,或运行过之后才换到组那一项)在启动 Agent 前纳入组,
* 不挪动它;当时没纳入的(一直开着、或启动时问不到组所在电脑)出错时再补上,然后照常换电脑。
@@ -28,6 +30,8 @@ import {
import type {
ProviderGroupConfig,
ProviderGroupMember,
+ ProviderGroupMemberQuota,
+ ProviderGroupRebalanceSuggestion,
ProviderGroupRemoteCoolCause,
ProviderGroupRemotePick,
ProviderGroupSessionGroup,
@@ -43,7 +47,7 @@ import {
import type { ProviderGroupBinding, ProviderGroupRef } from './bindings.js';
import type { ProviderGroupDirectory } from './directory.js';
import type { ProviderGroupGuestSwitch } from './guestSwitch.js';
-import { providerGroupMemberUsageState } from './usage.js';
+import { providerGroupMemberUsageState, providerGroupRebalanceTarget } from './usage.js';
import {
PROVIDER_GROUP_DEFAULT_COOLDOWN_MS,
PROVIDER_GROUP_FAILURE_COOLDOWN_MS,
@@ -184,9 +188,16 @@ export interface ProviderGroupServiceDeps {
switchAgentLocation(
sessionId: string,
route: { agentKind: AgentKind; model: string; providerId: string | null; agentDeviceId: string | null },
- /** `relocate`:位置不变也重新交接、新建会话(分享的人换电脑,实际运行的电脑由组所在电脑重新选)。 */
- options?: { beforeSend?: boolean; isCurrent?: () => boolean; relocate?: boolean },
+ /**
+ * `relocate`:位置不变也重新交接、新建会话(分享的人换电脑,实际运行的电脑由组所在电脑重新选)。
+ * `reason: 'quota-rebalance'`:用户确认为了先用那台的配额换过去,分隔条写明原因。
+ */
+ options?: { beforeSend?: boolean; isCurrent?: () => boolean; relocate?: boolean; reason?: 'quota-rebalance' },
): Promise<void>;
+ /** 这个任务选过「以后自动换,不再询问」(provider-groups.md §6.2「任务进行中换号」)。不提供 = 都没选过。 */
+ readAutoRebalance?(sessionId: string): boolean;
+ /** 记下这个任务以后自动换号。 */
+ writeAutoRebalance?(sessionId: string): Promise<void>;
/**
* 分享的人这边的「需要换一台」凭证(guestSwitch.ts);不提供 = 分享来的供应商出错时一律交回原有处理。
*/
@@ -277,11 +288,24 @@ export interface ProviderGroupService {
* 不问组所在电脑。
*/
sessionGroup(sessionId: string): Promise<ProviderGroupSessionGroup>;
+ /**
+ * 用户自己发下一条消息前(电脑与手机的发送按钮):任务所在那台能用、组里另一台的配额明显更该先用时返回提议
+ * (provider-groups.md §6.2「任务进行中换号」)。这个任务选过「以后自动换」时 `kind` 为 `auto`,客户端不再弹窗、直接确认。
+ * 正在回复、没归组、读不到配额时返回 null。只读,不记占用。
+ */
+ rebalanceSuggestion(sessionId: string): Promise<ProviderGroupRebalanceSuggestion>;
+ /**
+ * 用户确认换号:这个任务接下来的一次发送(PROVIDER_GROUP_REBALANCE_ACCEPT_TTL_MS 内)先换到 `memberKey` 再发;
+ * `remember` = 以后自动换。`memberKey` 不在组里返回 false。
+ */
+ rebalanceDecision(sessionId: string, memberKey: string, remember: boolean): Promise<boolean>;
}
export interface ProviderGroupBeforeSendOptions {
/** 这次发送被停止或取消:等原电脑恢复时就此停下,不再换电脑。 */
signal?: AbortSignal;
+ /** 定时任务的发送:不使用用户为下一条消息确认的换号。 */
+ scheduled?: boolean;
/** 等原电脑恢复的进度(第几次重试);`switching` = 没等到,开始换电脑。 */
progress?(state: { attempt: number; maxAttempts: number } | 'switching'): void;
}
@@ -303,6 +327,12 @@ export interface ProviderGroupTurnErrorHooks {
/** 发送前检查组内电脑状态的上限:读不到就照常发送,不让一台卡住的电脑拖慢每次发送。 */
export const PROVIDER_GROUP_BEFORE_SEND_TIMEOUT_MS = 3_000;
+/** 用户确认的换号只用于接下来这么久内的一次发送:确认后没发出去(停止、断线)的不留到以后。 */
+export const PROVIDER_GROUP_REBALANCE_ACCEPT_TTL_MS = 2 * 60_000;
+
+/** 换号没换成的那台,这么久内不再提议(看着能用却接不了任务时,不每条消息都打扰一次)。 */
+export const PROVIDER_GROUP_REBALANCE_BACKOFF_MS = 30 * 60_000;
+
/**
* 那台连不上时,换电脑前先等它恢复:同一轮每台最多重试几次。两次之间的等待与中断自愈相同
* (约 3、6、12、20、20 秒,合计约一分钟)。
@@ -350,6 +380,20 @@ type SourcePick =
| { kind: 'unavailable'; usageLimit?: ProviderGroupUsageLimit }
| { kind: 'member'; member: ProviderGroupMember; label: string; labelOf(memberKey: string): string | undefined };
+/** 任务进行中换号的目标:哪台、提示里怎么称呼、它此刻的配额窗口。 */
+interface RebalanceTarget {
+ memberKey: string;
+ label: string;
+ quota: ProviderGroupMemberQuota;
+}
+
+/** 同一台电脑上有几个账号时,提示里带上账号名。 */
+function rebalanceLabel(config: ProviderGroupConfig, memberKey: string, label: string, account: string | undefined): string {
+ const member = config.members.find((m) => m.key === memberKey);
+ const shared = member ? config.members.filter((m) => m.kind === member.kind && m.agentDeviceId === member.agentDeviceId).length > 1 : false;
+ return shared && account ? `${label} · ${account}` : label;
+}
+
/** 组来源:本机的组,或同账号另一台电脑上的组。 */
interface GroupSource {
/** null = 本机的组。 */
@@ -370,6 +414,18 @@ interface GroupSource {
isKnownDown(providerId: string, memberKey: string, model?: string, agentKind?: AgentKind): Promise<boolean>;
/** 发送前:这台现在该不该换掉;null = 读不到,照常发送。 */
shouldMoveAway(providerId: string, config: ProviderGroupConfig, memberKey: string, model: string, agentKind: AgentKind): Promise<{ reason: string } | false | null>;
+ /**
+ * 任务进行中换号(provider-groups.md §6.2):这台能用时,组里明显更该先用的那台(usage.ts providerGroupRebalanceTarget);
+ * 这台本身有问题(交给出问题换电脑)、不值得换或读不到时返回 null。只读。
+ */
+ rebalanceTarget(
+ providerId: string,
+ config: ProviderGroupConfig,
+ memberKey: string,
+ model: string,
+ agentKind: AgentKind,
+ exclude: ReadonlySet<string>,
+ ): Promise<RebalanceTarget | null>;
invalidate(member: ProviderGroupMember): void;
/** 任务记录里 Agent 的位置对应组里哪一项(组所在电脑视角的键);不对应任何组员返回 null。 */
memberKeyOf(groupProviderId: string, row: ProviderGroupSessionRow): Promise<string | null>;
@@ -431,6 +487,10 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
* 不放在这一轮试过的名单里——用户亲自发的消息被接受时会重开一轮(noteUserAction),那份名单随之清空。
*/
const preSendFailed = new Map<string, { keys: string[]; at: number }>();
+ /** 用户为这个任务接下来的一次发送确认的换号(provider-groups.md §6.2「任务进行中换号」)。 */
+ const acceptedRebalance = new Map<string, { memberKey: string; at: number }>();
+ /** 换号没换成的组内电脑(按组区分) → 到这个时刻之前不再提议。 */
+ const rebalanceBackoff = new Map<string, number>();
const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
/** 等 `promise`,但发送被停止时立刻返回 undefined(不再干等退避或一次慢的现读)。 */
@@ -693,6 +753,18 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
if (state.state === 'ok' && !cooling) return false;
return { reason: cooling ? 'cooling' : state.state };
},
+ async rebalanceTarget(providerId, config, memberKey, model, agentKind, exclude) {
+ const resolved = await withTimeout(deps.directory.resolveMembers(providerId, config), PROVIDER_GROUP_BEFORE_SEND_TIMEOUT_MS);
+ const current = resolved?.find((r) => r.member.key === memberKey);
+ if (!resolved || current?.state !== 'ok' || router.coolingUntil(providerId, memberKey, model) !== null) return null;
+ const now = deps.now();
+ const state = providerGroupMemberUsageState(current, model, now, agentKind);
+ if (state.limited || !state.quota) return null;
+ const candidates = router.rebalanceCandidates({ providerId, agentKind, model, localTask: true, exclude }, resolved);
+ const key = providerGroupRebalanceTarget(state.quota, candidates, now);
+ const target = key ? candidates.find((c) => c.key === key) : undefined;
+ return target ? { memberKey: target.key, label: target.label, quota: target.quota } : null;
+ },
invalidate(member) {
deps.directory.invalidate(member.agentDeviceId ?? undefined);
},
@@ -757,6 +829,20 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
if (view?.model !== model && state !== 'offline' && state !== 'unavailable' && state !== 'cooling') return null;
return state === 'offline' || state === 'unavailable' || state === 'cooling' ? { reason: state } : false;
},
+ async rebalanceTarget(providerId, config, memberKey, model, agentKind, exclude) {
+ // 组所在电脑随状态回每台的配额窗口(旧版本不回,就不提议);只换到它看着「可用」(在线、未满载、未暂停、
+ // 不在冷却)且 5 小时配额不紧张的电脑。
+ const view = await withTimeout(remote.view(ownerDeviceId, providerId, model, agentKind), PROVIDER_GROUP_BEFORE_SEND_TIMEOUT_MS);
+ const current = view?.members.find((m) => m.key === memberKey);
+ if (!view || view.model !== model || !current?.quota || (current.state !== 'available' && current.state !== 'full')) return null;
+ const candidates = view.members.flatMap((m) => m.key !== memberKey && !exclude.has(m.key) && m.state === 'available'
+ && m.quota && !m.fiveHourTight && !m.unreachableHere
+ ? [{ key: m.key, label: rebalanceLabel(config, m.key, m.label, m.providerName), quota: m.quota }]
+ : []);
+ const key = providerGroupRebalanceTarget(current.quota, candidates, deps.now());
+ const target = key ? candidates.find((c) => c.key === key) : undefined;
+ return target ? { memberKey: target.key, label: target.label, quota: target.quota } : null;
+ },
invalidate() {
remote.invalidate(ownerDeviceId);
},
@@ -883,6 +969,106 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
return exclude;
}
+ function backoffKey(source: GroupSource, groupProviderId: string, memberKey: string): string {
+ return `${source.ownerDeviceId ?? ''}\u0000${groupProviderId}\u0000${memberKey}`;
+ }
+
+ /** 换号时不考虑的:同一台电脑上的账号(交接只能换电脑),以及刚换失败、还在退避中的。 */
+ function rebalanceExclusion(source: GroupSource, groupProviderId: string, config: ProviderGroupConfig, current: ProviderGroupMember): Set<string> {
+ const exclude = switchExclusion(config, current, new Set());
+ const now = deps.now();
+ for (const member of config.members) {
+ const key = backoffKey(source, groupProviderId, member.key);
+ const until = rebalanceBackoff.get(key);
+ if (until === undefined) continue;
+ if (until > now) exclude.add(member.key);
+ else rebalanceBackoff.delete(key);
+ }
+ return exclude;
+ }
+
+ /**
+ * 提议换号的前提:任务归组、不在回复中、可以由组换电脑(不是伙伴、共享中的任务等),任务记录里的位置就是绑定的那台。
+ * 只读,不改绑定(核对与修正留给发送前检查)。
+ */
+ async function rebalanceContext(sessionId: string) {
+ if (!deps.readBinding(sessionId) || deps.isTurnRunning(sessionId)) return null;
+ const bound = await withTimeout(loadBound(sessionId), PROVIDER_GROUP_BEFORE_SEND_TIMEOUT_MS);
+ if (!bound?.config || !(await deps.isFailoverEligible(sessionId))) return null;
+ const { binding, source, config } = bound;
+ const row = await deps.readSessionRow(sessionId);
+ if (!row?.model || row.remoteHostId) return null;
+ const located = await locatedMemberKey(source, binding.providerId, row);
+ const current = located === binding.memberKey ? config.members.find((m) => m.key === located) : undefined;
+ if (!current || (current.paused && !(source.ownerDeviceId === null && current.kind === 'local'))) return null;
+ return { binding, source, config, row: { ...row, model: row.model }, current };
+ }
+
+ /**
+ * 发送前换号(用户确认过,provider-groups.md §6.2「任务进行中换号」):任务所在那台能用,只是 `target` 的配额更该先用。
+ * 只试这一台,不记「这一轮试过」(原电脑没出问题,之后出错时仍可以换回来);它此刻接不了或交接失败就照常发到原电脑、
+ * 不报错,这台 PROVIDER_GROUP_REBALANCE_BACKOFF_MS 内不再提议。交接期间进行中行显示「正在换一台电脑继续」,
+ * 分隔条写明是为了先用那台的配额。
+ */
+ async function rebalanceBeforeSend(
+ sessionId: string,
+ source: GroupSource,
+ groupProviderId: string,
+ config: ProviderGroupConfig,
+ current: ProviderGroupMember,
+ row: ProviderGroupSessionRow & { model: string },
+ target: string,
+ options: ProviderGroupBeforeSendOptions | undefined,
+ ): Promise<boolean> {
+ const { run, done } = trackRun(sessionId);
+ const isCurrent = () => !run.superseded && options?.signal?.aborted !== true;
+ const backoff = () => rebalanceBackoff.set(backoffKey(source, groupProviderId, target), deps.now() + PROVIDER_GROUP_REBALANCE_BACKOFF_MS);
+ try {
+ options?.progress?.('switching');
+ const pick = await source.pick({
+ sessionId,
+ providerId: groupProviderId,
+ config,
+ agentKind: row.agentKind,
+ model: row.model,
+ exclude: new Set(config.members.map((m) => m.key).filter((key) => key !== target)),
+ });
+ if (!isCurrent()) return false;
+ if (pick.kind !== 'member' || pick.member.key !== target) {
+ backoff();
+ deps.log.info('provider group: the account chosen for balancing is not available now; sending on the current one', { sessionId, to: target });
+ return false;
+ }
+ const localProviderId = current.kind === 'local' && !source.ownerDeviceId ? row.providerId : groupProviderId;
+ const route = source.routeOf(pick.member, localProviderId);
+ await deps.writeBinding(sessionId, bindingFor(source, groupProviderId, target));
+ try {
+ await deps.switchAgentLocation(sessionId, {
+ agentKind: row.agentKind,
+ model: row.model,
+ providerId: route.providerId,
+ agentDeviceId: route.agentDeviceId,
+ }, { beforeSend: true, isCurrent, reason: 'quota-rebalance' });
+ deps.log.info('provider group: moved a task to the account whose quota should be used first', {
+ sessionId,
+ from: current.key,
+ to: target,
+ });
+ return true;
+ } catch (error) {
+ await restoreBindingAfterFailedSwitch(sessionId, source, groupProviderId, config);
+ if (isCurrent()) backoff();
+ deps.log.warn('provider group: moving a task to balance quota failed; sending on the current computer', {
+ sessionId,
+ error: errorText(error),
+ });
+ return false;
+ }
+ } finally {
+ done();
+ }
+ }
+
/** 交接失败后以任务记录为准还原绑定(交接可能已改了位置,也可能没有)。 */
async function restoreBindingAfterFailedSwitch(
sessionId: string,
@@ -1652,6 +1838,13 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
async beforeSend(sessionId, options) {
// 每次发送前重新记:上一条消息发送前换不过去的电脑不带到这一条。
preSendFailed.delete(sessionId);
+ // 用户为这一条消息确认的换号只用这一次;定时任务的发送不用它(留给用户自己那条)。
+ let accepted: { memberKey: string; at: number } | undefined;
+ if (!options?.scheduled) {
+ accepted = acceptedRebalance.get(sessionId);
+ acceptedRebalance.delete(sessionId);
+ if (accepted && deps.now() - accepted.at > PROVIDER_GROUP_REBALANCE_ACCEPT_TTL_MS) accepted = undefined;
+ }
if (!deps.readBinding(sessionId) || deps.isTurnRunning(sessionId)) return;
// 读组设置也算进发送前检查的上限:组所在电脑断线或不响应时保留绑定、照常发送,不等默认的请求超时。
const bound = await withTimeout(loadBound(sessionId), PROVIDER_GROUP_BEFORE_SEND_TIMEOUT_MS);
@@ -1664,7 +1857,7 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
await releaseDeletedGroup(sessionId, groupOf(source, binding.providerId));
return;
}
- if (!config.autoSwitch) return;
+ if (!config.autoSwitch && !accepted) return;
if (!(await deps.isFailoverEligible(sessionId))) return;
const row = await deps.readSessionRow(sessionId);
if (!row?.model || row.remoteHostId) return;
@@ -1674,6 +1867,15 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
if (!current || (current.paused && !(source.ownerDeviceId === null && current.kind === 'local'))) return;
const cached = await source.shouldMoveAway(binding.providerId, config, current.key, row.model, row.agentKind);
if (cached === null) return;
+ // 用户确认过换号、这台也没出问题:换到确认的那台。那台出了问题时交给下面出问题换电脑的流程。
+ if (cached === false && accepted && config.members.some((m) => m.key === accepted.memberKey)
+ && !switchExclusion(config, current, new Set()).has(accepted.memberKey)) {
+ const moved = await rebalanceBeforeSend(
+ sessionId, source, binding.providerId, config, current, { ...row, model: row.model }, accepted.memberKey, options,
+ );
+ if (moved || options?.signal?.aborted) return;
+ }
+ if (!config.autoSwitch) return;
let reason = cached ? cached.reason : null;
const currentRoute = source.routeOf(current, row.providerId);
const { agentDeviceId, providerId } = currentRoute;
@@ -1773,6 +1975,33 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
}
},
+ async rebalanceSuggestion(sessionId) {
+ const context = await rebalanceContext(sessionId);
+ if (!context) return null;
+ const { binding, source, config, row, current } = context;
+ const target = await source.rebalanceTarget(
+ binding.providerId, config, current.key, row.model, row.agentKind,
+ rebalanceExclusion(source, binding.providerId, config, current),
+ );
+ if (!target) return null;
+ return { kind: deps.readAutoRebalance?.(sessionId) ? 'auto' : 'ask', ...target };
+ },
+
+ async rebalanceDecision(sessionId, memberKey, remember) {
+ const loaded = deps.readBinding(sessionId) ? await withTimeout(loadBound(sessionId), PROVIDER_GROUP_BEFORE_SEND_TIMEOUT_MS) : undefined;
+ if (!loaded?.config?.members.some((m) => m.key === memberKey)) return false;
+ acceptedRebalance.set(sessionId, { memberKey, at: deps.now() });
+ if (remember) {
+ try {
+ await deps.writeAutoRebalance?.(sessionId);
+ } catch (error) {
+ // 没记住只影响以后还会再问,这次照常换。
+ deps.log.warn('provider group: remembering automatic balancing failed', { sessionId, error: errorText(error) });
+ }
+ }
+ return true;
+ },
+
claimGuestStartSwitch(sessionId) {
const claimed = deps.guestSwitch?.claim(sessionId) === true;
if (claimed) deps.log.info('provider group: reopening a shared task through the sharer’s group after it did not start', { sessionId });
diff --git a/apps/desktop/src/main/provider-group/sessionPrefs.ts b/apps/desktop/src/main/provider-group/sessionPrefs.ts
new file mode 100644
index 0000000000..8371ac0da5
--- /dev/null
+++ b/apps/desktop/src/main/provider-group/sessionPrefs.ts
@@ -0,0 +1,62 @@
+/**
+ * 任务级的供应商组偏好(docs/product-rules/provider-groups.md §6.2「任务进行中换号」):用户在换号提示里勾了
+ * 「以后自动换,不再询问」的任务,之后用户自己发消息前直接换、不再弹窗。只对那一个任务有效。
+ *
+ * 记在任务所在电脑上(发送前的检查在这里跑),按账号存放,跨重启保留:
+ * `userData/owners/<账号>/provider-group-session-prefs.json`,只有任务 id 与打开的时间,不含消息、凭证或用户身份。
+ * 超出容量时淘汰最久之前打开的。
+ */
+import { activeOwnerScopeKey, ownerScopedUserDataPath } from '../appSessionState.js';
+import { desktopMakerLogger } from '../maker-host/logger-adapter.js';
+import { createOverrideSettingsFile } from '../maker-host/override-settings-file.js';
+
+interface SessionPrefsFile {
+ /** 任务 id → 打开「以后自动换」的时间(unix ms)。 */
+ autoRebalance: Record<string, number>;
+}
+
+const SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
+export const MAX_PROVIDER_GROUP_SESSION_PREFS = 4000;
+
+function prune(sessions: Record<string, number>): Record<string, number> {
+ const entries = Object.entries(sessions);
+ if (entries.length <= MAX_PROVIDER_GROUP_SESSION_PREFS) return sessions;
+ entries.sort((a, b) => b[1] - a[1]);
+ return Object.fromEntries(entries.slice(0, MAX_PROVIDER_GROUP_SESSION_PREFS));
+}
+
+function normalize(raw: unknown): SessionPrefsFile {
+ const value = (raw as Partial<SessionPrefsFile> | null)?.autoRebalance;
+ const out: Record<string, number> = {};
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
+ for (const [sessionId, at] of Object.entries(value)) {
+ if (SESSION_ID_PATTERN.test(sessionId) && typeof at === 'number' && Number.isFinite(at) && at > 0) out[sessionId] = at;
+ }
+ }
+ return { autoRebalance: prune(out) };
+}
+
+const store = createOverrideSettingsFile<SessionPrefsFile>({
+ filePath: () => ownerScopedUserDataPath('provider-group-session-prefs.json'),
+ scopeKey: activeOwnerScopeKey,
+ defaults: { autoRebalance: {} },
+ normalize,
+ log: desktopMakerLogger.child('provider-group-session-prefs'),
+ label: 'provider-group-session-prefs',
+ maxBytes: 512 * 1024,
+ preserveUnreadableFile: true,
+ logLoadedValue: false,
+});
+
+/** 这个任务选过「以后自动换,不再询问」。 */
+export function readProviderGroupAutoRebalance(sessionId: string): boolean {
+ if (!SESSION_ID_PATTERN.test(sessionId)) return false;
+ store.invalidateIfChanged();
+ return store.read().autoRebalance[sessionId] !== undefined;
+}
+
+/** 记下这个任务以后自动换号。 */
+export async function writeProviderGroupAutoRebalance(sessionId: string, now: number = Date.now()): Promise<void> {
+ if (!SESSION_ID_PATTERN.test(sessionId)) return;
+ await store.updateAtomic(({ value }) => ({ autoRebalance: prune({ ...value.autoRebalance, [sessionId]: now }) }));
+}
diff --git a/apps/desktop/src/main/provider-group/usage.ts b/apps/desktop/src/main/provider-group/usage.ts
index 8951b70a11..8bdbde2dad 100644
--- a/apps/desktop/src/main/provider-group/usage.ts
+++ b/apps/desktop/src/main/provider-group/usage.ts
@@ -7,13 +7,98 @@ import {
import { codexLimitBucketKey, matchCodexBucketForModel, resolveCodexBucketTable } from '@cindy/maker-shared/codex-usage-buckets';
import { accountUsageLimitFromWindows, claudeAccountUsageLimit } from '../../shared/accountUsageLimit.js';
-import type { ProviderGroupMember } from '../../shared/providerGroup.js';
+import type { ProviderGroupMember, ProviderGroupMemberQuota } from '../../shared/providerGroup.js';
import { isProviderShareAgentDeviceId } from '../../shared/providerShare.js';
export const PROVIDER_GROUP_USAGE_MAX_AGE_MS = 10 * 60_000;
export const PROVIDER_GROUP_USAGE_READ_TIMEOUT_MS = 1_500;
const REMOTE_USAGE_CACHE_MS = 15_000;
const MAX_CACHED_ACCOUNTS = 512;
+const WEEK_MS = 7 * 86_400_000;
+const FIVE_HOURS_MS = 5 * 3_600_000;
+
+/**
+ * 5 小时配额用到这么多以上算快满:离重置还早时先不分新任务,免得刚开始就撞上限、被迫换电脑丢上下文
+ * (2026-10-21 用户裁决)。5 小时配额是限速,没用完不会少用周配额。
+ */
+export const PROVIDER_GROUP_FIVE_HOUR_TIGHT_PERCENT = 85;
+/** 5 小时配额这么快就重置的,快满也照常分,把剩下的用掉(同日用户裁决)。 */
+export const PROVIDER_GROUP_FIVE_HOUR_RESET_SOON_MS = 60 * 60_000;
+
+/** 5 小时窗口快满、离重置还早或不知道何时重置。已过重置时刻的旧窗口不算(等新快照)。 */
+function fiveHourTight(usedPercent: number | undefined, resetAtMs: number | null, now: number): boolean {
+ if (usedPercent === undefined || usedPercent < PROVIDER_GROUP_FIVE_HOUR_TIGHT_PERCENT) return false;
+ if (resetAtMs === null) return true;
+ return resetAtMs > now && resetAtMs - now > PROVIDER_GROUP_FIVE_HOUR_RESET_SOON_MS;
+}
+
+/** 窗口还剩多少时间(按窗口长度的百分比);没开始计时为 100,已过重置时刻、用过却没有重置时刻为 null。 */
+function timeLeftPercent(window: ProviderGroupMemberQuota, now: number): number | null {
+ if (window.resetAtMs === null) return window.usedPercent > 0 ? null : 100;
+ const left = window.resetAtMs - now;
+ return left > 0 ? Math.min(100, (left / window.windowMs) * 100) : null;
+}
+
+/**
+ * 配额有多急着用:剩下的配额 ÷ 剩下的时间(都按窗口的百分比)。1 = 正好按时间用完;快重置还剩很多的最急,
+ * 刚重置的不急;重置时间相同时剩得多的更急,所以各账号的用量会被拉平(2026-10-21 用户裁决:快作废的最优先,
+ * 其次平均)。没开始计时的窗口没有要作废的,按 1 算;读不到返回 null。
+ */
+function quotaUrgency(window: ProviderGroupMemberQuota, now: number): number | null {
+ const left = timeLeftPercent(window, now);
+ return left === null ? null : Math.max(0, 100 - window.usedPercent) / left;
+}
+
+/**
+ * 任务进行中换号的门槛(2026-10-21 用户确认「明显不划算才提议」):换过去,在它重置前比留在原处多用掉这么多个百分点的
+ * 配额才提议。换号要把对话交接过去(只带最近几轮与摘要),差得不多不打扰用户。
+ */
+export const PROVIDER_GROUP_REBALANCE_MIN_GAIN = 15;
+
+/**
+ * 任务进行中换号换去哪台(provider-groups.md §6.2「任务进行中换号」):候选里挑最急的(与新任务同一把尺子,相同时按组里的
+ * 顺序),再看值不值得——它比当前急,且换过去在它重置前多用掉的配额 = (它的急迫度 − 当前的急迫度) × 它剩下的时间,
+ * 至少 PROVIDER_GROUP_REBALANCE_MIN_GAIN 个百分点。重置时间相同时就是两边剩下的配额差 15 个百分点以上(用了 70%
+ * 对 50%);快作废的一台即使剩得不多也会被提议,刚重置的不会把任务从快作废的那台拉走。读不到返回 null。
+ */
+export function providerGroupRebalanceTarget(
+ current: ProviderGroupMemberQuota,
+ candidates: readonly { key: string; quota: ProviderGroupMemberQuota }[],
+ now: number,
+): string | null {
+ const from = quotaUrgency(current, now);
+ if (from === null) return null;
+ let best: { key: string; urgency: number; quota: ProviderGroupMemberQuota } | null = null;
+ for (const candidate of candidates) {
+ const urgency = quotaUrgency(candidate.quota, now);
+ if (urgency !== null && (!best || urgency > best.urgency)) best = { key: candidate.key, urgency, quota: candidate.quota };
+ }
+ if (!best || best.urgency <= from) return null;
+ const left = timeLeftPercent(best.quota, now);
+ return left !== null && (best.urgency - from) * left >= PROVIDER_GROUP_REBALANCE_MIN_GAIN ? best.key : null;
+}
+
+/**
+ * 几个窗口取最不急的那个(也是设置页进度条画的那个):一个窗口已经用得太快,就不再催这台。有一个读不到就整台读不到。
+ */
+function paceOf(
+ windows: readonly ProviderGroupMemberQuota[],
+ now: number,
+): { urgency: number; window: ProviderGroupMemberQuota } | null {
+ let pace: { urgency: number; window: ProviderGroupMemberQuota } | null = null;
+ for (const window of windows) {
+ const urgency = quotaUrgency(window, now);
+ if (urgency === null) return null;
+ if (!pace || urgency < pace.urgency) pace = { urgency, window };
+ }
+ return pace;
+}
+
+/** 排序用的急不急,加上设置页进度条画的那个窗口;读不到时两者都是 null。 */
+function paceState(windows: readonly ProviderGroupMemberQuota[] | null, now: number) {
+ const pace = windows ? paceOf(windows, now) : null;
+ return { urgency: pace?.urgency ?? null, quota: pace?.window ?? null };
+}
interface CodexUsageWindow {
usedPercent?: number;
@@ -102,12 +187,21 @@ function codexUsageState(snapshot: ProviderGroupCodexUsageSnapshot, model: strin
const limit = accountUsageLimitFromWindows(windows.flatMap((w) => w.usedPercent === undefined
? [] : [{ usedPercent: w.usedPercent, resetsAtSec: w.resetsAt }]), now);
const current = (w: CodexUsageWindow) => w.usedPercent !== undefined && (!w.resetsAt || w.resetsAt * 1000 > now);
- const usagePercent = windows.length > 0 && windows.every(current) ? Math.max(...windows.map((w) => w.usedPercent!)) : null;
- const unusedUntil = (minutes: number) => {
- const w = windows.find((w) => w.windowMinutes === minutes);
- return w && w.usedPercent !== undefined && w.usedPercent < 100 && w.resetsAt && w.resetsAt * 1000 > now ? w.resetsAt * 1000 : null;
+ // 按长于 5 小时的窗口(周额度)排;只有 5 小时窗口的套餐按它排。
+ const timed = windows.filter((w) => w.windowMinutes !== null);
+ const long = timed.filter((w) => w.windowMinutes! * 60_000 > FIVE_HOURS_MS);
+ const paced = long.length > 0 ? long : timed;
+ const tight = timed.some((w) => w.windowMinutes! * 60_000 <= FIVE_HOURS_MS
+ && fiveHourTight(w.usedPercent, w.resetsAt ? w.resetsAt * 1000 : null, now));
+ return {
+ ...limit,
+ fiveHourTight: tight,
+ ...paceState(paced.length > 0 && paced.every(current)
+ ? paced.map((w) => ({
+ usedPercent: w.usedPercent!, resetAtMs: w.resetsAt ? w.resetsAt * 1000 : null, windowMs: w.windowMinutes! * 60_000,
+ }))
+ : null, now),
};
- return { ...limit, usagePercent, weeklyResetAtMs: unusedUntil(10_080), fiveHourResetAtMs: unusedUntil(300) };
}
export function providerGroupMemberUsageState(
@@ -147,27 +241,29 @@ export function providerGroupUsageSnapshot(raw: unknown, now: number): ClaudeSub
};
}
-/** Check exhaustion first. A score requires both current windows, so missing data cannot win as 0%. */
+/**
+ * Check exhaustion first. Ranking uses the weekly window plus the selected model's weekly window; the 5-hour
+ * window excludes an exhausted account and marks a nearly full one that is not about to reset. Missing or stale
+ * data stays unknown rather than looking unused.
+ */
export function providerGroupUsageState(raw: unknown, model: string | null | undefined, now: number) {
const snapshot = providerGroupUsageSnapshot(raw, now);
const limit = claudeAccountUsageLimit(snapshot, model, now);
const current = (w: ClaudeUsageWindow | null | undefined) =>
- w && (!w.resetsAt || w.resetsAt * 1000 > now) ? w.utilization : null;
- const fiveHour = current(snapshot?.fiveHour);
+ w && (!w.resetsAt || w.resetsAt * 1000 > now) ? w : null;
const sevenDay = current(snapshot?.sevenDay);
const scoped = matchScopedWindowForModel(snapshot?.scoped, model);
- const scopedUsage = current(scoped);
- const usagePercent = fiveHour !== null && sevenDay !== null && (!scoped || scopedUsage !== null)
- ? Math.max(fiveHour, sevenDay, scopedUsage ?? 0) : null;
- // Quota left in a window is lost when it resets; only a known future reset with quota left can be "expiring".
- const unusedUntil = (w: ClaudeUsageWindow | null | undefined) =>
- w?.resetsAt && w.resetsAt * 1000 > now && w.utilization < 100 ? w.resetsAt * 1000 : null;
+ const scopedWeek = current(scoped);
+ const fiveHour = snapshot?.fiveHour;
return {
limited: limit?.limited ?? false,
resetAtMs: limit?.resetAtMs ?? null,
- usagePercent,
- weeklyResetAtMs: unusedUntil(snapshot?.sevenDay),
- fiveHourResetAtMs: unusedUntil(snapshot?.fiveHour),
+ fiveHourTight: fiveHour ? fiveHourTight(fiveHour.utilization, fiveHour.resetsAt ? fiveHour.resetsAt * 1000 : null, now) : false,
+ ...paceState(sevenDay && (!scoped || scopedWeek)
+ ? [sevenDay, ...(scopedWeek ? [scopedWeek] : [])].map((w) => ({
+ usedPercent: w.utilization, resetAtMs: w.resetsAt ? w.resetsAt * 1000 : null, windowMs: WEEK_MS,
+ }))
+ : null, now),
};
}
diff --git a/apps/desktop/src/renderer/components/chat/SystemCard.tsx b/apps/desktop/src/renderer/components/chat/SystemCard.tsx
index 7d5f3871d2..3632ba7396 100644
--- a/apps/desktop/src/renderer/components/chat/SystemCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/SystemCard.tsx
@@ -1127,11 +1127,22 @@ function isEnglishSourceHandoff(handoff: string): boolean {
/**
* 远程 Agent 换电脑的分隔条文案:只有边界行带 toAgentDeviceId 时才是换电脑。null = 任务所在电脑 ——
* 在本机打开的任务就是「本机」;远程控制另一台电脑上的任务时那台不是本机,用切换时快照的名字。
+ * 用户确认为了先用那台的配额换过去的(switchReason: 'quota-rebalance')在后面写明原因。
*/
function agentRelocationLabel(
data: Record<string, unknown> | undefined,
sessionId: string | undefined,
t: ReturnType<typeof useTranslation>['t'],
+): string | null {
+ const place = agentRelocationPlace(data, sessionId, t);
+ if (place === null || data?.switchReason !== 'quota-rebalance') return place;
+ return `${place} · ${t('chat.systemCard.agentSwitch.quotaRebalance')}`;
+}
+
+function agentRelocationPlace(
+ data: Record<string, unknown> | undefined,
+ sessionId: string | undefined,
+ t: ReturnType<typeof useTranslation>['t'],
): string | null {
if (!data || !('toAgentDeviceId' in data)) return null;
const name =
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/SystemCard.i18n.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/SystemCard.i18n.test.tsx
index d22fb83cd0..c6a3a8bf17 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/SystemCard.i18n.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/SystemCard.i18n.test.tsx
@@ -27,6 +27,16 @@ it('shows a model-only boundary without inventing a Harness change', () => {
expect(screen.queryByText(/Claude Code/)).toBeNull();
});
+// provider-groups.md §6.2:用户确认为了先用那台的配额换号时,分隔条在位置后写明原因(手机端同一句)。
+it('says why the task moved when the user switched accounts to use quota first', async () => {
+ await i18n.changeLanguage('zh-CN');
+ render(<SystemCard cardType="agent-switch" data={{
+ fromAgentKind: 'cc', toAgentKind: 'cc', toModel: 'claude-opus-5-5',
+ fromAgentDeviceId: null, toAgentDeviceId: 'office-pc', toAgentDeviceName: 'Office PC', switchReason: 'quota-rebalance',
+ }} />);
+ expect(screen.getByRole('separator').getAttribute('aria-label')).toBe('Agent 已改到 Office PC 上运行 · 这个账号的配额更该先用');
+});
+
describe('command card localization boundaries', () => {
it.each(SUPPORTED_LOCALES)('localizes card labels while preserving command data: %s', async (locale) => {
await i18n.changeLanguage(locale);
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 39a15a5ad2..d2bff3d160 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -190,6 +190,7 @@ import {
} from '@/lib/controlledTaskAgentLocation';
import { resolveUsageAccountLocation } from '@/lib/usageAccountLocation';
import { useProviderShareAgentDevices } from '@/features/provider-share/useProviderShareAgentDevices';
+import { offerSessionRebalance, useSessionRebalancePrefetch } from '@/features/provider-group/sessionRebalancePrompt';
import {
canExposeWritableDirsChange,
resolveManualCompactChannel,
@@ -1400,6 +1401,7 @@ function CCAgentSessionContent({
}
}, [session?.status, sessionId, navigate, ownsWindowRoute]);
const vendorAuthGate = useVendorAuthGate();
+ const { confirmWithCheckbox } = useConfirmDialog();
useEffect(() => {
if (!sessionId || !searchJump) return;
@@ -2131,6 +2133,8 @@ function CCAgentSessionContent({
// 仍调 compact-session → pi 拒绝 → confirm 后吃 rejection toast」(codex P2)。
const isRunningRef = useRef(agentStatus.isRunning);
isRunningRef.current = agentStatus.isRunning;
+ // 任务空闲时预先问好要不要换号,发送时不再多等一次往返(provider-groups.md §6.2「任务进行中换号」)。
+ useSessionRebalancePrefetch(sessionId, remoteDeviceId, !agentStatus.isRunning && !readOnly);
// live 供应商目录(含内置 + 自定义,按 agent 挂模型)—— vendor↔model 一致性校验的真源,
// 与模型选择器同源(见下方 M35 vendor fallback effect)。本地 IPC 极快返回,有模块级缓存。
// device-link 远程会话用被控端经隧道带来的 providers(per-provider,fast 判定与本地同口径)。
@@ -4162,6 +4166,17 @@ function CCAgentSessionContent({
message = finalDispatch.message;
}
+ // 上一轮已经结束、用户发下一条消息:供应商组里另一个账号的配额明显更该先用时,问用户要不要换过去
+ // (provider-groups.md §6.2「任务进行中换号」)。只记下用户的选择,这条消息无论换不换都照常发出。
+ if (deliveryMode !== 'steer' && sessionId && !isRunningRef.current) {
+ await offerSessionRebalance({
+ sessionId,
+ ...(remoteDeviceId ? { hostDeviceId: remoteDeviceId } : {}),
+ confirmWithCheckbox,
+ t,
+ });
+ }
+
// ④ Execute send — effort + permissionMode came straight from ChatInput (fresh value)
const sendOptions = {
beforeEnqueue: opts?.beforeEnqueue,
@@ -4248,6 +4263,7 @@ function CCAgentSessionContent({
readOnly,
t,
vendorAuthGate,
+ confirmWithCheckbox,
remoteDeviceId,
sessionHandoffPreparing,
cindyMakeInputLocked,
diff --git a/apps/desktop/src/renderer/features/provider-group/GroupMemberPace.tsx b/apps/desktop/src/renderer/features/provider-group/GroupMemberPace.tsx
new file mode 100644
index 0000000000..ca6e96fdd2
--- /dev/null
+++ b/apps/desktop/src/renderer/features/provider-group/GroupMemberPace.tsx
@@ -0,0 +1,65 @@
+/**
+ * 组内电脑行里的配额进度条(docs/product-rules/provider-groups.md §10,2026-10-21 用户要求:一眼看出各账号
+ * 是不是在平均地用):已用多少、按时间这时候该用到哪(竖线)、多久后重置。数字是组所在电脑选电脑时排序用的
+ * 同一个窗口,不另读那台电脑。
+ *
+ * 这一行整个是展开详情的按钮:按钮里只能放行内元素,所以条用 span 画、对读屏隐藏,数字由旁边的文字说出来。
+ * 颜色与 QuotaBar 同一套额度条 token 和预警分级。
+ */
+import { useTranslation } from 'react-i18next';
+
+import { quotaSeverity } from '@/components/status/QuotaBar';
+import { formatQuotaResetCountdown } from '@/components/status/usageCardModel';
+import { cn } from '@/lib/utils';
+
+import type { ProviderGroupMemberQuota } from '../../../shared/providerGroup';
+
+const FILL = {
+ normal: 'bg-[var(--quota-bar-fill)]',
+ warn: 'bg-[var(--quota-bar-warn)]',
+ crit: 'bg-[var(--quota-bar-crit)]',
+} as const;
+
+/** 跟在状态行后面(前面由调用方放分隔点);几段各自换行,窄的时候不撑破这一行。 */
+export function GroupMemberPace({ quota, nowMs = Date.now() }: { quota: ProviderGroupMemberQuota; nowMs?: number }) {
+ const { t } = useTranslation();
+ const used = Math.round(quota.usedPercent);
+ // 还没开始计时的窗口没有「该用到哪」,也没有重置时间。
+ const expected = quota.resetAtMs === null
+ ? null
+ : Math.round(Math.min(100, Math.max(0, (1 - (quota.resetAtMs - nowMs) / quota.windowMs) * 100)));
+ const reset = quota.resetAtMs === null ? null : formatQuotaResetCountdown(quota.resetAtMs / 1000, nowMs, t);
+ const text = expected === null
+ ? t('providerGroup.member.pace.used', { used })
+ : t('providerGroup.member.pace.usedExpected', { used, expected });
+ return (
+ <>
+ <span data-testid="provider-group-member-pace" className="inline-flex items-center gap-1.5 [font-variant-numeric:tabular-nums]">
+ <span aria-hidden="true" className="relative inline-flex items-center">
+ <span className="inline-flex h-[5px] w-12 overflow-hidden rounded-full bg-[var(--quota-bar-track)]">
+ <span
+ data-testid="provider-group-member-pace-fill"
+ className={cn('h-full rounded-full', used > 0 && 'min-w-[4px]', FILL[quotaSeverity(quota.usedPercent)])}
+ style={{ width: `${quota.usedPercent}%` }}
+ />
+ </span>
+ {expected !== null && (
+ // 竖线比条高出上下各 2px,落在已用部分里也看得见。
+ <span
+ data-testid="provider-group-member-pace-marker"
+ className="pointer-events-none absolute top-1/2 h-[9px] w-[2px] -translate-x-1/2 -translate-y-1/2 bg-[var(--text-primary)]"
+ style={{ left: `${expected}%` }}
+ />
+ )}
+ </span>
+ <span>{text}</span>
+ </span>
+ {reset && (
+ <>
+ <span aria-hidden="true">·</span>
+ <span className="[font-variant-numeric:tabular-nums]">{reset}</span>
+ </>
+ )}
+ </>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/provider-group/ProviderGroupSection.tsx b/apps/desktop/src/renderer/features/provider-group/ProviderGroupSection.tsx
index 229efab05d..16df014541 100644
--- a/apps/desktop/src/renderer/features/provider-group/ProviderGroupSection.tsx
+++ b/apps/desktop/src/renderer/features/provider-group/ProviderGroupSection.tsx
@@ -44,6 +44,7 @@ import {
type ProviderGroupStrategy,
} from '../../../shared/providerGroup';
import { providerShareComputerName, useProviderShareOwnerNameOf } from '../provider-share/providerShareNames';
+import { GroupMemberPace } from './GroupMemberPace';
import { GroupMemberQuota, groupMemberQuotaTarget } from './GroupMemberQuota';
import { GroupMemberReshare, reshareSummaryText } from './GroupMemberReshare';
import { GroupMemberDetailsButton, GroupMemberVersion } from './GroupMemberVersion';
@@ -460,6 +461,12 @@ function MemberRow({
</span>
</>
)}
+ {status?.quota && (
+ <>
+ <span aria-hidden="true">·</span>
+ <GroupMemberPace quota={status.quota} />
+ </>
+ )}
</span>
</span>
</GroupMemberDetailsButton>
diff --git a/apps/desktop/src/renderer/features/provider-group/RemoteProviderGroupMembers.tsx b/apps/desktop/src/renderer/features/provider-group/RemoteProviderGroupMembers.tsx
index 5daa20d1dc..983dfd5ffe 100644
--- a/apps/desktop/src/renderer/features/provider-group/RemoteProviderGroupMembers.tsx
+++ b/apps/desktop/src/renderer/features/provider-group/RemoteProviderGroupMembers.tsx
@@ -20,6 +20,7 @@ import type {
ProviderGroupView,
} from '../../../shared/providerGroup';
import { providerShareComputerName, useProviderShareOwnerNameOf } from '../provider-share/providerShareNames';
+import { GroupMemberPace } from './GroupMemberPace';
import { GroupMemberQuota, groupMemberQuotaTarget } from './GroupMemberQuota';
import { GroupMemberDetailsButton, GroupMemberVersion } from './GroupMemberVersion';
import { memberStatusText } from './ProviderGroupSection';
@@ -288,6 +289,12 @@ function MemberRow({
</span>
</>
)}
+ {status?.quota && (
+ <>
+ <span aria-hidden="true">·</span>
+ <GroupMemberPace quota={status.quota} />
+ </>
+ )}
</span>
</span>
</>
diff --git a/apps/desktop/src/renderer/features/provider-group/__tests__/ProviderGroupSection.test.tsx b/apps/desktop/src/renderer/features/provider-group/__tests__/ProviderGroupSection.test.tsx
index 496f9d601e..34ad3f0660 100644
--- a/apps/desktop/src/renderer/features/provider-group/__tests__/ProviderGroupSection.test.tsx
+++ b/apps/desktop/src/renderer/features/provider-group/__tests__/ProviderGroupSection.test.tsx
@@ -288,6 +288,25 @@ describe('ProviderGroupSection', () => {
expect(within(rows[0]).queryByText(/providerGroup\.member\.runningCount/)).toBeNull();
});
+ // provider-groups.md §10(2026-10-21 用户要求):不展开就能比较各账号用到哪;读不到配额的电脑不画进度条。
+ it('shows each computer’s quota against an even pace without expanding, and nothing when unknown', async () => {
+ realLocale = createInstance();
+ await realLocale.init({ lng: 'zh-CN', resources: { 'zh-CN': { translation: zhCN } }, interpolation: { escapeValue: false } });
+ const DAY = 86_400_000;
+ stored = { strategy: 'least', autoSwitch: true, members: [LOCAL, MINI] };
+ const view = viewOf(stored);
+ // 周配额还剩一半时间:按时间该用到 50%。
+ view.members[0] = { ...view.members[0], quota: { usedPercent: 40, resetAtMs: Date.now() + 3.5 * DAY + 30_000, windowMs: 7 * DAY } };
+ command.mockImplementation(async (cmd: { action: string }) => (cmd.action === 'list' ? { anthropic: stored } : view));
+ render(<ProviderGroupSection providerId="anthropic" providerName="Anthropic" />);
+ const rows = await screen.findAllByTestId('provider-group-member');
+ expect(await within(rows[0]).findByText('已用 40%,该用到 50%')).toBeTruthy();
+ expect(within(rows[0]).getByTestId('provider-group-member-pace-fill').style.width).toBe('40%');
+ expect(within(rows[0]).getByTestId('provider-group-member-pace-marker').style.left).toBe('50%');
+ expect(within(rows[0]).getByText('3天 12小时后重置')).toBeTruthy();
+ expect(within(rows[1]).queryByTestId('provider-group-member-pace')).toBeNull();
+ });
+
it('changes the group strategy and turns automatic switching off', async () => {
stored = { strategy: 'least', autoSwitch: true, members: [LOCAL, MINI] };
render(<ProviderGroupSection providerId="anthropic" providerName="Anthropic" />);
@@ -315,7 +334,7 @@ describe('ProviderGroupSection', () => {
providerState.providers[0].connected = false;
stored = { strategy: 'usage', autoSwitch: true, members: [LOCAL] };
render(<ProviderGroupSection providerId="anthropic" providerName="Claude" />);
- expect(await screen.findByText('能读取订阅用量时,先用配额快重置的电脑,再选用量低的,相近时按组策略')).toBeTruthy();
+ expect(await screen.findByText('能读取订阅用量时,先用快重置、还剩得多的电脑,各账号会按时间均匀用掉;差不多时按组策略')).toBeTruthy();
expect(screen.getByRole('radio', { name: '最少占用' }).getAttribute('aria-checked')).toBe('true');
expect(screen.getByText('给最闲的那台')).toBeTruthy();
expect(screen.queryByRole('radio', { name: '用量均衡' })).toBeNull();
@@ -334,7 +353,7 @@ describe('ProviderGroupSection', () => {
stored = { strategy: 'order', autoSwitch: true, members };
render(<ProviderGroupSection providerId="anthropic" providerName="Anthropic" />);
await screen.findAllByTestId('provider-group-member');
- expect(screen.getByText('能读取订阅用量时,先用配额快重置的电脑,再选用量低的,相近时按组策略')).toBeTruthy();
+ expect(screen.getByText('能读取订阅用量时,先用快重置、还剩得多的电脑,各账号会按时间均匀用掉;差不多时按组策略')).toBeTruthy();
expect(screen.getByRole('radio', { name: '按顺序' }).getAttribute('aria-checked')).toBe('true');
expect(screen.queryByRole('radio', { name: '用量均衡' })).toBeNull();
});
@@ -497,7 +516,7 @@ describe('ProviderGroupSection', () => {
initialConfig={stored}
/>);
await screen.findAllByTestId('provider-group-member');
- expect(screen.getByText('能读取订阅用量时,先用配额快重置的电脑,再选用量低的,相近时按组策略')).toBeTruthy();
+ expect(screen.getByText('能读取订阅用量时,先用快重置、还剩得多的电脑,各账号会按时间均匀用掉;差不多时按组策略')).toBeTruthy();
});
});
diff --git a/apps/desktop/src/renderer/features/provider-group/__tests__/sessionRebalancePrompt.test.ts b/apps/desktop/src/renderer/features/provider-group/__tests__/sessionRebalancePrompt.test.ts
new file mode 100644
index 0000000000..acffcc8881
--- /dev/null
+++ b/apps/desktop/src/renderer/features/provider-group/__tests__/sessionRebalancePrompt.test.ts
@@ -0,0 +1,89 @@
+/**
+ * 发送前问换号(provider-groups.md §6.2「任务进行中换号」,2026-10-21 用户裁决):确认才换,勾「以后自动换」只记这个任务;
+ * 选过以后自动换的不再弹窗;取消不换。提议在任务空闲时预先问好,发送时没有问好的提议(问不到、旧版本、还没问完)就
+ * 立即照常发送,不多等一次往返。用户看到什么、任务所在电脑收到什么由这里决定,所以从发送前调用的真实入口验证。
+ */
+import type { TFunction } from 'i18next';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { i18n } from '@/i18n';
+
+import { offerSessionRebalance, prefetchSessionRebalance, SESSION_REBALANCE_CACHE_MS } from '../sessionRebalancePrompt';
+
+const MINI = 'device:mini:anthropic';
+const t = i18n.t.bind(i18n) as TFunction;
+const suggestion = (kind: 'ask' | 'auto') => ({
+ kind,
+ memberKey: MINI,
+ label: 'Mini',
+ quota: { usedPercent: 20, resetAtMs: Date.now() + 86_400_000, windowMs: 7 * 86_400_000 },
+});
+
+type Answer = { ok: boolean; checked: boolean };
+
+function setup(reply: () => Promise<unknown>, answer: Answer = { ok: false, checked: false }) {
+ const command = vi.fn((request: { action: string }) =>
+ request.action === 'rebalance-suggestion' ? reply() : Promise.resolve({ ok: true }));
+ vi.stubGlobal('window', { electronAPI: { providerGroup: { command } } });
+ const confirmWithCheckbox = vi.fn(async (_options: { title: string; description?: string }) => answer);
+ const decisions = () => command.mock.calls.map(([request]) => request).filter((r) => r.action === 'rebalance-decision');
+ return { command, confirmWithCheckbox, decisions };
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('offerSessionRebalance', () => {
+ it.each([
+ ['switch once', 'ask', { ok: true, checked: false }, false],
+ ['switch and remember for this task', 'ask', { ok: true, checked: true }, true],
+ ['cancel', 'ask', { ok: false, checked: false }, null],
+ ['already set to switch automatically', 'auto', undefined, false],
+ ] as const)('%s', async (_name, kind, answer, remember) => {
+ const h = setup(async () => suggestion(kind), answer);
+ await prefetchSessionRebalance('s1');
+ await offerSessionRebalance({ sessionId: 's1', confirmWithCheckbox: h.confirmWithCheckbox, t });
+
+ expect(h.confirmWithCheckbox).toHaveBeenCalledTimes(kind === 'ask' ? 1 : 0);
+ if (kind === 'ask') {
+ expect(h.confirmWithCheckbox.mock.calls[0][0]).toMatchObject({
+ title: expect.stringContaining('Mini'),
+ description: expect.stringContaining('80%'),
+ });
+ }
+ expect(h.decisions()).toEqual(remember === null
+ ? []
+ : [{ action: 'rebalance-decision', sessionId: 's1', memberKey: MINI, remember }]);
+ // 一次提议只管一条消息:下一条等任务再空闲、重新问过才可能再问。
+ await offerSessionRebalance({ sessionId: 's1', confirmWithCheckbox: h.confirmWithCheckbox, t });
+ expect(h.confirmWithCheckbox).toHaveBeenCalledTimes(kind === 'ask' ? 1 : 0);
+ });
+
+ it('sends at once without asking when nothing usable was fetched beforehand', async () => {
+ // 还在问(慢):不等它。
+ const slow = setup(() => new Promise(() => undefined));
+ void prefetchSessionRebalance('s1');
+ await offerSessionRebalance({ sessionId: 's1', confirmWithCheckbox: slow.confirmWithCheckbox, t });
+ expect(slow.confirmWithCheckbox).not.toHaveBeenCalled();
+
+ // 旧版本不认识这个请求。
+ const old = setup(() => Promise.reject(new Error('[INVALID_PARAMS] unknown provider group action')));
+ await prefetchSessionRebalance('s2');
+ await offerSessionRebalance({ sessionId: 's2', confirmWithCheckbox: old.confirmWithCheckbox, t });
+ expect(old.confirmWithCheckbox).not.toHaveBeenCalled();
+
+ // 问好的提议已经过期(配额快照只在这么久内有效)。
+ vi.useFakeTimers();
+ try {
+ const stale = setup(async () => suggestion('ask'));
+ await prefetchSessionRebalance('s3');
+ vi.advanceTimersByTime(SESSION_REBALANCE_CACHE_MS + 1);
+ await offerSessionRebalance({ sessionId: 's3', confirmWithCheckbox: stale.confirmWithCheckbox, t });
+ expect(stale.confirmWithCheckbox).not.toHaveBeenCalled();
+ expect(stale.decisions()).toEqual([]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/apps/desktop/src/renderer/features/provider-group/sessionRebalancePrompt.ts b/apps/desktop/src/renderer/features/provider-group/sessionRebalancePrompt.ts
new file mode 100644
index 0000000000..5e0c9ab5aa
--- /dev/null
+++ b/apps/desktop/src/renderer/features/provider-group/sessionRebalancePrompt.ts
@@ -0,0 +1,166 @@
+/**
+ * 任务进行中换号(provider-groups.md §6.2,2026-10-21 用户裁决):用户自己发下一条消息前,看任务所在电脑是否提议为了
+ * 均匀用完各账号的配额换一台。要换就弹窗确认(换过去 / 取消,可勾「以后自动换」,只管这个任务);这个任务勾过的
+ * 不再弹窗、直接换,消息里的分隔条写明原因。
+ *
+ * 换号的判断和记录都在任务所在电脑:本机任务问本机,被控电脑上的任务经设备互联问那台。为了不让每次发送都多等一次往返,
+ * 提议在任务空闲时预先问好(上一轮结束、打开任务时,空闲期间每 5 分钟再问),发送时只用问好的结果;没问到、问不到、
+ * 旧版本不认识这个请求都按不提议处理。无论用户怎么选,这条消息都照常发出。
+ */
+import { useEffect } from 'react';
+import type { TFunction } from 'i18next';
+
+import { PROVIDER_GROUP_REMOTE_CHANNEL } from '@cindy/device-link';
+
+import { formatQuotaResetCountdown } from '@/components/status/usageCardModel';
+
+import {
+ parseProviderGroupRebalanceSuggestion,
+ type ProviderGroupCommand,
+ type ProviderGroupRebalanceSuggestion,
+} from '../../../shared/providerGroup';
+
+/** 预先问一次的上限:问不到就当没有提议,不留着挂起的请求。 */
+export const SESSION_REBALANCE_QUERY_TIMEOUT_MS = 5_000;
+/** 问到的提议多久内可用:与组所在电脑判断配额用的快照有效期一致。 */
+export const SESSION_REBALANCE_CACHE_MS = 10 * 60_000;
+/** 任务空闲、开着时多久重新问一次。 */
+export const SESSION_REBALANCE_REFRESH_MS = 5 * 60_000;
+const MAX_PREFETCHED = 200;
+
+type ConfirmWithCheckbox = (options: {
+ title: string;
+ description?: string;
+ confirmText?: string;
+ cancelText?: string;
+ checkboxLabel: string;
+ autoFocusConfirm?: boolean;
+}) => Promise<{ ok: boolean; checked: boolean }>;
+
+type RebalanceRequest = Extract<ProviderGroupCommand, { action: 'rebalance-suggestion' | 'rebalance-decision' }>;
+
+const prefetched = new Map<string, { at: number; suggestion: ProviderGroupRebalanceSuggestion }>();
+const inFlight = new Set<string>();
+
+function cacheKey(sessionId: string, hostDeviceId: string | undefined): string {
+ return `${hostDeviceId ?? ''}\u0000${sessionId}`;
+}
+
+function withTimeout<T>(promise: Promise<T>, fallback: T): Promise<T> {
+ return new Promise((resolve) => {
+ const timer = setTimeout(() => resolve(fallback), SESSION_REBALANCE_QUERY_TIMEOUT_MS);
+ promise.then(
+ (value) => {
+ clearTimeout(timer);
+ resolve(value);
+ },
+ () => {
+ clearTimeout(timer);
+ resolve(fallback);
+ },
+ );
+ });
+}
+
+async function command(hostDeviceId: string | undefined, request: RebalanceRequest): Promise<unknown> {
+ if (hostDeviceId) {
+ const deviceLink = window.electronAPI?.deviceLink;
+ if (typeof deviceLink?.invoke !== 'function') return null;
+ return deviceLink.invoke(hostDeviceId, PROVIDER_GROUP_REMOTE_CHANNEL, [request]);
+ }
+ const api = window.electronAPI?.providerGroup;
+ if (typeof api?.command !== 'function') return null;
+ return api.command(request);
+}
+
+/** 任务空闲时预先问好提议。同一个任务同时只问一次。@param hostDeviceId 任务所在的被控电脑;本机任务不传。 */
+export async function prefetchSessionRebalance(sessionId: string, hostDeviceId?: string): Promise<void> {
+ const key = cacheKey(sessionId, hostDeviceId);
+ if (inFlight.has(key)) return;
+ inFlight.add(key);
+ try {
+ const raw = await withTimeout(command(hostDeviceId, { action: 'rebalance-suggestion', sessionId }), null);
+ prefetched.delete(key);
+ prefetched.set(key, { at: Date.now(), suggestion: parseProviderGroupRebalanceSuggestion(raw) });
+ if (prefetched.size > MAX_PREFETCHED) prefetched.delete(prefetched.keys().next().value!);
+ } finally {
+ inFlight.delete(key);
+ }
+}
+
+/** 开着的任务空闲时预先问好提议:变空闲(上一轮结束、打开任务)时问一次,之后每 5 分钟再问。 */
+export function useSessionRebalancePrefetch(sessionId: string | undefined, hostDeviceId: string | undefined, idle: boolean): void {
+ useEffect(() => {
+ if (!sessionId || !idle) return;
+ void prefetchSessionRebalance(sessionId, hostDeviceId);
+ const timer = setInterval(() => void prefetchSessionRebalance(sessionId, hostDeviceId), SESSION_REBALANCE_REFRESH_MS);
+ return () => clearInterval(timer);
+ }, [sessionId, hostDeviceId, idle]);
+}
+
+/** 取走问好的提议:一次提议只用于一条消息,过期的不用。 */
+function takePrefetched(sessionId: string, hostDeviceId: string | undefined): ProviderGroupRebalanceSuggestion {
+ const key = cacheKey(sessionId, hostDeviceId);
+ const entry = prefetched.get(key);
+ prefetched.delete(key);
+ return entry && Date.now() - entry.at <= SESSION_REBALANCE_CACHE_MS ? entry.suggestion : null;
+}
+
+async function recordDecision(
+ sessionId: string,
+ memberKey: string,
+ remember: boolean,
+ hostDeviceId: string | undefined,
+): Promise<boolean> {
+ try {
+ const raw = await command(hostDeviceId, { action: 'rebalance-decision', sessionId, memberKey, remember });
+ return !!raw && typeof raw === 'object' && (raw as { ok?: unknown }).ok === true;
+ } catch {
+ return false;
+ }
+}
+
+/** 弹窗正文:换到哪台、那台的配额还剩多少、多久重置,以及换过去会丢一部分上下文。 */
+export function describeSessionRebalance(
+ suggestion: NonNullable<ProviderGroupRebalanceSuggestion>,
+ t: TFunction,
+ nowMs = Date.now(),
+): string {
+ const left = Math.max(0, Math.round(100 - suggestion.quota.usedPercent));
+ const reset = suggestion.quota.resetAtMs === null
+ ? null
+ : formatQuotaResetCountdown(suggestion.quota.resetAtMs / 1000, nowMs, t);
+ const quota = reset
+ ? t('providerGroup.rebalance.quotaReset', { left, reset })
+ : t('providerGroup.rebalance.quota', { left });
+ return t('providerGroup.rebalance.description', { label: suggestion.label, quota });
+}
+
+/**
+ * 发送前调用:有问好的提议就按用户的选择记下(任务所在电脑在这条消息发出前换过去);没有提议时立即返回,不等网络。
+ * 不拦发送——调用方之后照常发出这条消息。
+ */
+export async function offerSessionRebalance(options: {
+ sessionId: string;
+ hostDeviceId?: string;
+ confirmWithCheckbox: ConfirmWithCheckbox;
+ t: TFunction;
+}): Promise<void> {
+ const { sessionId, hostDeviceId, confirmWithCheckbox, t } = options;
+ const suggestion = takePrefetched(sessionId, hostDeviceId);
+ if (!suggestion) return;
+ if (suggestion.kind === 'auto') {
+ await recordDecision(sessionId, suggestion.memberKey, false, hostDeviceId);
+ return;
+ }
+ const { ok, checked } = await confirmWithCheckbox({
+ title: t('providerGroup.rebalance.title', { label: suggestion.label }),
+ description: describeSessionRebalance(suggestion, t),
+ confirmText: t('providerGroup.rebalance.confirm'),
+ cancelText: t('providerGroup.rebalance.cancel'),
+ checkboxLabel: t('providerGroup.rebalance.remember'),
+ autoFocusConfirm: true,
+ });
+ if (!ok) return;
+ await recordDecision(sessionId, suggestion.memberKey, checked, hostDeviceId);
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 64898334dd..42743b7504 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -640,7 +640,7 @@
"round": "Round Robin",
"order": "In Order",
"weight": "By Weight",
- "quotaFirst": "When subscription usage is available, prefer computers whose quota resets soon, then those with lower usage; apply the group strategy among similar ones",
+ "quotaFirst": "When subscription usage is available, computers whose quota resets soon with plenty left go first, so each account is used up evenly over time; similar ones follow the group strategy",
"description": {
"least": "Goes to the least busy one",
"round": "Rotates across computers",
@@ -677,6 +677,10 @@
},
"runningCount_one": "{{count}} task running",
"runningCount_other": "{{count}} tasks running",
+ "pace": {
+ "used": "{{used}}% used",
+ "usedExpected": "{{used}}% used, {{expected}}% expected by now"
+ },
"limitAria": "Task limit for {{name}}",
"limitOption_one": "Max {{count}}",
"limitOption_other": "Max {{count}}",
@@ -728,6 +732,15 @@
}
}
},
+ "rebalance": {
+ "title": "Continue on {{label}}?",
+ "description": "To use every account’s quota evenly, send this message from {{label}} ({{quota}}). The last few messages and a summary carry over; older details may be lost.",
+ "quota": "{{left}}% left",
+ "quotaReset": "{{left}}% left · {{reset}}",
+ "confirm": "Switch",
+ "cancel": "Cancel",
+ "remember": "Switch automatically from now on (this task only)"
+ },
"deleteConfirm": {
"title": "Delete the {{provider}} provider group?",
"description": "New tasks on this computer will run here. Tasks already on other computers stay where they are.",
@@ -11997,7 +12010,8 @@
"relocatedHere": "Agent now runs on this computer",
"relocatedTo": "Agent now runs on {{device}}",
"relocatedTaskComputer": "Agent now runs on the task’s computer",
- "relocatedElsewhere": "Agent now runs on another computer"
+ "relocatedElsewhere": "Agent now runs on another computer",
+ "quotaRebalance": "its quota should be used first"
},
"contextRebuild": {
"labelOverflow": "Context reorganized, continuing",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index c962b2f18c..215eb46e05 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -635,7 +635,7 @@
"round": "順番に",
"order": "並び順",
"weight": "重み付け",
- "quotaFirst": "サブスクリプションの使用量を取得できる場合、クォータのリセットが近いパソコンを優先し、次に使用量の少ないものを選びます。同程度ならグループの割り当て方式で選びます",
+ "quotaFirst": "サブスクリプションの使用量を取得できる場合、リセットが近く残りの多いパソコンを優先し、各アカウントを時間に沿って均等に使い切ります。同程度ならグループの割り当て方式で選びます",
"description": {
"least": "空いているパソコンへ",
"round": "順番に割り当て",
@@ -670,6 +670,10 @@
"share": "ほかの人から共有されたパソコンのクォータは表示されません"
},
"runningCount_other": "{{count}} 件実行中",
+ "pace": {
+ "used": "{{used}}% 使用",
+ "usedExpected": "{{used}}% 使用、目安 {{expected}}%"
+ },
"limitAria": "{{name}} の同時実行数の上限",
"limitOption_other": "上限 {{count}}",
"weightAria": "{{name}} の重み",
@@ -718,6 +722,15 @@
}
}
},
+ "rebalance": {
+ "title": "{{label}} に切り替えて続けますか?",
+ "description": "各アカウントのクォータを均等に使い切るため、このメッセージは {{label}} から送ることをおすすめします({{quota}})。直近数回のやり取りと要約は引き継がれますが、それより前の細部は失われることがあります。",
+ "quota": "残り {{left}}%",
+ "quotaReset": "残り {{left}}%・{{reset}}",
+ "confirm": "切り替える",
+ "cancel": "キャンセル",
+ "remember": "今後は確認せず自動で切り替える(このタスクのみ)"
+ },
"deleteConfirm": {
"title": "{{provider}} のプロバイダーグループを削除しますか?",
"description": "このパソコンの新しいセッションはこのパソコンで実行されます。ほかのパソコンに割り当て済みのセッションはそのまま残ります。",
@@ -11953,7 +11966,8 @@
"relocatedHere": "Agent をこのパソコンで実行するようにしました",
"relocatedTo": "Agent を {{device}} で実行するようにしました",
"relocatedTaskComputer": "Agent をタスクのあるパソコンで実行するようにしました",
- "relocatedElsewhere": "Agent を別のパソコンで実行するようにしました"
+ "relocatedElsewhere": "Agent を別のパソコンで実行するようにしました",
+ "quotaRebalance": "こちらのクォータを先に使うため"
},
"contextRebuild": {
"labelOverflow": "コンテキストを整理して続行しました",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 42693fc0ad..a8ae8433ab 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -635,7 +635,7 @@
"round": "순환",
"order": "순서대로",
"weight": "가중치",
- "quotaFirst": "구독 사용량을 확인할 수 있으면 할당량 초기화가 가까운 컴퓨터를 우선하고, 그다음 사용량이 적은 컴퓨터를 선택합니다. 비슷하면 그룹 배정 방식을 따릅니다",
+ "quotaFirst": "구독 사용량을 확인할 수 있으면 초기화가 가깝고 남은 양이 많은 컴퓨터를 먼저 사용해 각 계정을 시간에 맞춰 고르게 소진합니다. 비슷하면 그룹 배정 방식을 따릅니다",
"description": {
"least": "가장 여유로운 컴퓨터로",
"round": "차례대로 배정",
@@ -670,6 +670,10 @@
"share": "다른 사람이 공유한 컴퓨터의 할당량은 표시되지 않습니다"
},
"runningCount_other": "{{count}}개 실행 중",
+ "pace": {
+ "used": "{{used}}% 사용",
+ "usedExpected": "{{used}}% 사용, 기준 {{expected}}%"
+ },
"limitAria": "{{name}}의 동시 실행 한도",
"limitOption_other": "한도 {{count}}",
"weightAria": "{{name}}의 가중치",
@@ -718,6 +722,15 @@
}
}
},
+ "rebalance": {
+ "title": "{{label}}(으)로 바꿔서 계속할까요?",
+ "description": "각 계정의 할당량을 고르게 쓰기 위해 이 메시지는 {{label}}에서 보내는 것을 권장합니다({{quota}}). 최근 몇 번의 대화와 요약은 이어지지만, 그 이전의 세부 내용은 빠질 수 있습니다.",
+ "quota": "{{left}}% 남음",
+ "quotaReset": "{{left}}% 남음 · {{reset}}",
+ "confirm": "전환",
+ "cancel": "취소",
+ "remember": "앞으로 묻지 않고 자동 전환(이 작업만)"
+ },
"deleteConfirm": {
"title": "{{provider}} 제공자 그룹을 삭제할까요?",
"description": "이 컴퓨터의 새 세션은 이 컴퓨터에서 실행됩니다. 다른 컴퓨터에 배정된 세션은 그대로 남습니다.",
@@ -11953,7 +11966,8 @@
"relocatedHere": "이제 Agent가 이 컴퓨터에서 실행됩니다",
"relocatedTo": "이제 Agent가 {{device}}에서 실행됩니다",
"relocatedTaskComputer": "이제 Agent가 작업이 있는 컴퓨터에서 실행됩니다",
- "relocatedElsewhere": "이제 Agent가 다른 컴퓨터에서 실행됩니다"
+ "relocatedElsewhere": "이제 Agent가 다른 컴퓨터에서 실행됩니다",
+ "quotaRebalance": "이 계정의 할당량을 먼저 쓰기 위해"
},
"contextRebuild": {
"labelOverflow": "컨텍스트를 정리하고 계속합니다",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 8081c40602..6ccf6f7851 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -635,7 +635,7 @@
"round": "轮询",
"order": "按顺序",
"weight": "按权重",
- "quotaFirst": "能读取订阅用量时,先用配额快重置的电脑,再选用量低的,相近时按组策略",
+ "quotaFirst": "能读取订阅用量时,先用快重置、还剩得多的电脑,各账号会按时间均匀用掉;差不多时按组策略",
"description": {
"least": "给最闲的那台",
"round": "依次轮流",
@@ -670,6 +670,10 @@
"share": "别人分享的电脑不显示配额"
},
"runningCount_other": "{{count}} 个任务运行中",
+ "pace": {
+ "used": "已用 {{used}}%",
+ "usedExpected": "已用 {{used}}%,该用到 {{expected}}%"
+ },
"limitAria": "{{name}} 的并发上限",
"limitOption_other": "上限 {{count}}",
"weightAria": "{{name}} 的权重",
@@ -718,6 +722,15 @@
}
}
},
+ "rebalance": {
+ "title": "换到 {{label}} 继续?",
+ "description": "为了均匀用完各账号的配额,建议这条消息换到 {{label}} 发送({{quota}})。换过去会带上最近几轮对话和摘要,更早的细节可能记不全。",
+ "quota": "还剩 {{left}}%",
+ "quotaReset": "还剩 {{left}}%,{{reset}}",
+ "confirm": "换过去",
+ "cancel": "取消",
+ "remember": "以后自动换,不再询问(仅本任务)"
+ },
"deleteConfirm": {
"title": "删除 {{provider}} 的供应商组?",
"description": "之后这台电脑上的新任务都在本机运行;已经分到其他电脑的任务留在那台电脑上。",
@@ -11953,7 +11966,8 @@
"relocatedHere": "Agent 已改到这台电脑上运行",
"relocatedTo": "Agent 已改到 {{device}} 上运行",
"relocatedTaskComputer": "Agent 已改到任务所在的电脑上运行",
- "relocatedElsewhere": "Agent 已改到另一台电脑上运行"
+ "relocatedElsewhere": "Agent 已改到另一台电脑上运行",
+ "quotaRebalance": "这个账号的配额更该先用"
},
"contextRebuild": {
"labelOverflow": "已整理上下文并继续",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 901f8bab4d..693dc5631b 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -635,7 +635,7 @@
"round": "輪詢",
"order": "依順序",
"weight": "依權重",
- "quotaFirst": "能讀取訂閱用量時,先用配額快重置的電腦,再選用量低的,相近時依組策略",
+ "quotaFirst": "能讀取訂閱用量時,先用快重置、還剩得多的電腦,各帳號會依時間均勻用掉;差不多時依組策略",
"description": {
"least": "給最閒的那臺",
"round": "依序輪流",
@@ -670,6 +670,10 @@
"share": "別人分享的電腦不顯示配額"
},
"runningCount_other": "{{count}} 個任務執行中",
+ "pace": {
+ "used": "已用 {{used}}%",
+ "usedExpected": "已用 {{used}}%,該用到 {{expected}}%"
+ },
"limitAria": "{{name}} 的並行上限",
"limitOption_other": "上限 {{count}}",
"weightAria": "{{name}} 的權重",
@@ -718,6 +722,15 @@
}
}
},
+ "rebalance": {
+ "title": "換到 {{label}} 繼續?",
+ "description": "為了平均用完各帳號的配額,建議這則訊息換到 {{label}} 傳送({{quota}})。換過去會帶上最近幾輪對話和摘要,更早的細節可能記不全。",
+ "quota": "還剩 {{left}}%",
+ "quotaReset": "還剩 {{left}}%,{{reset}}",
+ "confirm": "換過去",
+ "cancel": "取消",
+ "remember": "以後自動換,不再詢問(僅此任務)"
+ },
"deleteConfirm": {
"title": "刪除 {{provider}} 的供應商組?",
"description": "之後這臺電腦上的新任務都在本機執行;已經分到其他電腦的任務留在那臺電腦上。",
@@ -11952,7 +11965,8 @@
"relocatedHere": "Agent 已改到這台電腦上執行",
"relocatedTo": "Agent 已改到 {{device}} 上執行",
"relocatedTaskComputer": "Agent 已改到任務所在的電腦上執行",
- "relocatedElsewhere": "Agent 已改到另一台電腦上執行"
+ "relocatedElsewhere": "Agent 已改到另一台電腦上執行",
+ "quotaRebalance": "這個帳號的配額更該先用"
},
"contextRebuild": {
"labelOverflow": "已整理上下文並繼續",
diff --git a/apps/desktop/src/shared/__tests__/providerGroup.test.ts b/apps/desktop/src/shared/__tests__/providerGroup.test.ts
index 65128d8788..8455f1c513 100644
--- a/apps/desktop/src/shared/__tests__/providerGroup.test.ts
+++ b/apps/desktop/src/shared/__tests__/providerGroup.test.ts
@@ -10,6 +10,7 @@ import {
providerGroupDeviceCount,
providerGroupMemberKey,
providerGroupSummaryForWire,
+ parseProviderGroupRebalanceSuggestion,
parseProviderGroupRemoteRequest,
parseProviderGroupRemoteView,
parseProviderGroupRemotePick,
@@ -46,6 +47,60 @@ describe('group detail diagnostics compatibility', () => {
expect(member.guestSupport).toBeUndefined();
},
);
+
+ // Unit protocol (protocol-compatibility.md 供应商组配额): the same-account `view` may carry one quota window
+ // for the progress bar. Old owners omit it; malformed values must not draw a bar from invented numbers.
+ it('keeps a valid quota window and clamps its percentage', () => {
+ const week = 7 * 86_400_000;
+ expect(parseProviderGroupRemoteView(payload({ quota: { usedPercent: 140, resetAtMs: 5_000, windowMs: week } }), 'anthropic')
+ .members[0].quota).toEqual({ usedPercent: 100, resetAtMs: 5_000, windowMs: week });
+ expect(parseProviderGroupRemoteView(payload({ quota: { usedPercent: 0, resetAtMs: null, windowMs: week } }), 'anthropic')
+ .members[0].quota).toEqual({ usedPercent: 0, resetAtMs: null, windowMs: week });
+ });
+
+ it.each([
+ 'full', { usedPercent: '40', resetAtMs: 5_000, windowMs: 1 }, { usedPercent: 40, windowMs: 1 },
+ { usedPercent: 40, resetAtMs: -1, windowMs: 1 }, { usedPercent: 40, resetAtMs: 5_000, windowMs: 0 },
+ { usedPercent: 40, resetAtMs: 5_000, windowMs: 32 * 86_400_000 },
+ ])('drops a malformed quota window: %j', (quota) => {
+ expect(parseProviderGroupRemoteView(payload({ quota }), 'anthropic').members[0]).not.toHaveProperty('quota');
+ });
+
+ it('never takes a quota window for a shared-in computer', () => {
+ const raw = {
+ config: { members: [{ kind: 'share', agentDeviceId: 'share:s1', providerId: 'anthropic' }] },
+ members: [{ key: 'share:s1:anthropic', state: 'available', quota: { usedPercent: 40, resetAtMs: 5_000, windowMs: 1_000 } }],
+ };
+ expect(parseProviderGroupRemoteView(raw, 'anthropic').members[0]).not.toHaveProperty('quota');
+ });
+});
+
+// Unit protocol (protocol-compatibility.md 供应商组任务进行中换号):手机与远程控制经 `provider-group:remote` 问任务所在电脑
+// 要不要换号、转达用户的选择。旧端不认识这两个动作(客户端按不提议处理);被控端必须拒绝改不了组的坏请求,客户端不能
+// 用编造的提议弹窗。
+describe('switching accounts between messages', () => {
+ const quota = { usedPercent: 20, resetAtMs: 5_000, windowMs: 7 * 86_400_000 };
+
+ it('reads both requests and rejects a malformed choice', () => {
+ expect(parseProviderGroupRemoteRequest({ action: 'rebalance-suggestion', sessionId: 's1' }))
+ .toEqual({ action: 'rebalance-suggestion', sessionId: 's1' });
+ expect(parseProviderGroupRemoteRequest({ action: 'rebalance-decision', sessionId: 's1', memberKey: 'device:mini:anthropic', remember: true }))
+ .toEqual({ action: 'rebalance-decision', sessionId: 's1', memberKey: 'device:mini:anthropic', remember: true });
+ for (const bad of [{ remember: 'true' }, { memberKey: 'a b' }, { memberKey: '' }]) {
+ expect(() => parseProviderGroupRemoteRequest({
+ action: 'rebalance-decision', sessionId: 's1', memberKey: 'device:mini:anthropic', remember: false, ...bad,
+ })).toThrow();
+ }
+ });
+
+ it('only turns a well-formed reply into a suggestion', () => {
+ expect(parseProviderGroupRebalanceSuggestion({ kind: 'auto', memberKey: 'device:mini:anthropic', label: 'Mini', quota }))
+ .toEqual({ kind: 'auto', memberKey: 'device:mini:anthropic', label: 'Mini', quota });
+ for (const raw of [null, { ok: false }, { kind: 'move', memberKey: 'local', label: 'Mini', quota },
+ { kind: 'ask', memberKey: 'local', label: '', quota }, { kind: 'ask', memberKey: 'local', label: 'Mini', quota: { usedPercent: 20 } }]) {
+ expect(parseProviderGroupRebalanceSuggestion(raw)).toBeNull();
+ }
+ });
});
describe('accounts on the same computer', () => {
diff --git a/apps/desktop/src/shared/providerGroup.ts b/apps/desktop/src/shared/providerGroup.ts
index 9302e46e19..4e231e7e2d 100644
--- a/apps/desktop/src/shared/providerGroup.ts
+++ b/apps/desktop/src/shared/providerGroup.ts
@@ -108,6 +108,16 @@ export interface ProviderGroupMemberStatus {
paused: boolean;
/** 冷却到何时(unix ms)。 */
coolingUntil?: number;
+ /**
+ * 选电脑时排序用的那个配额窗口(provider-groups.md §5、§10):本机与同账号电脑的订阅才有,读不到时省略。
+ * 发给同账号电脑,不进受邀者的匿名状态。
+ */
+ quota?: ProviderGroupMemberQuota;
+ /**
+ * 5 小时配额快满、离重置还早(provider-groups.md §5「配额先比」第 0 条):任务进行中不提议换到这台。只在为真时出现,
+ * 规则同 `quota`。
+ */
+ fiveHourTight?: true;
/**
* 另一台电脑上的组:组所在电脑那边看它能用,这台电脑却连不上(provider-groups.md §10)。只由这台电脑的主进程
* 按自己的连接情况补上,不来自组所在电脑的回包。
@@ -120,6 +130,48 @@ export interface ProviderGroupMemberStatus {
reshare?: ProviderGroupReshareSummary;
}
+/** 一个配额窗口此刻的用量:组内电脑行的进度条按它画已用多少、按时间该用到哪。 */
+export interface ProviderGroupMemberQuota {
+ usedPercent: number;
+ /** 重置时刻(unix ms);null = 这个窗口还没开始计时。 */
+ resetAtMs: number | null;
+ /** 窗口长度(ms),周配额是 7 天。 */
+ windowMs: number;
+}
+
+/** 最长按 31 天的窗口接收,超出或格式不对就当没有。 */
+const MAX_QUOTA_WINDOW_MS = 31 * 86_400_000;
+
+export function readProviderGroupMemberQuota(value: unknown): ProviderGroupMemberQuota | undefined {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
+ const { usedPercent, resetAtMs, windowMs } = value as Record<string, unknown>;
+ if (typeof usedPercent !== 'number' || !Number.isFinite(usedPercent)) return undefined;
+ if (typeof windowMs !== 'number' || !Number.isFinite(windowMs) || windowMs <= 0 || windowMs > MAX_QUOTA_WINDOW_MS) return undefined;
+ if (resetAtMs !== null && (typeof resetAtMs !== 'number' || !Number.isFinite(resetAtMs) || resetAtMs <= 0)) return undefined;
+ return { usedPercent: Math.min(100, Math.max(0, usedPercent)), resetAtMs, windowMs };
+}
+
+/**
+ * 任务进行中换号的提议(provider-groups.md §6.2「任务进行中换号」):用户自己发下一条消息前问任务所在的电脑。
+ * `ask` = 弹窗问;`auto` = 这个任务选过「以后自动换」,不再问,直接确认这个提议。`label` 是要换去的那台(带账号名)。
+ */
+export type ProviderGroupRebalanceSuggestion =
+ | { kind: 'ask' | 'auto'; memberKey: string; label: string; quota: ProviderGroupMemberQuota }
+ | null;
+
+const REBALANCE_MEMBER_KEY_PATTERN = /^[A-Za-z0-9_.:-]{1,300}$/;
+
+/** 客户端读任务所在电脑回的提议;旧端不认识这个动作、格式不对都按没有提议处理(照常发送)。 */
+export function parseProviderGroupRebalanceSuggestion(raw: unknown): ProviderGroupRebalanceSuggestion {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const value = raw as Record<string, unknown>;
+ if (value.kind !== 'ask' && value.kind !== 'auto') return null;
+ if (typeof value.memberKey !== 'string' || !REBALANCE_MEMBER_KEY_PATTERN.test(value.memberKey)) return null;
+ const label = normalizeLabel(value.label);
+ const quota = readProviderGroupMemberQuota(value.quota);
+ return label && quota ? { kind: value.kind, memberKey: value.memberKey, label, quota } : null;
+}
+
/** 本机分享出去的一个人:分享来的那台电脑的主人是否同意他经组使用那台。 */
export interface ProviderGroupReshareGuest {
memberId: string;
@@ -187,7 +239,11 @@ export type ProviderGroupLocalCommand =
/** 本机全部组的设置(不读远端)。 */
| { action: 'list' }
/** 这个任务此刻归哪个组(模型列表把它显示在组那一项下)。 */
- | { action: 'session-group'; sessionId: string };
+ | { action: 'session-group'; sessionId: string }
+ /** 用户发下一条消息前:要不要提议换号(provider-groups.md §6.2「任务进行中换号」)。 */
+ | { action: 'rebalance-suggestion'; sessionId: string }
+ /** 用户确认换号:这个任务的下一条消息先换到 `memberKey`;`remember` = 这个任务以后自动换。 */
+ | { action: 'rebalance-decision'; sessionId: string; memberKey: string; remember: boolean };
export type ProviderGroupCommand = ProviderGroupLocalCommand
| { action: 'remote-manage'; deviceId: string; request: ProviderManagementRequest };
@@ -207,7 +263,9 @@ export type ProviderGroupCommandResult<C extends ProviderGroupCommand> =
: C extends { action: 'delete' | 'delete-if-current' } ? ProviderGroupView
: C extends { action: 'remote-view' } ? ProviderGroupView
: C extends { action: 'session-group' } ? ProviderGroupSessionGroup
- : never;
+ : C extends { action: 'rebalance-suggestion' } ? ProviderGroupRebalanceSuggestion
+ : C extends { action: 'rebalance-decision' } ? { ok: boolean }
+ : never;
const PROVIDER_ID_PATTERN = /^[a-zA-Z0-9._-]{1,128}$/;
const DEVICE_ID_PATTERN = /^[A-Za-z0-9_.-]{1,128}$/;
@@ -424,7 +482,10 @@ export type ProviderGroupRemoteRequest =
* 只读:这台电脑上的某个任务此刻归哪个组(手机与远程控制的模型列表用,provider-groups.md §10)。
* 发给任务所在的电脑,不是组所在电脑。
*/
- | { action: 'session-group'; sessionId: string };
+ | { action: 'session-group'; sessionId: string }
+ /** 发给任务所在的电脑(手机、远程控制):同本机命令的 `rebalance-suggestion` / `rebalance-decision`。 */
+ | { action: 'rebalance-suggestion'; sessionId: string }
+ | { action: 'rebalance-decision'; sessionId: string; memberKey: string; remember: boolean };
/** `session-group` 的回包:坐标是任务所在电脑视角(`groupDeviceId` 为 null = 那台自己建的组)。 */
export interface ProviderGroupRemoteSessionGroup {
@@ -582,6 +643,16 @@ export function parseProviderGroupRemoteRequest(raw: unknown): ProviderGroupRemo
}
case 'session-group':
return { action: 'session-group', sessionId: remoteSessionId(value.sessionId) };
+ case 'rebalance-suggestion':
+ return { action: 'rebalance-suggestion', sessionId: remoteSessionId(value.sessionId) };
+ case 'rebalance-decision':
+ if (typeof value.remember !== 'boolean') invalidRemote('invalid remember');
+ return {
+ action: 'rebalance-decision',
+ sessionId: remoteSessionId(value.sessionId),
+ memberKey: remoteMemberKey(value.memberKey),
+ remember: value.remember as boolean,
+ };
default:
invalidRemote('unknown provider group action');
}
@@ -657,6 +728,9 @@ export function parseProviderGroupRemoteView(raw: unknown, groupProviderId: stri
const guestSupport = ['supported', 'needs-update', 'unknown'].includes(item.guestSupport as string)
? item.guestSupport as ProviderGroupGuestSupport : undefined;
const coolingUntil = typeof item.coolingUntil === 'number' && Number.isFinite(item.coolingUntil) ? item.coolingUntil : undefined;
+ // 分享来的电脑不读配额(provider-groups.md §5「分享边界」):回包里有也不收。
+ const quota = member.kind === 'share' ? undefined : readProviderGroupMemberQuota(item.quota);
+ const fiveHourTight = quota !== undefined && item.fiveHourTight === true;
return [{
key: member.key,
kind: member.kind,
@@ -672,6 +746,8 @@ export function parseProviderGroupRemoteView(raw: unknown, groupProviderId: stri
weight: member.weight,
paused: member.paused,
...(coolingUntil !== undefined ? { coolingUntil } : {}),
+ ...(quota ? { quota } : {}),
+ ...(fiveHourTight ? { fiveHourTight: true as const } : {}),
}];
});
return { providerId: groupProviderId, config, members, ...(model ? { model } : {}) };
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 5c4f40a8ed..d1f2231061 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -394,6 +394,11 @@ import { formatProviderAccountLabel, resolveSessionUsageAccount } from '@/sessio
import { useRemoteAgentCatalogs } from '@/session/useRemoteAgentCatalogs';
import { isProviderShareAgentDeviceId } from '@/session/providerShareAgentDevice';
import { useSessionProviderGroup } from '@/session/useSessionProviderGroup';
+import {
+ askMobileSessionRebalance,
+ offerMobileSessionRebalance,
+ useMobileSessionRebalancePrefetch,
+} from '@/session/sessionRebalancePrompt';
import {
drainComposerAnnotationSubmissions,
drainComposerAttachments,
@@ -2607,6 +2612,13 @@ function SessionScreenContent() {
() => currentTurnHasStreamingAssistant(latestMessagesRef.current),
[messageStructureToken],
);
+ // 任务空闲时预先问好要不要换号,点发送时不多等一次往返(provider-groups.md §6.2「任务进行中换号」)。
+ useMobileSessionRebalancePrefetch({
+ invoke,
+ hostDeviceId: deviceId,
+ sessionId,
+ idle: status === 'online' && !remoteSessionRunning && !currentTurnStreaming,
+ });
const canStopCurrentRun = (remoteSessionRunning || currentTurnStreaming)
&& !inputProjection.queueAbortPending;
const canStopComposer = canStopQueue || canStopCurrentRun;
@@ -6548,6 +6560,21 @@ function SessionScreenContent() {
const planModeAtSend = runtimeOptions?.planModeSupported === true
? (readSessionRowNow() ?? currentSession).planModeEnabled === true
: undefined;
+ // 上一轮已经结束、用户发下一条消息:供应商组里另一个账号的配额明显更该先用时,问要不要换过去
+ // (provider-groups.md §6.2「任务进行中换号」,与电脑一致)。只把选择记到任务所在电脑,这条消息照常发出;
+ // 前面还有没发出的消息、断线或正在回复时不问。
+ if (
+ useDurableOutbox
+ && !dispatchBlockedAtSend
+ && outboxRef.current.length === 0
+ && !remoteSessionRunning
+ && !currentTurnStreaming
+ && !isRemoteSessionMissing(readSessionRowNow())
+ ) {
+ await offerMobileSessionRebalance({ invoke, hostDeviceId: deviceId, sessionId, ask: askMobileSessionRebalance });
+ // 弹窗期间离开了这个任务:草稿还没清空,留在原处,不发。
+ if (outboxSessionAliveRef.current !== sessionId) return;
+ }
pendingSkillSelectionRef.current = null;
dismissPromptRecommendation();
// 乐观第一拍:点发送立刻清空输入框并跟到底部,不等任何网络往返(enqueue 是
diff --git a/apps/mobile/src/__tests__/sessionRebalancePrompt.test.ts b/apps/mobile/src/__tests__/sessionRebalancePrompt.test.ts
new file mode 100644
index 0000000000..8c489ab01d
--- /dev/null
+++ b/apps/mobile/src/__tests__/sessionRebalancePrompt.test.ts
@@ -0,0 +1,101 @@
+/**
+ * 手机发送前问换号(provider-groups.md §6.2「任务进行中换号」,2026-10-21 用户裁决「和电脑一样」):系统弹窗的三个按钮
+ * 分别是换过去、换过去并让这个任务以后自动换、取消;选过以后自动换的不再弹窗。提议在任务空闲时预先问好,点发送时
+ * 没有问好的提议(问不到、回包不对、还没问完)就立即照常发送,不多等一次往返。
+ * 从发送前调用的入口验证用户看到什么、任务所在电脑收到什么。
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const alert = vi.hoisted(() => vi.fn());
+vi.mock('react-native', () => ({ Alert: { alert } }));
+
+import { PROVIDER_GROUP_REMOTE_CHANNEL } from '@cindy/device-link';
+
+import { i18n } from '@/i18n';
+import {
+ askMobileSessionRebalance,
+ offerMobileSessionRebalance,
+ prefetchMobileSessionRebalance,
+} from '@/session/sessionRebalancePrompt';
+
+const MINI = 'device:mini:anthropic';
+const reply = (kind: 'ask' | 'auto') => ({
+ kind,
+ memberKey: MINI,
+ label: 'Mini',
+ quota: { usedPercent: 20, resetAtMs: Date.now() + 86_400_000, windowMs: 7 * 86_400_000 },
+});
+
+function invoker(suggestion: unknown) {
+ return vi.fn((_deviceId: string, _channel: string, args?: unknown[]): Promise<unknown> => {
+ const request = args?.[0] as { action: string };
+ if (request.action !== 'rebalance-suggestion') return Promise.resolve({ ok: true });
+ if (suggestion === 'pending') return new Promise(() => undefined);
+ return suggestion instanceof Error ? Promise.reject(suggestion) : Promise.resolve(suggestion);
+ });
+}
+
+type Button = { text: string; onPress(): void };
+
+function press(button: 'confirm' | 'remember' | 'cancel') {
+ alert.mockImplementationOnce((_title: string, _body: string, buttons: Button[]) => {
+ buttons.find((b) => b.text === i18n.t(`session.providerGroupRebalance.${button}`))!.onPress();
+ });
+}
+
+const decisions = (invoke: ReturnType<typeof invoker>) =>
+ invoke.mock.calls.map(([, , args]) => args?.[0] as { action: string }).filter((r) => r.action === 'rebalance-decision');
+
+async function offer(invoke: ReturnType<typeof invoker>, sessionId = 's1') {
+ await offerMobileSessionRebalance({ invoke, hostDeviceId: 'pc', sessionId, ask: askMobileSessionRebalance });
+}
+
+beforeEach(() => {
+ alert.mockReset();
+});
+
+describe('offerMobileSessionRebalance', () => {
+ it.each([
+ ['confirm', false],
+ ['remember', true],
+ ['cancel', null],
+ ] as const)('passes the choice to the task’s computer: %s', async (button, remember) => {
+ press(button);
+ const invoke = invoker(reply('ask'));
+ await prefetchMobileSessionRebalance(invoke, 'pc', 's1');
+ await offer(invoke);
+
+ expect(invoke).toHaveBeenCalledWith('pc', PROVIDER_GROUP_REMOTE_CHANNEL, [{ action: 'rebalance-suggestion', sessionId: 's1' }]);
+ expect(alert).toHaveBeenCalledTimes(1);
+ expect(alert.mock.calls[0][0]).toContain('Mini');
+ expect(alert.mock.calls[0][2]).toHaveLength(3);
+ expect(decisions(invoke)).toEqual(remember === null
+ ? []
+ : [{ action: 'rebalance-decision', sessionId: 's1', memberKey: MINI, remember }]);
+ // 一次提议只管一条消息。
+ await offer(invoke);
+ expect(alert).toHaveBeenCalledTimes(1);
+ });
+
+ it('switches without asking for a task set to switch automatically', async () => {
+ const invoke = invoker(reply('auto'));
+ await prefetchMobileSessionRebalance(invoke, 'pc', 's1');
+ await offer(invoke);
+ expect(alert).not.toHaveBeenCalled();
+ expect(decisions(invoke)).toEqual([{ action: 'rebalance-decision', sessionId: 's1', memberKey: MINI, remember: false }]);
+ });
+
+ it.each([
+ ['an older computer that does not know the request', new Error('[INVALID_PARAMS] unknown action')],
+ ['no suggestion', null],
+ ['a malformed reply', { ...reply('ask'), label: '' }],
+ ['a question still on its way', 'pending'],
+ ])('sends at once without asking for %s', async (name, suggestion) => {
+ const invoke = invoker(suggestion);
+ const fetched = prefetchMobileSessionRebalance(invoke, 'pc', name);
+ if (suggestion !== 'pending') await fetched;
+ await offer(invoke, name);
+ expect(alert).not.toHaveBeenCalled();
+ expect(decisions(invoke)).toEqual([]);
+ });
+});
diff --git a/apps/mobile/src/__tests__/systemCard.test.ts b/apps/mobile/src/__tests__/systemCard.test.ts
index e84d7084e9..d1fe2d275e 100644
--- a/apps/mobile/src/__tests__/systemCard.test.ts
+++ b/apps/mobile/src/__tests__/systemCard.test.ts
@@ -241,6 +241,15 @@ describe('formatMobileSystemCard — Agent 切换', () => {
}).title).toBe(
`${i18n.t('message.systemCard.agentSwitchLocation', { device: 'Studio Mac' })} · Codex`,
);
+ // 用户确认为了先用那台的配额换过去(provider-groups.md §6.2):与桌面一样写明原因。
+ expect(formatMobileSystemCard('agent-switch', {
+ ...base,
+ toAgentDeviceId: 'device-office-pc',
+ toAgentDeviceName: 'Office PC',
+ switchReason: 'quota-rebalance',
+ }).title).toBe(
+ `${i18n.t('message.systemCard.agentSwitchLocation', { device: 'Office PC' })} · ${i18n.t('message.systemCard.agentSwitchLocationQuotaRebalance')}`,
+ );
});
});
diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.json
index 5e3ffa1cae..237ba29944 100644
--- a/apps/mobile/src/i18n/locales/en/message.json
+++ b/apps/mobile/src/i18n/locales/en/message.json
@@ -294,6 +294,7 @@
"agentSwitchLocation": "Agent moved to {{device}}",
"agentSwitchLocationThisComputer": "Agent moved back to this computer",
"agentSwitchLocationOtherComputer": "Agent moved to another computer",
+ "agentSwitchLocationQuotaRebalance": "its quota should be used first",
"learnStarted": "Skill learning started",
"learnStartedBody": "Distillation runs in the background on desktop. When it's done, review the skill draft on desktop.",
"learnFailed": "Skill learning couldn't start",
diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.json
index aaae7abe88..735834b398 100644
--- a/apps/mobile/src/i18n/locales/en/session.json
+++ b/apps/mobile/src/i18n/locales/en/session.json
@@ -734,5 +734,14 @@
"start": "Start Following Up",
"notNow": "Not Now",
"saveFailed": "Couldn't save. Try again."
+ },
+ "providerGroupRebalance": {
+ "title": "Continue on {{label}}?",
+ "body": "To use every account’s quota evenly, send this message from {{label}} ({{quota}}). The last few messages and a summary carry over; older details may be lost.",
+ "quota": "{{left}}% left",
+ "quotaReset": "{{left}}% left · resets in {{reset}}",
+ "confirm": "Switch",
+ "remember": "Switch, and do it automatically from now on (this task only)",
+ "cancel": "Cancel"
}
}
diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.json
index d2b53c996b..2c3f017aee 100644
--- a/apps/mobile/src/i18n/locales/ja/message.json
+++ b/apps/mobile/src/i18n/locales/ja/message.json
@@ -294,6 +294,7 @@
"agentSwitchLocation": "Agent の実行先を {{device}} に変更しました",
"agentSwitchLocationThisComputer": "Agent の実行先をこのパソコンに戻しました",
"agentSwitchLocationOtherComputer": "Agent の実行先を別のパソコンに変更しました",
+ "agentSwitchLocationQuotaRebalance": "こちらのクォータを先に使うため",
"learnStarted": "スキル学習を開始しました",
"learnStartedBody": "蒸留はデスクトップのバックグラウンドで進行します。完了後、デスクトップでスキルの草案を確認・レビューしてください。",
"learnFailed": "スキル学習を開始できませんでした",
diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.json
index 3839f09ef6..3cefb8823c 100644
--- a/apps/mobile/src/i18n/locales/ja/session.json
+++ b/apps/mobile/src/i18n/locales/ja/session.json
@@ -734,5 +734,14 @@
"start": "フォローを開始",
"notNow": "今はしない",
"saveFailed": "保存できませんでした。もう一度お試しください"
+ },
+ "providerGroupRebalance": {
+ "title": "{{label}} に切り替えて続けますか?",
+ "body": "各アカウントのクォータを均等に使い切るため、このメッセージは {{label}} から送ることをおすすめします({{quota}})。直近数回のやり取りと要約は引き継がれますが、それより前の細部は失われることがあります。",
+ "quota": "残り {{left}}%",
+ "quotaReset": "残り {{left}}%・{{reset}}後にリセット",
+ "confirm": "切り替える",
+ "remember": "切り替えて、今後は自動にする(このタスクのみ)",
+ "cancel": "キャンセル"
}
}
diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.json
index 0c2fec6a4f..9484447c8d 100644
--- a/apps/mobile/src/i18n/locales/ko/message.json
+++ b/apps/mobile/src/i18n/locales/ko/message.json
@@ -294,6 +294,7 @@
"agentSwitchLocation": "Agent 실행 위치가 {{device}}(으)로 변경됨",
"agentSwitchLocationThisComputer": "Agent 실행 위치가 이 컴퓨터로 돌아옴",
"agentSwitchLocationOtherComputer": "Agent 실행 위치가 다른 컴퓨터로 변경됨",
+ "agentSwitchLocationQuotaRebalance": "이 계정의 할당량을 먼저 쓰기 위해",
"learnStarted": "스킬 학습을 시작했습니다",
"learnStartedBody": "증류는 데스크톱 백그라운드에서 진행됩니다. 완료되면 데스크톱에서 스킬 초안을 확인하고 검토하세요.",
"learnFailed": "스킬 학습을 시작하지 못했습니다",
diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.json
index 748eecc8f2..078a4bcffd 100644
--- a/apps/mobile/src/i18n/locales/ko/session.json
+++ b/apps/mobile/src/i18n/locales/ko/session.json
@@ -730,5 +730,14 @@
"start": "후속 확인 시작",
"notNow": "나중에",
"saveFailed": "저장하지 못했습니다. 다시 시도하세요"
+ },
+ "providerGroupRebalance": {
+ "title": "{{label}}(으)로 바꿔서 계속할까요?",
+ "body": "각 계정의 할당량을 고르게 쓰기 위해 이 메시지는 {{label}}에서 보내는 것을 권장합니다({{quota}}). 최근 몇 번의 대화와 요약은 이어지지만, 그 이전의 세부 내용은 빠질 수 있습니다.",
+ "quota": "{{left}}% 남음",
+ "quotaReset": "{{left}}% 남음 · {{reset}} 후 초기화",
+ "confirm": "전환",
+ "remember": "전환하고 앞으로 자동으로(이 작업만)",
+ "cancel": "취소"
}
}
diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.json
index d5b9968db4..10455d7a06 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/message.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json
@@ -294,6 +294,7 @@
"agentSwitchLocation": "Agent 改到 {{device}} 运行",
"agentSwitchLocationThisComputer": "Agent 改回这台电脑运行",
"agentSwitchLocationOtherComputer": "Agent 改到另一台电脑运行",
+ "agentSwitchLocationQuotaRebalance": "这个账号的配额更该先用",
"learnStarted": "技能学习已启动",
"learnStartedBody": "蒸馏在电脑端后台进行,完成后请到电脑端查看并评审技能草案。",
"learnFailed": "技能学习未能启动",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.json
index 72a13ae77e..3d3277c3b8 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/session.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json
@@ -730,5 +730,14 @@
"start": "开始跟进",
"notNow": "暂不开启",
"saveFailed": "没能保存,请重试"
+ },
+ "providerGroupRebalance": {
+ "title": "换到 {{label}} 继续?",
+ "body": "为了均匀用完各账号的配额,建议这条消息换到 {{label}} 发送({{quota}})。换过去会带上最近几轮对话和摘要,更早的细节可能记不全。",
+ "quota": "还剩 {{left}}%",
+ "quotaReset": "还剩 {{left}}%,{{reset}}后重置",
+ "confirm": "换过去",
+ "remember": "换过去,以后自动换(仅本任务)",
+ "cancel": "取消"
}
}
diff --git a/apps/mobile/src/i18n/locales/zh-TW/message.json b/apps/mobile/src/i18n/locales/zh-TW/message.json
index d2677c9653..3160071d36 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/message.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/message.json
@@ -294,6 +294,7 @@
"agentSwitchLocation": "Agent 改到 {{device}} 執行",
"agentSwitchLocationThisComputer": "Agent 改回這台電腦執行",
"agentSwitchLocationOtherComputer": "Agent 改到另一台電腦執行",
+ "agentSwitchLocationQuotaRebalance": "這個帳號的配額更該先用",
"learnStarted": "技能學習已啟動",
"learnStartedBody": "蒸餾在電腦端後臺進行,完成後請到電腦端檢視並評審技能草案。",
"learnFailed": "技能學習未能啟動",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/session.json b/apps/mobile/src/i18n/locales/zh-TW/session.json
index da6f6635a8..f1b845a4a5 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/session.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json
@@ -734,5 +734,14 @@
"start": "開始跟進",
"notNow": "暫不開啟",
"saveFailed": "沒能儲存,請重試"
+ },
+ "providerGroupRebalance": {
+ "title": "換到 {{label}} 繼續?",
+ "body": "為了平均用完各帳號的配額,建議這則訊息換到 {{label}} 傳送({{quota}})。換過去會帶上最近幾輪對話和摘要,更早的細節可能記不全。",
+ "quota": "還剩 {{left}}%",
+ "quotaReset": "還剩 {{left}}%,{{reset}}後重置",
+ "confirm": "換過去",
+ "remember": "換過去,以後自動換(僅此任務)",
+ "cancel": "取消"
}
}
diff --git a/apps/mobile/src/session/sessionRebalancePrompt.ts b/apps/mobile/src/session/sessionRebalancePrompt.ts
new file mode 100644
index 0000000000..45cb868917
--- /dev/null
+++ b/apps/mobile/src/session/sessionRebalancePrompt.ts
@@ -0,0 +1,187 @@
+/**
+ * 任务进行中换号(provider-groups.md §6.2,2026-10-21 用户裁决「手机和电脑一样」):上一轮结束后用户发下一条消息前,
+ * 看任务所在电脑是否提议为了均匀用完各账号的配额换一台。要换就弹窗(换过去 / 换过去并以后自动换 / 取消,手机弹窗
+ * 没有复选框,用第二个按钮代替电脑上的「以后自动换」勾选),只管这个任务;选过以后自动换的不再弹窗,直接换。
+ *
+ * 判断和记录都在任务所在电脑(`provider-group:remote` 的 `rebalance-suggestion` / `rebalance-decision`)。点发送要立刻清空
+ * 输入框、不等网络往返,所以提议在任务空闲时预先问好(上一轮结束、打开任务时,空闲期间每 5 分钟再问),发送时只用问好的
+ * 结果;没问到、问不到、旧版本不认识这个请求都按不提议处理。无论用户怎么选,这条消息都照常发出。
+ */
+import { useEffect } from 'react';
+import { Alert } from 'react-native';
+
+import { PROVIDER_GROUP_REMOTE_CHANNEL } from '@cindy/device-link';
+
+import { i18n } from '@/i18n';
+
+import { formatLocalizedSeconds } from './sessionDurationFormat';
+
+/** 预先问一次的上限:问不到就当没有提议。 */
+export const SESSION_REBALANCE_QUERY_TIMEOUT_MS = 5_000;
+/** 问到的提议多久内可用:与组所在电脑判断配额用的快照有效期一致。 */
+export const SESSION_REBALANCE_CACHE_MS = 10 * 60_000;
+/** 任务空闲、开着时多久重新问一次。 */
+export const SESSION_REBALANCE_REFRESH_MS = 5 * 60_000;
+const MAX_PREFETCHED = 100;
+
+// 与桌面端 shared/providerGroup.ts 读这个回包的口径一致。
+const MEMBER_KEY = /^[A-Za-z0-9_.:-]{1,300}$/;
+// eslint-disable-next-line no-control-regex -- 控制字符是显式拒绝目标
+const CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
+const MAX_WINDOW_MS = 31 * 86_400_000;
+
+export interface MobileRebalanceSuggestion {
+ kind: 'ask' | 'auto';
+ memberKey: string;
+ label: string;
+ quota: { usedPercent: number; resetAtMs: number | null; windowMs: number };
+}
+
+export type MobileRebalanceChoice = 'switch' | 'remember' | 'cancel';
+
+type Invoke = (deviceId: string, channel: string, args?: unknown[]) => Promise<unknown>;
+
+const prefetched = new Map<string, { at: number; suggestion: MobileRebalanceSuggestion | null }>();
+const inFlight = new Set<string>();
+
+function cacheKey(hostDeviceId: string, sessionId: string): string {
+ return `${hostDeviceId}\u0000${sessionId}`;
+}
+
+/** 读 `rebalance-suggestion` 的回包;格式不对按不提议处理。 */
+export function parseMobileRebalanceSuggestion(raw: unknown): MobileRebalanceSuggestion | null {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const value = raw as Record<string, unknown>;
+ if (value.kind !== 'ask' && value.kind !== 'auto') return null;
+ if (typeof value.memberKey !== 'string' || !MEMBER_KEY.test(value.memberKey)) return null;
+ const label = typeof value.label === 'string' ? value.label.trim() : '';
+ const quota = value.quota as Record<string, unknown> | null | undefined;
+ if (!label || label.length > 128 || CONTROL_CHARS.test(label) || !quota || typeof quota !== 'object') return null;
+ const { usedPercent, resetAtMs, windowMs } = quota;
+ if (typeof usedPercent !== 'number' || !Number.isFinite(usedPercent)) return null;
+ if (typeof windowMs !== 'number' || !Number.isFinite(windowMs) || windowMs <= 0 || windowMs > MAX_WINDOW_MS) return null;
+ if (resetAtMs !== null && (typeof resetAtMs !== 'number' || !Number.isFinite(resetAtMs) || resetAtMs <= 0)) return null;
+ return {
+ kind: value.kind,
+ memberKey: value.memberKey,
+ label,
+ quota: { usedPercent: Math.min(100, Math.max(0, usedPercent)), resetAtMs, windowMs },
+ };
+}
+
+/** 弹窗正文:换到哪台、那台的配额还剩多少、多久重置,以及换过去会丢一部分上下文。 */
+export function describeMobileRebalance(suggestion: MobileRebalanceSuggestion, nowMs = Date.now()): string {
+ const left = Math.max(0, Math.round(100 - suggestion.quota.usedPercent));
+ const remainingMs = suggestion.quota.resetAtMs === null ? null : suggestion.quota.resetAtMs - nowMs;
+ const quota = remainingMs !== null && remainingMs > 0
+ ? i18n.t('session.providerGroupRebalance.quotaReset', {
+ left,
+ reset: formatLocalizedSeconds(Math.ceil(remainingMs / 60_000) * 60),
+ })
+ : i18n.t('session.providerGroupRebalance.quota', { left });
+ return i18n.t('session.providerGroupRebalance.body', { label: suggestion.label, quota });
+}
+
+/** 系统弹窗问用户;点外面关掉(Android)按取消处理。 */
+export function askMobileSessionRebalance(suggestion: MobileRebalanceSuggestion): Promise<MobileRebalanceChoice> {
+ return new Promise((resolve) => {
+ Alert.alert(
+ i18n.t('session.providerGroupRebalance.title', { label: suggestion.label }),
+ describeMobileRebalance(suggestion),
+ [
+ { text: i18n.t('session.providerGroupRebalance.cancel'), style: 'cancel', onPress: () => resolve('cancel') },
+ { text: i18n.t('session.providerGroupRebalance.remember'), onPress: () => resolve('remember') },
+ { text: i18n.t('session.providerGroupRebalance.confirm'), onPress: () => resolve('switch') },
+ ],
+ { cancelable: true, onDismiss: () => resolve('cancel') },
+ );
+ });
+}
+
+function withTimeout<T>(promise: Promise<T>, fallback: T): Promise<T> {
+ return new Promise((resolve) => {
+ const timer = setTimeout(() => resolve(fallback), SESSION_REBALANCE_QUERY_TIMEOUT_MS);
+ promise.then(
+ (value) => {
+ clearTimeout(timer);
+ resolve(value);
+ },
+ () => {
+ clearTimeout(timer);
+ resolve(fallback);
+ },
+ );
+ });
+}
+
+/** 任务空闲时预先问好提议。同一个任务同时只问一次。 */
+export async function prefetchMobileSessionRebalance(invoke: Invoke, hostDeviceId: string, sessionId: string): Promise<void> {
+ const key = cacheKey(hostDeviceId, sessionId);
+ if (inFlight.has(key)) return;
+ inFlight.add(key);
+ try {
+ const raw = await withTimeout(
+ invoke(hostDeviceId, PROVIDER_GROUP_REMOTE_CHANNEL, [{ action: 'rebalance-suggestion', sessionId }]),
+ null,
+ );
+ prefetched.delete(key);
+ prefetched.set(key, { at: Date.now(), suggestion: parseMobileRebalanceSuggestion(raw) });
+ if (prefetched.size > MAX_PREFETCHED) prefetched.delete(prefetched.keys().next().value!);
+ } finally {
+ inFlight.delete(key);
+ }
+}
+
+/** 开着的任务空闲且连着时预先问好提议:变空闲(上一轮结束、打开任务)时问一次,之后每 5 分钟再问。 */
+export function useMobileSessionRebalancePrefetch(input: {
+ invoke: Invoke;
+ hostDeviceId: string;
+ sessionId: string;
+ idle: boolean;
+}): void {
+ const { invoke, hostDeviceId, sessionId, idle } = input;
+ useEffect(() => {
+ if (!hostDeviceId || !sessionId || !idle) return;
+ void prefetchMobileSessionRebalance(invoke, hostDeviceId, sessionId);
+ const timer = setInterval(
+ () => void prefetchMobileSessionRebalance(invoke, hostDeviceId, sessionId),
+ SESSION_REBALANCE_REFRESH_MS,
+ );
+ return () => clearInterval(timer);
+ }, [invoke, hostDeviceId, sessionId, idle]);
+}
+
+/** 取走问好的提议:一次提议只用于一条消息,过期的不用。 */
+function takePrefetched(hostDeviceId: string, sessionId: string): MobileRebalanceSuggestion | null {
+ const key = cacheKey(hostDeviceId, sessionId);
+ const entry = prefetched.get(key);
+ prefetched.delete(key);
+ return entry && Date.now() - entry.at <= SESSION_REBALANCE_CACHE_MS ? entry.suggestion : null;
+}
+
+/**
+ * 发送前调用:有问好的提议就按用户的选择记到任务所在电脑(它在这条消息发出前换过去);没有提议时立即返回,不等网络。
+ * 不拦发送——调用方之后照常发出这条消息。
+ */
+export async function offerMobileSessionRebalance(input: {
+ invoke: Invoke;
+ hostDeviceId: string;
+ sessionId: string;
+ ask(suggestion: MobileRebalanceSuggestion): Promise<MobileRebalanceChoice>;
+}): Promise<void> {
+ const { invoke, hostDeviceId, sessionId } = input;
+ const suggestion = takePrefetched(hostDeviceId, sessionId);
+ if (!suggestion) return;
+ const choice = suggestion.kind === 'auto' ? 'switch' : await input.ask(suggestion);
+ if (choice === 'cancel') return;
+ try {
+ await invoke(hostDeviceId, PROVIDER_GROUP_REMOTE_CHANNEL, [{
+ action: 'rebalance-decision',
+ sessionId,
+ memberKey: suggestion.memberKey,
+ remember: choice === 'remember',
+ }]);
+ } catch {
+ // 没记上就是这条照常发到原来的账号,下一条再问。
+ }
+}
diff --git a/apps/mobile/src/session/systemCard.ts b/apps/mobile/src/session/systemCard.ts
index f7f499e176..a4e5fc43f6 100644
--- a/apps/mobile/src/session/systemCard.ts
+++ b/apps/mobile/src/session/systemCard.ts
@@ -208,6 +208,7 @@ type AgentSwitchTranslate = (key: string, options?: Record<string, unknown>) =>
* 远程 Agent:边界行带 toAgentDeviceId 键 = 这次切换把 Agent 换到了另一台电脑上运行
* (null = 被控电脑本机),标题改说位置;引擎同时换了再以「 · 目标引擎」带上。没换电脑
* 返回 null,调用方沿用「已从 X 切换到 Y」。名称是切换时的快照,缺名时按位置给通用说法。
+ * 用户确认为了先用那台的配额换过去的(switchReason: 'quota-rebalance')最后写明原因,与桌面一致。
*/
export function formatAgentSwitchLocationLabel(
data: Record<string, unknown> | undefined,
@@ -215,14 +216,17 @@ export function formatAgentSwitchLocationLabel(
): string | null {
const location = readAgentSwitchLocationTarget(data);
if (!location) return null;
- const label = location.kind === 'named'
+ const place = location.kind === 'named'
? translate('message.systemCard.agentSwitchLocation', { device: location.name })
: translate(location.kind === 'thisComputer'
? 'message.systemCard.agentSwitchLocationThisComputer'
: 'message.systemCard.agentSwitchLocationOtherComputer');
const from = mobileAgentLabelFromUnknown(data?.fromAgentKind);
const to = mobileAgentLabelFromUnknown(data?.toAgentKind);
- return from === to ? label : `${label} · ${to}`;
+ const label = from === to ? place : `${place} · ${to}`;
+ return data?.switchReason === 'quota-rebalance'
+ ? `${label} · ${translate('message.systemCard.agentSwitchLocationQuotaRebalance')}`
+ : label;
}
/**
diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.md
index 4ecd73e960..17c6bdeed7 100644
--- a/docs/dev-rules/credentials-and-local-storage.md
+++ b/docs/dev-rules/credentials-and-local-storage.md
@@ -214,6 +214,7 @@ refresh 与 relay 自救节流。在途 refresh 尚未返回时收到的恢复
| 供应商分享:短期审批弹窗归属 | `userData/owners/<账号>/provider-share-approval-windows.json`,只记供应商 id、生成端关注的供应商所在电脑 id、非秘密链接标识 `linkId`(随机邀请口令的 SHA-256 摘要)与七分钟截止时刻,不含链接口令、申请、配对码或身份。复用设置文件跨进程锁与原子替换;生成链接返回前完成保存,静默与关注均按链接区分。本机新链接仅清除旧版按供应商静默的窗口,不影响其它链接的精确归属。旧记录仍可读,无标识的旧关注只接无标识申请。完整应用重启的第一轮快照前恢复;远端读取使用新运行时的同账号只读管理通道,不恢复旧回调或重放写操作。过期记录读时忽略、下次写入清理;账号切换隔离,损坏文件保留且拒绝覆写。见 `device-link/providerShareApprovalWindows.ts`、`providerShareHost.ts` 与 `__tests__/providerShareApprovalWindows.test.ts` |
| 供应商组:本机组绑定待清理记录 | 复用 `userData/owners/<账号>/provider-group-prefs.json` 的可选 `bindingCleanups`,只记供应商 id、保留的组员键(整组删除为 null)、时间与不透明代次,不含消息、凭证或用户身份。与组修改共用文件锁和原子替换;组修改、清理回放与新绑定写入另共用同账号目录的 `provider-group-mutation.lock`(先取该锁,再取各文件锁),防止迟到清理误删新分配。账号切换或重启后仍使旧绑定失效;重新加入不撤销清理,多次移出的保留键取交集。新写绑定前先将旧绑定删除与解除记录原子提交,再按代次确认;写盘失败或确认中断保留意图重试,迟到确认不删除新一代记录。旧文件缺字段视为空,旧版写组设置保留未知根字段。见 `provider-group/store.ts`、`bindings.ts`、`managementScope.ts` 与 `__tests__/stores.test.ts` |
| 供应商组:本机组的绑定解除记录 | 复用 `userData/owners/<账号>/provider-group-bindings.json` 的可选 `released`,按任务 id 只记供应商 id 与解除时间,不含消息、凭证或用户身份。删组或移出组员时,与对应绑定删除共用文件锁和原子替换;账号切换前已提交的两部分一同保留。旧文件缺字段视为空,旧版写绑定保留未知根字段,升级后解除记录优先于旧版恢复的绑定;显式重新分配给同一个组时原子清除记录。其他解除路径仍读写 `provider-group-released.json`,读方合并两处记录;损坏绑定文件保留并拒绝覆写。见 `provider-group/bindings.ts` 与 `__tests__/stores.test.ts` |
+| 供应商组:任务里选过「以后自动换号」 | `userData/owners/<账号>/provider-group-session-prefs.json` 的 `autoRebalance`,按任务 id 只记打开时间,不含消息、凭证或用户身份(provider-groups.md §6.2)。存在任务所在的电脑上,跨重启保留,不同步、不外发;最多 4000 条,超出丢最早的,上限 512 KB。原子替换写入;读不出或超限时保留原文件、按都没选过处理。降级旧版忽略这个文件。见 `provider-group/sessionPrefs.ts` |
| 供应商组:转分享待清空记录 | 复用 `userData/owners/<账号>/provider-group-prefs.json` 的可选 `reshareCleanups`,只含分享来的电脑逻辑 id 与随机清理代次,不含昵称、头像、对话或凭证。最后一个组引用移出时,与组设置在同一跨进程锁内原子写入;对端确认空名单后按代次删除,失败每分钟重试,重启继续,重新加入先清空旧同意。旧文件缺字段视为空,旧版改写组设置仍保留未知字段;损坏文件保留并拒绝覆写。见 `provider-group/store.ts` 与 `__tests__/stores.test.ts` |
| 供应商按使用方的用量 | `userData/owners/<账号>/provider-usage-by-party.json`,按(日期、供应商、使用方、设备 id、组内电脑的键、Agent、模型)聚合 token 与轮次。使用方:本机、同账号另一台电脑、经同账号组所在电脑转来的受邀者任务、本机经另一台电脑的组在别的组内电脑上运行的(只用来报告给那台组所在电脑)、同账号电脑报告来的(每次报告整体替换那台从某天起的行);没有使用方字段的旧行按设备 id 推出。原子替换写入,保留 400 天;只含供应商 id、设备 id、组内电脑的键与模型名,不含对话或凭证。按账号存放(供应商 id 在不同账号下会重复),从开始记录起不补历史 |
| macOS 菜单栏余量设置 | `userData/menubar-settings.json`,本机偏好:是否显示、来源顺序与显隐、菜单栏文字、快见底通知、隐藏个人信息、统计范围;只含供应商 id,不含凭证或用量数值 |
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 666f9f620f..b8306b11af 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -1589,6 +1589,8 @@ B 上的 Worker 是一条普通任务,`sessions.orca_remote_lead`(migration 01
的模型列表据此把归组的任务显示在组那一项下、在组那一项里选模型时留在此刻运行的那台(provider-groups.md §10)。不读写分配器、
负载与绑定。旧版本回 `CHANNEL_NOT_ALLOWED`(没有这个通道)或 `[INVALID_PARAMS] unknown provider group action`(有通道没有这个
动作),控制端一律按没归组处理,即与改动前相同。
+ - `rebalance-suggestion { sessionId }` / `rebalance-decision { sessionId, memberKey, remember: boolean }`(2026-10-21,任务进行中
+ 换号,provider-groups.md §6.2):同样发给**任务所在的电脑**,见下方「供应商组任务进行中换号」。
旧 O 回 `CHANNEL_NOT_ALLOWED`:`pick` 按 `none` 处理,任务照旧直接在 O 上运行。
- **`maker:provider:list` 新增可选字段 `group`**:只对同账号调用方、只加在建了组且「允许被远程调用」的供应商上:
`{ strategy, autoSwitch, members: [{ key, kind, agentDeviceId, providerId, label?, paused }] }`(并发上限与权重不外发)。
@@ -1651,8 +1653,9 @@ B 上的 Worker 是一条普通任务,`sessions.orca_remote_lead`(migration 01
- **可选策略枚举扩展**:本地组配置与同账号组摘要的 `strategy` 增加 `usage`,原默认 `least` 不变。
旧版桌面读取未知策略时归一化为 `least`,旧版手机不依赖这个字段;远程 `pick` 仍由组所在电脑执行,因此
旧控制端连接新组所在电脑也能使用新策略。组所在电脑降级后按 `least` 分配,旧版再次保存组设置会写回 `least`。
- 2026-10-15 起配额排序(快到期先用、已用百分比低的先用)对所有策略生效,设置界面不再提供 `usage`;枚举值与归一化
- 保持不变,已存的 `usage` 照常读写,挑法与 `least` 相同。这只改组所在电脑本机的选择,不新增字段、不改通道。
+ 2026-10-15 起配额排序对所有策略生效(2026-10-21 起按「剩下的额度 ÷ 剩下的时间」,最急的先用),设置界面不再提供
+ `usage`;枚举值与归一化保持不变,已存的 `usage` 照常读写,挑法与 `least` 相同。这只改组所在电脑本机的选择,
+ 沿用已有的用量快照字段,不新增字段、不改通道。
- **复用已有同账号通道**:向成员电脑调用 `maker:usage:claude-subscription`,参数 `[member.providerId]`;本机走同一
订阅 reader。只信与请求一致的 `providerId` 回显;旧端未回显时仅允许默认 `anthropic`,具名账号按未知用量处理,
避免旧端忽略参数后拿默认账号的额度代替。通道不可用、失败、超时或快照过期时按未知处理,分配照常进行。
@@ -1662,13 +1665,50 @@ B 上的 Worker 是一条普通任务,`sessions.orca_remote_lead`(migration 01
不调用兑换重置卡接口,不把重置卡、账号标识或凭证放进内部目录的配额快照。本机和远端读取合并在途,短缓存 15 秒。
- **可选框架信息**:同账号 `view` 请求增加可选 `agentKind: 'codex' | 'pi' | 'claude-code'`,供 OpenAI 发送前检查
选择原生模型桶或 web 槽;缺省仍按原生模型桶处理,旧组所在电脑忽略该字段。原有仅带模型的查询和回包形状不变。
-- **隐私与状态**:额度快照只留在组所在电脑的内部目录中,不加入 `ProviderGroupView` 的额度字段或供应商目录,不传给受邀者;
- 分享来的成员不调用此通道。同账号不带 `model` 的 `view` 仅复用已有 `cooling` / `coolingUntil` 表达总窗口耗尽,带 `model`
- 的发送前查询只在回显模型一致时临时表达该模型的额度状态,不能改变其他模型的可用性。账号切换时丢弃旧读取,不扩大 allowlist
- 或凭证访问。
+- **隐私与状态**:完整额度快照只留在组所在电脑的内部目录中,不进供应商目录,不传给受邀者;分享来的成员不调用此通道。
+ 同账号不带 `model` 的 `view` 用已有 `cooling` / `coolingUntil` 表达总窗口耗尽,带 `model` 的发送前查询只在回显模型一致时
+ 临时表达该模型的额度状态,不能改变其他模型的可用性。账号切换时丢弃旧读取,不扩大 allowlist 或凭证访问。
+- **成员状态可选 `quota`(2026-10-21 用户确认)**:`ProviderGroupView.members[]` 增加可选
+ `quota: { usedPercent, resetAtMs: number | null, windowMs }`,只是选电脑排序用的那一个窗口(provider-groups.md §5、§10
+ 的进度条),不带 5 小时窗口、模型桶名、账号标识或重置卡。组所在电脑本机界面与同账号 `view` 回包都带;读不到配额的成员
+ 省略。`parseProviderGroupRemoteView` 只收有限数值(百分比收敛到 0–100,窗口 0–31 天,重置时刻为正数或 `null`),
+ 分享来的成员一律丢弃;受邀者的匿名状态是白名单投影,不带此字段。旧组所在电脑不回此字段,查看端不画进度条;
+ 旧查看端忽略它。不新增 channel、请求参数或持久数据。
- 不新增 channel,不改 relay、服务器、数据库或持久冷却格式。实现:`provider-group/usage.ts`、`directory.ts`、`runtime.ts`、
`router.ts`、`remoteClient.ts`、`remoteHandler.ts`、`service.ts`;额度判定与自动继续复用 `shared/accountUsageLimit.ts`。回归见
`provider-group/__tests__/usage.test.ts`、`router.usage.test.ts`、`runtime.test.ts` 与 `scheduler.test.ts`。
+- **成员状态可选 `fiveHourTight: true`(2026-10-21)**:只在带 `quota` 时出现,表示这台的 5 小时配额已用 85% 以上、离重置还有
+ 1 小时以上(provider-groups.md §5 第 0 条)。同账号电脑据此不把它当作任务进行中换号的目标。旧组所在电脑不回,查看端按不紧张处理
+ (最坏是提议后组所在电脑按自己的排序选不中它,照常留在原处);旧查看端忽略。`parseProviderGroupRemoteView` 只认 `true`。
+
+## 供应商组任务进行中换号
+
+产品规则见 [`provider-groups.md`](../product-rules/provider-groups.md) §6.2(2026-10-21 用户裁决:上一轮结束、用户发下一条消息
+前弹窗问要不要换号,可为这个任务选「以后自动换」,手机与电脑一致)。
+
+- **两个新动作,发给任务所在的电脑**:本机走 `providerGroup.command`(IPC,只限本机 renderer),手机与桌面远程控制走已有的
+ 同账号 `provider-group:remote`(dispatch 已拒绝受邀者与共享任务访客,allowlist 不变)。
+ - `rebalance-suggestion { sessionId }` → `{ kind: 'ask' | 'auto', memberKey, label, quota } | null`:只读,不记占用、不改绑定。
+ `auto` = 这个任务选过以后自动换,客户端不弹窗、直接回 `rebalance-decision`。`quota` 是要换去那台排序用的窗口,形状同
+ `ProviderGroupView.members[].quota`;`label` 是那台的显示名(同一台电脑上有几个账号时带账号名),不含账号标识。
+ - `rebalance-decision { sessionId, memberKey, remember }` → `{ ok: boolean }`:记下这个任务接下来的一次发送先换到 `memberKey`
+ (2 分钟内有效,定时任务的发送不用它);`remember: true` 时另记这个任务以后自动换。`memberKey` 不在组里回 `ok: false`。
+ - 解析:`sessionId` 与 `memberKey` 按已有远程 id 规则校验,`remember` 必须是布尔值,坏请求回 `[INVALID_PARAMS]`。客户端读回包用
+ `parseProviderGroupRebalanceSuggestion`(手机端 `parseMobileRebalanceSuggestion`,口径相同),格式不对按不提议处理。
+- **时机**:客户端在任务空闲时预先问 `rebalance-suggestion`(变空闲、打开任务时,空闲期间每 5 分钟;单次最多等 5 秒),
+ 结果 10 分钟内有效、只用于一条消息;点发送时只用问好的结果,不为它多等一次往返。只有用户确认换号(或任务选过自动换)时,
+ 发送前等 `rebalance-decision` 回来再发,确保任务所在电脑先记下决定。
+- **新旧兼容**:旧任务所在电脑不认识这两个动作,回 `[INVALID_PARAMS] unknown provider group action`;客户端失败或超时都按
+ 不提议处理、照常发送,与改动前一致。旧客户端不发这两个动作,任务所在电脑不会自己换号(没有用户确认就不换),行为与改动前
+ 一致。不新增 channel、relay、服务器或数据库字段。
+- **分隔条内容可选 `switchReason: 'quota-rebalance'`**:`agent_switch` 边界行(`AgentSwitchBoundaryContent`)只在供应商组为此换了
+ 电脑时带上,桌面与手机在位置后写「· 这个账号的配额更该先用」。旧端忽略,照常只显示位置。
+- **本机持久数据**:「以后自动换」存在按账号隔离的 `provider-group-session-prefs.json`(`{ autoRebalance: { [sessionId]: at } }`,
+ 最多 4000 条、超出丢最早的;读不出时保留原文件、按都没选过处理)。不同步、不外发;降级旧版忽略这个文件,相当于每次都不提议。
+- 实现:`provider-group/service.ts`、`usage.ts`(`providerGroupRebalanceTarget`)、`router.ts`(`rebalanceCandidates`)、`runtime.ts`、
+ `ipc.ts`、`remoteHandler.ts`、`remoteRegistration.ts`、`sessionPrefs.ts`、`maker-ipc/sessionAgentSwitchHandler.ts`;客户端
+ `renderer/features/provider-group/sessionRebalancePrompt.ts` 与 `apps/mobile/src/session/sessionRebalancePrompt.ts`。回归见
+ `shared/__tests__/providerGroup.test.ts`、`provider-group/__tests__/service.test.ts`、两端 `sessionRebalancePrompt.test.ts`。
## 供应商组:受邀者经组所在电脑中转(P2b)
diff --git a/docs/product-rules/provider-groups.md b/docs/product-rules/provider-groups.md
index 98a6aa275a..8aa72ea337 100644
--- a/docs/product-rules/provider-groups.md
+++ b/docs/product-rules/provider-groups.md
@@ -32,6 +32,11 @@
> 分享的人一样按组策略分配,本机只是组里普通的一台;「暂停对外分配」仍只拦外部新任务。同日要求**配额先比、快到期的先用**
> (目的是尽快把快重置的配额用掉):不论选哪种组策略,都先用每周配额 5 小时内重置的,然后是 5 小时配额 1 小时内重置的,
> 再选已用百分比低的;组策略只在用量相近的几台里挑,「用量均衡」不再单列为选项,见 §5。
+> 2026-10-21 用户裁决(取代上一条的两档快到期与已用百分比比较):优先级依次是**快作废的配额先用**、**各账号平均使用且能看出来**。
+> 配额先比改为比「剩下的配额 ÷ 剩下的时间」,最急的先用,见 §5「配额先比」;组内电脑每行显示配额进度条(已用多少、按时间该用到哪、
+> 多久后重置),数据由组所在电脑随组状态发给同账号电脑(同日用户确认),见 §10。同日还评估过「任务进行中自动换账号」:
+> 换电脑的交接只带最近几轮原文与前面的摘要,会丢工具输出与推理细节,用户决定不自动换;随后改为**上一轮结束、用户发下一条消息时
+> 弹窗问要不要换号**,可以为这个任务选「以后自动换」,手机与电脑一致,见 §6.2。
> 2026-10-16 用户要求:「远程与分享」页的**「已分享的人」并进「用量」**——同一个人不在两处各占一行:分享的人那一行同时写分享状态、
> 加入时间与用量,关闭/恢复与删除收进行尾 `···`,见 §7、§10。同日用户反馈底部的「生成分享链接」太难找:它放到页面标题右侧,
> 待处理紧跟标题,页面不再单设「分享」块与分享说明,见 §10。
@@ -180,7 +185,7 @@
代价(用户已知并接受):本机任务可能分到别的电脑运行,读文件、跑命令要在两台电脑之间往返;选电脑时与外部任务一样
最多等组内电脑状态 3 秒。
- **选择方式**:最少占用(默认,选正在运行任务最少的那台)、轮询、按顺序(排在前面的优先,前面的不可用才用后面的)、
- 按权重。读得到 Claude Code 订阅用量时,先按下方「配额先比」筛,组策略只在剩下的几台里挑(2026-10-15)。
+ 按权重。读得到 Claude Code 或 OpenAI 订阅用量时,先按下方「配额先比」筛,组策略只在剩下的几台里挑(2026-10-15)。
原来单列的「用量均衡」不再出现在设置里;已经存了它的组挑法与最少占用相同,界面按最少占用显示,用户改选时才写回新值。
- **并发上限**:每台组内电脑单独设置,默认 4,最多 16(组分配的独立设置,不随远程任务数量设置改变);只统计经本组分到这台的任务,
包括同账号其他电脑经本组直连过去的任务:它们由任务所在的电脑在每一轮开始、结束时报告,运行期间每分钟再报一次,
@@ -207,22 +212,27 @@
实际错误产生的冷却也按任务模型隔离,不能把分模型限额变成整台电脑的冷却。
OpenAI 按任务框架和模型取数:Codex 按模型匹配原生限额桶,Pi 与 Claude Code bridge 使用 ChatGPT web 槽;
不拿其他模型的桶或另一框架的槽代替。Codex 的每个桶与 web 槽分别检查快照时间,新桶更新不能让旧桶重新有效。
- - **配额先比**(2026-10-15 用户裁决:目的是尽快把快重置的配额用掉;不论选哪种组策略都先做这一步):先做上述排除,
- 再在未达到并发上限的候选里先保留用量完整的电脑(窗口有效性见第 2 条),然后依次筛;全部读不到用量时不比较重置时间,
- 也不按用量筛,原样交给组策略:
- 1. **快到期的配额先用**:总周配额 5 小时内就重置、还没用完的先用;没有时,5 小时配额 1 小时内就重置、还没用完的
- 先用。同一档里先用重置最早的;重置时刻相差 10 分钟以内的算同时,一起进入下一条。重置时刻未知、已过或配额已用完的
- 不算快到期。
- 2. **已用百分比低的先用**:比较 5 小时、总周与当前模型专属周窗口的**最高已用百分比**,只留与最低值相差不超过
- 5 个百分点的几台。Claude 两个总窗口都有效且已知才参与比较;有对应模型的专属窗口时,它也必须有效。
- OpenAI 比较所选桶或 web 槽实际返回的窗口,支持只有一个窗口的套餐;已返回窗口的用量缺失或已重置时不参与比较。
- 缺失值不当成 0%;读不到用量的电脑(别人分享的、尚未接入用量的订阅或 API 连接)排在读得到的后面,全部读不到时不筛。
- 3. **组策略在剩下的几台里挑**:最少占用选运行任务少的,按顺序选排在前面的,轮询接着上次往下轮,按权重按比例随机。
- 全部达到并发上限时同样先按第 1、2 条筛,再选运行任务最少的;未满载的电脑永远排在满载的前面。设置页在组策略下始终显示适用条件与规则
- 「能读取订阅用量时,先用配额快重置的电脑,再选用量低的,相近时按组策略」;不能仅按组所属的本机连接类型隐藏说明,
- 因为 API Key 连接建的组也能包含同品牌的远端订阅账号。实现见 `apps/desktop/src/main/provider-group/scheduler.ts`
- 与 `apps/desktop/src/renderer/features/provider-group/ProviderGroupSection.tsx`,回归见同目录
- `__tests__/scheduler.test.ts`、`router.usage.test.ts` 与 `ProviderGroupSection.test.tsx`。
+ - **配额先比**(2026-10-21 用户裁决:快作废的额度最优先,其次各账号平均;取代 2026-10-15 的「5 小时内重置的周配额、
+ 1 小时内重置的 5 小时配额先用,再比已用百分比」。不论选哪种组策略都先做这一步):先做上述排除,再在未达到并发上限的候选里
+ 按**额度有多急着用**筛;全部读不到用量时不筛,原样交给组策略:
+ 0. **先避开 5 小时配额快满、离重置还早的**(同日用户裁决):5 小时配额用到 85% 以上、离重置还有 1 小时以上(或不知道何时
+ 重置)的号先不分新任务——刚开始就撞上限会被迫换电脑、丢上下文;5 小时配额是限速,没用完不会少用周配额。1 小时内就重置的
+ 照常分,把剩下的用掉;所有能分的号都是这样时不避开。读不到用量的电脑排在这种号前面。
+ 1. **急不急 = 剩下的额度 ÷ 剩下的时间**:两者都按窗口的百分比算。比如周额度还剩 40%、这一周还剩一半时间,急不急是 0.8;
+ 1 表示照这个速度到重置时正好用完,越大越该先用。快重置还剩很多的最急,刚重置的不急;几个账号重置时间相同时剩得多的
+ 更急,所以用量会被拉平。比的是比例而不是差多少:周额度还剩 3%、3 小时后重置(1.68)仍排在周中只用了 40%(1.2)的
+ 账号前面,免得最后一点作废。
+ 2. **只看周额度**:Claude 看总周窗口,有对应模型的专属周窗口时两者取不急的那个(一个窗口用得太快就不再催这台);
+ OpenAI 看所选桶或 web 槽里长于 5 小时的窗口,只有 5 小时窗口的套餐按它算。5 小时窗口用完时排除这台、快满时按第 0 条
+ 避开,不参与急不急的计算。窗口还没开始计时(没用过、没有重置时刻)按 1 算;用过却没有重置时刻、快照过期或窗口已重置但
+ 还没刷新的,按读不到处理,不当成没用过。
+ 3. **组策略在一样急的几台里挑**:只留不低于最急那台 90% 的几台,再由组策略挑:最少占用选运行任务少的,按顺序选排在前面的,
+ 轮询接着上次往下轮,按权重按比例随机。读不到用量的电脑(别人分享的、尚未接入用量的订阅或 API 连接)排在读得到的后面。
+ 全部达到并发上限时同样先按急不急筛,再选运行任务最少的;未满载的电脑永远排在满载的前面。设置页在组策略下始终显示适用条件与规则
+ 「能读取订阅用量时,先用快重置、还剩得多的电脑,各账号会按时间均匀用掉;差不多时按组策略」;不能仅按组所属的本机连接类型隐藏说明,
+ 因为 API Key 连接建的组也能包含同品牌的远端订阅账号。实现见 `apps/desktop/src/main/provider-group/usage.ts`(急不急)、
+ `scheduler.ts`(筛选与组策略)与 `apps/desktop/src/renderer/features/provider-group/ProviderGroupSection.tsx`,回归见
+ `apps/desktop/src/main/provider-group/__tests__/usage.test.ts`、`scheduler.test.ts` 与 `router.usage.test.ts`。
- **取数与兜底**:复用已有订阅 reader,组模块不读取凭证、不直连新的订阅 API;每台按自己的供应商账号读取。
OpenAI 并行读取已有原生限额 RPC 和账号用量 reader:原生限额不依赖已有任务或用量面板,web 槽沿用现有后台刷新。
OpenAI 本机与同账号远端快照短缓存 15 秒,Claude 仅远端短缓存;同账号同一请求在途去重;两路并行、各自缓存与限时,单次最多等待 1.5 秒,
@@ -232,7 +242,8 @@
重试选电脑时清掉短缓存。账号切换后丢弃旧账号的读取结果。
- **分享边界**:不读取别人分享来的电脑的订阅配额,按未知用量处理,仍复用现有可用性与失败后换电脑;
组所在电脑为受邀者选电脑时可以使用自己组内的同账号配额,但不向受邀者返回配额。
- - 正常运行的任务不因用量差距而迁移;新任务和需要换电脑时才按此策略分配。
+ - 正常运行的任务不因用量差距自动迁移;新任务和需要换电脑时按此策略分配,上一轮结束后用户发下一条消息时可以在用户确认后
+ 换号(§6.2)。
- 已经绑定的任务在发送前由组所在电脑按本次模型重新核对额度;总窗口或该模型专属周窗口耗尽时换电脑,
OpenAI 同时核对任务框架,快照未知时不因额度判断阻塞发送。
- **冷却**:组内电脑上的任务报用量上限时,仅该任务模型进入冷却(Claude 按同一模型家族合并别名),其他模型仍可分配;
@@ -264,7 +275,8 @@
- 任务第一次在组里运行时按 §5 的组策略选定一台组内电脑,之后固定在这台:对话记录保存在那台电脑上。只有正常运行时才保持
固定;那台电脑出问题时按下面的规则**自动换电脑**,不需要用户操作。
-- 正在正常运行的任务不会因为组策略变化或其他电脑空闲而迁移。
+- 正在正常运行的任务不会因为组策略变化或其他电脑空闲而自动迁移;为配额换号只在上一轮结束、用户发下一条消息并确认后
+ 进行(换电脑的交接只带最近几轮原文与前面的摘要,会丢工具输出与推理细节),见 §6.2。
- 只给从没运行过的任务按 §5 选电脑。已经运行过、正用着组那一项的任务不按策略挪走:留在原处并纳入组,之后出问题时
照常自动换电脑(2026-10-10 用户要求:老任务也要生效)。包括:
- 建组前就在用这个供应商的任务、回退或清空后原生会话被清掉的任务;
@@ -422,6 +434,41 @@
已知差异(P2a):同账号其他电脑的模型列表里,组那一项列的是组所在电脑本机这个供应商的模型,还不是并集。
- 任务详情与任务头部显示实际运行的电脑:「在 {电脑} 上运行 · 由供应商组分配」;受邀者那边不显示(§8)。
+### 6.2 任务进行中换号
+
+2026-10-21 用户裁决(取代同日「任务进行中不换账号」):同一个任务里,上一轮已经结束、用户发下一条消息时也做负载均衡,
+但换号会丢一部分上下文,**必须先弹窗问用户**;用户可以为这个任务选「以后自动换,不再询问」。
+
+- **什么时候问**:用户自己在电脑或手机上发下一条消息、上一轮已经结束时,问任务所在的电脑。它按 §5 同一把尺子比较:
+ 组里另一台电脑的配额明显更该先用才提议——两台「急不急」的差乘以那台剩下的时间(百分比)不小于 15,即重置时间相同时
+ 那台剩下的配额要多 15 个百分点以上(例如已用 70% 对 50%),差一点不打扰。要换去的那台必须此刻能接:在线、未满载、
+ 未暂停、不在冷却、5 小时配额不紧(§5 第 0 条)、读得到配额;任务所在那台本身也要正常(有问题时交给 §6.1)。
+- **不拖慢发送**:点发送要立刻发出、不多等一次网络往返(手机尤其如此),所以电脑与手机在任务空闲时预先问好——上一轮结束、
+ 打开任务时问一次,空闲期间每 5 分钟再问;问到的提议 10 分钟内有效,只用于下一条消息。没问到、问不到或任务所在电脑是旧版本时
+ 不弹窗,照常发送。只有真要换号时才等用户选择、等任务所在电脑记下决定再发。
+- **不问、不换**:正在回复时排队或插话的消息、定时任务的消息、IM 渠道发来的消息;手机上前面还有没发出的消息或断线时;
+ 只能换到同一台电脑上的另一个账号时(交接只能换电脑);伙伴、共享中、目标模式管着限额等待等不由组自动换电脑的任务(与 §6.1
+ 同一个判定)。
+- **弹窗**:写明要换去哪台(同一台电脑上有几个账号时带账号名)、那台的配额还剩多少、多久重置,以及换过去只带最近几轮对话
+ 和摘要、更早的细节可能记不全。电脑上是「换过去」「取消」两个按钮加一个默认不勾的复选框「以后自动换,不再询问(仅本任务)」;
+ 手机系统弹窗没有复选框,用三个按钮「换过去」「换过去,以后自动换(仅本任务)」「取消」(用户要求与电脑一致)。
+- **选择的结果**:
+ - 换过去:这条消息发出前先换到那台(进行中行显示「正在换一台电脑继续」),消息里的分隔条写
+ 「Agent 已改到 {电脑} 上运行 · 这个账号的配额更该先用」。不勾复选框时这个任务以后遇到同样情况每次仍会问。
+ - 勾了「以后自动换」再换过去:这个任务以后不再弹窗,直接换,分隔条照常写一行。只记这个任务,记录存在任务所在的电脑上,
+ 换一台电脑或在手机上看这个任务也一样;任务删除后记录不再有用,超过 4000 条时丢掉最早的。
+ - 取消(含关闭弹窗):不换,这条消息照常发到原来的账号;下一条消息仍会再问。
+ - 无论选什么,这条消息都照常发出。
+- **换不过去**:用户确认后 2 分钟内没发出去的(停止、断线)不留到以后;那台此刻接不了或交接失败时照常发到原来的账号、
+ 不报错,那台 30 分钟内不再提议。这次换号不算 §6.1 的「这一轮试过」,之后原电脑出问题照常可以换回来。
+- 用户确认的换号不受「出问题时自动换电脑」开关影响(开关管的是出问题时不问就换)。
+- **实现**:判断与执行在任务所在电脑的 `apps/desktop/src/main/provider-group/service.ts`(`rebalanceSuggestion`、
+ `rebalanceDecision`、`beforeSend`),尺子是 `usage.ts` 的 `providerGroupRebalanceTarget`;「以后自动换」存在
+ `provider-group/sessionPrefs.ts`。电脑在 `features/provider-group/sessionRebalancePrompt.ts`(发送前由
+ `CCAgentSessionView` 调用),手机在 `apps/mobile/src/session/sessionRebalancePrompt.ts`(会话页发送前调用);
+ 协议见 protocol-compatibility.md「供应商组任务进行中换号」。回归见 `provider-group/__tests__/service.test.ts`、
+ `usage.test.ts`、两端的 `sessionRebalancePrompt.test.ts` 与分隔条的 `SystemCard.i18n.test.tsx`、手机 `systemCard.test.ts`。
+
## 7. 用量
- **记账位置**:组所在电脑。经这个供应商运行或转发的任务都记账,包括本机、同账号其他电脑与分享的人;
@@ -620,6 +667,14 @@
只写「别人分享的电脑不显示配额」;不在线的电脑不去读。展示组件只在展开时读,收起时停止展示读取;
组状态与分配所需的 Claude 订阅额度另按 §5 读取,不依赖这一行是否展开。
另一台电脑上的组的只读列表同样可以展开。这是剩余配额,不是 §7 的经组运行的用量统计(P3)。
+ - **状态行带配额进度条**(2026-10-21 用户要求:不展开就能看出各账号是不是在平均地用):状态词后面接一条细进度条,
+ 条上的竖线是按时间这时候该用到的位置,后面写「已用 40%,该用到 50%」与「3天 12小时后重置」。画的是 §5 选电脑排序用的
+ 同一个窗口(周配额;有模型专属周配额时取两者中不急的那个;只有 5 小时窗口的 OpenAI 套餐画 5 小时窗口),由组所在电脑
+ 随组状态给出,不另读那台电脑;窗口还没开始计时时只写已用、不画竖线。读不到配额的电脑(别人分享的、API 连接、
+ 旧版本的组所在电脑)不画。本机的组与另一台电脑上的组的只读列表都显示;受邀者的匿名状态不带。
+ 实现见 `apps/desktop/src/renderer/features/provider-group/GroupMemberPace.tsx`,回归见同目录
+ `__tests__/ProviderGroupSection.test.tsx`、`apps/desktop/src/main/provider-group/__tests__/router.usage.test.ts`
+ 与 `apps/desktop/src/shared/__tests__/providerGroup.test.ts`。
- **添加电脑**:弹窗分「已经能用的」与「分享链接」两页:前者把你的其他电脑和别人分享给你的放在同一个列表里勾选;分享链接沿用申请与配对码流程,
供应商不一致(§3 口径)、链接属于自己账号、链接失效时给出对应提示。
- **同一台电脑上的几个账号按电脑聚合**(2026-10-15 用户要求):组里的一项仍是「电脑 + 这台电脑上的一个供应商账号」,
diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.md
index 81a1b33c0a..ddebd2edd0 100644
--- a/i18n/GLOSSARY.md
+++ b/i18n/GLOSSARY.md
@@ -341,7 +341,7 @@ Chat Server 的群角色,可由人或伙伴担任;不要与伙伴主人或
### Group Strategy
-供应商组为新任务选择组内电脑的规则:最少占用、轮询、按顺序、按权重。读得到 Claude 订阅用量时先按配额筛(快重置的先用、用量低的先用),组策略只在用量相近的几台里挑。只决定新任务分到哪台,正常运行的任务不因均衡迁移。
+供应商组为新任务选择组内电脑的规则:最少占用、轮询、按顺序、按权重。读得到 Claude Code 或 OpenAI 订阅用量时先按配额筛(2026-10-21 起比「剩下的配额 ÷ 剩下的时间」,最急的先用),组策略只在差不多急的几台里挑。只决定新任务分到哪台,正常运行的任务不因均衡迁移。
### Thread (in a group chat)
@@ -659,7 +659,7 @@ Codex 模型的第三档速度;与推理深度 Ultra 独立。标准、快速
### Usage Balancing
-原 Claude 订阅供应商组的分配策略。2026-10-15 起配额排序(先用快重置的配额:周配额5小时内、5小时配额1小时内重置的;再选用量较低的账号)对所有组策略生效,设置里不再单列此选项,旧组存的此值按最少占用挑;不迁移正常运行的任务。
+原 Claude 订阅供应商组的分配策略。2026-10-15 起配额排序对所有组策略生效(2026-10-21 起比「剩下的配额 ÷ 剩下的时间」,最急的先用),设置里不再单列此选项,旧组存的此值按最少占用挑;不迁移正常运行的任务。
### Use my browser logins
diff --git a/i18n/glossary.json b/i18n/glossary.json
index c982e09380..3e0d6e2531 100644
--- a/i18n/glossary.json
+++ b/i18n/glossary.json
@@ -2424,7 +2424,7 @@
"ko": "그룹 배정 방식"
},
"checkCase": false,
- "note": "供应商组为新任务选择组内电脑的规则:最少占用、轮询、按顺序、按权重。读得到 Claude 订阅用量时先按配额筛(快重置的先用、用量低的先用),组策略只在用量相近的几台里挑。只决定新任务分到哪台,正常运行的任务不因均衡迁移。"
+ "note": "供应商组为新任务选择组内电脑的规则:最少占用、轮询、按顺序、按权重。读得到 Claude Code 或 OpenAI 订阅用量时先按配额筛(2026-10-21 起比「剩下的配额 ÷ 剩下的时间」,最急的先用),组策略只在差不多急的几台里挑。只决定新任务分到哪台,正常运行的任务不因均衡迁移。"
},
{
"id": "usage-balancing",
@@ -2437,7 +2437,7 @@
"ko": "사용량 균형"
},
"checkCase": false,
- "note": "原 Claude 订阅供应商组的分配策略。2026-10-15 起配额排序(先用快重置的配额:周配额5小时内、5小时配额1小时内重置的;再选用量较低的账号)对所有组策略生效,设置里不再单列此选项,旧组存的此值按最少占用挑;不迁移正常运行的任务。"
+ "note": "原 Claude 订阅供应商组的分配策略。2026-10-15 起配额排序对所有组策略生效(2026-10-21 起比「剩下的配额 ÷ 剩下的时间」,最急的先用),设置里不再单列此选项,旧组存的此值按最少占用挑;不迁移正常运行的任务。"
},
{
"id": "pairing-code",