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): 交互拒绝在原生终态时失败,关闭时不吞授权写盘失败

david5f2dc33f7dbd
diff --git a/apps/desktop/src/main/local-agent/__tests__/runtime.test.ts b/apps/desktop/src/main/local-agent/__tests__/runtime.test.ts
index b7fa5c1566..02b8c76605 100644
--- a/apps/desktop/src/main/local-agent/__tests__/runtime.test.ts
+++ b/apps/desktop/src/main/local-agent/__tests__/runtime.test.ts
@@ -155,6 +155,22 @@ describe('native event projection', () => {
expect(emit.mock.calls[2][0].data).toEqual({ input: 15, cached: 5, output: 2 });
},
);
+ it('fails a dismissed interaction only at the native boundary, after its usage', () => {
+ const emit = vi.fn(),
+ p = createEventProjection(emit);
+ p.begin();
+ p.failAtEnd('interaction unavailable');
+ p.accept({ type: 'text', data: { text: 'wrapping up', isFinal: false } } as any);
+ p.accept({
+ type: 'done',
+ data: { status: 'completed', usage: { inputTokens: 3, outputTokens: 1 } },
+ } as any);
+ expect(emit.mock.calls.map(([e]) => e)).toEqual([
+ { type: 'text', data: 'wrapping up' },
+ { type: 'usage', data: { input: 3, cached: 0, output: 1 } },
+ { type: 'turn_end', data: { status: 'failed', message: 'interaction unavailable' } },
+ ]);
+ });
it('appends a final-only tail per message and never repeats a diverged snapshot', () => {
const emit = vi.fn(),
p = createEventProjection(emit);
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 b2e7ad98fe..fc7ec5b495 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
@@ -13,6 +13,17 @@ import { promisify } from 'node:util';
import { fileURLToPath } from 'node:url';
import { createServer, request } from 'node:http';
import { once } from 'node:events';
+const grantWrites = vi.hoisted(() => ({ fail: false }));
+vi.mock('../../utils/atomicWriteFile.js', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../utils/atomicWriteFile.js')>();
+ return {
+ ...actual,
+ atomicWriteFileSync: (file: string, contents: string) => {
+ if (grantWrites.fail && file.endsWith('grants.json')) throw new Error('disk rejected write');
+ actual.atomicWriteFileSync(file, contents);
+ },
+ };
+});
import { createLocalAgentServer, type LocalAgentServerDeps } from '../server.js';
import type { LocalAgentModel } from '../catalog.js';
import { formatLocalAgentConnectionCode } from '../../../shared/localAgent.js';
@@ -32,6 +43,7 @@ const model: LocalAgentModel = {
};
const cleanups: Array<() => Promise<unknown>> = [];
afterEach(async () => {
+ grantWrites.fail = false;
for (const cleanup of cleanups.splice(0).reverse()) await cleanup();
});
@@ -268,6 +280,17 @@ describe('local application authorization and lifecycle', () => {
await f.server().close();
expect(f.close).toHaveBeenCalledTimes(2);
});
+ it('fails close instead of silently keeping a revoked grant on disk', async () => {
+ const f = await fixture(),
+ secret = await f.connect(),
+ file = path.join(f.directory, 'grants.json');
+ grantWrites.fail = true;
+ await expect(f.server().revoke(f.server().connections()[0].id)).rejects.toBeDefined();
+ expect((await f.rpc('models', {}, secret)).error.code).toBe('UNAUTHORIZED');
+ await expect(f.server().close()).rejects.toMatchObject({ code: 'GRANT_PERSIST_FAILED' });
+ grantWrites.fail = false;
+ expect(JSON.parse(await fs.readFile(file, 'utf8')).grants).toHaveLength(1);
+ });
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) => {
diff --git a/apps/desktop/src/main/local-agent/runtime.ts b/apps/desktop/src/main/local-agent/runtime.ts
index e30095aace..4fbf388755 100644
--- a/apps/desktop/src/main/local-agent/runtime.ts
+++ b/apps/desktop/src/main/local-agent/runtime.ts
@@ -58,9 +58,11 @@ export function createEventProjection(
};
const ignoredTools = new Set<string>();
const streamed = new Map<string, string>();
+ let failure: string | undefined;
return {
begin() {
textSeen = false;
+ failure = undefined;
streamed.clear();
ended = false;
usageReported = false;
@@ -144,19 +146,27 @@ export function createEventProjection(
}
reportUsage();
ended = true;
+ const interrupted = ['cancelled', 'aborted', 'interrupted'].includes(string(d.status));
emit({
type: 'turn_end',
data: {
- status: ['cancelled', 'aborted', 'interrupted'].includes(string(d.status))
+ status: interrupted
? 'interrupted'
- : d.is_error === true || d.status === 'error' || d.status === 'failed'
+ : failure !== undefined ||
+ d.is_error === true ||
+ d.status === 'error' ||
+ d.status === 'failed'
? 'failed'
: 'completed',
- message: string(d.error),
+ message: (!interrupted && failure) || string(d.error),
},
});
}
},
+ /** Fail this turn at its real native boundary, after the engine has settled. */
+ failAtEnd(message: string) {
+ if (!ended) failure ??= message;
+ },
fail(message: string, status: 'failed' | 'interrupted' = 'failed') {
if (!ended) {
ended = true;
@@ -249,8 +259,9 @@ export async function openLocalAgentRuntime(
reason: 'The authorized client controls this session tool surface.',
};
}
- // Native interactive prompts cannot be answered on behalf of the user.
- projection.fail(
+ // Native interactive prompts cannot be answered on behalf of the user. The dismissal
+ // goes back to the engine first; the turn fails once it actually settles.
+ projection.failAtEnd(
localize('INTERACTION_UNAVAILABLE', 'Cindy 引擎需要交互确认,当前应用无法接收。'),
);
if (request.kind === 'ask_user_question')
diff --git a/apps/desktop/src/main/local-agent/server.ts b/apps/desktop/src/main/local-agent/server.ts
index 15e8843b6f..739a4f4759 100644
--- a/apps/desktop/src/main/local-agent/server.ts
+++ b/apps/desktop/src/main/local-agent/server.ts
@@ -914,13 +914,21 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
await persistence;
- if (unsaved) await persist().catch(() => {});
+ // The last retry decides whether a revocation survives restart; never report it as closed.
+ const saved = unsaved ? await persist().then(() => true, () => false) : true;
try {
if (JSON.parse(await fs.readFile(discoveryFile, 'utf8')).instance === instanceId)
await fs.rm(discoveryFile, { force: true });
} catch {
/* profile already closed */
}
+ if (!saved) {
+ deps.warn('GRANT_PERSIST_FAILED');
+ throw new LocalAgentError(
+ 'GRANT_PERSIST_FAILED',
+ '本机应用授权变更未能写入磁盘,重启后已撤销的连接可能恢复。',
+ );
+ }
const failed = stopped.find((result) => result.status === 'rejected');
if (failed?.status === 'rejected') throw failed.reason;
},