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(plugins): 修正运行接口的隔离与时序

liugaowei8a0b717f18b6
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/harnessSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/harnessSlot.test.ts
index f85a6469b5..30ab7b7d4f 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/harnessSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/harnessSlot.test.ts
@@ -5,7 +5,7 @@ import { GhostHarnessSlot } from '../harnessSlot.js';
import { GhostSubscriptionGateway } from '../subscriptionGateway.js';
import type { GhostPipeEventPush, InstalledGhost } from '../../../shared/ghost.js';
-function fixture() {
+function fixture(remote: { remoteHostId?: string; agentDeviceId?: string } = {}) {
let owner = true;
let live = true;
let nativeId = 'native-1';
@@ -43,6 +43,8 @@ function fixture() {
id: 's',
agentKind: 'codex',
model: 'model',
+ remoteHostId: remote.remoteHostId ?? null,
+ agentDeviceId: remote.agentDeviceId ?? null,
get requestSessionId() {
return nativeId;
},
@@ -62,18 +64,18 @@ function fixture() {
actions: ['turn.interrupt'],
}),
runHarnessAction: vi.fn(async () => ({ ok: true, value: { state: 'requested' } })),
- setHarnessHookHandler: (handler: HarnessHookHandler) => {
+ setHarnessHookHandler: vi.fn((handler: HarnessHookHandler) => {
hook = handler;
return () => {
hook = undefined;
};
- },
- onEvent: (handler: (event: AgentEvent) => void) => {
+ }),
+ onEvent: vi.fn((handler: (event: AgentEvent) => void) => {
observe = handler;
return () => {
observe = undefined;
};
- },
+ }),
} as unknown as Session;
const eligible = vi.fn(async (): Promise<'eligible' | 'ineligible' | 'retry'> => 'eligible');
const readHistory = vi.fn(async () => ({
@@ -128,6 +130,62 @@ function fixture() {
afterEach(() => vi.useRealTimers());
describe('Harness host bridge', () => {
+ // Unit regressions for the local-only, per-turn and per-runtime contracts.
+ // Existing cases only used local bindings and current event generations.
+ it.each([{ remoteHostId: 'ssh-host' }, { agentDeviceId: 'other-device' }])(
+ 'does not bind remote execution %j', async (remote) => {
+ const f = fixture(remote);
+ expect(await f.slot.handleRequest('a', {
+ kind: 'read', name: 'runtime', sessionId: 's',
+ }, () => true)).toMatchObject({ errorCode: 'SESSION_UNAVAILABLE' });
+ expect(f.session.setHarnessHookHandler).not.toHaveBeenCalled();
+ expect(f.session.onEvent).not.toHaveBeenCalled();
+ f.dispose();
+ },
+ );
+
+ it('drops old turn events before publishing or replacing usage', async () => {
+ const f = fixture();
+ await f.slot.handleRequest('a', { kind: 'read', name: 'usage', sessionId: 's' }, () => true);
+ f.emit({ type: 'done', sessionTurnGeneration: 1, data: { usage: { inputTokens: 10 } } });
+ f.emit({ type: 'done', sessionTurnGeneration: 0, data: { usage: { inputTokens: 999 } } });
+ f.emit({ type: 'tool_result_full', sessionTurnGeneration: 0,
+ data: { toolUseId: 'old', fullText: 'old result' } });
+ f.emit({ type: 'tool_result_full', sessionTurnGeneration: 1,
+ data: { toolUseId: 'current', fullText: 'current result' } });
+ expect(f.events).toHaveLength(1);
+ expect(f.events[0]).toMatchObject({ name: 'tool.completed', data: { turnGeneration: 1 } });
+ expect(await f.slot.handleRequest('a', {
+ kind: 'read', name: 'usage', sessionId: 's',
+ }, () => true)).toMatchObject({ value: { inputTokens: 10 } });
+ f.dispose();
+ });
+
+ it('resets an old hook opt-out before selecting the new runtime recipients', async () => {
+ const f = fixture();
+ f.ghosts[1].enabled = false;
+ const runtime = await f.slot.handleRequest('a', {
+ kind: 'read', name: 'runtime', sessionId: 's',
+ }, () => true) as { runtimeId: string };
+ await f.slot.handleRequest('a', {
+ kind: 'hook', name: 'permission.request', sessionId: 's',
+ runtimeId: runtime.runtimeId, enabled: false,
+ }, () => true);
+ f.changeNative();
+ const decision = f.screen();
+ try {
+ await vi.waitFor(() => expect(f.messages).toHaveLength(1));
+ const sent = f.messages[0].payload;
+ if (sent.type !== 'harness-hook') throw new Error('expected hook');
+ expect(sent.data.runtimeId).not.toBe(runtime.runtimeId);
+ f.slot.handleVerdict('a', { hookId: sent.hookId, action: 'block' });
+ expect(await decision).toMatchObject({ action: 'block' });
+ } finally {
+ f.dispose();
+ await decision;
+ }
+ });
+
it('releases an outstanding decision when its hook is unregistered and ignores the late verdict', async () => {
const f = fixture();
f.ghosts[1].enabled = false;
diff --git a/apps/desktop/src/main/cindy-brain/harnessSlot.ts b/apps/desktop/src/main/cindy-brain/harnessSlot.ts
index 847fa00ed4..9a16c39c23 100644
--- a/apps/desktop/src/main/cindy-brain/harnessSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/harnessSlot.ts
@@ -88,6 +88,8 @@ export class GhostHarnessSlot {
constructor(private readonly deps: GhostHarnessSlotDeps) {}
bind(session: Session, isCurrent: () => boolean): () => void {
+ // This bridge covers local execution only; remote sessions use separate authority.
+ if (session.remoteHostId || session.agentDeviceId) return () => {};
const owner = this.deps.ownerScope.capture();
const binding: Binding = {
session,
@@ -408,6 +410,8 @@ export class GhostHarnessSlot {
if (
binding.eligibilityState === 'ineligible' ||
!binding.current() ||
+ (event.sessionTurnGeneration !== undefined &&
+ event.sessionTurnGeneration !== binding.session.getTurnGeneration()) ||
// Pi marks idle manual compaction as background work within this task.
(event.turnScope === 'background' && !(event.type === 'compact_boundary' && raw.trigger === 'manual')) ||
event.runtimeRecovery ||
@@ -525,6 +529,7 @@ export class GhostHarnessSlot {
}
private async screen(binding: Binding, request: HarnessHookRequest): Promise<HarnessHookResult> {
+ this.sync(binding);
const ghosts = this.deps
.listGhosts()
.filter(
diff --git a/packages/maker-core/src/session.harness.test.ts b/packages/maker-core/src/session.harness.test.ts
index 0f8cf651d6..efe9150cbe 100644
--- a/packages/maker-core/src/session.harness.test.ts
+++ b/packages/maker-core/src/session.harness.test.ts
@@ -58,6 +58,61 @@ function fixture() {
}
describe("Session Harness hooks preserve permission authority", () => {
+ // Unit regressions: waiting interactions must still stop, while user input
+ // cannot join the native compact lane, including after async preparation.
+ it('interrupts a turn waiting for permission while keeping compaction blocked', async () => {
+ vi.useFakeTimers();
+ const f = fixture();
+ f.handle.isTurnRunning = () => true;
+ f.handle.abort = vi.fn(async () => {});
+ f.handle.requestHarnessCompaction = vi.fn(async () => ({ noop: true }));
+ let release!: (value: InteractionDecision) => void;
+ const waiting = f.session.runHostInteraction(f.request, () => new Promise(resolve => { release = resolve; }));
+ try {
+ expect(await f.session.runHarnessAction('context.compact', 0)).toMatchObject({ errorCode: 'BUSY' });
+ expect(await f.session.runHarnessAction('turn.interrupt', 0)).toMatchObject({ ok: true, value: { state: 'requested' } });
+ expect(f.handle.abort).toHaveBeenCalledOnce();
+ expect(f.handle.requestHarnessCompaction).not.toHaveBeenCalled();
+ } finally {
+ release({ kind: 'permission', behavior: 'deny' });
+ await waiting;
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ }
+ });
+
+ it.each([false, true])('rejects steering during compaction after preparation=%s', async (afterPreparation) => {
+ const f = fixture();
+ let running = afterPreparation;
+ let finish!: () => void;
+ f.session.capabilities.sameTurnSteer = { supported: true };
+ f.handle.isTurnRunning = () => running;
+ f.handle.steer = vi.fn(async () => {});
+ f.handle.requestHarnessCompaction = () => {
+ running = true;
+ return new Promise<{ noop: true }>(resolve => { finish = () => { running = false; resolve({ noop: true }); }; });
+ };
+ let release!: () => void;
+ let prepared!: () => void;
+ const entered = new Promise<void>(resolve => { prepared = resolve; });
+ const held = new Promise<void>(resolve => { release = resolve; });
+ const pending = afterPreparation ? f.session.steer('late input', {
+ beforeProviderStart: () => { prepared(); return held; },
+ }) : undefined;
+ if (afterPreparation) await entered;
+ running = false;
+ const compact = f.session.runHarnessAction('context.compact', 0);
+ try {
+ const rejected = expect(pending ?? f.session.steer('new input')).rejects.toThrow('no active turn to steer');
+ release();
+ await rejected;
+ expect(f.handle.steer).not.toHaveBeenCalled();
+ } finally {
+ finish();
+ await compact;
+ }
+ });
+
// Unit regression for the Desktop pre-dispatch cancellation repro: two sends
// reserve the same number, but a late permission verdict must stay with the
// first attempt. Existing native-id-change coverage never reused a generation.
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index 1f5a195c12..697488796c 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -1204,7 +1204,7 @@ export class Session {
if (!this.capabilities.sameTurnSteer.supported) {
throw new NotSupportedError('sameTurnSteer', this.capabilities.sameTurnSteer);
}
- if (!this.handle.isTurnRunning?.()) {
+ if (this.harnessActionInFlight || !this.handle.isTurnRunning?.()) {
throw new Error(`Session ${this.id} has no active turn to steer`);
}
// 记录发起时的 turn generation:异步视觉转换期间原 turn 可能结束、同 Session
@@ -1226,7 +1226,7 @@ export class Session {
// 异步视觉转换期间 turn 可能已完成/被中止(视觉后端慢、用户已切任务等):
// 转换结果此时已无人接收,必须先复查原 turn 生命周期再调用 handle.steer,
// 否则底层以「No active turn to steer」拒绝或 Pi 把迟到消息交给已结束的 turn。
- if (this.getTurnGeneration() !== steerTurnGeneration || !this.handle.isTurnRunning?.()) {
+ if (this.harnessActionInFlight || this.getTurnGeneration() !== steerTurnGeneration || !this.handle.isTurnRunning?.()) {
throw new Error(`Session ${this.id} has no active turn to steer`);
}
this.startEventLoopIfNeeded();
@@ -1708,9 +1708,9 @@ export class Session {
async runHarnessAction(name: 'context.compact' | 'turn.interrupt', expectedGeneration: number) {
this.ensureActive();
if (expectedGeneration !== this.turnGeneration) return { ok: false as const, errorCode: 'STALE_RUNTIME' as const };
- if (this.harnessActionInFlight || this.pendingInteractions > 0 || this.permissionModeChangesInFlight > 0)
+ if (this.harnessActionInFlight || this.permissionModeChangesInFlight > 0)
return { ok: false as const, errorCode: 'BUSY' as const };
- if (name === 'context.compact' && (this.isTurnRunning() || this.hasUnsettledTurn()))
+ if (name === 'context.compact' && (this.pendingInteractions > 0 || this.isTurnRunning() || this.hasUnsettledTurn()))
return { ok: false as const, errorCode: 'BUSY' as const };
if (!this.getHarnessCapabilities().actions.includes(name))
return { ok: false as const, errorCode: 'UNAVAILABLE' as const };