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(im): 后台结果只回传自动执行的轮次,静默的自动任务不回传

Dashb44b8910fec7
diff --git a/apps/desktop/src/main/hook-control/__tests__/backgroundResults.test.ts b/apps/desktop/src/main/hook-control/__tests__/backgroundResults.test.ts
index dfb1ec42a2..b642bcbba5 100644
--- a/apps/desktop/src/main/hook-control/__tests__/backgroundResults.test.ts
+++ b/apps/desktop/src/main/hook-control/__tests__/backgroundResults.test.ts
@@ -1,5 +1,6 @@
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { createBackgroundResults } from '../backgroundResults';
+import { setSilencedRunProbe } from '../../scheduler-host/silent-output';
import type { HookContinuationWatchRequest, HookSessionRunner } from '../dispatcher';
function fixture(key = 'telegram:dm:bot:user:g0') {
@@ -23,15 +24,18 @@ function fixture(key = 'telegram:dm:bot:user:g0') {
const result = { status: 'ok' as const, finalText: '自动执行结果', errorMessage: null, durationMs: 10 };
describe('IM session background results', () => {
+ afterEach(() => setSilencedRunProbe(null));
+
it.each([
'telegram:dm:bot:user:g0', 'slack:T:C:1.2', 'slack:dm:T1:U1:g2',
'team-slack:C1:1.1', 'T1:C1:1.1', 'dm:U1:g2', 'dm:T1:U1:g2',
])('forwards %s once, including attachments', (key) => {
const f = fixture(key);
- f.output.start('session', '/work');
- f.output.start('session', '/work');
+ f.output.start('session', '/work', 'other-task');
+ f.output.start('session', '/work', 'other-task');
expect(f.watchContinuation).toHaveBeenCalledTimes(1);
const outcome = { ...result, attachments: [{ mimeType: 'text/plain', dataBase64: 'YQ==', name: 'a.txt' }] };
+ f.watch().onSettling?.();
f.watch().onEnd(outcome);
f.watch().onEnd(outcome);
expect(f.send).toHaveBeenCalledTimes(1);
@@ -44,7 +48,7 @@ describe('IM session background results', () => {
it.each(['x:post:1', 'discord:channel-1', 'arbitrary', 'dm:U1:invalid', 'T1:C1:invalid'])(
'does not observe unsupported lane %s', (key) => {
const f = fixture(key);
- f.output.start('session', '/work');
+ f.output.start('session', '/work', 'other-task');
expect(f.watchContinuation).not.toHaveBeenCalled();
expect(f.send).not.toHaveBeenCalled();
},
@@ -53,17 +57,17 @@ describe('IM session background results', () => {
it('excludes old servers and turns already owned by normal IM/reopen delivery', () => {
const f = fixture();
f.owned.mockReturnValue(true);
- f.output.start('session', '/work');
+ f.output.start('session', '/work', 'other-task');
expect(f.watchContinuation).not.toHaveBeenCalled();
f.owned.mockReturnValue(false);
f.sender.mockReturnValue(undefined as never);
- f.output.start('session', '/work');
+ f.output.start('session', '/work', 'other-task');
expect(f.watchContinuation).not.toHaveBeenCalled();
});
it.each(['binding', 'directory', 'connection', 'account'] as const)('discards late results after %s changes', (kind) => {
const f = fixture();
- f.output.start('session', '/work');
+ f.output.start('session', '/work', 'other-task');
f.watch().onSettling?.();
if (kind === 'binding') f.get.mockReturnValue('replacement');
if (kind === 'directory') f.allowed.mockReturnValue(false);
@@ -75,7 +79,7 @@ describe('IM session background results', () => {
it('teardown suppresses the observer cancellation result', () => {
const f = fixture();
- f.output.start('session', '/work');
+ f.output.start('session', '/work', 'other-task');
f.output.clear();
expect(f.cancel).toHaveBeenCalledOnce();
expect(f.send).not.toHaveBeenCalled();
@@ -83,24 +87,70 @@ describe('IM session background results', () => {
it('a cancelled preflight cannot claim the next turn', () => {
const f = fixture();
- f.output.start('session', '/work');
+ f.output.start('session', '/work', 'other-task');
const abandoned = f.watch();
f.output.cancel('session');
- f.output.start('session', '/work');
+ f.output.start('session', '/work', 'other-task');
abandoned.onEnd(result);
expect(f.send).not.toHaveBeenCalled();
+ f.watch().onSettling?.();
f.watch().onEnd(result);
expect(f.send).toHaveBeenCalledOnce();
});
- it('ignores empty output and admits the following turn during attachment collection', () => {
+ it('relays only scheduler and other-task turns, never desktop input', () => {
+ const f = fixture();
+ f.output.start('session', '/work');
+ f.watch().onSettling?.(undefined);
+ f.watch().onEnd(result);
+ expect(f.send).not.toHaveBeenCalled();
+
+ f.output.start('session', '/work');
+ f.watch().onSettling?.({ kind: 'scheduler', scheduleId: 's', runId: 'r' });
+ f.watch().onEnd(result);
+ expect(f.send).toHaveBeenCalledOnce();
+
+ f.output.start('session', '/work', 'other-task');
+ f.watch().onSettling?.(undefined);
+ f.watch().onEnd(result);
+ expect(f.send).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps a silenced scheduler run quiet but still delivers its failure', () => {
+ const silencedRuns = new Set(['quiet-run']);
+ setSilencedRunProbe((runId) => silencedRuns.has(runId));
+ const origin = (runId: string) => ({ kind: 'scheduler' as const, scheduleId: 's', runId });
const f = fixture();
+
+ f.output.start('session', '/work');
+ f.watch().onSettling?.(origin('quiet-run'));
+ // The run finishes after the terminal event; the decision taken at settle time stands.
+ silencedRuns.delete('quiet-run');
+ f.watch().onSettling?.();
+ f.watch().onEnd(result);
+ expect(f.send).not.toHaveBeenCalled();
+
+ silencedRuns.add('failed-run');
f.output.start('session', '/work');
+ f.watch().onSettling?.(origin('failed-run'));
+ f.watch().onEnd({ status: 'error', finalText: '', errorMessage: 'boom', durationMs: 1 });
+ expect(f.send).toHaveBeenCalledOnce();
+
+ f.output.start('session', '/work');
+ f.watch().onSettling?.(origin('notified-run'));
+ f.watch().onEnd(result);
+ expect(f.send).toHaveBeenCalledTimes(2);
+ });
+
+ it('ignores empty output and admits the following turn during attachment collection', () => {
+ const f = fixture();
+ f.output.start('session', '/work', 'other-task');
const first = f.watch();
first.onSettling?.();
- f.output.start('session', '/work');
+ f.output.start('session', '/work', 'other-task');
expect(f.watchContinuation).toHaveBeenCalledTimes(2);
first.onEnd({ ...result, finalText: '' });
+ f.watch().onSettling?.();
f.watch().onEnd(result);
expect(f.send).toHaveBeenCalledOnce();
});
diff --git a/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts b/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts
index 76e1126b28..5fb1eedf45 100644
--- a/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts
+++ b/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts
@@ -271,8 +271,9 @@ describe('background results during normal turn delivery', () => {
signal(req.sessionId, req.workingDir, 'starting');
expect(watches).toHaveLength(0);
req.onTurnTerminal?.();
- signal(req.sessionId, req.workingDir, 'starting');
+ signal(req.sessionId, req.workingDir, 'starting', 'other-task');
expect(watches).toHaveLength(1);
+ watches[0]!.onSettling?.();
watches[0]!.onEnd({ status: 'ok', finalText: 'next result', errorMessage: null, durationMs: 1 });
fr.finish({ finalText: 'original result' });
await tick();
diff --git a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
index 45f1026eca..1eb259db0a 100644
--- a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
+++ b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
@@ -3552,6 +3552,24 @@ describe('watchContinuation: 观察桌面端续跑并回流', () => {
expect(ends[0]?.errorMessage).toBeNull();
});
+ it('轮次收口时把这一轮的来源同步交给 onSettling(后台回传据此读静默态)', async () => {
+ fakeMaker.getSession.mockReturnValueOnce(makeManualSession('sess-live'));
+ const runner = createMakerHookSessionRunner({ log });
+ const settled: unknown[] = [];
+ const { req, events } = watchReq({ onSettling: (origin?: unknown) => settled.push(origin) });
+ runner.watchContinuation!(req as never);
+
+ const origin = { kind: 'scheduler', scheduleId: 's1', runId: 'r1' };
+ const cb = h.eventCbs.get('sess-live')!;
+ cb({ type: 'text', data: { text: '巡检完成', isFinal: true }, turnOrigin: origin } as never);
+ cb({ type: 'done', data: null, turnOrigin: origin } as never);
+ // 终态事件当拍同步拿到来源, 早于异步收口。
+ expect(settled[0]).toEqual(origin);
+ expect(events).not.toContain('end:ok');
+ await flush();
+ expect(events.at(-1)).toBe('end:ok');
+ });
+
it('续跑轮同样吃到多消息累积语义: 两条 claude 消息都在, 不只剩最后一条', async () => {
// run() 与 watchContinuation 共用 observeHookTurn, 所以 2026-07-28 那个
// 「先回一句 → 思考 → 终答 只剩最后一条」的修订对续跑轮自动生效。抽取若
diff --git a/apps/desktop/src/main/hook-control/backgroundResults.ts b/apps/desktop/src/main/hook-control/backgroundResults.ts
index b548f7ad39..0711666f26 100644
--- a/apps/desktop/src/main/hook-control/backgroundResults.ts
+++ b/apps/desktop/src/main/hook-control/backgroundResults.ts
@@ -3,6 +3,8 @@ import { makeTurnEnd, type HookMessage } from '@cindy/slack-hook-protocol';
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';
/** Shares the normal observer/final attachment collector; no task replay or outbox. */
export function createBackgroundResults(deps: {
@@ -16,7 +18,7 @@ export function createBackgroundResults(deps: {
}) {
const watches = new Map<string, { cancel(): void; active: boolean }>();
return {
- start(sessionId: string, workingDir: string) {
+ start(sessionId: string, workingDir: string, source?: ChannelTurnSource) {
if (deps.owned(sessionId) || watches.has(sessionId) || !deps.runner.watchContinuation) return;
const targets = (deps.bindings.findBySession?.(sessionId) ?? []).filter(({ connectionId, externalKey }) => {
const provider = providerForExternalKey(externalKey);
@@ -29,14 +31,24 @@ export function createBackgroundResults(deps: {
const state = { cancel: () => {}, active: true };
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.
+ let relay: 'all' | 'failure' | 'none' | null = null;
state.cancel = deps.runner.watchContinuation({
sessionId, workingDir,
isDirAuthorized: (dir) => senders.some((t) => deps.allowed(t.connectionId, dir)),
- onClaim() {}, onProgress() {}, onSettling: detach,
+ onClaim() {}, onProgress() {},
+ onSettling(origin) {
+ relay ??= origin?.kind === 'scheduler'
+ ? (isSilencedSchedulerTurn(origin) ? 'failure' : 'all')
+ : source === 'other-task' ? 'all' : 'none';
+ detach();
+ },
onAbandon: () => { state.active = false; detach(); },
onEnd(outcome) {
detach();
if (!state.active || generation !== deps.generation() ||
+ (relay !== 'all' && !(relay === 'failure' && outcome.status === 'error')) ||
(!outcome.finalText.trim() && !outcome.errorMessage && !outcome.attachments?.length)) return;
state.active = false;
for (const target of senders) {
diff --git a/apps/desktop/src/main/hook-control/dispatcher.ts b/apps/desktop/src/main/hook-control/dispatcher.ts
index 5a853ea1cb..0b3ecf2eb8 100644
--- a/apps/desktop/src/main/hook-control/dispatcher.ts
+++ b/apps/desktop/src/main/hook-control/dispatcher.ts
@@ -71,6 +71,8 @@ import {
makeProviderCommandsSet,
} from '@cindy/slack-hook-protocol';
import { createTelegramMessageLifecycle, type TelegramMessageLifecycle } from '@cindy/im';
+import type { SendOrigin } from '@cindy/maker-core';
+import type { ChannelTurnSource } from '../maker-ipc/channelTurnSignal.js';
import type { AutoReviewQuotedMessage } from '@cindy/maker-shared/auto-review-intent';
import { HOOK_CHAT_WORKSPACE_ALIAS } from '../../shared/hookControlIpc.js';
@@ -163,8 +165,11 @@ export interface HookContinuationWatchRequest {
* 已不是活跃轮, 于是判定被 Stop 顶掉并就地收口。少了这一步, 附件收集那段时间里它还
* 挂在表上, 排在后面的桌面消息一 dispatch 就会被误判成顶替
* (review: "附件收集期间误判顶替")。发帧的闭包不受影响, 迟到的 onEnd 照样如实收口。
+ *
+ * 轮次真正收口时附这一轮的来源(此刻 scheduler run 仍在跑, 可同步读静默态);
+ * 停止观察等其它路径不带。
*/
- onSettling?: () => void;
+ onSettling?: (origin?: SendOrigin) => void;
/** 收口(仅 onClaim 之后)。 */
onEnd: (outcome: HookRunOutcome) => void;
/** 一个事件都没等到就放弃(onClaim 未发生)。 */
@@ -353,7 +358,7 @@ export interface HookDispatcherDeps {
* 返回退订函数, dispose 时调用。
*/
subscribeUiContinuation?: (listener: (sessionId: string, clientId: string) => void) => () => void;
- subscribeChannelTurn?: (listener: (sessionId: string, workingDir: string, phase: 'starting' | 'undispatched') => void) => () => void;
+ subscribeChannelTurn?: (listener: (sessionId: string, workingDir: string, phase: 'starting' | 'undispatched', source?: ChannelTurnSource) => void) => () => void;
/**
* 可选: 订阅「桌面端在某会话里做了与续跑无关的事」(生产为 maker-ipc 的
* onUiSessionIntervention)。命中即作废该会话的待续跑记账 —— 记账只按 sessionId
@@ -1436,8 +1441,8 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
sender: (connectionId) => accountActive && serverFeatures.get(connectionId)?.includes(HOOK_FEATURE_SESSION_RESULT)
? sendFns.get(connectionId) : undefined,
});
- const unsubscribeBackgroundResults = deps.subscribeChannelTurn?.((sessionId, dir, phase) => {
- if (phase === 'starting') backgroundResults.start(sessionId, dir);
+ const unsubscribeBackgroundResults = deps.subscribeChannelTurn?.((sessionId, dir, phase, source) => {
+ if (phase === 'starting') backgroundResults.start(sessionId, dir, source);
else backgroundResults.cancel(sessionId);
});
diff --git a/apps/desktop/src/main/hook-control/ipc.ts b/apps/desktop/src/main/hook-control/ipc.ts
index cec484aa1f..b35a38f900 100644
--- a/apps/desktop/src/main/hook-control/ipc.ts
+++ b/apps/desktop/src/main/hook-control/ipc.ts
@@ -553,7 +553,7 @@ function ensureInstances(): { store: SlackHookStore; manager: HookControlManager
// 「用户在桌面端点了重试 / 继续任务」信号 -> 把那一轮接回渠道原消息
// (turn.reopen, 协议阶段 18)。信号由 maker 的发送事务发布。
subscribeUiContinuation: onUiContinuation,
- subscribeChannelTurn: (listener) => onChannelTurn((session, phase) => listener(session.id, session.workDir, phase)),
+ subscribeChannelTurn: (listener) => onChannelTurn((session, phase, source) => listener(session.id, session.workDir, phase, source)),
subscribeUiSessionIntervention: onUiSessionIntervention,
subscribeUiTurnDispatching: onUiTurnDispatching,
subscribeUiTurnUndispatched: onUiTurnUndispatched,
diff --git a/apps/desktop/src/main/hook-control/turnObserver.ts b/apps/desktop/src/main/hook-control/turnObserver.ts
index 1067f109d8..b3db0db8bf 100644
--- a/apps/desktop/src/main/hook-control/turnObserver.ts
+++ b/apps/desktop/src/main/hook-control/turnObserver.ts
@@ -21,7 +21,7 @@
* 本模块只碰事件流与定时器, 不做 IO —— 图片旁路、附件收集、落库都留在调用方。
*/
-import type { AgentEvent, TurnContinuationState } from '@cindy/maker-core';
+import type { AgentEvent, SendOrigin, TurnContinuationState } from '@cindy/maker-core';
import { isTerminalAgentErrorEvent } from '@cindy/maker-core';
import {
@@ -93,8 +93,8 @@ export interface HookTurnObserverDeps {
flushProgressOnDone?: boolean;
/** tool_result 全文旁路(出站图片收集留在调用方, 观察器不碰 IO)。 */
onToolResult?: (fullText: string) => void;
- /** 完整 turn(含后台续跑)收口时同步通知,早于 finished settle。 */
- onTurnTerminal?: () => void;
+ /** 完整 turn(含后台续跑)收口时同步通知,早于 finished settle;附这一轮最后见到的来源。 */
+ onTurnTerminal?: (origin: SendOrigin | undefined) => void;
/** silent-stop 自动续跑守卫的 settle 订阅(生产为 maker-ipc 的同名函数)。 */
onSilentStopSettled: (
sessionId: string,
@@ -156,6 +156,7 @@ export function observeHookTurn(
});
let errorReason: string | null = null;
+ let turnOrigin: SendOrigin | undefined;
let stopListening: (() => void) | undefined;
const finished = new Promise<void>((resolve, reject) => {
let turnTerminalNotified = false;
@@ -165,7 +166,7 @@ export function observeHookTurn(
if (turnTerminalNotified) return;
turnTerminalNotified = true;
try {
- onTurnTerminal?.();
+ onTurnTerminal?.(turnOrigin);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
log.warn(`[hook-runner] onTurnTerminal failed: ${message}`);
@@ -203,6 +204,7 @@ export function observeHookTurn(
});
const off = session.onEvent((ev: AgentEvent) => {
if (isImSubagentEvent(ev) || ev.turnScope === 'background') return;
+ if (ev.turnOrigin) turnOrigin = ev.turnOrigin;
if (ev.type === 'text') {
// 正文累积(isFinal 逐条契约 / 定稿段按消息切开 / fallbackTail 自成段 /
// uuid 缺失退 requestId)都在 presenter 的 finalized-segments 策略里。
diff --git a/apps/desktop/src/main/im/shared/__tests__/orchestratorOutput.test.ts b/apps/desktop/src/main/im/shared/__tests__/orchestratorOutput.test.ts
index 1174ff1d13..f39c88b9b7 100644
--- a/apps/desktop/src/main/im/shared/__tests__/orchestratorOutput.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/orchestratorOutput.test.ts
@@ -34,7 +34,7 @@ vi.mock('../messageHandler', () => ({ createMessageHandler: () => vi.fn() }));
vi.mock('../cardActionHandler', () => ({ createCardActionHandler: () => vi.fn() }));
import { createImOrchestrator } from '../orchestrator';
-import { publishChannelTurn } from '../../../maker-ipc/channelTurnSignal';
+import { channelTurnSourceFor, publishChannelTurn, withChannelTurnSource } from '../../../maker-ipc/channelTurnSignal';
for (const channel of ['telegram', 'feishu', 'discord', 'wechat', 'wecom', 'dingtalk'] as const) {
createImOrchestrator({
@@ -66,13 +66,26 @@ describe('background output route recovery', () => {
mocks.limit.mockResolvedValue([{ ...nativeRow, source }]);
mocks.binding.mockReturnValue(binding);
await publishChannelTurn(session, 'starting');
- expect(mocks.attach).toHaveBeenCalledExactlyOnceWith(session, 'group-user', { attached: true, scopeKey: 'topic' });
+ expect(mocks.attach).toHaveBeenCalledExactlyOnceWith(session, 'group-user', { attached: true, scopeKey: 'topic' }, undefined);
});
it.each(['feishu', 'telegram', 'wechat', 'wecom', 'dingtalk'])('falls back to native %s identity without a binding', async (source) => {
mocks.limit.mockResolvedValue([{ ...nativeRow, source, imBotContextId: 'bot', imUserId: 'native-user' }]);
await publishChannelTurn(session, 'starting');
- expect(mocks.attach).toHaveBeenCalledExactlyOnceWith(session, 'native-user', { attached: false, scopeKey: undefined });
+ expect(mocks.attach).toHaveBeenCalledExactlyOnceWith(session, 'native-user', { attached: false, scopeKey: undefined }, undefined);
+ });
+
+ it('passes the other-task source of the send that starts the turn, only to that turn', async () => {
+ mocks.limit.mockResolvedValue([{ ...nativeRow, source: 'telegram', imBotContextId: 'bot', imUserId: 'native-user' }]);
+ const other = { kind: 'session', senderSessionId: 'sender', displayText: 'hi' };
+ await withChannelTurnSource(session.id, channelTurnSourceFor(other, false), () => publishChannelTurn(session, 'starting'));
+ expect(mocks.attach).toHaveBeenLastCalledWith(session, 'native-user', { attached: false, scopeKey: undefined }, 'other-task');
+ await publishChannelTurn(session, 'starting');
+ expect(mocks.attach).toHaveBeenLastCalledWith(session, 'native-user', { attached: false, scopeKey: undefined }, undefined);
+ // Internal delegation coordination and guest-projected origins are not other-task mail.
+ expect(channelTurnSourceFor(other, true)).toBeUndefined();
+ expect(channelTurnSourceFor({ ...other, senderSessionId: '' }, false)).toBeUndefined();
+ expect(channelTurnSourceFor({ kind: 'scheduler', scheduleId: 's' }, false)).toBeUndefined();
});
it.each([false, true])('uses stable Discord identity for cold route (takeover: %s)', async (attached) => {
@@ -82,7 +95,7 @@ describe('background output route recovery', () => {
await publishChannelTurn(session, 'starting');
expect(mocks.attach).toHaveBeenCalledExactlyOnceWith(session, attached ? 'group-user' : 'user', {
attached, scopeKey: attached ? 'topic' : undefined,
- });
+ }, undefined);
mocks.attach.mockClear();
mocks.botContextId.mockReturnValue('other-bot');
await publishChannelTurn(session, 'starting');
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts
index 4eedc38dfe..ce6cd16492 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts
@@ -110,6 +110,7 @@ vi.mock('../fbotTitle', () => ({
import { ImAccountScopeClosedError } from '../../accountBoundary';
import { createTurnRunner, type ImTurnRunner } from '../turnRunner';
+import { setSilencedRunProbe } from '../../../scheduler-host/silent-output';
import type { ImCardBuilders } from '../cardBuilders';
import type { ImSessionRepo, ImSessionRow } from '../sessionRepo';
import type { ImChannelAdapter } from '../types';
@@ -569,6 +570,7 @@ describe('turnRunner 渠道任务后台结果回传', () => {
h.emit({ type: 'done', data: {} });
await vi.waitFor(() => expect(stub.finalize).toHaveBeenCalledTimes(1));
if (action === 'next-background') {
+ runner.attachSessionOutput(h.session, 'U1', undefined, 'other-task');
h.emit({ type: 'text', data: { text: 'second background' } });
h.emit({ type: 'done', data: {} });
await vi.waitFor(() => expect(stub.finalize).toHaveBeenCalledTimes(2));
@@ -696,7 +698,7 @@ describe('turnRunner 渠道任务后台结果回传', () => {
} }, fakeRepo, fakeCards);
}
const h = makeSessionHarness('image-background');
- runner.attachSessionOutput(h.session, 'U1');
+ runner.attachSessionOutput(h.session, 'U1', undefined, 'other-task');
const absPath = path.resolve('generated.png');
mocks.resolveXdtImageUrl.mockReturnValue({ absPath });
const event: AgentEvent = { type: 'tool_result_full', data: {
@@ -718,7 +720,7 @@ describe('turnRunner 渠道任务后台结果回传', () => {
it('远端后台轮次不把媒体路径作为本地文件发送', async () => {
const h = makeSessionHarness('remote-background');
Object.assign(h.session, { remoteHostId: 'ssh-host' });
- runner.attachSessionOutput(h.session, 'U1');
+ runner.attachSessionOutput(h.session, 'U1', undefined, 'other-task');
h.emit({ type: 'tool_result_full', data: { fullText: '{"xdt_image_url":"xdt-image://remote"}' } });
h.emit({ type: 'done', data: {} });
expect(mocks.resolveXdtImageUrl).not.toHaveBeenCalled();
@@ -735,7 +737,7 @@ describe('turnRunner 渠道任务后台结果回传', () => {
}
const h = makeSessionHarness('remote-markdown');
Object.assign(h.session, { remoteHostId: 'ssh-host' });
- runner.attachSessionOutput(h.session, 'U1');
+ runner.attachSessionOutput(h.session, 'U1', undefined, 'other-task');
h.emit({ type: 'text', data: {
text: '结果 ![图](xdt-image://remote.png) ![媒体](cindy-media://blobs/remote.png) [文件](xdt-file:///repo/report.txt)',
isFinal: true,
@@ -767,7 +769,7 @@ describe('turnRunner 渠道任务后台结果回传', () => {
}
const h = makeSessionHarness('citation-background');
if (remote) Object.assign(h.session, { remoteHostId: 'ssh-host' });
- runner.attachSessionOutput(h.session, 'U1');
+ runner.attachSessionOutput(h.session, 'U1', undefined, 'other-task');
const turnOrigin = remote
? { kind: 'scheduler' as const, scheduleId: 's', scheduleName: 'daily' }
: undefined;
@@ -798,12 +800,62 @@ describe('turnRunner 渠道任务后台结果回传', () => {
await runner.disposeAllSessions();
});
+ it.each(['rich-card', 'chunked-text'] as const)('%s 静默的自动任务轮次不回传;请求提醒后只发终稿,失败照发', async (kind) => {
+ const silencedRuns = new Set<string>();
+ setSilencedRunProbe((runId) => silencedRuns.has(runId));
+ try {
+ const stub = streamingHandleStub();
+ mocks.slackIm.startStreamingText.mockResolvedValue(stub);
+ if (kind === 'chunked-text') {
+ runner = createTurnRunner({ ...fakeAdapter, output: {
+ kind, im: fakeAdapter.im, commitFinal: vi.fn(async () => undefined),
+ } }, fakeRepo, fakeCards);
+ }
+ const h = makeSessionHarness('silent-background');
+ runner.attachSessionOutput(h.session, 'U1');
+ const origin = (runId: string) =>
+ ({ kind: 'scheduler' as const, scheduleId: 's', scheduleName: 'daily', runId });
+ const delivered = () => kind === 'rich-card'
+ ? stub.finalize.mock.calls.map((call) => (call as unknown[])[0])
+ : mocks.slackIm.sendMarkdownText.mock.calls.map((call) => (call as unknown[])[1]);
+ const tick = () => new Promise((resolve) => setTimeout(resolve, 10));
+
+ silencedRuns.add('quiet');
+ h.emit({ type: 'tool_use', data: { toolName: 'Read', input: { file_path: '/x/a.ts' } }, turnOrigin: origin('quiet') });
+ h.emit({ type: 'text', data: { text: '无新变化', isFinal: true }, turnOrigin: origin('quiet') });
+ h.emit({ type: 'done', data: {}, turnOrigin: origin('quiet') });
+ // The run is released after its terminal event; the decision taken at done stands.
+ silencedRuns.delete('quiet');
+ await tick();
+ expect(mocks.slackIm.startStreamingText).not.toHaveBeenCalled();
+ expect(delivered()).toEqual([]);
+
+ silencedRuns.add('notified');
+ h.emit({ type: 'tool_use', data: { toolName: 'Read', input: { file_path: '/x/b.ts' } }, turnOrigin: origin('notified') });
+ h.emit({ type: 'text', data: { text: '发现新评论', isFinal: true }, turnOrigin: origin('notified') });
+ await tick();
+ expect(mocks.slackIm.startStreamingText).not.toHaveBeenCalled();
+ silencedRuns.delete('notified'); // schedule_notify_current_run
+ h.emit({ type: 'done', data: {}, turnOrigin: origin('notified') });
+ await vi.waitFor(() => expect(delivered()).toEqual(['🤖 自动任务「daily」\n\n发现新评论']));
+ expect(stub.replace).not.toHaveBeenCalled();
+
+ silencedRuns.add('failed');
+ h.emit({ type: 'error', data: { message: 'failed', isTerminal: true }, turnOrigin: origin('failed') });
+ await vi.waitFor(() => expect(delivered()).toHaveLength(2));
+ expect(delivered()[1]).toContain(slackUi.agent.runtimeError('failed'));
+ } finally {
+ setSilencedRunProbe(null);
+ await runner.disposeAllSessions();
+ }
+ });
+
it('重启后仅恢复输出监听,不新建会话;重复恢复不会重复回复', async () => {
const h = makeSessionHarness('cold-session');
const stub = streamingHandleStub();
mocks.slackIm.startStreamingText.mockResolvedValue(stub);
- runner.attachSessionOutput(h.session, 'U1');
- runner.attachSessionOutput(h.session, 'U1');
+ runner.attachSessionOutput(h.session, 'U1', undefined, 'other-task');
+ runner.attachSessionOutput(h.session, 'U1', undefined, 'other-task');
h.emit({ type: 'text', data: { text: '冷启动结果', isFinal: true } });
h.emit({ type: 'done', data: {} });
await vi.waitFor(() => expect(stub.finalize).toHaveBeenCalledWith('冷启动结果'));
@@ -842,7 +894,8 @@ describe('turnRunner 渠道任务后台结果回传', () => {
expect(h.unsubscribe).toHaveBeenCalledTimes(1);
});
- async function channelAndIdle(): Promise<SessionHarness> {
+ /** IM-owned task gone idle; the next non-IM turn starts with `source` (default: another task's mail). */
+ async function channelAndIdle(source: 'other-task' | 'desktop' = 'other-task'): Promise<SessionHarness> {
await runTurn('100.1');
const h = harnesses.get(sessionIdFor('T1', 'U1', '100.1'))!;
const initial = streamingHandleStub();
@@ -852,9 +905,32 @@ describe('turnRunner 渠道任务后台结果回传', () => {
await vi.waitFor(() => expect(initial.finalize).toHaveBeenCalledTimes(1));
mocks.slackIm.startStreamingText.mockClear();
mocks.slackIm.sendMarkdownText.mockClear();
+ runner.attachSessionOutput(h.session, 'U1', undefined, source === 'desktop' ? undefined : source);
return h;
}
+ it('桌面输入发起的轮次不回传,下一次其它任务来信仍回传', async () => {
+ const h = await channelAndIdle('desktop');
+ const stub = streamingHandleStub();
+ mocks.slackIm.startStreamingText.mockResolvedValue(stub);
+ 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 new Promise((resolve) => setTimeout(resolve, 10));
+ expect(mocks.slackIm.startStreamingText).not.toHaveBeenCalled();
+
+ runner.attachSessionOutput(h.session, 'U1', undefined, 'other-task');
+ h.emit({ type: 'text', data: { text: '来信结果', isFinal: true } });
+ h.emit({ type: 'done', data: {} });
+ await vi.waitFor(() => expect(stub.finalize).toHaveBeenCalledExactlyOnceWith('来信结果'));
+
+ // The mark belongs to that turn only; a following desktop turn stays local again.
+ 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.each([
['自动任务', { kind: 'scheduler', scheduleId: 's1', scheduleName: '检查进度' }],
['其它任务消息触发的轮次', undefined],
@@ -896,6 +972,7 @@ describe('turnRunner 渠道任务后台结果回传', () => {
h.emit({ type: 'done', data: {} });
await vi.waitFor(() => expect(commitFinal).toHaveBeenCalledTimes(1));
mocks.slackIm.sendMarkdownText.mockClear();
+ runner.attachSessionOutput(h.session, 'U1', undefined, 'other-task');
h.emit({ type: 'text', data: { text: '后台结果', isFinal: true } });
expect(mocks.slackIm.sendMarkdownText).not.toHaveBeenCalled();
h.emit({ type: 'done', data: {} });
@@ -925,6 +1002,7 @@ describe('turnRunner 渠道任务后台结果回传', () => {
h.emit({ type: 'done', data: {} });
expect(mocks.slackIm.startStreamingText).not.toHaveBeenCalled();
mocks.slackIm.startStreamingText.mockRejectedValue(new Error('offline'));
+ runner.attachSessionOutput(h.session, 'U1', undefined, 'other-task');
h.emit({ type: 'text', data: { text: '结果' } });
h.emit({ type: 'done', data: {} });
await vi.waitFor(() => expect(mocks.logger.warn).toHaveBeenCalledWith(expect.stringContaining('transpond finalize failed')));
diff --git a/apps/desktop/src/main/im/shared/orchestrator.ts b/apps/desktop/src/main/im/shared/orchestrator.ts
index bf3c04ef91..9cb0fc9433 100644
--- a/apps/desktop/src/main/im/shared/orchestrator.ts
+++ b/apps/desktop/src/main/im/shared/orchestrator.ts
@@ -50,7 +50,7 @@ const registry = new Map<ImChannelName, ImOrchestrator>();
// Background sends can be the first activity after restart: restore only output
// routing from the saved channel identity, without creating/resuming a session.
-onChannelTurn(async (session, phase) => {
+onChannelTurn(async (session, phase, source) => {
if (phase !== 'starting') return;
const generation = captureImAccountGeneration();
if (generation === null || ![...registry.values()].some((o) => o.adapter.im.getStatus().kind === 'connected')) return;
@@ -69,7 +69,7 @@ onChannelTurn(async (session, phase) => {
if (userId) orchestrator.turnRunner.attachSessionOutput(session, userId, {
attached: binding !== null,
scopeKey: binding?.scopeKey,
- });
+ }, source);
});
/**
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index 70b9575582..4e4f3c4bc7 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -123,6 +123,8 @@ import { agentHandoffPending } from '../../maker-ipc/agentHandoffPendingSingleto
import { prependHandoffToUserMessage, prependNoteToWireUserMessage } from '../../maker-ipc/agentHandoff';
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 { listMessagesForAgentHandoff } from '../../localDb/ipc/messages';
import {
enqueueDurableWrite,
@@ -371,6 +373,11 @@ interface SessionState {
scheduledTranspond: ScheduledTranspond | null;
/** Agent execution ended, but its background output is still being delivered. */
pendingTranspondFinals: number;
+ /**
+ * 正在开始的非 IM 轮次由其它任务的可见来信发起(channelTurnSignal 盖章)。桌面输入等
+ * 其它来源不回传;在该轮终态清除,避免沿用到下一轮。
+ */
+ otherTaskTurn: boolean;
}
/**
@@ -381,6 +388,13 @@ interface ScheduledTranspond {
silentStopSettleUnsub: (() => void) | null;
/** 仅 scheduler 轮次显示自动任务标题,其它来源直接回复正文。 */
header: string | null;
+ /** 首条事件的来源;静默判据在收口时按它的 runId 读。 */
+ origin: AgentEvent['turnOrigin'];
+ /**
+ * 首条事件时 run 已静默(静默运行任务):只累积不开卡,收口时仍静默就整轮不发;
+ * 中途请求提醒则收口时一次性发终稿。
+ */
+ held: boolean;
activity: TurnActivityState;
activityTicker: ReturnType<typeof setInterval> | null;
/** 自动任务这一轮 agent 的回复文本累加。 */
@@ -520,7 +534,12 @@ export type ImTurnDispatch =
/** createTurnRunner 返回的编排实例 — per channel 一个。 */
export interface ImTurnRunner {
- attachSessionOutput(session: MakerSession, userId: string, route?: { attached: boolean; scopeKey?: string }): void;
+ attachSessionOutput(
+ session: MakerSession,
+ userId: string,
+ route?: { attached: boolean; scopeKey?: string },
+ source?: ChannelTurnSource,
+ ): void;
runAgentTurn(args: ImRunAgentTurnArgs): Promise<void>;
/**
* 把渠道用户消息**提前**写进本地 messages 表 —— 只给「dispatch 之前还有重活」
@@ -1951,6 +1970,7 @@ export function createTurnRunner(
attached,
scheduledTranspond: null,
pendingTranspondFinals: 0,
+ otherTaskTurn: false,
};
sessionStates.set(row.id, state);
@@ -2411,12 +2431,14 @@ export function createTurnRunner(
if (!state) return;
const turn = state.queue[0];
if (!turn) {
- // 渠道自有任务始终把回复送回自己的聊天;跨任务消息没有 scheduler
- // turnOrigin,也不能丢弃。通知回复只临时使用普通任务,不建立持续转播。
- // 接管普通任务仍仅转播 scheduler,保留其桌面输入的原有可见性。
+ // 只回传自动执行:scheduler 轮次,以及渠道自有任务里其它任务来信触发的轮次。
+ // 桌面输入留在桌面。通知回复只临时使用普通任务,不建立持续转播;接管普通任务
+ // 仍仅转播 scheduler。已开始的转播持续到收口(含 silent-stop 自动续跑)。
+ const channelOwned = !state.preserveSessionConfig;
if (
- !state.preserveSessionConfig ||
- (state.attached && event.turnOrigin?.kind === 'scheduler')
+ state.scheduledTranspond !== null ||
+ (event.turnOrigin?.kind === 'scheduler' && (channelOwned || state.attached)) ||
+ (channelOwned && state.otherTaskTurn)
) {
transpondScheduledEvent(state, event);
}
@@ -2424,6 +2446,7 @@ export function createTurnRunner(
// 非终止 error 表示底层仍在自动恢复,不能抢跑下一条消息(放行排队消息会让
// 下一条撞上 SESSION_RUNNING)。
if (isProductTurnDoneEvent(event) || isTerminalAgentErrorEvent(event)) {
+ state.otherTaskTurn = false;
maybeDispatchNextQueued(state, userId);
return;
}
@@ -2703,7 +2726,7 @@ export function createTurnRunner(
function refreshTranspondCard(state: SessionState): void {
const t = state.scheduledTranspond;
- if (!t || !richIm) return;
+ if (!t || !richIm || t.held) return;
void ensureTranspondHandle(state, t)
.then((h) => {
if (state.scheduledTranspond === t) h.replace(composeTranspondView(state, t, false));
@@ -2727,6 +2750,8 @@ export function createTurnRunner(
header: origin?.kind === 'scheduler'
? ui.agent.scheduledTaskHeader(origin.scheduleName ?? null)
: null,
+ origin,
+ held: isSilencedSchedulerTurn(origin),
activity: createTurnActivity(Date.now()),
activityTicker: null,
buffer: '',
@@ -2740,7 +2765,7 @@ export function createTurnRunner(
case 'tool_result_full': {
if (state.makerSession.remoteHostId) return;
const paths = collectToolResultImages(t.mediaAbsPaths, event);
- if (paths.length && richIm) {
+ if (paths.length && richIm && !t.held) {
void ensureTranspondHandle(state, t).then((handle) => {
if (sessionStates.get(state.makerSession.id) !== state) return;
for (const absPath of paths) handle.addExtraImageAbsPath?.(absPath);
@@ -2771,7 +2796,7 @@ export function createTurnRunner(
typeof data.toolUseId === 'string' ? data.toolUseId : undefined,
);
// 低频 ticker 刷新耗时(只刷已存在的卡)。
- if (richIm && !t.activityTicker) {
+ if (richIm && !t.held && !t.activityTicker) {
t.activityTicker = setInterval(() => {
t.streamingHandle?.replace(composeTranspondView(state, t, false));
}, ACTIVITY_TICK_MS);
@@ -2818,6 +2843,8 @@ export function createTurnRunner(
const t = state.scheduledTranspond;
if (!t) return;
state.scheduledTranspond = null; // 防重入(下一条 stray 不会再命中)
+ // 静默须在终态事件同步读(run 此时仍在跑)。失败照发;已开卡的不留半截卡。
+ const silenced = !errMsg && isSilencedSchedulerTurn(t.origin);
state.pendingTranspondFinals += 1;
clearSilentStopSettleWait(t);
clearTranspondTicker(t);
@@ -2831,6 +2858,7 @@ export function createTurnRunner(
if (!t.streamingHandle && t.buffer.length === 0 && t.mediaAbsPaths.length === 0 && t.activity.totalSteps === 0 && !errMsg) {
return;
}
+ if (silenced && !t.streamingHandlePromise) return;
if (output.kind === 'chunked-text' && !state.makerSession.remoteHostId && t.buffer.includes('![')) {
const materialized = await materializeLocalMarkdownImages({
text: t.buffer, workingDir: state.workingDir, sessionId: state.makerSession.id,
@@ -2856,6 +2884,7 @@ export function createTurnRunner(
}
const handle = await ensureTranspondHandle(state, t);
if (sessionStates.get(state.makerSession.id) !== state) return;
+ if (t.held) for (const absPath of t.mediaAbsPaths) handle.addExtraImageAbsPath?.(absPath);
await handle.finalize(body);
} catch (err) {
log.warn(
@@ -4095,9 +4124,10 @@ export function createTurnRunner(
}
return {
- attachSessionOutput: (session, userId, route) => {
+ attachSessionOutput: (session, userId, route, source) => {
const existing = sessionStates.get(session.id);
if (existing) {
+ existing.otherTaskTurn = source === 'other-task';
const userChanged = existing.userId !== userId;
if (route?.attached) {
existing.attached = true;
@@ -4124,6 +4154,7 @@ export function createTurnRunner(
attached: route?.attached === true,
scheduledTranspond: null,
pendingTranspondFinals: 0,
+ otherTaskTurn: source === 'other-task',
};
sessionStates.set(session.id, state);
state.unsubscribers.push(session.onEvent(handleEventFor(session.id, userId)));
diff --git a/apps/desktop/src/main/maker-ipc/channelTurnSignal.ts b/apps/desktop/src/main/maker-ipc/channelTurnSignal.ts
index 9d934b7e3a..814ac6865a 100644
--- a/apps/desktop/src/main/maker-ipc/channelTurnSignal.ts
+++ b/apps/desktop/src/main/maker-ipc/channelTurnSignal.ts
@@ -3,17 +3,73 @@ import { createLogger } from '../logger';
const log = createLogger('channel-turn');
export type ChannelTurnPhase = 'starting' | 'undispatched';
-const listeners = new Set<(session: Session, phase: ChannelTurnPhase) => void | Promise<void>>();
+/**
+ * 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.
+ */
+export type ChannelTurnSource = 'other-task';
+type ChannelTurnListener = (
+ session: Session,
+ phase: ChannelTurnPhase,
+ source: ChannelTurnSource | undefined,
+) => void | Promise<void>;
+const listeners = new Set<ChannelTurnListener>();
+/** Lives only for one Session.send call: the signal fires inside it, before provider output. */
+const pendingSources = new Map<string, { source: ChannelTurnSource }>();
/** Runs before provider output, including scheduler and cross-session direct sends. */
-export function onChannelTurn(listener: (session: Session, phase: ChannelTurnPhase) => void | Promise<void>): () => void {
+export function onChannelTurn(listener: ChannelTurnListener): () => void {
listeners.add(listener);
return () => { listeners.delete(listener); };
}
export async function publishChannelTurn(session: Session, phase: ChannelTurnPhase): Promise<void> {
+ const source = pendingSources.get(session.id)?.source;
+ pendingSources.delete(session.id);
await Promise.all([...listeners].map(async (listener) => {
- try { await listener(session, phase); }
+ try { await listener(session, phase, source); }
catch { log.warn('channel output observer could not be updated'); }
}));
}
+
+/** Classify a host-stamped user message origin (see AgentInputQueuedMessage['origin']). */
+export function channelTurnSourceFor(
+ origin: unknown,
+ internalCoordination: boolean,
+): ChannelTurnSource | undefined {
+ const typed = origin as { kind?: unknown; senderSessionId?: unknown } | null | undefined;
+ return !internalCoordination &&
+ typed?.kind === 'session' &&
+ typeof typed.senderSessionId === 'string' &&
+ typed.senderSessionId !== ''
+ ? 'other-task'
+ : undefined;
+}
+
+/** Mark the Session.send about to run; call the returned release once that send returns. */
+export function noteChannelTurnSource(
+ sessionId: string,
+ source: ChannelTurnSource | undefined,
+): () => void {
+ if (!source) return () => undefined;
+ const entry = { source };
+ pendingSources.set(sessionId, entry);
+ return () => {
+ if (pendingSources.get(sessionId) === entry) pendingSources.delete(sessionId);
+ };
+}
+
+/** Wrap the Session.send that dispatches a message from `source`. */
+export async function withChannelTurnSource<T>(
+ sessionId: string,
+ source: ChannelTurnSource | undefined,
+ send: () => Promise<T>,
+): Promise<T> {
+ const release = noteChannelTurnSource(sessionId, source);
+ try {
+ return await send();
+ } finally {
+ release();
+ }
+}
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index fd3e639ac5..6909ed035d 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -52,6 +52,7 @@ import {
validateExtraDirs,
} from './extraDirsValidator.js';
import type { MakerSessionCreateOpts } from './sessionRequest.js';
+import { channelTurnSourceFor, withChannelTurnSource } from './channelTurnSignal.js';
import type { CindyLearnInvocationGrant } from '../learn-host/invocationGrant.js';
import { AUTO_REVIEW_DELEGATED_CONTINUATION, currentAutoReviewResourceIntent, readAutoReviewUserText, restoreAutoReviewUserIntent, type AutoReviewHistoryMessage } from './autoReviewUserIntent.js';
@@ -1543,7 +1544,11 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
const retryTranscriptUserEntryId = sess.agentKind === 'pi' && so.retryUserClientId
? await deps.readPiUserEntry?.(sessionId, so.retryUserClientId)
: undefined;
- const sendResult = await sess.send(outgoing as never, {
+ // Other-task mail is the only non-scheduler turn whose reply IM relays (channelTurnSignal).
+ const sendResult = await withChannelTurnSource(sess.id, channelTurnSourceFor(
+ persistUserMessage?.origin,
+ persistUserMessage?.botTaskCoordination !== undefined,
+ ), () => sess.send(outgoing as never, {
...(retryTranscriptUserEntryId ? { retryTranscriptUserEntryId } : {}),
...(resolveScheduledIntent ? { resolveAutoReviewUserIntent: resolveScheduledIntent } : {}),
[AUTO_REVIEW_SOURCE_CONTENT]: autoReviewSourceContent,
@@ -1711,7 +1716,7 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
);
}
},
- });
+ }));
sendAccepted = sendResult.accepted;
if (sendAccepted) {
cleanupAfterAcceptance?.();
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 89a0438adb..8913edac66 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1267,6 +1267,7 @@ import {
publishUiTurnDispatching,
publishUiTurnUndispatched,
} from './uiContinuationSignal.js';
+import { channelTurnSourceFor, noteChannelTurnSource } from './channelTurnSignal.js';
import { readSilentStopAutoResumeSettings } from '../maker-host/silent-stop-auto-resume-store.js';
import {
AutoResumeBookkeeping,
@@ -10038,6 +10039,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const outgoingMessage: UserMessage = sourceNote
? (prependNoteToWireUserMessage(withHandoff as HandoffWireMessage, sourceNote) as UserMessage)
: withHandoff;
+ // Idle direct sends never carry internal coordination (that is force-queued).
+ const releaseTurnSource = noteChannelTurnSource(session.id, channelTurnSourceFor(source?.origin, false));
try {
const sendResult = await session.send(outgoingMessage, {
...opts,
@@ -10077,6 +10080,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
gitSnapshotCoordinator?.onTurnAbort(session.id);
}
throw err;
+ } finally {
+ releaseTurnSource();
}
};
return session.remoteHostId
diff --git a/apps/desktop/src/main/scheduler-host/index.ts b/apps/desktop/src/main/scheduler-host/index.ts
index b9fefd70ec..3725afdad3 100644
--- a/apps/desktop/src/main/scheduler-host/index.ts
+++ b/apps/desktop/src/main/scheduler-host/index.ts
@@ -53,6 +53,7 @@ import {
import { DrizzleScheduleStorage, type SchedulerDrizzleDb } from './storage';
import { ProjectAutomationLoader } from './project-automation-loader';
import { MakerScheduleRunner } from './runner';
+import { setSilencedRunProbe } from './silent-output';
import { listMessagesForAgentHandoff } from '../localDb/ipc/messages.js';
import { drainPersistQueue } from '../messagePersistBroadcaster.js';
import { buildForcedFailureRun } from './forcedFailureRun';
@@ -257,6 +258,7 @@ async function startSchedulerInternal(deps: StartSchedulerDeps): Promise<Schedul
},
});
_scheduler = scheduler;
+ setSilencedRunProbe((runId) => scheduler.isRunSilenced(runId));
void getRoutineEngine().catch((error) => deps.logger.warn?.('routine startup failed', { error: String(error) }));
_loader = loader;
deps.logger.info?.(`[scheduler-host] started${passive ? ' (passive: auto-fire disabled)' : ''}`);
@@ -318,6 +320,7 @@ export async function resetScheduler(): Promise<void> {
// Superseded startup rejects after stopping itself; teardown continues.
}
}
+ setSilencedRunProbe(null);
if (_scheduler) {
await _scheduler.stop();
}
diff --git a/apps/desktop/src/main/scheduler-host/silent-output.ts b/apps/desktop/src/main/scheduler-host/silent-output.ts
index 3688581098..1a2aad400d 100644
--- a/apps/desktop/src/main/scheduler-host/silent-output.ts
+++ b/apps/desktop/src/main/scheduler-host/silent-output.ts
@@ -1,6 +1,26 @@
-import type { AgentEvent } from '@cindy/maker-core';
+import type { AgentEvent, SendOrigin } from '@cindy/maker-core';
import type { Schedule } from '@cindy/maker-scheduler';
+/** Live scheduler policy, registered by the scheduler host; IM relays read it without loading the host. */
+let silencedRunProbe: ((runId: string) => boolean) | null = null;
+
+export function setSilencedRunProbe(probe: ((runId: string) => boolean) | null): void {
+ silencedRunProbe = probe;
+}
+
+/**
+ * Whether this scheduler turn's run is currently silenced. Read it synchronously at the turn's
+ * terminal event: the run is still in flight then, and the agent's notify/silence call is final.
+ * Unknown runs (restart, hook origins without runId) are not silenced, matching completion alerts.
+ */
+export function isSilencedSchedulerTurn(origin: SendOrigin | undefined): boolean {
+ return (
+ origin?.kind === 'scheduler' &&
+ typeof origin.runId === 'string' &&
+ silencedRunProbe?.(origin.runId) === true
+ );
+}
+
/** Ordinary tasks keep their transcript even when completion notifications are silent. */
export function hidesScheduledTranscript(
schedule: Pick<Schedule, 'source' | 'silentWhenIdle'>,
diff --git a/docs/product-rules/telegram-bot-parity.md b/docs/product-rules/telegram-bot-parity.md
index 2bf9cc055b..3e76b5eac0 100644
--- a/docs/product-rules/telegram-bot-parity.md
+++ b/docs/product-rules/telegram-bot-parity.md
@@ -268,8 +268,12 @@ hook 侧既有的逐轮 `[渠道说明]`,两者措辞不同但都向模型说
适用范围:个人飞书/Lark、Telegram、Discord、微信、企业微信、钉钉,以及官方 Telegram、Slack;X 不参与。
-个人渠道通过 `im/shared/turnRunner.ts` 回传非 IM 入站轮次的输出,
-包括自动任务、其它任务发送消息触发的回复;无需先 `/ctr` 接管。自动任务保留任务名,
+只回传自动执行的轮次:自动任务(scheduler `turnOrigin`),以及其它任务经 `send_to_session` 等
+发来的可见消息触发的回复。桌面里直接输入的消息、伙伴委派的内部协调输入都不回传。其它任务来信由
+主进程在派发它的那次 `Session.send` 期间盖章(`maker-ipc/channelTurnSignal.ts`),随该轮的开始信号
+交给两条路径,只作用于这一轮;不改 maker-core 的 `SendOrigin`,以免插件钩子等把它当作非用户轮次。
+
+个人渠道通过 `im/shared/turnRunner.ts` 回传上述轮次的输出,无需先 `/ctr` 接管。自动任务保留任务名,
其它来源直接显示回复正文,目的地沿用该任务原聊天和话题。正常 IM 入站轮次仍只发送一次;
子代理和旧轮次的后台事件不转播。纯文本渠道通过适配器使用现有有效聊天上下文发送最终结果。
个人后台正文与普通回复、官方后台结果共用 `stripInternalWebCitations` 清理内部引用标记,
@@ -291,10 +295,16 @@ bot 身份按入站使用的稳定 ID 校验;Discord 取 gateway application i
官方 Telegram、Slack 复用已有 hook binding、轮次观察和附件收集;双方宣告 `session-result-v1`
后,后台回传与任务派发共用渠道 key 判定,兼容既有 Slack 前缀、team-slack、旧频道和 DM key;X 不回传。
-结果用 `turn.end(background: true)` 发送,服务端在原私聊或话题新发消息。普通 IM 轮次和
+轮次终态时按来源决定是否发送(scheduler 来源,或开始时盖了其它任务来信章)。结果用 `turn.end(background: true)` 发送,服务端在原私聊或话题新发消息。普通 IM 轮次和
已有 retry/reopen 轮次不另发一份。发送前复核账号代次、连接、目录授权与会话绑定;服务端
再核对设备绑定、聊天归属及 `/new` 代次。Telegram 保存新消息 route,回复结果仍回到原 lane。
+静默的自动任务轮次不回传,两条路径同判据:轮次终态时读 scheduler 该 run 的静默标记
+(`scheduler-host/silent-output.ts` 的 `isSilencedSchedulerTurn`),与桌面完成通知一致——
+静默运行默认静默,`schedule_notify_current_run` 解除,`schedule_silence_current_run` 设为静默;
+失败照常回传。个人渠道对开始即静默的轮次不开流式卡,仅累积;收口仍静默则整轮不发,
+已请求提醒则一次性发终稿。中途才静默且已开卡的轮次照常收口,不留半截卡。
+
两条路径均为在线尽力投递,不增加离线补发或持久化出箱。官方能力需客户端与服务端同时支持,
旧版本通过能力协商保持原行为;本地测试通过不代表服务端已经部署或真实渠道已联调。