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: 完善任务关闭清理并在 60 秒无新样本后隐藏速度 (#4816)

Dashb7a70f30274f
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
index 92cf22be62..d96d6c2bca 100644
--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
@@ -8,7 +8,7 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import { ScriptTarget, transpileModule } from 'typescript';
import type { AgentEvent } from '@cindy/maker-core';
@@ -25,6 +25,42 @@ const goalStorageSourcePath = resolve(__dirname, '..', 'goal-host', 'storage.ts'
const goalStorageSource = readFileSync(goalStorageSourcePath, 'utf8').replace(/\r\n?/g, '\n');
describe('maker:event hot path ordering', () => {
+ it('finishes mandatory runtime cleanup when optional remote refresh throws at an owner boundary', () => {
+ const start = source.indexOf('function cleanupClosedSessionRuntime(');
+ const code = source.slice(start, source.indexOf('\n// Keep holder reads', start));
+ const js = transpileModule(code, { compilerOptions: { target: ScriptTarget.ES2022 } }).outputText;
+ const cleared = vi.fn();
+ const deps = {
+ pendingCredentialSwitchHolder: null, deferredCodexRestartHolder: null,
+ agentInputCoordinatorHolder: null,
+ refreshRemoteCodexMcpOnTurnSettledHolder: () => { throw new Error('App session is switching'); },
+ gitSnapshotCoordinator: { onSessionClosed: vi.fn() },
+ clearOrcaMcpHydrated: vi.fn(), knownNonOrcaSessionIds: new Set(),
+ lastReportedCostUsdBySession: new Map(), lastReportedModelUsageBySession: new Map(),
+ turnModelPromiseBySession: new Map(), turnUsageContextBySession: new Map(),
+ productTurnWallClockTracker: { clear: cleared }, productTurnUsageTargetTracker: { clear: vi.fn() },
+ claudeOutputLagTimingGuard: { clear: vi.fn() }, clearClaudeSessionBackgroundActivity: vi.fn(),
+ clearSessionPersistState: vi.fn(), clearSubagentObservationRewindState: () => true,
+ handleAgentIslandSessionClosedAfterCleanup: vi.fn(), log: { warn: vi.fn() },
+ };
+ const cleanup = new Function(...Object.keys(deps), `${js}; return cleanupClosedSessionRuntime;`)(...Object.values(deps));
+ expect(() => cleanup({ id: 'departing-task' })).not.toThrow();
+ expect(cleared).toHaveBeenCalledWith('departing-task');
+ expect(deps.clearSessionPersistState).toHaveBeenCalledWith('departing-task');
+ expect(deps.handleAgentIslandSessionClosedAfterCleanup).toHaveBeenCalledWith('departing-task', 'process-closed');
+ });
+
+ it('does not read the guarded Maker during account-boundary remote refresh', () => {
+ const start = source.indexOf('refreshRemoteCodexMcpOnTurnSettledHolder = (sessionId: string): void => {');
+ const prefix = source.slice(start, source.indexOf(' const remoteHostId', start));
+ const js = transpileModule(`let refreshRemoteCodexMcpOnTurnSettledHolder; ${prefix}\n};`, {
+ compilerOptions: { target: ScriptTarget.ES2022 },
+ }).outputText;
+ const getSession = vi.fn(() => { throw new Error('App session is switching'); });
+ const refresh = new Function('isAppSessionBoundaryPending', 'maker', `${js}; return refreshRemoteCodexMcpOnTurnSettledHolder;`)(() => true, { getSession });
+ expect(() => refresh('departing-task')).not.toThrow();
+ expect(getSession).not.toHaveBeenCalled();
+ });
it.each([undefined, null, { text: 'Restart Cindy before using Pi again.', isFinal: true }])(
'strips Host recovery metadata from the boundary copy with data %j',
(data) => {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 56713ecb46..6faf83ddd1 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -4423,7 +4423,14 @@ function cleanupClosedSessionRuntime(session: WiredSession): void {
pendingCredentialSwitchHolder?.onSessionClosed(session.id);
deferredCodexRestartHolder?.onSessionSettled();
agentInputCoordinatorHolder?.onExternalTurnSettled(session.id);
- refreshRemoteCodexMcpOnTurnSettledHolder?.(session.id);
+ try {
+ refreshRemoteCodexMcpOnTurnSettledHolder?.(session.id);
+ } catch (error) {
+ log.warn('optional remote MCP refresh failed during session close', {
+ sessionId: session.id,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
gitSnapshotCoordinator?.onSessionClosed(session.id);
clearOrcaMcpHydrated(session.id);
knownNonOrcaSessionIds.delete(session.id);
@@ -7364,6 +7371,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// holder 供各 turn 收口路径调用。远端 CC 走 holder 的 detach 补偿
// (bridge 重建 / 端口重绑已让 fresh 失效时重建 query)。
refreshRemoteCodexMcpOnTurnSettledHolder = (sessionId: string): void => {
+ // Shutdown closes sessions while the dynamic Maker facade rejects access.
+ // No remote reconfiguration belongs to the departing owner's boundary.
+ if (isAppSessionBoundaryPending()) return;
const session = maker.getSession(sessionId);
const remoteHostId = session?.remoteHostId;
if (!remoteHostId) return;
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts
index fa53e0902e..736d0c9236 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts
@@ -1671,6 +1671,27 @@ describe('computer mcp integration', () => {
expect(events).toEqual(['type_text', 'type_text', 'type_text', 'launch_app']);
});
+ it('stops remaining text chunks on session close and releases input only after the in-flight call settles', async () => {
+ const first = createDeferred<unknown>();
+ const events: string[] = [];
+ mcpCallToolMock.mockImplementation(({ name }) => {
+ events.push(name);
+ if (name === 'type_text') return first.promise;
+ return { structuredContent: { ok: true, effect: 'confirmed' } };
+ });
+ const typing = callComputerDriverTool('type_text', { pid: 123, text: 'a'.repeat(850) }, { sessionId: 'closing-input' });
+ const rejected = expect(typing).rejects.toBeDefined();
+ await waitForCondition(() => events.includes('type_text'));
+ await cleanupComputerDriverSession('closing-input');
+ const next = callComputerDriverTool('launch_app', { name: 'Calculator' }, { sessionId: 'after-close' });
+ await waitForCondition(() => transportCtorMock.mock.calls.length === 2);
+ expect(events).not.toContain('launch_app');
+ first.resolve({ structuredContent: { ok: true, effect: 'confirmed' } });
+ await Promise.all([rejected, next]);
+ expect(events.filter((name) => name === 'type_text')).toHaveLength(1);
+ expect(events.filter((name) => name === 'launch_app')).toHaveLength(1);
+ });
+
it('holds ownership through failed-input teardown before admitting the next Agent', async () => {
const input = createDeferred<unknown>();
const teardown = createDeferred<unknown>();
diff --git a/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx b/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx
index 11c082bc55..b96c18e824 100644
--- a/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/runningStatusBarSuppression.test.tsx
@@ -109,7 +109,9 @@ it.each([false, true])('reconnect hides stale speed and pinned history, then wai
// Recovery must not redisplay the pre-interruption 46.5 tok/s.
rerender(<RunningStatusBar {...measured} />);
expect(screen.getByText('Generating...')).toBeTruthy();
- expect(trigger()?.textContent).toContain('chat.runningStatus.waitingSample');
+ expect(trigger()).not.toBeNull();
+ expect(trigger()?.textContent).not.toContain('chat.runningStatus.waitingSample');
+ expect(trigger()?.textContent).not.toContain('chat.runningStatus.tokenRate');
expect(screen.queryByRole('dialog')).toBeNull();
rerender(<RunningStatusBar {...measured} outputTokens={515} generationDurationMs={11000} />);
expect(trigger()?.textContent).toContain('chat.runningStatus.tokenRate');
diff --git a/apps/desktop/src/renderer/__tests__/runningTokenRatePopover.test.tsx b/apps/desktop/src/renderer/__tests__/runningTokenRatePopover.test.tsx
index c42a1bb270..258f619711 100644
--- a/apps/desktop/src/renderer/__tests__/runningTokenRatePopover.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/runningTokenRatePopover.test.tsx
@@ -20,6 +20,31 @@ vi.mock('react-i18next', () => ({
}));
afterEach(cleanup);
+it('expires the displayed rate without losing history, including after remount', () => {
+ vi.useFakeTimers();
+ try {
+ clearRateHistoryCache();
+ function Probe({ tokens }: { tokens: number }) {
+ const history = useRunningTokenRateHistory({ sessionKey: 'freshness', startedAt: 1,
+ outputTokens: tokens, generationDurationMs: tokens * 10, generationReliable: true });
+ return <div data-testid="rate">{history.latestRate ?? 'waiting'}:{history.samples.length}</div>;
+ }
+ const view = render(<Probe tokens={0} />);
+ view.rerender(<Probe tokens={100} />);
+ expect(screen.getByTestId('rate').textContent).toBe('100:1');
+ act(() => vi.advanceTimersByTime(59_999));
+ expect(screen.getByTestId('rate').textContent).toBe('100:1');
+ act(() => vi.advanceTimersByTime(1));
+ expect(screen.getByTestId('rate').textContent).toBe('waiting:1');
+ view.unmount();
+ const again = render(<Probe tokens={100} />);
+ expect(screen.getByTestId('rate').textContent).toBe('waiting:1');
+ again.rerender(<Probe tokens={200} />);
+ expect(screen.getByTestId('rate').textContent).toBe('100:2');
+ again.unmount();
+ } finally { clearRateHistoryCache(); vi.useRealTimers(); }
+});
+
it('distinguishes an unobserved peak from measured zero throughput', () => {
const props = {
elapsedText: '1s',
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index a7e95c11af..eb1e0e498b 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -5933,7 +5933,7 @@ function RunningStatusBar({
!isHidden && !reconnecting && usageMeta.kind === 'rate'
? latestRateText !== null
? t('chat.runningStatus.tokenRate', { rate: latestRateText })
- : t('chat.runningStatus.waitingSample')
+ : null
: null;
// 淡入淡出/隐藏占位样式 —— 同时作用于左(状态)、右(elapsed/tokens)两段。
@@ -5951,7 +5951,6 @@ function RunningStatusBar({
(!workflowWaiting &&
!sideTaskRunning &&
!backgroundTasksRunning &&
- Boolean(rateText) &&
usageMeta.kind === 'rate'));
// A pinned panel keeps its anchor mounted through idle and subsequent turns.
// 空闲后真正收起,不再给输入框上方留下固定空行。overlay 的 ResizeObserver 会在
diff --git a/apps/desktop/src/renderer/features/cc-agent/RunningTokenRatePopover.tsx b/apps/desktop/src/renderer/features/cc-agent/RunningTokenRatePopover.tsx
index a474a89f24..665e3ddf13 100644
--- a/apps/desktop/src/renderer/features/cc-agent/RunningTokenRatePopover.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/RunningTokenRatePopover.tsx
@@ -9,6 +9,7 @@ import {
loadCachedRateHistory,
recordRunningTokenRate,
saveCachedRateHistory,
+ RATE_SAMPLE_FRESH_MS,
type RateHistory,
} from './lib/runningTokenRateHistory';
@@ -43,8 +44,20 @@ export function useRunningTokenRateHistory(input: {
useEffect(() => {
if (sessionKey) saveCachedRateHistory(sessionKey, history);
}, [sessionKey, history]);
+ const [now, setNow] = useState(Date.now);
+ useEffect(() => {
+ const timestamp = history.latestSampleAt;
+ if (timestamp === undefined || history.latestRate === null) return;
+ setNow(Date.now());
+ const timer = setTimeout(() => setNow(Date.now()),
+ Math.max(0, timestamp + RATE_SAMPLE_FRESH_MS - Date.now()));
+ return () => clearTimeout(timer);
+ }, [history.latestSampleAt, history.latestRate]);
+ const visibleHistory = history.latestSampleAt === undefined ||
+ Math.max(now, Date.now()) - history.latestSampleAt >= RATE_SAMPLE_FRESH_MS
+ ? { ...history, latestRate: null } : history;
return startedAt === null || history.startedAt === startedAt
- ? history
+ ? visibleHistory
: { ...history, startedAt, baseline: null, latestRate: null };
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/runningTokenRateHistory.ts b/apps/desktop/src/renderer/features/cc-agent/lib/runningTokenRateHistory.ts
index 2b40c5f4c7..81434368a3 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/runningTokenRateHistory.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/runningTokenRateHistory.ts
@@ -11,6 +11,7 @@ export interface RateSample extends RateCounters {
// Millisecond-scale usage batches are not meaningful throughput measurements.
const MIN_SAMPLE_DURATION_MS = 1000;
+export const RATE_SAMPLE_FRESH_MS = 60_000;
export interface RateHistory {
startedAt: number | null;
@@ -20,6 +21,7 @@ export interface RateHistory {
samples: RateSample[];
peak: number;
latestRate: number | null;
+ latestSampleAt?: number;
}
export function emptyRateHistory(startedAt: number | null): RateHistory {
@@ -36,6 +38,7 @@ export function recordRunningTokenRate(
outputTokens: number;
generationDurationMs: number;
generationReliable: boolean;
+ now?: number;
},
): RateHistory {
const { outputTokens, generationDurationMs, generationReliable } = input;
@@ -105,6 +108,7 @@ export function recordRunningTokenRate(
samples,
peak: Math.max(...samples.map((sample) => sample.rate)),
latestRate: rate,
+ latestSampleAt: input.now ?? Date.now(),
};
}
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index b455f81ef4..ef5ba673f8 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -6,6 +6,7 @@ import { applyPatch, formatPatch, parsePatch, reversePatch } from 'diff';
import { CodexAgent, isExactNoRolloutThreadResumeError } from './index.js';
import { CodexForkError } from './fork-error.js';
+import { Session } from '../../session.js';
import { Method } from './app-server/protocol.js';
import type { ThreadEventHandlers } from './app-server/host.js';
import {
@@ -7053,6 +7054,65 @@ describe('CodexAgent MCP thread context hooks', () => {
await handle.close();
});
+ it('closes an in-flight turn when external dispose retires its host', async () => {
+ const agent = new CodexAgent(createDeps());
+ const handle = await agent.startSession({
+ sessionId: 'session-dispose-active-turn',
+ model: 'gpt-5.4',
+ workingDir: '/repo-local',
+ });
+ const iterator = handle.events()[Symbol.asyncIterator]();
+ const transport = createdTransports[0];
+ const clearIntervalSpy = vi.spyOn(globalThis, 'clearInterval');
+
+ transport.emitMockLine({
+ method: 'turn/started',
+ params: { threadId: 'thread-1', turn: { id: 'turn-dispose-active' } },
+ });
+ await waitForExpectation(() => {
+ expect(handle.isTurnRunning?.()).toBe(true);
+ });
+
+ await agent.dispose();
+
+ expect(clearIntervalSpy).toHaveBeenCalledOnce();
+ expect(handle.isTurnRunning?.()).toBe(false);
+ await expect(nextEvent(iterator)).resolves.toMatchObject({
+ type: 'error',
+ data: expect.objectContaining({
+ isTerminal: true,
+ willRetry: false,
+ message: expect.stringContaining('app-server force-retired'),
+ }),
+ });
+ await expect(nextEvent(iterator)).resolves.toMatchObject({
+ type: 'status',
+ data: expect.objectContaining({ status: 'Done', isRunning: false }),
+ });
+
+ await handle.close();
+ });
+
+ it('propagates global disposal through Session closure without replaying the input', async () => {
+ const deps = createDeps();
+ const agent = new CodexAgent(deps);
+ const handle = await agent.startSession({ sessionId: 'dispose-session', model: 'gpt-5.4', workingDir: '/repo' });
+ const send = vi.spyOn(handle, 'send');
+ const session = new Session({ id: 'dispose-session', agentKind: 'codex', workDir: '/repo',
+ handle, capabilities: {} as never, logger: deps.logger, turnStallMs: 0 });
+ const statuses: string[] = [];
+ const events: CoreAgentEvent[] = [];
+ session.onStatusChange((status) => statuses.push(status));
+ session.onEvent((event) => events.push(event));
+ await session.send('perform one input');
+ await Promise.all([agent.dispose(), agent.dispose()]);
+ await waitForExpectation(() => expect(session.getStatus()).toBe('closed'));
+ expect(statuses.filter((status) => status === 'closed')).toHaveLength(1);
+ expect(events.filter((event) => event.type === 'error')).toHaveLength(1);
+ expect(send).toHaveBeenCalledOnce();
+ expect(handle.isTurnRunning?.()).toBe(false);
+ });
+
it('force-retires one shared local Host under the credential guard and blocks its lazy replacement', async () => {
const getRemoteCodexTransport = vi.fn(() => {
const transport = new MockCodexTransport();
@@ -23600,7 +23660,7 @@ describe('CodexAgent resume preparation', () => {
}));
const host = installFakeHost(agent);
try {
- await expect(agent.forkSdkSession({ sourceSdkSessionId: resumeSessionId, workingDir: root })).rejects.toThrow();
+ await expect(agent.forkSdkSession({ sourceSdkSessionId: resumeSessionId, upToMessageId: 'missing-message', workingDir: root })).rejects.toThrow();
expect(host.getHost).not.toHaveBeenCalled();
expect(host.request).not.toHaveBeenCalled();
} finally {
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 873693e108..fd0bdf4fc3 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -11516,6 +11516,13 @@ export class CodexAgent extends BaseAgent {
|| overloadRetryPending()
|| yieldContinuationInFlight
|| activeYieldContinuationClaim() != null;
+ log.info('Codex session forced retirement received', {
+ threadId,
+ turnId: currentTurnId,
+ reason,
+ hadPendingWork,
+ pendingToolCount: pendingToolItemIds.size,
+ });
if (!hadPendingWork) {
log.info('idle Codex session invalidated by forced host retirement', { threadId });
eventQueue.end();
@@ -14545,11 +14552,24 @@ export class CodexAgent extends BaseAgent {
});
}
}
- for (const [key, host] of this.hosts) {
- this.beginHostRetirement(key, host, 'CodexAgent.dispose()');
+ // `dispose()` is normally used during app shutdown, but auth/config
+ // boundaries can reach it while a turn is still attached. Retiring a
+ // host silently clears its subscribers; without the same structured
+ // notification used by `retireHostKey(..., failIfActive: false)`, an
+ // in-flight Computer Use turn remains busy forever after its transport
+ // disappears. Notify hosts before retirement so the
+ // session can emit its terminal interruption and release its input/turn
+ // ownership.
+ const hostsToRetire = new Map<string, AppServerHost>();
+ for (const [key, host] of this.hosts) hostsToRetire.set(key, host);
+ for (const [key, entry] of this.retiringHosts) {
+ if (!hostsToRetire.has(key)) hostsToRetire.set(key, entry.host);
+ }
+ const retirements: Promise<void>[] = [];
+ for (const [key, host] of hostsToRetire) {
+ host.notifySubscribersOfForcedRetire('CodexAgent.dispose()');
+ retirements.push(this.beginHostRetirement(key, host, 'CodexAgent.dispose()'));
}
- const retirements = Array.from(this.retiringHosts, ([key, entry]) =>
- this.beginHostRetirement(key, entry.host, 'CodexAgent.dispose()'));
for (const key of this.hosts.keys()) {
this.hostGenerations.set(key, (this.hostGenerations.get(key) ?? 0) + 1);
}
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index 4628b14688..3da3105591 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -507,6 +507,8 @@ export class Session {
// ── turn 零事件看门狗(见 DEFAULT_TURN_STALL_MS)────────────────────────
private readonly turnStallMs: number;
private turnStallTimer: ReturnType<typeof setTimeout> | null = null;
+ private turnStallDiagnosticState = 'idle';
+ private turnStallLastDiagnosticAt = 0;
/** 还需要"清醒地"静默多久才判卡死;按分片递减(见 armTurnStallSlice)。 */
private turnStallRemainingMs = 0;
/** 当前分片的起始壁钟时刻;片尾据此识别系统挂起。 */
@@ -2099,7 +2101,7 @@ export class Session {
): Promise<InteractionDecision> {
this.pendingInteractions += 1;
const runtime = this.observeInteractionStarted(request);
- this.clearTurnStallWatchdog();
+ this.armTurnStallWatchdog();
try {
return await resolve();
} finally {
@@ -2731,13 +2733,17 @@ export class Session {
}
}
- private clearTurnStallWatchdog(): void {
+ private clearTurnStallWatchdog(refresh = false): void {
if (this.turnStallTimer) {
clearTimeout(this.turnStallTimer);
this.turnStallTimer = null;
}
this.turnStallRemainingMs = 0;
this.turnStallSliceStartedAt = 0;
+ if (!refresh && this.turnStallDiagnosticState === 'armed') {
+ this.logger.info('turn stall watchdog disarmed', { status: this.status });
+ this.turnStallDiagnosticState = 'idle';
+ }
}
private clearTerminalErrorDrain(): void {
@@ -2776,14 +2782,33 @@ export class Session {
* 后两条是误杀防护(见 DEFAULT_TURN_STALL_MS)。
*/
private armTurnStallWatchdog(): void {
- this.clearTurnStallWatchdog();
- if (this.turnStallMs <= 0) return;
- if (this.status !== 'active') return;
- if (this.closePromise) return;
- if (!this.isTurnRunning() && !this.hasUnsettledTurn()) return;
- if (this.pendingInteractions > 0) return;
- if (this.hasRunningBackgroundTasks()) return;
+ this.clearTurnStallWatchdog(true);
+ const reason = this.turnStallMs <= 0 ? 'disabled'
+ : this.status !== 'active' ? this.status
+ : this.closePromise ? 'closing'
+ : !this.isTurnRunning() && !this.hasUnsettledTurn() ? 'no-active-turn'
+ : this.pendingInteractions > 0 ? 'pending-interaction'
+ : this.hasRunningBackgroundTasks() ? 'background-task' : null;
+ if (reason) {
+ if (this.turnStallDiagnosticState !== reason) {
+ this.logger.info('turn stall watchdog suspended', { reason });
+ this.turnStallDiagnosticState = reason;
+ }
+ return;
+ }
this.turnStallRemainingMs = this.turnStallMs;
+ const now = Date.now();
+ // Bound refresh diagnostics to once per minute, independent of token volume.
+ if (this.turnStallDiagnosticState !== 'armed' || now - this.turnStallLastDiagnosticAt >= 60_000) {
+ this.logger.info(this.turnStallDiagnosticState !== 'armed'
+ ? 'turn stall watchdog armed' : 'turn stall watchdog refreshed', {
+ timeoutMs: this.turnStallMs,
+ lastActivityAt: now,
+ deadlineWithoutSuspendAt: now + this.turnStallMs,
+ });
+ this.turnStallLastDiagnosticAt = now;
+ }
+ this.turnStallDiagnosticState = 'armed';
this.armTurnStallSlice();
}
diff --git a/packages/maker-core/src/session.turn-stall.test.ts b/packages/maker-core/src/session.turn-stall.test.ts
index 7afd853884..3856adcf1c 100644
--- a/packages/maker-core/src/session.turn-stall.test.ts
+++ b/packages/maker-core/src/session.turn-stall.test.ts
@@ -18,9 +18,11 @@ import type { AgentSessionHandle, BackgroundTaskSnapshot } from './agents/base-a
type LoggedError = { msg: string; meta?: Record<string, unknown> };
-function createLogger(sink?: LoggedError[]) {
+function createLogger(sink?: LoggedError[], diagnostics?: LoggedError[]) {
const logger = {
- trace() {}, debug() {}, info() {}, warn() {}, fatal() {},
+ trace() {}, debug() {}, fatal() {},
+ info(msg: string, meta?: Record<string, unknown>) { diagnostics?.push({ msg, meta }); },
+ warn(msg: string, meta?: Record<string, unknown>) { diagnostics?.push({ msg, meta }); },
error(msg: string, meta?: Record<string, unknown>) {
sink?.push({ msg, meta });
},
@@ -111,7 +113,7 @@ function createStubHandle(opts?: StubOptions) {
function createSession(
stub: ReturnType<typeof createStubHandle>,
- opts?: { turnStallMs?: number; errorSink?: LoggedError[] },
+ opts?: { turnStallMs?: number; errorSink?: LoggedError[]; diagnostics?: LoggedError[] },
) {
return new Session({
id: 'session-1',
@@ -119,12 +121,44 @@ function createSession(
workDir: '/repo',
handle: stub.handle,
capabilities: {} as never,
- logger: createLogger(opts?.errorSink) as never,
+ logger: createLogger(opts?.errorSink, opts?.diagnostics) as never,
turnStallMs: opts?.turnStallMs ?? STALL_MS,
});
}
describe('Session turn stall watchdog', () => {
+ it('logs bounded activity refreshes, suspension, resumption and disarming', async () => {
+ vi.useFakeTimers();
+ try {
+ const backgroundTasks: BackgroundTaskSnapshot[] = [];
+ const stub = createStubHandle({ backgroundTasks });
+ const diagnostics: LoggedError[] = [];
+ const session = createSession(stub, { turnStallMs: 120_000, diagnostics });
+ await session.send('work');
+ const tick = async () => {
+ stub.pushEvent({ type: 'text', data: { text: 'progress' }, source: 'claude-code' });
+ await vi.advanceTimersByTimeAsync(0);
+ };
+ for (let i = 0; i < 10; i++) await tick();
+ expect(diagnostics.filter(x => x.msg.endsWith('armed'))).toHaveLength(1);
+ await vi.advanceTimersByTimeAsync(60_000);
+ await tick();
+ expect(diagnostics.find(x => x.msg.endsWith('refreshed'))?.meta).toMatchObject({
+ lastActivityAt: Date.now(), deadlineWithoutSuspendAt: Date.now() + 120_000,
+ });
+ backgroundTasks.push({ taskId: 'background' } as BackgroundTaskSnapshot);
+ await tick();
+ await tick();
+ expect(diagnostics.filter(x => x.msg.endsWith('suspended'))).toEqual([
+ { msg: 'turn stall watchdog suspended', meta: { reason: 'background-task' } },
+ ]);
+ backgroundTasks.length = 0;
+ await tick();
+ expect(diagnostics.filter(x => x.msg === 'turn stall watchdog armed')).toHaveLength(2);
+ await session.close();
+ expect(diagnostics.filter(x => x.msg.endsWith('disarmed'))).toHaveLength(1);
+ } finally { vi.useRealTimers(); }
+ });
it('closes an idle missing-terminal turn when stall abort never returns', async () => {
vi.useFakeTimers();
try {
@@ -379,7 +413,8 @@ describe('Session turn stall watchdog', () => {
vi.useFakeTimers();
try {
const stub = createStubHandle();
- const session = createSession(stub);
+ const diagnostics: LoggedError[] = [];
+ const session = createSession(stub, { diagnostics });
const seen: AgentEvent[] = [];
session.onEvent((ev) => seen.push(ev));
// listener 永不回应 —— 模拟用户离开
@@ -389,6 +424,10 @@ describe('Session turn stall watchdog', () => {
void stub.callInteraction();
await vi.advanceTimersByTimeAsync(STALL_MS * 5);
+ expect(diagnostics).toContainEqual({
+ msg: 'turn stall watchdog suspended',
+ meta: { reason: 'pending-interaction' },
+ });
expect(seen.some((ev) => ev.type === 'error')).toBe(false);
expect(stub.abort).not.toHaveBeenCalled();
} finally {