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(local-agent): 中断未派发的发送时补发终态,撤权等待启动中的执行关闭

david9ec87ec15f03
diff --git a/apps/desktop/src/main/local-agent/__tests__/runtime.integration.test.ts b/apps/desktop/src/main/local-agent/__tests__/runtime.integration.test.ts
index f6fa43eee3..6475d4c3e9 100644
--- a/apps/desktop/src/main/local-agent/__tests__/runtime.integration.test.ts
+++ b/apps/desktop/src/main/local-agent/__tests__/runtime.integration.test.ts
@@ -51,6 +51,7 @@ async function fixture() {
cleanups.push(() => fs.rm(directory, { recursive: true, force: true }));
const first = handle('first');
const maker = { startLocalAgentSession: vi.fn(async () => first) };
+ const events: unknown[] = [];
const runtime = await openLocalAgentRuntime(
maker as any,
directory,
@@ -72,10 +73,14 @@ async function fixture() {
access: 'none',
tools: [],
},
- { url: 'http://127.0.0.1:1/mcp/fixture', token: 'invalid-fixture-token', emit: () => {} },
+ {
+ url: 'http://127.0.0.1:1/mcp/fixture',
+ token: 'invalid-fixture-token',
+ emit: (event) => events.push(event),
+ },
);
cleanups.push(() => runtime.close());
- return { runtime, maker, first, directory };
+ return { runtime, maker, first, directory, events };
}
const image = { type: 'image', mimeType: 'image/png', data: Buffer.from('png').toString('base64') };
async function inputFiles(directory: string) {
@@ -219,6 +224,28 @@ describe('local client runtime lifecycle', () => {
await vi.waitFor(() => expect(f.runtime.call('send', message)).resolves.toEqual({}));
expect(f.first.send).toHaveBeenCalledTimes(2);
});
+ it('ends a send that an interrupt cancels before the supplier accepts it', async () => {
+ const f = await fixture(),
+ reserved = deferred();
+ let cancel!: (value: { accepted: boolean }) => void;
+ f.first.send.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ cancel = resolve;
+ reserved.resolve();
+ }),
+ );
+ f.first.abort.mockImplementationOnce(async () => cancel({ accepted: false }));
+ await f.runtime.call('send', { parts: message.parts });
+ await reserved.promise;
+ await f.runtime.call('interrupt', {});
+ await vi.waitFor(() =>
+ expect(f.events).toContainEqual({
+ type: 'turn_end',
+ data: { status: 'interrupted', message: '' },
+ }),
+ );
+ });
it('removes images written for a send that is rejected before the engine takes it', async () => {
const f = await fixture();
await expect(
diff --git a/apps/desktop/src/main/local-agent/__tests__/server.integration.test.ts b/apps/desktop/src/main/local-agent/__tests__/server.integration.test.ts
index 117ccdb2bd..b2e7ad98fe 100644
--- a/apps/desktop/src/main/local-agent/__tests__/server.integration.test.ts
+++ b/apps/desktop/src/main/local-agent/__tests__/server.integration.test.ts
@@ -268,6 +268,37 @@ describe('local application authorization and lifecycle', () => {
await f.server().close();
expect(f.close).toHaveBeenCalledTimes(2);
});
+ it('keeps revoke pending until an engine still starting is closed, and reports a failed late close', async () => {
+ let release!: () => void, began!: () => void;
+ const started = new Promise<void>((resolve) => {
+ began = resolve;
+ });
+ const held = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const close = vi.fn(async () => {});
+ close.mockRejectedValueOnce(new Error('native process exit unconfirmed'));
+ const f = await fixture({
+ open: async () => {
+ began();
+ await held;
+ return { id: 'late', resumed: false, call: async () => ({}), close };
+ },
+ });
+ const secret = await f.connect();
+ const opening = f.start(secret);
+ await started;
+ let settled = false;
+ const revoking = f.server().revoke(f.server().connections()[0].id);
+ void revoking.catch(() => {}).finally(() => (settled = true));
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(settled).toBe(false);
+ release();
+ await expect(revoking).rejects.toMatchObject({ code: 'RUNTIME_CLOSE_UNCONFIRMED' });
+ expect((await opening).error).toBeDefined();
+ await f.server().close();
+ expect(close).toHaveBeenCalledTimes(2);
+ });
it('keeps concurrent opens within the persisted resume limit so the service can restart', async () => {
const releases: Array<() => void> = [];
const f = await fixture({
diff --git a/apps/desktop/src/main/local-agent/runtime.ts b/apps/desktop/src/main/local-agent/runtime.ts
index b2f184ab61..e30095aace 100644
--- a/apps/desktop/src/main/local-agent/runtime.ts
+++ b/apps/desktop/src/main/local-agent/runtime.ts
@@ -157,10 +157,10 @@ export function createEventProjection(
});
}
},
- fail(message: string) {
+ fail(message: string, status: 'failed' | 'interrupted' = 'failed') {
if (!ended) {
ended = true;
- emit({ type: 'turn_end', data: { status: 'failed', message } });
+ emit({ type: 'turn_end', data: { status, message } });
}
},
};
@@ -183,7 +183,8 @@ export async function openLocalAgentRuntime(
// Instructions are read when a Session starts; only that applied version is clean.
let instructionsVersion = 0,
appliedInstructions = 0;
- let epoch = 0;
+ let epoch = 0,
+ turn = 0;
const assertCurrent = (expected: number) => {
if (closed) throw new LocalAgentError('SESSION_UNAVAILABLE', 'Cindy 会话已关闭。');
if (epoch !== expected)
@@ -412,6 +413,7 @@ export async function openLocalAgentRuntime(
await handle.setEffort(params.effort as Parameters<Session['setEffort']>[0]);
assertCurrent(current);
preparing = false;
+ const generation = ++turn;
projection.begin();
// Some harnesses await the entire turn; acceptance must not block tool delivery/control RPCs.
const sending = content;
@@ -420,9 +422,13 @@ export async function openLocalAgentRuntime(
if (!result.accepted) await discard(sending);
assertSendDispatched(result, 'local-agent/send');
})().catch(() => {
- if (!closed && epoch === current) {
+ if (closed || turn !== generation) return;
+ if (epoch === current) {
busy = false;
projection.fail(localize('EXECUTION_FAILED', 'Cindy 未能完成本次发送。'));
+ } else {
+ // An interrupt cancelled the turn before the supplier saw it: no native terminal follows.
+ projection.fail('', 'interrupted');
}
});
return {};
diff --git a/apps/desktop/src/main/local-agent/server.ts b/apps/desktop/src/main/local-agent/server.ts
index 30f68c946b..15e8843b6f 100644
--- a/apps/desktop/src/main/local-agent/server.ts
+++ b/apps/desktop/src/main/local-agent/server.ts
@@ -88,6 +88,8 @@ interface Run {
pending: Map<string, { resolve: (value: unknown) => void; timer: ReturnType<typeof setTimeout> }>;
resumeKey?: string;
closing?: Promise<void>;
+ /** A revoke during startup must wait for the late runtime and confirm its close. */
+ opening?: Promise<LocalAgentRuntime>;
}
export interface LocalAgentServerDeps {
directory: string;
@@ -252,6 +254,12 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {
const clients = new Map<string, number>();
let base = '';
let closing = false;
+ /** Closes of engines that were still starting when their run was closed, by grant. */
+ const lateCloses = new Map<Promise<void>, string>();
+ const lateClosed = (owner?: string) =>
+ Promise.all(
+ [...lateCloses].filter(([, o]) => owner === undefined || o === owner).map(([p]) => p),
+ );
const closeRun = async (id: string, expected?: Run) => {
const run = runs.get(id);
if (!run || (expected && expected !== run)) return;
@@ -266,6 +274,28 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {
}
run.pending.clear();
for (const wake of run.waiters) wake();
+ if (!run.runtime && run.opening) {
+ // Free the session ID now; revocation still waits until the late engine is closed.
+ runs.delete(id);
+ const settled = run.opening.then(
+ async (runtime) => {
+ try {
+ await runtime.close();
+ } catch {
+ deps.warn('RUNTIME_CLOSE_UNCONFIRMED');
+ runs.set(`late:${token()}`, run); // closed run kept for a later close retry
+ throw new LocalAgentError(
+ 'RUNTIME_CLOSE_UNCONFIRMED',
+ '连接已失效,但尚未确认执行进程停止。',
+ );
+ }
+ },
+ () => {},
+ );
+ lateCloses.set(settled, run.owner);
+ void settled.catch(() => {}).finally(() => lateCloses.delete(settled));
+ return;
+ }
run.closing = (async () => {
try {
await run.runtime?.close();
@@ -348,7 +378,7 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {
for (const key of clients.keys()) if (key.startsWith(`${id}:`)) clients.delete(key);
const stopped = Promise.all(
[...runs].filter(([, run]) => run.owner === id).map(([key]) => closeRun(key)),
- );
+ ).then(() => lateClosed(id));
try {
await Promise.all([persist(), stopped]);
} finally {
@@ -448,7 +478,7 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {
};
runs.set(id, run);
try {
- run.runtime = await deps.open(
+ run.opening = deps.open(
{
isolationKey: hash(grant.id),
mcpName: grant.legacyRuntime ? 'hhh' : 'client',
@@ -469,10 +499,10 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {
},
},
);
- if (run.closed || !grants.includes(grant) || grant.scope !== deps.scope()) {
- await run.runtime.close();
+ run.runtime = await run.opening;
+ // The catch below joins any revoke already closing this run instead of closing twice.
+ if (run.closed || !grants.includes(grant) || grant.scope !== deps.scope())
throw new LocalAgentError('UNAUTHORIZED', '连接已失效。');
- }
// Another open may have used the last slot while this engine started.
if (!binding && Object.keys(bindings).length >= 4096)
throw new LocalAgentError(
@@ -869,7 +899,10 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {
pairs.clear();
dedup.clear();
clients.clear();
- await Promise.all([persist(), ...[...runs.keys()].map((id) => closeRun(id))]);
+ await Promise.all([
+ persist(),
+ Promise.all([...runs.keys()].map((id) => closeRun(id))).then(() => lateClosed()),
+ ]);
deps.changed?.();
},
async close() {