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(session): bound hung stall abort and isolate retirement recovery

Cursor Agent24539b9219ce
diff --git a/apps/desktop/src/main/__tests__/directSessionSendGuard.test.ts b/apps/desktop/src/main/__tests__/directSessionSendGuard.test.ts
index 5f9ce86ec5..2d06d6c350 100644
--- a/apps/desktop/src/main/__tests__/directSessionSendGuard.test.ts
+++ b/apps/desktop/src/main/__tests__/directSessionSendGuard.test.ts
@@ -180,9 +180,10 @@ function findDirectSendViolations(program: ts.Program): SendViolation[] {
function isMakerSessionSendCall(node: ts.CallExpression, checker: ts.TypeChecker): boolean {
if (!ts.isPropertyAccessExpression(node.expression)) return false;
- if (node.expression.name.text !== 'send') return false;
+ const methodName = node.expression.name.text;
+ if (methodName !== 'send' && methodName !== 'sendHostTurnContinuation') return false;
const receiverType = checker.getTypeAtLocation(node.expression.expression);
- const sendSymbol = receiverType.getProperty('send') ?? checker.getSymbolAtLocation(node.expression.name);
+ const sendSymbol = receiverType.getProperty(methodName) ?? checker.getSymbolAtLocation(node.expression.name);
const declarations = sendSymbol?.getDeclarations() ?? [];
return declarations.some((declaration) => {
const sourceFile = normalizePath(declaration.getSourceFile().fileName);
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
index bd9fca9a19..cea4a49ad7 100644
--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
@@ -143,7 +143,7 @@ describe('maker:event hot path ordering', () => {
expectOrder(
continuation,
'productTurnWallClockTracker.preserveForContinuation(session.id);',
- 'const sendResult = await session.send(',
+ 'const sendResult = await session.sendHostTurnContinuation(',
);
});
diff --git a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts b/apps/desktop/src/main/goal-host/__tests__/controller.test.ts
index d5a81dfbe1..8e4a63632b 100644
--- a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/goal-host/__tests__/controller.test.ts
@@ -2101,6 +2101,38 @@ describe('GoalController', () => {
expect((await h.storage.get('s1'))?.tokensUsed).toBe(777);
});
+ it('does not let a post-terminal runtimeRecovery receipt replace Goal verdict text', async () => {
+ await startGoal(h);
+ const active = await h.storage.get('s1');
+ let releaseGet!: (state: GoalState | null) => void;
+ const blockedGet = new Promise<GoalState | null>((resolve) => {
+ releaseGet = resolve;
+ });
+ vi.spyOn(h.storage, 'get').mockReturnValueOnce(blockedGet);
+
+ h.session.emit({ type: 'tool_use', data: { name: 'Bash' } } as never);
+ h.session.emit({
+ type: 'text',
+ data: { text: '```json\n{"goal_status":"complete","reason":"green"}\n```', isFinal: true },
+ } as never);
+ h.session.emit({ type: 'done', data: {}, turnOrigin: { kind: 'goal' } } as never);
+ h.session.emit({
+ type: 'text',
+ source: 'pi',
+ runtimeRecovery: true,
+ data: {
+ isFinal: true,
+ text: '[Cindy Pi package runtime convergence receipt]\n```json\n{"runtimeConvergence":"partial","recoveryAction":"restart-cindy-to-refresh-packages"}\n```',
+ },
+ } as never);
+
+ releaseGet(active);
+ await vi.waitFor(() => expect(h.completions).toHaveLength(1));
+ expect(await h.storage.get('s1')).toBeNull();
+ expect(h.completions[0]?.summary.reason).toBe('green');
+ expect(h.session.sends).toHaveLength(1);
+ });
+
it('on complete: persists a completion record, clears the row, emits null, no continuation', async () => {
await startGoal(h);
h.session.emitGoalTurn({ toolUse: true, verdictJson: '```json\n{"goal_status":"complete","reason":"green"}\n```', tokens: 42 });
diff --git a/apps/desktop/src/main/goal-host/controller.ts b/apps/desktop/src/main/goal-host/controller.ts
index d275b8fc98..11ecf78266 100644
--- a/apps/desktop/src/main/goal-host/controller.ts
+++ b/apps/desktop/src/main/goal-host/controller.ts
@@ -1765,6 +1765,9 @@ export class GoalController {
private onEvent(sessionId: string, event: AgentEvent): void {
if (this.disposed) return;
+ // Host-only recovery notice after deferred Pi retirement. Independent of the
+ // product turn: never treat it as Goal assistant text / verdict input.
+ if (event.runtimeRecovery) return;
let turn = this.turns.get(sessionId);
if (!turn) {
turn = freshTurn();
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnLease.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnLease.test.ts
index 9befebfda3..79972abac5 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnLease.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnLease.test.ts
@@ -349,7 +349,7 @@ describe('shared-process session turn lease', () => {
finish();
await vi.waitFor(() => expect(seen).toHaveLength(1));
expect(handle.close).not.toHaveBeenCalled();
- if (successor) await runtime.send('already authorized continuation');
+ if (successor) await runtime.sendHostTurnContinuation('already authorized continuation');
fail = true;
await expect(tracker.markTurnEndedAndCheckIdle('source-1', 'turn',
() => runtime.settleHostTurnContinuation(generation))).rejects.toThrow(`injected lease ${stage} failure`);
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 36c2813406..f2b1664d92 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -4146,7 +4146,7 @@ async function handleSilentStopTurnEnd(
// Mark it before send(), which may synchronously emit status events.
productTurnWallClockTracker.preserveForContinuation(session.id);
const clientId = randomUUID();
- const sendResult = await session.send(
+ const sendResult = await session.sendHostTurnContinuation(
{ type: 'user', content: SILENT_STOP_RESUME_PROMPT },
{
origin: turnOrigin,
diff --git a/packages/maker-core/src/session.close.test.ts b/packages/maker-core/src/session.close.test.ts
index 5704e0b37d..0a564fc8fb 100644
--- a/packages/maker-core/src/session.close.test.ts
+++ b/packages/maker-core/src/session.close.test.ts
@@ -163,7 +163,7 @@ describe('Session close lifecycle', () => {
expect(await session.closeAfterCurrentTurn()).toBe('deferred');
expect(await session.closeIfIdle()).toBe(false);
expect(handle.close).not.toHaveBeenCalled();
- await session.send('continue'); // Host owns the existing bounded budget.
+ await session.sendHostTurnContinuation('continue'); // Host owns the existing bounded budget.
idle();
queue.push({ type: 'done', source: 'pi', data: { status: 'completed', result: 'delivered' } });
await vi.waitFor(() => expect(session.getStatus()).toBe('closed'));
@@ -171,6 +171,23 @@ describe('Session close lifecycle', () => {
expect(seen.at(-1)?.data).toMatchObject({ result: 'delivered' });
});
+ it('rejects a non-Host send while a retiring silent-stop claim is live', async () => {
+ const { session, handle, queue, seen, idle } = liveTurn();
+ await session.send('work');
+ await session.closeAfterCurrentTurn();
+ idle();
+ queue.push({ type: 'done', source: 'pi', data: { status: 'completed', silentStop: true } });
+ await vi.waitFor(() => expect(seen).toHaveLength(1));
+ await expect(session.send('user follow-up')).rejects.toThrow(/closing/);
+ expect(handle.send).toHaveBeenCalledOnce();
+ expect(handle.close).not.toHaveBeenCalled();
+ await session.sendHostTurnContinuation('continue');
+ idle();
+ queue.push({ type: 'done', source: 'pi', data: { status: 'completed', result: 'delivered' } });
+ await vi.waitFor(() => expect(session.getStatus()).toBe('closed'));
+ expect(handle.send).toHaveBeenCalledTimes(2);
+ });
+
it('does not retire at a provider boundary with an outstanding continuation claim', async () => {
const { session, handle, queue, seen, idle } = liveTurn();
handle.beginTurnContinuationWait = (id) => id === 4 ? 'awaiting' : null;
@@ -247,7 +264,7 @@ describe('Session close lifecycle', () => {
idle();
queue.push({ type: 'done', source: 'pi', data: { status: 'completed', silentStop: true } });
await vi.waitFor(() => expect(seen).toHaveLength(1));
- await session.send('continue');
+ await session.sendHostTurnContinuation('continue');
session.settleHostTurnContinuation(generation);
expect(handle.close).not.toHaveBeenCalled();
idle();
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index 45e3edaae3..14feb2665f 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -699,6 +699,26 @@ export class Session {
}
async send(message: UserMessage | string, opts?: SessionSendOptions): Promise<SessionSendResult> {
+ return this.dispatchSend(message, opts, false);
+ }
+
+ /**
+ * Host-owned silent-stop continuation. This is the only send admitted while a
+ * retiring runtime has claimed the current generation; ordinary `send()` stays
+ * rejected so queued/user work cannot run on the snapshot being retired.
+ */
+ async sendHostTurnContinuation(
+ message: UserMessage | string,
+ opts?: SessionSendOptions,
+ ): Promise<SessionSendResult> {
+ return this.dispatchSend(message, opts, true);
+ }
+
+ private async dispatchSend(
+ message: UserMessage | string,
+ opts: SessionSendOptions | undefined,
+ allowRetirementContinuation: boolean,
+ ): Promise<SessionSendResult> {
const {
afterTurnReserved,
beforeProviderStart,
@@ -741,8 +761,12 @@ export class Session {
: message;
this.logger.debug('send', summarizeUserMessage(msg));
this.ensureActive();
+ // A silent-stop claim keeps this generation alive for Host continuation only.
+ // Any other sender (user, queue, Goal, IM) must not start new work on a
+ // runtime that is already marked to retire after the current product turn.
if (this.retirementRequested
- && this.retirementContinuationGeneration !== this.turnGeneration) {
+ && (this.retirementContinuationGeneration !== this.turnGeneration
+ || !allowRetirementContinuation)) {
throw new Error(`Session ${this.id} is closing`);
}
if (this.terminalErrorDrainGeneration !== null) {
@@ -2893,7 +2917,15 @@ export class Session {
});
return;
}
- if (!this.isTurnRunning() && !this.hasUnsettledTurn()) return;
+ if (!this.isTurnRunning() && !this.hasUnsettledTurn()) {
+ // Watchdog may already have synthesized the missing terminal, which clears
+ // turnControlState. If abort() never returns, status stays aborting and a
+ // naive idle check would no-op — bypassing bounded recovery. Keep that
+ // in-flight abort as evidence this diagnosed generation must close.
+ if (this.status !== 'aborting' || this.abortRecoveryScheduledFor !== stalledGeneration) {
+ return;
+ }
+ }
this.logger.error(
'turn still running after abort — closing session so the next send can rebuild it',
{ trigger: ctx.trigger, graceMs: ctx.graceMs },
diff --git a/packages/maker-core/src/session.turn-stall.test.ts b/packages/maker-core/src/session.turn-stall.test.ts
index 404e85ccf8..038b48fe7c 100644
--- a/packages/maker-core/src/session.turn-stall.test.ts
+++ b/packages/maker-core/src/session.turn-stall.test.ts
@@ -124,6 +124,31 @@ function createSession(
}
describe('Session turn stall watchdog', () => {
+ it('closes an idle missing-terminal turn when stall abort never returns', async () => {
+ vi.useFakeTimers();
+ try {
+ const stub = createStubHandle({ abortHangs: true });
+ const session = createSession(stub);
+ const seen: AgentEvent[] = [];
+ session.onEvent((event) => seen.push(event));
+ await session.send('perform a side effect');
+ stub.endTurn();
+ await vi.advanceTimersByTimeAsync(STALL_MS + 1);
+ expect(seen).toContainEqual(expect.objectContaining({ type: 'error',
+ data: expect.objectContaining({ reason: 'turn_no_event_timeout', isTerminal: true }) }));
+ expect(stub.abort).toHaveBeenCalledTimes(1);
+ expect(session.getStatus()).toBe('aborting');
+ // A paired leftover done would clear the 250ms terminal-error drain. The
+ // hung abort must still force close this diagnosed generation.
+ stub.pushEvent({ type: 'done', data: {}, source: 'claude-code' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(session.getStatus()).toBe('aborting');
+ await vi.advanceTimersByTimeAsync(STALL_ABORT_RECOVERY_GRACE_MS + 1);
+ expect(session.getStatus()).toBe('closed');
+ expect(stub.handle.send).toHaveBeenCalledOnce();
+ } finally { vi.useRealTimers(); }
+ });
+
it('times out an accepted turn even if the provider went idle without delivering its terminal', async () => {
vi.useFakeTimers();
try {