Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(provider-group): bind rebalance approval to its message and recheck target

MagicLizid3cb6c93cf88
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
index 60ad976382..0e2df98b40 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
@@ -421,7 +421,7 @@ describe('maker SEND transaction', () => {
},
});
expect(applyPendingAgentSwitch).toHaveBeenCalledWith('session-1',
- scheduled ? { scheduled: true } : undefined);
+ { clientId: 'model-input', ...(scheduled ? { scheduled: true } : {}) });
expect(onModelDispatched).toHaveBeenCalledExactlyOnceWith('session-1', 'model-input');
});
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index eff3ac8e92..15e264a798 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -503,7 +503,7 @@ export interface MakerSendTransactionDeps {
* 保留意图本次不动。undefined = 不启用(测试最小 harness)。`signal` 是这次发送的取消信号:
* 供应商组在这里等原电脑恢复时,发送被停止就不再等、不再换电脑。
*/
- applyPendingAgentSwitch?(sessionId: string, options?: { signal?: AbortSignal; scheduled?: boolean }): Promise<void>;
+ applyPendingAgentSwitch?(sessionId: string, options?: { signal?: AbortSignal; scheduled?: boolean; clientId?: string }): Promise<void>;
onModelDispatched?(sessionId: string, clientId: string): void;
/**
* 发送前换窗:必须在 getSession 之前。prepare 会关掉不健康的 live handle,
@@ -1045,11 +1045,14 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
const sendOrigin = requestedSendOpts.persistUserMessage?.origin ?? requestedSendOpts.origin;
const scheduled = !!sendOrigin && typeof sendOrigin === 'object' &&
(sendOrigin as { kind?: unknown }).kind === 'scheduler';
+ const rawClientId = requestedSendOpts.persistUserMessage?.clientId;
+ const clientId = typeof rawClientId === 'string' ? rawClientId : undefined;
await deps.applyPendingAgentSwitch?.(
sessionId,
- requestedSendOpts.signal || scheduled ? {
+ requestedSendOpts.signal || scheduled || clientId ? {
...(requestedSendOpts.signal ? { signal: requestedSendOpts.signal } : {}),
...(scheduled ? { scheduled: true } : {}),
+ ...(clientId ? { clientId } : {}),
} : undefined,
);
// 发送前的准备期间就被停止(如供应商组正在等原电脑恢复):不再打开会话、不再派发,与 Session 在派发前
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 889be1ed58..7472cb066e 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -10547,7 +10547,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 电脑与手机发送前问要不要换号、记下用户的决定(provider-groups.md §6.2「任务进行中换号」)。
setProviderGroupSessionRebalance({
suggest: (sessionId) => sessionGroupService.rebalanceSuggestion(sessionId),
- decide: (sessionId, memberKey, remember) => sessionGroupService.rebalanceDecision(sessionId, memberKey, remember),
+ decide: (sessionId, memberKey, remember, clientId) => sessionGroupService.rebalanceDecision(sessionId, memberKey, remember, clientId),
});
// 这台电脑上每个供应商正在运行一轮的任务数:组里「本机」这台显示它,同账号电脑读目录时也带上(§5)。
setProviderGroupLocalLoad(() => countProviderRunningTurns({
@@ -17184,6 +17184,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
await providerGroupService?.beforeSend(sessionId, {
...(options?.signal ? { signal: options.signal } : {}),
...(options?.scheduled ? { scheduled: true } : {}),
+ ...(options?.clientId ? { clientId: options.clientId } : {}),
progress: (state) => agentInputCoordinatorHolder?.setProviderGroupSendReconnect(sessionId, state),
}).catch((error) => {
log.warn('provider group: pre-send check failed', {
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 16195ea87b..c263fbd7f2 100644
--- a/apps/desktop/src/main/provider-group/__tests__/ipc.test.ts
+++ b/apps/desktop/src/main/provider-group/__tests__/ipc.test.ts
@@ -88,6 +88,16 @@ function deps(candidates: ProviderGroupCandidate[], existing: ProviderGroupConfi
}
describe('parseProviderGroupCommand', () => {
+ // Unit: the real command boundary must preserve the confirmed message ID instead of a session-wide decision.
+ it('passes a confirmed message id through parsing and execution', async () => {
+ const d = deps([]);
+ d.rebalanceDecision = vi.fn(async () => true);
+ const request = { action: 'rebalance-decision', sessionId: 's1', memberKey: MINI.key, remember: false, clientId: 'message-a' };
+ expect(await executeProviderGroupCommand(d, parseProviderGroupCommand(request))).toEqual({ ok: true });
+ expect(d.rebalanceDecision).toHaveBeenCalledWith('s1', MINI.key, false, 'message-a');
+ expect(() => parseProviderGroupCommand({ ...request, clientId: 'bad id' })).toThrow();
+ });
+
it('rejects malformed commands', () => {
expect(() => parseProviderGroupCommand(null)).toThrow();
expect(() => parseProviderGroupCommand({ action: 'get', providerId: 'bad id' })).toThrow();
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 bb45237fb2..c22f92e7ee 100644
--- a/apps/desktop/src/main/provider-group/__tests__/remoteHandler.test.ts
+++ b/apps/desktop/src/main/provider-group/__tests__/remoteHandler.test.ts
@@ -92,6 +92,30 @@ function deps(overrides: Partial<ProviderGroupRemoteHandlerDeps> = {}) {
const PICK = { action: 'pick', sessionId: 's1', providerId: 'anthropic', agentKind: 'claude-code', model: 'opus', exclude: ['local'] };
describe('provider-group:remote', () => {
+ // Unit/protocol: old owners ignored the final rebalance constraints. Verify the real wire and acknowledgement.
+ it('requires the owner to acknowledge the rebalance constraint before accepting its pick', async () => {
+ const d = deps();
+ let legacy = false;
+ const client = createProviderGroupRemoteClient(async (_device, _channel, args) => {
+ const result = await handleProviderGroupRemote(d, 'laptop', args[0]);
+ if (legacy && result && typeof result === 'object') delete (result as { quotaRebalance?: unknown }).quotaRebalance;
+ return { ok: true, result };
+ });
+ const input = { ...PICK, agentKind: 'claude-code' as const, quotaRebalance: 'local' };
+ expect(await client.pick('mini', input)).toMatchObject({ kind: 'member', member: { key: MINI.key } });
+ expect(d.router.pick).toHaveBeenLastCalledWith(expect.objectContaining({ quotaRebalance: 'local' }));
+ legacy = true;
+ expect(await client.pick('mini', input)).toEqual({ kind: 'none' });
+ expect(await client.pick('mini', { ...PICK, agentKind: 'claude-code' })).toMatchObject({ kind: 'member' });
+ });
+
+ it('carries the confirmed message id to the task host', async () => {
+ const rebalanceDecision = vi.fn(async () => true);
+ const d = deps({ rebalanceDecision });
+ await handleProviderGroupRemote(d, 'laptop', { action: 'rebalance-decision', sessionId: 's1', memberKey: MINI.key, remember: false, clientId: 'message-a' });
+ expect(rebalanceDecision).toHaveBeenCalledWith('s1', MINI.key, false, 'message-a');
+ });
+
// Unit protocol regression: the real host/client used to discard the reset at both boundaries.
it.each([null, 5_000_000])('preserves verified quota exhaustion across computers (reset=%s)', async (resetAtMs) => {
const d = deps();
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 92ed71abe5..d57b550c5a 100644
--- a/apps/desktop/src/main/provider-group/__tests__/service.test.ts
+++ b/apps/desktop/src/main/provider-group/__tests__/service.test.ts
@@ -1275,12 +1275,12 @@ describe('switching accounts between messages to balance quota', () => {
memberKey: MINI.key,
quota: { usedPercent: 20, resetAtMs: 87_400_000 },
});
- await h.service.beforeSend('s1');
+ await h.service.beforeSend('s1', { clientId: 'message-a' });
expect(h.deps.switchAgentLocation).not.toHaveBeenCalled();
- expect(await h.service.rebalanceDecision('s1', MINI.key, false)).toBe(true);
+ expect(await h.service.rebalanceDecision('s1', MINI.key, false, 'message-a')).toBe(true);
const progress = vi.fn();
- await h.service.beforeSend('s1', { progress });
+ await h.service.beforeSend('s1', { progress, clientId: 'message-a' });
expect(progress).toHaveBeenCalledWith('switching');
expect(h.deps.switchAgentLocation).toHaveBeenCalledWith(
's1',
@@ -1289,29 +1289,52 @@ describe('switching accounts between messages to balance quota', () => {
);
expect(h.bindings.get('s1')?.memberKey).toBe(MINI.key);
// 确认只管那一条消息;到了那台也不再提议换回来。
- await h.service.beforeSend('s1');
+ await h.service.beforeSend('s1', { clientId: 'message-a' });
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.rebalanceDecision('s1', MINI.key, false, 'message-a');
await h.service.beforeSend('s1', { scheduled: true });
expect(h.deps.switchAgentLocation).not.toHaveBeenCalled();
- await h.service.beforeSend('s1');
+ await h.service.beforeSend('s1', { clientId: 'message-a' });
expect(h.bindings.get('s1')?.memberKey).toBe(MINI.key);
});
+ // §6.2:弹窗期间目标已满载或短窗口变紧时,普通分配的兜底不能用于主动换号。
+ // 现有成功/交接失败用例没有覆盖提议之后的状态变化;unit,从服务入口验证仍留原账号。
+ it.each(['full', 'tight', 'unknown', 'less-urgent'] as const)('keeps the current account when the proposed target becomes %s', async (state) => {
+ const h = paced();
+ expect(await h.service.rebalanceSuggestion('s1')).toMatchObject({ memberKey: MINI.key });
+ if (state === 'full') {
+ for (let i = 0; i < MINI.limit; i++) {
+ await h.router.pick({ providerId: 'anthropic', agentKind: 'claude-code', model: MODEL,
+ exclude: new Set(['local']), reserveFor: `other-${i}` });
+ }
+ } else if (state === 'tight') {
+ h.usage[MINI.key].fiveHour = { utilization: 90, resetsAt: 11_800 };
+ } else if (state === 'less-urgent') {
+ h.usage[MINI.key].sevenDay = { utilization: 20, resetsAt: 600_000 };
+ } else {
+ delete h.usage[MINI.key];
+ }
+ await h.service.rebalanceDecision('s1', MINI.key, false, 'message-a');
+ await h.service.beforeSend('s1', { clientId: 'message-a' });
+ expect(h.deps.switchAgentLocation).not.toHaveBeenCalled();
+ expect(h.bindings.get('s1')?.memberKey).toBe('local');
+ });
+
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);
+ await h.service.rebalanceDecision('s1', MINI.key, false, 'message-a');
h.advance(PROVIDER_GROUP_REBALANCE_ACCEPT_TTL_MS + 1);
- await h.service.beforeSend('s1');
+ await h.service.beforeSend('s1', { clientId: 'message-a' });
expect(h.deps.switchAgentLocation).not.toHaveBeenCalled();
expect(await h.service.rebalanceDecision('s1', 'device:elsewhere:anthropic', false)).toBe(false);
});
@@ -1319,17 +1342,29 @@ describe('switching accounts between messages to balance quota', () => {
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);
+ await h.service.rebalanceDecision('s1', MINI.key, true, 'message-a');
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 });
});
+ // §6.2:A 确认后离开而未发送,B 取消或没有提议时不能继承 A 的换号;此前只按任务 id 暂存。
+ it('consumes a confirmation only for the message whose client id was confirmed', async () => {
+ const h = paced();
+ expect(await h.service.rebalanceDecision('s1', MINI.key, true)).toBe(false);
+ expect(h.deps.writeAutoRebalance).not.toHaveBeenCalled();
+ await h.service.rebalanceDecision('s1', MINI.key, false, 'message-a');
+ await h.service.beforeSend('s1', { clientId: 'message-b' });
+ expect(h.deps.switchAgentLocation).not.toHaveBeenCalled();
+ await h.service.beforeSend('s1', { clientId: 'message-a' });
+ expect(h.deps.switchAgentLocation).toHaveBeenCalledTimes(1);
+ });
+
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');
+ await h.service.rebalanceDecision('s1', MINI.key, false, 'message-a');
+ await h.service.beforeSend('s1', { clientId: 'message-a' });
expect(h.deps.switchAgentLocation).toHaveBeenCalledTimes(1);
expect(h.bindings.get('s1')?.memberKey).toBe('local');
expect(await h.service.rebalanceSuggestion('s1')).toBeNull();
diff --git a/apps/desktop/src/main/provider-group/ipc.ts b/apps/desktop/src/main/provider-group/ipc.ts
index f04ea59218..468e6c9f7d 100644
--- a/apps/desktop/src/main/provider-group/ipc.ts
+++ b/apps/desktop/src/main/provider-group/ipc.ts
@@ -63,7 +63,7 @@ export interface ProviderGroupCommandDeps {
/** 用户发下一条消息前要不要提议换号(provider-groups.md §6.2「任务进行中换号」)。 */
rebalanceSuggestion(sessionId: string): Promise<ProviderGroupRebalanceSuggestion>;
/** 记下用户确认的换号。 */
- rebalanceDecision(sessionId: string, memberKey: string, remember: boolean): Promise<boolean>;
+ rebalanceDecision(sessionId: string, memberKey: string, remember: boolean, clientId?: string): Promise<boolean>;
changed(providerId: string): void;
/**
* 转分享(provider-sharing.md §4.3):分享来的组内电脑的主人对本机分享出去的人逐人同意的结果,设置页据此显示;
@@ -123,7 +123,11 @@ export function parseProviderGroupCommand(raw: unknown): ProviderGroupCommand {
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 (value.clientId !== undefined && (typeof value.clientId !== 'string' || !SESSION_ID_PATTERN.test(value.clientId))) {
+ throwIpcError('INVALID_PARAMS', 'invalid clientId');
+ }
+ return { action: 'rebalance-decision', sessionId, memberKey: value.memberKey as string, remember: value.remember as boolean,
+ ...(typeof value.clientId === 'string' ? { clientId: value.clientId } : {}) };
}
if (!isProviderGroupProviderId(value.providerId)) throwIpcError('INVALID_PARAMS', 'providerId required');
const providerId = value.providerId as string;
@@ -217,7 +221,7 @@ async function runProviderGroupCommand(
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) };
+ return { ok: await deps.rebalanceDecision(command.sessionId, command.memberKey, command.remember, command.clientId) };
}
const { providerId } = command;
switch (command.action) {
diff --git a/apps/desktop/src/main/provider-group/remoteClient.ts b/apps/desktop/src/main/provider-group/remoteClient.ts
index 69e50a0710..2759a39a19 100644
--- a/apps/desktop/src/main/provider-group/remoteClient.ts
+++ b/apps/desktop/src/main/provider-group/remoteClient.ts
@@ -38,6 +38,7 @@ export interface ProviderGroupRemoteClient {
agentKind: 'claude-code' | 'codex' | 'pi';
model: string;
exclude: readonly string[];
+ quotaRebalance?: string;
}): Promise<ProviderGroupRemotePick>;
cool(ownerDeviceId: string, input: {
providerId: string;
@@ -83,7 +84,11 @@ export function createProviderGroupRemoteClient(invoke: ProviderGroupRemoteInvok
agentKind: input.agentKind,
model: input.model,
exclude: [...input.exclude],
+ ...(input.quotaRebalance ? { quotaRebalance: input.quotaRebalance } : {}),
});
+ // 旧组所在电脑可能忽略这个可选约束:只有明确执行并回显的结果才用于主动换号。
+ if (input.quotaRebalance && (!raw || typeof raw !== 'object'
+ || (raw as { quotaRebalance?: unknown }).quotaRebalance !== true)) return { kind: 'none' };
return parseProviderGroupRemotePick(raw, input.providerId);
} catch (error) {
if (error instanceof ProviderGroupRemoteUnsupportedError) return { kind: 'none' };
diff --git a/apps/desktop/src/main/provider-group/remoteHandler.ts b/apps/desktop/src/main/provider-group/remoteHandler.ts
index a412405f14..7f19dea1eb 100644
--- a/apps/desktop/src/main/provider-group/remoteHandler.ts
+++ b/apps/desktop/src/main/provider-group/remoteHandler.ts
@@ -47,7 +47,7 @@ export interface ProviderGroupRemoteHandlerDeps {
/** 手机、远程控制发下一条消息前:这台电脑上的任务要不要提议换号(provider-groups.md §6.2「任务进行中换号」)。 */
rebalanceSuggestion?(sessionId: string): Promise<ProviderGroupRebalanceSuggestion>;
/** 记下用户确认的换号。 */
- rebalanceDecision?(sessionId: string, memberKey: string, remember: boolean): Promise<boolean>;
+ rebalanceDecision?(sessionId: string, memberKey: string, remember: boolean, clientId?: string): Promise<boolean>;
}
/** 每个账号、每台报告来的电脑最近收下的用量报告序号(乱序到达的旧份丢弃)。按账号的负载对象区分账号。 */
@@ -130,7 +130,7 @@ export async function handleProviderGroupRemote(
if (request.action === 'rebalance-decision') {
return {
ok: deps.rebalanceDecision
- ? await deps.rebalanceDecision(request.sessionId, request.memberKey, request.remember)
+ ? await deps.rebalanceDecision(request.sessionId, request.memberKey, request.remember, request.clientId)
: false,
};
}
@@ -144,6 +144,7 @@ export async function handleProviderGroupRemote(
agentKind: request.agentKind,
model: request.model,
exclude: new Set(request.exclude),
+ ...(request.quotaRebalance ? { quotaRebalance: request.quotaRebalance } : {}),
// 带着这一轮试过的来问:那台电脑试过不行,本机现读最新状态再选(状态以本机为准,2026-10-11)。
...(request.exclude.length > 0 ? { fresh: true } : {}),
// 选中的同一步记上临时占用:同时来的几个请求不会读到同一份负载、全落到同一台。
@@ -153,7 +154,8 @@ export async function handleProviderGroupRemote(
if (!scope.isCurrent() || pick.kind === 'none') return { kind: 'none' };
if (pick.kind === 'unavailable') return { kind: 'unavailable', ...(pick.usageLimit ? { usageLimit: pick.usageLimit } : {}) };
const { key, kind, agentDeviceId, providerId: memberProviderId } = pick.member;
- return { kind: 'member', member: { key, kind, agentDeviceId, providerId: memberProviderId }, label: pick.label };
+ return { kind: 'member', member: { key, kind, agentDeviceId, providerId: memberProviderId }, label: pick.label,
+ ...(request.quotaRebalance ? { quotaRebalance: true as const } : {}) };
}
case 'cool':
case 'cool-model': {
diff --git a/apps/desktop/src/main/provider-group/router.ts b/apps/desktop/src/main/provider-group/router.ts
index 666f1e2303..d3bcae3159 100644
--- a/apps/desktop/src/main/provider-group/router.ts
+++ b/apps/desktop/src/main/provider-group/router.ts
@@ -26,7 +26,7 @@ import type { ProviderGroupBinding } from './bindings.js';
import type { ProviderGroupDirectory, ResolvedProviderGroupMember } from './directory.js';
import { pickProviderGroupMember, type SchedulableMember } from './scheduler.js';
import { createGuestSupportReader } from './sharedStatus.js';
-import { providerGroupMemberUsageState } from './usage.js';
+import { providerGroupMemberUsageState, providerGroupRebalanceTarget } from './usage.js';
import { coolingScope, currentCooling, PROVIDER_GROUP_COOLING_SCOPE_CAP, type ProviderGroupPersistedCooling } from './cooling.js';
export { PROVIDER_GROUP_FAILURE_COOLDOWN_MS, type ProviderGroupPersistedCooling } from './cooling.js';
@@ -77,6 +77,8 @@ export interface ProviderGroupPickInput {
exclude?: ReadonlySet<string>;
/** 现读组内电脑的最新状态,不用短时缓存(试过不行、带着这一轮试过的来选时)。 */
fresh?: boolean;
+ /** 用户确认的配额均衡,值为当前成员键;同一步重验目标未满载、配额可信、短窗口不紧张及换号收益。 */
+ quotaRebalance?: string;
/**
* 选中后在同一步(读负载与选电脑之间没有等待)调用,用来立即记上占用:同时来的几个请求各自读到前一个的
* 占用,不会全落到同一台。
@@ -251,7 +253,8 @@ export function createProviderGroupRouter(deps: ProviderGroupRouterDeps): Provid
const quota = providerGroupMemberUsageState(r, input.model, now, input.agentKind);
return {
key: r.member.key,
- usable: usable(r),
+ usable: usable(r) && (!input.quotaRebalance
+ || (memberRunning(input.providerId, r) < r.member.limit && !!quota.quota && !quota.fiveHourTight)),
paused: paused(r),
running: memberRunning(input.providerId, r),
limit: r.member.limit,
@@ -284,6 +287,15 @@ export function createProviderGroupRouter(deps: ProviderGroupRouterDeps): Provid
...(limited.length > 0 ? { usageLimit: { resetAtMs: resets.length > 0 ? Math.min(...resets) : null } } : {}),
};
}
+ if (input.quotaRebalance) {
+ const current = resolved.find((r) => r.member.key === input.quotaRebalance);
+ const chosen = resolved.find((r) => r.member.key === key)!;
+ const currentQuota = current && providerGroupMemberUsageState(current, input.model, now, input.agentKind).quota;
+ const targetQuota = providerGroupMemberUsageState(chosen, input.model, now, input.agentKind).quota;
+ if (!currentQuota || !targetQuota || providerGroupRebalanceTarget(currentQuota, [{ key, quota: targetQuota }], now) !== key) {
+ return { kind: 'unavailable', resolved };
+ }
+ }
lastPicked.set(input.providerId, key);
if (input.reserveFor) {
provisional.set(input.reserveFor, {
diff --git a/apps/desktop/src/main/provider-group/runtime.ts b/apps/desktop/src/main/provider-group/runtime.ts
index c89e071f0a..011ec34a04 100644
--- a/apps/desktop/src/main/provider-group/runtime.ts
+++ b/apps/desktop/src/main/provider-group/runtime.ts
@@ -265,7 +265,7 @@ 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>;
+ decide(sessionId: string, memberKey: string, remember: boolean, clientId?: string): Promise<boolean>;
}
let sessionRebalance: ProviderGroupSessionRebalance | null = null;
@@ -285,10 +285,10 @@ export async function readProviderGroupRebalanceSuggestion(sessionId: string): P
}
/** 记下用户确认换号;没记上返回 false,这条消息照常发到原来的号。 */
-export async function recordProviderGroupRebalanceDecision(sessionId: string, memberKey: string, remember: boolean): Promise<boolean> {
+export async function recordProviderGroupRebalanceDecision(sessionId: string, memberKey: string, remember: boolean, clientId?: string): Promise<boolean> {
if (!sessionRebalance) return false;
try {
- return await sessionRebalance.decide(sessionId, memberKey, remember);
+ return await sessionRebalance.decide(sessionId, memberKey, remember, clientId);
} catch {
return false;
}
diff --git a/apps/desktop/src/main/provider-group/service.ts b/apps/desktop/src/main/provider-group/service.ts
index b025c7bdec..5eb1c02632 100644
--- a/apps/desktop/src/main/provider-group/service.ts
+++ b/apps/desktop/src/main/provider-group/service.ts
@@ -128,6 +128,7 @@ export interface ProviderGroupRemoteGroups {
agentKind: 'claude-code' | 'codex' | 'pi';
model: string;
exclude: readonly string[];
+ quotaRebalance?: string;
}): Promise<ProviderGroupRemotePick>;
cool(ownerDeviceId: string, input: {
providerId: string;
@@ -298,10 +299,12 @@ export interface ProviderGroupService {
* 用户确认换号:这个任务接下来的一次发送(PROVIDER_GROUP_REBALANCE_ACCEPT_TTL_MS 内)先换到 `memberKey` 再发;
* `remember` = 以后自动换。`memberKey` 不在组里返回 false。
*/
- rebalanceDecision(sessionId: string, memberKey: string, remember: boolean): Promise<boolean>;
+ rebalanceDecision(sessionId: string, memberKey: string, remember: boolean, clientId?: string): Promise<boolean>;
}
export interface ProviderGroupBeforeSendOptions {
+ /** 用户确认换号的具体消息;复用发送协议已有的幂等 ID。 */
+ clientId?: string;
/** 这次发送被停止或取消:等原电脑恢复时就此停下,不再换电脑。 */
signal?: AbortSignal;
/** 定时任务的发送:不使用用户为下一条消息确认的换号。 */
@@ -407,6 +410,7 @@ interface GroupSource {
agentKind: AgentKind;
model: string;
exclude: ReadonlySet<string>;
+ quotaRebalance?: string;
}): Promise<SourcePick>;
/** 记进组的状态(只在判定说要记时调用:那台账号的问题)。 */
cool(providerId: string, memberKey: string, cause: ProviderGroupFailureCause, resetAt: number | null, model: string): void;
@@ -488,7 +492,15 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
*/
const preSendFailed = new Map<string, { keys: string[]; at: number }>();
/** 用户为这个任务接下来的一次发送确认的换号(provider-groups.md §6.2「任务进行中换号」)。 */
- const acceptedRebalance = new Map<string, { memberKey: string; at: number }>();
+ const acceptedRebalance = new Map<string, Map<string, { memberKey: string; at: number }>>();
+ function pruneAcceptedRebalance(): void {
+ for (const [sessionId, messages] of acceptedRebalance) {
+ for (const [clientId, decision] of messages) {
+ if (deps.now() - decision.at > PROVIDER_GROUP_REBALANCE_ACCEPT_TTL_MS) messages.delete(clientId);
+ }
+ if (!messages.size) acceptedRebalance.delete(sessionId);
+ }
+ }
/** 换号没换成的组内电脑(按组区分) → 到这个时刻之前不再提议。 */
const rebalanceBackoff = new Map<string, number>();
const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
@@ -713,7 +725,7 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
async readGroup(providerId) {
return deps.readGroup(providerId);
},
- async pick({ sessionId, providerId, agentKind, model, exclude }) {
+ async pick({ sessionId, providerId, agentKind, model, exclude, quotaRebalance }) {
// 带着这一轮试过的来选:试过不行说明状态可能旧了,现读最新状态再选。选中的同一步记上临时占用:本机同时
// 开的几个任务不会读到同一份负载、全落到同一台(与同账号电脑、分享的人问组所在电脑同一做法)。
const pick = await router.pick({
@@ -724,6 +736,7 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
localTask: true,
exclude,
reserveFor: sessionId,
+ ...(quotaRebalance ? { quotaRebalance } : {}),
...(exclude.size > 0 ? { fresh: true } : {}),
});
if (pick.kind !== 'member') return pick;
@@ -793,13 +806,14 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
const source: GroupSource = {
ownerDeviceId,
readGroup: (providerId) => remote.readGroup(ownerDeviceId, providerId),
- async pick({ sessionId, providerId, config, agentKind, model, exclude }) {
+ async pick({ sessionId, providerId, config, agentKind, model, exclude, quotaRebalance }) {
const pick = await remote.pick(ownerDeviceId, {
sessionId,
providerId,
agentKind: agentKind as 'claude-code' | 'codex' | 'pi',
model,
exclude: [...exclude],
+ ...(quotaRebalance ? { quotaRebalance } : {}),
});
if (pick.kind !== 'member') return pick;
const labelOf = (key: string) => {
@@ -1032,6 +1046,7 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
agentKind: row.agentKind,
model: row.model,
exclude: new Set(config.members.map((m) => m.key).filter((key) => key !== target)),
+ quotaRebalance: current.key,
});
if (!isCurrent()) return false;
if (pick.kind !== 'member' || pick.member.key !== target) {
@@ -1840,10 +1855,12 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
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;
+ pruneAcceptedRebalance();
+ if (!options?.scheduled && options?.clientId) {
+ const messages = acceptedRebalance.get(sessionId);
+ accepted = messages?.get(options.clientId);
+ messages?.delete(options.clientId);
+ if (!messages?.size) acceptedRebalance.delete(sessionId);
}
if (!deps.readBinding(sessionId) || deps.isTurnRunning(sessionId)) return;
// 读组设置也算进发送前检查的上限:组所在电脑断线或不响应时保留绑定、照常发送,不等默认的请求超时。
@@ -1987,10 +2004,14 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Prov
return { kind: deps.readAutoRebalance?.(sessionId) ? 'auto' : 'ask', ...target };
},
- async rebalanceDecision(sessionId, memberKey, remember) {
+ async rebalanceDecision(sessionId, memberKey, remember, clientId) {
+ if (!clientId || !/^[A-Za-z0-9_-]{1,128}$/.test(clientId)) return false;
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() });
+ pruneAcceptedRebalance();
+ const messages = acceptedRebalance.get(sessionId) ?? new Map();
+ messages.set(clientId, { memberKey, at: deps.now() });
+ acceptedRebalance.set(sessionId, messages);
if (remember) {
try {
await deps.writeAutoRebalance?.(sessionId);
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index d2bff3d160..5f553f85e2 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -4168,8 +4168,9 @@ function CCAgentSessionContent({
// 上一轮已经结束、用户发下一条消息:供应商组里另一个账号的配额明显更该先用时,问用户要不要换过去
// (provider-groups.md §6.2「任务进行中换号」)。只记下用户的选择,这条消息无论换不换都照常发出。
+ let recordRebalance: ((clientId: string) => Promise<void>) | undefined;
if (deliveryMode !== 'steer' && sessionId && !isRunningRef.current) {
- await offerSessionRebalance({
+ recordRebalance = await offerSessionRebalance({
sessionId,
...(remoteDeviceId ? { hostDeviceId: remoteDeviceId } : {}),
confirmWithCheckbox,
@@ -4178,9 +4179,17 @@ function CCAgentSessionContent({
}
// ④ Execute send — effort + permissionMode came straight from ChatInput (fresh value)
+ let rebalanceClientId: string | undefined;
const sendOptions = {
- beforeEnqueue: opts?.beforeEnqueue,
- onInputCreated: opts?.onInputCreated,
+ beforeEnqueue: recordRebalance ? async () => {
+ if (await opts?.beforeEnqueue?.() === false) return false;
+ if (rebalanceClientId) await recordRebalance(rebalanceClientId);
+ return true;
+ } : opts?.beforeEnqueue,
+ onInputCreated: recordRebalance ? (clientId: string) => {
+ rebalanceClientId = clientId;
+ opts?.onInputCreated?.(clientId);
+ } : opts?.onInputCreated,
...orcaLeadVendorOptions,
...(opts?.quotesEncoded ? { quotesEncoded: true } : {}),
...(opts?.agentReferences?.length ? { agentReferences: opts.agentReferences } : {}),
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
index acffcc8881..f949ad7d3c 100644
--- a/apps/desktop/src/renderer/features/provider-group/__tests__/sessionRebalancePrompt.test.ts
+++ b/apps/desktop/src/renderer/features/provider-group/__tests__/sessionRebalancePrompt.test.ts
@@ -43,7 +43,10 @@ describe('offerSessionRebalance', () => {
] 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 });
+ const record = await offerSessionRebalance({ sessionId: 's1', confirmWithCheckbox: h.confirmWithCheckbox, t });
+ expect(h.decisions()).toEqual([]);
+ if (remember === null) expect(record).toBeUndefined();
+ else { expect(record).toBeTypeOf('function'); await record!('message-a'); }
expect(h.confirmWithCheckbox).toHaveBeenCalledTimes(kind === 'ask' ? 1 : 0);
if (kind === 'ask') {
@@ -54,7 +57,7 @@ describe('offerSessionRebalance', () => {
}
expect(h.decisions()).toEqual(remember === null
? []
- : [{ action: 'rebalance-decision', sessionId: 's1', memberKey: MINI, remember }]);
+ : [{ action: 'rebalance-decision', sessionId: 's1', memberKey: MINI, remember, clientId: 'message-a' }]);
// 一次提议只管一条消息:下一条等任务再空闲、重新问过才可能再问。
await offerSessionRebalance({ sessionId: 's1', confirmWithCheckbox: h.confirmWithCheckbox, t });
expect(h.confirmWithCheckbox).toHaveBeenCalledTimes(kind === 'ask' ? 1 : 0);
diff --git a/apps/desktop/src/renderer/features/provider-group/sessionRebalancePrompt.ts b/apps/desktop/src/renderer/features/provider-group/sessionRebalancePrompt.ts
index 5e0c9ab5aa..becb76ba05 100644
--- a/apps/desktop/src/renderer/features/provider-group/sessionRebalancePrompt.ts
+++ b/apps/desktop/src/renderer/features/provider-group/sessionRebalancePrompt.ts
@@ -111,9 +111,10 @@ async function recordDecision(
memberKey: string,
remember: boolean,
hostDeviceId: string | undefined,
+ clientId: string,
): Promise<boolean> {
try {
- const raw = await command(hostDeviceId, { action: 'rebalance-decision', sessionId, memberKey, remember });
+ const raw = await command(hostDeviceId, { action: 'rebalance-decision', sessionId, memberKey, remember, clientId });
return !!raw && typeof raw === 'object' && (raw as { ok?: unknown }).ok === true;
} catch {
return false;
@@ -137,7 +138,7 @@ export function describeSessionRebalance(
}
/**
- * 发送前调用:有问好的提议就按用户的选择记下(任务所在电脑在这条消息发出前换过去);没有提议时立即返回,不等网络。
+ * 发送前询问;返回的闭包在消息创建后绑定 clientId 记录确认。没有提议时立即返回,不等网络。
* 不拦发送——调用方之后照常发出这条消息。
*/
export async function offerSessionRebalance(options: {
@@ -145,13 +146,12 @@ export async function offerSessionRebalance(options: {
hostDeviceId?: string;
confirmWithCheckbox: ConfirmWithCheckbox;
t: TFunction;
-}): Promise<void> {
+}): Promise<((clientId: string) => Promise<void>) | undefined> {
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;
+ return async (clientId) => { await recordDecision(sessionId, suggestion.memberKey, false, hostDeviceId, clientId); };
}
const { ok, checked } = await confirmWithCheckbox({
title: t('providerGroup.rebalance.title', { label: suggestion.label }),
@@ -162,5 +162,5 @@ export async function offerSessionRebalance(options: {
autoFocusConfirm: true,
});
if (!ok) return;
- await recordDecision(sessionId, suggestion.memberKey, checked, hostDeviceId);
+ return async (clientId) => { await recordDecision(sessionId, suggestion.memberKey, checked, hostDeviceId, clientId); };
}
diff --git a/apps/desktop/src/shared/__tests__/providerGroup.test.ts b/apps/desktop/src/shared/__tests__/providerGroup.test.ts
index 8455f1c513..220b9cb1da 100644
--- a/apps/desktop/src/shared/__tests__/providerGroup.test.ts
+++ b/apps/desktop/src/shared/__tests__/providerGroup.test.ts
@@ -94,6 +94,10 @@ describe('switching accounts between messages', () => {
});
it('only turns a well-formed reply into a suggestion', () => {
+ // 电脑名和账号名分别合法,组合名称不能让整条提议消失(review #6693)。
+ const label = `${'D'.repeat(128)} · ${'A'.repeat(128)}`;
+ expect(parseProviderGroupRebalanceSuggestion({ kind: 'ask', memberKey: 'local', label, quota })?.label).toBe(label);
+ expect(parseProviderGroupRebalanceSuggestion({ kind: 'ask', memberKey: 'local', label: `${label}X`, quota })).toBeNull();
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 },
diff --git a/apps/desktop/src/shared/providerGroup.ts b/apps/desktop/src/shared/providerGroup.ts
index 4e231e7e2d..0a8cdec591 100644
--- a/apps/desktop/src/shared/providerGroup.ts
+++ b/apps/desktop/src/shared/providerGroup.ts
@@ -160,6 +160,8 @@ export type ProviderGroupRebalanceSuggestion =
| null;
const REBALANCE_MEMBER_KEY_PATTERN = /^[A-Za-z0-9_.:-]{1,300}$/;
+/** 电脑名与账号名各最多 128 个 UTF-16 单元,组合时另加分隔符。 */
+export const PROVIDER_GROUP_REBALANCE_LABEL_MAX_LENGTH = 128 * 2 + 3;
/** 客户端读任务所在电脑回的提议;旧端不认识这个动作、格式不对都按没有提议处理(照常发送)。 */
export function parseProviderGroupRebalanceSuggestion(raw: unknown): ProviderGroupRebalanceSuggestion {
@@ -167,7 +169,7 @@ export function parseProviderGroupRebalanceSuggestion(raw: unknown): ProviderGro
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 label = normalizeLabel(value.label, PROVIDER_GROUP_REBALANCE_LABEL_MAX_LENGTH);
const quota = readProviderGroupMemberQuota(value.quota);
return label && quota ? { kind: value.kind, memberKey: value.memberKey, label, quota } : null;
}
@@ -243,7 +245,7 @@ export type ProviderGroupLocalCommand =
/** 用户发下一条消息前:要不要提议换号(provider-groups.md §6.2「任务进行中换号」)。 */
| { action: 'rebalance-suggestion'; sessionId: string }
/** 用户确认换号:这个任务的下一条消息先换到 `memberKey`;`remember` = 这个任务以后自动换。 */
- | { action: 'rebalance-decision'; sessionId: string; memberKey: string; remember: boolean };
+ | { action: 'rebalance-decision'; sessionId: string; memberKey: string; remember: boolean; clientId?: string };
export type ProviderGroupCommand = ProviderGroupLocalCommand
| { action: 'remote-manage'; deviceId: string; request: ProviderManagementRequest };
@@ -299,11 +301,11 @@ function clampInt(value: unknown, min: number, max: number, fallback: number): n
return Math.min(max, Math.max(min, Math.round(value)));
}
-function normalizeLabel(value: unknown): string | undefined {
+function normalizeLabel(value: unknown, maxLength = 128): string | undefined {
if (typeof value !== 'string') return undefined;
const trimmed = value.trim();
// eslint-disable-next-line no-control-regex -- 控制字符是显式拒绝目标
- if (!trimmed || trimmed.length > 128 || /[\u0000-\u001f\u007f]/.test(trimmed)) return undefined;
+ if (!trimmed || trimmed.length > maxLength || /[\u0000-\u001f\u007f]/.test(trimmed)) return undefined;
return trimmed;
}
@@ -464,7 +466,7 @@ export interface ProviderGroupUsagePartAck {
export type ProviderGroupRemoteRequest =
/** 新任务该用组里哪台;选中即给那台记一个短暂的占用,同时开的几个任务不会全落到同一台。 */
- | { action: 'pick'; sessionId: string; providerId: string; agentKind: 'claude-code' | 'codex' | 'pi'; model: string; exclude: string[] }
+ | { action: 'pick'; sessionId: string; providerId: string; agentKind: 'claude-code' | 'codex' | 'pi'; model: string; exclude: string[]; quotaRebalance?: string }
/** 那台电脑出了问题(用量上限、登录失效、服务繁忙):组所在电脑冷却它,不再分新任务。 */
| { action: 'cool' | 'cool-model'; providerId: string; memberKey: string; cause: ProviderGroupRemoteCoolCause; resetAt?: number; model?: string }
/** 这台电脑经组运行、正在跑的任务(整体替换上一份;seq 只增,乱序到达的旧份丢弃)。 */
@@ -485,7 +487,7 @@ export type ProviderGroupRemoteRequest =
| { action: 'session-group'; sessionId: string }
/** 发给任务所在的电脑(手机、远程控制):同本机命令的 `rebalance-suggestion` / `rebalance-decision`。 */
| { action: 'rebalance-suggestion'; sessionId: string }
- | { action: 'rebalance-decision'; sessionId: string; memberKey: string; remember: boolean };
+ | { action: 'rebalance-decision'; sessionId: string; memberKey: string; remember: boolean; clientId?: string };
/** `session-group` 的回包:坐标是任务所在电脑视角(`groupDeviceId` 为 null = 那台自己建的组)。 */
export interface ProviderGroupRemoteSessionGroup {
@@ -576,6 +578,7 @@ export function parseProviderGroupRemoteRequest(raw: unknown): ProviderGroupRemo
agentKind: agentKind as 'claude-code' | 'codex' | 'pi',
model: value.model,
exclude: exclude.map(remoteMemberKey),
+ ...(value.quotaRebalance !== undefined ? { quotaRebalance: remoteMemberKey(value.quotaRebalance) } : {}),
};
}
case 'cool':
@@ -652,6 +655,7 @@ export function parseProviderGroupRemoteRequest(raw: unknown): ProviderGroupRemo
sessionId: remoteSessionId(value.sessionId),
memberKey: remoteMemberKey(value.memberKey),
remember: value.remember as boolean,
+ ...(value.clientId !== undefined ? { clientId: remoteSessionId(value.clientId) } : {}),
};
default:
invalidRemote('unknown provider group action');
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index d1f2231061..c8726ca53e 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -6557,6 +6557,7 @@ function SessionScreenContent() {
return;
}
const useDurableOutbox = outboxEligible && !earlyLocalCommand && !earlyDesktopCommand && !legacyPlanRequiresLiveDispatch;
+ const outboxClientId = useDurableOutbox ? createOutboxClientId() : undefined;
const planModeAtSend = runtimeOptions?.planModeSupported === true
? (readSessionRowNow() ?? currentSession).planModeEnabled === true
: undefined;
@@ -6571,7 +6572,7 @@ function SessionScreenContent() {
&& !currentTurnStreaming
&& !isRemoteSessionMissing(readSessionRowNow())
) {
- await offerMobileSessionRebalance({ invoke, hostDeviceId: deviceId, sessionId, ask: askMobileSessionRebalance });
+ await offerMobileSessionRebalance({ invoke, hostDeviceId: deviceId, sessionId, clientId: outboxClientId!, ask: askMobileSessionRebalance });
// 弹窗期间离开了这个任务:草稿还没清空,留在原处,不发。
if (outboxSessionAliveRef.current !== sessionId) return;
}
@@ -6696,7 +6697,7 @@ function SessionScreenContent() {
const readyPreviews = readyAttachments.map((attachment) => attachmentPreviews[attachment.id] ?? null);
const permissionModeAtSend = permissionModeOrAsk(currentSession.permissionMode);
const item = buildOutboxItem({
- clientId: createOutboxClientId(), sessionId, text, quotesEncoded: quotesEncodedAtSend,
+ clientId: outboxClientId!, sessionId, text, quotesEncoded: quotesEncodedAtSend,
sessionRefs: sessionRefsAtSend, agentReferences: agentReferencesAtSend,
pastedTextRanges: pastedTextRangesAtSend, slashCommandRanges: slashCommandRangesAtSend ?? [],
permissionModeAtSend, planModeAtSend, readyAttachments, readyPreviews,
diff --git a/apps/mobile/src/__tests__/mobileGoalCommands.test.ts b/apps/mobile/src/__tests__/mobileGoalCommands.test.ts
index a2e1ecefc0..863a49ad32 100644
--- a/apps/mobile/src/__tests__/mobileGoalCommands.test.ts
+++ b/apps/mobile/src/__tests__/mobileGoalCommands.test.ts
@@ -92,6 +92,8 @@ function existingHarness(args = 'target') {
sendInFlightRef: { current: false }, sending: false, setSending: vi.fn((_sending: boolean) => {}), currentSession: session,
invalidateHistoryRecoveryNavigation: vi.fn(),
outboxConnectionBlockedNow: () => false, getPendingUploadCount: () => 0,
+ outboxRef: { current: [] }, remoteSessionRunning: false, currentTurnStreaming: false,
+ offerMobileSessionRebalance: vi.fn(async () => {}), askMobileSessionRebalance: vi.fn(), invoke: vi.fn(),
parseMobileLocalSystemCommand: () => null, parseMobileDesktopCommand, pendingSkillSelectionRef: { current: null },
resolveSessionAgentKind: () => 'pi', modelNeedsReselection: () => false, getCachedDeviceProviders: () => undefined,
commandNeedsRemoteSession: () => false, extractMobileSessionReferences: () => [], outboxDispatchBlockedNow: () => false,
diff --git a/apps/mobile/src/__tests__/sessionRebalancePrompt.test.ts b/apps/mobile/src/__tests__/sessionRebalancePrompt.test.ts
index 8c489ab01d..818f023e80 100644
--- a/apps/mobile/src/__tests__/sessionRebalancePrompt.test.ts
+++ b/apps/mobile/src/__tests__/sessionRebalancePrompt.test.ts
@@ -47,7 +47,7 @@ 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 });
+ await offerMobileSessionRebalance({ invoke, hostDeviceId: 'pc', sessionId, clientId: 'message-a', ask: askMobileSessionRebalance });
}
beforeEach(() => {
@@ -69,9 +69,10 @@ describe('offerMobileSessionRebalance', () => {
expect(alert).toHaveBeenCalledTimes(1);
expect(alert.mock.calls[0][0]).toContain('Mini');
expect(alert.mock.calls[0][2]).toHaveLength(3);
+ expect(alert.mock.calls[0][3]).toEqual({ cancelable: false });
expect(decisions(invoke)).toEqual(remember === null
? []
- : [{ action: 'rebalance-decision', sessionId: 's1', memberKey: MINI, remember }]);
+ : [{ action: 'rebalance-decision', sessionId: 's1', clientId: 'message-a', memberKey: MINI, remember }]);
// 一次提议只管一条消息。
await offer(invoke);
expect(alert).toHaveBeenCalledTimes(1);
@@ -82,7 +83,18 @@ describe('offerMobileSessionRebalance', () => {
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 }]);
+ expect(decisions(invoke)).toEqual([{ action: 'rebalance-decision', sessionId: 's1', clientId: 'message-a', memberKey: MINI, remember: false }]);
+ });
+
+ // Unit/protocol: combining two valid names used to silently discard the complete suggestion.
+ it('offers a combined computer and account name at the protocol limit', async () => {
+ const label = `${'D'.repeat(128)} · ${'A'.repeat(128)}`;
+ const invoke = invoker({ ...reply('ask'), label });
+ press('confirm');
+ await prefetchMobileSessionRebalance(invoke, 'pc', 'long-name');
+ await offer(invoke, 'long-name');
+ expect(alert.mock.calls[0][0]).toContain(label);
+ expect(decisions(invoke)).toHaveLength(1);
});
it.each([
diff --git a/apps/mobile/src/session/sessionRebalancePrompt.ts b/apps/mobile/src/session/sessionRebalancePrompt.ts
index 45cb868917..ff8af10bfb 100644
--- a/apps/mobile/src/session/sessionRebalancePrompt.ts
+++ b/apps/mobile/src/session/sessionRebalancePrompt.ts
@@ -29,6 +29,7 @@ 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;
+const MAX_REBALANCE_LABEL_LENGTH = 128 * 2 + 3;
export interface MobileRebalanceSuggestion {
kind: 'ask' | 'auto';
@@ -56,7 +57,7 @@ export function parseMobileRebalanceSuggestion(raw: unknown): MobileRebalanceSug
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;
+ if (!label || label.length > MAX_REBALANCE_LABEL_LENGTH || 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;
@@ -82,7 +83,7 @@ export function describeMobileRebalance(suggestion: MobileRebalanceSuggestion, n
return i18n.t('session.providerGroupRebalance.body', { label: suggestion.label, quota });
}
-/** 系统弹窗问用户;点外面关掉(Android)按取消处理。 */
+/** 系统弹窗问用户;通过明确的取消按钮关闭,禁止点遮罩关闭。 */
export function askMobileSessionRebalance(suggestion: MobileRebalanceSuggestion): Promise<MobileRebalanceChoice> {
return new Promise((resolve) => {
Alert.alert(
@@ -93,7 +94,7 @@ export function askMobileSessionRebalance(suggestion: MobileRebalanceSuggestion)
{ text: i18n.t('session.providerGroupRebalance.remember'), onPress: () => resolve('remember') },
{ text: i18n.t('session.providerGroupRebalance.confirm'), onPress: () => resolve('switch') },
],
- { cancelable: true, onDismiss: () => resolve('cancel') },
+ { cancelable: false },
);
});
}
@@ -167,6 +168,7 @@ export async function offerMobileSessionRebalance(input: {
invoke: Invoke;
hostDeviceId: string;
sessionId: string;
+ clientId: string;
ask(suggestion: MobileRebalanceSuggestion): Promise<MobileRebalanceChoice>;
}): Promise<void> {
const { invoke, hostDeviceId, sessionId } = input;
@@ -178,6 +180,7 @@ export async function offerMobileSessionRebalance(input: {
await invoke(hostDeviceId, PROVIDER_GROUP_REMOTE_CHANNEL, [{
action: 'rebalance-decision',
sessionId,
+ clientId: input.clientId,
memberKey: suggestion.memberKey,
remember: choice === 'remember',
}]);
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index b8306b11af..df378b9ab8 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -1691,9 +1691,11 @@ B 上的 Worker 是一条普通任务,`sessions.orca_remote_lead`(migration 01
- `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]`。客户端读回包用
+ 组合名称最多 259 个 UTF-16 单元(电脑名 128 + 分隔符 3 + 账号名 128),电脑与手机按相同上限解析。
+ - `rebalance-decision { sessionId, memberKey, remember, clientId? }` → `{ ok: boolean }`:只允许这个任务中匹配 `clientId` 的消息
+ 发送前换到 `memberKey`(2 分钟内有效,定时任务不消费);复用 `persistUserMessage.clientId`,不增加发送协议字段。
+ 缺少消息 ID 或 `memberKey` 不在组里回 `ok: false`,不记决定与偏好;`remember: true` 时另记这个任务以后自动换。
+ - 解析:`sessionId`、`clientId` 与 `memberKey` 按已有远程 id 规则校验,`remember` 必须是布尔值,坏请求回 `[INVALID_PARAMS]`。客户端读回包用
`parseProviderGroupRebalanceSuggestion`(手机端 `parseMobileRebalanceSuggestion`,口径相同),格式不对按不提议处理。
- **时机**:客户端在任务空闲时预先问 `rebalance-suggestion`(变空闲、打开任务时,空闲期间每 5 分钟;单次最多等 5 秒),
结果 10 分钟内有效、只用于一条消息;点发送时只用问好的结果,不为它多等一次往返。只有用户确认换号(或任务选过自动换)时,
@@ -1701,6 +1703,9 @@ B 上的 Worker 是一条普通任务,`sessions.orca_remote_lead`(migration 01
- **新旧兼容**:旧任务所在电脑不认识这两个动作,回 `[INVALID_PARAMS] unknown provider group action`;客户端失败或超时都按
不提议处理、照常发送,与改动前一致。旧客户端不发这两个动作,任务所在电脑不会自己换号(没有用户确认就不换),行为与改动前
一致。不新增 channel、relay、服务器或数据库字段。
+- **最终选路约束**:`pick` 可选 `quotaRebalance: <当前成员键>`;组所在电脑在选路与占用登记的同一步,按当前负载、配额和换号
+ 收益门槛重新校验。成功结果回显 `quotaRebalance: true`;新调用端未收到回显就不主动迁移。旧组忽略可选字段时仍可普通
+ 分配,但不能作为主动换号结果;旧调用端不传该字段,行为不变。
- **分隔条内容可选 `switchReason: 'quota-rebalance'`**:`agent_switch` 边界行(`AgentSwitchBoundaryContent`)只在供应商组为此换了
电脑时带上,桌面与手机在位置后写「· 这个账号的配额更该先用」。旧端忽略,照常只显示位置。
- **本机持久数据**:「以后自动换」存在按账号隔离的 `provider-group-session-prefs.json`(`{ autoRebalance: { [sessionId]: at } }`,
diff --git a/docs/product-rules/provider-groups.md b/docs/product-rules/provider-groups.md
index 8aa72ea337..3002ac2389 100644
--- a/docs/product-rules/provider-groups.md
+++ b/docs/product-rules/provider-groups.md
@@ -459,7 +459,9 @@
换一台电脑或在手机上看这个任务也一样;任务删除后记录不再有用,超过 4000 条时丢掉最早的。
- 取消(含关闭弹窗):不换,这条消息照常发到原来的账号;下一条消息仍会再问。
- 无论选什么,这条消息都照常发出。
-- **换不过去**:用户确认后 2 分钟内没发出去的(停止、断线)不留到以后;那台此刻接不了或交接失败时照常发到原来的账号、
+- **确认的归属**:换号确认绑定具体这条消息;离开任务而未发送,或另一台控制端随后发消息,都不能把这次确认用到另一条消息上。
+- **换不过去**:用户确认后 2 分钟内没发出去的(停止、断线)不留到以后;实际选路时重新检查目标负载、配额和换号收益门槛。
+ 那台此刻接不了、不再值得换或交接失败时照常发到原来的账号、
不报错,那台 30 分钟内不再提议。这次换号不算 §6.1 的「这一轮试过」,之后原电脑出问题照常可以换回来。
- 用户确认的换号不受「出问题时自动换电脑」开关影响(开关管的是出问题时不问就换)。
- **实现**:判断与执行在任务所在电脑的 `apps/desktop/src/main/provider-group/service.ts`(`rebalanceSuggestion`、
@@ -774,8 +776,8 @@
2. 组所在电脑自己的任务、同账号其他电脑与分享的人的任务,初次分配与故障重选都按同一个组策略选电脑;本机的
对外暂停只拦外部任务。正常运行的任务留在原电脑。离线、冷却、不提供模型或可信快照显示所需 Claude 订阅额度
已耗尽的电脑不选。按组策略分配时优先未满载的,全部满载时仍选运行任务最少的。
- 所有组策略都先按 §5「配额先比」:先排除配额耗尽的,再按每周 5 小时内、5 小时配额 1 小时内的顺序先用快到期的
- (重置早的先),再留已用百分比相差 5 个百分点以内的,最后由组策略挑;读不到用量时只按组策略,重置后的旧窗口不再阻塞。
+ 所有组策略都先按 §5「配额先比」:先排除配额耗尽的,按规则避开 5 小时配额快满且离重置还早的,再按「剩下的额度 ÷ 剩下的时间」
+ 留下不低于最急那台 90% 的候选,最后由组策略挑;全部读不到用量时只按组策略,重置后的旧窗口不再阻塞。
3. 正常运行的任务固定在原电脑;原电脑因 §6.1 列出的原因失败时,自动交接到组内另一台继续这一轮,消息流显示换电脑的
活动记录;同一轮每台最多试一次,全部失败才报错并逐台列出原因;其中有撞上限的,等最早恢复的一台自动继续。
4. 用户停止、权限被拒、上下文超限、请求无效、内容被拒、工具出错时不换电脑;其余失败都换(含认不出的)。「故障 × 阶段」的判定表