Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(provider-group): 停止时作废进行中的换电脑,发送前交接不再提交新位置 (#5882)
FicoWang3e39a8ac5478
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.tsindex f556c5229e..963d563442 100644--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts@@ -682,7 +682,24 @@ describe('maker:event hot path ordering', () => {expect(resetSource).toContain('silentStopAutoResumeGuard.noteSessionReset(sessionId);');expect(resetSource).toContain('interruptedTurnAutoResumeGuard.noteSessionReset(sessionId);');expect(resetSource).toContain('autoResumeBookkeeping.teardown(sessionId);');- expect(source).toContain('noteSessionReset: resetAutomaticRecoveryForExplicitStop,');+ // 「全部停止」:先撤自动续跑与退避簿记,再作废供应商组进行中的换电脑(#5880,provider-groups.md §6.1)。+ const stopAllStart = source.indexOf(+ 'registerStopSessionBackgroundTasksHandler(createElectronIpcHandlerRegistry(), {',+ );+ const stopAllEnd = source.indexOf('\n });', stopAllStart);+ const stopAllSource = source.slice(stopAllStart, stopAllEnd);+ const stopAllResetStart = stopAllSource.indexOf(' noteSessionReset: (sessionId) => {');+ const stopAllResetSource = stopAllSource.slice(+ stopAllResetStart,+ stopAllSource.indexOf('\n notifyGoalStop:', stopAllResetStart),+ );+ expect(stopAllStart).toBeGreaterThanOrEqual(0);+ expect(stopAllResetStart).toBeGreaterThanOrEqual(0);+ expectOrder(+ stopAllResetSource,+ 'resetAutomaticRecoveryForExplicitStop(sessionId);',+ 'providerGroupService?.noteUserAction(sessionId);',+ );expect(source).toContain('resetAutomaticRecoveryForExplicitStop(sid);');expectOrder(diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 5f3b2afa34..4f7bfe3a06 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -6174,7 +6174,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)closeSession: (sessionId) => maker.closeSession(sessionId),clearBackgroundActivity: clearClaudeSessionBackgroundActivity,// 「全部停止」是会话级止损:已排期的自动续跑必须撤掉,别在用户喊停后又补发一条。- noteSessionReset: resetAutomaticRecoveryForExplicitStop,+ // 它不经过输入协调器的 Stop(错误与重试入口仍在):供应商组进行中的换电脑也要作废,+ // 用户停止不换(provider-groups.md §6.1,#5880)。+ noteSessionReset: (sessionId) => {+ resetAutomaticRecoveryForExplicitStop(sessionId);+ providerGroupService?.noteUserAction(sessionId);+ },notifyGoalStop: pauseGoalBeforeExplicitStop,});diff --git a/apps/desktop/src/main/provider-group/__tests__/failoverSessionClose.test.ts b/apps/desktop/src/main/provider-group/__tests__/failoverSessionClose.test.tsindex b2db3e8c18..0328f53072 100644--- a/apps/desktop/src/main/provider-group/__tests__/failoverSessionClose.test.ts+++ b/apps/desktop/src/main/provider-group/__tests__/failoverSessionClose.test.ts@@ -6,6 +6,7 @@*/import type { SessionStatus } from '@cindy/maker-core';import type { ProviderView } from '@cindy/model-providers';+import { readFileSync } from 'node:fs';import { describe, expect, it, vi } from 'vitest';import { CONTINUE_AFTER_ERROR_PROMPT } from '../../../shared/interruptedTurn';@@ -14,6 +15,8 @@ import type { ProviderGroupConfig, ProviderGroupMember } from '../../../shared/pimport { AgentInputCoordinator, type AgentInputCoordinatorDeps } from '../../maker-ipc/agent-input-coordinator';import { shouldPreserveWaitingContinuationOnlyAutoResume } from '../../maker-ipc/interruptedTurnAutoResume';import { createSessionBindingLifecycle, runSessionCloseCleanup } from '../../maker-ipc/sessionBindingLifecycle';+import type { IpcHandler } from '../../maker-ipc/ipcHandlerRegistry';+import { registerStopSessionBackgroundTasksHandler } from '../../maker-ipc/stopSessionBackgroundTasksHandler';import type { ProviderGroupBinding } from '../bindings';import type { ProviderGroupDirectory, ResolvedMemberState, ResolvedProviderGroupMember } from '../directory';import { createProviderGroupRouter } from '../router';@@ -78,6 +81,37 @@ function item(clientId: string, text: string): AgentInputQueuedMessage {} as AgentInputQueuedMessage;}+/**+ * register.ts 里「全部停止」注册处的 noteSessionReset:逐行(去掉缩进与注释)与这份期望原文完全一致,+ * 下面的「全部停止」用例按同一份原文接线(resetAutomaticRecoveryForExplicitStop 用 spy 代替)。+ */+const REGISTER_SOURCE = readFileSync(new URL('../../maker-ipc/register.ts', import.meta.url), 'utf8').replace(/\r\n/g, '\n');+const STOP_ALL_NOTE_SESSION_RESET = [+ 'noteSessionReset: (sessionId) => {',+ 'resetAutomaticRecoveryForExplicitStop(sessionId);',+ 'providerGroupService?.noteUserAction(sessionId);',+ '},',+];+function stopAllRegistration(): string {+ const start = REGISTER_SOURCE.indexOf('registerStopSessionBackgroundTasksHandler(createElectronIpcHandlerRegistry(), {');+ const end = REGISTER_SOURCE.indexOf('\n });', start);+ expect(start).toBeGreaterThan(0);+ expect(end).toBeGreaterThan(start);+ return REGISTER_SOURCE.slice(start, end);+}+function stopAllNoteSessionResetLines(): string[] {+ const registration = stopAllRegistration();+ const start = registration.indexOf(' noteSessionReset:');+ const end = registration.indexOf('\n notifyGoalStop:', start);+ expect(start).toBeGreaterThan(0);+ expect(end).toBeGreaterThan(start);+ return registration+ .slice(start, end)+ .split('\n')+ .map((line) => line.trim())+ .filter((line) => line !== '' && !line.startsWith('//'));+}+async function flush() {for (let i = 0; i < 200; i++) await Promise.resolve();}@@ -90,7 +124,7 @@ function gate() {interface FakeSession {id: string;- closeReason: 'unexpected' | 'agent-switch';+ closeReason: 'unexpected' | 'agent-switch' | 'requested';listeners: Set<(status: SessionStatus) => void>;onStatusChange(listener: (status: SessionStatus) => void): () => void;setInteractionListener(listener: unknown): void;@@ -229,6 +263,7 @@ function setup(options: { bComesBack?: boolean } = {}) {});let readRowGate: { opened: Promise<void>; open: () => void } | null = null;let probeGate: { opened: Promise<void>; open: () => void } | null = null;+ let writeBindingGate: { opened: Promise<void>; open: () => void } | null = null;let held: (() => void) | null = null;const leaseResults: Array<object | null> = [];const deps = {@@ -237,6 +272,9 @@ function setup(options: { bComesBack?: boolean } = {}) {readGroup: (id: string) => (id === 'anthropic' ? config : null),readBinding: (id: string) => bindings.get(id) ?? null,writeBinding: vi.fn(async (id: string, binding: { providerId: string; memberKey: string } | null) => {+ const pending = writeBindingGate;+ writeBindingGate = null;+ if (pending) await pending.opened;if (binding) bindings.set(id, { ...binding, at: 2 });else bindings.delete(id);}),@@ -309,11 +347,30 @@ function setup(options: { bComesBack?: boolean } = {}) {}const markTried = vi.spyOn(router, 'markTried');+ // 「全部停止」的真实 IPC handler;noteSessionReset 按 register 里的原文接线(STOP_ALL_NOTE_SESSION_RESET,+ // 由下面的接线用例逐行核对),resetAutomaticRecoveryForExplicitStop(撤中断自愈 / silent-stop / 退避簿记,+ // 不碰输入协调器与供应商组)用 spy 代替;closeSession 接 maker.closeSession(requested)。+ const noteSessionReset = vi.fn((_sessionId: string) => {});+ const resetAutomaticRecoveryForExplicitStop = noteSessionReset;+ const providerGroupService: { noteUserAction(sessionId: string): void } | null = service;+ let stopAllHandler: IpcHandler | null = null;+ registerStopSessionBackgroundTasksHandler({ handle: (_channel, handler) => { stopAllHandler = handler; } }, {+ closeSession: async () => closeSession(live, 'requested'),+ clearBackgroundActivity: () => {},+ noteSessionReset: (sessionId) => {+ resetAutomaticRecoveryForExplicitStop(sessionId);+ providerGroupService?.noteUserAction(sessionId);+ },+ notifyGoalStop: () => {},+ });return {coordinator,service,router,markTried,+ noteSessionReset,+ /** 用户点「全部停止」。 */+ stopAll: () => stopAllHandler!({}, SID),deps,hooks,row,@@ -326,10 +383,20 @@ function setup(options: { bComesBack?: boolean } = {}) {readRowGate = gate();held = readRowGate.open;},+ /** 暂停下一次写绑定(换电脑已选好目标、正要交接)。 */+ pauseNextWriteBinding: () => {+ writeBindingGate = gate();+ held = writeBindingGate.open;+ },pauseNextProbe: () => {probeGate = gate();held = probeGate.open;},+ /** 只放行暂停的那一步(不等终态错误的处理)。 */+ release() {+ held?.();+ held = null;+ },/** 放行暂停的那一步,等这次错误处理走完。 */async releaseAndSettle() {held?.();@@ -486,4 +553,91 @@ describe('provider group failover vs. the terminal-error drain close (#5880)', (expectNothingDoneFor(h);expect(h.sendToAgent).toHaveBeenCalledTimes(1);});++ // 「全部停止」(stopSessionBackgroundTasksHandler) 只关闭会话、撤自动续跑簿记,不走协调器的 Stop:+ // 换电脑这一趟也必须停下,不换、不续跑、不交回(provider-groups.md §6.1「用户停止」)。+ function expectStoppedByStopAll(h: ReturnType<typeof setup>) {+ expect(h.noteSessionReset).toHaveBeenCalledWith(SID);+ expect(h.closeContexts.at(-1)).toEqual({ closeReason: 'requested', preserveAutoResumeIntent: false });+ expect(h.deps.switchAgentLocation).not.toHaveBeenCalled();+ expect(h.deps.continueSession).not.toHaveBeenCalled();+ expect(h.deps.fallback).not.toHaveBeenCalled();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ }++ it('stop all while the checks are pending stops the switch', async () => {+ const h = setup();+ h.pauseNextReadSessionRow();+ await h.failOnB();+ await flush();+ await h.stopAll();+ await h.releaseAndSettle();+ expectStoppedByStopAll(h);+ });++ it('stop all while waiting for B to come back stops the switch', async () => {+ const h = setup();+ h.pauseNextProbe();+ await h.failOnB();+ await flush();+ expect(h.leaseResults).toEqual([expect.any(Object)]);+ await h.stopAll();+ await h.releaseAndSettle();+ expectStoppedByStopAll(h);+ });++ it('register wires stop all to the provider group without changing the shared explicit-stop reset', () => {+ expect(stopAllNoteSessionResetLines()).toEqual(STOP_ALL_NOTE_SESSION_RESET);+ // 只接在「全部停止」:其他停止入口共用的 resetAutomaticRecoveryForExplicitStop 本身不碰供应商组。+ const start = REGISTER_SOURCE.indexOf('function resetAutomaticRecoveryForExplicitStop(');+ const end = REGISTER_SOURCE.indexOf('\n}\n', start);+ expect(start).toBeGreaterThan(0);+ expect(REGISTER_SOURCE.slice(start, end)).not.toContain('providerGroupService');+ });++ // 发送前换电脑(beforeSend):已选好目标、正在写绑定 / 交接时用户停止,交接在改动之前停下,任务留在原电脑+ // (provider-groups.md §6.1 发送前:「用户停止这次发送时立刻停下:不再等、不再换」)。+ async function relocateBeforeSend(h: ReturnType<typeof setup>, signal?: AbortSignal) {+ const moving = h.service.beforeSend(SID, signal ? { signal } : undefined);+ await flush();+ return moving;+ }++ it('control: before sending, a task on an offline B moves to this computer', async () => {+ const h = setup();+ await relocateBeforeSend(h);+ expect(h.deps.switchAgentLocation).toHaveBeenCalledTimes(1);+ expect(h.row.agentDeviceId).toBeNull();+ expect(h.bindings.get(SID)?.memberKey).toBe(LOCAL.key);+ });++ it('stop all while the task is being moved before sending keeps it on B', async () => {+ const h = setup();+ h.pauseNextWriteBinding();+ const moving = relocateBeforeSend(h);+ await flush();+ expect(h.deps.writeBinding).toHaveBeenCalledTimes(1);+ await h.stopAll();+ h.release();+ await moving;+ await flush();+ expect(h.row.agentDeviceId).toBe(MAC_B.agentDeviceId);+ expect(h.bindings.get(SID)?.memberKey).toBe(MAC_B.key);+ expect(h.markTried.mock.calls.map(([, key]) => key)).toEqual([MAC_B.key]);+ });++ it('stopping the send while the task is being moved before sending keeps it on B', async () => {+ const h = setup();+ const controller = new AbortController();+ h.pauseNextWriteBinding();+ const moving = relocateBeforeSend(h, controller.signal);+ await flush();+ expect(h.deps.writeBinding).toHaveBeenCalledTimes(1);+ controller.abort();+ h.release();+ await moving;+ await flush();+ expect(h.row.agentDeviceId).toBe(MAC_B.agentDeviceId);+ expect(h.bindings.get(SID)?.memberKey).toBe(MAC_B.key);+ });});diff --git a/apps/desktop/src/main/provider-group/__tests__/remoteGroup.test.ts b/apps/desktop/src/main/provider-group/__tests__/remoteGroup.test.tsindex e1f9a10509..05920480da 100644--- a/apps/desktop/src/main/provider-group/__tests__/remoteGroup.test.ts+++ b/apps/desktop/src/main/provider-group/__tests__/remoteGroup.test.ts@@ -484,7 +484,7 @@ describe('switching computers within a group on another computer', () => {expect(h.deps.switchAgentLocation).toHaveBeenCalledWith('s1',expect.objectContaining({ agentDeviceId: 'share:s1', providerId: 'anthropic' }),- { beforeSend: true },+ { beforeSend: true, isCurrent: expect.any(Function) },);const healthy = bound();await healthy.service.beforeSend('s1');diff --git a/apps/desktop/src/main/provider-group/__tests__/service.test.ts b/apps/desktop/src/main/provider-group/__tests__/service.test.tsindex ee1072750f..993c83bc12 100644--- a/apps/desktop/src/main/provider-group/__tests__/service.test.ts+++ b/apps/desktop/src/main/provider-group/__tests__/service.test.ts@@ -1064,7 +1064,7 @@ describe('beforeSend', () => {expect(h.deps.switchAgentLocation).toHaveBeenCalledWith('s1',{ agentKind: 'claude-code', model: MODEL, providerId: 'anthropic', agentDeviceId: null },- { beforeSend: true },+ { beforeSend: true, isCurrent: expect.any(Function) },);expect(h.bindings.get('s1')?.memberKey).toBe('local');expect(h.deps.continueSession).not.toHaveBeenCalled();@@ -1107,7 +1107,7 @@ describe('beforeSend', () => {expect(reopen.deps.switchAgentLocation).toHaveBeenCalledWith('s1',expect.objectContaining({ agentDeviceId: null }),- { beforeSend: true },+ { beforeSend: true, isCurrent: expect.any(Function) },);// 会话还开着:信缓存的状态,不现读。diff --git a/apps/desktop/src/main/provider-group/service.ts b/apps/desktop/src/main/provider-group/service.tsindex 3d8390690d..e35b4a0adc 100644--- a/apps/desktop/src/main/provider-group/service.ts+++ b/apps/desktop/src/main/provider-group/service.ts@@ -1730,12 +1730,13 @@ export function createProviderGroupService(deps: ProviderGroupServiceDeps): Provconst route = source.routeOf(pick.member, localProviderId);await deps.writeBinding(sessionId, bindingFor(source, binding.providerId, pick.member.key));try {+ // 写绑定、交接期间用户停止(停止这次发送或「全部停止」):交接在改动之前停下,留在原电脑。await deps.switchAgentLocation(sessionId, {agentKind: row.agentKind,model: row.model,providerId: route.providerId,agentDeviceId: route.agentDeviceId,- }, { beforeSend: true });+ }, { beforeSend: true, isCurrent });deps.log.info('provider group: moved a task before sending', {sessionId,from: current.key,