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): 处理审核指出的说明竞态、撤销持久化与路径问题

davidcbf4afc8bd24
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 f289018a8f..bb69e223d5 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
@@ -8,7 +8,12 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
-vi.mock('@cindy/maker-core', () => ({ LOCAL_AGENT_CLIENT: Symbol('local-agent-client') }));
+vi.mock('@cindy/maker-core', () => ({
+ LOCAL_AGENT_CLIENT: Symbol('local-agent-client'),
+ assertSendDispatched: (result: { accepted: boolean }) => {
+ if (!result.accepted) throw new Error('not dispatched');
+ },
+}));
import { openLocalAgentRuntime } from '../runtime.js';
import type { AgentEvent } from '@cindy/maker-core';
@@ -27,7 +32,7 @@ function handle(id: string) {
const ended = deferred();
return {
sdkSessionId: id,
- send: vi.fn(async () => {}),
+ send: vi.fn(async () => ({ accepted: true })),
steer: vi.fn(async () => {}),
abort: vi.fn(async () => {}),
setEffort: vi.fn(async () => {}),
@@ -172,4 +177,40 @@ describe('local client runtime lifecycle', () => {
expect(late.close).toHaveBeenCalledWith({ reason: 'account-boundary' });
expect(late.send).not.toHaveBeenCalled();
});
+ it('rebuilds again when instructions change while a rebuild is still starting', async () => {
+ const f = await fixture(),
+ entered = deferred(),
+ held = deferred(),
+ second = handle('second'),
+ third = handle('third');
+ cleanups.push(() => second.close(), () => third.close());
+ f.maker.startLocalAgentSession
+ .mockImplementationOnce(async () => {
+ entered.resolve();
+ await held.promise;
+ return second;
+ })
+ .mockImplementationOnce(async () => third);
+ await f.runtime.call('instructions', { instructions: 'first update' });
+ const sending = f.runtime.call('send', message);
+ await entered.promise;
+ await f.runtime.call('instructions', { instructions: 'latest' });
+ held.resolve();
+ await sending;
+ second.getObservedCurrentTurnTerminal.mockReturnValue({ kind: 'done' });
+ second.onEvent.mock.calls[0][0]({ type: 'done', data: { status: 'completed' } });
+ await f.runtime.call('send', message);
+ expect(f.maker.startLocalAgentSession).toHaveBeenLastCalledWith(
+ 'pi',
+ expect.objectContaining({ userPrompt: 'latest' }),
+ );
+ expect(third.send).toHaveBeenCalledTimes(1);
+ });
+ it('releases the execution when the engine declines a send before dispatch', async () => {
+ const f = await fixture();
+ f.first.send.mockResolvedValueOnce({ accepted: false });
+ await f.runtime.call('send', message);
+ await vi.waitFor(() => expect(f.runtime.call('send', message)).resolves.toEqual({}));
+ expect(f.first.send).toHaveBeenCalledTimes(2);
+ });
});
diff --git a/apps/desktop/src/main/local-agent/runtime.ts b/apps/desktop/src/main/local-agent/runtime.ts
index 6ec326a92f..b3badb471f 100644
--- a/apps/desktop/src/main/local-agent/runtime.ts
+++ b/apps/desktop/src/main/local-agent/runtime.ts
@@ -162,8 +162,10 @@ export async function openLocalAgentRuntime(
let closed = false,
busy = false,
preparing = false,
- dirtyInstructions = false,
resumed = false;
+ // Instructions are read when a Session starts; only that applied version is clean.
+ let instructionsVersion = 0,
+ appliedInstructions = 0;
let epoch = 0;
const assertCurrent = (expected: number) => {
if (closed) throw new LocalAgentError('SESSION_UNAVAILABLE', 'Cindy 会话已关闭。');
@@ -332,7 +334,7 @@ export async function openLocalAgentRuntime(
}
if (method === 'instructions') {
instructions = typeof params.instructions === 'string' ? params.instructions : undefined;
- dirtyInstructions = true;
+ instructionsVersion += 1;
return {};
}
if (method !== 'send' && method !== 'steer')
@@ -358,12 +360,13 @@ export async function openLocalAgentRuntime(
try {
const content = await message(params);
assertCurrent(current);
- if (dirtyInstructions) {
+ if (appliedInstructions !== instructionsVersion) {
const previous = handle;
await previous.close();
assertCurrent(current);
+ const applying = instructionsVersion;
handle = await start(previous.sdkSessionId, current);
- dirtyInstructions = false;
+ appliedInstructions = applying;
}
if (params.effort !== undefined)
await handle.setEffort(params.effort as Parameters<Session['setEffort']>[0]);
diff --git a/apps/desktop/src/main/local-agent/server.ts b/apps/desktop/src/main/local-agent/server.ts
index 53746315f5..30f68c946b 100644
--- a/apps/desktop/src/main/local-agent/server.ts
+++ b/apps/desktop/src/main/local-agent/server.ts
@@ -224,6 +224,8 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {
throw new LocalAgentError('GRANT_STORE_INVALID', '本机应用授权记录无法读取,原文件已保留。');
}
let persistence = Promise.resolve();
+ // A failed write must not let a revoked grant come back from disk after restart.
+ let unsaved = false;
const persist = () => {
const value = JSON.stringify({ version: 2, grants, bindings });
const write = async () => {
@@ -236,9 +238,12 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {
}
atomicWriteFileSync(grantFile, value);
legacyStore = undefined;
+ unsaved = false;
};
const result = persistence.then(write, write);
- persistence = result.catch(() => {});
+ persistence = result.catch(() => {
+ unsaved = true;
+ });
return result;
};
const pairs = new Map<string, Pair>();
@@ -380,7 +385,7 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {
'所选模型或供应商已不可用,请在 Cindy 中检查后重新选择。',
);
const cwd = text(p.cwd, 32768);
- if (!path.isAbsolute(cwd) || !(await fs.stat(cwd)).isDirectory())
+ if (!path.isAbsolute(cwd) || !(await fs.stat(cwd).catch(() => undefined))?.isDirectory())
throw new LocalAgentError('INVALID_WORKSPACE', '工作目录不存在或不是绝对路径。');
const effort = text(p.effort, 64, true) || undefined;
if (effort && !model.efforts.includes(effort))
@@ -831,6 +836,10 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {
throw new LocalAgentError('DISCOVERY_UNAVAILABLE', '未能保存本机应用连接信息。');
}
const sweep = setInterval(() => {
+ if (unsaved) {
+ unsaved = false;
+ void persist().catch(() => {});
+ }
for (const [id, pair] of pairs)
if (pair.expires < Date.now() || pair.scope !== deps.scope()) {
pair.consent?.abort();
@@ -872,6 +881,7 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
await persistence;
+ if (unsaved) await persist().catch(() => {});
try {
if (JSON.parse(await fs.readFile(discoveryFile, 'utf8')).instance === instanceId)
await fs.rm(discoveryFile, { force: true });
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index e9ac4a00ba..57aac4bd49 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -1790,9 +1790,15 @@ export function getMaker(): Maker {
const restricted = { ...catalog, models: catalog.models.map(model => ({...model, apply_patch_tool_type: null, supports_search_tool: false})) };
const directory = ownerScopedUserDataPath('local-agent', 'codex-catalogs');
await fs.mkdir(directory, {recursive:true});
- const target = path.join(directory, `host-tools-only-${createHash('sha256').update(JSON.stringify([modelId, contextWindow])).digest('hex')}.json`);
+ // Content-addressed: an existing identical file is reused, so Windows never has to
+ // replace a catalog another session may still hold or be publishing concurrently.
+ const content = JSON.stringify(restricted);
+ const target = path.join(directory, `host-tools-only-${createHash('sha256').update(content).digest('hex')}.json`);
+ const published = () => fs.readFile(target, 'utf8').then(existing => existing === content, () => false);
+ if (await published()) return target;
const temporary = target + '.' + randomUUID() + '.tmp';
- try { await fs.writeFile(temporary, JSON.stringify(restricted), {mode:0o600}); await fs.rename(temporary,target); }
+ try { await fs.writeFile(temporary, content, {mode:0o600}); await fs.rename(temporary,target); }
+ catch (error) { if (!(await published())) throw error; }
finally { await fs.rm(temporary,{force:true}); }
return target;
},