Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(im): 后台子任务唤醒的轮次也回传到原 IM 渠道 (#5907)
Dashf14b2f0db1d0
diff --git a/apps/desktop/src/main/hook-control/__tests__/backgroundResults.test.ts b/apps/desktop/src/main/hook-control/__tests__/backgroundResults.test.tsindex b642bcbba5..18c24ca4ec 100644--- a/apps/desktop/src/main/hook-control/__tests__/backgroundResults.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/backgroundResults.test.ts@@ -58,6 +58,8 @@ describe('IM session background results', () => {const f = fixture();f.owned.mockReturnValue(true);f.output.start('session', '/work', 'other-task');+ // A harness wake-up while the hook turn still observes the session belongs to that turn.+ f.output.start('session', '/work', 'provider-wake');expect(f.watchContinuation).not.toHaveBeenCalled();f.owned.mockReturnValue(false);f.sender.mockReturnValue(undefined as never);@@ -98,7 +100,7 @@ describe('IM session background results', () => {expect(f.send).toHaveBeenCalledOnce();});- it('relays only scheduler and other-task turns, never desktop input', () => {+ it('relays only scheduler, other-task and harness wake-up turns, never desktop input', () => {const f = fixture();f.output.start('session', '/work');f.watch().onSettling?.(undefined);@@ -114,6 +116,12 @@ describe('IM session background results', () => {f.watch().onSettling?.(undefined);f.watch().onEnd(result);expect(f.send).toHaveBeenCalledTimes(2);++ f.output.start('session', '/work', 'provider-wake');+ f.watch().onSettling?.(undefined);+ f.watch().onEnd(result);+ expect(f.send).toHaveBeenCalledTimes(3);+ expect(f.send).toHaveBeenLastCalledWith(expect.objectContaining({ payload: expect.objectContaining({ background: true }) }));});it('keeps a silenced scheduler run quiet but still delivers its failure', () => {diff --git a/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts b/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.tsindex 5fb1eedf45..a0764301db 100644--- a/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts@@ -7,8 +7,19 @@import path from 'node:path';import { describe, expect, it, vi } from 'vitest';-import { Session, type AgentEvent, type AgentSessionHandle, type Capabilities } from '@cindy/maker-core';+import {+ Session,+ type AgentEvent,+ type AgentSessionHandle,+ type Capabilities,+ type TurnContinuationState,+} from '@cindy/maker-core';import { observeHookTurn } from '../turnObserver';+import {+ onChannelTurn,+ publishChannelTurn,+ publishProviderInitiatedTurn,+} from '../../maker-ipc/channelTurnSignal';import { bindRuntimeRecoveryNotice } from '../../im/shared/runtimeRecoveryNotice';import { setMainLocale } from '../../i18n';@@ -283,6 +294,152 @@ describe('background results during normal turn delivery', () => {});});+describe('harness wake-ups of an IM-bound task (real Session)', () => {+ /** Claude-like handle: the test pushes provider events, including turns no send started. */+ function wakeableSession(id: string) {+ const queue: Array<AgentEvent | null> = [];+ let waiter: ((event: AgentEvent | null) => void) | null = null;+ let running = false;+ const continuations = new Map<number, TurnContinuationState>();+ const push = (event: AgentEvent | null) => {+ if (!waiter) { queue.push(event); return; }+ const deliver = waiter;+ waiter = null;+ deliver(event);+ };+ const handle = {+ id: 'claude', agentKind: 'claude-code', model: 'm',+ send: vi.fn(async () => { running = true; }),+ steer: vi.fn(async () => {}),+ abort: vi.fn(async () => {}),+ close: vi.fn(async () => { running = false; push(null); }),+ isTurnRunning: () => running,+ setInteractionResolver() {},+ beginTurnContinuationWait: (continuationId?: number) =>+ continuationId === undefined ? null : continuations.get(continuationId) ?? null,+ async *events() {+ for (;;) {+ const next = queue.length > 0+ ? queue.shift() ?? null+ : await new Promise<AgentEvent | null>((resolve) => { waiter = resolve; });+ if (next === null) return;+ yield next;+ }+ },+ } as unknown as AgentSessionHandle;+ const logger = { ...noopLog, debug() {}, trace() {}, error() {}, fatal() {}, child() { return this; } };+ const session = new Session({ id, agentKind: 'claude-code', workDir: WS_DIR,+ handle, capabilities: {} as Capabilities, logger, turnStallMs: 0 });+ // Production wiring: maker-ipc/sessionTurnObserver.ts.+ session.setTurnLifecycleObserver({+ beforeProviderStart: () => publishChannelTurn(session, 'starting'),+ onUndispatched: () => publishChannelTurn(session, 'undispatched'),+ onTerminal: () => undefined,+ onProviderInitiatedTurn: () => { void publishProviderInitiatedTurn(session); },+ });+ return {+ session,+ continuations,+ /** One provider event; a terminal `done` without keepRunning flips the handle idle. */+ async emit(event: Partial<AgentEvent>, opts: { keepRunning?: boolean } = {}) {+ if (event.type !== 'done' || opts.keepRunning) running = true;+ else running = false;+ push({ source: 'claude-code', data: {}, ...event } as AgentEvent);+ await new Promise((resolve) => setTimeout(resolve, 0));+ },+ };+ }++ function hookSessionObserver(session: Session, onTurnTerminal?: () => void) {+ return observeHookTurn(session, {+ ...(onTurnTerminal ? { onTurnTerminal } : {}),+ onSilentStopSettled: () => () => {},+ log: noopLog,+ });+ }++ it('relays each wake-up after the hook turn once, never desktop turns or subagent output', async () => {+ const externalKey = 'telegram:group:bot:-100200:user-7:g1';+ let live: ReturnType<typeof wakeableSession> | undefined;+ const run = vi.fn(async (req: HookRunRequest): Promise<HookRunOutcome> => {+ live = wakeableSession(req.sessionId);+ const observer = hookSessionObserver(live.session, req.onTurnTerminal);+ await live.session.send(req.prompt);+ await observer.finished;+ return { status: 'ok', finalText: observer.finalText(), errorMessage: null, durationMs: 1 };+ });+ // Same shape as session-runner's watchContinuation: observe from the claim, settle on the turn end.+ const watchContinuation = vi.fn((req: HookContinuationWatchRequest) => {+ const observer = hookSessionObserver(live!.session, () => req.onSettling?.());+ req.onClaim();+ void observer.finished.then(+ () => req.onEnd({ status: 'ok', finalText: observer.finalText(), errorMessage: null, durationMs: 1 }),+ (error: unknown) => req.onEnd({ status: 'error', finalText: '', errorMessage: String(error), durationMs: 1 }),+ );+ return () => observer.stop();+ });+ const bindings = memoryBindings();+ bindings.findBySession = (sessionId) => bindings.get('conn-1', externalKey) === sessionId+ ? [{ connectionId: 'conn-1', externalKey }] : [];+ let signal!: Parameters<NonNullable<HookDispatcherDeps['subscribeChannelTurn']>>[0];+ const { d } = makeDispatcher({+ runner: { isBusy: () => false, inspect: async () => null, run, watchContinuation },+ bindings,+ // Production wiring: hook-control/ipc.ts.+ subscribeChannelTurn: (listener) => {+ signal = listener;+ return onChannelTurn((session, phase, source) => listener(session.id, session.workDir, phase, source));+ },+ });+ expect(signal).toBeDefined();+ const c = collector();+ d.onConnected('conn-1', c.send, [HOOK_FEATURE_SESSION_RESULT]);+ const turnEnds = () => c.ofType('turn.end').map((frame) => [frame.payload.background ?? false, frame.payload.finalText]);+ try {+ d.handleDispatch('conn-1', dispatch({ externalKey }), c.send);+ await vi.waitFor(() => expect(live).toBeDefined());+ const h = live!;+ // The hook turn launches background agents and replies; the wake task claim keeps it open,+ // so the first wake-up belongs to the hook turn and is not sent a second time.+ await h.emit({ type: 'text', data: { text: 'Still working.', isFinal: true } }, { keepRunning: true });+ h.continuations.set(1, 'awaiting');+ await h.emit({ type: 'done', turnContinuationId: 1 }, { keepRunning: true });+ h.continuations.set(1, 'active');+ await h.emit({ type: 'text', data: { text: 'Agent A finished.', isFinal: true } }, { keepRunning: true });+ await h.emit({ type: 'done' });+ await vi.waitFor(() => expect(turnEnds()).toHaveLength(1));+ expect(turnEnds()[0]![0]).toBe(false);+ expect(turnEnds()[0]![1]).toContain('Agent A finished.');++ // Background subagent output while the task is idle is not a turn.+ await h.emit({ type: 'text', data: { text: 'subagent notes' }, agentMeta: { parentUuid: 'toolu_b' } });+ expect(watchContinuation).not.toHaveBeenCalled();++ // Claude wakes the session itself for each later task notification: no send, no hook request.+ for (const report of ['Agent B finished.', 'Final report.']) {+ await h.emit({ type: 'thinking', data: { text: 'task notification' } }, { keepRunning: true });+ await h.emit({ type: 'text', data: { text: report, isFinal: true } }, { keepRunning: true });+ await h.emit({ type: 'done' });+ await vi.waitFor(() => expect(turnEnds().at(-1)).toEqual([true, report]));+ }++ // Typed on the desktop: Session.send without other-task stamp stays in the app.+ await h.session.send('desktop question');+ await h.emit({ type: 'text', data: { text: 'desktop answer', isFinal: true } }, { keepRunning: true });+ await h.emit({ type: 'done' });+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(turnEnds()).toHaveLength(3);+ expect(run).toHaveBeenCalledOnce();+ expect(c.ofType('turn.end').filter((frame) => frame.payload.background).every(+ (frame) => frame.payload.externalKey === externalKey && frame.payload.sessionId === h.session.id,+ )).toBe(true);+ } finally {+ d.dispose();+ await live?.session.close();+ }+ });+});+describe('post-terminal runtime recovery delivery', () => {it.each([['en', 'Pi extensions could not be refreshed. Restart Cindy before using Pi again.'],diff --git a/apps/desktop/src/main/hook-control/backgroundResults.ts b/apps/desktop/src/main/hook-control/backgroundResults.tsindex 0711666f26..6d1fea91f7 100644--- a/apps/desktop/src/main/hook-control/backgroundResults.ts+++ b/apps/desktop/src/main/hook-control/backgroundResults.ts@@ -4,7 +4,7 @@ import type { HookSessionRunner } from './dispatcher';import type { HookBindingStore } from './bindings';import { providerForExternalKey } from './providerRouting.js';import { isSilencedSchedulerTurn } from '../scheduler-host/silent-output.js';-import type { ChannelTurnSource } from '../maker-ipc/channelTurnSignal.js';+import { isRelayedChannelTurnSource, type ChannelTurnSource } from '../maker-ipc/channelTurnSignal.js';/** Shares the normal observer/final attachment collector; no task replay or outbox. */export function createBackgroundResults(deps: {@@ -32,7 +32,8 @@ export function createBackgroundResults(deps: {watches.set(sessionId, state);const detach = () => { if (watches.get(sessionId) === state) watches.delete(sessionId); };// Desktop input stays in the app. Scheduler turns are only known at terminal (turnOrigin);- // a silenced run then sends only its failure.+ // a silenced run then sends only its failure. Other-task mail and harness wake-ups (no send)+ // share the personal IM predicate. A wake-up inside the hook's own turn is owned above.let relay: 'all' | 'failure' | 'none' | null = null;state.cancel = deps.runner.watchContinuation({sessionId, workingDir,@@ -41,7 +42,7 @@ export function createBackgroundResults(deps: {onSettling(origin) {relay ??= origin?.kind === 'scheduler'? (isSilencedSchedulerTurn(origin) ? 'failure' : 'all')- : source === 'other-task' ? 'all' : 'none';+ : isRelayedChannelTurnSource(source) ? 'all' : 'none';detach();},onAbandon: () => { state.active = false; detach(); },diff --git a/apps/desktop/src/main/im/shared/__tests__/orchestratorOutput.test.ts b/apps/desktop/src/main/im/shared/__tests__/orchestratorOutput.test.tsindex f39c88b9b7..1fc61afe54 100644--- a/apps/desktop/src/main/im/shared/__tests__/orchestratorOutput.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/orchestratorOutput.test.ts@@ -11,6 +11,7 @@ const mocks = vi.hoisted(() => ({status: vi.fn(),botContextId: vi.fn(),attach: vi.fn(),+ note: vi.fn(),}));vi.mock('../../../logger', () => ({ createLogger: () => ({ info: vi.fn(), warn: vi.fn() }) }));vi.mock('../../../localDb/client/current', () => ({@@ -28,13 +29,20 @@ vi.mock('../../../maker-ipc/register', () => ({vi.mock('../channelDefaultRouteSync', () => ({ createImChannelDefaultRouteSync: () => ({}) }));vi.mock('../sessionRepo', () => ({ createImSessionRepo: () => ({}) }));vi.mock('../cardBuilders', () => ({ createCardBuilders: () => ({}) }));-vi.mock('../turnRunner', () => ({ createTurnRunner: () => ({ attachSessionOutput: mocks.attach }) }));+vi.mock('../turnRunner', () => ({+ createTurnRunner: () => ({ attachSessionOutput: mocks.attach, noteChannelTurnSource: mocks.note }),+}));vi.mock('../slashCommands', () => ({ createSlashHandlers: () => ({}) }));vi.mock('../messageHandler', () => ({ createMessageHandler: () => vi.fn() }));vi.mock('../cardActionHandler', () => ({ createCardActionHandler: () => vi.fn() }));import { createImOrchestrator } from '../orchestrator';-import { channelTurnSourceFor, publishChannelTurn, withChannelTurnSource } from '../../../maker-ipc/channelTurnSignal';+import {+ channelTurnSourceFor,+ publishChannelTurn,+ publishProviderInitiatedTurn,+ withChannelTurnSource,+} from '../../../maker-ipc/channelTurnSignal';for (const channel of ['telegram', 'feishu', 'discord', 'wechat', 'wecom', 'dingtalk'] as const) {createImOrchestrator({@@ -88,6 +96,26 @@ describe('background output route recovery', () => {expect(channelTurnSourceFor({ kind: 'scheduler', scheduleId: 's' }, false)).toBeUndefined();});+ it('marks a harness wake-up on wired output synchronously, without a cold route lookup', () => {+ mocks.limit.mockResolvedValue([{ ...nativeRow, source: 'telegram', imBotContextId: 'bot', imUserId: 'native-user' }]);+ // Not awaited: the wake-up's first event fans out right after this call returns.+ void publishProviderInitiatedTurn(session);+ expect(mocks.note).toHaveBeenCalledTimes(6);+ expect(mocks.note).toHaveBeenCalledWith(session, 'provider-wake');+ expect(mocks.limit).not.toHaveBeenCalled();+ expect(mocks.attach).not.toHaveBeenCalled();+ });++ it('relays no harness wake-up for a logged-out account or a disconnected channel', () => {+ mocks.capture.mockReturnValue(null);+ void publishProviderInitiatedTurn(session);+ expect(mocks.note).not.toHaveBeenCalled();+ mocks.capture.mockReturnValue(1);+ mocks.status.mockReturnValue({ kind: 'disconnected' });+ void publishProviderInitiatedTurn(session);+ expect(mocks.note).not.toHaveBeenCalled();+ });+it.each([false, true])('uses stable Discord identity for cold route (takeover: %s)', async (attached) => {mocks.status.mockReturnValue({ kind: 'connected', appId: 'display#0000' });mocks.limit.mockResolvedValue([{ source: 'discord', status: 'active', imBotContextId: 'bot', imUserId: 'user' }]);diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.tsindex 03dd141a01..360855b7d6 100644--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts@@ -956,6 +956,53 @@ describe('turnRunner 渠道任务后台结果回传', () => {expect(stub.finalize).toHaveBeenCalledWith(turnOrigin ? '🤖 自动任务「检查进度」\n\n处理结果' : '处理结果');});+ it('Agent 自己唤醒的轮次(后台任务完成)回到原聊天,子代理与桌面轮次仍不回传', async () => {+ const h = await channelAndIdle('desktop');+ const stub = streamingHandleStub();+ mocks.slackIm.startStreamingText.mockResolvedValue(stub);+ // Background subagent output while the task is idle is filtered, before and after the mark.+ h.emit({ type: 'text', data: { text: '子代理内部' }, agentMeta: { parentUuid: 'toolu_1' } });+ runner.noteChannelTurnSource(h.session, 'provider-wake');+ h.emit({ type: 'text', data: { text: '子代理内部' }, agentMeta: { parentUuid: 'toolu_1' } });+ h.emit({ type: 'tool_use', data: { toolName: 'Read', input: { file_path: '/x/a.ts' } } });+ h.emit({ type: 'text', data: { text: '最终报告', isFinal: true } });+ h.emit({ type: 'done', data: {} });+ await vi.waitFor(() => expect(stub.finalize).toHaveBeenCalledExactlyOnceWith('最终报告'));+ expect(mocks.slackIm.startStreamingText).toHaveBeenCalledExactlyOnceWith('U1', undefined, { threadTs: '100.1' });++ // The mark ends with that turn: the next desktop-typed turn stays in the app.+ h.emit({ type: 'text', data: { text: '桌面里的回复', isFinal: true } });+ h.emit({ type: 'done', data: {} });+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(mocks.slackIm.startStreamingText).toHaveBeenCalledTimes(1);+ });++ it('IM 轮次仍在进行时不另开后台回传,也不把标记留给下一轮', async () => {+ await runTurn('100.1');+ const h = harnesses.get(sessionIdFor('T1', 'U1', '100.1'))!;+ const initial = streamingHandleStub();+ mocks.slackIm.startStreamingText.mockResolvedValue(initial);+ runner.noteChannelTurnSource(h.session, 'provider-wake');+ h.emit({ type: 'text', data: { text: 'IM 回复', isFinal: true } });+ h.emit({ type: 'done', data: {} });+ await vi.waitFor(() => expect(initial.finalize).toHaveBeenCalledExactlyOnceWith('IM 回复'));+ mocks.slackIm.startStreamingText.mockClear();+ h.emit({ type: 'text', data: { text: '桌面里的回复', isFinal: true } });+ h.emit({ type: 'done', data: {} });+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(mocks.slackIm.startStreamingText).not.toHaveBeenCalled();+ });++ it('接管(/ctr)的桌面任务仍只转播自动任务,不回传 Agent 自己唤醒的轮次', async () => {+ const h = await channelAndIdle('desktop');+ runner.attachSessionOutput(h.session, 'U1', { attached: true, scopeKey: '100.1' });+ runner.noteChannelTurnSource(h.session, 'provider-wake');+ h.emit({ type: 'text', data: { text: '后台结果', isFinal: true } });+ h.emit({ type: 'done', data: {} });+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(mocks.slackIm.startStreamingText).not.toHaveBeenCalled();+ });+it('子代理及旧轮次的后台事件不回传,也不提前结束当前回复', async () => {const h = await channelAndIdle();const stub = streamingHandleStub();diff --git a/apps/desktop/src/main/im/shared/orchestrator.ts b/apps/desktop/src/main/im/shared/orchestrator.tsindex 9cb0fc9433..e29a2e42cb 100644--- a/apps/desktop/src/main/im/shared/orchestrator.ts+++ b/apps/desktop/src/main/im/shared/orchestrator.ts@@ -52,6 +52,17 @@ const registry = new Map<ImChannelName, ImOrchestrator>();// routing from the saved channel identity, without creating/resuming a session.onChannelTurn(async (session, phase, source) => {if (phase !== 'starting') return;+ if (source === 'provider-wake') {+ // No send precedes a harness wake-up: its first event fans out right after this synchronous+ // call. Only output already wired for a channel can be marked in time; a cold route restored+ // after the row query would relay from mid-turn, so it is not attempted. Same admission as+ // below: a logged-out or replaced account, or a disconnected channel, relays nothing.+ if (captureImAccountGeneration() === null) return;+ for (const orchestrator of registry.values()) {+ if (orchestrator.adapter.im.getStatus().kind === 'connected') orchestrator.turnRunner.noteChannelTurnSource(session, source);+ }+ return;+ }const generation = captureImAccountGeneration();if (generation === null || ![...registry.values()].some((o) => o.adapter.im.getStatus().kind === 'connected')) return;const [row] = await getDbClient().drizzle.select().from(sessions)diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.tsindex 64ba245ce9..e8c7557461 100644--- a/apps/desktop/src/main/im/shared/turnRunner.ts+++ b/apps/desktop/src/main/im/shared/turnRunner.ts@@ -124,7 +124,7 @@ import { prependHandoffToUserMessage, prependNoteToWireUserMessage } from '../..import { buildPlanReconcileNote, summarizeOpenPlan } from '../../maker-ipc/planReconcile';import { peekGoalInactiveNote } from '../../goal-host/inactiveNote';import { isSilencedSchedulerTurn } from '../../scheduler-host/silent-output';-import type { ChannelTurnSource } from '../../maker-ipc/channelTurnSignal';+import { isRelayedChannelTurnSource, type ChannelTurnSource } from '../../maker-ipc/channelTurnSignal';import { listMessagesForAgentHandoff } from '../../localDb/ipc/messages';import {enqueueDurableWrite,@@ -384,10 +384,11 @@ interface SessionState {/** Agent execution ended, but its background output is still being delivered. */pendingTranspondFinals: number;/**- * 正在开始的非 IM 轮次由其它任务的可见来信发起(channelTurnSignal 盖章)。桌面输入等- * 其它来源不回传;在该轮终态清除,避免沿用到下一轮。+ * 正在开始的非 IM 轮次需要回传(`isRelayedChannelTurnSource`):其它任务的可见来信+ * (channelTurnSignal 盖章),或 Agent 自己唤醒、没有任何发送的轮次(后台任务完成通知)。+ * 桌面输入等其它来源不回传;在该轮终态清除,避免沿用到下一轮。*/- otherTaskTurn: boolean;+ relayedTurn: boolean;}/**@@ -550,6 +551,11 @@ export interface ImTurnRunner {route?: { attached: boolean; scopeKey?: string },source?: ChannelTurnSource,): void;+ /**+ * 同步标记已接好输出的会话正在开始的轮次来源,不查库、不新建监听。Agent 自己唤醒的+ * 轮次没有发送前的等待窗口,首个事件紧随其后,只有已接线的会话来得及完整回传。+ */+ noteChannelTurnSource(session: MakerSession, source: ChannelTurnSource): void;runAgentTurn(args: ImRunAgentTurnArgs): Promise<void>;/*** 把渠道用户消息**提前**写进本地 messages 表 —— 只给「dispatch 之前还有重活」@@ -1987,7 +1993,7 @@ export function createTurnRunner(scheduledTranspond: null,pendingTranspondTokenRate: null,pendingTranspondFinals: 0,- otherTaskTurn: false,+ relayedTurn: false,};sessionStates.set(row.id, state);@@ -2448,14 +2454,15 @@ export function createTurnRunner(if (!state) return;const turn = state.queue[0];if (!turn) {- // 只回传自动执行:scheduler 轮次,以及渠道自有任务里其它任务来信触发的轮次。- // 桌面输入留在桌面。通知回复只临时使用普通任务,不建立持续转播;接管普通任务- // 仍仅转播 scheduler。已开始的转播持续到收口(含 silent-stop 自动续跑)。+ // 只回传自动执行:scheduler 轮次,以及渠道自有任务里其它任务来信或 Agent 自己唤醒+ // (后台任务完成通知,没有任何发送)触发的轮次。桌面输入留在桌面。通知回复只临时+ // 使用普通任务,不建立持续转播;接管普通任务仍仅转播 scheduler。已开始的转播持续到+ // 收口(含 silent-stop 自动续跑)。const channelOwned = !state.preserveSessionConfig;if (state.scheduledTranspond !== null ||(event.turnOrigin?.kind === 'scheduler' && (channelOwned || state.attached)) ||- (channelOwned && state.otherTaskTurn)+ (channelOwned && state.relayedTurn)) {transpondScheduledEvent(state, event);}@@ -2463,7 +2470,7 @@ export function createTurnRunner(// 非终止 error 表示底层仍在自动恢复,不能抢跑下一条消息(放行排队消息会让// 下一条撞上 SESSION_RUNNING)。if (isProductTurnDoneEvent(event) || isTerminalAgentErrorEvent(event)) {- state.otherTaskTurn = false;+ state.relayedTurn = false;maybeDispatchNextQueued(state, userId);return;}@@ -4168,7 +4175,7 @@ export function createTurnRunner(attachSessionOutput: (session, userId, route, source) => {const existing = sessionStates.get(session.id);if (existing) {- existing.otherTaskTurn = source === 'other-task';+ existing.relayedTurn = isRelayedChannelTurnSource(source);const userChanged = existing.userId !== userId;if (route?.attached) {existing.attached = true;@@ -4196,11 +4203,17 @@ export function createTurnRunner(scheduledTranspond: null,pendingTranspondTokenRate: null,pendingTranspondFinals: 0,- otherTaskTurn: source === 'other-task',+ relayedTurn: isRelayedChannelTurnSource(source),};sessionStates.set(session.id, state);state.unsubscribers.push(session.onEvent(handleEventFor(session.id, userId)));},+ noteChannelTurnSource: (session, source) => {+ const state = sessionStates.get(session.id);+ // An IM turn still in the queue owns whatever runs now; it is delivered once, as itself.+ if (state?.makerSession !== session || state.queue.length > 0) return;+ state.relayedTurn = isRelayedChannelTurnSource(source);+ },runAgentTurn,persistInboundUserMessageEarly,dispatchAgentTurn,diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.tsindex 1e2a5265e8..05cc3878d4 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts@@ -1102,6 +1102,52 @@ describe('provider turn observer on real Session.send', () => {} finally { unsubscribe(); dispose(); await h.dispose(); }});+ it('announces a harness wake-up as a provider-wake channel turn before its first event', async () => {+ const pushed: Array<AgentEvent | null> = [];+ let wake: (() => void) | null = null;+ let running = false;+ const handle = {+ id: 'provider', agentKind: 'claude-code', model: 'test-model',+ send: vi.fn(async () => { running = true; }),+ close: vi.fn(async () => { pushed.push(null); wake?.(); }),+ isTurnRunning: () => running,+ setInteractionResolver: vi.fn(),+ async *events() {+ for (;;) {+ while (pushed.length === 0) await new Promise<void>((resolve) => { wake = resolve; });+ const next = pushed.shift()!;+ if (next === null) return;+ yield next;+ }+ },+ } as unknown as AgentSessionHandle;+ const log = { trace: vi.fn(), debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(), fatal: vi.fn(),+ child: () => log };+ const session = new Session({ id: 'wake-task', agentKind: 'claude-code', workDir: '/unused', handle,+ capabilities: {} as never, logger: log, turnStallMs: 0 });+ const emit = async (value: AgentEvent) => {+ running = value.type !== 'done';+ pushed.push(value);+ wake?.();+ await vi.waitFor(() => expect(pushed).toHaveLength(0));+ await microtasks();+ };+ const order: string[] = [];+ const dispose = installSessionTurnObserver(observerDeps(), session);+ const unsubscribe = onChannelTurn((target, phase, source) => {+ if (target === session) order.push(`${phase}:${source ?? 'none'}`);+ });+ const off = session.onEvent((value) => order.push(value.type));+ try {+ await session.send('typed on desktop');+ await emit(event('text', { text: 'launched agents' }));+ await emit(event('done'));+ await emit(event('text', { text: 'agent result' }));+ await emit(event('done'));+ expect(order).toEqual(['starting:none', 'text', 'done', 'starting:provider-wake', 'text', 'done']);+ } finally { off(); unsubscribe(); dispose(); await session.close(); }+ });+it('channel attachment failure does not block task execution', async () => {const h = harness();const dispose = installSessionTurnObserver(observerDeps(), h.session);diff --git a/apps/desktop/src/main/maker-ipc/channelTurnSignal.ts b/apps/desktop/src/main/maker-ipc/channelTurnSignal.tsindex 814ac6865a..969ff47ca6 100644--- a/apps/desktop/src/main/maker-ipc/channelTurnSignal.ts+++ b/apps/desktop/src/main/maker-ipc/channelTurnSignal.ts@@ -4,11 +4,21 @@ import { createLogger } from '../logger';const log = createLogger('channel-turn');export type ChannelTurnPhase = 'starting' | 'undispatched';/**- * Main-stamped requester of the turn that is starting. Only another task's user-visible message is- * marked; desktop input, IM input and internal delegation coordination are not. Scheduler turns are- * recognised by their own turnOrigin instead.+ * Requester of the turn that is starting. `other-task`: main stamped another task's user-visible+ * message on the send. `provider-wake`: no send at all, the agent harness woke the session itself+ * (Claude Code background task notifications; see Session `onProviderInitiatedTurn`). Desktop input,+ * IM input and internal delegation coordination are not marked. Scheduler turns are recognised by+ * their own turnOrigin instead.*/-export type ChannelTurnSource = 'other-task';+export type ChannelTurnSource = 'other-task' | 'provider-wake';++/**+ * The one relay predicate shared by official hook background results and personal IM output:+ * a non-IM, non-scheduler turn returns to the task's channel only for these sources.+ */+export function isRelayedChannelTurnSource(source: ChannelTurnSource | undefined): boolean {+ return source === 'other-task' || source === 'provider-wake';+}type ChannelTurnListener = (session: Session,phase: ChannelTurnPhase,@@ -27,6 +37,23 @@ export function onChannelTurn(listener: ChannelTurnListener): () => void {export async function publishChannelTurn(session: Session, phase: ChannelTurnPhase): Promise<void> {const source = pendingSources.get(session.id)?.source;pendingSources.delete(session.id);+ await notifyListeners(session, phase, source);+}++/**+ * A turn the provider started without a send. Session calls this before the turn's first event fans+ * out, and every listener's synchronous part runs before this returns, so observers it attaches see+ * the whole turn. Listeners must decide synchronously; an awaited lookup would start mid-turn.+ */+export function publishProviderInitiatedTurn(session: Session): Promise<void> {+ return notifyListeners(session, 'starting', 'provider-wake');+}++async function notifyListeners(+ session: Session,+ phase: ChannelTurnPhase,+ source: ChannelTurnSource | undefined,+): Promise<void> {await Promise.all([...listeners].map(async (listener) => {try { await listener(session, phase, source); }catch { log.warn('channel output observer could not be updated'); }diff --git a/apps/desktop/src/main/maker-ipc/sessionTurnObserver.ts b/apps/desktop/src/main/maker-ipc/sessionTurnObserver.tsindex aa923aaf8d..0aea1d5f67 100644--- a/apps/desktop/src/main/maker-ipc/sessionTurnObserver.ts+++ b/apps/desktop/src/main/maker-ipc/sessionTurnObserver.ts@@ -1,5 +1,5 @@import type { Session } from '@cindy/maker-core';-import { publishChannelTurn } from './channelTurnSignal';+import { publishChannelTurn, publishProviderInitiatedTurn } from './channelTurnSignal';import { MANAGED_LLAMACPP_PROVIDER_ID } from '../../shared/llamaCpp.js';import { ensureManagedOllamaReadyForSession } from '../local-model-runtime/preflight.js';import { createLogger } from '../logger.js';@@ -102,6 +102,11 @@ export function installSessionTurnObserver(deps: InstallSessionTurnObserverDeps,deps.providerTurnLeaseId(session.instanceId, turnGeneration),);},+ onProviderInitiatedTurn: () => {+ // Harness wake-ups (Claude Code background task notifications) skip beforeProviderStart.+ // IM relay decides synchronously inside this call, before the first event fans out.+ void publishProviderInitiatedTurn(session);+ },onTerminal: ({ turnGeneration, event, isCurrentGeneration }) => {if (session.remoteHostId) return;const turnLeaseId = deps.providerTurnLeaseId(session.instanceId, turnGeneration);diff --git a/docs/dev-rules/im-turn-flow.md b/docs/dev-rules/im-turn-flow.mdindex d1c2fbe646..df059f3a8b 100644--- a/docs/dev-rules/im-turn-flow.md+++ b/docs/dev-rules/im-turn-flow.md@@ -31,6 +31,7 @@ Telegram / Slack / X)是同一件事的两套实现:把渠道里的一条消| 用户消息落库 | 部分渠道提前落库(`persistInboundUserMessageEarly`),`onAccepted` 补 `imSource` | 只在 `onAccepted` 落库,`agentMeta.hookSource` | 共用流程(`onAccepted` 落库;提前落库保留为渠道能力) || 发送 | `makerSession.send`,`MAIN_OWNED_SEND_CONTEXT.origin.kind='im'` | `session.send`,origin `hook`(Telegram/X)或 `im`(Slack) | 共用流程;Pi 管理命令授权来源按渠道各自声明(hook 不得伪装成本机命令) || 观察事件 | `turnPresenter`(buffer-replace)+ 流式 handle | `turnObserver`(finalized-segments)+ 进度发射器 | 共用流程(presenter 已同源;两个正文累积引擎有意不同) |+| 后台轮次回传(非 IM 入站) | `orchestrator` 的 `onChannelTurn` → `turnRunner` 转播(Agent 自己唤醒的轮次只同步标记已接线的会话) | `backgroundResults` → `turn.end(background: true)` | 已同源判据:`maker-ipc/channelTurnSignal.ts` 的开始信号与 `isRelayedChannelTurnSource`(其它任务来信、Agent 自己唤醒;scheduler 按 `turnOrigin`);仍属原 IM 轮次的不另发 || 表情 | `TurnState` 的 ack 句柄 | `ackReactions`(msg.op react) | 渠道适配(出站载体不同,档位语义同源) || 交互 | `beginInteractionRoute` + `pendingInteractions` + 渠道卡片 | `beginInteractionRoute` + `interactions.ts`(30 分钟超时)+ 卡片发布器 | 共用流程(路由与语义层已同源;超时差异见台账缺口 2g) || 收尾 | `handleTurnDoneAsync` / `handleTurnErrorAsync` → 流式 handle finalize | `execute` 收口 → `turnCarrier.publishFinal` → `turn.end`(持久出箱) | 共用流程的收口骨架 + 渠道出站载体 |diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.mdindex 2fc6478c88..b2ebdf2f47 100644--- a/docs/dev-rules/maker-core-and-agent-behavior.md+++ b/docs/dev-rules/maker-core-and-agent-behavior.md@@ -409,6 +409,15 @@ sessionRunningRetry 就停。每次因 replacement 关闭而重新入队都计capability selection 与 auto-review intent。不得把无人值守只读边界重置成普通Auto,也不得用固定 wait 提示覆盖原请求的能力选择或审查意图。Claude wake continuation 与 Codex yield continuation 先分账,不抽公共模块。+- **Provider 自己开的轮次要显式交给宿主。** 本代产品轮次已收口、没有预留中的 `Session.send`+ 时出现的主代理新输出(Claude Code 后台任务完成后 CLI 自行注入 `<task-notification>` 开的+ 新一轮)沿用上一代 generation、没有 `turnOrigin`,也不经过 `beforeProviderStart`。`Session`+ 在该轮首个事件分发给监听者之前同步调用 `SessionTurnLifecycleObserver.onProviderInitiatedTurn`,+ 每轮一次,终态后清除;子代理事件、后台事件、claim 挡住的续跑段不触发。同一产品轮次接受过+ 插话时,收口后第一个无发送的轮次归插话(分不出插话是否已被原轮次吸收,宁可漏报)。桌面用它把这类轮次回传到 IM(`maker-ipc/channelTurnSignal.ts`);+ 回调必须同步决定,异步查询会从轮次中途开始观察;桌面侧与普通回传一样只在 IM 账号仍有效、渠道已连接时标记。+ 该轮沿用的 generation 已记过上一轮的 `done`,唤醒轮自己的终止 error 不按「done 之后的迟到 error」过滤,+ 照常按失败收口(唤醒输出之前到达的迟到 error 仍过滤)。回归见 `session.origin.test.ts`。### Auto 模式的同范围自动跟进diff --git a/docs/product-rules/telegram-bot-parity.md b/docs/product-rules/telegram-bot-parity.mdindex cb5cd45d67..62dfce6d44 100644--- a/docs/product-rules/telegram-bot-parity.md+++ b/docs/product-rules/telegram-bot-parity.md@@ -269,10 +269,26 @@ hook 侧既有的逐轮 `[渠道说明]`,两者措辞不同但都向模型说适用范围:个人飞书/Lark、Telegram、Discord、微信、企业微信、钉钉,以及官方 Telegram、Slack;X 不参与。-只回传自动执行的轮次:自动任务(scheduler `turnOrigin`),以及其它任务经 `send_to_session` 等-发来的可见消息触发的回复。桌面里直接输入的消息、伙伴委派的内部协调输入都不回传。其它任务来信由+只回传自动执行的轮次:自动任务(scheduler `turnOrigin`),其它任务经 `send_to_session` 等+发来的可见消息触发的回复,以及 Agent 自己唤醒的轮次。桌面里直接输入的消息、伙伴委派的内部协调输入都不回传。其它任务来信由主进程在派发它的那次 `Session.send` 期间盖章(`maker-ipc/channelTurnSignal.ts`),随该轮的开始信号交给两条路径,只作用于这一轮;不改 maker-core 的 `SendOrigin`,以免插件钩子等把它当作非用户轮次。+两条路径共用 `isRelayedChannelTurnSource` 一个判据。++Agent 自己唤醒的轮次(2026-10-13 补齐):Claude Code 的后台子代理、后台命令等完成后,CLI 自己注入+`<task-notification>` 开新一轮,Cindy 这边没有任何 `Session.send`,旧版因此既没有开始信号也没有来源,+被当作桌面输入留在桌面,只有原 IM 轮次还挂着的那一段(wake 任务的 continuation claim 让 IM 轮次等到第一次+唤醒结束)随原轮次发出。现在 maker-core `Session` 在本代产品轮次已收口、没有预留中的发送时看到主代理的新+输出(文本、思考、工具),就在该事件分发给监听者之前同步调用 `onProviderInitiatedTurn`;桌面以+`provider-wake` 来源发出开始信号,回传与其它任务来信同一条发送、收口与清理路径。判据与引擎无关,+Codex / Pi 目前没有此类自动唤醒。子代理事件(`agentMeta.parentUuid`)、后台事件、claim 挡住的续跑段都不算;+产品轮次里接受过插话(steer)时,收口后第一个无发送的轮次一律归插话、不回传:插话赶不上原轮次时+Claude 会把它当作新一轮执行,而 Cindy 分不出插话是否已被原轮次吸收,宁可漏传这一轮,也不把桌面输入的回复发到渠道。+仍属原 IM 轮次(官方 hook 仍在观察、个人渠道队列里仍有 IM 轮次)时由该轮次一并发出,不另发后台结果。+已知边界:唤醒轮次自身没有来源,跟在桌面输入或静默运行的自动任务之后被唤醒时同样回传;个人渠道只对已接好+输出的渠道自有任务生效(重启后先在桌面发起、尚未经 IM 接线的任务,唤醒轮次留在桌面,不从中途开始转播),+`/ctr` 接管任务仍只转播 scheduler 输出;唤醒后还没产生任何输出就直接失败的轮次(只有一个终止错误)与上一轮迟到的+错误分不开,不识别为唤醒、不回传,失败留在桌面(与此前行为相同)。个人渠道通过 `im/shared/turnRunner.ts` 回传上述轮次的输出,无需先 `/ctr` 接管。自动任务保留任务名,其它来源直接显示回复正文,目的地沿用该任务原聊天和话题。正常 IM 入站轮次仍只发送一次;@@ -296,7 +312,7 @@ bot 身份按入站使用的稳定 ID 校验;Discord 取 gateway application i官方 Telegram、Slack 复用已有 hook binding、轮次观察和附件收集;双方宣告 `session-result-v1`后,后台回传与任务派发共用渠道 key 判定,兼容既有 Slack 前缀、team-slack、旧频道和 DM key;X 不回传。-轮次终态时按来源决定是否发送(scheduler 来源,或开始时盖了其它任务来信章)。结果用 `turn.end(background: true)` 发送,服务端在原私聊或话题新发消息。普通 IM 轮次和+轮次终态时按来源决定是否发送(scheduler 来源,或开始时带其它任务来信 / Agent 自己唤醒的来源)。结果用 `turn.end(background: true)` 发送,服务端在原私聊或话题新发消息。普通 IM 轮次和已有 retry/reopen 轮次不另发一份。发送前复核账号代次、连接、目录授权与会话绑定;服务端再核对设备绑定、聊天归属及 `/new` 代次。Telegram 保存新消息 route,回复结果仍回到原 lane。diff --git a/packages/maker-core/src/session.origin.test.ts b/packages/maker-core/src/session.origin.test.tsindex a9159ca7b5..6e21528028 100644--- a/packages/maker-core/src/session.origin.test.ts+++ b/packages/maker-core/src/session.origin.test.ts@@ -1748,3 +1748,137 @@ describe('Session per-turn origin 打标', () => {expect(JSON.stringify(seen[0])).not.toContain('upstream-secret');});});++describe('Session provider-initiated turns (harness wake-ups)', () => {+ function makeSteerableSession(handle: AgentSessionHandle): Session {+ return new Session({+ id: 'session-1',+ agentKind: 'claude-code',+ workDir: path.join('workspace', 'repo'),+ handle,+ capabilities: { sameTurnSteer: { supported: true } } as never,+ logger: createLogger() as never,+ });+ }++ function observe(session: Session) {+ const order: string[] = [];+ const wakes: number[] = [];+ session.setTurnLifecycleObserver({+ beforeProviderStart: () => undefined,+ onUndispatched: () => undefined,+ onTerminal: () => undefined,+ onProviderInitiatedTurn: (generation) => {+ wakes.push(generation);+ order.push('wake');+ },+ });+ session.onEvent((event) => order.push(event.type));+ return { order, wakes };+ }++ it('announces a turn started without a send, once, before listeners see its first event', async () => {+ const h = createControllableHandle({ agentKind: 'claude-code' });+ const session = makeSession(h.handle, 'claude-code');+ const { order, wakes } = observe(session);++ await session.send('launch background agents', { origin: SCHED_ORIGIN });+ await h.emit({ type: 'text', data: { text: 'still working', isFinal: true } });+ await h.emit({ type: 'done', data: {} });+ expect(wakes).toEqual([]);++ const seen: AgentEvent[] = [];+ session.onEvent((event) => seen.push({ ...event }));+ h.setTurnRunning(true);+ await h.emit({ type: 'thinking', data: { text: 'task finished' } }, { keepRunning: true });+ await h.emit({ type: 'text', data: { text: 'final report', isFinal: true } });+ await h.emit({ type: 'done', data: {} });+ expect(wakes).toEqual([1]);+ expect(order.slice(order.indexOf('wake'))).toEqual(['wake', 'thinking', 'text', 'done']);+ // A wake-up reuses the previous generation and carries no origin of its own.+ expect(seen.every((event) => event.sessionTurnGeneration === 1 && event.turnOrigin === undefined)).toBe(true);++ // Each later wake-up is announced again.+ h.setTurnRunning(true);+ await h.emit({ type: 'tool_use', data: { toolName: 'Read', input: {} } }, { keepRunning: true });+ await h.emit({ type: 'done', data: {} });+ expect(wakes).toEqual([1, 1]);+ await session.close();+ });++ it('settles a provider-initiated turn that ends in an error as a failure, not as the earlier success', async () => {+ const h = createControllableHandle({ agentKind: 'claude-code' });+ const session = makeSession(h.handle, 'claude-code');+ const terminals: string[] = [];+ session.setTurnLifecycleObserver({+ beforeProviderStart: () => undefined,+ onUndispatched: () => undefined,+ onTerminal: ({ event }) => { terminals.push(event.type); },+ onProviderInitiatedTurn: () => undefined,+ });+ const seen: string[] = [];+ session.onEvent((event) => seen.push(event.type));++ await session.send('launch background agents', { origin: SCHED_ORIGIN });+ await h.emit({ type: 'done', data: {} });+ // A late error right after that done is still the previous turn's leftover.+ await h.emit({ type: 'error', data: { message: 'late' } });+ expect(terminals).toEqual(['done']);++ h.setTurnRunning(true);+ await h.emit({ type: 'text', data: { text: 'woke up' } }, { keepRunning: true });+ await h.emit({ type: 'error', data: { message: 'wake failed' } });+ await h.emit({ type: 'done', data: {} });+ expect(terminals.slice(1, 2)).toEqual(['error']);+ expect(seen.filter((type) => type === 'error').length).toBeGreaterThan(0);+ await session.close();+ });++ it('never announces sent turns, subagent output, idle tails or claimed continuations', async () => {+ const h = createControllableHandle({ agentKind: 'claude-code' });+ const session = makeSession(h.handle, 'claude-code');+ const { wakes } = observe(session);++ await session.send('typed on desktop');+ await h.emit({ type: 'text', data: { text: 'reply' } }, { keepRunning: true });+ h.setContinuationState(1, 'awaiting');+ await h.emit({ type: 'done', data: {}, turnContinuationId: 1 }, { keepRunning: true });+ // The automatic continuation still belongs to the sent turn.+ h.setContinuationState(1, 'active');+ await h.emit({ type: 'text', data: { text: 'continuation result' } }, { keepRunning: true });+ await h.emit({ type: 'done', data: {} });++ // Background subagent output while the parent is idle is not a wake-up.+ await h.emit({ type: 'text', data: { text: 'subagent' }, agentMeta: { parentUuid: 'toolu_1' } });+ await h.emit({ type: 'status', data: { status: 'idle', isRunning: false } });+ await h.emit({ type: 'text', data: { text: 'late child' }, turnScope: 'background' });+ expect(wakes).toEqual([]);++ await session.send('next desktop turn');+ await h.emit({ type: 'text', data: { text: 'answer' } }, { keepRunning: true });+ await h.emit({ type: 'done', data: {} });+ expect(wakes).toEqual([]);+ await session.close();+ });++ it('attributes the first unsent turn after an accepted steer to that steer', async () => {+ const h = createControllableHandle({ agentKind: 'claude-code' });+ const session = makeSteerableSession(h.handle);+ const { wakes } = observe(session);++ await session.send('first');+ await session.steer('one more thing');+ await h.emit({ type: 'done', data: {} });+ // Claude runs a steer that missed the ending turn as its own SDK turn.+ h.setTurnRunning(true);+ await h.emit({ type: 'text', data: { text: 'steer reply' } }, { keepRunning: true });+ await h.emit({ type: 'done', data: {} });+ expect(wakes).toEqual([]);++ h.setTurnRunning(true);+ await h.emit({ type: 'text', data: { text: 'background agent done' } }, { keepRunning: true });+ await h.emit({ type: 'done', data: {} });+ expect(wakes).toEqual([1]);+ await session.close();+ });+});diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.tsindex 2bd3f25819..3600a4e9c2 100644--- a/packages/maker-core/src/session.ts+++ b/packages/maker-core/src/session.ts@@ -357,6 +357,14 @@ export interface SessionTurnLifecycleObserver {event: AgentEvent;isCurrentGeneration: boolean;}): void | Promise<void>;+ /**+ * Called synchronously, before event listeners see its first event, when the provider starts a+ * turn on its own: top-level output after this generation's product terminal, with no+ * `Session.send` reserved and no `Session.steer` carried over (e.g. Claude Code waking itself on a+ * background task notification). The turn reuses the previous generation and has no turnOrigin.+ * Claimed continuations never reach here: their `done` is not a product terminal.+ */+ onProviderInitiatedTurn?(turnGeneration: number): void;}/**@@ -465,6 +473,13 @@ export class Session {private readonly statusListeners = new Set<SessionStatusListener>();private interactionListener: InteractionRequestListener | null = null;private turnLifecycleObserver: SessionTurnLifecycleObserver | null = null;+ /** Generation whose turn after the product terminal (no send) is currently open. */+ private unsolicitedTurnGeneration: number | null = null;+ /**+ * Generation that accepted a steer. Claude may run a steer that missed the ending turn as a new+ * SDK turn without a send; that turn belongs to the steering input, not to the provider.+ */+ private steerAcceptedGeneration: number | null = null;private status: SessionStatus = 'active';/*** 同一 Session 的并发 close 共享一次底层关闭过程。renderer 与 main 生命周期钩子可能@@ -1169,7 +1184,17 @@ export class Session {throw new Error(`Session ${this.id} has no active turn to steer`);}this.startEventLoopIfNeeded();- await this.handle.steer(msg, { ...opts, [AUTO_REVIEW_SOURCE_CONTENT]: autoReviewSourceContent });+ // Mark before dispatch: the provider may start the steer's own turn as soon as it accepts it.+ const previousSteerGeneration = this.steerAcceptedGeneration;+ this.steerAcceptedGeneration = steerTurnGeneration;+ try {+ await this.handle.steer(msg, { ...opts, [AUTO_REVIEW_SOURCE_CONTENT]: autoReviewSourceContent });+ } catch (error) {+ if (this.steerAcceptedGeneration === steerTurnGeneration) {+ this.steerAcceptedGeneration = previousSteerGeneration;+ }+ throw error;+ }}async abort(): Promise<void> {@@ -2474,6 +2499,37 @@ export class Session {);}+ /**+ * First top-level output after this generation's product terminal while no send is reserved:+ * the provider started a turn by itself. Subagent output (live `agentMeta.parentUuid`) is the+ * background work, not the wake-up. A steer carried over from the ended turn owns the first+ * such turn instead. Returns true only for the opening event of a provider-initiated turn.+ */+ private isProviderInitiatedTurnStart(+ event: AgentEvent,+ isBackgroundEvent: boolean,+ isCurrentGeneration: boolean,+ ): boolean {+ if (isBackgroundEvent || !isCurrentGeneration || !this.isNewTurnProgressEvent(event)) return false;+ const parentUuid = event.agentMeta?.parentUuid;+ if (typeof parentUuid === 'string' && parentUuid.length > 0) return false;+ const generation = this.turnGeneration;+ if (+ generation <= 0 ||+ this.terminalEventObservedGeneration !== generation ||+ this.sendReservation !== null ||+ this.isUnacceptedCurrentSend() ||+ this.retirementContinuationGeneration === generation ||+ this.unsolicitedTurnGeneration === generation+ ) {+ return false;+ }+ this.unsolicitedTurnGeneration = generation;+ const carriedSteer = this.steerAcceptedGeneration === generation;+ this.steerAcceptedGeneration = null;+ return !carriedSteer;+ }+private resolveSessionTurnGeneration(waitStartGeneration: number,observedGeneration: number,@@ -2720,7 +2776,10 @@ export class Session {this.terminalEventObservedKind === 'done';// A late leftover error must not replace N+1's result-only success,// nor fan-out as a current-generation failure to lifecycle / IPC listeners.- const lateErrorAfterDoneSnapshot = event.type === 'error' && sameGenerationDone;+ // A provider-initiated turn reuses the generation whose done was already+ // seen: its own terminal error is not a leftover of that done.+ const lateErrorAfterDoneSnapshot =+ event.type === 'error' && sameGenerationDone && this.unsolicitedTurnGeneration !== this.turnGeneration;const reservationWindowLeftover =isTerminal &&!isBackgroundEvent &&@@ -2780,6 +2839,16 @@ export class Session {// Rolled-back / leftover paired done still belongs to the promoted error.this.clearTerminalErrorDrain();}+ if (this.isProviderInitiatedTurnStart(event, isBackgroundEvent, isCurrentGeneration)) {+ try {+ this.turnLifecycleObserver?.onProviderInitiatedTurn?.(resolvedGeneration);+ } catch (error) {+ this.logger.warn('provider-initiated turn observer failed', {+ turnGeneration: resolvedGeneration,+ error: String(error),+ });+ }+ }const listenerEvent = redactEventForListeners(event);if (terminalBoundaryObserved &&@@ -2802,6 +2871,7 @@ export class Session {}if (isCurrentGeneration && isTerminal && !isBackgroundEvent && !lateErrorAfterDoneSnapshot && !reservationWindowLeftover) {if (!this.isSilentStopDoneEvent(event)) this.retirementContinuationGeneration = null;+ this.unsolicitedTurnGeneration = null;this.clearTurnControl(resolvedGeneration);}const isLeftoverProductTerminal =