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): 保留推理力度、轮次结束清理图片、关闭与绑定持久化边界

david08c58c4bdcd3
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 6475d4c3e9..3fdc4f879b 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
@@ -246,6 +246,29 @@ describe('local client runtime lifecycle', () => {
}),
);
});
+ it('keeps the effort chosen by send.effort when instructions rebuild the session', async () => {
+ const f = await fixture(),
+ second = handle('second');
+ cleanups.push(() => second.close());
+ f.maker.startLocalAgentSession.mockImplementationOnce(async () => second);
+ await f.runtime.call('send', message);
+ f.first.getObservedCurrentTurnTerminal.mockReturnValue({ kind: 'done' });
+ f.first.onEvent.mock.calls[0][0]({ type: 'done', data: { status: 'completed' } });
+ await f.runtime.call('instructions', { instructions: 'new context' });
+ await f.runtime.call('send', { parts: message.parts });
+ expect(f.maker.startLocalAgentSession).toHaveBeenLastCalledWith(
+ 'pi',
+ expect.objectContaining({ effort: 'high', userPrompt: 'new context' }),
+ );
+ });
+ it('removes accepted input images once their turn settles', async () => {
+ const f = await fixture();
+ await f.runtime.call('send', { parts: [image] });
+ expect(await inputFiles(f.directory)).toHaveLength(1);
+ f.first.getObservedCurrentTurnTerminal.mockReturnValue({ kind: 'done' });
+ f.first.onEvent.mock.calls[0][0]({ type: 'done', data: { status: 'completed' } });
+ await vi.waitFor(async () => expect(await inputFiles(f.directory)).toEqual([]));
+ });
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 cf789d84b7..6eb2b55d3d 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
@@ -291,6 +291,16 @@ describe('local application authorization and lifecycle', () => {
grantWrites.fail = false;
expect(JSON.parse(await fs.readFile(file, 'utf8')).grants).toHaveLength(1);
});
+ it('rolls back a resume binding whose open could not be persisted', async () => {
+ const f = await fixture(),
+ secret = await f.connect();
+ grantWrites.fail = true;
+ expect((await f.start(secret, 'lost')).error).toBeDefined();
+ grantWrites.fail = false;
+ expect((await f.start(secret, 'kept')).error).toBeUndefined();
+ const stored = JSON.parse(await fs.readFile(path.join(f.directory, 'grants.json'), 'utf8'));
+ expect(Object.keys(stored.bindings)).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 680ad377b2..694f0d32c7 100644
--- a/apps/desktop/src/main/local-agent/runtime.ts
+++ b/apps/desktop/src/main/local-agent/runtime.ts
@@ -205,6 +205,8 @@ export async function openLocalAgentRuntime(
localize = (_code: string, fallback: string) => fallback,
): Promise<LocalAgentRuntime> {
let instructions = input.instructions;
+ // The effort last applied by send.effort survives an instructions rebuild.
+ let effort = input.effort;
const sessionId = `local-agent-${randomUUID()}`;
let handle: Session;
let closed = false,
@@ -232,7 +234,7 @@ export async function openLocalAgentRuntime(
workingDir: input.cwd,
providerId: input.model.provider,
model: input.model.model,
- effort: input.effort as StartSessionOptions['effort'],
+ effort: effort as StartSessionOptions['effort'],
userPrompt: instructions,
makerMemoryEnabled: false,
permissionMode: 'bypassPermissions',
@@ -299,8 +301,10 @@ export async function openLocalAgentRuntime(
const claimed =
event.type === 'done' && next.beginTurnContinuationWait(event.turnContinuationId) !== null;
projection.accept(event, !claimed);
- if (!preparing && !claimed && next.getObservedCurrentTurnTerminal().kind !== 'none')
+ if (!preparing && !claimed && next.getObservedCurrentTurnTerminal().kind !== 'none') {
busy = false;
+ releaseInputs();
+ }
});
next.onStatusChange((status) => {
if (status === 'closed') unsubscribe();
@@ -326,6 +330,11 @@ export async function openLocalAgentRuntime(
),
).catch(() => {});
};
+ // Inputs the engine took during the current turn; it no longer reads them once the turn settles.
+ let turnInputs: UserMessage[] = [];
+ const releaseInputs = () => {
+ for (const content of turnInputs.splice(0)) void discard(content);
+ };
const message = async (params: Record<string, unknown>): Promise<UserMessage> => {
if (!Array.isArray(params.parts) || !params.parts.length || params.parts.length > 64)
throw new LocalAgentError('INVALID_INPUT', '消息内容无效。');
@@ -419,6 +428,7 @@ export async function openLocalAgentRuntime(
assertCurrent(current);
if (!busy) throw new LocalAgentError('NOT_RUNNING', '当前没有正在运行的回答。');
await handle.steer(content);
+ turnInputs.push(content);
} catch (error) {
await discard(content);
throw error;
@@ -441,14 +451,18 @@ export async function openLocalAgentRuntime(
handle = await start(previous.sdkSessionId, current);
appliedInstructions = applying;
}
- if (params.effort !== undefined)
+ if (params.effort !== undefined) {
await handle.setEffort(params.effort as Parameters<Session['setEffort']>[0]);
+ effort = string(params.effort);
+ }
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;
+ releaseInputs();
+ turnInputs.push(sending);
void (async () => {
const result = await handle.send(sending);
if (!result.accepted) await discard(sending);
@@ -478,7 +492,8 @@ export async function openLocalAgentRuntime(
++epoch;
busy = false;
await handle.close({ reason: 'account-boundary' });
- await fs.rm(temporary, { recursive: true, force: true });
+ // The engine is confirmed closed; leftover input files must not report it as still running.
+ await fs.rm(temporary, { recursive: true, force: true }).catch(() => {});
},
};
}
diff --git a/apps/desktop/src/main/local-agent/server.ts b/apps/desktop/src/main/local-agent/server.ts
index 13ac6cf2f4..18b3e64002 100644
--- a/apps/desktop/src/main/local-agent/server.ts
+++ b/apps/desktop/src/main/local-agent/server.ts
@@ -535,8 +535,20 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {
'本机接入的恢复记录已满,请在 Cindy 中撤销连接后重新连接。',
);
run.resumeKey = binding && resumeKey ? resumeKey : token();
- bindings[run.resumeKey] = { owner: grant.id, model: model.id, native: run.runtime.id };
- await persist();
+ const key = run.resumeKey,
+ prior = bindings[key],
+ added = { owner: grant.id, model: model.id, native: run.runtime.id };
+ bindings[key] = added;
+ try {
+ await persist();
+ } catch (error) {
+ // The caller never receives this handle; keep a resumable prior binding intact.
+ if (bindings[key] === added) {
+ if (prior) bindings[key] = prior;
+ else delete bindings[key];
+ }
+ throw error;
+ }
assertGrant(grant);
return { id: run.resumeKey, resumed: run.runtime.resumed, sessionId };
} catch (error) {