Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(im): 将任务后台执行结果回传到绑定渠道
Dashedf512c1fe4f
diff --git a/apps/desktop/src/main/hook-control/__tests__/backgroundResults.test.ts b/apps/desktop/src/main/hook-control/__tests__/backgroundResults.test.tsnew file mode 100644index 0000000000..6d8914a801--- /dev/null+++ b/apps/desktop/src/main/hook-control/__tests__/backgroundResults.test.ts@@ -0,0 +1,98 @@+import { describe, expect, it, vi } from 'vitest';+import { createBackgroundResults } from '../backgroundResults';+import type { HookContinuationWatchRequest, HookSessionRunner } from '../dispatcher';++function fixture(key = 'telegram:dm:bot:user:g0') {+ let watch!: HookContinuationWatchRequest;+ let generation = 0;+ const send = vi.fn(() => true);+ const sender = vi.fn(() => send);+ const get = vi.fn(() => 'session');+ const allowed = vi.fn(() => true);+ const owned = vi.fn(() => false);+ const cancel = vi.fn(() => watch.onEnd({ status: 'error', finalText: '', errorMessage: 'cancelled', durationMs: 0 }));+ const watchContinuation = vi.fn((req: HookContinuationWatchRequest) => { watch = req; req.onClaim(); return cancel; });+ const output = createBackgroundResults({+ bindings: { get, set() {}, remove() {}, findBySession: () => [{ connectionId: 'conn', externalKey: key }] },+ runner: { watchContinuation } as unknown as HookSessionRunner,+ sender, allowed, owned, generation: () => generation, log: { warn: vi.fn() },+ });+ return { output, send, sender, get, allowed, owned, watchContinuation, cancel,+ watch: () => watch, rotate: () => { generation++; } };+}+const result = { status: 'ok' as const, finalText: '自动执行结果', errorMessage: null, durationMs: 10 };++describe('IM session background results', () => {+ it.each(['telegram:dm:bot:user:g0', 'slack:T:C:1.2'])('forwards %s once, including attachments', (key) => {+ const f = fixture(key);+ f.output.start('session', '/work');+ f.output.start('session', '/work');+ expect(f.watchContinuation).toHaveBeenCalledTimes(1);+ const outcome = { ...result, attachments: [{ mimeType: 'text/plain', dataBase64: 'YQ==', name: 'a.txt' }] };+ f.watch().onEnd(outcome);+ f.watch().onEnd(outcome);+ expect(f.send).toHaveBeenCalledTimes(1);+ expect(f.send).toHaveBeenCalledWith(expect.objectContaining({ type: 'turn.end', payload: expect.objectContaining({+ status: 'ok', finalText: result.finalText, usage: { durationMs: 10 },+ background: true, externalKey: key, attachments: outcome.attachments,+ }) }));+ });++ it('excludes X, old servers, and turns already owned by normal IM/reopen delivery', () => {+ const x = fixture('x:post:1');+ x.output.start('session', '/work');+ expect(x.watchContinuation).not.toHaveBeenCalled();+ const f = fixture();+ f.owned.mockReturnValue(true);+ f.output.start('session', '/work');+ expect(f.watchContinuation).not.toHaveBeenCalled();+ f.owned.mockReturnValue(false);+ f.sender.mockReturnValue(undefined as never);+ f.output.start('session', '/work');+ 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.watch().onSettling?.();+ if (kind === 'binding') f.get.mockReturnValue('replacement');+ if (kind === 'directory') f.allowed.mockReturnValue(false);+ if (kind === 'connection') f.sender.mockReturnValue(vi.fn());+ if (kind === 'account') f.rotate();+ f.watch().onEnd(result);+ expect(f.send).not.toHaveBeenCalled();+ });++ it('teardown suppresses the observer cancellation result', () => {+ const f = fixture();+ f.output.start('session', '/work');+ f.output.clear();+ expect(f.cancel).toHaveBeenCalledOnce();+ expect(f.send).not.toHaveBeenCalled();+ });++ it('a cancelled preflight cannot claim the next turn', () => {+ const f = fixture();+ f.output.start('session', '/work');+ const abandoned = f.watch();+ f.output.cancel('session');+ f.output.start('session', '/work');+ abandoned.onEnd(result);+ expect(f.send).not.toHaveBeenCalled();+ f.watch().onEnd(result);+ expect(f.send).toHaveBeenCalledOnce();+ });++ it('ignores empty output and admits the following turn during attachment collection', () => {+ const f = fixture();+ f.output.start('session', '/work');+ const first = f.watch();+ first.onSettling?.();+ f.output.start('session', '/work');+ expect(f.watchContinuation).toHaveBeenCalledTimes(2);+ first.onEnd({ ...result, finalText: '' });+ f.watch().onEnd(result);+ expect(f.send).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/main/hook-control/__tests__/bindings.test.ts b/apps/desktop/src/main/hook-control/__tests__/bindings.test.tsindex dfd7398e22..b765637eac 100644--- a/apps/desktop/src/main/hook-control/__tests__/bindings.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/bindings.test.ts@@ -46,6 +46,7 @@ describe('hook binding store', () => {makeStore().set('conn-1', 'k', 'sess-1');expect(makeStore().get('conn-1', 'k')).toBe('sess-1');+ expect(makeStore().findBySession?.('sess-1')).toEqual([{ connectionId: 'conn-1', externalKey: 'k' }]);});it('行里只写 sessionId + updatedAt, 不写任何授权状态', () => {diff --git a/apps/desktop/src/main/hook-control/__tests__/transport-manager.test.ts b/apps/desktop/src/main/hook-control/__tests__/transport-manager.test.tsindex 601da27eb9..34a1766528 100644--- a/apps/desktop/src/main/hook-control/__tests__/transport-manager.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/transport-manager.test.ts@@ -24,6 +24,7 @@ import {HOOK_FEATURE_PROVIDER_X,HOOK_FEATURE_SESSION_PICKER,HOOK_FEATURE_SESSION_NEW,+ HOOK_FEATURE_SESSION_RESULT,HOOK_FEATURE_SLACK_TOOLS,HOOK_FEATURE_TURN_DELIVERY,makeBindState,@@ -1969,6 +1970,7 @@ describe('Telegram provider capability, binding and prefs', () => {const telegramHello = await telegram.server.waitFor('hello');if (telegramHello.type !== 'hello') throw new Error('unreachable');expect(telegramHello.payload.features).toContain(HOOK_FEATURE_PROVIDER_BIND);+ expect(telegramHello.payload.features).toContain(HOOK_FEATURE_SESSION_RESULT);expect(telegramHello.payload.features).not.toContain(HOOK_FEATURE_MULTI_TEAM);telegram.sock.send(serializeHookMessage(@@ -1987,6 +1989,7 @@ describe('Telegram provider capability, binding and prefs', () => {const slackHello = await slack.server.waitFor('hello');if (slackHello.type !== 'hello') throw new Error('unreachable');expect(slackHello.payload.features).toContain(HOOK_FEATURE_MULTI_TEAM);+ expect(slackHello.payload.features).toContain(HOOK_FEATURE_SESSION_RESULT);expect(slackHello.payload.features).not.toContain(HOOK_FEATURE_PROVIDER_BIND);slack.sock.send(serializeHookMessage(makeWelcome({ serverName: 'slack-server', features: [] })),diff --git a/apps/desktop/src/main/hook-control/backgroundResults.ts b/apps/desktop/src/main/hook-control/backgroundResults.tsnew file mode 100644index 0000000000..5927ff1f4f--- /dev/null+++ b/apps/desktop/src/main/hook-control/backgroundResults.ts@@ -0,0 +1,65 @@+import { randomUUID } from 'node:crypto';+import { makeTurnEnd, type HookMessage } from '@cindy/slack-hook-protocol';+import type { HookSessionRunner } from './dispatcher';+import type { HookBindingStore } from './bindings';++/** Shares the normal observer/final attachment collector; no task replay or outbox. */+export function createBackgroundResults(deps: {+ bindings: HookBindingStore;+ runner: HookSessionRunner;+ owned(sessionId: string): boolean;+ allowed(connectionId: string, workingDir: string): boolean;+ sender(connectionId: string): ((message: HookMessage) => boolean) | undefined;+ generation(): number;+ log: { warn(message: string): void };+}) {+ const watches = new Map<string, { cancel(): void; active: boolean }>();+ return {+ start(sessionId: string, workingDir: string) {+ if (deps.owned(sessionId) || watches.has(sessionId) || !deps.runner.watchContinuation) return;+ const targets = (deps.bindings.findBySession?.(sessionId) ?? []).filter(({ connectionId, externalKey }) =>+ /^(telegram|slack):/.test(externalKey) && deps.allowed(connectionId, workingDir));+ if (!targets.length) return;+ const senders = targets.map((target) => ({ ...target, send: deps.sender(target.connectionId) })).filter((t) => t.send);+ if (!senders.length) return;+ const generation = deps.generation();+ const state = { cancel: () => {}, active: true };+ watches.set(sessionId, state);+ const detach = () => { if (watches.get(sessionId) === state) watches.delete(sessionId); };+ state.cancel = deps.runner.watchContinuation({+ sessionId, workingDir,+ isDirAuthorized: (dir) => senders.some((t) => deps.allowed(t.connectionId, dir)),+ onClaim() {}, onProgress() {}, onSettling: detach,+ onAbandon: () => { state.active = false; detach(); },+ onEnd(outcome) {+ detach();+ if (!state.active || generation !== deps.generation() ||+ (!outcome.finalText.trim() && !outcome.errorMessage && !outcome.attachments?.length)) return;+ state.active = false;+ for (const target of senders) {+ if (deps.sender(target.connectionId) !== target.send ||+ !deps.allowed(target.connectionId, workingDir) ||+ deps.bindings.get(target.connectionId, target.externalKey) !== sessionId) continue;+ try { target.send?.(makeTurnEnd({+ background: true, requestId: randomUUID(), externalKey: target.externalKey, sessionId,+ status: outcome.status, finalText: outcome.finalText, errorMessage: outcome.errorMessage,+ usage: { durationMs: outcome.durationMs },+ ...(outcome.attachments ? { attachments: outcome.attachments } : {}),+ })); } catch { deps.log.warn('background session result could not be sent'); }+ }+ },+ });+ },+ cancel(sessionId: string) {+ const state = watches.get(sessionId);+ if (!state) return;+ state.active = false;+ watches.delete(sessionId);+ state.cancel();+ },+ clear() {+ for (const state of watches.values()) { state.active = false; state.cancel(); }+ watches.clear();+ },+ };+}diff --git a/apps/desktop/src/main/hook-control/bindings.ts b/apps/desktop/src/main/hook-control/bindings.tsindex d086b84577..81e92b0537 100644--- a/apps/desktop/src/main/hook-control/bindings.ts+++ b/apps/desktop/src/main/hook-control/bindings.ts@@ -23,6 +23,7 @@ import fs from 'node:fs';import path from 'node:path';export interface HookBindingStore {+ findBySession?(sessionId: string): Array<{ connectionId: string; externalKey: string }>;get(connectionId: string, externalKey: string): string | null;/*** 整行覆盖写。只在绑定真正变化时调用(新建会话、legacy 命名空间迁移、接管)——@@ -89,6 +90,16 @@ export function createHookBindingStore(deps: {}return {+ findBySession(sessionId) {+ const found: Array<{ connectionId: string; externalKey: string }> = [];+ for (const [connectionId, rows] of Object.entries(readAll())) {+ if (!rows || typeof rows !== 'object' || Array.isArray(rows)) continue;+ for (const [externalKey, row] of Object.entries(rows)) {+ if (row?.sessionId === sessionId) found.push({ connectionId, externalKey });+ }+ }+ return found;+ },get(connectionId, externalKey) {const ns: unknown = readAll()[connectionId];if (!ns || typeof ns !== 'object' || Array.isArray(ns)) return null;diff --git a/apps/desktop/src/main/hook-control/dispatcher.ts b/apps/desktop/src/main/hook-control/dispatcher.tsindex 92f9f41eb9..b9ced0e8ba 100644--- a/apps/desktop/src/main/hook-control/dispatcher.ts+++ b/apps/desktop/src/main/hook-control/dispatcher.ts@@ -53,6 +53,7 @@ import {HOOK_FEATURE_TELEGRAM_PROGRESS_OPS,HOOK_FEATURE_TURN_DELIVERY,HOOK_FEATURE_TURN_REOPEN,+ HOOK_FEATURE_SESSION_RESULT,type HookMessage,type HookTurnEndMessage,type InteractionButton,@@ -96,6 +97,7 @@ import type { HookBindingStore } from './bindings.js';import { terminalDeliveryExpired } from './requestLedger.js';import { composeXPrompt } from './xPrompt.js';import type { HookRequestLedger, HookTerminalRecord } from './requestLedger.js';+import { createBackgroundResults } from './backgroundResults.js';/** 会话执行器抽象 —— 生产实现 session-runner.ts(包 maker), 测试注入假的。 */export interface HookSessionRunner {@@ -347,6 +349,7 @@ export interface HookDispatcherDeps {* 返回退订函数, dispose 时调用。*/subscribeUiContinuation?: (listener: (sessionId: string, clientId: string) => void) => () => void;+ subscribeChannelTurn?: (listener: (sessionId: string, workingDir: string, phase: 'starting' | 'undispatched') => void) => () => void;/*** 可选: 订阅「桌面端在某会话里做了与续跑无关的事」(生产为 maker-ipc 的* onUiSessionIntervention)。命中即作废该会话的待续跑记账 —— 记账只按 sessionId@@ -1419,6 +1422,20 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {return serverFeatures.get(connectionId)?.includes(HOOK_FEATURE_TURN_REOPEN) === true;}+ const backgroundResults = createBackgroundResults({+ bindings, runner,+ generation: () => accountGeneration,+ log,+ owned: (sessionId) => running.has(sessionId) || activeContinuations.has(sessionId) || pendingClaims.has(sessionId),+ allowed: (connectionId, dir) => accountActive && dirStillAllowed(connectionId, dir),+ 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);+ else backgroundResults.cancel(sessionId);+ });+/*** 放弃这个 session 的续跑回流: 撤销在观察的那一轮 + 清掉记账。*@@ -2789,6 +2806,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {accountActive = true;},async deactivateAccount() {+ backgroundResults.clear();// Invalidate a deferred activation on every close request, including a// duplicate request that arrives while the physical drain is running.const wasActive = accountActive;@@ -3133,6 +3151,8 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {serverFeatures.delete(connectionId);},dispose() {+ backgroundResults.clear();+ unsubscribeBackgroundResults?.();clearRecoveryDeliveries();closeTelegramTurnOps();unsubscribeUiContinuation?.();diff --git a/apps/desktop/src/main/hook-control/ipc.ts b/apps/desktop/src/main/hook-control/ipc.tsindex e66248fcd9..cec484aa1f 100644--- a/apps/desktop/src/main/hook-control/ipc.ts+++ b/apps/desktop/src/main/hook-control/ipc.ts@@ -24,6 +24,7 @@ import { createLogger } from '../logger.js';import { t } from '../i18n.js';import { buildOfficialBotCommandMenus } from '../im/shared/botCommands.js';import { stopSessionTurnExplicitly } from '../maker-ipc/register.js';+import { onChannelTurn } from '../maker-ipc/channelTurnSignal.js';import { getMaker, restartCodexAfterAuthModeChange } from '../maker-host/index.js';import { shutdownCodexEnvironment } from '../mcp-integrations/codexEnvironment.js';import { getDesktopProviderService } from '../maker-host/createDesktopProviderService.js';@@ -552,6 +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)),subscribeUiSessionIntervention: onUiSessionIntervention,subscribeUiTurnDispatching: onUiTurnDispatching,subscribeUiTurnUndispatched: onUiTurnUndispatched,diff --git a/apps/desktop/src/main/hook-control/manager.ts b/apps/desktop/src/main/hook-control/manager.tsindex 4bf493c798..3a5209a7db 100644--- a/apps/desktop/src/main/hook-control/manager.ts+++ b/apps/desktop/src/main/hook-control/manager.ts@@ -23,6 +23,7 @@ import {HOOK_FEATURE_GROUP_RELAY_RECIPIENT,HOOK_FEATURE_LIFECYCLE_ANNOUNCEMENT,HOOK_FEATURE_MULTI_TEAM,+ HOOK_FEATURE_SESSION_RESULT,HOOK_FEATURE_PROVIDER_BIND,HOOK_FEATURE_PROVIDER_BEHAVIOR,HOOK_FEATURE_PROVIDER_PREFS,@@ -692,6 +693,7 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookContrequiredFeatures: telegramProviderBaseFeatures,helloFeatures: [...telegramProviderBaseFeatures,+ HOOK_FEATURE_SESSION_RESULT,HOOK_FEATURE_GROUP_RELAY,HOOK_FEATURE_GROUP_RELAY_RECIPIENT,HOOK_FEATURE_PROVIDER_BEHAVIOR,@@ -1890,6 +1892,7 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookCont/** Slack legacy 线的 hello 能力声明(provider-neutral 线各自在 config.helloFeatures)。 */const SLACK_HELLO_FEATURES: readonly string[] = [+ HOOK_FEATURE_SESSION_RESULT,HOOK_FEATURE_MULTI_TEAM,HOOK_FEATURE_SESSION_PICKER,];diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.tsindex 944f09487f..96dff9f76b 100644--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts@@ -553,6 +553,110 @@ describe('turnRunner thread = session 路由(slack threadScoped)', () => {});});+describe('turnRunner 渠道任务后台结果回传', () => {+ 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');+ h.emit({ type: 'text', data: { text: '冷启动结果', isFinal: true } });+ h.emit({ type: 'done', data: {} });+ await vi.waitFor(() => expect(stub.finalize).toHaveBeenCalledWith('冷启动结果'));+ expect(mocks.slackIm.startStreamingText).toHaveBeenCalledTimes(1);+ expect(h.send).not.toHaveBeenCalled();+ expect(mocks.getMaker().createSession).not.toHaveBeenCalled();+ });++ async function channelAndIdle(): Promise<SessionHarness> {+ await runTurn('100.1');+ const h = harnesses.get(sessionIdFor('T1', 'U1', '100.1'))!;+ const initial = streamingHandleStub();+ mocks.slackIm.startStreamingText.mockResolvedValue(initial);+ h.emit({ type: 'text', data: { text: '首次回复' } });+ h.emit({ type: 'done' } as AgentEvent);+ await vi.waitFor(() => expect(initial.finalize).toHaveBeenCalledTimes(1));+ mocks.slackIm.startStreamingText.mockClear();+ mocks.slackIm.sendMarkdownText.mockClear();+ return h;+ }++ it.each([+ ['自动任务', { kind: 'scheduler', scheduleId: 's1', scheduleName: '检查进度' }],+ ['其它任务消息触发的轮次', undefined],+ ] as const)('%s 的结果回到原聊天,不要求先接管', async (_name, turnOrigin) => {+ const h = await channelAndIdle();+ const stub = streamingHandleStub();+ mocks.slackIm.startStreamingText.mockResolvedValue(stub);+ h.emit({ type: 'text', data: { text: '处理结果', isFinal: true }, turnOrigin });+ h.emit({ type: 'done', data: {}, turnOrigin });+ await vi.waitFor(() => expect(stub.finalize).toHaveBeenCalledTimes(1));+ expect(mocks.slackIm.startStreamingText).toHaveBeenCalledTimes(1);+ expect(mocks.slackIm.startStreamingText).toHaveBeenCalledWith('U1', undefined, { threadTs: '100.1' });+ expect(stub.finalize).toHaveBeenCalledWith(turnOrigin ? '🤖 自动任务「检查进度」\n\n处理结果' : '处理结果');+ });++ it('子代理及旧轮次的后台事件不回传,也不提前结束当前回复', async () => {+ const h = await channelAndIdle();+ const stub = streamingHandleStub();+ mocks.slackIm.startStreamingText.mockResolvedValue(stub);+ for (const scope of [{ agentMeta: { parentUuid: 'child' } }, { turnScope: 'background' as const }]) {+ h.emit({ type: 'text', data: { text: '内部内容' }, ...scope });+ h.emit({ type: 'done', data: {}, ...scope });+ }+ expect(mocks.slackIm.startStreamingText).not.toHaveBeenCalled();+ h.emit({ type: 'text', data: { text: '公开结果' } });+ h.emit({ type: 'done', data: {} });+ await vi.waitFor(() => expect(stub.finalize).toHaveBeenCalledWith('公开结果'));+ });++ it('纯文本渠道仅在收口时通过适配器回传结果', async () => {+ const commitFinal = vi.fn(async () => undefined);+ runner = createTurnRunner({+ ...fakeAdapter,+ channel: 'wechat',+ output: { kind: 'chunked-text', im: fakeAdapter.im, commitFinal },+ }, fakeRepo, fakeCards);+ await runTurn('100.1');+ const h = harnesses.get(sessionIdFor('T1', 'U1', '100.1'))!;+ h.emit({ type: 'done', data: {} });+ await vi.waitFor(() => expect(commitFinal).toHaveBeenCalledTimes(1));+ mocks.slackIm.sendMarkdownText.mockClear();+ h.emit({ type: 'text', data: { text: '后台结果', isFinal: true } });+ expect(mocks.slackIm.sendMarkdownText).not.toHaveBeenCalled();+ h.emit({ type: 'done', data: {} });+ await vi.waitFor(() => expect(mocks.slackIm.sendMarkdownText).toHaveBeenCalledWith('U1', '后台结果', { threadTs: '100.1' }));+ expect(commitFinal).toHaveBeenCalledTimes(1);+ expect(mocks.slackIm.startStreamingText).not.toHaveBeenCalled();+ });++ it('断开渠道后丢弃迟到的消息句柄,避免继续回传', async () => {+ const h = await channelAndIdle();+ const stub = streamingHandleStub();+ let resolveHandle!: (handle: ReturnType<typeof streamingHandleStub>) => void;+ mocks.slackIm.startStreamingText.mockReturnValue(new Promise((resolve) => { resolveHandle = resolve; }));+ h.emit({ type: 'text', data: { text: '结果' } });+ h.emit({ type: 'done', data: {} });+ await runner.disposeAllSessions();+ resolveHandle(stub);+ await vi.waitFor(() => expect(stub.close).toHaveBeenCalled());+ expect(stub.finalize).not.toHaveBeenCalled();+ expect(stub.replace).not.toHaveBeenCalled();+ });++ it('空输出不发送,发送失败不会留下未处理的 rejection', async () => {+ const h = await channelAndIdle();+ h.emit({ type: 'status', data: { isRunning: true } });+ h.emit({ type: 'session_id', data: { sessionId: 'sdk' } });+ h.emit({ type: 'done', data: {} });+ expect(mocks.slackIm.startStreamingText).not.toHaveBeenCalled();+ mocks.slackIm.startStreamingText.mockRejectedValue(new Error('offline'));+ h.emit({ type: 'text', data: { text: '结果' } });+ h.emit({ type: 'done', data: {} });+ await vi.waitFor(() => expect(mocks.logger.warn).toHaveBeenCalledWith(expect.stringContaining('transpond finalize failed')));+ });+});+describe('turnRunner 自动任务转播(scheduler turn → 远程控制 thread)', () => {/** 接管 desktop-sess-1 到 thread 300.3,并清掉用户首轮,使后续 scheduler 事件走 stray。 */async function attachAndIdle(): Promise<SessionHarness> {diff --git a/apps/desktop/src/main/im/shared/orchestrator.ts b/apps/desktop/src/main/im/shared/orchestrator.tsindex 6d99d54495..0c2ac50019 100644--- a/apps/desktop/src/main/im/shared/orchestrator.ts+++ b/apps/desktop/src/main/im/shared/orchestrator.ts@@ -11,6 +11,11 @@*/import { createLogger } from '../../logger';+import { eq } from 'drizzle-orm';+import { getDbClient } from '../../localDb/client/current';+import { sessions } from '../../localDb/schema';+import { onChannelTurn } from '../../maker-ipc/channelTurnSignal';+import { captureImAccountGeneration, isImAccountGenerationCurrent } from '../accountBoundary';import {acquirePendingAgentSwitchForDirectSend,acquirePendingAgentSwitchForImSend,@@ -42,6 +47,24 @@ export interface ImOrchestrator {/** 渠道名 → orchestrator 注册表 — composition root (im/index.ts) 查询用。 */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) => {+ if (phase !== 'starting') 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)+ .where(eq(sessions.id, session.id)).limit(1);+ if (!row || row.status === 'deleted' || row.status === 'archived' || !isImAccountGenerationCurrent(generation)) return;+ const orchestrator = registry.get(row.source as ImChannelName);+ if (!orchestrator) return;+ const status = orchestrator.adapter.im.getStatus();+ const botId = row.source === 'feishu' ? row.feishuBotAppId : row.imBotContextId;+ if (status.kind !== 'connected' || status.appId !== botId) return;+ const userId = row.source === 'feishu' ? row.feishuOpenId : row.imUserId;+ if (userId) orchestrator.turnRunner.attachSessionOutput(session, userId);+});+/*** 创建并接线一个渠道编排器:所有渠道订阅 im.onMessage;只有 rich-card* 渠道订阅 onCardAction。每个渠道只允许调一次(重复调说明 wiring 层 bug,diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.tsindex daa57469b2..a6f700f6ed 100644--- a/apps/desktop/src/main/im/shared/turnRunner.ts+++ b/apps/desktop/src/main/im/shared/turnRunner.ts@@ -362,10 +362,8 @@ interface SessionState {*/attached: boolean;/**- * 自动任务(scheduler)在本(被接管的)session 上发起的 turn 的转播态。- * 这类 turn 没有本渠道的 TurnState(走 stray 路径),为了让远程控制的用户在- * thread 里看到"系统自动发了什么 + 步骤 + 结果",单独开一张卡转播。null = 当前- * 没有进行中的自动任务转播。见 transpondScheduledEvent。+ * 非 IM 入站轮次的转播态:渠道自有任务的自动执行、跨任务消息回复,以及+ * 接管任务的 scheduler 输出。与正常入站 TurnState 分开,避免重复发送。*/scheduledTranspond: ScheduledTranspond | null;}@@ -375,8 +373,8 @@ interface SessionState {* 复用 turnActivity 的纯函数 + streamingHandle 原语,但用自己的卡片与渲染。*/interface ScheduledTranspond {- /** 任务展示名(来自事件 turnOrigin.scheduleName)。 */- scheduleName: string | null;+ /** 仅 scheduler 轮次显示自动任务标题,其它来源直接回复正文。 */+ header: string | null;activity: TurnActivityState;activityTicker: ReturnType<typeof setInterval> | null;/** 自动任务这一轮 agent 的回复文本累加。 */@@ -510,6 +508,7 @@ export type ImTurnDispatch =/** createTurnRunner 返回的编排实例 — per channel 一个。 */export interface ImTurnRunner {+ attachSessionOutput(session: MakerSession, userId: string): void;runAgentTurn(args: ImRunAgentTurnArgs): Promise<void>;/*** 把渠道用户消息**提前**写进本地 messages 表 —— 只给「dispatch 之前还有重活」@@ -2383,16 +2382,18 @@ export function createTurnRunner(function handleEventFor(localSessionId: string, userId: string) {return (event: AgentEvent) => {- if (isImSubagentEvent(event)) return;+ if (isImSubagentEvent(event) || event.turnScope === 'background') return;const state = sessionStates.get(localSessionId);if (!state) return;const turn = state.queue[0];if (!turn) {- // 自动任务(scheduler)在被接管的共享 session 上发起的 turn — 本渠道没有- // TurnState(stray)。转播到远程控制 thread, 让用户看到"系统自动发了什么 +- // 步骤 + 结果"。turnOrigin 由 maker Session 打标(PR1)。仅 attached(确有- // 远程控制 thread)才转播;desktop 自己发起的 turn 无 origin, 不转播。- if (state.attached && event.turnOrigin?.kind === 'scheduler') {+ // 渠道自有任务始终把回复送回自己的聊天;跨任务消息没有 scheduler+ // turnOrigin,也不能丢弃。通知回复只临时使用普通任务,不建立持续转播。+ // 接管普通任务仍仅转播 scheduler,保留其桌面输入的原有可见性。+ if (+ !state.preserveSessionConfig ||+ (state.attached && event.turnOrigin?.kind === 'scheduler')+ ) {transpondScheduledEvent(state, event);}// done / 终止型 error 同时是"session 空闲了"的信号 — 触发排队消息派发。@@ -2624,22 +2625,23 @@ export function createTurnRunner(}// ── 自动任务转播 ─────────────────────────────────────────────────────────────- // 把 scheduler 在被接管 session 上发起的 turn 转播到远程控制 thread。与上面的+ // 把非 IM 入站轮次转播到所属聊天。与上面的// 用户 turn 渲染完全隔离(独立卡 / 独立 buffer / 独立 ticker),不碰// composeStreamingView,避免回归 #118。/** 转播卡正文:运行中 = 头 + 步骤时间线 + 正文;收口 = 头 + 正文(去步骤)。 */function composeTranspondView(t: ScheduledTranspond, final: boolean): string {- const header = ui.agent.scheduledTaskHeader(t.scheduleName);+ const header = t.header;if (final) {- return t.buffer ? `${header}\n\n${t.buffer}` : header;+ return [header, t.buffer].filter(Boolean).join('\n\n');}const act = renderActivity(t.activity, Date.now());- const parts = [header];+ const parts: string[] = header ? [header] : [];if (act) parts.push(act);if (t.buffer) parts.push(t.buffer);- // 头与(步骤/正文)之间空行分隔;步骤紧跟头。- return parts.length === 1 ? header : `${parts[0]}\n${parts.slice(1).join('\n\n')}`;+ // 自动任务沿用标题紧接步骤的排版,其它轮次只显示步骤和正文。+ if (header && parts.length > 1) return `${header}\n${parts.slice(1).join('\n\n')}`;+ return parts.join('\n\n');}function ensureTranspondHandle(@@ -2654,6 +2656,7 @@ export function createTurnRunner(threadTs: state.scopeKey,});t.streamingHandle = handle;+ if (sessionStates.get(state.makerSession.id) !== state) handle.close();return handle;})();return t.streamingHandlePromise;@@ -2668,26 +2671,29 @@ export function createTurnRunner(function refreshTranspondCard(state: SessionState): void {const t = state.scheduledTranspond;- if (!t) return;- void ensureTranspondHandle(state, t).then((h) => h.replace(composeTranspondView(t, false)));+ if (!t || !richIm) return;+ void ensureTranspondHandle(state, t)+ .then((h) => {+ if (state.scheduledTranspond === t) h.replace(composeTranspondView(t, false));+ })+ .catch((err) => log.warn('transpond refresh failed (non-fatal)', err));}- /** 处理一条 scheduler-origin stray 事件,转播到远程控制 thread。 */+ /** 处理一条非 IM 入站事件,按原聊天 / 话题回传。 */function transpondScheduledEvent(state: SessionState, event: AgentEvent): void {- // Durable text channels need an inbound context token to address replies.- // A desktop-originated scheduler turn has no such token, so it cannot be- // safely mirrored and must never fall through to rich-card primitives.- if (output.kind === 'chunked-text') return;// Lifecycle status is not user-facing scheduler content. In particular,// the claim-bearing status(false) paired with an SDK boundary must not// create or close a projection card.if (event.type === 'status') return;if (event.type === 'done' && isTurnContinuationBoundaryEvent(event)) return;+ if (!['text', 'tool_use', 'done', 'error'].includes(event.type)) return;// 首条事件惰性建转播态(避免给空 turn 开卡)。if (!state.scheduledTranspond) {const origin = event.turnOrigin;state.scheduledTranspond = {- scheduleName: origin?.kind === 'scheduler' ? (origin.scheduleName ?? null) : null,+ header: origin?.kind === 'scheduler'+ ? ui.agent.scheduledTaskHeader(origin.scheduleName ?? null)+ : null,activity: createTurnActivity(Date.now()),activityTicker: null,buffer: '',@@ -2720,7 +2726,7 @@ export function createTurnRunner(typeof data.toolUseId === 'string' ? data.toolUseId : undefined,);// 低频 ticker 刷新耗时(只刷已存在的卡)。- if (!t.activityTicker) {+ if (richIm && !t.activityTicker) {t.activityTicker = setInterval(() => {t.streamingHandle?.replace(composeTranspondView(t, false));}, ACTIVITY_TICK_MS);@@ -2771,9 +2777,16 @@ export function createTurnRunner(return;}try {- const handle = await ensureTranspondHandle(state, t);const base = composeTranspondView(t, true);- const body = errMsg ? `${base}\n\n${ui.agent.runtimeError(errMsg)}` : base;+ const body = errMsg ? [base, ui.agent.runtimeError(errMsg)].filter(Boolean).join('\n\n') : base;+ if (output.kind === 'chunked-text') {+ // 微信等文本渠道由适配器解析当前账号下该聊天最近的有效回复上下文。+ // 不伪造入站 taskId,也不占用另一次用户消息的 durable final。+ if (body) await im.sendMarkdownText(state.userId, body, { threadTs: state.scopeKey });+ return;+ }+ const handle = await ensureTranspondHandle(state, t);+ if (sessionStates.get(state.makerSession.id) !== state) return;await handle.finalize(body);} catch (err) {log.warn(@@ -3980,6 +3993,11 @@ export function createTurnRunner(function cleanupSessionState(state: SessionState): void {clearPendingSends(state);clearQueuedTurnTimers(state);+ if (state.scheduledTranspond) {+ clearTranspondTicker(state.scheduledTranspond);+ state.scheduledTranspond.streamingHandle?.close();+ state.scheduledTranspond = null;+ }for (const u of state.unsubscribers) {try {u();@@ -3996,6 +4014,28 @@ export function createTurnRunner(}return {+ attachSessionOutput: (session, userId) => {+ const existing = sessionStates.get(session.id);+ if (existing?.makerSession === session) return;+ if (existing) cleanupSessionState(existing);+ ensureMakerCloseSubscription(getMaker());+ const state: SessionState = {+ makerSession: session,+ preserveSessionConfig: false,+ userId,+ workingDir: session.workDir,+ queue: [],+ sendQueue: [],+ dispatchRetryTimer: null,+ unsubscribers: [],+ detachDrainPromise: null,+ resolveDetachDrain: null,+ attached: false,+ scheduledTranspond: null,+ };+ sessionStates.set(session.id, state);+ state.unsubscribers.push(session.onEvent(handleEventFor(session.id, userId)));+ },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 63c75ee1bd..cb0e9e2a93 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts@@ -5,6 +5,7 @@ import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';import { handleSessionEvent, type SessionEventDependencies } from '../sessionEventPipeline.js';import { setMainLocale } from '../../i18n.js';import { installSessionTurnObserver } from '../sessionTurnObserver.js';+import { onChannelTurn } from '../channelTurnSignal.js';import { createSessionBindingLifecycle } from '../sessionBindingLifecycle.js';import { SessionTurnActivityTracker } from '../sessionTurnActivityTracker.js';import { ProductTurnWallClockTracker, ProductTurnUsageTargetTracker } from '../turnWallClock.js';@@ -960,6 +961,38 @@ describe('provider turn observer on real Session.send', () => {},};}+ it('awaits channel output attachment for direct sends and releases an undispatched turn', async () => {+ const h = harness();+ const phases: string[] = [];+ const dispose = installSessionTurnObserver(observerDeps(), h.session);+ const unsubscribe = onChannelTurn(async (session, phase) => {+ expect(session).toBe(h.session);+ await Promise.resolve();+ phases.push(phase);+ });+ try {+ await expect(h.session.send('peer message', { beforeProviderStart: async () => {+ expect(phases).toEqual(['starting']);+ throw new Error('cancel before dispatch');+ } })).rejects.toThrow('cancel before dispatch');+ expect(phases).toEqual(['starting', 'undispatched']);+ expect(h.handle.send).not.toHaveBeenCalled();+ await h.session.send('automatic task');+ expect(phases).toEqual(['starting', 'undispatched', 'starting']);+ expect(h.handle.send).toHaveBeenCalledOnce();+ } finally { unsubscribe(); dispose(); await h.dispose(); }+ });++ it('channel attachment failure does not block task execution', async () => {+ const h = harness();+ const dispose = installSessionTurnObserver(observerDeps(), h.session);+ const unsubscribe = onChannelTurn(() => { throw new Error('channel unavailable'); });+ try {+ await h.session.send('automatic task');+ expect(h.handle.send).toHaveBeenCalledOnce();+ } finally { unsubscribe(); dispose(); await h.dispose(); }+ });+it('awaits llama.cpp readiness on an existing task before dispatch and propagates startup failure', async () => {const h = harness();const gate = deferred();diff --git a/apps/desktop/src/main/maker-ipc/channelTurnSignal.ts b/apps/desktop/src/main/maker-ipc/channelTurnSignal.tsnew file mode 100644index 0000000000..9d934b7e3a--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/channelTurnSignal.ts@@ -0,0 +1,19 @@+import type { Session } from '@cindy/maker-core';+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>>();++/** Runs before provider output, including scheduler and cross-session direct sends. */+export function onChannelTurn(listener: (session: Session, phase: ChannelTurnPhase) => void | Promise<void>): () => void {+ listeners.add(listener);+ return () => { listeners.delete(listener); };+}++export async function publishChannelTurn(session: Session, phase: ChannelTurnPhase): Promise<void> {+ await Promise.all([...listeners].map(async (listener) => {+ try { await listener(session, phase); }+ 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 f22454f8cf..ff83631877 100644--- a/apps/desktop/src/main/maker-ipc/sessionTurnObserver.ts+++ b/apps/desktop/src/main/maker-ipc/sessionTurnObserver.ts@@ -1,4 +1,5 @@import type { Session } from '@cindy/maker-core';+import { publishChannelTurn } from './channelTurnSignal';import { MANAGED_LLAMACPP_PROVIDER_ID } from '../../shared/llamaCpp.js';import { ensureManagedOllamaReadyForSession } from '../local-model-runtime/preflight.js';import { createLogger } from '../logger.js';@@ -25,7 +26,10 @@ export interface InstallSessionTurnObserverDeps {export function installSessionTurnObserver(deps: InstallSessionTurnObserverDeps, session: Session) {session.setTurnLifecycleObserver({beforeProviderStart: async (turnGeneration) => {- if (session.remoteHostId) return;+ if (session.remoteHostId) {+ await publishChannelTurn(session, 'starting');+ return;+ }await deps.beforeLocalProviderStart?.(session);// 每条本地 Session.send 都经过这一个 Main-owned 边界,包括 renderer、IM、// Goal、Learn、Hook 与 Scheduler。付费权限不能只挂在普通 IPC 发送事务上。@@ -66,8 +70,10 @@ export function installSessionTurnObserver(deps: InstallSessionTurnObserverDeps,session.id,deps.providerTurnLeaseId(session.instanceId, turnGeneration),);+ await publishChannelTurn(session, 'starting');},onUndispatched: async (turnGeneration) => {+ await publishChannelTurn(session, 'undispatched');if (session.remoteHostId) return;await deps.sessionTurnLeaseTracker.markTurnEnded(session.id,diff --git a/docs/product-rules/telegram-bot-parity.md b/docs/product-rules/telegram-bot-parity.mdindex 21d2c9969d..da513958ce 100644--- a/docs/product-rules/telegram-bot-parity.md+++ b/docs/product-rules/telegram-bot-parity.md@@ -242,6 +242,26 @@ hook 侧既有的逐轮 `[渠道说明]`,两者措辞不同但都向模型说个人渠道切换表情时,删除失败向共享 turn runner 返回错误,保留旧 token 给终态再清理,避免飞书/Discord 同时遗留旧排队表情和新处理中表情;最终清理仍是尽力而为。+### IM bot 任务的后台结果回传++适用范围:个人飞书/Lark、Telegram、Discord、微信、企业微信、钉钉,以及官方 Telegram、Slack;X 不参与。++个人渠道通过 `im/shared/turnRunner.ts` 回传非 IM 入站轮次的输出,+包括自动任务、其它任务发送消息触发的回复;无需先 `/ctr` 接管。自动任务保留任务名,+其它来源直接显示回复正文,目的地沿用该任务原聊天和话题。正常 IM 入站轮次仍只发送一次;+子代理和旧轮次的后台事件不转播。纯文本渠道通过适配器使用现有有效聊天上下文发送最终结果。++临时回复通知不建立普通任务的持续转播;`/ctr` 接管任务仍只转播 scheduler 输出。+每轮执行前从当前账号库恢复输出监听,核对 bot 身份和任务状态,因此重启后无需先从 IM 发一条消息。++官方 Telegram、Slack 复用已有 hook binding、轮次观察和附件收集;双方宣告 `session-result-v1`+后用 `turn.end(background: true)` 发送结果,服务端在原私聊或话题新发消息。普通 IM 轮次和+已有 retry/reopen 轮次不另发一份。发送前复核账号代次、连接、目录授权与会话绑定;服务端+再核对设备绑定、聊天归属及 `/new` 代次。Telegram 保存新消息 route,回复结果仍回到原 lane。++两条路径均为在线尽力投递,不增加离线补发或持久化出箱。官方能力需客户端与服务端同时支持,+旧版本通过能力协商保持原行为;本地测试通过不代表服务端已经部署或真实渠道已联调。+## 五、怎么用这张表1. **动任一 bot 的用户可见行为前**,先看这里有没有对应行。diff --git a/packages/slack-hook-protocol/src/__tests__/protocol-session-result.test.ts b/packages/slack-hook-protocol/src/__tests__/protocol-session-result.test.tsnew file mode 100644index 0000000000..41787f48aa--- /dev/null+++ b/packages/slack-hook-protocol/src/__tests__/protocol-session-result.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from 'vitest';+import { makeTurnEnd, parseHookMessage, serializeHookMessage } from '../index';++describe('background turn.end compatibility', () => {+ const payload = { requestId: 'result', externalKey: 'slack:dm:T:U:g0', sessionId: 'session',+ status: 'ok' as const, finalText: 'result', errorMessage: null, usage: { durationMs: 1 } };+ it('keeps ordinary frames unchanged and round-trips background results', () => {+ for (const value of [payload, { ...payload, background: true as const }]) {+ const frame = makeTurnEnd(value);+ expect(parseHookMessage(serializeHookMessage(frame))).toEqual({ ok: true, message: frame });+ }+ });+ it.each([false, 'true', 1])('rejects invalid background flag %s', (background) => {+ const frame = makeTurnEnd(payload);+ expect(parseHookMessage({ ...frame, payload: { ...payload, background } }).ok).toBe(false);+ });+ it('rejects a background result claiming an inbound client-final delivery', () => {+ const frame = makeTurnEnd(payload);+ expect(parseHookMessage({ ...frame, payload: { ...payload, background: true, clientFinal: { delivered: true } } }).ok).toBe(false);+ });+});diff --git a/packages/slack-hook-protocol/src/parse.ts b/packages/slack-hook-protocol/src/parse.tsindex 957a3382df..a4a61634ad 100644--- a/packages/slack-hook-protocol/src/parse.ts+++ b/packages/slack-hook-protocol/src/parse.ts@@ -333,6 +333,8 @@ function validateAck(p: Record<string, unknown>): string | null {}function validateTurnEnd(p: Record<string, unknown>): string | null {+ if (p.background !== undefined && p.background !== true) return 'turn.end.background must be true or absent';+ if (p.background === true && p.clientFinal !== undefined) return 'background results cannot carry clientFinal';if (!isNonEmptyString(p.requestId)) return 'turn.end.requestId must be a non-empty string';if (!isNonEmptyString(p.externalKey)) return 'turn.end.externalKey must be a non-empty string';if (!isNullableString(p.sessionId)) return 'turn.end.sessionId must be a string or null';diff --git a/packages/slack-hook-protocol/src/types.ts b/packages/slack-hook-protocol/src/types.tsindex 5b2a66f28a..a6ab1f2641 100644--- a/packages/slack-hook-protocol/src/types.ts+++ b/packages/slack-hook-protocol/src/types.ts@@ -501,6 +501,8 @@ export interface TurnEndUsage {* 为 'error' 时 errorMessage 必须为非空字符串。*/export interface TurnEndPayload {+ /** session-result-v1: a new result for the bound lane, not a dispatched/reopened request. */+ background?: true;requestId: string;externalKey: string;sessionId: string | null;@@ -1330,6 +1332,8 @@ export interface LifecyclePreferencePayload {* 时才登记续跑记账并发帧; 缺席则维持旧行为(渠道消息停在失败上)。*/export const HOOK_FEATURE_TURN_REOPEN = 'turn-reopen-v1';+/** New messages for background execution in an existing IM-bound session. Excludes X. */+export const HOOK_FEATURE_SESSION_RESULT = 'session-result-v1';/*** 双向能力标识:server 会在收到普通 turn.end 后回 turn.delivery,并以