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): 后台续跑继承发起轮次的回复去向

Dashc12aff755236
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 ad1837d8cc..2457ce92f0 100644
--- a/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts
+++ b/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts
@@ -11,6 +11,7 @@ import { tmpdir } from 'node:os';
import { describe, expect, it, vi } from 'vitest';
import {
Session,
+ TurnDispatchRejectedError,
type AgentEvent,
type AgentSessionHandle,
type Capabilities,
@@ -19,8 +20,8 @@ import {
import { observeHookTurn } from '../turnObserver';
import {
onChannelTurn,
- publishChannelTurn,
- publishProviderInitiatedTurn,
+ createChannelTurnObserver,
+ withChannelTurnSource,
} from '../../maker-ipc/channelTurnSignal';
import { bindRuntimeRecoveryNotice } from '../../im/shared/runtimeRecoveryNotice';
import { setMainLocale } from '../../i18n';
@@ -379,13 +380,12 @@ describe('harness wake-ups of an IM-bound task (real Session)', () => {
handle, capabilities: {} as Capabilities, logger, turnStallMs: 0 });
// Production wiring: maker-ipc/sessionTurnObserver.ts.
session.setTurnLifecycleObserver({
- beforeProviderStart: () => publishChannelTurn(session, 'starting'),
- onUndispatched: () => publishChannelTurn(session, 'undispatched'),
+ ...createChannelTurnObserver(session),
onTerminal: () => undefined,
- onProviderInitiatedTurn: () => { void publishProviderInitiatedTurn(session); },
});
return {
session,
+ handle,
continuations,
/** One provider event; a terminal `done` without keepRunning flips the handle idle. */
async emit(event: Partial<AgentEvent>, opts: { keepRunning?: boolean } = {}) {
@@ -405,13 +405,13 @@ describe('harness wake-ups of an IM-bound task (real Session)', () => {
});
}
- 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';
+ it.each(['telegram:group:bot:-100200:user-7:g1', 'slack:T:C:1.2'])(
+ '%s keeps desktop-started background results in Cindy after a channel turn', async (externalKey) => {
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 live.session.send(req.prompt, { origin: { kind: 'user', surface: 'im' } });
await observer.finished;
return { status: 'ok', finalText: observer.finalText(), errorMessage: null, durationMs: 1 };
});
@@ -476,6 +476,32 @@ describe('harness wake-ups of an IM-bound task (real Session)', () => {
await h.emit({ type: 'done' });
await new Promise((resolve) => setTimeout(resolve, 10));
expect(turnEnds()).toHaveLength(3);
+ // Regression: a task created in Slack later runs tests from Cindy. Their completion
+ // wakes the provider without Session.send; it must inherit the desktop destination.
+ for (const report of ['Desktop test results.', 'Desktop final report.']) {
+ await h.emit({ type: 'text', data: { text: report, isFinal: true } });
+ await h.emit({ type: 'done' });
+ expect(turnEnds()).toHaveLength(3);
+ }
+ // A failed channel send must not turn the previous desktop work into channel output.
+ vi.mocked(h.handle.send).mockRejectedValueOnce(new TurnDispatchRejectedError('rejected'));
+ await expect(h.session.send('rejected channel request', { origin: { kind: 'user', surface: 'im' } }))
+ .resolves.toEqual({ accepted: false, reason: 'provider-rejected-before-dispatch' });
+ await expect(h.session.send('failed channel request', {
+ origin: { kind: 'user', surface: 'im' },
+ beforeProviderStart: async () => { throw new Error('preflight failed'); },
+ })).rejects.toThrow('preflight failed');
+ await h.emit({ type: 'text', data: { text: 'More desktop results.', isFinal: true } });
+ await h.emit({ type: 'done' });
+ expect(turnEnds()).toHaveLength(3);
+
+ // An actual new other-task request changes the destination again, including later wakes.
+ await withChannelTurnSource(h.session.id, 'other-task', () => h.session.send('other task request'));
+ await h.emit({ type: 'text', data: { text: 'Other task result.', isFinal: true } });
+ await h.emit({ type: 'done' });
+ await h.emit({ type: 'text', data: { text: 'Other task background result.', isFinal: true } });
+ await h.emit({ type: 'done' });
+ expect(turnEnds().slice(-2)).toEqual([[true, 'Other task result.'], [true, 'Other task background result.']]);
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,
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 1fc61afe54..068c5f1181 100644
--- a/apps/desktop/src/main/im/shared/__tests__/orchestratorOutput.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/orchestratorOutput.test.ts
@@ -96,12 +96,12 @@ 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', () => {
+ it.each([true, false])('marks a harness wake-up synchronously without a cold lookup (relay: %s)', (relay) => {
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);
+ void publishProviderInitiatedTurn(session, relay);
expect(mocks.note).toHaveBeenCalledTimes(6);
- expect(mocks.note).toHaveBeenCalledWith(session, 'provider-wake');
+ expect(mocks.note).toHaveBeenCalledWith(session, relay ? 'provider-wake' : 'provider-wake-local');
expect(mocks.limit).not.toHaveBeenCalled();
expect(mocks.attach).not.toHaveBeenCalled();
});
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 5550e499b5..d2b9360ba5 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts
@@ -985,7 +985,8 @@ describe('turnRunner 渠道任务后台结果回传', () => {
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.
+ // The mark ends with that turn: a desktop-origin wake stays in the app too.
+ runner.noteChannelTurnSource(h.session, 'provider-wake-local');
h.emit({ type: 'text', data: { text: '桌面里的回复', isFinal: true } });
h.emit({ type: 'done', data: {} });
await new Promise((resolve) => setTimeout(resolve, 10));
diff --git a/apps/desktop/src/main/im/shared/orchestrator.ts b/apps/desktop/src/main/im/shared/orchestrator.ts
index 8696b99d5f..dcef3ec736 100644
--- a/apps/desktop/src/main/im/shared/orchestrator.ts
+++ b/apps/desktop/src/main/im/shared/orchestrator.ts
@@ -72,7 +72,7 @@ const registry = new Map<string, 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') {
+ if (source === 'provider-wake' || source === 'provider-wake-local') {
// 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
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
index 5a68b78c8e..0ca034f97d 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
@@ -1555,7 +1555,11 @@ 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 () => {
+ it.each([
+ [undefined, 'provider-wake-local'],
+ [{ kind: 'user' as const, surface: 'im' as const }, 'provider-wake'],
+ [{ kind: 'scheduler' as const, scheduleId: 'hook:slack', surface: 'im' as const }, 'provider-wake'],
+ ])('inherits the dispatched origin %j when announcing a harness wake-up', async (origin, expectedSource) => {
const pushed: Array<AgentEvent | null> = [];
let wake: (() => void) | null = null;
let running = false;
@@ -1592,12 +1596,12 @@ describe('provider turn observer on real Session.send', () => {
});
const off = session.onEvent((value) => order.push(value.type));
try {
- await session.send('typed on desktop');
+ await session.send('launch background work', { origin });
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']);
+ expect(order).toEqual(['starting:none', 'text', 'done', `starting:${expectedSource}`, 'text', 'done']);
} finally { off(); unsubscribe(); dispose(); await session.close(); }
});
diff --git a/apps/desktop/src/main/maker-ipc/channelTurnSignal.ts b/apps/desktop/src/main/maker-ipc/channelTurnSignal.ts
index 969ff47ca6..47938e07f7 100644
--- a/apps/desktop/src/main/maker-ipc/channelTurnSignal.ts
+++ b/apps/desktop/src/main/maker-ipc/channelTurnSignal.ts
@@ -6,11 +6,12 @@ export type ChannelTurnPhase = 'starting' | 'undispatched';
/**
* 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,
+ * (Claude Code background task notifications; see Session `onProviderInitiatedTurn`).
+ * `provider-wake-local` inherits an app-only send, or has no known dispatch. 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' | 'provider-wake';
+export type ChannelTurnSource = 'other-task' | 'provider-wake' | 'provider-wake-local';
/**
* The one relay predicate shared by official hook background results and personal IM output:
@@ -28,6 +29,37 @@ 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 }>();
+/**
+ * Keep the reply destination with the live Session, not its historical IM binding. A provider
+ * wake reuses the last dispatched generation. No persisted route or new channel authorization
+ * is created; the channel still checks its existing binding/account before delivery.
+ */
+export function createChannelTurnObserver(session: Session) {
+ let source: ChannelTurnSource | undefined;
+ let relayWake = false;
+ let rollbackRelayWake: boolean | undefined;
+ return {
+ beforeProviderStart() {
+ source = pendingSources.get(session.id)?.source;
+ rollbackRelayWake = undefined;
+ return publishChannelTurn(session, 'starting');
+ },
+ onDispatching() {
+ const origin = session.getCurrentTurnOrigin();
+ rollbackRelayWake = relayWake;
+ relayWake = isRelayedChannelTurnSource(source) || origin?.surface === 'im' || origin?.kind === 'scheduler';
+ },
+ onUndispatched() {
+ if (rollbackRelayWake !== undefined) relayWake = rollbackRelayWake;
+ rollbackRelayWake = undefined;
+ return publishChannelTurn(session, 'undispatched');
+ },
+ onProviderInitiatedTurn() {
+ void publishProviderInitiatedTurn(session, relayWake);
+ },
+ };
+}
+
/** Runs before provider output, including scheduler and cross-session direct sends. */
export function onChannelTurn(listener: ChannelTurnListener): () => void {
listeners.add(listener);
@@ -45,8 +77,8 @@ export async function publishChannelTurn(session: Session, phase: ChannelTurnPha
* 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');
+export function publishProviderInitiatedTurn(session: Session, relay = false): Promise<void> {
+ return notifyListeners(session, 'starting', relay ? 'provider-wake' : 'provider-wake-local');
}
async function notifyListeners(
diff --git a/apps/desktop/src/main/maker-ipc/sessionTurnObserver.ts b/apps/desktop/src/main/maker-ipc/sessionTurnObserver.ts
index 3b5801eaa6..72d1d4f9fb 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, publishProviderInitiatedTurn } from './channelTurnSignal';
+import { createChannelTurnObserver } from './channelTurnSignal';
import { MANAGED_LLAMACPP_PROVIDER_ID } from '../../shared/llamaCpp.js';
import { ensureManagedOllamaReadyForSession } from '../local-model-runtime/preflight.js';
import { createLogger } from '../logger.js';
@@ -27,12 +27,16 @@ export interface InstallSessionTurnObserverDeps {
export function installSessionTurnObserver(deps: InstallSessionTurnObserverDeps, session: Session) {
let assertPermissionDispatch: (() => void) | undefined;
+ const channelTurn = createChannelTurnObserver(session);
session.setTurnLifecycleObserver({
- onDispatching: () => assertPermissionDispatch?.(),
+ onDispatching: () => {
+ assertPermissionDispatch?.();
+ channelTurn.onDispatching();
+ },
beforeProviderStart: async (turnGeneration) => {
assertPermissionDispatch = undefined;
if (session.remoteHostId) {
- await publishChannelTurn(session, 'starting');
+ await channelTurn.beforeProviderStart();
return;
}
assertPermissionDispatch = await prepareBotPermissionDispatch(session);
@@ -97,10 +101,10 @@ export function installSessionTurnObserver(deps: InstallSessionTurnObserverDeps,
session.id,
deps.providerTurnLeaseId(session.instanceId, turnGeneration),
);
- await publishChannelTurn(session, 'starting');
+ await channelTurn.beforeProviderStart();
},
onUndispatched: async (turnGeneration) => {
- await publishChannelTurn(session, 'undispatched');
+ await channelTurn.onUndispatched();
if (session.remoteHostId) return;
await deps.sessionTurnLeaseTracker.markTurnEnded(
session.id,
@@ -110,7 +114,7 @@ export function installSessionTurnObserver(deps: InstallSessionTurnObserverDeps,
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);
+ channelTurn.onProviderInitiatedTurn();
},
onTerminal: ({ turnGeneration, event, isCurrentGeneration }) => {
if (session.remoteHostId) return;
diff --git a/docs/dev-rules/im-turn-flow.md b/docs/dev-rules/im-turn-flow.md
index 381d012006..41d9e8c62b 100644
--- a/docs/dev-rules/im-turn-flow.md
+++ b/docs/dev-rules/im-turn-flow.md
@@ -56,7 +56,7 @@ Telegram、Discord、钉钉和官方 hook 共用调度器,Telegram 长轮询
| 用户消息落库 | 部分渠道提前落库(`persistInboundUserMessageEarly`),`onAccepted` 补 `imSource` | 只在 `onAccepted` 落库,`agentMeta.hookSource` | 共用流程(`onAccepted` 落库;提前落库保留为渠道能力) |
| 发送 | 发送前应用任务待切换选择,再 `makerSession.send`,`MAIN_OWNED_SEND_CONTEXT.origin.kind='im'` | 复用任务先经 `acquirePendingAgentSwitchForImSend` 跟随默认并应用任务选择,再读 meta、建会话、挂观察器和 `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 轮次的不另发 |
+| 后台轮次回传(非 IM 入站) | `orchestrator` 的 `onChannelTurn` → `turnRunner` 转播(Agent 自己唤醒的轮次只同步标记已接线的会话) | `backgroundResults` → `turn.end(background: true)` | 已同源判据:`maker-ipc/channelTurnSignal.ts` 的开始信号与 `isRelayedChannelTurnSource`(其它任务来信;后台唤醒继承当前 Session 最近实际派发的来源,Cindy 输入及内部协调不回传;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/product-rules/telegram-bot-parity.md b/docs/product-rules/telegram-bot-parity.md
index 695f9676c9..63a970f0fd 100644
--- a/docs/product-rules/telegram-bot-parity.md
+++ b/docs/product-rules/telegram-bot-parity.md
@@ -350,7 +350,8 @@ Telegram 个人 bot、官方旧服务端兼容回应与 hello 声明复用同一
适用范围:个人飞书/Lark、Telegram、Discord、微信、企业微信、钉钉,以及官方 Telegram、Slack;X 不参与。
只回传自动执行的轮次:自动任务(scheduler `turnOrigin`),其它任务经 `send_to_session` 等
-发来的可见消息触发的回复,以及 Agent 自己唤醒的轮次。桌面里直接输入的消息、伙伴委派的内部协调输入都不回传。其它任务来信由
+发来的可见消息触发的回复,以及继承了上述来源或 IM 来源的 Agent 自己唤醒轮次。
+桌面、手机里直接输入的消息、伙伴委派的内部协调输入及其后台唤醒都不回传。其它任务来信由
主进程在派发它的那次 `Session.send` 期间盖章(`maker-ipc/channelTurnSignal.ts`),随该轮的开始信号
交给两条路径,只作用于这一轮;不改 maker-core 的 `SendOrigin`,以免插件钩子等把它当作非用户轮次。
两条路径共用 `isRelayedChannelTurnSource` 一个判据。
@@ -360,12 +361,19 @@ Agent 自己唤醒的轮次(2026-10-13 补齐):Claude Code 的后台子代
被当作桌面输入留在桌面,只有原 IM 轮次还挂着的那一段(wake 任务的 continuation claim 让 IM 轮次等到第一次
唤醒结束)随原轮次发出。现在 maker-core `Session` 在本代产品轮次已收口、没有预留中的发送时看到主代理的新
输出(文本、思考、工具),就在该事件分发给监听者之前同步调用 `onProviderInitiatedTurn`;桌面以
-`provider-wake` 来源发出开始信号,回传与其它任务来信同一条发送、收口与清理路径。判据与引擎无关,
+后台唤醒来源发出开始信号,回传与其它任务来信同一条发送、收口与清理路径。2026-10-27 修正:
+`createChannelTurnObserver` 在实际派发边界记录当前 Session 的回复去向,派发未成功时还原;
+后台唤醒继承该去向,渠道来源标为 `provider-wake`,Cindy 输入或未知来源标为
+`provider-wake-local`,不因任务曾绑定渠道而回传。手机、同账号远程输入沿普通发送入口复用此规则。
+仅在当前运行实例内保留,不从历史渠道绑定补造;不改变来源展示、模型输入或工具权限。
+回归见 `hook-control/__tests__/dispatcher.test.ts` 的真实 Session → 官方回传测试及
+`im/shared/__tests__/orchestratorOutput.test.ts`、`turnRunnerThreadRouting.test.ts`。判据与引擎无关,
Codex / Pi 目前没有此类自动唤醒。子代理事件(`agentMeta.parentUuid`)、后台事件、claim 挡住的续跑段都不算;
产品轮次里接受过插话(steer)时,收口后第一个无发送的轮次一律归插话、不回传:插话赶不上原轮次时
Claude 会把它当作新一轮执行,而 Cindy 分不出插话是否已被原轮次吸收,宁可漏传这一轮,也不把桌面输入的回复发到渠道。
仍属原 IM 轮次(官方 hook 仍在观察、个人渠道队列里仍有 IM 轮次)时由该轮次一并发出,不另发后台结果。
-已知边界:唤醒轮次自身没有来源,跟在桌面输入或静默运行的自动任务之后被唤醒时同样回传;个人渠道只对已接好
+已知边界:唤醒轮次自身没有原始后台任务的输入标识,按当前 Session 最近实际派发的一轮继承;
+静默自动任务之后的后台唤醒仍沿原有回传规则,不延续已结束 run 的静默策略。个人渠道只对已接好
输出的渠道自有任务生效(重启后先在桌面发起、尚未经 IM 接线的任务,唤醒轮次留在桌面,不从中途开始转播),
`/ctr` 接管任务仍只转播 scheduler 输出;唤醒后还没产生任何输出就直接失败的轮次(只有一个终止错误)与上一轮迟到的
错误分不开,不识别为唤醒、不回传,失败留在桌面(与此前行为相同)。