mirror of
https://github.com/makecindy/cindy.git
synced 2026-12-02 01:29:58 +08:00
fix(desktop): release stale task bindings at account reset (#6732)
Signed-off-by: Chris <4436110+zqchris@users.noreply.github.com> Co-authored-by: Chris <4436110+zqchris@users.noreply.github.com>
This commit is contained in:
@@ -124,6 +124,7 @@ import {
|
||||
isActiveInputOwnerAuthored,
|
||||
isSessionInTurn,
|
||||
wireSessionToIpc,
|
||||
releaseSessionBindingsForOwnerBoundary,
|
||||
} from '../maker-ipc/register.js';
|
||||
import { MAKER_PUSH } from '../maker-ipc/channels.js';
|
||||
import { readProviderGroupBinding } from '../provider-group/bindings.js';
|
||||
@@ -3296,6 +3297,11 @@ export async function preflightBotRuntimeResources(
|
||||
* 重置 Maker 单例(切账号 / 测试用)。
|
||||
*/
|
||||
export function resetMaker(): void {
|
||||
// A disconnected remote handle may reject detach without emitting closed.
|
||||
// Retire its Desktop input/turn observers before dropping the owning Maker;
|
||||
// otherwise a relogin inherits the old dispatch-busy and abort boundaries.
|
||||
// Callers keep this Maker when PI teardown is unconfirmed, preserving supervision.
|
||||
releaseSessionBindingsForOwnerBoundary();
|
||||
remoteWorkerBridge = null;
|
||||
disposeRemoteAgentHost();
|
||||
_sessionArchiveSync?.stop();
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
AgentInputCoordinator,
|
||||
type AgentInputCoordinatorDeps,
|
||||
} from '../agent-input-coordinator.js';
|
||||
import { SessionTurnActivityTracker } from '../sessionTurnActivityTracker.js';
|
||||
import { createRehydrateCloseSuppression } from '../../maker-host/rehydrateCloseSuppression.js';
|
||||
import type { AgentInputQueuedMessage } from '../../../shared/agentInputQueue.js';
|
||||
|
||||
@@ -35,6 +36,33 @@ function deferred() {
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
const item = (id: string): AgentInputQueuedMessage => ({
|
||||
clientId: id,
|
||||
text: id,
|
||||
persistedContent: id,
|
||||
model: 'test-model',
|
||||
effort: 'medium',
|
||||
permissionMode: 'default',
|
||||
workingDir: '/unused',
|
||||
chatMessage: {
|
||||
clientId: id,
|
||||
role: 'user',
|
||||
content: id,
|
||||
isStreaming: false,
|
||||
createdAt: '2026-09-05T00:00:00.000Z',
|
||||
},
|
||||
createOpts: {
|
||||
agentKind: 'codex',
|
||||
workingDir: '/unused',
|
||||
model: 'test-model',
|
||||
effort: 'medium',
|
||||
permissionMode: 'default',
|
||||
userPrompt: '',
|
||||
makerMemoryEnabled: false,
|
||||
displayReasoning: 'summarized',
|
||||
},
|
||||
});
|
||||
|
||||
/** Retains captured callbacks so tests can deliver a stale transport notification explicitly. */
|
||||
class TestSession {
|
||||
readonly statuses = new Set<SessionStatusListener>();
|
||||
@@ -448,32 +476,6 @@ describe('binding with the real maker-core Session', () => {
|
||||
coordinator.onSessionClosed('task', options),
|
||||
);
|
||||
h.bind(old.session);
|
||||
const item = (id: string): AgentInputQueuedMessage => ({
|
||||
clientId: id,
|
||||
text: id,
|
||||
persistedContent: id,
|
||||
model: 'test-model',
|
||||
effort: 'medium',
|
||||
permissionMode: 'default',
|
||||
workingDir: '/unused',
|
||||
chatMessage: {
|
||||
clientId: id,
|
||||
role: 'user',
|
||||
content: id,
|
||||
isStreaming: false,
|
||||
createdAt: '2026-09-05T00:00:00.000Z',
|
||||
},
|
||||
createOpts: {
|
||||
agentKind: 'codex',
|
||||
workingDir: '/unused',
|
||||
model: 'test-model',
|
||||
effort: 'medium',
|
||||
permissionMode: 'default',
|
||||
userPrompt: '',
|
||||
makerMemoryEnabled: false,
|
||||
displayReasoning: 'summarized',
|
||||
},
|
||||
});
|
||||
const queued = coordinator.enqueue('task', item('first'));
|
||||
await entered.promise;
|
||||
old.closeFinished.resolve();
|
||||
@@ -523,6 +525,62 @@ describe('binding with the real maker-core Session', () => {
|
||||
expect(h.finalActions.clearTurnState).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
// #6718: a failed detach is not process-exit proof, but abandoning the old
|
||||
// Maker must release Desktop's dispatch gate. Existing close tests only cover
|
||||
// successful retry. Unit tier: real Session/tracker with an injected transport failure.
|
||||
it('releases failed-detach dispatch state only when its owner is discarded', async () => {
|
||||
const h = harness<Session>();
|
||||
const old = realSession(), next = realSession();
|
||||
const tracker = new SessionTurnActivityTracker();
|
||||
h.finalActions.clearTurnState.mockImplementation(() => tracker.deleteSession('task'));
|
||||
const abort = deferred();
|
||||
const sendToAgent = vi.fn<AgentInputCoordinatorDeps['sendToAgent']>(async (_id, message) => {
|
||||
const text = typeof message === 'string' ? message : message.content;
|
||||
if (typeof text !== 'string') throw new Error('This fixture sends text only');
|
||||
await h.lifecycle.getSession('task')!.send(text);
|
||||
return { kind: 'session-dispatch', source: 'owner-boundary-test', dispatched: true };
|
||||
});
|
||||
const coordinator = new AgentInputCoordinator({
|
||||
sendToAgent, steerToAgent: vi.fn(), abortSession: () => abort.promise,
|
||||
isTurnRunning: () => tracker.isSessionTurnDispatchBoundaryBusy('task'),
|
||||
hasPendingInteraction: () => false, getAgentKind: () => 'codex',
|
||||
getSdkSessionId: async () => undefined, emitProjection: vi.fn(),
|
||||
});
|
||||
h.actions.closeInputCoordinator.mockImplementation(options => coordinator.onSessionClosed('task', options));
|
||||
vi.mocked(old.handle.close).mockRejectedValueOnce(new Error('DEVICE_LINK_NOT_CONNECTED'));
|
||||
h.bind(old.session);
|
||||
await old.session.send('work before expiration');
|
||||
tracker.setSessionInTurn('task', true);
|
||||
await expect(old.session.detach({ reason: 'account-boundary' }))
|
||||
.rejects.toThrow('DEVICE_LINK_NOT_CONNECTED');
|
||||
expect(old.session.getStatus()).toBe('error');
|
||||
expect(h.lifecycle.getSession('task')).toBe(old.session);
|
||||
expect(tracker.isSessionTurnDispatchBoundaryBusy('task')).toBe(true);
|
||||
|
||||
await coordinator.enqueue('task', item('queued-after-expiration'));
|
||||
expect(sendToAgent).not.toHaveBeenCalled();
|
||||
coordinator.stop('task', { keepQueue: true, pauseQueue: true });
|
||||
expect(coordinator.getProjection('task').queueAbortPending).toBe(true);
|
||||
h.lifecycle.releaseForOwnerBoundary();
|
||||
expect(coordinator.getProjection('task').queueAbortPending).toBe(false);
|
||||
expect(tracker.isSessionTurnDispatchBoundaryBusy('task')).toBe(false);
|
||||
expect(h.lifecycle.getSession('task')).toBeUndefined();
|
||||
expect(old.session.getStatus()).toBe('error'); // No fabricated process exit.
|
||||
expect(h.actions.closeInputCoordinator).toHaveBeenCalledOnce();
|
||||
h.lifecycle.releaseForOwnerBoundary();
|
||||
expect(h.finalActions.clearTurnState).toHaveBeenCalledOnce();
|
||||
h.bind(next.session);
|
||||
abort.resolve();
|
||||
coordinator.resume('task');
|
||||
await vi.waitFor(() => expect(next.handle.send).toHaveBeenCalledOnce());
|
||||
expect(sendToAgent).toHaveBeenCalledOnce();
|
||||
old.closeFinished.resolve();
|
||||
await old.session.detach(); // A late old-owner success cannot erase its replacement.
|
||||
expect(h.lifecycle.getSession('task')).toBe(next.session);
|
||||
next.closeFinished.resolve();
|
||||
await next.session.close();
|
||||
});
|
||||
|
||||
it('retains the binding on provider close failure and tears down after a successful retry', async () => {
|
||||
const h = harness<Session>();
|
||||
const r = realSession();
|
||||
|
||||
@@ -5849,6 +5849,11 @@ const sessionBindings = createSessionBindingLifecycle<WiredSession, WiredSession
|
||||
},
|
||||
});
|
||||
|
||||
/** Called only when the outgoing Maker is actually discarded, not on any error status. */
|
||||
export function releaseSessionBindingsForOwnerBoundary(): void {
|
||||
sessionBindings.releaseForOwnerBoundary();
|
||||
}
|
||||
|
||||
let pluginTaskServiceForCurrentOwner: (() => PluginTaskService) | null = null;
|
||||
let drainPluginTaskReceipts: (() => Promise<void>) | null = null;
|
||||
export async function flushPluginTaskLifecycle(): Promise<void> {
|
||||
|
||||
@@ -50,6 +50,45 @@ export function createSessionBindingLifecycle<S extends BindingSession, CloseCon
|
||||
return registration;
|
||||
}
|
||||
|
||||
function releaseRegistration(registration: SessionBindingRegistration<S>): void {
|
||||
const { session } = registration;
|
||||
if (bindings.get(session.id) !== registration) return;
|
||||
// Capture abort/recovery ownership before any cleanup removes it.
|
||||
const context = deps.captureCloseContext(session);
|
||||
try {
|
||||
deps.cleanupClosedSession(session, context);
|
||||
} catch (err) {
|
||||
deps.log.warn('session close cleanup failed; forcing idle reconciliation', {
|
||||
sessionId: session.id,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
} finally {
|
||||
// Product cleanup is best-effort. Unregister before calling disposers
|
||||
// so a late status callback cannot enter the close boundary again.
|
||||
deps.beforeCloseTeardown(session);
|
||||
bindings.delete(session.id);
|
||||
for (const dispose of registration.disposers) {
|
||||
try {
|
||||
dispose();
|
||||
} catch (err) {
|
||||
deps.log.warn('session disposer failed during close teardown', {
|
||||
sessionId: session.id,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
}
|
||||
}
|
||||
try {
|
||||
session.setInteractionListener(null);
|
||||
} catch (err) {
|
||||
deps.log.warn('session interaction listener teardown failed', {
|
||||
sessionId: session.id,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
}
|
||||
deps.finalizeClosedSession(session, context);
|
||||
}
|
||||
}
|
||||
|
||||
function attachStatusListener(registration: SessionBindingRegistration<S>): void {
|
||||
const { session } = registration;
|
||||
registration.disposers.push(
|
||||
@@ -66,40 +105,7 @@ export function createSessionBindingLifecycle<S extends BindingSession, CloseCon
|
||||
}
|
||||
if (status !== 'closed') return;
|
||||
|
||||
// Capture abort/recovery ownership before any cleanup removes it.
|
||||
const context = deps.captureCloseContext(session);
|
||||
try {
|
||||
deps.cleanupClosedSession(session, context);
|
||||
} catch (err) {
|
||||
deps.log.warn('session close cleanup failed; forcing idle reconciliation', {
|
||||
sessionId: session.id,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
} finally {
|
||||
// Product cleanup is best-effort. Unregister before calling disposers
|
||||
// so a late status callback cannot enter the close boundary again.
|
||||
deps.beforeCloseTeardown(session);
|
||||
bindings.delete(session.id);
|
||||
for (const dispose of registration.disposers) {
|
||||
try {
|
||||
dispose();
|
||||
} catch (err) {
|
||||
deps.log.warn('session disposer failed during close teardown', {
|
||||
sessionId: session.id,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
}
|
||||
}
|
||||
try {
|
||||
session.setInteractionListener(null);
|
||||
} catch (err) {
|
||||
deps.log.warn('session interaction listener teardown failed', {
|
||||
sessionId: session.id,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
}
|
||||
deps.finalizeClosedSession(session, context);
|
||||
}
|
||||
releaseRegistration(registration);
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -107,6 +113,12 @@ export function createSessionBindingLifecycle<S extends BindingSession, CloseCon
|
||||
return {
|
||||
beginBinding,
|
||||
attachStatusListener,
|
||||
// Discard only Desktop observers/bookkeeping. This is not confirmation that
|
||||
// the underlying process exited: Maker retains failed handles until its
|
||||
// account-boundary policy explicitly permits replacing that Maker.
|
||||
releaseForOwnerBoundary(): void {
|
||||
for (const registration of [...bindings.values()]) releaseRegistration(registration);
|
||||
},
|
||||
getSession: (sessionId: string): S | undefined => bindings.get(sessionId)?.session,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user