Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(feishu): stop mirroring thread replies to the group feed
MagicLizi944b1c261bcb
diff --git a/apps/desktop/src/main/im/shared/__tests__/messageHandler.finalReplyMirror.test.ts b/apps/desktop/src/main/im/shared/__tests__/messageHandler.finalReplyMirror.test.tsdeleted file mode 100644index 2066f51446..0000000000--- a/apps/desktop/src/main/im/shared/__tests__/messageHandler.finalReplyMirror.test.ts+++ /dev/null@@ -1,151 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import {- activateImAccountBoundary,- deactivateImAccountBoundary,-} from '../../accountBoundary';-import { createMessageHandler } from '../messageHandler';-import type { IMMessageEvent } from '@cindy/im';--function deferred(): { promise: Promise<void>; resolve: () => void } {- let resolve!: () => void;- const promise = new Promise<void>((done) => {- resolve = done;- });- return { promise, resolve };-}--function inboundEvent(overrides: Partial<IMMessageEvent> = {}): IMMessageEvent {- return {- channelName: 'feishu',- senderId: 'g/oc_group/omt_topic',- chatId: 'oc_group',- contextId: 'cli_bot',- messageId: 'om_1',- text: 'hello',- attachments: [],- unsupported: [],- ...overrides,- };-}--describe('messageHandler parent-chat mirror retain', () => {- beforeEach(() => {- activateImAccountBoundary();- });-- afterEach(() => {- activateImAccountBoundary();- });-- it('releases a queued parent-chat mirror retain when the IM account generation drops', async () => {- const gate = deferred();- const release = vi.fn();- const retainFinalReplyMirror = vi.fn(() => release);- const runAgentTurn = vi.fn(async () => {- await gate.promise;- });-- const attach = createMessageHandler(- {- channel: 'feishu',- processingEmoji: 'OK',- output: { kind: 'rich-card', im: { retainFinalReplyMirror } },- ui: {- agent: {- sendInternalError: () => 'internal',- unsupportedOnly: () => 'unsupported',- unsupportedNotice: () => 'notice',- },- },- } as never,- { handleSlashCommand: vi.fn() } as never,- { runAgentTurn } as never,- );-- let onMessage: ((event: IMMessageEvent) => void) | undefined;- attach({- name: 'feishu',- onMessage: (handler: (event: IMMessageEvent) => void) => {- onMessage = handler;- return () => undefined;- },- sendText: vi.fn(async () => ({ messageId: 'om_text' })),- sendMarkdownText: vi.fn(async () => ({ messageId: 'om_md' })),- } as never);-- onMessage?.(inboundEvent());- await vi.waitFor(() => expect(runAgentTurn).toHaveBeenCalledTimes(1));- onMessage?.(- inboundEvent({- messageId: 'om_queued',- finalReplyMirror: {- kind: 'parent-chat',- chatId: 'oc_group',- idempotencyKey: 'k'.repeat(64),- accountEpoch: 1,- },- }),- );-- expect(retainFinalReplyMirror).toHaveBeenCalledTimes(1);- expect(release).not.toHaveBeenCalled();-- deactivateImAccountBoundary();- gate.resolve();- await vi.waitFor(() => expect(release).toHaveBeenCalledTimes(1));- expect(runAgentTurn).toHaveBeenCalledTimes(1);- });-- it('releases a queued parent-chat mirror retain when message preprocessing throws', async () => {- const release = vi.fn();- const retainFinalReplyMirror = vi.fn(() => release);- const runAgentTurn = vi.fn();-- const attach = createMessageHandler(- {- channel: 'feishu',- processingEmoji: 'OK',- output: { kind: 'rich-card', im: { retainFinalReplyMirror } },- turnPermissionPolicyFor: () => {- throw new Error('policy exploded');- },- ui: {- agent: {- sendInternalError: () => 'internal',- unsupportedOnly: () => 'unsupported',- unsupportedNotice: () => 'notice',- },- },- } as never,- { handleSlashCommand: vi.fn() } as never,- { runAgentTurn } as never,- );-- let onMessage: ((event: IMMessageEvent) => void) | undefined;- attach({- name: 'feishu',- onMessage: (handler: (event: IMMessageEvent) => void) => {- onMessage = handler;- return () => undefined;- },- sendText: vi.fn(async () => ({ messageId: 'om_text' })),- sendMarkdownText: vi.fn(async () => ({ messageId: 'om_md' })),- } as never);-- onMessage?.(- inboundEvent({- finalReplyMirror: {- kind: 'parent-chat',- chatId: 'oc_group',- idempotencyKey: 'unexpected-error',- accountEpoch: 1,- },- }),- );-- await vi.waitFor(() => expect(release).toHaveBeenCalledTimes(1));- expect(retainFinalReplyMirror).toHaveBeenCalledTimes(1);- expect(runAgentTurn).not.toHaveBeenCalled();- });-});diff --git a/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.ts b/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.tsindex ba4789626a..a8f811aa0f 100644--- a/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.ts@@ -197,85 +197,6 @@ describe('IM slash commands', () => {expect(mocks.sendMarkdownText).not.toHaveBeenCalled();});- it('slash 回复发送失败时仍镜像到群主流以释放保留', async () => {- const { handlers } = makeHarness();- mocks.sendMarkdownText.mockRejectedValueOnce(new Error('send failed'));- const mirrorTerminalReply = vi.fn(async () => undefined);-- const handled = await handlers.handleSlashCommand('/help', {- botContextId: 'bot',- userId: 'ou_user',- mirrorTerminalReply,- });-- expect(handled).toBe(true);- expect(mirrorTerminalReply).toHaveBeenCalledTimes(1);- expect(mirrorTerminalReply).toHaveBeenCalledWith(ui.slash.help);- });-- it('已确认双投时把首个 markdown 终态镜像到群主流', async () => {- const { handlers } = makeHarness();- const mirrorTerminalReply = vi.fn(async () => undefined);-- const handled = await handlers.handleSlashCommand('/help', {- botContextId: 'bot',- userId: 'ou_user',- mirrorTerminalReply,- });-- expect(handled).toBe(true);- expect(mocks.sendMarkdownText).toHaveBeenCalledWith('ou_user', ui.slash.help);- expect(mirrorTerminalReply).toHaveBeenCalledTimes(1);- expect(mirrorTerminalReply).toHaveBeenCalledWith(ui.slash.help);- });-- it('已确认双投时把卡片型 slash 的正文镜像到群主流', async () => {- const spec = {- title: '选择模型',- body: '当前 **claude-opus-4-8**',- buttons: [{ id: 'pick', label: '切换' }],- };- const { handlers, cards } = makeHarness();- vi.mocked(cards.buildModelPickerCard).mockReturnValue(spec);- const mirrorTerminalReply = vi.fn(async () => undefined);-- const handled = await handlers.handleSlashCommand('/model', {- botContextId: 'bot',- userId: 'ou_user',- mirrorTerminalReply,- });-- expect(handled).toBe(true);- expect(mocks.sendInteractiveCard).toHaveBeenCalled();- expect(mirrorTerminalReply).toHaveBeenCalledTimes(1);- expect(mirrorTerminalReply).toHaveBeenCalledWith(spec.body);- });-- it('卡片型 slash 消费开场白卡后仍镜像正文到群主流', async () => {- const spec = {- title: '接管',- body: '选择一个工作区',- buttons: [{ id: 'pick', label: '选择' }],- };- const { handlers, cards } = makeHarness();- vi.mocked(cards.buildControlPickerCard).mockReturnValue(spec);- const withCard = vi.fn(async () => true);- const mirrorTerminalReply = vi.fn(async () => undefined);-- const handled = await handlers.handleSlashCommand('/ctr', {- botContextId: 'bot',- userId: 'ou_user',- consumePendingOpener: { withMarkdown: vi.fn(async () => false), withCard },- mirrorTerminalReply,- });-- expect(handled).toBe(true);- expect(withCard).toHaveBeenCalledWith('ou_user', spec);- expect(mocks.sendInteractiveCard).not.toHaveBeenCalled();- expect(mirrorTerminalReply).toHaveBeenCalledTimes(1);- expect(mirrorTerminalReply).toHaveBeenCalledWith(spec.body);- });-it('首条 slash 消费失败时回落正常发送', async () => {const { handlers } = makeHarness();const withMarkdown = vi.fn(async () => false);diff --git a/apps/desktop/src/main/im/shared/__tests__/stopCommandRouting.test.ts b/apps/desktop/src/main/im/shared/__tests__/stopCommandRouting.test.tsindex acaaa6a60d..3c6f49eb13 100644--- a/apps/desktop/src/main/im/shared/__tests__/stopCommandRouting.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/stopCommandRouting.test.ts@@ -93,7 +93,6 @@ describe('messageHandler !stop routing', () => {let handleSlashCommand: ReturnType<typeof vi.fn>;let sendMarkdownText: ReturnType<typeof vi.fn>;let sendText: ReturnType<typeof vi.fn>;- let mirrorFinalReply: ReturnType<typeof vi.fn>;let consumePendingOpenerCard: ReturnType<typeof vi.fn>;let consumePendingOpenerAsCard: ReturnType<typeof vi.fn>;let deliver: (event: IMMessageEvent) => void;@@ -104,7 +103,6 @@ describe('messageHandler !stop routing', () => {handleSlashCommand = vi.fn(async () => true);sendMarkdownText = vi.fn(async () => undefined);sendText = vi.fn(async () => undefined);- mirrorFinalReply = vi.fn(async () => undefined);// 群主流 @ 开话题的开场白卡收口能力(仅 feishu 实现; 这里模拟富卡渠道)。consumePendingOpenerCard = vi.fn(async () => false);consumePendingOpenerAsCard = vi.fn(async () => false);@@ -116,7 +114,6 @@ describe('messageHandler !stop routing', () => {},sendMarkdownText,sendText,- mirrorFinalReply,consumePendingOpenerCard,consumePendingOpenerAsCard,} as unknown as ChannelIM;@@ -492,119 +489,6 @@ describe('messageHandler !stop routing', () => {expect(sendText).not.toHaveBeenCalled();});- it('runAgentTurn 抛错时同步镜像已确认双投的群主流终态', async () => {- runAgentTurn.mockRejectedValueOnce(new Error('provider exploded'));- const mirror = {- kind: 'parent-chat' as const,- chatId: 'oc_group',- accountEpoch: 1,- idempotencyKey: 'mirror-throw',- };- const errorText = slackUi.agent.sendInternalError('provider exploded');- deliver(makeEvent({ text: '帮我看看', finalReplyMirror: mirror }));- await flushMicrotasks();-- expect(sendText).toHaveBeenCalledWith('U123456789', errorText, {- threadTs: '1234.5678',- });- expect(mirrorFinalReply).toHaveBeenCalledWith(mirror, errorText);- });-- it('!stop 时同步镜像已确认双投的群主流终态', async () => {- const mirror = {- kind: 'parent-chat' as const,- chatId: 'oc_group',- accountEpoch: 1,- idempotencyKey: 'mirror-stop',- };- deliver(makeEvent({ text: '!stop', finalReplyMirror: mirror }));- await flushMicrotasks();-- expect(runAgentTurn).not.toHaveBeenCalled();- expect(sendMarkdownText).toHaveBeenCalledWith('U123456789', slackUi.agent.stopDone(0), {- threadTs: '1234.5678',- });- expect(mirrorFinalReply).toHaveBeenCalledWith(mirror, slackUi.agent.stopDone(0));- });-- it('纯 unsupported 输入时同步镜像已确认双投的群主流终态', async () => {- const mirror = {- kind: 'parent-chat' as const,- chatId: 'oc_group',- accountEpoch: 1,- idempotencyKey: 'mirror-unsupported',- };- const unsupported = [{ type: 'audio', label: '语音(暂不支持)' }] as IMMessageEvent['unsupported'];- const notice = slackUi.agent.unsupportedOnly(unsupported);- deliver(makeEvent({ text: '', unsupported, finalReplyMirror: mirror }));- await flushMicrotasks();-- expect(runAgentTurn).not.toHaveBeenCalled();- expect(sendText).toHaveBeenCalledWith('U123456789', notice, { threadTs: '1234.5678' });- expect(mirrorFinalReply).toHaveBeenCalledWith(mirror, notice);- });-- it('/ctr 控制中拦截时同步镜像已确认双投的群主流终态', async () => {- enterControl('bot-ctx', 'U123456789');- const mirror = {- kind: 'parent-chat' as const,- chatId: 'oc_group',- accountEpoch: 1,- idempotencyKey: 'mirror-ctr',- };- deliver(makeEvent({ text: '帮我看看', finalReplyMirror: mirror }));- await flushMicrotasks();-- expect(runAgentTurn).not.toHaveBeenCalled();- expect(handleSlashCommand).not.toHaveBeenCalled();- expect(sendMarkdownText).toHaveBeenCalledWith(- 'U123456789',- slackUi.agent.controlInProgress,- { threadTs: '1234.5678' },- );- expect(mirrorFinalReply).toHaveBeenCalledWith(mirror, slackUi.agent.controlInProgress);- });-- it('slash 抛错时同步镜像已确认双投的群主流终态', async () => {- handleSlashCommand.mockRejectedValueOnce(new Error('list projects failed'));- const mirror = {- kind: 'parent-chat' as const,- chatId: 'oc_group',- accountEpoch: 1,- idempotencyKey: 'mirror-slash-error',- };- const errorText = slackUi.agent.sendInternalError('list projects failed');- deliver(makeEvent({ text: '/ctr', finalReplyMirror: mirror }));- await flushMicrotasks();-- expect(runAgentTurn).not.toHaveBeenCalled();- expect(sendMarkdownText).toHaveBeenCalledWith('U123456789', errorText, {- threadTs: '1234.5678',- });- expect(mirrorFinalReply).toHaveBeenCalledWith(mirror, errorText);- });-- it('slash 成功时把镜像回调交给命令实现', async () => {- let captured: Parameters<typeof handleSlashCommand>[1] | undefined;- handleSlashCommand.mockImplementationOnce(async (_text, ctx) => {- captured = ctx;- await ctx.mirrorTerminalReply?.('帮助正文');- return true;- });- const mirror = {- kind: 'parent-chat' as const,- chatId: 'oc_group',- accountEpoch: 1,- idempotencyKey: 'mirror-slash-ok',- };- deliver(makeEvent({ text: '/help', finalReplyMirror: mirror }));- await flushMicrotasks();-- expect(captured?.mirrorTerminalReply).toBeTypeOf('function');- expect(runAgentTurn).not.toHaveBeenCalled();- expect(mirrorFinalReply).toHaveBeenCalledWith(mirror, '帮助正文');- });-it('早期拒绝终态(missing_auth)经 onEarlyReject 收口开场白卡', async () => {let capturedArgs: Parameters<ImTurnRunner['runAgentTurn']>[0] | undefined;runAgentTurn.mockImplementationOnce(async (args: Parameters<ImTurnRunner['runAgentTurn']>[0]) => {diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.tsindex f418a939c7..f8793db099 100644--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts@@ -28,7 +28,6 @@ const mocks = vi.hoisted(() => ({error: vi.fn(),debug: vi.fn(),},- releaseFinalReplyMirror: vi.fn(),feishuIm: {reactToMessage: vi.fn(),removeMessageReaction: vi.fn(),@@ -41,8 +40,6 @@ const mocks = vi.hoisted(() => ({consumePendingOpenerCard: vi.fn(),getPendingOpenerTrigger: vi.fn(),takeNotedFallbackOpenerId: vi.fn(),- retainFinalReplyMirror: vi.fn(),- mirrorFinalReply: vi.fn(),},getMaker: vi.fn(),listProviders: vi.fn(),@@ -432,12 +429,6 @@ interface TurnOverrides {groupHistoryAccess?: GroupHistoryAccessScope;prePersistedUserMessage?: { sessionId: string; clientId: string };onEarlyReject?: (reason: string, text: string) => Promise<boolean> | boolean;- finalReplyMirror?: {- kind: 'parent-chat';- chatId: string;- idempotencyKey: string;- accountEpoch: number;- };}async function runDefaultTurn(onTurnComplete = vi.fn(), overrides: TurnOverrides = {}) {@@ -462,7 +453,6 @@ async function startDefaultTurn(onTurnComplete = vi.fn(), overrides: TurnOverrid? { prePersistedUserMessage: overrides.prePersistedUserMessage }: {}),...(overrides.onEarlyReject ? { onEarlyReject: overrides.onEarlyReject } : {}),- ...(overrides.finalReplyMirror ? { finalReplyMirror: overrides.finalReplyMirror } : {}),});return { onTurnComplete, turnPromise };}@@ -567,7 +557,6 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()mocks.feishuIm.consumePendingOpenerCard.mockResolvedValue(false);mocks.feishuIm.getPendingOpenerTrigger.mockReturnValue(undefined);mocks.feishuIm.takeNotedFallbackOpenerId.mockReturnValue(undefined);- mocks.feishuIm.retainFinalReplyMirror.mockReturnValue(mocks.releaseFinalReplyMirror);mocks.feishuIm.startStreamingText.mockResolvedValue({messageId: 'stream-1',append: vi.fn(),@@ -1800,32 +1789,6 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ());});- it('mirrors credential-busy early reject onto the parent-chat dual-delivery target', async () => {- const busy = new CredentialModeSwitchBusyError(['busy-session']);- mocks.getMaker.mockReturnValue(createMakerCreateSessionFailureHarness(busy));- const mirror = {- kind: 'parent-chat' as const,- chatId: 'oc_group',- accountEpoch: 1,- idempotencyKey: 'mirror-busy',- };-- await runDefaultTurn(vi.fn(), { finalReplyMirror: mirror });- await flushMicrotasks();-- expect(mocks.feishuIm.sendText).toHaveBeenCalledWith('ou_user', ui.agent.credentialBusy, {- threadTs: undefined,- });- expect(mocks.feishuIm.mirrorFinalReply).toHaveBeenCalledWith(- {- ...mirror,- allowedFileRoots: ['F:\\XDMaker'],- pinnedFileRoots: [],- },- ui.agent.credentialBusy,- );- });-it('queues a second message while the first turn is running and dispatches it after done', async () => {mocks.feishuIm.reactToMessage.mockImplementation(async (messageId: string) => `reaction-${messageId}`,@@ -1900,36 +1863,6 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ());});- it('releases mirror retention when a queued turn is dropped by stop', async () => {- setupSession(async () => ({ accepted: true }));- await runDefaultTurn(vi.fn(), { userMessageId: 'msg-first' });- const mirror = {- kind: 'parent-chat' as const,- chatId: 'oc_group',- accountEpoch: 1,- idempotencyKey: 'mirror-queued-stop',- };-- await runDefaultTurn(vi.fn(), {- userMessageId: 'msg-second',- finalReplyMirror: mirror,- });- expect(mocks.feishuIm.retainFinalReplyMirror).toHaveBeenCalledWith({- ...mirror,- allowedFileRoots: ['F:\\XDMaker'],- pinnedFileRoots: [],- });- expect(mocks.releaseFinalReplyMirror).not.toHaveBeenCalled();-- await expect(- getRunner().stopActiveTurn({- botContextId: 'cli_test_bot',- userId: 'ou_user',- }),- ).resolves.toMatchObject({ stopped: true, droppedQueued: 1 });- expect(mocks.releaseFinalReplyMirror).toHaveBeenCalledTimes(1);- });-it('queues while a desktop-originated turn is running (attached takeover) and dispatches on its stray done', async () => {// 接管模式典型场景: desktop 侧 turn 在跑(本渠道没有对应 TurnState),// isTurnRunning=true → 入队; desktop turn 的 done 以 stray event 到达 → 派发。@@ -2699,188 +2632,12 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ());});- it('mirrors missing-auth early reject onto the parent-chat dual-delivery target', async () => {- mocks.readXdGatewayApiKey.mockReturnValue(null);- mocks.findActiveSession.mockResolvedValue(null);- const mirror = {- kind: 'parent-chat' as const,- chatId: 'oc_group',- accountEpoch: 1,- idempotencyKey: 'mirror-auth',- };- const expected = ui.agent.authMissing?.({- agentKind: 'claude-code',- model: 'claude-opus-4-7',- providerId: 'xd',- providerLabel: 'XD',- missing: 'gateway-key',- });-- await runDefaultTurn(vi.fn(), { finalReplyMirror: mirror });-- expect(mocks.createSession).not.toHaveBeenCalled();- expect(mocks.feishuIm.sendText).toHaveBeenCalledWith('ou_user', expected, {- threadTs: undefined,- });- expect(mocks.feishuIm.mirrorFinalReply).toHaveBeenCalledWith(mirror, expected);- });-- it('arms only the true terminal finalize with the parent-chat mirror', async () => {- const handle = {- messageId: 'stream-terminal',- append: vi.fn(),- replace: vi.fn(),- finalize: vi.fn(),- close: vi.fn(),- };- mocks.feishuIm.startStreamingText.mockResolvedValue(handle);- const mirror = {- kind: 'parent-chat' as const,- chatId: 'oc_group',- accountEpoch: 1,- idempotencyKey: 'mirror-stream-done',- };- const h = setupSession(async () => ({ accepted: true }));- const onTurnComplete = vi.fn();- await runDefaultTurn(onTurnComplete, { finalReplyMirror: mirror });-- expect(mocks.feishuIm.retainFinalReplyMirror).toHaveBeenCalledWith({- ...mirror,- allowedFileRoots: ['F:\\XDMaker'],- pinnedFileRoots: [],- });- expect(mocks.releaseFinalReplyMirror).not.toHaveBeenCalled();-- h.emit({ type: 'text', data: { text: 'final answer', isFinal: true } });- await waitForAssertion(() => {- expect(mocks.feishuIm.startStreamingText).toHaveBeenCalledTimes(1);- });- expect(mocks.feishuIm.startStreamingText).toHaveBeenCalledWith('ou_user', undefined, {- threadTs: undefined,- });- expect(mocks.feishuIm.mirrorFinalReply).not.toHaveBeenCalled();-- h.emit({ type: 'done', data: {} });- await waitForAssertion(() => {- expect(onTurnComplete).toHaveBeenCalledTimes(1);- expect(handle.finalize).toHaveBeenCalledTimes(1);- });- expect(handle.finalize).toHaveBeenCalledWith(expect.stringContaining('final answer'), {- finalReplyMirror: {- ...mirror,- allowedFileRoots: ['F:\\XDMaker'],- pinnedFileRoots: [],- },- });- expect(mocks.releaseFinalReplyMirror).toHaveBeenCalledTimes(1);- expect(mocks.feishuIm.mirrorFinalReply).not.toHaveBeenCalled();- });-- it('supplies the parent-chat mirror only at terminal finalize so files reuse the upload key', async () => {- const handle = {- messageId: 'stream-armed',- append: vi.fn(),- replace: vi.fn(),- finalize: vi.fn(),- close: vi.fn(),- };- mocks.feishuIm.startStreamingText.mockResolvedValue(handle);- const mirror = {- kind: 'parent-chat' as const,- chatId: 'oc_group',- accountEpoch: 1,- idempotencyKey: 'mirror-armed',- };- const h = setupSession(async () => ({ accepted: true }));- const onTurnComplete = vi.fn();- await runDefaultTurn(onTurnComplete, { finalReplyMirror: mirror });-- h.emit({ type: 'text', data: { text: 'see the file', isFinal: true } });- await waitForAssertion(() => {- expect(mocks.feishuIm.startStreamingText).toHaveBeenCalledTimes(1);- });- expect(handle.finalize).not.toHaveBeenCalled();- expect(mocks.feishuIm.mirrorFinalReply).not.toHaveBeenCalled();-- h.emit({ type: 'done', data: {} });- await waitForAssertion(() => {- expect(onTurnComplete).toHaveBeenCalledTimes(1);- expect(handle.finalize).toHaveBeenCalledTimes(1);- });- expect(handle.finalize).toHaveBeenCalledWith(expect.stringContaining('see the file'), {- finalReplyMirror: {- ...mirror,- allowedFileRoots: ['F:\\XDMaker'],- pinnedFileRoots: [],- },- });- expect(mocks.feishuIm.mirrorFinalReply).not.toHaveBeenCalled();- });-- it('mirrors side-channel tool images onto the parent-chat even when the final text omits them', async () => {- const extraAbsPath = 'C:\\cindy-media\\tool-extra.png';- mocks.resolveXdtImageUrl.mockReturnValue({ absPath: extraAbsPath });- const handle = {- messageId: 'stream-extra-image',- append: vi.fn(),- replace: vi.fn(),- finalize: vi.fn(),- close: vi.fn(),- addExtraImageAbsPath: vi.fn(),- };- mocks.feishuIm.startStreamingText.mockResolvedValue(handle);- const mirror = {- kind: 'parent-chat' as const,- chatId: 'oc_group',- accountEpoch: 1,- idempotencyKey: 'mirror-extra-image',- };- const h = setupSession(async () => ({ accepted: true }));- const onTurnComplete = vi.fn();- await runDefaultTurn(onTurnComplete, { finalReplyMirror: mirror });-- h.emit({- type: 'tool_result_full',- data: {- fullText: JSON.stringify({ xdt_image_url: 'xdt-image://blob/tool-extra.png' }),- },- });- h.emit({ type: 'text', data: { text: 'here is the image', isFinal: true } });- await waitForAssertion(() => {- expect(mocks.feishuIm.startStreamingText).toHaveBeenCalled();- });- h.emit({ type: 'done', data: {} });- await waitForAssertion(() => {- expect(onTurnComplete).toHaveBeenCalledTimes(1);- expect(handle.finalize).toHaveBeenCalledTimes(1);- });- expect(handle.addExtraImageAbsPath).toHaveBeenCalledWith(extraAbsPath);- expect(handle.finalize).toHaveBeenCalledWith(- expect.stringContaining('here is the image'),- {- finalReplyMirror: {- ...mirror,- allowedFileRoots: ['F:\\XDMaker'],- pinnedFileRoots: [],- },- },- );- expect(mocks.feishuIm.mirrorFinalReply).not.toHaveBeenCalled();-- });-- it('never treats SSH workdir or media paths as local parent-chat files', async () => {- const mirror = {- kind: 'parent-chat' as const,- chatId: 'oc_group',- accountEpoch: 1,- idempotencyKey: 'mirror-remote-safe',- };+ it('never treats SSH workdir or media paths as local files', async () => {const h = setupAttachedSession(async () => ({ accepted: true }), {remoteHostId: 'ssh-host-1',});const onTurnComplete = vi.fn();- await runDefaultTurn(onTurnComplete, { finalReplyMirror: mirror });+ await runDefaultTurn(onTurnComplete);h.emit({type: 'tool_result_full',@@ -2898,100 +2655,7 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()expect(mocks.resolveXdtImageUrl).not.toHaveBeenCalled();expect(mocks.materializeLocalMarkdownImages).not.toHaveBeenCalled();const handle = await mocks.feishuIm.startStreamingText.mock.results[0].value;- expect(handle.finalize).toHaveBeenCalledWith(expect.stringContaining('remote final'), {- finalReplyMirror: {- ...mirror,- allowedFileRoots: [],- pinnedFileRoots: [],- },- });- expect(mocks.feishuIm.mirrorFinalReply).not.toHaveBeenCalled();- });-- it('defers parent-chat mirroring across an in-turn permission card until the turn completes', async () => {- const firstHandle = {- messageId: 'stream-pre',- append: vi.fn(),- replace: vi.fn(),- finalize: vi.fn(),- close: vi.fn(),- };- const secondHandle = {- messageId: 'stream-post',- append: vi.fn(),- replace: vi.fn(),- finalize: vi.fn(),- close: vi.fn(),- };- mocks.feishuIm.startStreamingText- .mockResolvedValueOnce(firstHandle)- .mockResolvedValueOnce(secondHandle);- mocks.buildPermissionCard.mockReturnValue({- title: 'allow bash?',- body: 'run bash',- buttons: [{ id: 'allow', label: 'Allow' }],- });- mocks.feishuIm.sendInteractiveCard.mockResolvedValue({ messageId: 'perm-card' });- const permissionGate = deferred<InteractionDecision>();- mocks.registerPending.mockReturnValue(permissionGate.promise);- const mirror = {- kind: 'parent-chat' as const,- chatId: 'oc_group',- accountEpoch: 1,- idempotencyKey: 'mirror-interact',- };- const h = setupSession(async () => ({ accepted: true }));- const onTurnComplete = vi.fn();- await runDefaultTurn(onTurnComplete, { finalReplyMirror: mirror });-- h.emit({ type: 'text', data: { text: 'I will run bash', isFinal: true } });- await waitForAssertion(() => {- expect(mocks.feishuIm.startStreamingText).toHaveBeenCalledTimes(1);- });- expect(mocks.feishuIm.startStreamingText).toHaveBeenCalledWith('ou_user', undefined, {- threadTs: undefined,- });-- const interactionPromise = h.dispatchInteraction({- kind: 'permission',- requestId: 'req-perm',- toolName: 'bash',- input: { command: 'ls' },- });- await waitForAssertion(() => {- expect(firstHandle.finalize).toHaveBeenCalled();- expect(mocks.feishuIm.sendInteractiveCard).toHaveBeenCalled();- });- expect(firstHandle.finalize).toHaveBeenCalledWith(expect.stringContaining('I will run bash'));- expect(mocks.feishuIm.mirrorFinalReply).not.toHaveBeenCalled();-- permissionGate.resolve({ kind: 'permission', behavior: 'allow' });- await expect(interactionPromise).resolves.toEqual({- kind: 'permission',- behavior: 'allow',- });-- h.emit({ type: 'text', data: { text: 'command finished: ok', isFinal: true } });- await waitForAssertion(() => {- expect(mocks.feishuIm.startStreamingText).toHaveBeenCalledTimes(2);- });- h.emit({ type: 'done', data: {} });- await waitForAssertion(() => {- expect(onTurnComplete).toHaveBeenCalledTimes(1);- expect(secondHandle.finalize).toHaveBeenCalled();- });- expect(secondHandle.finalize).toHaveBeenCalledWith(- expect.stringContaining('command finished: ok'),- {- finalReplyMirror: {- ...mirror,- allowedFileRoots: ['F:\\XDMaker'],- pinnedFileRoots: [],- },- },- );- expect(String(secondHandle.finalize.mock.calls[0][0])).not.toContain('I will run bash');- expect(mocks.feishuIm.mirrorFinalReply).not.toHaveBeenCalled();+ expect(handle.finalize).toHaveBeenCalledWith(expect.stringContaining('remote final'));});it('does not report route resolution before auth passes on an existing route', async () => {diff --git a/apps/desktop/src/main/im/shared/messageHandler.ts b/apps/desktop/src/main/im/shared/messageHandler.tsindex 6d63b1d380..b941561c30 100644--- a/apps/desktop/src/main/im/shared/messageHandler.ts+++ b/apps/desktop/src/main/im/shared/messageHandler.ts@@ -66,14 +66,6 @@ export function createMessageHandler(}}- async function mirrorTerminalReply(event: IMMessageEvent, text: string): Promise<void> {- if (!event.finalReplyMirror) return;- try {- await richIm?.mirrorFinalReply?.(event.finalReplyMirror, text);- } catch {- /* swallow */- }- }const log = createLogger(`im:${channel}:msg`);/** Per-user serial lock — same shape as legacy messageRouter.turnLocks. */@@ -158,7 +150,6 @@ export function createMessageHandler(const msg = err instanceof Error ? err.message : String(err);log.warn(`controlInProgress notice failed (non-fatal): ${msg}`);}- await mirrorTerminalReply(event, ui.agent.controlInProgress);return;}@@ -202,7 +193,6 @@ export function createMessageHandler(log.warn(`!stop reply failed (non-fatal): ${msg}`);}}- await mirrorTerminalReply(event, reply);return;}@@ -239,18 +229,11 @@ export function createMessageHandler(},}: undefined;- let slashMirrored = false;- const mirrorSlashReply = async (text: string): Promise<void> => {- if (slashMirrored) return;- slashMirrored = true;- await mirrorTerminalReply(event, text);- };try {await slash.handleSlashCommand(event.text, {botContextId: event.contextId,userId: event.senderId,consumePendingOpener: sink,- ...(event.finalReplyMirror ? { mirrorTerminalReply: mirrorSlashReply } : {}),});} catch (err) {const msg = err instanceof Error ? err.message : String(err);@@ -278,7 +261,6 @@ export function createMessageHandler(/* 发送失败与卡残留同一最终边界 */}}- await mirrorSlashReply(errorText);}return;}@@ -304,7 +286,6 @@ export function createMessageHandler(log.warn(`unsupportedOnly send failed (non-fatal): ${msg}`);}}- await mirrorTerminalReply(event, notice);return;}@@ -407,7 +388,6 @@ export function createMessageHandler(}: {}),attachments: event.attachments,- ...(event.finalReplyMirror ? { finalReplyMirror: event.finalReplyMirror } : {}),// threadScoped 渠道: scopeKey = thread root ts(thread = session 路由键)scopeKey: threadScoped ? event.scopeKey : undefined,// Title generation and similar detached work must stay visible to the@@ -442,7 +422,6 @@ export function createMessageHandler(/* swallow */}}- await mirrorTerminalReply(event, errorText);}}@@ -455,16 +434,6 @@ export function createMessageHandler(log.info(`drop inbound message after account boundary closed channel=${channel}`);return;}- let releaseQueuedMirror: (() => void) | undefined;- if (event.finalReplyMirror) {- try {- const release = richIm?.retainFinalReplyMirror?.(event.finalReplyMirror);- if (typeof release === 'function') releaseQueuedMirror = release;- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- log.warn(`retainFinalReplyMirror at enqueue failed (non-fatal): ${msg}`);- }- }// threadScoped 渠道: 同 thread 串行、跨 thread 并行(scopeKey 进锁键);// feishu scopeKey 恒 undefined — 键多一个冒号后缀, 行为不变。const key = `${event.contextId}:${event.senderId}:${threadScoped ? (event.scopeKey ?? '') : ''}`;@@ -477,15 +446,6 @@ export function createMessageHandler(runInImAccountGeneration(accountGeneration, () =>processOne(im, event, accountGeneration),).catch((err) => {- // `processOne` only rejects before it has handed the mirror to a- // terminal send path (for example, when an adapter policy hook- // throws). Release the enqueue retain for every such drop, not- // only account-generation invalidation.- try {- releaseQueuedMirror?.();- } catch {- /* best-effort */- }if (isImAccountScopeClosedError(err)) {log.info(`drop inbound message from stale account generation channel=${channel}`);return;diff --git a/apps/desktop/src/main/im/shared/slashCommands.ts b/apps/desktop/src/main/im/shared/slashCommands.tsindex 3a38a71f46..6d220ef37a 100644--- a/apps/desktop/src/main/im/shared/slashCommands.ts+++ b/apps/desktop/src/main/im/shared/slashCommands.ts@@ -62,12 +62,6 @@ export interface SlashCtx {withMarkdown(userId: string, markdown: string): Promise<boolean>;withCard(userId: string, spec: InteractiveCardSpec): Promise<boolean>;};- /**- * 已确认双投时由 messageHandler 注入: 首个 markdown 终态同步到群主流。- * 只应消费一次(与 consumePendingOpener 同口径)。卡片回复镜像卡片正文- * (没有正文时退回标题);按钮仍只在话题内可点。- */- mirrorTerminalReply?: (text: string) => Promise<void>;}export interface ImSlashHandlers {@@ -100,27 +94,6 @@ export function createSlashHandlers(* 群主流 @ 开话题的首条 slash: 首个回复经 ctx.consumePendingOpener 就地* patch 开场白卡(消费过一次后回落正常发送)。*/- async function mirrorFirstSlashReply(ctx: SlashCtx, text: string): Promise<void> {- const mirror = ctx.mirrorTerminalReply;- if (!mirror) return;- const trimmed = text.trim();- if (!trimmed) return;- ctx.mirrorTerminalReply = undefined;- try {- await mirror(trimmed);- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- log.warn(`slash parent-chat mirror failed (non-fatal): ${msg}`);- }- }-- function slashCardMirrorText(spec: InteractiveCardSpec | null | undefined): string {- if (!spec || typeof spec !== 'object') return '';- const body = typeof spec.body === 'string' ? spec.body.trim() : '';- const title = typeof spec.title === 'string' ? spec.title.trim() : '';- return body || title;- }-async function safeSendText(ctx: SlashCtx, text: string): Promise<void> {try {if (ctx.consumePendingOpener) {@@ -144,10 +117,6 @@ export function createSlashHandlers(} catch (err) {const msg = err instanceof Error ? err.message : String(err);log.warn(`safeSendText failed (non-fatal): ${msg}`);- } finally {- // Thread send failure must still consume the parent-chat retain; otherwise- // enqueue retention pins confirmed forever.- await mirrorFirstSlashReply(ctx, text);}}@@ -184,8 +153,6 @@ export function createSlashHandlers(const msg = err instanceof Error ? err.message : String(err);log.warn(`safeSendCard failed (non-fatal): ${msg}`);return false;- } finally {- await mirrorFirstSlashReply(ctx, slashCardMirrorText(spec));}}diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.tsindex 3c5f38560e..27101add97 100644--- a/apps/desktop/src/main/im/shared/turnRunner.ts+++ b/apps/desktop/src/main/im/shared/turnRunner.ts@@ -31,7 +31,6 @@*/import { createHash, randomUUID } from 'node:crypto';-import fs from 'node:fs';import path from 'node:path';/**@@ -86,7 +85,6 @@ import type {} from '@cindy/maker-core';import type {IMAttachment,- IMFinalReplyMirror,InteractiveCardSpec,StreamingTextHandle,} from '@cindy/im';@@ -184,55 +182,12 @@ function resolveTurnFileRoots(return remoteHostId ? [] : [workingDir];}-function openRootDirectory(target: string): number {- let flags = fs.constants.O_RDONLY;- if (fs.constants.O_DIRECTORY) flags |= fs.constants.O_DIRECTORY;- return fs.openSync(target, flags);-}--function pinTurnFileRoots(- roots: readonly string[],-): Array<{ dev: string; ino: string }> {- const pinned: Array<{ dev: string; ino: string }> = [];- for (const root of roots) {- if (!root.trim()) continue;- let fd: number | undefined;- try {- fd = openRootDirectory(root);- const st = fs.fstatSync(fd, { bigint: true });- if (!st.isDirectory() || st.ino === 0n) continue;- pinned.push({ dev: String(st.dev), ino: String(st.ino) });- } catch {- /* Unresolvable roots are omitted; an empty pin fail-closes file reuse. */- } finally {- if (fd !== undefined) fs.closeSync(fd);- }- }- return pinned;-}--function withTurnFileRoots(- mirror: IMFinalReplyMirror | undefined,- allowedFileRoots: string[],-): IMFinalReplyMirror | undefined {- if (!mirror) return undefined;- return {- ...mirror,- allowedFileRoots,- pinnedFileRoots: pinTurnFileRoots(allowedFileRoots),- };-}-interface TurnState {/** Stable identity used by the central interaction router for this turn. */turnId: string;userId: string;/** thread = session 模型的会话维度键(slack thread root ts);feishu undefined。 */scopeKey?: string;- /** Optional secondary presentation target for this turn's terminal output only. */- finalReplyMirror?: IMFinalReplyMirror;- /** Releases channel-side confirmation retention when this turn leaves the queue/lifecycle. */- finalReplyMirrorRelease: (() => void) | null;initialMessageText: string;/** First text-delta resolves this lazily (avoids creating a card for empty turns). */streamingHandle: StreamingTextHandle | null;@@ -426,8 +381,6 @@ export interface ImRunAgentTurnArgs {attachments: IMAttachment[];/** thread = session 模型的会话维度键(slack);feishu 不传。 */scopeKey?: string;- /** Secondary destination for this turn's completed answer; never affects routing. */- finalReplyMirror?: IMFinalReplyMirror;/*** 发给 agent 的正文覆盖(群上下文前缀拼装, 见 adapter.prepareAgentTurnText)。* 缺省 = text。落库(persistUserMessage)与标题生成恒用 text(渠道原文)。@@ -768,7 +721,6 @@ export function createTurnRunner(ui.agent.apiKeyMissing;const consumed = (await args.onEarlyReject?.('missing_auth', text)) ?? false;if (!consumed) await replyMissingAuth(userId, created.missingAuth, scopeKey);- await mirrorEarlyRejectReply(args.finalReplyMirror, text);}await discardHandedOverAck(userMessageId, args.ackReactionIdPromise);return { kind: 'rejected', reason: 'missing_auth' };@@ -789,7 +741,6 @@ export function createTurnRunner(if (!consumed) {await replyMissingAuth(userId, authStatus, scopeKey, target.attached);}- await mirrorEarlyRejectReply(withTurnFileRoots(args.finalReplyMirror, allowedFileRoots), text);}await discardHandedOverAck(userMessageId, args.ackReactionIdPromise);return { kind: 'rejected', reason: 'missing_auth' };@@ -844,8 +795,6 @@ export function createTurnRunner(turnId: randomUUID(),userId,scopeKey: target.scopeKey,- finalReplyMirror: withTurnFileRoots(args.finalReplyMirror, allowedFileRoots),- finalReplyMirrorRelease: null,initialMessageText: text,streamingHandle: null,streamingHandlePromise: null,@@ -885,7 +834,6 @@ export function createTurnRunner(} else {await completeTurnCallbackAfterAck(turn);}- await mirrorEarlyRejectReply(turn.finalReplyMirror, ui.agent.credentialBusy);} else {await completeTurnCallbackAfterAck(turn);}@@ -983,7 +931,6 @@ export function createTurnRunner(await completeTurnCallbackAfterAck(turn);return { kind: 'busy', reason: 'session_running' };}- retainTurnFinalReplyMirror(turn);state.sendQueue.push(item);log.info(`queued message for session=${row.id.slice(-8)} position=${state.sendQueue.length}`);// 本渠道没有未收口的 turn(纯 desktop turn 在跑) → 派发只能靠它的 stray@@ -997,7 +944,6 @@ export function createTurnRunner(return { kind: 'busy', reason: 'queued_internally' };}- retainTurnFinalReplyMirror(turn);const dispatch = await dispatchQueuedSend(state, userId, item);if (dispatch.kind !== 'accepted') return dispatch;return {@@ -1317,13 +1263,11 @@ export function createTurnRunner(/* The session is already detaching; reporting remains best-effort. */}}- releaseTurnFinalReplyMirror(item.turn);finishDeferredDetachIfIdle(state);return { kind: 'busy', reason: 'session_detaching' };}if (item.queueMode === 'external') {await completeTurnCallbackAfterAck(item.turn);- releaseTurnFinalReplyMirror(item.turn);return { kind: 'busy', reason: 'session_running' };}state.sendQueue.unshift(item);@@ -1563,45 +1507,11 @@ export function createTurnRunner(}}- async function mirrorEarlyRejectReply(- mirror: IMFinalReplyMirror | undefined,- text: string,- ): Promise<void> {- await mirrorTurnFinalReply(mirror, text);- }-- async function mirrorTurnFinalReply(- mirror: IMFinalReplyMirror | undefined,- text: string,- opts?: { mediaAbsPaths?: string[] },- ): Promise<void> {- if (!mirror || output.kind !== 'rich-card') return;- try {- if (opts) {- await output.im.mirrorFinalReply?.(mirror, text, opts);- } else {- await output.im.mirrorFinalReply?.(mirror, text);- }- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- log.warn(`terminal mirror failed (non-fatal): ${msg}`);- }- }-- /**- * Terminal streaming finalize. Parent-chat copies are supplied here — not at- * `startStreamingText` — so permission / ask / plan `finalizeActiveStream`- * cannot reuse the same card UUID for a fragment.- */async function finalizeTurnStream(turn: TurnState, finalView: string): Promise<void> {const handle = turn.streamingHandle;if (!handle) return;try {- if (turn.finalReplyMirror) {- await handle.finalize(finalView, { finalReplyMirror: turn.finalReplyMirror });- } else {- await handle.finalize(finalView);- }+ await handle.finalize(finalView);} catch (err) {if (output.kind === 'chunked-text') {turn.terminalKind = 'error';@@ -2595,38 +2505,7 @@ export function createTurnRunner(return true;}- function retainTurnFinalReplyMirror(turn: TurnState): void {- if (turn.finalReplyMirrorRelease || !turn.finalReplyMirror || output.kind !== 'rich-card') {- return;- }- try {- const release = output.im.retainFinalReplyMirror?.(turn.finalReplyMirror);- if (typeof release === 'function') turn.finalReplyMirrorRelease = release;- } catch (err) {- log.warn(- `final reply mirror retention failed (non-fatal): ${- err instanceof Error ? err.message : String(err)- }`,- );- }- }-- function releaseTurnFinalReplyMirror(turn: TurnState): void {- const release = turn.finalReplyMirrorRelease;- turn.finalReplyMirrorRelease = null;- try {- release?.();- } catch (err) {- log.warn(- `final reply mirror retention release failed (non-fatal): ${- err instanceof Error ? err.message : String(err)- }`,- );- }- }-function settleTurnTerminal(turn: TurnState): void {- releaseTurnFinalReplyMirror(turn);const resolve = turn.resolveTerminal;if (!resolve) return;turn.resolveTerminal = null;@@ -2749,7 +2628,6 @@ export function createTurnRunner(await sendTextClaimingOpener(userId, message, state.scopeKey);}}- await mirrorEarlyRejectReply(failure.turn.finalReplyMirror, message);// 群会话「完全访问」档被强确认策略拒绝: 报错文案之外, 再给 owner// 私聊发一张一键修复卡(切回 auto)。只对提供 permissionModeFix 文案// 的渠道(飞书)与群 lane 生效 — 私聊不挂群策略, 防御性跳过; 卡片@@ -2788,7 +2666,6 @@ export function createTurnRunner(/* 忽略失败:派发失败提示不能再阻塞收口。 */}}- releaseTurnFinalReplyMirror(failure.turn);if (finishDeferredDetachIfIdle(state)) return;// 一条 pre-dispatch failure 不能卡死后面的排队消息 — 继续放行。maybeDispatchNextQueued(state, userId);@@ -2901,9 +2778,6 @@ export function createTurnRunner(// 创建失败集中在此捕获并 resolve null(#2164):调用点全部是 fire-and-forget// 的 .then(...),各自补 rejection handler 必然遗漏;失败留下脱敏日志与// streamingStartFailed 标记,已生成正文由收口分支一次性降级发送。- // Dual-delivery parent-chat copies are armed only by the true terminal- // finalize call. Pre-interaction fragments use the same handle contract but- // deliberately finalize without finalReplyMirror.turn.streamingHandlePromise = (async () => {try {const handle =@@ -3053,11 +2927,6 @@ export function createTurnRunner(if (!consumed) {await sendTextClaimingOpener(userId, '✅ (本轮无文本输出)', state.scopeKey);}- await mirrorTurnFinalReply(- turn.finalReplyMirror,- '✅ (本轮无文本输出)',- turn.mediaAbsPaths.length > 0 ? { mediaAbsPaths: turn.mediaAbsPaths } : undefined,- );}} catch {/* swallow */@@ -3079,11 +2948,6 @@ export function createTurnRunner(});} else {await output.im.sendText(userId, fallbackText, { threadTs: state.scopeKey });- await mirrorTurnFinalReply(- turn.finalReplyMirror,- fallbackText,- turn.mediaAbsPaths.length > 0 ? { mediaAbsPaths: turn.mediaAbsPaths } : undefined,- );}log.info(`[${channel}/turn] streaming surface unavailable — final text delivered via plain send`);} catch (err) {@@ -3172,11 +3036,6 @@ export function createTurnRunner(if (!consumed) {await sendTextClaimingOpener(userId, errorText, state.scopeKey);}- await mirrorTurnFinalReply(- turn?.finalReplyMirror,- errorText,- turn && turn.mediaAbsPaths.length > 0 ? { mediaAbsPaths: turn.mediaAbsPaths } : undefined,- );}} catch {/* swallow */@@ -3460,7 +3319,6 @@ export function createTurnRunner(const dropped = state.sendQueue.splice(0, state.sendQueue.length);log.warn(`dropping ${dropped.length} queued message(s) on cleanup/detach`);for (const item of dropped) {- releaseTurnFinalReplyMirror(item.turn);releaseAttachedImTurnHeadless(item.turn);void cancelAckReaction(item.turn);}diff --git a/packages/lizi-im/src/channelIM.ts b/packages/lizi-im/src/channelIM.tsindex 3531882c56..b8ef7783b4 100644--- a/packages/lizi-im/src/channelIM.ts+++ b/packages/lizi-im/src/channelIM.ts@@ -18,7 +18,6 @@import type {IMCardActionEvent,- IMFinalReplyMirror,IMMessageEvent,IMStatus,InteractiveCardSpec,@@ -130,16 +129,6 @@ export interface RichChannelIM extends TextChannelIM {opts?: { threadTs?: string },): Promise<StreamingTextHandle>;- /** Keep mirror confirmation alive while a turn is active or queued; returns its release hook. */- retainFinalReplyMirror?(mirror: IMFinalReplyMirror): (() => void) | void;-- /** Best-effort terminal mirror when the primary rich surface could not be created. */- mirrorFinalReply?(- mirror: IMFinalReplyMirror,- text: string,- opts?: { mediaAbsPaths?: string[] },- ): Promise<void>;-/*** 从出站消息的 messageId 提取 thread 维度键(= 该消息作为 thread root 时的* thread_ts)。thread 能力渠道(slack)实现;编排层用它把"刚发出的接管卡"diff --git a/packages/lizi-im/src/feishu/__tests__/dualDelivery.test.ts b/packages/lizi-im/src/feishu/__tests__/dualDelivery.test.tsindex 8516f6ddb8..4bfcc7ed9d 100644--- a/packages/lizi-im/src/feishu/__tests__/dualDelivery.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/dualDelivery.test.ts@@ -1,14 +1,6 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import {- coordinateDualDelivery,- isMirrorConfirmationRetainedForTest,- releaseMirrorConfirmation,- resetDualDeliveryForTest,- retainMirrorConfirmation,- scheduleMirrorOnConfirmation,- waitForMirrorConfirmation,-} from '../dualDelivery.js';+import { coordinateDualDelivery, resetDualDeliveryForTest } from '../dualDelivery.js';function input(overrides: Partial<Parameters<typeof coordinateDualDelivery>[0]> = {}) {return {@@ -35,13 +27,7 @@ describe('Feishu native thread/main dual delivery', () => {const topic = await coordinateDualDelivery(input());await expect(flat).resolves.toEqual({ kind: 'suppress-main-copy' });- expect(topic).toMatchObject({- kind: 'dispatch',- mirrorKey: expect.any(String),- alreadyConfirmed: true,- });- if (topic.kind !== 'dispatch' || !topic.mirrorKey) throw new Error('missing mirror key');- await expect(waitForMirrorConfirmation(topic.mirrorKey)).resolves.toBe(true);+ expect(topic).toMatchObject({ kind: 'dispatch' });});it('suppresses a main-feed copy that arrives after topic dispatch', async () => {@@ -50,53 +36,12 @@ describe('Feishu native thread/main dual delivery', () => {expect(topic.kind).toBe('dispatch');expect(flat).toEqual({ kind: 'suppress-main-copy' });- if (topic.kind !== 'dispatch' || !topic.mirrorKey) throw new Error('missing mirror key');- await expect(waitForMirrorConfirmation(topic.mirrorKey)).resolves.toBe(true);- });-- it('retains a live turn confirmation past the normal TTL and cache cap', async () => {- vi.useFakeTimers();- const topic = await coordinateDualDelivery(input());- if (topic.kind !== 'dispatch' || !topic.mirrorKey) throw new Error('missing mirror key');- retainMirrorConfirmation(topic.mirrorKey);- await expect(- coordinateDualDelivery(input({ messageId: 'om_flat', threadId: '' })),- ).resolves.toEqual({ kind: 'suppress-main-copy' });-- // Fill beyond MAX_CONFIRMED while consuming each unrelated mirror. The- // target represents a still-running Agent turn and must remain pinned.- for (let i = 0; i < 2_001; i++) {- const fillerTopic = await coordinateDualDelivery(- input({ createTime: `filler-${i}`, messageId: `om_filler_topic_${i}` }),- );- if (fillerTopic.kind !== 'dispatch' || !fillerTopic.mirrorKey) {- throw new Error('missing filler mirror key');- }- await coordinateDualDelivery(- input({- createTime: `filler-${i}`,- messageId: `om_filler_flat_${i}`,- threadId: '',- }),- );- await expect(waitForMirrorConfirmation(fillerTopic.mirrorKey)).resolves.toBe(true);- }-- await vi.advanceTimersByTimeAsync(2 * 60 * 60 * 1000 + 1);- await coordinateDualDelivery(- input({ createTime: 'prune-trigger', messageId: 'om_prune_trigger' }),- );-- await expect(waitForMirrorConfirmation(topic.mirrorKey)).resolves.toBe(true);- await expect(- coordinateDualDelivery(input({ messageId: 'om_flat_after_terminal', threadId: '' })),- ).resolves.toEqual({ kind: 'suppress-main-copy' });});it('does not pin a confirmed route until the caller emits an Agent turn', async () => {vi.useFakeTimers();const topic = await coordinateDualDelivery(input());- if (topic.kind !== 'dispatch' || !topic.mirrorKey) throw new Error('missing mirror key');+ expect(topic.kind).toBe('dispatch');await expect(coordinateDualDelivery(input({ messageId: 'om_flat', threadId: '' })),).resolves.toEqual({ kind: 'suppress-main-copy' });@@ -106,7 +51,9 @@ describe('Feishu native thread/main dual delivery', () => {input({ createTime: 'prune-unemitted', messageId: 'om_prune_unemitted' }),);- await expect(waitForMirrorConfirmation(topic.mirrorKey)).resolves.toBe(false);+ const lateFlat = coordinateDualDelivery(input({ messageId: 'om_flat_after_ttl', threadId: '' }));+ await vi.advanceTimersByTimeAsync(1_000);+ await expect(lateFlat).resolves.toMatchObject({ kind: 'dispatch' });});it('releases an uncommitted topic lease so a later retry can acquire a fresh one', async () => {@@ -138,7 +85,6 @@ describe('Feishu native thread/main dual delivery', () => {).resolves.toEqual({ kind: 'suppress-main-copy' });expect(topic).toMatchObject({kind: 'dispatch',- mirrorKey: expect.any(String),commitTopic: expect.any(Function),});@@ -147,8 +93,6 @@ describe('Feishu native thread/main dual delivery', () => {);expect(retry).toMatchObject({kind: 'dispatch',- mirrorKey: expect.any(String),- alreadyConfirmed: true,commitTopic: expect.any(Function),});await expect(@@ -199,7 +143,7 @@ describe('Feishu native thread/main dual delivery', () => {await vi.advanceTimersByTimeAsync(1_000);await expect(duplicate).resolves.toEqual({ kind: 'suppress-main-copy' });- expect(topic).toMatchObject({ kind: 'dispatch', mirrorKey: expect.any(String) });+ expect(topic).toMatchObject({ kind: 'dispatch' });});it('dispatches an unpaired flat group message after the bounded wait', async () => {@@ -207,11 +151,7 @@ describe('Feishu native thread/main dual delivery', () => {const flat = coordinateDualDelivery(input({ messageId: 'om_flat', threadId: '' }));await vi.advanceTimersByTimeAsync(1_000);const flatDecision = await flat;- expect(flatDecision).toMatchObject({ kind: 'dispatch', mirrorKey: expect.any(String) });- if (flatDecision.kind !== 'dispatch' || !flatDecision.mirrorKey) {- throw new Error('unpaired flat must expose mirrorKey');- }- await expect(waitForMirrorConfirmation(flatDecision.mirrorKey)).resolves.toBe(false);+ expect(flatDecision).toMatchObject({ kind: 'dispatch' });});it('elects only one route when duplicate flat ids share a logical send', async () => {@@ -234,8 +174,6 @@ describe('Feishu native thread/main dual delivery', () => {await expect(coordinateDualDelivery(input())).resolves.toMatchObject({kind: 'dispatch',- mirrorKey: expect.any(String),- alreadyConfirmed: true,});expect(firstDecision.commitUnpairedFlat()).toBe(false);});@@ -250,8 +188,6 @@ describe('Feishu native thread/main dual delivery', () => {await expect(flat).resolves.toMatchObject({ kind: 'dispatch' });expect(topic.kind).toBe('dispatch');- if (topic.kind !== 'dispatch' || !topic.mirrorKey) throw new Error('missing mirror key');- await expect(waitForMirrorConfirmation(topic.mirrorKey)).resolves.toBe(false);});it('does not correlate messages when Feishu omits create_time', async () => {@@ -292,13 +228,7 @@ describe('Feishu native thread/main dual delivery', () => {}const topic = await coordinateDualDelivery(input());- expect(topic).toMatchObject({- kind: 'dispatch',- mirrorKey: expect.any(String),- alreadyConfirmed: true,- });- if (topic.kind !== 'dispatch' || !topic.mirrorKey) throw new Error('missing mirror key');- await expect(waitForMirrorConfirmation(topic.mirrorKey)).resolves.toBe(true);+ expect(topic).toMatchObject({ kind: 'dispatch' });expect(flatDecision.commitUnpairedFlat()).toBe(false);});@@ -317,11 +247,7 @@ describe('Feishu native thread/main dual delivery', () => {);const lateTopic = await coordinateDualDelivery(input());- expect(lateTopic).toMatchObject({- kind: 'dispatch',- mirrorKey: expect.any(String),- alreadyConfirmed: true,- });+ expect(lateTopic).toMatchObject({ kind: 'dispatch' });expect(flatDecision.commitUnpairedFlat()).toBe(false);});@@ -349,15 +275,11 @@ describe('Feishu native thread/main dual delivery', () => {input({ createTime: 'capacity-0', messageId: 'om_capacity_topic' }),);- expect(lateTopic).toMatchObject({- kind: 'dispatch',- mirrorKey: expect.any(String),- alreadyConfirmed: true,- });+ expect(lateTopic).toMatchObject({ kind: 'dispatch' });expect(flatDecision.commitUnpairedFlat()).toBe(false);});- it('keeps an abandoned flat observable so a late topic confirms its mirror', async () => {+ it('lets a late topic take over after an unpaired flat is abandoned', async () => {vi.useFakeTimers();const flat = coordinateDualDelivery(input({ messageId: 'om_flat', threadId: '' }));await vi.advanceTimersByTimeAsync(1_000);@@ -373,17 +295,7 @@ describe('Feishu native thread/main dual delivery', () => {flatDecision.abandonUnpairedFlat();expect(flatDecision.commitUnpairedFlat()).toBe(false);const topic = await coordinateDualDelivery(input());- expect(topic).toMatchObject({- kind: 'dispatch',- mirrorKey: expect.any(String),- alreadyConfirmed: true,- });- if (topic.kind !== 'dispatch' || !topic.mirrorKey) throw new Error('missing mirror key');- await expect(waitForMirrorConfirmation(topic.mirrorKey)).resolves.toBe(true);-- const scheduled = vi.fn();- scheduleMirrorOnConfirmation(topic.mirrorKey, scheduled);- expect(scheduled).toHaveBeenCalledTimes(1);+ expect(topic).toMatchObject({ kind: 'dispatch' });});it('lets a fresh flat retry acquire a new route lease after abandonment', async () => {@@ -401,7 +313,6 @@ describe('Feishu native thread/main dual delivery', () => {const retryDecision = await retry;expect(retryDecision).toMatchObject({kind: 'dispatch',- mirrorKey: expect.any(String),commitUnpairedFlat: expect.any(Function),});if (retryDecision.kind !== 'dispatch' || !retryDecision.commitUnpairedFlat) {@@ -410,50 +321,20 @@ describe('Feishu native thread/main dual delivery', () => {expect(retryDecision.commitUnpairedFlat()).toBe(true);});- it('releases inflight retain when an abandoned flat drops its deferred mirror', async () => {- vi.useFakeTimers();- const flat = coordinateDualDelivery(input({ messageId: 'om_flat', threadId: '' }));- await vi.advanceTimersByTimeAsync(1_000);- const flatDecision = await flat;- if (- flatDecision.kind !== 'dispatch' ||- !flatDecision.mirrorKey ||- !flatDecision.abandonUnpairedFlat- ) {- throw new Error('unpaired flat must expose abandonUnpairedFlat');- }- retainMirrorConfirmation(flatDecision.mirrorKey);- const scheduled = vi.fn();- expect(scheduleMirrorOnConfirmation(flatDecision.mirrorKey, scheduled)).toBe(true);- flatDecision.abandonUnpairedFlat();- expect(scheduled).not.toHaveBeenCalled();- expect(isMirrorConfirmationRetainedForTest(flatDecision.mirrorKey)).toBe(false);- });-it('suppresses a late topic after the unpaired flat has committed its route', async () => {vi.useFakeTimers();const flat = coordinateDualDelivery(input({ messageId: 'om_flat', threadId: '' }));await vi.advanceTimersByTimeAsync(1_000);const flatDecision = await flat;- expect(flatDecision).toMatchObject({ kind: 'dispatch', mirrorKey: expect.any(String) });- if (- flatDecision.kind !== 'dispatch' ||- !flatDecision.mirrorKey ||- !flatDecision.commitUnpairedFlat- ) {- throw new Error('unpaired flat must expose mirrorKey and commitUnpairedFlat');+ expect(flatDecision).toMatchObject({ kind: 'dispatch' });+ if (flatDecision.kind !== 'dispatch' || !flatDecision.commitUnpairedFlat) {+ throw new Error('unpaired flat must expose commitUnpairedFlat');}expect(flatDecision.commitUnpairedFlat()).toBe(true);- const scheduled = vi.fn();- scheduleMirrorOnConfirmation(flatDecision.mirrorKey, scheduled);- expect(scheduled).not.toHaveBeenCalled();-await expect(coordinateDualDelivery(input())).resolves.toEqual({kind: 'suppress-main-copy',});- expect(scheduled).toHaveBeenCalledTimes(1);- await expect(waitForMirrorConfirmation(flatDecision.mirrorKey)).resolves.toBe(true);});it('suppresses a later main-feed copy after a late topic has taken over', async () => {@@ -469,28 +350,13 @@ describe('Feishu native thread/main dual delivery', () => {).resolves.toEqual({ kind: 'suppress-main-copy' });});- it('delivers a scheduled mirror when the main-feed copy arrives after the pair window', async () => {- vi.useFakeTimers();- const topic = await coordinateDualDelivery(input());- if (topic.kind !== 'dispatch' || !topic.mirrorKey) throw new Error('missing mirror key');- await vi.advanceTimersByTimeAsync(1_000);- await expect(waitForMirrorConfirmation(topic.mirrorKey)).resolves.toBe(false);-- const scheduled = vi.fn();- scheduleMirrorOnConfirmation(topic.mirrorKey, scheduled);- await expect(- coordinateDualDelivery(input({ messageId: 'om_flat', threadId: '' })),- ).resolves.toEqual({ kind: 'suppress-main-copy' });- expect(scheduled).toHaveBeenCalledTimes(1);- });-it('writes a recent-thread tombstone when a pending pair is capacity-evicted', async () => {// Must stay in lockstep with dualDelivery MAX_PENDING (512).const pendingCap = 512;const first = await coordinateDualDelivery(input({ createTime: '1', messageId: 'om_t0', threadId: 'omt_0' }),);- expect(first).toMatchObject({ kind: 'dispatch', mirrorKey: expect.any(String) });+ expect(first).toMatchObject({ kind: 'dispatch' });for (let i = 1; i <= pendingCap; i++) {await coordinateDualDelivery(@@ -533,11 +399,7 @@ describe('Feishu native thread/main dual delivery', () => {const lateTopic = await coordinateDualDelivery(input({ createTime: '1', messageId: 'om_t0', threadId: 'omt_0' }),);- expect(lateTopic).toMatchObject({- kind: 'dispatch',- mirrorKey: expect.any(String),- alreadyConfirmed: true,- });+ expect(lateTopic).toMatchObject({ kind: 'dispatch' });expect(firstDecision.commitUnpairedFlat()).toBe(false);});@@ -547,94 +409,23 @@ describe('Feishu native thread/main dual delivery', () => {await expect(coordinateDualDelivery(input({ messageId: 'om_flat', threadId: '' })),).resolves.toEqual({ kind: 'suppress-main-copy' });- if (topic.kind !== 'dispatch' || !topic.mirrorKey) throw new Error('missing mirror key');+ expect(topic.kind).toBe('dispatch');await vi.advanceTimersByTimeAsync(2 * 60 * 60 * 1000 + 1);- await expect(waitForMirrorConfirmation(topic.mirrorKey)).resolves.toBe(false);const lateFlat = coordinateDualDelivery(input({ messageId: 'om_flat_late', threadId: '' }));await vi.advanceTimersByTimeAsync(1_000);await expect(lateFlat).resolves.toMatchObject({ kind: 'dispatch' });});- it('keeps a held confirmation past the confirmed TTL', async () => {- vi.useFakeTimers();- const topic = await coordinateDualDelivery(input());- await expect(- coordinateDualDelivery(input({ messageId: 'om_flat', threadId: '' })),- ).resolves.toEqual({ kind: 'suppress-main-copy' });- if (topic.kind !== 'dispatch' || !topic.mirrorKey) throw new Error('missing mirror key');- retainMirrorConfirmation(topic.mirrorKey);-- await vi.advanceTimersByTimeAsync(2 * 60 * 60 * 1000 + 1);- await expect(waitForMirrorConfirmation(topic.mirrorKey)).resolves.toBe(true);- await expect(- coordinateDualDelivery(input({ messageId: 'om_flat_late', threadId: '' })),- ).resolves.toEqual({ kind: 'suppress-main-copy' });- releaseMirrorConfirmation(topic.mirrorKey);- });-- it('does not capacity-evict a held confirmation', async () => {- const topic = await coordinateDualDelivery(input({ createTime: 'held-0', messageId: 'om_held' }));- await expect(- coordinateDualDelivery(- input({ createTime: 'held-0', messageId: 'om_held_flat', threadId: '' }),- ),- ).resolves.toEqual({ kind: 'suppress-main-copy' });- if (topic.kind !== 'dispatch' || !topic.mirrorKey) throw new Error('missing mirror key');- retainMirrorConfirmation(topic.mirrorKey);-- for (let i = 1; i <= 2_001; i++) {- await coordinateDualDelivery(- input({ createTime: `held-${i}`, messageId: `om_held_t${i}` }),- );- await coordinateDualDelivery(- input({ createTime: `held-${i}`, messageId: `om_held_f${i}`, threadId: '' }),- );- }-- await expect(waitForMirrorConfirmation(topic.mirrorKey)).resolves.toBe(true);- await expect(- coordinateDualDelivery(- input({ createTime: 'held-0', messageId: 'om_held_later', threadId: '' }),- ),- ).resolves.toEqual({ kind: 'suppress-main-copy' });- releaseMirrorConfirmation(topic.mirrorKey);- });-- it('does not suppress a copy after the late-copy window, and drops the deferred mirror', async () => {+ it('does not suppress a copy after the late-copy window', async () => {vi.useFakeTimers();const topic = await coordinateDualDelivery(input());- if (topic.kind !== 'dispatch' || !topic.mirrorKey) throw new Error('missing mirror key');- retainMirrorConfirmation(topic.mirrorKey);+ expect(topic.kind).toBe('dispatch');await vi.advanceTimersByTimeAsync(1_000);- const scheduled = vi.fn();- scheduleMirrorOnConfirmation(topic.mirrorKey, scheduled);- expect(isMirrorConfirmationRetainedForTest(topic.mirrorKey)).toBe(true);await vi.advanceTimersByTimeAsync(25_001);const lateFlat = coordinateDualDelivery(input({ messageId: 'om_flat', threadId: '' }));await vi.advanceTimersByTimeAsync(1_000);await expect(lateFlat).resolves.toMatchObject({ kind: 'dispatch' });- expect(scheduled).not.toHaveBeenCalled();- expect(isMirrorConfirmationRetainedForTest(topic.mirrorKey)).toBe(false);- });-- it('keeps a live confirmation past the TTL and restarts the TTL on release', async () => {- vi.useFakeTimers();- const topic = await coordinateDualDelivery(input());- await coordinateDualDelivery(input({ messageId: 'om_flat', threadId: '' }));- if (topic.kind !== 'dispatch' || !topic.mirrorKey) throw new Error('missing mirror key');- retainMirrorConfirmation(topic.mirrorKey);-- await vi.advanceTimersByTimeAsync(2 * 60 * 60 * 1000 + 1);- await coordinateDualDelivery(- input({ createTime: 'release-prune-trigger', messageId: 'om_release_prune_trigger' }),- );-- releaseMirrorConfirmation(topic.mirrorKey);- await expect(waitForMirrorConfirmation(topic.mirrorKey)).resolves.toBe(true);-- await vi.advanceTimersByTimeAsync(2 * 60 * 60 * 1000 + 1);- await expect(waitForMirrorConfirmation(topic.mirrorKey)).resolves.toBe(false);});});diff --git a/packages/lizi-im/src/feishu/__tests__/streamingText.test.ts b/packages/lizi-im/src/feishu/__tests__/streamingText.test.tsindex e1ed1cf2c6..ca377a3d2f 100644--- a/packages/lizi-im/src/feishu/__tests__/streamingText.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/streamingText.test.ts@@ -1,35 +1,16 @@-import fsSync from 'node:fs';-import fs from 'node:fs/promises';-import os from 'node:os';-import path from 'node:path';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({patchCardRaw: vi.fn(),sendCardRaw: vi.fn(),sendFile: vi.fn(),- sendFileToChat: vi.fn(),- sendCardToChat: vi.fn(),sendText: vi.fn(),uploadImage: vi.fn(),- getAccountEpoch: vi.fn(() => 1),- getBoundClient: vi.fn(() => ({ pinned: true })),- runWithPinnedAccount: vi.fn(async (_pin: unknown, fn: () => Promise<void>) => fn()),- isPinnedAccountCurrent: vi.fn(() => true),- attestedRealPath: vi.fn(),- attestOpenFileWithinDirectory: vi.fn(),- // 默认无 patchable opener — 走新建流式卡路径claimPatchableOpener: vi.fn(() => null),resolveMediaUrl: vi.fn((): string | null => null),}));vi.mock('../outbound.js', () => mocks);-vi.mock('../dualDelivery.js', () => ({- releaseMirrorConfirmation: vi.fn(),- waitForMirrorConfirmation: vi.fn(async () => true),- scheduleMirrorOnConfirmation: vi.fn(() => false),-}));vi.mock('../moduleScope.js', () => ({getLog: () => ({ debug: vi.fn(), error: vi.fn(), warn: vi.fn() }),getHost: () => ({@@ -39,12 +20,7 @@ vi.mock('../moduleScope.js', () => ({}));import { messages } from '../messages.js';-import { FEISHU_CARD_REQUEST_MAX_BYTES, mirrorFinal, start } from '../streamingText.js';-import {- releaseMirrorConfirmation,- scheduleMirrorOnConfirmation,- waitForMirrorConfirmation,-} from '../dualDelivery.js';+import { FEISHU_CARD_REQUEST_MAX_BYTES, start } from '../streamingText.js';function markdownContent(card: unknown): string {return (card as { body: { elements: Array<{ content: string }> } }).body.elements[0].content;@@ -54,115 +30,17 @@ function requestBytes(card: unknown): number {return Buffer.byteLength(JSON.stringify({ content: JSON.stringify(card) }), 'utf8');}-function terminalMirror(- key: string,- allowedFileRoots?: string[],- pinnedFileRoots?: Array<{ dev: string; ino: string; realPath?: string }>,-) {- return {- finalReplyMirror: {- kind: 'parent-chat' as const,- chatId: 'oc_group',- idempotencyKey: key,- accountEpoch: 1,- ...(allowedFileRoots ? { allowedFileRoots } : {}),- ...(pinnedFileRoots ? { pinnedFileRoots } : {}),- },- };-}--function pinRoot(root: string): Array<{ dev: string; ino: string; realPath: string }> {- const realPath = fsSync.realpathSync.native(root);- const st = fsSync.statSync(realPath, { bigint: true });- return [{ dev: String(st.dev), ino: String(st.ino), realPath }];-}--function ancestorInodes(fileRealPath: string): Array<{ dev: string; ino: string }> {- const ancestors: Array<{ dev: string; ino: string }> = [];- const seen = new Set<string>();- let current = path.dirname(fileRealPath);- for (;;) {- try {- const st = fsSync.statSync(current, { bigint: true });- if (st.ino === 0n) break;- const key = `${st.dev}:${st.ino}`;- if (seen.has(key)) break;- seen.add(key);- ancestors.push({ dev: String(st.dev), ino: String(st.ino) });- } catch {- break;- }- const parent = path.dirname(current);- if (parent === current) break;- current = parent;- }- return ancestors;-}--function fileSourceFromPath(absPath: string): {- realPath: string;- dev: string;- ino: string;- ancestors: Array<{ dev: string; ino: string }>;-} {- const realPath = fsSync.realpathSync.native(absPath);- const st = fsSync.statSync(realPath, { bigint: true });- return {- realPath,- dev: String(st.dev),- ino: String(st.ino),- ancestors: ancestorInodes(realPath),- };-}--function flipPathCase(value: string): string {- return value.replace(/[a-zA-Z]/g, (char) =>- char === char.toLowerCase() ? char.toUpperCase() : char.toLowerCase(),- );-}--const tempDirs: string[] = [];--afterEach(async () => {- await Promise.all(- tempDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true })),- );-});-describe('feishu streaming text', () => {beforeEach(() => {vi.clearAllMocks();mocks.sendCardRaw.mockResolvedValue({ messageId: 'om_stream' });mocks.patchCardRaw.mockResolvedValue(undefined);- mocks.sendCardToChat.mockResolvedValue({ messageId: 'om_mirror' });- mocks.sendFile.mockImplementation(async (_userId: string, absPath: string) => {- let uploadedSource: ReturnType<typeof fileSourceFromPath> | undefined;- try {- uploadedSource = fileSourceFromPath(absPath);- } catch {- /* tests may point at missing files */- }- return {- ok: true,- messageId: 'om_primary_file',- reusableMessage: {- msgType: 'file',- content: JSON.stringify({ file_key: 'file-key' }),- },- ...(uploadedSource ? { uploadedSource } : {}),- };+ mocks.sendFile.mockResolvedValue({+ ok: true,+ messageId: 'om_primary_file',});- mocks.sendFileToChat.mockResolvedValue({ ok: true, messageId: 'om_mirror_file' });mocks.sendText.mockResolvedValue({ messageId: 'om_fallback' });mocks.resolveMediaUrl.mockReturnValue(null);- mocks.getAccountEpoch.mockReturnValue(1);- mocks.getBoundClient.mockReturnValue({ pinned: true });- mocks.isPinnedAccountCurrent.mockReturnValue(true);- mocks.attestedRealPath.mockResolvedValue('');- mocks.attestOpenFileWithinDirectory.mockResolvedValue(true);- mocks.runWithPinnedAccount.mockImplementation(async (_pin: unknown, fn: () => Promise<void>) =>- fn(),- );});it('keeps an in-limit final card unchanged', async () => {@@ -200,21 +78,16 @@ describe('feishu streaming text', () => {expect(markdownContent(card)).toBe(messages.streaming.deliveryFailed);});- it('patches a short notice and still mirrors when the primary final card is rejected', async () => {+ it('patches a short notice when the primary final card is rejected', async () => {mocks.patchCardRaw.mockRejectedValueOnce(new Error('unsupported card shape'));const handle = await start('ou_owner');- await handle.finalize('正文', terminalMirror('v'.repeat(64)));+ await handle.finalize('正文');expect(mocks.patchCardRaw).toHaveBeenCalledTimes(2);expect(markdownContent(mocks.patchCardRaw.mock.calls[1][1])).toBe(messages.streaming.deliveryFailed,);expect(mocks.sendText).not.toHaveBeenCalled();- expect(mocks.sendCardToChat).toHaveBeenCalledWith(- 'oc_group',- expect.anything(),- `${'v'.repeat(32)}-card`,- );});it('falls back to plain text when even the short card patch fails', async () => {@@ -228,990 +101,18 @@ describe('feishu streaming text', () => {);});- it('mirrors one finalized card to the parent group with a stable uuid', async () => {- const handle = await start('g/oc_group/omt_topic');- await handle.finalize('最终正文', terminalMirror('a'.repeat(64)));-- expect(mocks.patchCardRaw).toHaveBeenCalledWith('om_stream', expect.anything());- expect(mocks.sendCardToChat).toHaveBeenCalledWith(- 'oc_group',- expect.anything(),- `${'a'.repeat(32)}-card`,- );- expect(markdownContent(mocks.sendCardToChat.mock.calls[0][1])).toBe('最终正文');- });-- it('keeps primary finalize successful when parent-group mirroring fails', async () => {- mocks.sendCardToChat.mockRejectedValueOnce(new Error('group rate limited'));- const handle = await start('g/oc_group/omt_topic');-- await expect(- handle.finalize('最终正文', terminalMirror('b'.repeat(64))),- ).resolves.toBeUndefined();- expect(mocks.patchCardRaw).toHaveBeenCalledTimes(1);- expect(mocks.sendText).not.toHaveBeenCalled();- });-- it('defers parent-chat mirroring until late confirmation', async () => {- vi.mocked(waitForMirrorConfirmation).mockResolvedValueOnce(false);- vi.mocked(scheduleMirrorOnConfirmation).mockImplementation((_key, run) => {- run();- return true;- });- const handle = await start('g/oc_group/omt_topic');- await handle.finalize('迟到镜像', terminalMirror('c'.repeat(64)));-- expect(scheduleMirrorOnConfirmation).toHaveBeenCalledWith('c'.repeat(64), expect.any(Function));- expect(mocks.sendCardToChat).toHaveBeenCalledWith(- 'oc_group',- expect.anything(),- `${'c'.repeat(32)}-card`,- );- });-- it('mirrors immediately when inbound pairing was already confirmed', async () => {- await mirrorFinal('oc_group', 'p'.repeat(64), '终态正文', [], [], 1, true);-- expect(waitForMirrorConfirmation).not.toHaveBeenCalled();- expect(scheduleMirrorOnConfirmation).not.toHaveBeenCalled();- expect(mocks.sendCardToChat).toHaveBeenCalledWith(- 'oc_group',- expect.anything(),- `${'p'.repeat(32)}-card`,- );- });-- it('still mirrors parent-chat text when one extra image upload fails', async () => {- mocks.uploadImage.mockImplementation(async (absPath: string) => {- if (absPath.includes('missing')) throw new Error('file gone');- return 'img_ok';- });-- await mirrorFinal(- 'oc_group',- 'g'.repeat(64),- '终态正文',- ['C:\\cindy-media\\ok.png', 'C:\\cindy-media\\missing.png'],- ['/allowed'],- 1,- );-- expect(mocks.sendCardToChat).toHaveBeenCalledTimes(1);- expect(markdownContent(mocks.sendCardToChat.mock.calls[0][1])).toBe('终态正文');- });-- it('still mirrors parent-chat text without reopening files when an inline image upload fails', async () => {- const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-inline-fail-'));- tempDirs.push(root);- const allowedFile = path.join(root, 'report.txt');- await fs.writeFile(allowedFile, 'report');- mocks.resolveMediaUrl.mockReturnValue('/cindy-media/missing.png');- mocks.uploadImage.mockRejectedValue(new Error('file gone'));-- await mirrorFinal(- 'oc_group',- 'j'.repeat(64),- `终态正文 \n[report.txt](xdt-file://${allowedFile})`,- [],- [root],- 1,- );-- expect(mocks.sendCardToChat).toHaveBeenCalledTimes(1);- expect(markdownContent(mocks.sendCardToChat.mock.calls[0][1])).toContain('终态正文');- expect(mocks.sendFileToChat).not.toHaveBeenCalled();- });-- it('still finalizes and mirrors a streaming card when an inline image upload throws', async () => {+ it('still finalizes a streaming card when an inline image upload throws', async () => {const absPath = '/cindy-media/missing.png';mocks.resolveMediaUrl.mockReturnValue(absPath);mocks.uploadImage.mockRejectedValue(new Error('file gone'));const handle = await start('g/oc_group/omt_topic');await expect(- handle.finalize(- '终态正文 ',- terminalMirror('w'.repeat(64), ['/cindy-media']),- ),+ handle.finalize('终态正文 '),).resolves.toBeUndefined();expect(mocks.uploadImage).toHaveBeenCalledTimes(1);expect(mocks.patchCardRaw).toHaveBeenCalledTimes(1);- expect(mocks.sendCardToChat).toHaveBeenCalledTimes(1);- expect(markdownContent(mocks.sendCardToChat.mock.calls[0][1])).toContain('终态正文');- expect(releaseMirrorConfirmation).toHaveBeenCalledWith('w'.repeat(64));- });-- it('does not re-upload extra images already inlined in the mirrored markdown', async () => {- const absPath = '/cindy-media/same.png';- mocks.resolveMediaUrl.mockReturnValue(absPath);- mocks.uploadImage.mockImplementation(async (p: string) => `img:${p}`);-- await mirrorFinal(- 'oc_group',- 'h'.repeat(64),- '见 ',- [absPath],- ['/allowed'],- 1,- );-- expect(mocks.uploadImage.mock.calls.filter(([p]) => p === absPath)).toHaveLength(1);- expect(mocks.sendCardToChat).toHaveBeenCalledTimes(1);- });-- it('does not resolve local images when allowedFileRoots is empty', async () => {- mocks.resolveMediaUrl.mockReturnValue('/cindy-media/secret.png');- mocks.uploadImage.mockResolvedValue('img_secret');-- await mirrorFinal(- 'oc_group',- 't'.repeat(64),- '正文 ',- ['/cindy-media/extra.png'],- [],- 1,- );-- expect(mocks.resolveMediaUrl).not.toHaveBeenCalled();- expect(mocks.uploadImage).not.toHaveBeenCalled();- expect(markdownContent(mocks.sendCardToChat.mock.calls[0][1])).toBe('正文');- });-- it('does not claim delivery for an image-only mirror with empty allowedFileRoots', async () => {- mocks.resolveMediaUrl.mockReturnValue('/cindy-media/secret.png');- mocks.uploadImage.mockResolvedValue('img_secret');-- await mirrorFinal(- 'oc_group',- 'u'.repeat(64),- '',- [],- [],- 1,- );-- expect(mocks.resolveMediaUrl).not.toHaveBeenCalled();- expect(mocks.uploadImage).not.toHaveBeenCalled();- expect(markdownContent(mocks.sendCardToChat.mock.calls[0][1])).toBe(- messages.streaming.deliveryFailed,- );- });-- it('does not copy local images on the streaming-handle parent-chat mirror when allowedFileRoots is empty', async () => {- mocks.resolveMediaUrl.mockReturnValue('/cindy-media/secret.png');- mocks.uploadImage.mockResolvedValue('img_secret');- const handle = await start('g/oc_group/omt_topic');-- await handle.finalize(- '正文 ',- terminalMirror('t'.repeat(64), []),- );-- expect(mocks.patchCardRaw).toHaveBeenCalled();- expect(mocks.sendCardToChat).toHaveBeenCalledTimes(1);- expect(markdownContent(mocks.sendCardToChat.mock.calls[0][1])).toBe('正文');- });-- it('fits an oversized SSH streaming mirror card within Feishu request limits', async () => {- const handle = await start('g/oc_group/omt_topic');- const longMarkdown = [- '| 列一 | 列二 |',- '| --- | --- |',- '| 很长的内容 | 更多内容 |',- '```ts',- 'const answer = "很长的代码块";',- '```',- ].join('\n').repeat(500);-- await handle.finalize(longMarkdown, terminalMirror('z'.repeat(64), []));-- const mirrored = mocks.sendCardToChat.mock.calls[0][1];- expect(requestBytes(mirrored)).toBeLessThanOrEqual(FEISHU_CARD_REQUEST_MAX_BYTES);- expect(markdownContent(mirrored)).toContain('完整内容仍可在 Cindy 桌面端查看');- });-- it('fails closed for one-shot file-only replies without a primary upload key', async () => {- const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-fileonly-'));- tempDirs.push(root);- const allowedFile = path.join(root, 'report.txt');- await fs.writeFile(allowedFile, 'report');-- await mirrorFinal(- 'oc_group',- 'i'.repeat(64),- `[report.txt](xdt-file://${allowedFile})`,- [],- [root],- 1,- );-- expect(markdownContent(mocks.sendCardToChat.mock.calls[0][1])).toBe(- messages.streaming.deliveryFailed,- );- expect(markdownContent(mocks.sendCardToChat.mock.calls[0][1])).not.toBe(- messages.streaming.emptyReply,- );- expect(mocks.sendFileToChat).not.toHaveBeenCalled();- });-- it('does not claim delivery when a file-only mirror path is unavailable', async () => {- const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-file-missing-'));- tempDirs.push(root);- const missingFile = path.join(root, 'missing.txt');- await mirrorFinal(- 'oc_group',- 'p'.repeat(64),- `[missing.txt](xdt-file://${missingFile})`,- [],- [root],- 1,- );-- expect(mocks.sendFileToChat).not.toHaveBeenCalled();- expect(markdownContent(mocks.sendCardToChat.mock.calls[0][1])).toBe(- messages.streaming.deliveryFailed,- );- });-- it('does not claim delivery for a file-only mirror outside allowed roots', async () => {- const allowedRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-file-allowed-'));- const outsideRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-file-outside-'));- tempDirs.push(allowedRoot, outsideRoot);- const outsideFile = path.join(outsideRoot, 'secret.txt');- await fs.writeFile(outsideFile, 'secret');- await mirrorFinal(- 'oc_group',- 's'.repeat(64),- `[secret.txt](xdt-file://${outsideFile})`,- [],- [allowedRoot],- 1,- );-- expect(mocks.sendFileToChat).not.toHaveBeenCalled();- expect(markdownContent(mocks.sendCardToChat.mock.calls[0][1])).toBe(- messages.streaming.deliveryFailed,- );- });-- it('preserves source indexes when only some primary uploads can be mirrored', async () => {- const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-file-partial-'));- tempDirs.push(root);- const firstFile = path.join(root, 'first.txt');- const secondFile = path.join(root, 'second.txt');- await Promise.all([fs.writeFile(firstFile, 'first'), fs.writeFile(secondFile, 'second')]);- mocks.sendFile.mockImplementation(async (_userId: string, absPath: string) =>- absPath === firstFile- ? { ok: false, reason: 'UPLOAD_FAIL' }- : {- ok: true,- messageId: 'om_second',- reusableMessage: {- msgType: 'file',- content: JSON.stringify({ file_key: 'second-key' }),- },- uploadedSource: fileSourceFromPath(secondFile),- },- );- const handle = await start('g/oc_group/omt_topic');-- await handle.finalize(- `[first.txt](xdt-file://${firstFile})\n[second.txt](xdt-file://${secondFile})`,- terminalMirror('q'.repeat(64), [root], pinRoot(root)),- );-- expect(mocks.sendFileToChat).toHaveBeenCalledOnce();- expect(mocks.sendFileToChat).toHaveBeenCalledWith(- 'oc_group',- {- msgType: 'file',- content: JSON.stringify({ file_key: 'second-key' }),- },- `${'q'.repeat(32)}-f1`,- );- expect(markdownContent(mocks.sendCardToChat.mock.calls[0][1])).toBe(- messages.streaming.fileSentDone(1),- );- });-- it('does not claim delivery when a streaming file-only mirror upload is rejected', async () => {- const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-handle-file-fail-'));- tempDirs.push(root);- const file = path.join(root, 'report.txt');- await fs.writeFile(file, 'report');- mocks.sendFileToChat.mockResolvedValue({ ok: false, reason: 'upload rejected' });- const handle = await start('g/oc_group/omt_topic');-- await handle.finalize(- `[report.txt](xdt-file://${file})`,- terminalMirror('r'.repeat(64), [root], pinRoot(root)),- );-- expect(markdownContent(mocks.sendCardToChat.mock.calls[0][1])).toBe(- messages.streaming.deliveryFailed,- );- });-- it('drops a deferred parent-chat mirror after Feishu credentials rebind', async () => {- vi.mocked(waitForMirrorConfirmation).mockResolvedValueOnce(false);- let deferred: (() => void) | undefined;- vi.mocked(scheduleMirrorOnConfirmation).mockImplementation((_key, run) => {- deferred = run;- return true;- });-- await mirrorFinal('oc_group', 'k'.repeat(64), '终态正文', [], [], 1);- expect(deferred).toBeDefined();- expect(mocks.sendCardToChat).not.toHaveBeenCalled();-- mocks.getAccountEpoch.mockReturnValue(2);- mocks.getBoundClient.mockReturnValue({ pinned: false });- deferred?.();- await Promise.resolve();- await Promise.resolve();- await new Promise((resolve) => setImmediate(resolve));-- expect(mocks.sendCardToChat).not.toHaveBeenCalled();- expect(mocks.sendFileToChat).not.toHaveBeenCalled();- expect(mocks.uploadImage).not.toHaveBeenCalled();- });-- it('drops a handle-deferred parent-chat mirror after Feishu credentials rebind', async () => {- vi.mocked(waitForMirrorConfirmation).mockResolvedValueOnce(false);- let deferred: (() => void) | undefined;- vi.mocked(scheduleMirrorOnConfirmation).mockImplementation((_key, run) => {- deferred = run;- return true;- });- const handle = await start('g/oc_group/omt_topic');- await handle.finalize('话题终态', terminalMirror('l'.repeat(64)));- expect(deferred).toBeDefined();- expect(mocks.sendCardToChat).not.toHaveBeenCalled();-- mocks.getAccountEpoch.mockReturnValue(2);- mocks.getBoundClient.mockReturnValue({ pinned: false });- deferred?.();- await Promise.resolve();- await Promise.resolve();- await new Promise((resolve) => setImmediate(resolve));-- expect(mocks.sendCardToChat).not.toHaveBeenCalled();- expect(mocks.sendFileToChat).not.toHaveBeenCalled();- });-- it('drops a parent-chat mirror when credentials rebind before terminal schedule', async () => {- mocks.getAccountEpoch.mockReturnValue(2);- mocks.getBoundClient.mockReturnValue({ pinned: false });-- await mirrorFinal('oc_group', 'm'.repeat(64), '终态正文', [], [], 1);-- expect(mocks.sendCardToChat).not.toHaveBeenCalled();- expect(mocks.sendFileToChat).not.toHaveBeenCalled();- expect(waitForMirrorConfirmation).not.toHaveBeenCalled();- expect(scheduleMirrorOnConfirmation).not.toHaveBeenCalled();- });-- it('drops a handle parent-chat mirror when credentials rebind before finalize', async () => {- const handle = await start('g/oc_group/omt_topic');- mocks.getAccountEpoch.mockReturnValue(2);- mocks.getBoundClient.mockReturnValue({ pinned: false });- await handle.finalize('话题终态', terminalMirror('n'.repeat(64)));-- expect(mocks.patchCardRaw).toHaveBeenCalled();- expect(mocks.sendCardToChat).not.toHaveBeenCalled();- expect(scheduleMirrorOnConfirmation).not.toHaveBeenCalled();- });-- it('does not parent-chat mirror a pre-interaction finalize without a terminal mirror', async () => {- const handle = await start('g/oc_group/omt_topic');- await handle.finalize('话题终态');-- expect(mocks.patchCardRaw).toHaveBeenCalled();- expect(mocks.sendCardToChat).not.toHaveBeenCalled();- });-- it('catches late-confirmation one-shot mirror failures instead of unhandledRejection', async () => {- vi.mocked(waitForMirrorConfirmation).mockResolvedValueOnce(false);- let deferred: (() => void) | undefined;- vi.mocked(scheduleMirrorOnConfirmation).mockImplementation((_key, run) => {- deferred = run;- return true;- });- mocks.sendCardToChat.mockRejectedValueOnce(new Error('group unavailable'));-- const rejections: unknown[] = [];- const onUnhandled = (reason: unknown) => {- rejections.push(reason);- };- process.on('unhandledRejection', onUnhandled);- try {- await mirrorFinal('oc_group', 'f'.repeat(64), '早期拒绝终态', [], [], 1);- expect(deferred).toBeDefined();- deferred?.();- await Promise.resolve();- await Promise.resolve();- await new Promise((resolve) => setImmediate(resolve));- expect(rejections).toEqual([]);- expect(mocks.sendCardToChat).toHaveBeenCalled();- } finally {- process.off('unhandledRejection', onUnhandled);- }- });-- it('does not copy parent-chat files outside allowedFileRoots', async () => {- const handle = await start('g/oc_group/omt_topic');- await handle.finalize(- `见 [secret](xdt-file://${path.join(os.tmpdir(), 'cindy-secret.txt')})`,- terminalMirror('d'.repeat(64), [- path.join(os.tmpdir(), 'cindy-feishu-allowed-missing'),- ]),- );-- expect(mocks.sendCardToChat).toHaveBeenCalled();- expect(mocks.sendFileToChat).not.toHaveBeenCalled();- });-- it('does not copy parent-chat files after the allowed root path is replaced with an outside symlink', async () => {- const allowedRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-pin-allowed-'));- const secretRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-pin-secret-'));- tempDirs.push(secretRoot);- await fs.writeFile(path.join(allowedRoot, 'report.txt'), 'ok');- await fs.writeFile(path.join(secretRoot, 'secret.txt'), 'secret');- const pinnedFileRoots = pinRoot(allowedRoot);- await fs.rm(allowedRoot, { recursive: true, force: true });- try {- await fs.symlink(secretRoot, allowedRoot);- } catch {- return;- }- tempDirs.push(allowedRoot);- const handle = await start('g/oc_group/omt_topic');-- await handle.finalize(- `见 [secret](xdt-file://${path.join(allowedRoot, 'secret.txt')})`,- terminalMirror('w'.repeat(64), [allowedRoot], pinnedFileRoots),- );-- expect(mocks.sendFile).toHaveBeenCalled();- expect(mocks.sendFileToChat).not.toHaveBeenCalled();- });-- it('does not copy a parent-chat file whose real path escapes allowedFileRoots via symlink', async () => {- const allowedRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-symlink-allowed-'));- const secretRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-symlink-secret-'));- tempDirs.push(allowedRoot, secretRoot);- const secretFile = path.join(secretRoot, 'secret.txt');- await fs.writeFile(secretFile, 'secret');- const link = path.join(allowedRoot, 'link.txt');- try {- await fs.symlink(secretFile, link);- } catch (error) {- if ((error as NodeJS.ErrnoException).code === 'EPERM') return;- throw error;- }- const handle = await start('g/oc_group/omt_topic');-- await handle.finalize(- `见 [secret](xdt-file://${link})`,- terminalMirror('y'.repeat(64), [allowedRoot]),- );-- expect(mocks.sendFile).toHaveBeenCalled();- expect(mocks.sendFileToChat).not.toHaveBeenCalled();- });-- it('does not reuse a file_key when stuffed ancestors claim the pinned root', async () => {- const allowedRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-stuffed-allowed-'));- const outsideRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-stuffed-outside-'));- tempDirs.push(allowedRoot, outsideRoot);- const secret = path.join(outsideRoot, 'secret.txt');- await fs.writeFile(secret, 'secret');- await fs.writeFile(path.join(allowedRoot, 'report.txt'), 'ok');- const secretReal = fsSync.realpathSync.native(secret);- const secretStat = fsSync.statSync(secretReal, { bigint: true });- const pinned = pinRoot(allowedRoot);- mocks.sendFile.mockResolvedValue({- ok: true,- messageId: 'om_primary_file',- reusableMessage: {- msgType: 'file',- content: JSON.stringify({ file_key: 'file-key' }),- },- uploadedSource: {- realPath: secretReal,- dev: String(secretStat.dev),- ino: String(secretStat.ino),- ancestors: pinned,- },- });- const handle = await start('g/oc_group/omt_topic');-- await handle.finalize(- `见 [secret](xdt-file://${secret})`,- terminalMirror('s'.repeat(64), [allowedRoot], pinned),- );-- expect(mocks.sendFile).toHaveBeenCalled();- expect(mocks.sendFileToChat).not.toHaveBeenCalled();- });-- it('does not reuse a file_key when a parent is swapped onto the pinned root after upload', async () => {- const allowedRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-swap-allowed-'));- const outsideRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-swap-outside-'));- tempDirs.push(allowedRoot, outsideRoot);- const secret = path.join(outsideRoot, 'secret.txt');- await fs.writeFile(secret, 'secret');- await fs.writeFile(path.join(allowedRoot, 'decoy.txt'), 'decoy');- const secretReal = fsSync.realpathSync.native(secret);- const secretStat = fsSync.statSync(secretReal, { bigint: true });- const pinned = pinRoot(allowedRoot);- mocks.sendFile.mockResolvedValue({- ok: true,- messageId: 'om_primary_file',- reusableMessage: {- msgType: 'file',- content: JSON.stringify({ file_key: 'file-key' }),- },- uploadedSource: {- realPath: secretReal,- dev: String(secretStat.dev),- ino: String(secretStat.ino),- ancestors: ancestorInodes(secretReal),- },- });-- const realStat = fsSync.statSync.bind(fsSync);- const spy = vi.spyOn(fsSync, 'statSync').mockImplementation(((- file: unknown,- options?: unknown,- ) => {- const target = typeof file === 'string' ? file : String(file);- if (target === secretReal) {- const leaf = realStat(file as Parameters<typeof realStat>[0], options as Parameters<typeof realStat>[1]);- try {- fsSync.rmSync(outsideRoot, { recursive: true, force: true });- fsSync.symlinkSync(allowedRoot, outsideRoot);- } catch {- /* already swapped */- }- return leaf;- }- return realStat(file as Parameters<typeof realStat>[0], options as Parameters<typeof realStat>[1]);- }) as typeof fsSync.statSync);-- try {- const handle = await start('g/oc_group/omt_topic');- await handle.finalize(- `见 [secret](xdt-file://${secret})`,- terminalMirror('v'.repeat(64), [allowedRoot], pinned),- );- expect(mocks.sendFile).toHaveBeenCalled();- expect(mocks.sendFileToChat).not.toHaveBeenCalled();- } finally {- spy.mockRestore();- }- });-- it('binds the uploaded leaf and pinned root through one descriptor-relative object chain', async () => {- const base = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-chain-race-'));- tempDirs.push(base);- const allowedRoot = path.join(base, 'allowed');- const outsideRoot = path.join(base, 'outside');- const parkedAllowed = path.join(base, 'parked-allowed');- await Promise.all([fs.mkdir(allowedRoot), fs.mkdir(outsideRoot)]);- await Promise.all([- fs.writeFile(path.join(allowedRoot, 'secret.txt'), 'decoy'),- fs.writeFile(path.join(outsideRoot, 'secret.txt'), 'secret'),- ]);- const pinned = pinRoot(allowedRoot);-- await fs.rename(allowedRoot, parkedAllowed);- await fs.rename(outsideRoot, allowedRoot);- const apparentSource = path.join(allowedRoot, 'secret.txt');- const uploadedSource = fileSourceFromPath(apparentSource);- mocks.sendFile.mockResolvedValue({- ok: true,- messageId: 'om_primary_file',- reusableMessage: {- msgType: 'file',- content: JSON.stringify({ file_key: 'file-key' }),- },- uploadedSource,- });- const actualOutbound = await vi.importActual<typeof import('../outbound.js')>('../outbound.js');- mocks.attestOpenFileWithinDirectory.mockImplementation(- actualOutbound.attestOpenFileWithinDirectory,- );-- const realOpen = fsSync.openSync.bind(fsSync);- let swapAttempted = false;- let swapCompleted = false;- const spyOpen = vi.spyOn(fsSync, 'openSync').mockImplementation(((- file: unknown,- flags: unknown,- mode?: unknown,- ) => {- const fd = realOpen(- file as Parameters<typeof fsSync.openSync>[0],- flags as Parameters<typeof fsSync.openSync>[1],- mode as Parameters<typeof fsSync.openSync>[2],- );- if (!swapAttempted && String(file) === uploadedSource.realPath) {- swapAttempted = true;- try {- fsSync.renameSync(allowedRoot, outsideRoot);- fsSync.renameSync(parkedAllowed, allowedRoot);- swapCompleted = true;- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'EPERM') throw error;- // Windows locks the parent while the leaf handle is open. That is- // already fail-closed; the direct helper test covers mismatched live- // root/source handles on Windows.- }- }- return fd;- }) as typeof fsSync.openSync);-- try {- const handle = await start('g/oc_group/omt_topic');- await handle.finalize(- `见 [secret](xdt-file://${apparentSource})`,- terminalMirror('o'.repeat(64), [allowedRoot], pinned),- );- expect(swapAttempted).toBe(true);- expect(mocks.attestOpenFileWithinDirectory).toHaveBeenCalledTimes(swapCompleted ? 1 : 0);- expect(mocks.sendFileToChat).not.toHaveBeenCalled();- } finally {- spyOpen.mockRestore();- }- });-- it('does not reuse a file_key when live root realpath and inode come from different lookups', async () => {- const allowedRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-root-bind-allowed-'));- const outsideRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-root-bind-outside-'));- tempDirs.push(allowedRoot, outsideRoot);- await fs.writeFile(path.join(allowedRoot, 'report.txt'), 'ok');- const secret = path.join(outsideRoot, 'secret.txt');- await fs.writeFile(secret, 'secret');- const secretReal = fsSync.realpathSync.native(secret);- const secretStat = fsSync.statSync(secretReal, { bigint: true });- const pinned = pinRoot(allowedRoot);- const outsideReal = fsSync.realpathSync.native(outsideRoot);- const allowedReal = fsSync.realpathSync.native(allowedRoot);- mocks.sendFile.mockResolvedValue({- ok: true,- messageId: 'om_primary_file',- reusableMessage: {- msgType: 'file',- content: JSON.stringify({ file_key: 'file-key' }),- },- uploadedSource: {- realPath: secretReal,- dev: String(secretStat.dev),- ino: String(secretStat.ino),- ancestors: pinned,- },- });-- const realRealpath = fsSync.realpathSync.native.bind(fsSync.realpathSync);- const realStat = fsSync.statSync.bind(fsSync);- const pinStat = fsSync.statSync(allowedReal, { bigint: true });- const rootNames = new Set([allowedRoot, allowedReal]);- const outsideNames = new Set([outsideRoot, outsideReal]);- const spyRealpath = vi.spyOn(fsSync.realpathSync, 'native').mockImplementation(((- file: unknown,- options?: unknown,- ) => {- const target = String(file);- if (rootNames.has(target)) return outsideReal;- return realRealpath(- file as Parameters<typeof realRealpath>[0],- options as Parameters<typeof realRealpath>[1],- );- }) as typeof fsSync.realpathSync.native);- const spyStat = vi.spyOn(fsSync, 'statSync').mockImplementation(((- file: unknown,- options?: unknown,- ) => {- const target = String(file);- if (outsideNames.has(target)) return pinStat;- return realStat(- file as Parameters<typeof realStat>[0],- options as Parameters<typeof realStat>[1],- );- }) as typeof fsSync.statSync);-- try {- const handle = await start('g/oc_group/omt_topic');- await handle.finalize(- `见 [secret](xdt-file://${secret})`,- terminalMirror('b'.repeat(64), [allowedRoot], pinned),- );- expect(mocks.sendFile).toHaveBeenCalled();- expect(mocks.sendFileToChat).not.toHaveBeenCalled();- } finally {- spyRealpath.mockRestore();- spyStat.mockRestore();- }- });-- it('does not reuse a file_key when the attested path no longer names the uploaded inode', async () => {- const allowedRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-leaf-allowed-'));- const secretRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-leaf-secret-'));- tempDirs.push(allowedRoot, secretRoot);- const decoy = path.join(allowedRoot, 'report.txt');- const secret = path.join(secretRoot, 'secret.txt');- await Promise.all([fs.writeFile(decoy, 'decoy'), fs.writeFile(secret, 'secret')]);- const secretStat = fsSync.statSync(secret, { bigint: true });- const decoyReal = fsSync.realpathSync.native(decoy);- mocks.sendFile.mockResolvedValue({- ok: true,- messageId: 'om_primary_file',- reusableMessage: {- msgType: 'file',- content: JSON.stringify({ file_key: 'file-key' }),- },- uploadedSource: {- realPath: decoyReal,- dev: String(secretStat.dev),- ino: String(secretStat.ino),- ancestors: ancestorInodes(fsSync.realpathSync.native(secret)),- },- });- const handle = await start('g/oc_group/omt_topic');-- await handle.finalize(- `见 [report.txt](xdt-file://${decoy})`,- terminalMirror('x'.repeat(64), [allowedRoot]),- );-- expect(mocks.sendFile).toHaveBeenCalled();- expect(mocks.sendFileToChat).not.toHaveBeenCalled();- });-- it('does not collapse distinct 64-bit inode identities through number precision', async () => {- const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-bigint-inode-'));- tempDirs.push(root);- const allowedFile = path.join(root, 'report.txt');- await fs.writeFile(allowedFile, 'report');- const realPath = fsSync.realpathSync.native(allowedFile);- const actual = fsSync.statSync(realPath, { bigint: true });- const uploadedIno = 2n ** 60n;- const differentIno = uploadedIno + 1n;- expect(Number(uploadedIno)).toBe(Number(differentIno));- mocks.sendFile.mockResolvedValue({- ok: true,- messageId: 'om_primary_file',- reusableMessage: {- msgType: 'file',- content: JSON.stringify({ file_key: 'file-key' }),- },- uploadedSource: {- realPath,- dev: String(actual.dev),- ino: String(uploadedIno),- ancestors: [],- },- });-- const realStat = fsSync.statSync.bind(fsSync);- const spy = vi.spyOn(fsSync, 'statSync').mockImplementation(((- file: unknown,- options?: unknown,- ) => {- if (String(file) === realPath && (options as { bigint?: boolean } | undefined)?.bigint) {- return { dev: actual.dev, ino: differentIno } as never;- }- return realStat(- file as Parameters<typeof realStat>[0],- options as Parameters<typeof realStat>[1],- );- }) as typeof fsSync.statSync);-- try {- const handle = await start('g/oc_group/omt_topic');- await handle.finalize(- `瑙?[report.txt](xdt-file://${allowedFile})`,- terminalMirror('q'.repeat(64), [root], pinRoot(root)),- );- expect(mocks.sendFileToChat).not.toHaveBeenCalled();- } finally {- spy.mockRestore();- }- });-- it('does not reuse a file_key when uploaded inode identity is zero', async () => {- const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-zero-ino-'));- tempDirs.push(root);- const allowedFile = path.join(root, 'report.txt');- await fs.writeFile(allowedFile, 'report');- const realPath = fsSync.realpathSync.native(allowedFile);- mocks.sendFile.mockResolvedValue({- ok: true,- messageId: 'om_primary_file',- reusableMessage: {- msgType: 'file',- content: JSON.stringify({ file_key: 'file-key' }),- },- uploadedSource: {- realPath,- dev: '1',- ino: '0',- ancestors: ancestorInodes(realPath),- },- });- const handle = await start('g/oc_group/omt_topic');-- await handle.finalize(- `见 [report.txt](xdt-file://${allowedFile})`,- terminalMirror('w'.repeat(64), [root], [{ dev: '1', ino: '0' }]),- );-- expect(mocks.sendFile).toHaveBeenCalled();- expect(mocks.sendFileToChat).not.toHaveBeenCalled();- });-- it('does not probe a mutable case alias during terminal containment', async () => {- const allowedRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-cs-allowed-'));- const outsideRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-cs-outside-'));- tempDirs.push(allowedRoot, outsideRoot);- await fs.writeFile(path.join(allowedRoot, 'report.txt'), 'ok');- const secret = path.join(outsideRoot, 'secret.txt');- await fs.writeFile(secret, 'secret');- const rootReal = fsSync.realpathSync.native(allowedRoot);- const flippedRoot = flipPathCase(rootReal);- if (flippedRoot === rootReal) return;- const collidingPath = path.join(flippedRoot, 'outside.txt');- const secretStat = fsSync.statSync(secret, { bigint: true });- const pinned = pinRoot(allowedRoot);- mocks.sendFile.mockResolvedValue({- ok: true,- messageId: 'om_primary_file',- reusableMessage: {- msgType: 'file',- content: JSON.stringify({ file_key: 'file-key' }),- },- uploadedSource: {- realPath: collidingPath,- dev: String(secretStat.dev),- ino: String(secretStat.ino),- ancestors: pinned,- },- });-- const realRealpath = fsSync.realpathSync.native.bind(fsSync.realpathSync);- const realStat = fsSync.statSync.bind(fsSync);- const spyRealpath = vi.spyOn(fsSync.realpathSync, 'native').mockImplementation(((- file: unknown,- options?: unknown,- ) => {- if (String(file) === collidingPath) return collidingPath;- return realRealpath(- file as Parameters<typeof realRealpath>[0],- options as Parameters<typeof realRealpath>[1],- );- }) as typeof fsSync.realpathSync.native);- const spyStat = vi.spyOn(fsSync, 'statSync').mockImplementation(((- file: unknown,- options?: unknown,- ) => {- const target = String(file);- if (target === collidingPath) return secretStat;- return realStat(- file as Parameters<typeof realStat>[0],- options as Parameters<typeof realStat>[1],- );- }) as typeof fsSync.statSync);-- try {- const handle = await start('g/oc_group/omt_topic');- await handle.finalize(- `见 [secret](xdt-file://${collidingPath})`,- terminalMirror('c'.repeat(64), [allowedRoot], pinned),- );- expect(mocks.sendFile).toHaveBeenCalled();- expect(mocks.sendFileToChat).not.toHaveBeenCalled();- expect(spyStat.mock.calls.some(([file]) => String(file) === flippedRoot)).toBe(false);- } finally {- spyRealpath.mockRestore();- spyStat.mockRestore();- }- });-- it('copies parent-chat files when the allowed root uses host filesystem case', async () => {- const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-case-'));- tempDirs.push(root);- const allowedFile = path.join(root, 'Report.txt');- await fs.writeFile(allowedFile, 'report');- const flipped = flipPathCase(root);- if (flipped === root) return;- try {- await fs.access(flipped);- } catch {- return;- }- const handle = await start('g/oc_group/omt_topic');- await handle.finalize(- `见 [Report.txt](xdt-file://${allowedFile})`,- terminalMirror('z'.repeat(64), [flipped], pinRoot(flipped)),- );-- expect(mocks.sendFileToChat).toHaveBeenCalledWith(- 'oc_group',- {- msgType: 'file',- content: JSON.stringify({ file_key: 'file-key' }),- },- `${'z'.repeat(32)}-f0`,- );- });-- it('copies parent-chat files that stay inside allowedFileRoots', async () => {- const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-allowed-'));- tempDirs.push(root);- const allowedFile = path.join(root, 'report.txt');- await fs.writeFile(allowedFile, 'report');- const actualOutbound = await vi.importActual<typeof import('../outbound.js')>('../outbound.js');- mocks.attestedRealPath.mockImplementation(actualOutbound.attestedRealPath);- mocks.attestOpenFileWithinDirectory.mockImplementation(- actualOutbound.attestOpenFileWithinDirectory,- );- const identityOnlyPin = pinRoot(root).map(({ dev, ino }) => ({ dev, ino }));- const handle = await start('g/oc_group/omt_topic');- await handle.finalize(- `见 [report.txt](xdt-file://${allowedFile})`,- terminalMirror('e'.repeat(64), [root], identityOnlyPin),- );-- expect(mocks.sendFileToChat).toHaveBeenCalledWith(- 'oc_group',- {- msgType: 'file',- content: JSON.stringify({ file_key: 'file-key' }),- },- `${'e'.repeat(32)}-f0`,- );- });-- it('copies parent-chat files when the mirror is supplied only at terminal finalize', async () => {- const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-armed-'));- tempDirs.push(root);- const allowedFile = path.join(root, 'report.txt');- await fs.writeFile(allowedFile, 'report');- const handle = await start('g/oc_group/omt_topic');- await handle.finalize(- `见 [report.txt](xdt-file://${allowedFile})`,- terminalMirror('r'.repeat(64), [root], pinRoot(root)),- );-- expect(mocks.sendFileToChat).toHaveBeenCalledWith(- 'oc_group',- {- msgType: 'file',- content: JSON.stringify({ file_key: 'file-key' }),- },- `${'r'.repeat(32)}-f0`,- );+ expect(markdownContent(mocks.patchCardRaw.mock.calls[0][1])).toContain('终态正文');});});diff --git a/packages/lizi-im/src/feishu/__tests__/wsClientGroupThreadRouting.test.ts b/packages/lizi-im/src/feishu/__tests__/wsClientGroupThreadRouting.test.tsindex b85592f1ab..2fa1bd2bff 100644--- a/packages/lizi-im/src/feishu/__tests__/wsClientGroupThreadRouting.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/wsClientGroupThreadRouting.test.ts@@ -296,13 +296,6 @@ describe('feishu group thread routing', () => {expect(events).toHaveLength(1);expect(events[0].senderId).toBe('g/oc_chat1/omt_existing');- expect(events[0].finalReplyMirror).toEqual({- kind: 'parent-chat',- chatId: 'oc_chat1',- idempotencyKey: expect.any(String),- accountEpoch: 1,- confirmed: true,- });expect(mocks.openThread).not.toHaveBeenCalled();});@@ -578,13 +571,6 @@ describe('feishu group thread routing', () => {expect(events).toHaveLength(1);expect(events[0].senderId).toBe('g/oc_chat1/omt_existing');- expect(events[0].finalReplyMirror).toEqual({- kind: 'parent-chat',- chatId: 'oc_chat1',- idempotencyKey: expect.any(String),- accountEpoch: 1,- confirmed: true,- });expect(mocks.openThread).toHaveBeenCalledTimes(1);expect(mocks.recallOwnMessage).toHaveBeenCalledWith('om_bot_opener');expect(mocks.pushPatchableOpener).not.toHaveBeenCalled();@@ -727,12 +713,6 @@ describe('feishu group thread routing', () => {expect(events).toHaveLength(1);expect(events[0]?.senderId).toBe('g/oc_chat1/omt_bot_committed');- expect(events[0]?.finalReplyMirror).toEqual({- kind: 'parent-chat',- chatId: 'oc_chat1',- idempotencyKey: expect.any(String),- accountEpoch: 1,- });expect(mocks.openThread).toHaveBeenCalledTimes(1);expect(mocks.pushPatchableOpener).toHaveBeenCalledWith('g/oc_chat1/omt_bot_committed',@@ -779,12 +759,6 @@ describe('feishu group thread routing', () => {expect(events).toHaveLength(1);expect(events[0]?.senderId).toBe('g/oc_chat1/omt_bot_recovered_committed');- expect(events[0]?.finalReplyMirror).toEqual({- kind: 'parent-chat',- chatId: 'oc_chat1',- idempotencyKey: expect.any(String),- accountEpoch: 1,- });await mocks.eventHandlers['im.message.receive_v1'](topic);@@ -823,13 +797,6 @@ describe('feishu group thread routing', () => {expect(events).toHaveLength(1);expect(events[0]?.senderId).toBe('g/oc_chat1/omt_existing');expect(events[0]?.messageId).toBe('om_topic_after_orphan');- expect(events[0]?.finalReplyMirror).toEqual({- kind: 'parent-chat',- chatId: 'oc_chat1',- idempotencyKey: expect.any(String),- accountEpoch: 1,- confirmed: true,- });expect(mocks.pushPatchableOpener).not.toHaveBeenCalled();});@@ -866,13 +833,6 @@ describe('feishu group thread routing', () => {expect(events).toHaveLength(1);expect(events[0]?.senderId).toBe('g/oc_chat1/omt_existing');expect(events[0]?.messageId).toBe('om_topic_after_unconfirmed');- expect(events[0]?.finalReplyMirror).toEqual({- kind: 'parent-chat',- chatId: 'oc_chat1',- idempotencyKey: expect.any(String),- accountEpoch: 1,- confirmed: true,- });expect(mocks.pushPatchableOpener).not.toHaveBeenCalled();await vi.advanceTimersByTimeAsync(10_000);@@ -1198,13 +1158,6 @@ describe('feishu group thread routing', () => {expect(events).toHaveLength(1);expect(events[0]?.senderId).toBe('g/oc_chat1/omt_existing');- expect(events[0]?.finalReplyMirror).toEqual({- kind: 'parent-chat',- chatId: 'oc_chat1',- idempotencyKey: expect.any(String),- accountEpoch: 1,- confirmed: true,- });vi.useRealTimers();});});diff --git a/packages/lizi-im/src/feishu/dualDelivery.ts b/packages/lizi-im/src/feishu/dualDelivery.tsindex 9952898b9a..0f45e0d148 100644--- a/packages/lizi-im/src/feishu/dualDelivery.ts+++ b/packages/lizi-im/src/feishu/dualDelivery.ts@@ -5,8 +5,9 @@ import { createHash } from 'node:crypto';* two `im.message.receive_v1` events: a topic message and a main-feed copy.* They have different message ids but retain the same sender/chat/create-time,* message type, and raw content. This coordinator elects the topic event as the- * only Agent route and records that its terminal answer needs a parent-chat- * mirror.+ * only Agent route and suppresses the main-feed copy so it cannot open a second+ * turn. Cindy does not copy the bot reply to the parent group: Feishu never+ * exposes the checkbox on the inbound event.*/const PAIR_WINDOW_MS = 1_000;@@ -39,13 +40,6 @@ export interface DualDeliveryInput {export type DualDeliveryDecision =| {kind: 'dispatch';- mirrorKey?: string;- /**- * Pairing was already confirmed when this topic/takeover dispatched.- * Terminal mirrors must not wait on a confirmation map that can be TTL- * or capacity pruned during a long Agent turn.- */- alreadyConfirmed?: boolean;/*** Unpaired main-feed copies call this after `openThread` returns, and* only when the copy is actually about to emit an Agent turn.@@ -81,25 +75,6 @@ const recentThreads = new Map<string, number>();const recentFlats = new Map<string, RecentFlatRecord>();const topicLeases = new Map<string, RecentFlatRecord>();const confirmed = new Map<string, number>();-const deferredMirrors = new Map<string, Array<() => void>>();-/** Confirmation records retained until the elected Agent turn reaches a terminal mirror path. */-const liveMirrorConfirmations = new Set<string>();--export function retainMirrorConfirmation(key: string): void {- liveMirrorConfirmations.add(key);-}--export function releaseMirrorConfirmation(key: string): void {- if (!liveMirrorConfirmations.delete(key)) return;- if (!confirmed.has(key)) return;- const now = Date.now();- // A duplicate can arrive after a very long Agent turn. Once the live pin is- // released, restart the ordinary suppression TTL from the terminal instead- // of immediately pruning the old pair timestamp.- confirmed.delete(key);- confirmed.set(key, now);- pruneConfirmed(now);-}function logicalSendKey(input: DualDeliveryInput): string | null {if (!input.createTime) return null;@@ -118,17 +93,10 @@ function logicalSendKey(input: DualDeliveryInput): string | null {.digest('hex');}-function dropDeferredMirrors(key: string): void {- if (!deferredMirrors.delete(key)) return;- // Dropped callbacks never run, so their `.finally(release)` cannot fire.- releaseMirrorConfirmation(key);-}-function pruneTtlMap(map: Map<string, number>, now: number): void {for (const [key, ts] of map) {if (now - ts <= LATE_COPY_TTL_MS && map.size <= MAX_RECENT) break;map.delete(key);- dropDeferredMirrors(key);}}@@ -147,7 +115,6 @@ function pruneRecentFlats(now: number): void {if (rec.state === 'pending') continue;if (now - rec.ts > LATE_COPY_TTL_MS) {recentFlats.delete(key);- dropDeferredMirrors(key);}}if (recentFlats.size <= MAX_RECENT) return;@@ -155,7 +122,6 @@ function pruneRecentFlats(now: number): void {if (recentFlats.size <= MAX_RECENT) break;if (rec.state === 'pending') continue;recentFlats.delete(key);- dropDeferredMirrors(key);}}@@ -255,39 +221,20 @@ function abandonUnpairedFlatRoute(key: string, rec: RecentFlatRecord): void {recentFlats.set(key, rec);pruneRecentFlats(rec.ts);}- dropDeferredMirrors(key);- releaseMirrorConfirmation(key);-}--function flushDeferredMirrors(key: string): void {- const scheduled = deferredMirrors.get(key);- deferredMirrors.delete(key);- if (scheduled) releaseMirrorConfirmation(key);- for (const run of scheduled ?? []) {- try {- run();- } catch {- /* best-effort; caller logs inside the scheduled work */- }- }}function pruneConfirmed(now: number): void {for (const [key, ts] of confirmed) {if (now - ts <= CONFIRMED_TTL_MS && confirmed.size <= MAX_CONFIRMED) break;- if (liveMirrorConfirmations.has(key)) continue;confirmed.delete(key);}}-function dispatchWithMirror(- key: string,- extra: Omit<Extract<DualDeliveryDecision, { kind: 'dispatch' }>, 'kind' | 'mirrorKey' | 'alreadyConfirmed'> = {},+function dispatchRoute(+ extra: Omit<Extract<DualDeliveryDecision, { kind: 'dispatch' }>, 'kind'> = {},): DualDeliveryDecision {return {kind: 'dispatch',- mirrorKey: key,- ...(confirmed.has(key) ? { alreadyConfirmed: true } : {}),...extra,};}@@ -337,7 +284,6 @@ function confirmLogicalSend(key: string, now: number): void {confirmed.delete(key);confirmed.set(key, now);pruneConfirmed(now);- flushDeferredMirrors(key);}function confirmPair(key: string, entry: PendingLogicalSend): void {@@ -371,7 +317,7 @@ export async function coordinateDualDelivery(if (input.threadId) {const lease = topicLeases.get(key);if (lease?.state === 'pending') {- return dispatchWithMirror(key, topicRouteCallbacks(key, lease));+ return dispatchRoute(topicRouteCallbacks(key, lease));}}return { kind: 'suppress-main-copy' };@@ -397,7 +343,7 @@ export async function coordinateDualDelivery(recentFlats.set(key, recentFlat);confirmLogicalSend(key, now);rememberRecent(recentThreads, key, now);- return dispatchWithMirror(key, topicRouteCallbacks(key));+ return dispatchRoute(topicRouteCallbacks(key));}if (!input.threadId && recentFlat) {if (recentFlat.state === 'abandoned') {@@ -420,7 +366,7 @@ export async function coordinateDualDelivery(// copy that arrived first is already parked on `entry.decision`; a later// flat copy is suppressed through `recentThreads`. A late topic after an// unpaired flat takes over unless that flat has already committed.- return dispatchWithMirror(key, topicRouteCallbacks(key));+ return dispatchRoute(topicRouteCallbacks(key));}entry.flatMessageIds.add(input.messageId);@@ -435,65 +381,12 @@ export async function coordinateDualDelivery(}const lease = entry.flatLease;return lease- ? dispatchWithMirror(key, {+ ? dispatchRoute({commitUnpairedFlat: () => commitUnpairedFlatRoute(key, lease),isUnpairedFlatTakenOver: () => isUnpairedFlatTakenOver(lease),abandonUnpairedFlat: () => abandonUnpairedFlatRoute(key, lease),})- : dispatchWithMirror(key);-}--/** Waits only for the bounded pairing window; Agent execution itself is never delayed. */-export async function waitForMirrorConfirmation(mirrorKey: string): Promise<boolean> {- pruneConfirmed(Date.now());- if (confirmed.has(mirrorKey)) {- releaseMirrorConfirmation(mirrorKey);- return true;- }- const entry = pending.get(mirrorKey);- if (!entry) return false;- const isConfirmed = await entry.decision;- if (isConfirmed) releaseMirrorConfirmation(mirrorKey);- return isConfirmed;-}--/**- * Run `send` if this logical send is already confirmed, or when a late pair- * (main-feed copy or committed-flat topic) confirms it inside the late-copy TTL.- * No-ops once that window has expired.- *- * @returns whether `send` ran immediately or was queued for a later confirmation.- */-export function scheduleMirrorOnConfirmation(mirrorKey: string, send: () => void): boolean {- const now = Date.now();- pruneConfirmed(now);- pruneTtlMap(recentThreads, now);- pruneRecentFlats(now);- if (confirmed.has(mirrorKey)) {- releaseMirrorConfirmation(mirrorKey);- send();- return true;- }- if (- !pending.has(mirrorKey) &&- !recentThreads.has(mirrorKey) &&- !recentFlats.has(mirrorKey)- ) {- releaseMirrorConfirmation(mirrorKey);- return false;- }- const queued = deferredMirrors.get(mirrorKey) ?? [];- queued.push(() => {- releaseMirrorConfirmation(mirrorKey);- send();- });- deferredMirrors.set(mirrorKey, queued);- return true;-}--/** Test-only: whether terminal-mirror retain is still holding this key. */-export function isMirrorConfirmationRetainedForTest(mirrorKey: string): boolean {- return liveMirrorConfirmations.has(mirrorKey);+ : dispatchRoute();}/** Test-only: pending elected-topic leases that pruneTopicLeases will not expire. */@@ -516,6 +409,4 @@ export function resetDualDeliveryForTest(): void {recentFlats.clear();topicLeases.clear();confirmed.clear();- deferredMirrors.clear();- liveMirrorConfirmations.clear();}diff --git a/packages/lizi-im/src/feishu/index.ts b/packages/lizi-im/src/feishu/index.tsindex 294999c70e..f50dac0b43 100644--- a/packages/lizi-im/src/feishu/index.ts+++ b/packages/lizi-im/src/feishu/index.ts@@ -20,7 +20,6 @@ import type { ChannelIM } from '../channelIM.js';import type {IMHost,IMCardActionEvent,- IMFinalReplyMirror,IMMessageEvent,IMStatus,InteractiveCardSpec,@@ -36,7 +35,6 @@ import { feishuEvents } from './events.js';import { cancelAppRegistration, reconnectSavedCredentials, registerFeishuIpc } from './ipc.js';import * as outbound from './outbound.js';import * as streamingText from './streamingText.js';-import { releaseMirrorConfirmation, retainMirrorConfirmation } from './dualDelivery.js';import { downloadAttachments, type DownloadResult } from './attachmentDownloader.js';import type { AttachmentRef } from './incomingContent.js';@@ -441,36 +439,6 @@ export class FeishuIM extends BaseIM implements ChannelIM {return streamingText.start(userId, initial);}- retainFinalReplyMirror(mirror: IMFinalReplyMirror): () => void {- retainMirrorConfirmation(mirror.idempotencyKey);- return () => releaseMirrorConfirmation(mirror.idempotencyKey);- }-- async mirrorFinalReply(- mirror: IMFinalReplyMirror,- text: string,- opts?: { mediaAbsPaths?: string[] },- ): Promise<void> {- if (mirror.kind !== 'parent-chat') return;- try {- await streamingText.mirrorFinal(- mirror.chatId,- mirror.idempotencyKey,- text,- opts?.mediaAbsPaths,- mirror.allowedFileRoots,- mirror.accountEpoch,- mirror.confirmed,- );- } catch (err) {- this.log.warn(- `parent-chat terminal mirror failed (non-fatal): ${- err instanceof Error ? err.message : String(err)- }`,- );- }- }-/*** 一次性把已有 card patch 成 v2 markdown 内容。/ctr 接管路径用这个把 picker* card 转成"已接管 + 总结"视图, 替代发新消息。diff --git a/packages/lizi-im/src/feishu/streamingText.ts b/packages/lizi-im/src/feishu/streamingText.tsindex ef3e48c59a..e24b54c465 100644--- a/packages/lizi-im/src/feishu/streamingText.ts+++ b/packages/lizi-im/src/feishu/streamingText.ts@@ -24,43 +24,24 @@* `[name](xdt-file:///abs/path)`).*/-import fs from 'node:fs';-import path from 'node:path';-import {sendCardRaw,patchCardRaw,uploadImage,sendFile,- sendFileToChat,- sendCardToChat,sendText,claimPatchableOpener,- getAccountEpoch,- getBoundClient,- runWithPinnedAccount,- isPinnedAccountCurrent,- attestedRealPath,- attestOpenFileWithinDirectory,- type FeishuUploadedFileSource,- type ReusableFeishuFileMessage,} from './outbound.js';import { buildMarkdownCardV2, buildMixedMarkdownCardV2 } from './cards.js';import { resolveFeishuMediaUrl } from './mediaCache.js';import { getHost, getLog } from './moduleScope.js';-import {- releaseMirrorConfirmation,- scheduleMirrorOnConfirmation,- waitForMirrorConfirmation,-} from './dualDelivery.js';import { messages as transportMessages } from './messages.js';-import type { IMFinalReplyMirror, StreamingTextHandle } from '../types.js';+import type { StreamingTextHandle } from '../types.js';// xdt-* 引用解析抽到渠道无关模块(slack streamingText 共用同一套语义)import {stripXdtForStreaming,classifyXdtOnly,stripXdtFileLinks,- stripXdtImageLinks,collectXdtFileLinks,collectXdtImageUrls,} from '../xdtRefs.js';@@ -101,10 +82,6 @@ function fitCardToLimit(return fitted;}-function mirrorUuid(key: string, suffix: string): string {- return `${key.slice(0, 32)}-${suffix}`.slice(0, 50);-}-async function uploadExtraImageKeys(absPaths: readonly string[]): Promise<string[]> {const results = await Promise.all(absPaths.map(async (absPath) => {@@ -124,135 +101,6 @@ async function uploadExtraImageKeys(absPaths: readonly string[]): Promise<stringreturn keys;}-interface FinalCardResult {- card: unknown;- /** Parent-chat copy. Differs from `card` when local media must not be mirrored. */- mirrorCard: unknown;- reusableFiles: ReusableMirroredFile[];- fileOnly: boolean;-}--interface ReusableMirroredFile {- message: ReusableFeishuFileMessage;- sourceIndex: number;-}--function sameInode(- left: { dev: string; ino: string },- right: { dev: string; ino: string },-): boolean {- // Node reports ino===0 on some Windows volumes for every file. Matching- // that sentinel would treat unrelated objects as the same inode.- if (left.ino === '0' || right.ino === '0') return false;- return left.dev === right.dev && left.ino === right.ino;-}--function isSyntheticFdPath(resolved: string): boolean {- const normalized = resolved.replaceAll('\\', '/');- return /(?:^|\/)(?:proc\/self\/fd|dev\/fd)\/\d+$/.test(normalized);-}--function normalizePathForContainment(value: string): string {- const resolved = path.resolve(value);- if (process.platform !== 'win32') return resolved;- // Drive letter is the only OS-defined case-insensitive component. Folding the- // rest would collapse NTFS per-directory case-sensitive siblings (C:\work vs- // C:\Work) into one root.- return resolved.replace(/^([A-Za-z]):/, (_, drive: string) => `${drive.toLowerCase()}:`);-}--function pathSegmentsWithinRoot(realFilePath: string, realRoot: string): string[] | null {- const file = normalizePathForContainment(realFilePath);- const root = normalizePathForContainment(realRoot);- if (file === root) return null;- // path.win32.relative is case-insensitive even when this directory is not.- const rootWithSep = root.endsWith(path.sep) ? root : `${root}${path.sep}`;- if (!file.startsWith(rootWithSep)) return null;- const segments = file.slice(rootWithSep.length).split(path.sep);- return segments.length > 0 && segments.every((segment) => segment && segment !== '.' && segment !== '..')- ? segments- : null;-}--function openDirectoryFd(target: string, noFollow: boolean): number {- let flags = fs.constants.O_RDONLY;- if (noFollow && fs.constants.O_NOFOLLOW) flags |= fs.constants.O_NOFOLLOW;- if (fs.constants.O_DIRECTORY) flags |= fs.constants.O_DIRECTORY;- return fs.openSync(target, flags);-}--/**- * Parent-chat reuse never re-uploads disk bytes. It reopens the frozen uploaded- * inode and the turn-pinned root only to prove object ancestry: the leaf is- * opened once, the root is opened once, and the native helper walks each child- * relative to the preceding directory handle without following links. A final- * handle identity comparison binds both sides even if their lexical paths are- * swapped between checks. Missing pins/helpers fail closed.- */-async function isSourceWithinAllowedFileRoots(- source: FeishuUploadedFileSource,- allowedFileRoots: readonly string[],- pinnedFileRoots?: ReadonlyArray<{ dev: string; ino: string; realPath?: string }>,-): Promise<boolean> {- if (source.ino === '0') return false;- if (!source.realPath || isSyntheticFdPath(source.realPath)) return false;- if (!pinnedFileRoots?.length) return false;-- let sourceFd: number | undefined;- try {- let flags = fs.constants.O_RDONLY;- if (fs.constants.O_NOFOLLOW) flags |= fs.constants.O_NOFOLLOW;- if (fs.constants.O_NONBLOCK) flags |= fs.constants.O_NONBLOCK;- sourceFd = fs.openSync(source.realPath, flags);- const sourceStat = fs.fstatSync(sourceFd, { bigint: true });- if (- !sourceStat.isFile() ||- !sameInode({ dev: String(sourceStat.dev), ino: String(sourceStat.ino) }, source)- ) {- return false;- }-- for (const root of allowedFileRoots) {- if (!root.trim()) continue;- let rootFd: number | undefined;- try {- rootFd = openDirectoryFd(root, false);- const rootStat = fs.fstatSync(rootFd, { bigint: true });- if (!rootStat.isDirectory()) continue;- const rootIdentity = { dev: String(rootStat.dev), ino: String(rootStat.ino) };- const pin = pinnedFileRoots.find((candidate) => sameInode(rootIdentity, candidate));- if (!pin) continue;- const rootRealPath =- pin.realPath && !isSyntheticFdPath(pin.realPath)- ? pin.realPath- : await attestedRealPath(rootFd, rootIdentity);- if (!rootRealPath || isSyntheticFdPath(rootRealPath)) continue;- const segments = pathSegmentsWithinRoot(source.realPath, rootRealPath);- if (!segments) continue;- if (await attestOpenFileWithinDirectory(sourceFd, rootFd, segments)) return true;- } catch {- /* This root cannot prove containment. Try the next approved root. */- } finally {- if (rootFd !== undefined) fs.closeSync(rootFd);- }- }- } catch {- return false;- } finally {- if (sourceFd !== undefined) fs.closeSync(sourceFd);- }- return false;-}--async function isWithinAllowedFileRoots(- allowedFileRoots: readonly string[],- pinnedFileRoots?: ReadonlyArray<{ dev: string; ino: string; realPath?: string }>,- uploadedSource?: FeishuUploadedFileSource,-): Promise<boolean> {- if (!uploadedSource) return false;- return isSourceWithinAllowedFileRoots(uploadedSource, allowedFileRoots, pinnedFileRoots);-}-class FeishuStreamingTextHandle implements StreamingTextHandle {readonly messageId: string;private readonly openId: string;@@ -300,10 +148,7 @@ class FeishuStreamingTextHandle implements StreamingTextHandle {}, PATCH_THROTTLE_MS);}- async finalize(- finalText: string,- opts?: { finalReplyMirror?: IMFinalReplyMirror },- ): Promise<void> {+ async finalize(finalText: string): Promise<void> {if (this.finalized) return;this.finalized = true;if (this.pending) {@@ -318,14 +163,7 @@ class FeishuStreamingTextHandle implements StreamingTextHandle {}}this.buffer = finalText;- const mirror = opts?.finalReplyMirror;- try {- await this.doFinalize(mirror);- } finally {- if (mirror?.kind === 'parent-chat') {- releaseMirrorConfirmation(mirror.idempotencyKey);- }- }+ await this.doFinalize();}close(): void {@@ -382,7 +220,7 @@ class FeishuStreamingTextHandle implements StreamingTextHandle {// ── finalize: upload images, send files, patch with mixed elements ────────- private async doFinalize(finalReplyMirror?: IMFinalReplyMirror): Promise<void> {+ private async doFinalize(): Promise<void> {const log = getLog();const text = this.buffer;@@ -445,38 +283,20 @@ class FeishuStreamingTextHandle implements StreamingTextHandle {// 2. Send xdt-file links as separate file messages.const fileLinks = collectXdtFileLinks(text);- let reusableFiles: ReusableMirroredFile[] = [];if (fileLinks.length > 0) {log.debug(`[feishu/streamingText] sending ${fileLinks.length} xdt-file(s)`);- const results = await Promise.all(- fileLinks.map(async (link, sourceIndex) => {+ await Promise.all(+ fileLinks.map(async (link) => {try {- const sent = await sendFile(this.openId, link.absPath, link.alt || undefined);- // This path check only decides whether an existing Feishu upload- // key may be mirrored. It never authorizes another filesystem read.- if (- sent.ok &&- sent.reusableMessage &&- (await isWithinAllowedFileRoots(- finalReplyMirror?.allowedFileRoots ?? [],- finalReplyMirror?.pinnedFileRoots,- sent.uploadedSource,- ))- ) {- return { message: sent.reusableMessage, sourceIndex };- }+ await sendFile(this.openId, link.absPath, link.alt || undefined);} catch (err) {const msg = err instanceof Error ? err.message : String(err);log.warn(`[feishu/streamingText] sendFile ${link.absPath} failed: ${msg}`,);}- return null;}),);- reusableFiles = results.filter(- (message): message is ReusableMirroredFile => message !== null,- );}// 3. Strip xdt-file from card text (delivered separately, no placeholder).@@ -490,8 +310,6 @@ class FeishuStreamingTextHandle implements StreamingTextHandle {// d) totally empty → fallback "(空回复)"const hasAnyImage = imageUrls.length > 0 || extraImageKeys.length > 0;const fileOnly = cardTextTrimmed.length === 0 && !hasAnyImage && fileLinks.length > 0;- let primaryCardPatched = false;- let mirrorResult: FinalCardResult | null = null;try {let card: unknown;if (fileOnly) {@@ -509,47 +327,9 @@ class FeishuStreamingTextHandle implements StreamingTextHandle {? buildMixedMarkdownCardV2(visibleText, imageMap, extraImageKeys): buildMarkdownCardV2(visibleText),);- const allowLocalMedia = allowLocalMediaRoots(finalReplyMirror?.allowedFileRoots ?? []);- let mirrorCard = card;- let mirroredFiles = reusableFiles;- let mirroredFileOnly = fileOnly;- if (!allowLocalMedia) {- const skippedLocalMedia =- this.extraImageAbsPaths.length > 0 || imageUrls.length > 0 || fileLinks.length > 0;- const mirrorText = stripXdtImageLinks(stripXdtFileLinks(text)).trim();- mirroredFiles = [];- mirroredFileOnly = false;- if (skippedLocalMedia && mirrorText.length === 0) {- mirrorCard = buildMarkdownCardV2(transportMessages.streaming.deliveryFailed);- } else {- const remoteSafeText =- mirrorText.length > 0 ? mirrorText : transportMessages.streaming.emptyReply;- mirrorCard = fitCardToLimit(- remoteSafeText,- buildMarkdownCardV2(remoteSafeText),- (visibleText) => buildMarkdownCardV2(visibleText),- );- }- }- mirrorResult = {- card,- mirrorCard,- reusableFiles: mirroredFiles,- fileOnly: mirroredFileOnly,- };await patchCardRaw(this.messageId, card);- primaryCardPatched = true;this.flushed = this.buffer;- await this.sendOrScheduleMirror(mirrorResult, finalReplyMirror);} catch (err) {- if (primaryCardPatched) {- log.warn(- `[feishu/streamingText] parent-chat mirror failed after primary finalize (non-fatal): ${- err instanceof Error ? err.message : String(err)- }`,- );- return;- }const msg = err instanceof Error ? err.message : String(err);log.warn(`[feishu/streamingText] finalize patch failed: ${msg}`);const notice = transportMessages.streaming.deliveryFailed;@@ -566,70 +346,7 @@ class FeishuStreamingTextHandle implements StreamingTextHandle {log.error(`[feishu/streamingText] fallback text failed: ${textMsg}`);}}- if (mirrorResult) {- try {- await this.sendOrScheduleMirror(mirrorResult, finalReplyMirror);- } catch (mirrorErr) {- log.warn(- `[feishu/streamingText] parent-chat mirror failed after primary fallback (non-fatal): ${- mirrorErr instanceof Error ? mirrorErr.message : String(mirrorErr)- }`,- );- }- }- }- }-- private async sendOrScheduleMirror(- result: FinalCardResult,- mirror: IMFinalReplyMirror | undefined,- ): Promise<void> {- if (mirror?.kind !== 'parent-chat') return;- await sendOrScheduleMirror(- mirror.idempotencyKey,- () => this.mirrorFinalResult(result, mirror),- mirror.accountEpoch,- mirror.confirmed,- );- }-- private async mirrorFinalResult(- result: FinalCardResult,- mirror: IMFinalReplyMirror,- ): Promise<void> {- const chatId = mirror.chatId;- const key = mirror.idempotencyKey;- const log = getLog();- if (result.fileOnly) {- const sentCount = await sendMirroredFiles(chatId, key, result.reusableFiles);- if (!isPinnedAccountCurrent()) return;- const status =- sentCount > 0- ? transportMessages.streaming.fileSentDone(sentCount)- : transportMessages.streaming.deliveryFailed;- try {- await sendCardToChat(chatId, buildMarkdownCardV2(status), mirrorUuid(key, 'card'));- } catch (err) {- log.warn(- `[feishu/streamingText] parent-chat mirror card failed (non-fatal): ${- err instanceof Error ? err.message : String(err)- }`,- );- }- return;- }- try {- await sendCardToChat(chatId, result.mirrorCard, mirrorUuid(key, 'card'));- } catch (err) {- log.warn(- `[feishu/streamingText] parent-chat mirror card failed (non-fatal): ${- err instanceof Error ? err.message : String(err)- }`,- );- return;}- if (!isPinnedAccountCurrent()) return;- await sendMirroredFiles(chatId, key, result.reusableFiles);}}@@ -654,185 +371,3 @@ export async function start(export async function patchMarkdown(messageId: string, markdown: string): Promise<void> {await patchCardRaw(messageId, buildMarkdownCardV2(markdown));}--function allowLocalMediaRoots(allowedFileRoots: readonly string[] = []): boolean {- return allowedFileRoots.some((root) => root.trim());-}--async function sendMirroredFiles(- chatId: string,- key: string,- files: readonly ReusableMirroredFile[],-): Promise<number> {- const log = getLog();- const delivered = await Promise.all(- files.map(async ({ message, sourceIndex }) => {- if (!isPinnedAccountCurrent()) return false;- try {- const sent = await sendFileToChat(- chatId,- message,- mirrorUuid(key, `f${sourceIndex}`),- );- if (!sent.ok) {- log.warn(- `[feishu/streamingText] parent-chat mirror file failed (non-fatal): ${- sent.reason ?? 'unknown'- }`,- );- return false;- }- return true;- } catch (err) {- log.warn(- `[feishu/streamingText] parent-chat mirror file threw (non-fatal): ${- err instanceof Error ? err.message : String(err)- }`,- );- return false;- }- }),- );- return delivered.filter(Boolean).length;-}--async function sendOrScheduleMirror(- mirrorKey: string,- send: () => Promise<void>,- inboundEpoch: number,- alreadyConfirmed = false,-): Promise<void> {- const release = (): void => {- releaseMirrorConfirmation(mirrorKey);- };- if (getAccountEpoch() !== inboundEpoch) {- release();- return;- }- const pinned = getBoundClient();- if (!pinned) {- release();- return;- }- const runPinned = async (): Promise<void> => {- if (getAccountEpoch() !== inboundEpoch) return;- await runWithPinnedAccount({ client: pinned, epoch: inboundEpoch }, send);- };- if (alreadyConfirmed || (await waitForMirrorConfirmation(mirrorKey))) {- try {- await runPinned();- } finally {- release();- }- return;- }- const deferred = scheduleMirrorOnConfirmation(mirrorKey, () => {- void runPinned()- .catch((err) => {- getLog().warn(- `[feishu/streamingText] deferred parent-chat mirror failed (non-fatal): ${- err instanceof Error ? err.message : String(err)- }`,- );- })- .finally(release);- });- if (!deferred) release();-}--/** One-shot mirror used when the primary streaming surface failed to start. */-export async function mirrorFinal(- chatId: string,- mirrorKey: string,- text: string,- extraImageAbsPaths: readonly string[] = [],- allowedFileRoots: readonly string[] = [],- inboundEpoch: number,- alreadyConfirmed = false,-): Promise<void> {- const send = async (): Promise<void> => {- // Empty roots is the SSH fail-closed signal from turnRunner. Do not resolve- // xdt-image / cindy-media URLs or extra absPaths through local media stores.- const allowLocalMedia = allowLocalMediaRoots(allowedFileRoots);- const requestedImageUrls = collectXdtImageUrls(text);- const imageUrls = allowLocalMedia ? requestedImageUrls : [];- const skippedLocalMedia =- !allowLocalMedia && (extraImageAbsPaths.length > 0 || requestedImageUrls.length > 0);- const imageMap = new Map<string, string>();- const bodyImageAbsPaths = new Set<string>();- if (imageUrls.length > 0) {- const results = await Promise.all(- imageUrls.map(async (url) => {- let absPath: string;- try {- absPath =- getHost().media?.resolveMediaUrl(url) ??- resolveFeishuMediaUrl(url, getHost().paths.feishuMediaDir).absPath;- } catch {- return null;- }- bodyImageAbsPaths.add(absPath);- try {- const key = await uploadImage(absPath);- return key ? ([url, key] as const) : null;- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- getLog().warn(- `[feishu/streamingText] uploadImage inline ${absPath} failed: ${msg}`,- );- return null;- }- }),- );- for (const result of results) {- if (result) imageMap.set(result[0], result[1]);- }- if (!isPinnedAccountCurrent()) return;- }- const imageKeys = await uploadExtraImageKeys(- allowLocalMedia- ? extraImageAbsPaths.filter((absPath) => !bodyImageAbsPaths.has(absPath))- : [],- );- if (!isPinnedAccountCurrent()) return;- const fileLinks = collectXdtFileLinks(text);- const cardText = allowLocalMedia- ? stripXdtFileLinks(text)- : stripXdtImageLinks(stripXdtFileLinks(text)).trim();- const cardTextTrimmed = cardText.trim();- const hasImages = imageUrls.length > 0 || imageKeys.length > 0;- const fileOnly = cardTextTrimmed.length === 0 && !hasImages && fileLinks.length > 0;- if (fileOnly) {- if (!isPinnedAccountCurrent()) return;- await sendCardToChat(- chatId,- buildMarkdownCardV2(transportMessages.streaming.deliveryFailed),- mirrorUuid(mirrorKey, 'card'),- );- return;- }- if (skippedLocalMedia && cardTextTrimmed.length === 0) {- await sendCardToChat(- chatId,- buildMarkdownCardV2(transportMessages.streaming.deliveryFailed),- mirrorUuid(mirrorKey, 'card'),- );- return;- }- let card: unknown;- if (hasImages) {- card = buildMixedMarkdownCardV2(cardText, imageMap, imageKeys);- } else {- card = buildMarkdownCardV2(- cardTextTrimmed.length > 0 ? cardText : transportMessages.streaming.emptyReply,- );- }- card = fitCardToLimit(cardText, card, (visibleText) =>- hasImages- ? buildMixedMarkdownCardV2(visibleText, imageMap, imageKeys)- : buildMarkdownCardV2(visibleText),- );- await sendCardToChat(chatId, card, mirrorUuid(mirrorKey, 'card'));- };- await sendOrScheduleMirror(mirrorKey, send, inboundEpoch, alreadyConfirmed);-}diff --git a/packages/lizi-im/src/feishu/wsClient.ts b/packages/lizi-im/src/feishu/wsClient.tsindex 03b50a834a..dccbaf9dba 100644--- a/packages/lizi-im/src/feishu/wsClient.ts+++ b/packages/lizi-im/src/feishu/wsClient.ts@@ -57,7 +57,7 @@ import * as storage from './storage.js';import { parseIncoming } from './incomingContent.js';import { downloadAttachments } from './attachmentDownloader.js';import { parseCardAction } from './cardActionParser.js';-import { decodeLaneUserId, encodeLaneUserId } from './codec.js';+import { encodeLaneUserId } from './codec.js';import {coordinateDualDelivery,resetDualDeliveryForTest,@@ -65,7 +65,7 @@ import {import { getLog } from './moduleScope.js';import { messages as transportMessages } from './messages.js';import type { BotCredentials, FeishuConnectionStatus } from './internal-types.js';-import type { IMFinalReplyMirror, IMMessageEvent } from '../types.js';+import type { IMMessageEvent } from '../types.js';// ── module state ──────────────────────────────────────────────────────────────@@ -275,31 +275,11 @@ interface UnconfirmedOpenRetry {commitUnpairedFlat?: () => boolean;isUnpairedFlatTakenOver?: () => boolean;abandonUnpairedFlat?: () => void;- /** 双投镜像身份与入站账号代次必须跨延迟恢复链保留。 */- mirrorKey?: string;- mirrorAccountEpoch?: number;- mirrorConfirmed?: boolean;}const unconfirmedOpenRetries = new Map<string, UnconfirmedOpenRetry>();const suspendedUnconfirmedOpens: UnconfirmedOpenRetry[] = [];-function parentChatMirror(- chatId: string,- key: string | undefined,- accountEpoch: number | undefined,- confirmed?: boolean,-): IMFinalReplyMirror | undefined {- if (!key || accountEpoch === undefined) return undefined;- return {- kind: 'parent-chat',- chatId,- idempotencyKey: key,- accountEpoch,- ...(confirmed ? { confirmed: true } : {}),- };-}-function clearUnconfirmedOpenRetries(): void {for (const retry of unconfirmedOpenRetries.values()) {if (retry.timer) clearTimeout(retry.timer);@@ -488,12 +468,6 @@ async function retryUnconfirmedOpen(log.info(`[feishu/wsClient] unconfirmed openThread recovered as ${opener.kind} — emitting deferred turn`,);- const recoveredMirror = parentChatMirror(- entry.chatId,- entry.mirrorKey,- entry.mirrorAccountEpoch,- entry.mirrorConfirmed,- );feishuEvents.emit('message', {channelName: 'feishu',senderId: laneUserId,@@ -503,7 +477,6 @@ async function retryUnconfirmedOpen(text: entry.text,speaker: { id: entry.senderOpenId, name: '', isOwner: true },...(groupContextLane ? { groupContextLane } : {}),- ...(recoveredMirror ? { finalReplyMirror: recoveredMirror } : {}),...(entry.replyContext ? { replyContext: entry.replyContext } : {}),attachments: entry.attachments,unsupported: entry.unsupported,@@ -1546,8 +1519,6 @@ async function processClaimedMessage(// 提取分支后 data.message 的窄化不跨函数传递。const msgType = data.message?.message_type ?? '';const rawContent = data.message?.content ?? '';- let finalReplyMirrorKey: string | undefined;- let finalReplyMirrorConfirmed = false;let commitUnpairedFlat: (() => boolean) | undefined;let isUnpairedFlatTakenOver: (() => boolean) | undefined;let abandonUnpairedFlat: (() => void) | undefined;@@ -1592,8 +1563,6 @@ async function processClaimedMessage(log.info('[feishu/wsClient] native thread main-feed copy suppressed');return;}- finalReplyMirrorKey = paired.mirrorKey;- finalReplyMirrorConfirmed = Boolean(paired.alreadyConfirmed);commitUnpairedFlat = paired.commitUnpairedFlat;isUnpairedFlatTakenOver = paired.isUnpairedFlatTakenOver;abandonUnpairedFlat = paired.abandonUnpairedFlat;@@ -1803,13 +1772,6 @@ async function processClaimedMessage(commitUnpairedFlat,isUnpairedFlatTakenOver,abandonUnpairedFlat,- ...(finalReplyMirrorKey- ? {- mirrorKey: finalReplyMirrorKey,- mirrorAccountEpoch: outbound.getAccountEpoch(),- ...(finalReplyMirrorConfirmed ? { mirrorConfirmed: true } : {}),- }- : {}),});return;}@@ -1861,14 +1823,6 @@ async function processClaimedMessage(// Emit raw fields — orchestrator decides how to render unsupported (it owns// the user-facing wording and the "skip agent for pure-unsupported" rule).- const inboundMirror = parentChatMirror(- chatId,- finalReplyMirrorKey && decodeLaneUserId(laneUserId ?? '')?.threadId- ? finalReplyMirrorKey- : undefined,- outbound.getAccountEpoch(),- finalReplyMirrorConfirmed,- );feishuEvents.emit('message', {channelName: 'feishu',senderId: laneUserId ?? senderOpenId,@@ -1884,7 +1838,6 @@ async function processClaimedMessage(}: {}),...(groupContextLane ? { groupContextLane } : {}),- ...(inboundMirror ? { finalReplyMirror: inboundMirror } : {}),...(resolvedReply ? { replyContext: resolvedReply.replyContext } : {}),attachments,unsupported,diff --git a/packages/lizi-im/src/index.ts b/packages/lizi-im/src/index.tsindex ed5718b0c0..9ede48c670 100644--- a/packages/lizi-im/src/index.ts+++ b/packages/lizi-im/src/index.ts@@ -25,7 +25,6 @@ export type {IMHost,IMAttachment,IMUnsupportedEntry,- IMFinalReplyMirror,IMMessageEvent,IMCardActionEvent,IMStatus,diff --git a/packages/lizi-im/src/types.ts b/packages/lizi-im/src/types.tsindex 01c213f41a..32f2e73439 100644--- a/packages/lizi-im/src/types.ts+++ b/packages/lizi-im/src/types.ts@@ -164,43 +164,6 @@ export interface IMUnsupportedEntry {label: string;}-/**- * Optional terminal-output mirror requested by an inbound channel event.- *- * Feishu uses this for its native “同时发送到群聊” thread option: the thread- * remains the single task/Agent route, while its final answer is copied once- * to the parent group timeline. The idempotency key is opaque to the host and- * must be stable for the logical user send.- */-export interface IMFinalReplyMirror {- kind: 'parent-chat';- chatId: string;- idempotencyKey: string;- /**- * Feishu account generation captured at inbound. Terminal parent-chat- * mirrors drop if credentials rebind before the answer is copied.- */- accountEpoch: number;- /**- * Host-approved directory roots for parent-chat file copies. Missing or empty- * means fail-closed: the card still mirrors, local files do not.- */- allowedFileRoots?: string[];- /**- * Filesystem identity of `allowedFileRoots`, captured before Agent execution.- * Parent-chat file reuse must open the same pinned directory object and prove- * the uploaded leaf through a descriptor-relative, no-link object walk.- * `realPath` is an optional compatibility hint only; it never replaces that- * live handle proof.- */- pinnedFileRoots?: ReadonlyArray<{ dev: string; ino: string; realPath?: string }>;- /**- * Dual-delivery pairing was already confirmed at inbound. Terminal- * parent-chat copies must not wait on a TTL-pruned confirmation map.- */- confirmed?: boolean;-}-export interface IMMessageEvent {channelName: string;/** Sender open_id (or channel-equivalent stable user id). */@@ -270,11 +233,6 @@ export interface IMMessageEvent {};/** Channel-specific raw event for debug. */raw?: unknown;- /**- * Copy this turn's complete terminal answer to another channel-native- * destination without changing the session/lane that runs the Agent.- */- finalReplyMirror?: IMFinalReplyMirror;/*** 群历史上下文的取数 lane, 与路由 lane(senderId)分离。仅 feishu 群主流 @* 开新话题时设置: 出站路由进新话题 lane, 但上下文前缀仍按触发时所在 lane@@ -365,16 +323,8 @@ export interface StreamingTextHandle {replace(fullText: string): void;/*** Replace the card with `finalText` and stop throttling.- *- * `finalReplyMirror` is supplied only for the true turn terminal. Callers- * intentionally omit it when finalising a pre-interaction fragment, so a- * channel can reuse media uploaded by this exact finalisation without- * publishing an incomplete answer to the secondary destination.*/- finalize(- finalText: string,- opts?: { finalReplyMirror?: IMFinalReplyMirror },- ): Promise<void>;+ finalize(finalText: string): Promise<void>;/** Cancel without finalising (still leaves the last rendered text on screen). */close(): void;/**