Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(feishu): 去重话题群聊双投并同步回复 (#3554)
Lizi9646acdcb068
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.tsnew file mode 100644index 0000000000..2066f51446--- /dev/null+++ b/apps/desktop/src/main/im/shared/__tests__/messageHandler.finalReplyMirror.test.ts@@ -0,0 +1,151 @@+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 a8f811aa0f..ba4789626a 100644--- a/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/slashCommands.test.ts@@ -197,6 +197,85 @@ 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 031d2e12ed..acaaa6a60d 100644--- a/apps/desktop/src/main/im/shared/__tests__/stopCommandRouting.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/stopCommandRouting.test.ts@@ -30,6 +30,7 @@ vi.mock('../slashCommands', () => ({}));import { createMessageHandler, isStopCommand } from '../messageHandler';+import { enterControl, exitControl } from '../controlState';import {activateImAccountBoundary,captureImAccountGeneration,@@ -92,6 +93,7 @@ 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;@@ -102,6 +104,7 @@ 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);@@ -113,6 +116,7 @@ describe('messageHandler !stop routing', () => {},sendMarkdownText,sendText,+ mirrorFinalReply,consumePendingOpenerCard,consumePendingOpenerAsCard,} as unknown as ChannelIM;@@ -135,6 +139,7 @@ describe('messageHandler !stop routing', () => {beforeEach(() => {vi.clearAllMocks();+ exitControl('bot-ctx', 'U123456789');activateImAccountBoundary();wire(true);});@@ -487,6 +492,119 @@ 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 dc8d940025..f418a939c7 100644--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts@@ -28,6 +28,7 @@ const mocks = vi.hoisted(() => ({error: vi.fn(),debug: vi.fn(),},+ releaseFinalReplyMirror: vi.fn(),feishuIm: {reactToMessage: vi.fn(),removeMessageReaction: vi.fn(),@@ -40,6 +41,8 @@ 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(),@@ -377,6 +380,7 @@ function setupSession(sendImpl: Parameters<typeof createSessionHarness>[0]): Sesfunction setupAttachedSession(sendImpl: Parameters<typeof createSessionHarness>[0],+ options: { remoteHostId?: string | null } = {},): SessionHarness {const sessionId = 'desktop-attached-session';const h = createSessionHarness(sendImpl, sessionId);@@ -391,6 +395,7 @@ function setupAttachedSession(permissionMode: 'bypassPermissions',fastMode: false,sdkSessionId: null,+ remoteHostId: options.remoteHostId ?? null,providerId: null,},]);@@ -427,6 +432,12 @@ 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 = {}) {@@ -451,6 +462,7 @@ async function startDefaultTurn(onTurnComplete = vi.fn(), overrides: TurnOverrid? { prePersistedUserMessage: overrides.prePersistedUserMessage }: {}),...(overrides.onEarlyReject ? { onEarlyReject: overrides.onEarlyReject } : {}),+ ...(overrides.finalReplyMirror ? { finalReplyMirror: overrides.finalReplyMirror } : {}),});return { onTurnComplete, turnPromise };}@@ -555,6 +567,7 @@ 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(),@@ -1787,6 +1800,32 @@ 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}`,@@ -1861,6 +1900,36 @@ 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 到达 → 派发。@@ -2630,6 +2699,301 @@ 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',+ };+ const h = setupAttachedSession(async () => ({ accepted: true }), {+ remoteHostId: 'ssh-host-1',+ });+ const onTurnComplete = vi.fn();+ await runDefaultTurn(onTurnComplete, { finalReplyMirror: mirror });++ h.emit({+ type: 'tool_result_full',+ data: {+ fullText: JSON.stringify({ xdt_image_url: 'xdt-image:///remote/project/tool.png' }),+ },+ });+ h.emit({ type: 'text', data: { text: 'remote final', isFinal: true } });+ h.emit({ type: 'done', data: {} });++ await waitForAssertion(() => {+ expect(onTurnComplete).toHaveBeenCalledTimes(1);+ expect(mocks.feishuIm.startStreamingText).toHaveBeenCalledTimes(1);+ });+ 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();+ });+it('does not report route resolution before auth passes on an existing route', async () => {// 群窗口游标的 commit 挂在 onRouteResolved 上(prepareAgentTurnText 契约):// 受理前鉴权失败若先触发它, 这批群上下文会被游标永久跳过。diff --git a/apps/desktop/src/main/im/shared/messageHandler.ts b/apps/desktop/src/main/im/shared/messageHandler.tsindex 7f86dbc065..6d63b1d380 100644--- a/apps/desktop/src/main/im/shared/messageHandler.ts+++ b/apps/desktop/src/main/im/shared/messageHandler.ts@@ -65,6 +65,15 @@ export function createMessageHandler(return false;}}++ 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. */@@ -149,6 +158,7 @@ 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;}@@ -192,6 +202,7 @@ export function createMessageHandler(log.warn(`!stop reply failed (non-fatal): ${msg}`);}}+ await mirrorTerminalReply(event, reply);return;}@@ -228,11 +239,18 @@ 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);@@ -260,6 +278,7 @@ export function createMessageHandler(/* 发送失败与卡残留同一最终边界 */}}+ await mirrorSlashReply(errorText);}return;}@@ -285,6 +304,7 @@ export function createMessageHandler(log.warn(`unsupportedOnly send failed (non-fatal): ${msg}`);}}+ await mirrorTerminalReply(event, notice);return;}@@ -387,6 +407,7 @@ 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@@ -407,12 +428,13 @@ export function createMessageHandler(log.error(`runAgentTurn threw: ${msg}`);// 本条消息自己开了话题(groupContextLane)时, 开场白卡还没被流式认领 —// 用内部错误内容收口它, 否则卡永久残留且同话题下一条会 patch 错卡。+ const errorText = ui.agent.sendInternalError(msg);const openerConsumed = event.groupContextLane- ? await consumeOpenerWithText(event.senderId, ui.agent.sendInternalError(msg))+ ? await consumeOpenerWithText(event.senderId, errorText): false;if (!openerConsumed) {try {- await im.sendText(event.senderId, ui.agent.sendInternalError(msg), {+ await im.sendText(event.senderId, errorText, {threadTs: event.scopeKey,fallbackOpenerId: richIm?.takeNotedFallbackOpenerId?.(event.senderId, 'markdown'),});@@ -420,6 +442,7 @@ export function createMessageHandler(/* swallow */}}+ await mirrorTerminalReply(event, errorText);}}@@ -432,6 +455,16 @@ 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 ?? '') : ''}`;@@ -444,6 +477,15 @@ 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/sessionRepo.ts b/apps/desktop/src/main/im/shared/sessionRepo.tsindex d8775ddb0e..2853b1e770 100644--- a/apps/desktop/src/main/im/shared/sessionRepo.ts+++ b/apps/desktop/src/main/im/shared/sessionRepo.ts@@ -53,6 +53,8 @@ export interface ImSessionRow {permissionMode: PermissionMode;fastMode: boolean;sdkSessionId: string | null;+ /** Non-empty means workingDir and Agent file paths live on an SSH host. */+ remoteHostId?: string | null;/*** 该会话显式选定的供应商 id(路由用,null = 跟随默认路由)。/model 卡片选行时一并持久化,* IM turn 启动前 hydrate 进 session-provider-store,保证按选中供应商路由。@@ -226,6 +228,7 @@ export function createImSessionRepo(permissionMode: row.permissionMode,fastMode: row.fastMode,sdkSessionId: row.sdkSessionId,+ remoteHostId: row.remoteHostId ?? null,providerId: row.providerId ?? null,workspaceKind: readWorkspaceKind(row.workingDir, row.workspaceKind ?? null, botContextId),};@@ -304,6 +307,7 @@ export function createImSessionRepo(permissionMode: row.permissionMode,fastMode: row.fastMode,sdkSessionId: row.sdkSessionId,+ remoteHostId: row.remoteHostId ?? null,providerId: row.providerId ?? null,// update 前读到的旧值不能直接回 —— 与 correctedWorkspaceKind 用同一判据现算,// caller 拿到的和库里落定的才是同一个答案。@@ -325,6 +329,7 @@ export function createImSessionRepo(permissionMode: row.permissionMode,fastMode: row.fastMode,sdkSessionId: row.sdkSessionId,+ remoteHostId: row.remoteHostId ?? null,providerId: row.providerId ?? null,workspaceKind: row.workspaceKind ?? null,};@@ -424,6 +429,7 @@ export function createImSessionRepo(permissionMode: persistedRow.permissionMode,fastMode: persistedRow.fastMode,sdkSessionId: persistedRow.sdkSessionId,+ remoteHostId: persistedRow.remoteHostId ?? null,providerId: persistedRow.providerId ?? null,}: row;@@ -472,6 +478,7 @@ function rowFromDefaults(permissionMode: defaults.permissionMode,fastMode: defaults.fastMode,sdkSessionId: null,+ remoteHostId: null,providerId: defaults.providerId,};}diff --git a/apps/desktop/src/main/im/shared/slashCommands.ts b/apps/desktop/src/main/im/shared/slashCommands.tsindex d2e41bb4d5..3a38a71f46 100644--- a/apps/desktop/src/main/im/shared/slashCommands.ts+++ b/apps/desktop/src/main/im/shared/slashCommands.ts@@ -62,6 +62,12 @@ 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 {@@ -94,11 +100,34 @@ 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) {try {- if (await ctx.consumePendingOpener.withMarkdown(ctx.userId, text)) return;+ if (await ctx.consumePendingOpener.withMarkdown(ctx.userId, text)) {+ return;+ }} catch (err) {// patch 失败不吞回复: 认领已完成(卡不会再被误 patch), 回落正常// 发送 — 用户至少收到结果。@@ -115,6 +144,10 @@ 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);}}@@ -127,7 +160,9 @@ export function createSlashHandlers(try {if (ctx.consumePendingOpener) {try {- if (await ctx.consumePendingOpener.withCard(ctx.userId, spec)) return true;+ if (await ctx.consumePendingOpener.withCard(ctx.userId, spec)) {+ return true;+ }} catch (err) {// 替换失败回落正常发卡: 认领已完成, 用户至少拿到一张可用卡片。const msg = err instanceof Error ? err.message : String(err);@@ -149,6 +184,8 @@ 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 10fa4a3e1e..3c5f38560e 100644--- a/apps/desktop/src/main/im/shared/turnRunner.ts+++ b/apps/desktop/src/main/im/shared/turnRunner.ts@@ -31,6 +31,7 @@*/import { createHash, randomUUID } from 'node:crypto';+import fs from 'node:fs';import path from 'node:path';/**@@ -83,7 +84,12 @@ import type {TurnPermissionPolicy,UserMessage,} from '@cindy/maker-core';-import type { IMAttachment, InteractiveCardSpec, StreamingTextHandle } from '@cindy/im';+import type {+ IMAttachment,+ IMFinalReplyMirror,+ InteractiveCardSpec,+ StreamingTextHandle,+} from '@cindy/im';import { persistUserMessage } from '../messagePersistence';import { bindingStore } from '../binding';@@ -171,12 +177,62 @@ const PRE_DISPATCH_ACK_CLEANUP_TIMEOUT_MS = 1500;/** SESSION_RUNNING 竞态 / desktop turn 仍在跑时的兜底重试间隔。 */const DISPATCH_RETRY_MS = 500;+function resolveTurnFileRoots(+ workingDir: string,+ remoteHostId: string | null | undefined,+): string[] {+ 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;@@ -201,8 +257,8 @@ interface TurnState {presenter: TurnPresenter;/** Managed images discovered in tool output for durable text channels. */mediaAbsPaths: string[];- /** Current session root used to confine model-authored local file links. */- workingDir: string;+ /** Empty for SSH sessions: remote paths must never be opened through local fs. */+ allowedFileRoots: string[];done: boolean;/** 过程区耗时刷新的低频 ticker(首个 tool_use 启动, 收口清除)。 */activityTicker: ReturnType<typeof setInterval> | null;@@ -370,6 +426,8 @@ 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(渠道原文)。@@ -649,6 +707,7 @@ export function createTurnRunner(permissionMode: row.permissionMode,fastMode: row.fastMode,sdkSessionId: row.sdkSessionId,+ remoteHostId: row.remoteHostId ?? null,providerId: row.providerId ?? null,},attached: true,@@ -709,6 +768,7 @@ 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' };@@ -716,6 +776,7 @@ export function createTurnRunner(target = created.target;}const row = target.row;+ const allowedFileRoots = resolveTurnFileRoots(row.workingDir, row.remoteHostId);if (!target.authChecked) {const auth = await checkImRouteAuthDetailed(row, undefined, authCheckDeps());if (!auth.ok) {@@ -728,6 +789,7 @@ 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' };@@ -782,13 +844,15 @@ export function createTurnRunner(turnId: randomUUID(),userId,scopeKey: target.scopeKey,+ finalReplyMirror: withTurnFileRoots(args.finalReplyMirror, allowedFileRoots),+ finalReplyMirrorRelease: null,initialMessageText: text,streamingHandle: null,streamingHandlePromise: null,streamingStartFailed: false,presenter: createTurnPresenter({ mode: 'buffer-replace' }),mediaAbsPaths: [],- workingDir: row.workingDir,+ allowedFileRoots,done: false,activityTicker: null,outputCardMessageId: args.outputCardMessageId ?? null,@@ -809,7 +873,6 @@ export function createTurnRunner(terminalPromise,resolveTerminal,};-let state: SessionState;try {state = await ensureSessionWired(target, userId);@@ -822,6 +885,7 @@ export function createTurnRunner(} else {await completeTurnCallbackAfterAck(turn);}+ await mirrorEarlyRejectReply(turn.finalReplyMirror, ui.agent.credentialBusy);} else {await completeTurnCallbackAfterAck(turn);}@@ -919,6 +983,7 @@ 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@@ -932,6 +997,7 @@ 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 {@@ -1251,11 +1317,13 @@ 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);@@ -1354,6 +1422,7 @@ export function createTurnRunner(fastMode: row.fastMode,// 保留 DB 的 null 语义:Pi 用 null 表示清除显式 provider,不能退化为 undefined。providerId: row.providerId,+ remoteHostId: row.remoteHostId ?? undefined,resumeSessionId: row.sdkSessionId ?? undefined,vendorOptions: state.attached? undefined@@ -1494,6 +1563,56 @@ 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);+ }+ } catch (err) {+ if (output.kind === 'chunked-text') {+ turn.terminalKind = 'error';+ turn.terminalErrorCode = 'terminal_output_commit_failed';+ }+ log.warn(+ `streamingHandle.finalize failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`,+ );+ }+ }+async function handleSessionWiringBusy(userId: string, turn: TurnState): Promise<void> {log.info(`session wiring hit credential busy for userId=...${userId.slice(-8)}`);await completeTurnCallbackAfterAck(turn);@@ -1554,6 +1673,7 @@ export function createTurnRunner(fastMode: row.fastMode,// 保留 DB 的 null 语义:Pi 用 null 表示清除显式 provider,不能退化为 undefined。providerId: row.providerId,+ remoteHostId: row.remoteHostId ?? undefined,// 行总是先由 repo 建好, maker 复用已有 row 时该 title 不会生效 —// 仅作防御兜底(原 feishu 实现传 '飞书会话' 字面量, 语义等价)。title: attached ? undefined : adapter.sessions.defaultTitle(userId),@@ -2156,26 +2276,32 @@ export function createTurnRunner(* materializeTurnLocalImages 会按真实路径去重并清理正文引用,渠道最终只发一份。*/function handleToolResultFullEvent(turn: TurnState, event: AgentEvent): void {+ if (turn.allowedFileRoots.length === 0) return;const data = event.data as { fullText?: unknown } | null;if (!data || typeof data.fullText !== 'string') return;const urls = extractRenderableXdtImageUrls(data.fullText);if (urls.length === 0) return;+ const extraAbsPaths: string[] = [];+ for (const url of urls) {+ try {+ const { absPath } = url.startsWith('cindy-media://')+ ? resolveCindyMediaUrl(url)+ : resolveXdtImageUrl(url);+ extraAbsPaths.push(absPath);+ if (!turn.mediaAbsPaths.includes(absPath)) turn.mediaAbsPaths.push(absPath);+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ log.warn(`[${channel}/turn] resolve managed image failed for ${url}: ${msg}`);+ }+ }+ if (extraAbsPaths.length === 0) return;// streamingHandle 可能还没 spawn (e.g. 工具调用先于任何 text delta) — 触发// 一下 ensureStreamingHandle 让 card 先建出来, 再投递。投递接口本身是- // O(1) 同步 push, 不阻塞事件循环。+ // O(1) 同步 push, 不阻塞事件循环。终态群主流镜像读 turn.mediaAbsPaths,+ // 所以 extra 图必须同步记到 turn 上, 不能只挂在句柄里。void ensureStreamingHandle(turn).then((handle) => {if (!handle?.addExtraImageAbsPath) return; // patchedCardHandle 不实现这个能力 / 创建失败(null)- for (const url of urls) {- try {- const { absPath } = url.startsWith('cindy-media://')- ? resolveCindyMediaUrl(url)- : resolveXdtImageUrl(url);- handle.addExtraImageAbsPath(absPath);- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- log.warn(`[${channel}/turn] resolve managed image failed for ${url}: ${msg}`);- }- }+ for (const absPath of extraAbsPaths) handle.addExtraImageAbsPath(absPath);});}@@ -2469,7 +2595,38 @@ 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;@@ -2592,6 +2749,7 @@ export function createTurnRunner(await sendTextClaimingOpener(userId, message, state.scopeKey);}}+ await mirrorEarlyRejectReply(failure.turn.finalReplyMirror, message);// 群会话「完全访问」档被强确认策略拒绝: 报错文案之外, 再给 owner// 私聊发一张一键修复卡(切回 auto)。只对提供 permissionModeFix 文案// 的渠道(飞书)与群 lane 生效 — 私聊不挂群策略, 防御性跳过; 卡片@@ -2630,6 +2788,7 @@ export function createTurnRunner(/* 忽略失败:派发失败提示不能再阻塞收口。 */}}+ releaseTurnFinalReplyMirror(failure.turn);if (finishDeferredDetachIfIdle(state)) return;// 一条 pre-dispatch failure 不能卡死后面的排队消息 — 继续放行。maybeDispatchNextQueued(state, userId);@@ -2742,6 +2901,9 @@ 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 =@@ -2788,7 +2950,7 @@ export function createTurnRunner(terminal: turn.terminalKind,threadTs: turn.scopeKey,...(turn.mediaAbsPaths.length > 0 ? { mediaAbsPaths: turn.mediaAbsPaths } : {}),- allowedFileRoots: [turn.workingDir],+ allowedFileRoots: turn.allowedFileRoots,...(turn.terminalErrorCode ? { errorCode: turn.terminalErrorCode } : {}),});}@@ -2863,18 +3025,8 @@ export function createTurnRunner(}}if (turn.streamingHandle) {- try {- const finalView = composeStreamingView(turn) || '_(空回复)_';- await turn.streamingHandle.finalize(finalView);- } catch (err) {- if (output.kind === 'chunked-text') {- turn.terminalKind = 'error';- turn.terminalErrorCode = 'terminal_output_commit_failed';- }- log.warn(- `streamingHandle.finalize failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`,- );- }+ const finalView = composeStreamingView(turn) || '_(空回复)_';+ await finalizeTurnStream(turn, finalView);} else if (turn.presenter.wholeText().length === 0) {// No streamed text at all — send a one-shot text so the user knows the// turn ended. (Rare; normally agents emit at least one text block.)@@ -2901,6 +3053,11 @@ export function createTurnRunner(if (!consumed) {await sendTextClaimingOpener(userId, '✅ (本轮无文本输出)', state.scopeKey);}+ await mirrorTurnFinalReply(+ turn.finalReplyMirror,+ '✅ (本轮无文本输出)',+ turn.mediaAbsPaths.length > 0 ? { mediaAbsPaths: turn.mediaAbsPaths } : undefined,+ );}} catch {/* swallow */@@ -2922,6 +3079,11 @@ 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) {@@ -2985,13 +3147,9 @@ export function createTurnRunner(}}if (turn?.streamingHandle) {- try {- const view = composeStreamingView(turn);- const body = view ? `${view}\n\n❌ 错误:${msg}` : `❌ 错误:${msg}`;- await turn.streamingHandle.finalize(body);- } catch {- /* swallow */- }+ const view = composeStreamingView(turn);+ const body = view ? `${view}\n\n❌ 错误:${msg}` : `❌ 错误:${msg}`;+ await finalizeTurnStream(turn, body);} else {try {if (output.kind === 'chunked-text') {@@ -3014,6 +3172,11 @@ 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 */@@ -3026,7 +3189,13 @@ export function createTurnRunner(}async function materializeTurnLocalImages(state: SessionState, turn: TurnState): Promise<void> {- if (output.kind !== 'chunked-text' || !turn.presenter.wholeText().includes('![')) return;+ if (+ output.kind !== 'chunked-text' ||+ turn.allowedFileRoots.length === 0 ||+ !turn.presenter.wholeText().includes('![')+ ) {+ return;+ }try {const materialized = await materializeLocalMarkdownImages({text: turn.presenter.wholeText(),@@ -3291,6 +3460,7 @@ 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/apps/desktop/src/main/maker-ipc/__tests__/bootstrapDirectoryGrants.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/bootstrapDirectoryGrants.test.tsindex f560df09d4..47b8d0a293 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/bootstrapDirectoryGrants.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/bootstrapDirectoryGrants.test.ts@@ -64,7 +64,7 @@ describe('prepareDirectoryGrantsForBootstrap', () => {it('drops caller-supplied writable roots when no persisted session grant exists', async () => {const { root, workspace, shared, specs, output } = makeGrantTree();const sharedAlias = path.join(root, 'shared-alias');- symlinkSync(shared, sharedAlias, 'dir');+ symlinkSync(shared, sharedAlias, process.platform === 'win32' ? 'junction' : 'dir');const opts = createOpts(workspace, [specs], [sharedAlias, output]);const persistExistingSession = vi.fn(async () => {// Direct maker:create-session has no SQLite row until maker-core creates it.diff --git a/apps/desktop/src/main/maker-ipc/__tests__/extraDirsValidator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/extraDirsValidator.test.tsindex 12fcc411ba..e0230111cb 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/extraDirsValidator.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/extraDirsValidator.test.ts@@ -22,7 +22,7 @@ describe('excludeDirectoryGrantConflicts', () => {const output = path.join(root, 'output');mkdirSync(reference);mkdirSync(output);- symlinkSync(reference, alias, 'dir');+ symlinkSync(reference, alias, process.platform === 'win32' ? 'junction' : 'dir');await expect(excludeDirectoryGrantConflicts([reference, alias, output], [reference]),@@ -69,7 +69,7 @@ describe('excludeDirectoryGrantConflicts', () => {const sibling = path.join(root, 'shared-other');mkdirSync(specs, { recursive: true });mkdirSync(sibling);- symlinkSync(shared, sharedAlias, 'dir');+ symlinkSync(shared, sharedAlias, process.platform === 'win32' ? 'junction' : 'dir');await expect(excludeDirectoryGrantConflicts([sharedAlias, sibling], [specs]),diff --git a/packages/lizi-im/src/channelIM.ts b/packages/lizi-im/src/channelIM.tsindex b8ef7783b4..3531882c56 100644--- a/packages/lizi-im/src/channelIM.ts+++ b/packages/lizi-im/src/channelIM.ts@@ -18,6 +18,7 @@import type {IMCardActionEvent,+ IMFinalReplyMirror,IMMessageEvent,IMStatus,InteractiveCardSpec,@@ -129,6 +130,16 @@ 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.tsnew file mode 100644index 0000000000..8516f6ddb8--- /dev/null+++ b/packages/lizi-im/src/feishu/__tests__/dualDelivery.test.ts@@ -0,0 +1,640 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ coordinateDualDelivery,+ isMirrorConfirmationRetainedForTest,+ releaseMirrorConfirmation,+ resetDualDeliveryForTest,+ retainMirrorConfirmation,+ scheduleMirrorOnConfirmation,+ waitForMirrorConfirmation,+} from '../dualDelivery.js';++function input(overrides: Partial<Parameters<typeof coordinateDualDelivery>[0]> = {}) {+ return {+ appId: 'cli_test',+ chatId: 'oc_group',+ senderOpenId: 'ou_owner',+ createTime: '1788000000000',+ messageType: 'text',+ rawContent: JSON.stringify({ text: '@_user_1 hello' }),+ messageId: 'om_thread',+ threadId: 'omt_topic',+ ...overrides,+ };+}++afterEach(() => {+ resetDualDeliveryForTest();+ vi.useRealTimers();+});++describe('Feishu native thread/main dual delivery', () => {+ it('prefers the topic event when the main-feed copy arrives first', async () => {+ const flat = coordinateDualDelivery(input({ messageId: 'om_flat', threadId: '' }));+ 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);+ });++ it('suppresses a main-feed copy that arrives after topic dispatch', async () => {+ const topic = await coordinateDualDelivery(input());+ const flat = await coordinateDualDelivery(input({ messageId: 'om_flat', threadId: '' }));++ 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');+ await expect(+ coordinateDualDelivery(input({ messageId: 'om_flat', threadId: '' })),+ ).resolves.toEqual({ kind: 'suppress-main-copy' });++ await vi.advanceTimersByTimeAsync(2 * 60 * 60 * 1000 + 1);+ await coordinateDualDelivery(+ input({ createTime: 'prune-unemitted', messageId: 'om_prune_unemitted' }),+ );++ await expect(waitForMirrorConfirmation(topic.mirrorKey)).resolves.toBe(false);+ });++ it('releases an uncommitted topic lease so a later retry can acquire a fresh one', async () => {+ const topic = await coordinateDualDelivery(input());+ if (topic.kind !== 'dispatch' || !topic.commitTopic || !topic.abandonTopic) {+ throw new Error('elected topic must expose abandonTopic');+ }+ topic.abandonTopic();+ expect(topic.commitTopic()).toBe(false);++ const retry = await coordinateDualDelivery(+ input({ messageId: 'om_topic_retry', threadId: 'omt_topic' }),+ );+ expect(retry).toMatchObject({+ kind: 'dispatch',+ commitTopic: expect.any(Function),+ abandonTopic: expect.any(Function),+ });+ if (retry.kind !== 'dispatch' || !retry.commitTopic) {+ throw new Error('abandoned topic must allow a fresh lease');+ }+ expect(retry.commitTopic()).toBe(true);+ });++ it('allows an elected topic retry before the topic route commits', async () => {+ const topic = await coordinateDualDelivery(input());+ await expect(+ coordinateDualDelivery(input({ messageId: 'om_flat', threadId: '' })),+ ).resolves.toEqual({ kind: 'suppress-main-copy' });+ expect(topic).toMatchObject({+ kind: 'dispatch',+ mirrorKey: expect.any(String),+ commitTopic: expect.any(Function),+ });++ const retry = await coordinateDualDelivery(+ input({ messageId: 'om_topic_retry', threadId: 'omt_topic' }),+ );+ expect(retry).toMatchObject({+ kind: 'dispatch',+ mirrorKey: expect.any(String),+ alreadyConfirmed: true,+ commitTopic: expect.any(Function),+ });+ await expect(+ coordinateDualDelivery(input({ messageId: 'om_flat_retry', threadId: '' })),+ ).resolves.toEqual({ kind: 'suppress-main-copy' });+ });++ it('suppresses a later topic retry after the elected topic route commits', async () => {+ const topic = await coordinateDualDelivery(input());+ await expect(+ coordinateDualDelivery(input({ messageId: 'om_flat', threadId: '' })),+ ).resolves.toEqual({ kind: 'suppress-main-copy' });+ if (topic.kind !== 'dispatch' || !topic.commitTopic) {+ throw new Error('elected topic must expose commitTopic');+ }+ expect(topic.commitTopic()).toBe(true);++ await expect(+ coordinateDualDelivery(input({ messageId: 'om_topic_retry' })),+ ).resolves.toEqual({ kind: 'suppress-main-copy' });+ });++ it('keeps a committed topic lease until the main-feed copy confirms the pair', async () => {+ const topic = await coordinateDualDelivery(input());+ if (topic.kind !== 'dispatch' || !topic.commitTopic) {+ throw new Error('elected topic must expose commitTopic');+ }+ expect(topic.commitTopic()).toBe(true);++ await expect(+ coordinateDualDelivery(input({ messageId: 'om_topic_retry', threadId: 'omt_topic' })),+ ).resolves.toEqual({ kind: 'suppress-main-copy' });+ await expect(+ coordinateDualDelivery(input({ messageId: 'om_flat', threadId: '' })),+ ).resolves.toEqual({ kind: 'suppress-main-copy' });+ });++ it('suppresses fresh flat message ids after the logical send is confirmed', async () => {+ vi.useFakeTimers();+ const topic = await coordinateDualDelivery(input());+ await expect(+ coordinateDualDelivery(input({ messageId: 'om_flat_first', threadId: '' })),+ ).resolves.toEqual({ kind: 'suppress-main-copy' });++ const duplicate = coordinateDualDelivery(+ input({ messageId: 'om_flat_second', threadId: '' }),+ );+ await vi.advanceTimersByTimeAsync(1_000);++ await expect(duplicate).resolves.toEqual({ kind: 'suppress-main-copy' });+ expect(topic).toMatchObject({ kind: 'dispatch', mirrorKey: expect.any(String) });+ });++ it('dispatches an unpaired flat group message after the bounded wait', 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) {+ throw new Error('unpaired flat must expose mirrorKey');+ }+ await expect(waitForMirrorConfirmation(flatDecision.mirrorKey)).resolves.toBe(false);+ });++ it('elects only one route when duplicate flat ids share a logical send', async () => {+ vi.useFakeTimers();+ const firstFlat = coordinateDualDelivery(input({ messageId: 'om_flat_first', threadId: '' }));+ const secondFlat = coordinateDualDelivery(+ input({ messageId: 'om_flat_second', threadId: '' }),+ );+ await vi.advanceTimersByTimeAsync(1_000);+ const firstDecision = await firstFlat;++ expect(firstDecision).toMatchObject({ kind: 'dispatch' });+ await expect(secondFlat).resolves.toEqual({ kind: 'suppress-main-copy' });+ await expect(+ coordinateDualDelivery(input({ messageId: 'om_flat_third', threadId: '' })),+ ).resolves.toEqual({ kind: 'suppress-main-copy' });+ if (firstDecision.kind !== 'dispatch' || !firstDecision.commitUnpairedFlat) {+ throw new Error('elected flat must expose commitUnpairedFlat');+ }++ await expect(coordinateDualDelivery(input())).resolves.toMatchObject({+ kind: 'dispatch',+ mirrorKey: expect.any(String),+ alreadyConfirmed: true,+ });+ expect(firstDecision.commitUnpairedFlat()).toBe(false);+ });++ it('does not merge equal text from different create_time values', async () => {+ vi.useFakeTimers();+ const flat = coordinateDualDelivery(input({ messageId: 'om_flat', threadId: '' }));+ const topic = await coordinateDualDelivery(+ input({ messageId: 'om_topic_later', createTime: '1788000000001' }),+ );+ await vi.advanceTimersByTimeAsync(1_000);++ 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 () => {+ const flat = await coordinateDualDelivery(+ input({ messageId: 'om_flat', threadId: '', createTime: '' }),+ );+ const topic = await coordinateDualDelivery(input({ createTime: '' }));++ expect(flat).toEqual({ kind: 'dispatch' });+ expect(topic).toEqual({ kind: 'dispatch' });+ });++ it('peeking taken-over does not commit an unpaired flat', 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' });+ if (flatDecision.kind !== 'dispatch' || !flatDecision.isUnpairedFlatTakenOver) {+ throw new Error('unpaired flat must expose isUnpairedFlatTakenOver');+ }+ expect(flatDecision.isUnpairedFlatTakenOver()).toBe(false);++ const topic = await coordinateDualDelivery(input());+ expect(topic.kind).toBe('dispatch');+ expect(flatDecision.isUnpairedFlatTakenOver()).toBe(true);+ expect(flatDecision.commitUnpairedFlat?.()).toBe(false);+ });++ it('lets a late topic take over an unpaired flat that has not committed yet', 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' });+ if (flatDecision.kind !== 'dispatch' || !flatDecision.commitUnpairedFlat) {+ throw new Error('unpaired flat must expose commitUnpairedFlat');+ }++ 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(flatDecision.commitUnpairedFlat()).toBe(false);+ });++ it('keeps an uncommitted flat route leased past the late-copy cache TTL', 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.commitUnpairedFlat) {+ throw new Error('unpaired flat must expose commitUnpairedFlat');+ }++ await vi.advanceTimersByTimeAsync(25_001);+ await coordinateDualDelivery(+ input({ createTime: 'unrelated', messageId: 'om_unrelated', threadId: 'omt_other' }),+ );+ const lateTopic = await coordinateDualDelivery(input());++ expect(lateTopic).toMatchObject({+ kind: 'dispatch',+ mirrorKey: expect.any(String),+ alreadyConfirmed: true,+ });+ expect(flatDecision.commitUnpairedFlat()).toBe(false);+ });++ it('does not capacity-evict an uncommitted flat route lease', async () => {+ const firstFlat = coordinateDualDelivery(+ input({ createTime: 'capacity-0', messageId: 'om_capacity_0', threadId: '' }),+ );+ // MAX_PENDING (512) must be exceeded before records enter recentFlats, then+ // MAX_RECENT (1,000) must also be exceeded to exercise cache pruning.+ for (let i = 1; i <= 1_512; i++) {+ void coordinateDualDelivery(+ input({+ createTime: `capacity-${i}`,+ messageId: `om_capacity_${i}`,+ threadId: '',+ }),+ );+ }+ const flatDecision = await firstFlat;+ if (flatDecision.kind !== 'dispatch' || !flatDecision.commitUnpairedFlat) {+ throw new Error('capacity-evicted flat must expose commitUnpairedFlat');+ }++ const lateTopic = await coordinateDualDelivery(+ input({ createTime: 'capacity-0', messageId: 'om_capacity_topic' }),+ );++ expect(lateTopic).toMatchObject({+ kind: 'dispatch',+ mirrorKey: expect.any(String),+ alreadyConfirmed: true,+ });+ expect(flatDecision.commitUnpairedFlat()).toBe(false);+ });++ it('keeps an abandoned flat observable so a late topic confirms its 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.commitUnpairedFlat ||+ !flatDecision.abandonUnpairedFlat+ ) {+ throw new Error('unpaired flat must expose route lifecycle callbacks');+ }++ 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);+ });++ it('lets a fresh flat retry acquire a new route lease after abandonment', async () => {+ vi.useFakeTimers();+ const firstFlat = coordinateDualDelivery(input({ messageId: 'om_flat_first', threadId: '' }));+ await vi.advanceTimersByTimeAsync(1_000);+ const firstDecision = await firstFlat;+ if (firstDecision.kind !== 'dispatch' || !firstDecision.abandonUnpairedFlat) {+ throw new Error('unpaired flat must expose abandonUnpairedFlat');+ }+ firstDecision.abandonUnpairedFlat();++ const retry = coordinateDualDelivery(input({ messageId: 'om_flat_retry', threadId: '' }));+ await vi.advanceTimersByTimeAsync(1_000);+ const retryDecision = await retry;+ expect(retryDecision).toMatchObject({+ kind: 'dispatch',+ mirrorKey: expect.any(String),+ commitUnpairedFlat: expect.any(Function),+ });+ if (retryDecision.kind !== 'dispatch' || !retryDecision.commitUnpairedFlat) {+ throw new Error('retried flat must expose a fresh route lease');+ }+ 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.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 () => {+ vi.useFakeTimers();+ const firstFlat = coordinateDualDelivery(input({ messageId: 'om_flat', threadId: '' }));+ await vi.advanceTimersByTimeAsync(1_000);+ await firstFlat;+ const topic = await coordinateDualDelivery(input());+ expect(topic.kind).toBe('dispatch');++ await expect(+ coordinateDualDelivery(input({ messageId: 'om_flat_retry', threadId: '' })),+ ).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) });++ for (let i = 1; i <= pendingCap; i++) {+ await coordinateDualDelivery(+ input({+ createTime: String(i + 1),+ messageId: `om_t${i}`,+ threadId: `omt_${i}`,+ }),+ );+ }++ vi.useFakeTimers();+ const lateFlat = coordinateDualDelivery(+ input({ createTime: '1', messageId: 'om_flat', threadId: '' }),+ );+ await vi.advanceTimersByTimeAsync(1_000);+ await expect(lateFlat).resolves.toEqual({ kind: 'suppress-main-copy' });+ });++ it('writes a recent-flat tombstone when a pending pair is capacity-evicted', async () => {+ const pendingCap = 512;+ const firstFlat = coordinateDualDelivery(+ input({ createTime: '1', messageId: 'om_f0', threadId: '' }),+ );+ for (let i = 1; i <= pendingCap; i++) {+ void coordinateDualDelivery(+ input({+ createTime: String(i + 1),+ messageId: `om_f${i}`,+ threadId: '',+ }),+ );+ }+ const firstDecision = await firstFlat;+ expect(firstDecision).toMatchObject({ kind: 'dispatch' });+ if (firstDecision.kind !== 'dispatch' || !firstDecision.commitUnpairedFlat) {+ throw new Error('evicted unpaired flat must expose commitUnpairedFlat');+ }++ 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(firstDecision.commitUnpairedFlat()).toBe(false);+ });++ it('forgets unheld confirmations after 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');++ 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 () => {+ vi.useFakeTimers();+ const topic = await coordinateDualDelivery(input());+ if (topic.kind !== 'dispatch' || !topic.mirrorKey) throw new Error('missing mirror key');+ retainMirrorConfirmation(topic.mirrorKey);+ 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__/ipcAccountScope.test.ts b/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.tsindex 24e13e68d2..71171043e2 100644--- a/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.ts@@ -379,6 +379,7 @@ describe('Feishu credential connection semantics', () => {expect(mocks.stop).toHaveBeenCalledWith({reason: 'credentials-cleared',clearOwnerBeforeIdle: true,+ discardPendingTopicLeases: true,});expect(mocks.clearOwner).not.toHaveBeenCalled();expect(mocks.clearAll).toHaveBeenCalledOnce();@@ -457,6 +458,7 @@ describe('Feishu credential connection semantics', () => {expect(mocks.stop).toHaveBeenCalledWith({announceOffline: false,reason: 'manual-reconnect',+ nextAccount: { appId: credentials.appId, service: credentials.service },});expect(mocks.start).toHaveBeenCalledWith(credentials, {announceLifecycle: false,@@ -474,6 +476,7 @@ describe('Feishu credential connection semantics', () => {expect(mocks.stop).toHaveBeenCalledWith({announceOffline: false,reason: 'manual-reconnect',+ nextAccount: { appId: credentials.appId, service: credentials.service },});expect(mocks.start).toHaveBeenCalledWith(credentials, {announceLifecycle: false,@@ -491,6 +494,7 @@ describe('Feishu credential connection semantics', () => {expect(mocks.stop).toHaveBeenCalledWith({reason: 'credentials-replaced',clearOwnerBeforeIdle: true,+ nextAccount: { appId: 'cli_other', service: 'feishu' },});expect(mocks.start).toHaveBeenCalledWith({ appId: 'cli_other', appSecret: 'other-secret', service: 'feishu' },@@ -513,6 +517,7 @@ describe('Feishu credential connection semantics', () => {expect(mocks.stop).toHaveBeenCalledWith({reason: 'credentials-replaced',clearOwnerBeforeIdle: true,+ nextAccount: { appId: credentials.appId, service: 'lark' },});expect(mocks.start).toHaveBeenCalledWith({@@ -536,6 +541,7 @@ describe('Feishu credential connection semantics', () => {expect(mocks.stop).toHaveBeenCalledWith({reason: 'credentials-replaced',clearOwnerBeforeIdle: true,+ nextAccount: { appId: 'cli_registered', service: 'feishu' },});expect(mocks.writeOwnerOpenId).toHaveBeenCalledWith('ou_registered_owner');expect(mocks.loadOwner).toHaveBeenCalledOnce();@@ -568,6 +574,7 @@ describe('Feishu credential connection semantics', () => {expect(mocks.stop).toHaveBeenCalledWith({reason: 'credentials-replaced',clearOwnerBeforeIdle: false,+ nextAccount: { appId: credentials.appId, service: credentials.service },});expect(mocks.writeOwnerOpenId).not.toHaveBeenCalled();expect(mocks.loadOwner).not.toHaveBeenCalled();diff --git a/packages/lizi-im/src/feishu/__tests__/outboundFile.test.ts b/packages/lizi-im/src/feishu/__tests__/outboundFile.test.tsnew file mode 100644index 0000000000..8bb575fed7--- /dev/null+++ b/packages/lizi-im/src/feishu/__tests__/outboundFile.test.ts@@ -0,0 +1,366 @@+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(() => ({+ createFile: vi.fn(),+ createImage: vi.fn(),+ createMessage: vi.fn(async () => ({ data: { message_id: 'om_sent' } })),+}));++vi.mock('@larksuiteoapi/node-sdk', () => ({+ Client: class {+ im = {+ v1: {+ message: { create: mocks.createMessage },+ messageReaction: { create: vi.fn(), delete: vi.fn() },+ image: { create: mocks.createImage },+ },+ file: { create: mocks.createFile },+ };+ },+ Domain: { Feishu: 'feishu-domain', Lark: 'lark-domain' },+}));++vi.mock('../ownerGuard.js', () => ({+ firstAllowed: vi.fn(() => 'ou_owner'),+ check: vi.fn(() => true),+}));++vi.mock('../moduleScope.js', () => ({+ getLog: () => ({+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ }),+}));++import * as outbound from '../outbound.js';++const tempDirs: string[] = [];++async function readStream(stream: NodeJS.ReadableStream): Promise<string> {+ const chunks: Buffer[] = [];+ for await (const chunk of stream) {+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));+ }+ return Buffer.concat(chunks).toString('utf8');+}++async function fileFixture(name: string, content: string): Promise<string> {+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-file-'));+ tempDirs.push(root);+ const absPath = path.join(root, name);+ await fs.writeFile(absPath, content);+ return absPath;+}++describe('Feishu parent-chat file reuse', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ outbound.unbindClient();+ outbound.bindClient({ appId: 'cli_file_test', appSecret: 'secret', service: 'feishu' });+ mocks.createFile.mockImplementation(+ async ({ data }: { data: { file: NodeJS.ReadableStream } }) => {+ await readStream(data.file);+ return { file_key: 'file-key' };+ },+ );+ mocks.createImage.mockImplementation(+ async ({ data }: { data: { image: NodeJS.ReadableStream } }) => {+ await readStream(data.image);+ return { image_key: 'image-key' };+ },+ );+ });++ afterEach(async () => {+ outbound.unbindClient();+ await Promise.all(+ tempDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true })),+ );+ });++ it('uploads a regular file once and reuses its file_key for the parent chat', async () => {+ const absPath = await fileFixture('报告.txt', 'trusted report');++ const primary = await outbound.sendFile('ou_owner', absPath, 'report.txt');+ expect(primary).toMatchObject({+ ok: true,+ messageId: 'om_sent',+ reusableMessage: {+ msgType: 'file',+ content: JSON.stringify({ file_key: 'file-key' }),+ },+ uploadedSource: {+ realPath: expect.any(String),+ dev: expect.any(String),+ ino: expect.any(String),+ ancestors: [],+ },+ });+ if (['linux', 'darwin', 'win32'].includes(process.platform)) {+ expect(primary.uploadedSource!.realPath.length).toBeGreaterThan(0);+ } else {+ expect(primary.uploadedSource!.realPath).toBe('');+ }++ await expect(+ outbound.sendFileToChat('oc_group', primary.reusableMessage!, 'u1'),+ ).resolves.toEqual({ ok: true, messageId: 'om_sent' });++ expect(mocks.createFile).toHaveBeenCalledOnce();+ expect(mocks.createImage).not.toHaveBeenCalled();+ expect(mocks.createMessage).toHaveBeenCalledTimes(2);+ });++ it('proves a Unicode file only through the same pinned directory object chain', async () => {+ const allowedRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-chain-allowed-'));+ const outsideRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-chain-outside-'));+ tempDirs.push(allowedRoot, outsideRoot);+ const segments = ['子目录', '报告.txt'];+ await Promise.all([+ fs.mkdir(path.join(allowedRoot, segments[0])),+ fs.mkdir(path.join(outsideRoot, segments[0])),+ ]);+ const allowedFile = path.join(allowedRoot, ...segments);+ const outsideFile = path.join(outsideRoot, ...segments);+ await Promise.all([+ fs.writeFile(allowedFile, 'allowed'),+ fs.writeFile(outsideFile, 'outside'),+ ]);++ const rootFd = fsSync.openSync(allowedRoot, fsSync.constants.O_RDONLY);+ const allowedFd = fsSync.openSync(allowedFile, fsSync.constants.O_RDONLY);+ const outsideFd = fsSync.openSync(outsideFile, fsSync.constants.O_RDONLY);+ try {+ await expect(+ outbound.attestOpenFileWithinDirectory(allowedFd, rootFd, segments),+ ).resolves.toBe(true);+ await expect(+ outbound.attestOpenFileWithinDirectory(outsideFd, rootFd, segments),+ ).resolves.toBe(false);+ } finally {+ fsSync.closeSync(outsideFd);+ fsSync.closeSync(allowedFd);+ fsSync.closeSync(rootFd);+ }+ });++ it('rejects a source reached only through an intermediate directory link', async () => {+ const allowedRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-chain-link-'));+ const outsideRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-chain-secret-'));+ tempDirs.push(allowedRoot, outsideRoot);+ const outsideFile = path.join(outsideRoot, 'secret.txt');+ await fs.writeFile(outsideFile, 'secret');+ const linked = path.join(allowedRoot, 'linked');+ try {+ await fs.symlink(outsideRoot, linked, process.platform === 'win32' ? 'junction' : 'dir');+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'EPERM') return;+ throw error;+ }++ const rootFd = fsSync.openSync(allowedRoot, fsSync.constants.O_RDONLY);+ const sourceFd = fsSync.openSync(outsideFile, fsSync.constants.O_RDONLY);+ try {+ await expect(+ outbound.attestOpenFileWithinDirectory(sourceFd, rootFd, ['linked', 'secret.txt']),+ ).resolves.toBe(false);+ } finally {+ fsSync.closeSync(sourceFd);+ fsSync.closeSync(rootFd);+ }+ });++ it('uploads an image once and reuses its image_key for the parent chat', async () => {+ const absPath = await fileFixture('preview.png', 'trusted image');++ const primary = await outbound.sendFile('ou_owner', absPath);+ expect(primary.reusableMessage).toEqual({+ msgType: 'image',+ content: JSON.stringify({ image_key: 'image-key' }),+ });++ await expect(+ outbound.sendFileToChat('oc_group', primary.reusableMessage!, 'u2'),+ ).resolves.toEqual({ ok: true, messageId: 'om_sent' });++ expect(mocks.createImage).toHaveBeenCalledOnce();+ expect(mocks.createFile).not.toHaveBeenCalled();+ expect(mocks.createMessage).toHaveBeenCalledTimes(2);+ });++ it('reports a parent-message failure without uploading the local file again', async () => {+ const absPath = await fileFixture('report.txt', 'trusted report');+ const primary = await outbound.sendFile('ou_owner', absPath);+ mocks.createMessage.mockRejectedValueOnce(new Error('group unavailable'));++ await expect(+ outbound.sendFileToChat('oc_group', primary.reusableMessage!, 'u3'),+ ).resolves.toEqual({ ok: false, reason: 'SEND_FAIL' });++ expect(mocks.createFile).toHaveBeenCalledOnce();+ expect(mocks.createImage).not.toHaveBeenCalled();+ });++ it('uploads the inode opened for identity when the path is replaced before the stream starts', async () => {+ const absPath = await fileFixture('report.txt', 'trusted report');+ const outsideRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-outside-'));+ tempDirs.push(outsideRoot);+ const outside = path.join(outsideRoot, 'secret.txt');+ await fs.writeFile(outside, 'LEAKED SECRET');++ let uploaded = '';+ mocks.createFile.mockImplementation(+ async ({ data }: { data: { file: NodeJS.ReadableStream } }) => {+ uploaded = await readStream(data.file);+ return { file_key: 'file-key' };+ },+ );++ const realCreateReadStream = fsSync.createReadStream;+ const spy = vi.spyOn(fsSync, 'createReadStream').mockImplementation(((+ file: unknown,+ options?: unknown,+ ) => {+ if (file === absPath) {+ fsSync.unlinkSync(absPath);+ fsSync.copyFileSync(outside, absPath);+ }+ return realCreateReadStream(+ file as Parameters<typeof realCreateReadStream>[0],+ options as Parameters<typeof realCreateReadStream>[1],+ );+ }) as typeof fsSync.createReadStream);++ try {+ const primary = await outbound.sendFile('ou_owner', absPath, 'report.txt');+ expect(primary.ok).toBe(true);+ expect(uploaded).toBe('trusted report');+ expect(primary.uploadedSource).toMatchObject({+ realPath: expect.any(String),+ dev: expect.any(String),+ ino: expect.any(String),+ });+ } finally {+ spy.mockRestore();+ }+ });++ it('does not attest a path-based fallback when the Windows helper is unavailable', async () => {+ const absPath = await fileFixture('report.txt', 'trusted report');+ const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32');+ const realStat = fsSync.statSync.bind(fsSync);+ const stat = vi.spyOn(fsSync, 'statSync').mockImplementation(((+ file: unknown,+ options?: unknown,+ ) => {+ if (String(file).toLowerCase().endsWith('\\powershell.exe')) {+ throw new Error('Windows helper unavailable');+ }+ return realStat(+ file as Parameters<typeof realStat>[0],+ options as Parameters<typeof realStat>[1],+ );+ }) as typeof fsSync.statSync);++ try {+ const primary = await outbound.sendFile('ou_owner', absPath, 'report.txt');+ expect(primary.ok).toBe(true);+ expect(primary.uploadedSource).toMatchObject({+ realPath: '',+ dev: expect.any(String),+ ino: expect.any(String),+ });+ } finally {+ stat.mockRestore();+ platform.mockRestore();+ }+ });++ it('keeps Darwin containment independent of Electron RunAsNode', async () => {+ // Windows CI may check out CRLF; the launcher marker below is LF-only.+ const source = (+ await fs.readFile(new URL('../outbound.ts', import.meta.url), 'utf8')+ ).replace(/\r\n/g, '\n');+ const helperStart = source.indexOf('const DARWIN_HANDLE_CONTAINMENT_SCRIPT');+ const helperEnd = source.indexOf('let client:', helperStart);+ const helper = source.slice(helperStart, helperEnd);+ const launcherStart = source.indexOf('async function darwinHandleContainment');+ const launcherEnd = source.indexOf('/**\n * Object-chain containment proof', launcherStart);+ const launcher = source.slice(launcherStart, launcherEnd);++ expect(helperStart).toBeGreaterThanOrEqual(0);+ expect(helperEnd).toBeGreaterThan(helperStart);+ expect(launcherStart).toBeGreaterThanOrEqual(0);+ expect(launcherEnd).toBeGreaterThan(launcherStart);+ expect(helper).toContain('O_NOFOLLOW');+ expect(helper).toContain('SYS_openat');+ expect(helper).not.toContain('/dev/fd/');+ expect(launcher).toContain("'/usr/bin/perl'");+ expect(launcher).not.toContain('process.execPath');+ expect(launcher).not.toContain('ELECTRON_RUN_AS_NODE');+ });++ it('does not attest the restored in-root path after the opened file is retargeted', async () => {+ const allowedRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-retarget-in-'));+ const outsideRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-feishu-retarget-out-'));+ tempDirs.push(allowedRoot, outsideRoot);+ const secret = path.join(outsideRoot, 'secret.txt');+ await fs.writeFile(secret, 'LEAKED SECRET');+ const absPath = path.join(allowedRoot, 'report.txt');+ try {+ await fs.symlink(secret, absPath);+ } catch {+ return;+ }+ const secretStat = fsSync.statSync(secret, { bigint: true });++ const realRealpath = fsSync.realpathSync.native.bind(fsSync.realpathSync);+ const spy = vi.spyOn(fsSync.realpathSync, 'native').mockImplementation(((+ file: unknown,+ options?: unknown,+ ) => {+ // Linux binds via /proc/self/fd and never realpath(absPath). Retarget+ // the in-root name on the first lookup of any candidate so the decoy+ // inode is distinct from the opened secret.+ try {+ if (fsSync.lstatSync(absPath).isSymbolicLink()) {+ fsSync.unlinkSync(absPath);+ fsSync.writeFileSync(absPath, 'trusted decoy');+ }+ } catch {+ /* absPath already replaced or gone */+ }+ return realRealpath(+ file as Parameters<typeof realRealpath>[0],+ options as Parameters<typeof realRealpath>[1],+ );+ }) as typeof fsSync.realpathSync.native);++ try {+ const primary = await outbound.sendFile('ou_owner', absPath, 'report.txt');+ expect(primary.ok).toBe(true);+ const decoyReal = realRealpath(absPath);+ const decoyStat = fsSync.statSync(decoyReal, { bigint: true });+ expect(primary.uploadedSource).toMatchObject({+ dev: String(secretStat.dev),+ ino: String(secretStat.ino),+ });+ expect(primary.uploadedSource!.ino).not.toBe(String(decoyStat.ino));+ expect(primary.uploadedSource!.realPath).not.toBe(decoyReal);+ if (primary.uploadedSource!.realPath) {+ const named = fsSync.statSync(primary.uploadedSource!.realPath, { bigint: true });+ expect(String(named.ino)).toBe(primary.uploadedSource!.ino);+ expect(String(named.dev)).toBe(primary.uploadedSource!.dev);+ }+ } finally {+ spy.mockRestore();+ }+ });+});diff --git a/packages/lizi-im/src/feishu/__tests__/streamingText.test.ts b/packages/lizi-im/src/feishu/__tests__/streamingText.test.tsindex 994324fbf9..e1ed1cf2c6 100644--- a/packages/lizi-im/src/feishu/__tests__/streamingText.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/streamingText.test.ts@@ -1,22 +1,50 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+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: () => ({+ media: { resolveMediaUrl: mocks.resolveMediaUrl },+ paths: { feishuMediaDir: '/tmp/feishu-media' },+ }),}));import { messages } from '../messages.js';-import { FEISHU_CARD_REQUEST_MAX_BYTES, start } from '../streamingText.js';+import { FEISHU_CARD_REQUEST_MAX_BYTES, mirrorFinal, start } from '../streamingText.js';+import {+ releaseMirrorConfirmation,+ scheduleMirrorOnConfirmation,+ waitForMirrorConfirmation,+} from '../dualDelivery.js';function markdownContent(card: unknown): string {return (card as { body: { elements: Array<{ content: string }> } }).body.elements[0].content;@@ -26,12 +54,115 @@ 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.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 () => {@@ -69,16 +200,21 @@ describe('feishu streaming text', () => {expect(markdownContent(card)).toBe(messages.streaming.deliveryFailed);});- it('patches a short user-visible notice when the final card shape is rejected', async () => {+ it('patches a short notice and still mirrors 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('正文');+ await handle.finalize('正文', terminalMirror('v'.repeat(64)));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 () => {@@ -91,4 +227,991 @@ describe('feishu streaming text', () => {messages.streaming.deliveryFailed,);});++ 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 () => {+ 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']),+ ),+ ).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`,+ );+ });});diff --git a/packages/lizi-im/src/feishu/__tests__/wsClientCardAction.test.ts b/packages/lizi-im/src/feishu/__tests__/wsClientCardAction.test.tsindex b159fe84a8..856a0bbc18 100644--- a/packages/lizi-im/src/feishu/__tests__/wsClientCardAction.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/wsClientCardAction.test.ts@@ -66,6 +66,7 @@ vi.doMock('../outbound.js', () => ({bindClient: mocks.bindClient,unbindClient: mocks.unbindClient,getBoundClient: mocks.getBoundClient,+ getAccountEpoch: () => 1,sendText: mocks.sendText,replyText: mocks.replyText,openThread: mocks.openThread,diff --git a/packages/lizi-im/src/feishu/__tests__/wsClientConflict.test.ts b/packages/lizi-im/src/feishu/__tests__/wsClientConflict.test.tsindex b192597da0..1e22933e75 100644--- a/packages/lizi-im/src/feishu/__tests__/wsClientConflict.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/wsClientConflict.test.ts@@ -67,6 +67,7 @@ vi.doMock('../outbound.js', () => ({bindClient: mocks.bindClient,unbindClient: mocks.unbindClient,getBoundClient: mocks.getBoundClient,+ getAccountEpoch: () => 1,sendText: mocks.sendText,}));@@ -172,9 +173,11 @@ describe('Feishu WebSocket conflict handling', () => {sdkClient.options.onError?.(new Error('exceed_conn_limit'));- await vi.waitFor(() => expect(wsClient.getCurrentStatus()).toBe('conflict'));+ await vi.waitFor(() => {+ expect(wsClient.getCurrentStatus()).toBe('conflict');+ expect(onConflict).toHaveBeenCalledOnce();+ });expect(sdkClient.close).toHaveBeenCalledWith({ force: true });- expect(onConflict).toHaveBeenCalledOnce();expect(onConflict).toHaveBeenCalledWith({ appId: credentials.appId });} finally {feishuEvents.off('conflict', onConflict);diff --git a/packages/lizi-im/src/feishu/__tests__/wsClientGroup.test.ts b/packages/lizi-im/src/feishu/__tests__/wsClientGroup.test.tsindex 39ca5a6a00..c48b2f6ed3 100644--- a/packages/lizi-im/src/feishu/__tests__/wsClientGroup.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/wsClientGroup.test.ts@@ -90,6 +90,7 @@ vi.doMock('../outbound.js', () => ({bindClient: mocks.bindClient,unbindClient: mocks.unbindClient,getBoundClient: mocks.getBoundClient,+ getAccountEpoch: () => 1,sendText: mocks.sendText,replyText: mocks.replyText,openThread: mocks.openThread,diff --git a/packages/lizi-im/src/feishu/__tests__/wsClientGroupThreadRouting.test.ts b/packages/lizi-im/src/feishu/__tests__/wsClientGroupThreadRouting.test.tsindex f39e6642bc..b85592f1ab 100644--- a/packages/lizi-im/src/feishu/__tests__/wsClientGroupThreadRouting.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/wsClientGroupThreadRouting.test.ts@@ -14,10 +14,15 @@*/import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { pendingTopicLeaseCountForTest, resetDualDeliveryForTest } from '../dualDelivery.js';import { feishuEvents } from '../events.js';import type { IMMessageEvent } from '../../types.js';type EventHandler = (data: unknown) => Promise<unknown> | unknown;+type DownloadResult = {+ attachments: IMMessageEvent['attachments'];+ unsupported: IMMessageEvent['unsupported'];+};const mocks = {options: [] as Array<{ onReady?: () => void }>,@@ -25,7 +30,12 @@ const mocks = {close: vi.fn(),bindClient: vi.fn(),unbindClient: vi.fn(),- getBoundClient: vi.fn(() => null),+ getBoundClient: vi.fn<() => unknown>(() => null),+ downloadAttachments: vi.fn<(...args: unknown[]) => Promise<DownloadResult>>(async () => ({+ attachments: [],+ unsupported: [],+ })),+ getAccountEpoch: vi.fn(() => 1),sendText: vi.fn(async () => ({ messageId: 'om_sent' })),replyText: vi.fn(async () => ({ messageId: 'om_reply' })),// 返回 degraded = 开话题失败(降级回群 lane), 单测按用例覆盖。@@ -37,6 +47,7 @@ const mocks = {| { kind: 'unconfirmed' }>>(async () => ({ kind: 'opened', messageId: 'om_opener', threadId: 'omt_new' })),+ recallOwnMessage: vi.fn(async () => true),evictOpenThreadOutcome: vi.fn(),pushReplyAnchor: vi.fn(),pushPatchableOpener: vi.fn(),@@ -81,13 +92,19 @@ vi.doMock('@larksuiteoapi/node-sdk', () => ({Domain: { Feishu: 'feishu-domain', Lark: 'lark-domain' },}));+vi.doMock('../attachmentDownloader.js', () => ({+ downloadAttachments: mocks.downloadAttachments,+}));+vi.doMock('../outbound.js', () => ({bindClient: mocks.bindClient,unbindClient: mocks.unbindClient,getBoundClient: mocks.getBoundClient,+ getAccountEpoch: mocks.getAccountEpoch,sendText: mocks.sendText,replyText: mocks.replyText,openThread: mocks.openThread,+ recallOwnMessage: mocks.recallOwnMessage,evictOpenThreadOutcome: mocks.evictOpenThreadOutcome,pushReplyAnchor: mocks.pushReplyAnchor,pushPatchableOpener: mocks.pushPatchableOpener,@@ -142,6 +159,15 @@ function groupTopicMessage(text: string, threadId: string): unknown {return raw;}+function groupTopicImageMessage(threadId: string, messageId: string): unknown {+ const raw = groupTopicMessage('unused', threadId) as { message: Record<string, unknown> };+ raw.message.message_id = messageId;+ raw.message.message_type = 'image';+ raw.message.content = JSON.stringify({ image_key: 'img_topic_1' });+ raw.message.create_time = '1788000000001';+ return raw;+}+async function connect(): Promise<void> {wsClient.setBotOpenIdForTest(BOT);const connecting = wsClient.start(credentials, { announceLifecycle: false });@@ -161,17 +187,24 @@ beforeEach(async () => {// message_id。wsClient.resetInboundDedupeForTest();wsClient.resetOrphanRetriesForTest();+ resetDualDeliveryForTest();mocks.options.length = 0;mocks.eventHandlers = {};vi.clearAllMocks();feishuEvents.removeAllListeners('message');mocks.firstAllowed.mockReturnValue(OWNER);mocks.checkOwner.mockImplementation((id: string) => id === OWNER);+ mocks.getBoundClient.mockImplementation(() => null);+ mocks.downloadAttachments.mockImplementation(async () => ({+ attachments: [],+ unsupported: [],+ }));});afterEach(async () => {await wsClient.stop({ announceOffline: false, reason: 'test-cleanup' });wsClient.resetOrphanRetriesForTest();+ resetDualDeliveryForTest();feishuEvents.removeAllListeners('message');vi.useRealTimers();});@@ -182,6 +215,7 @@ beforeAll(async () => {afterAll(() => {vi.doUnmock('@larksuiteoapi/node-sdk');+ vi.doUnmock('../attachmentDownloader.js');vi.doUnmock('../outbound.js');vi.doUnmock('../ownerGuard.js');vi.doUnmock('../storage.js');@@ -243,6 +277,691 @@ describe('feishu group thread routing', () => {expect(events[0].groupContextLane).toBeUndefined();});+ it('勾选同时发送到群聊: 不同 message_id 的话题/群副本只派一个话题 turn', async () => {+ const events = collectMessages();+ await connect();+ const topic = groupTopicMessage('同步回答', 'omt_existing') as {+ message: Record<string, unknown>;+ };+ topic.message.create_time = '1788000000000';+ topic.message.message_id = 'om_topic_copy';+ const flat = groupMainFlowMessage('同步回答', 'om_flat_copy') as {+ message: Record<string, unknown>;+ };+ flat.message.create_time = '1788000000000';++ const flatHandling = mocks.eventHandlers['im.message.receive_v1'](flat);+ await mocks.eventHandlers['im.message.receive_v1'](topic);+ await flatHandling;++ 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();+ });++ it('does not register a reply anchor for a topic delivery that loses the route lease', async () => {+ const events = collectMessages();+ await connect();+ const topicA = groupTopicMessage('同步回答', 'omt_existing') as {+ message: Record<string, unknown>;+ };+ topicA.message.create_time = '1788000000000';+ topicA.message.message_id = 'om_topic_a';+ const topicB = groupTopicMessage('同步回答', 'omt_existing') as {+ message: Record<string, unknown>;+ };+ topicB.message.create_time = '1788000000000';+ topicB.message.message_id = 'om_topic_b';++ await Promise.all([+ mocks.eventHandlers['im.message.receive_v1'](topicA),+ mocks.eventHandlers['im.message.receive_v1'](topicB),+ ]);++ expect(events).toHaveLength(1);+ expect(mocks.pushReplyAnchor).toHaveBeenCalledTimes(1);+ expect(mocks.pushReplyAnchor).toHaveBeenCalledWith(+ 'g/oc_chat1/omt_existing',+ events[0].messageId,+ );+ });++ it('releases the topic lease when a mention-only topic has nothing to relay', async () => {+ const events = collectMessages();+ await connect();+ const empty = groupTopicMessage('@_user_1', 'omt_existing') as {+ message: Record<string, unknown>;+ };+ empty.message.create_time = '1788000000000';+ empty.message.message_id = 'om_empty_mention';++ await mocks.eventHandlers['im.message.receive_v1'](empty);++ expect(events).toHaveLength(0);+ expect(mocks.openThread).not.toHaveBeenCalled();+ expect(pendingTopicLeaseCountForTest()).toBe(0);+ });++ it('abandons the topic lease when the account is replaced during attachment download', async () => {+ const events = collectMessages();+ let releaseDownload: ((value: {+ attachments: IMMessageEvent['attachments'];+ unsupported: IMMessageEvent['unsupported'];+ }) => void) | undefined;+ let downloadStarted!: () => void;+ const started = new Promise<void>((resolve) => {+ downloadStarted = resolve;+ });+ mocks.getBoundClient.mockReturnValue({});+ mocks.downloadAttachments.mockImplementationOnce(() => {+ downloadStarted();+ return new Promise((resolve) => {+ releaseDownload = resolve;+ });+ });+ await connect();+ const handling = mocks.eventHandlers['im.message.receive_v1'](+ groupTopicImageMessage('omt_existing', 'om_topic_img_switch'),+ );+ await started;+ mocks.unbindClient.mockImplementationOnce(() => {+ releaseDownload?.({+ attachments: [+ {+ kind: 'image',+ absPath: '/tmp/cindy-feishu-topic.png',+ originalName: 'topic.png',+ mimeType: 'image/png',+ },+ ],+ unsupported: [],+ });+ });+ await wsClient.stop({+ announceOffline: false,+ reason: 'test-switch-account',+ nextAccount: { appId: 'cli_other_bot', service: 'feishu' },+ });+ await handling;+ wsClient.setBotOpenIdForTest(BOT);+ const connecting = wsClient.start(+ { appId: 'cli_other_bot', appSecret: 'secret', service: 'feishu' },+ { announceLifecycle: false },+ );+ mocks.options.at(-1)?.onReady?.();+ await connecting;++ expect(events).toHaveLength(0);+ expect(pendingTopicLeaseCountForTest()).toBe(0);+ });++ it('abandons the topic lease in the stop/start gap during account replacement', async () => {+ const events = collectMessages();+ let releaseDownload: ((value: {+ attachments: IMMessageEvent['attachments'];+ unsupported: IMMessageEvent['unsupported'];+ }) => void) | undefined;+ let downloadStarted!: () => void;+ const started = new Promise<void>((resolve) => {+ downloadStarted = resolve;+ });+ mocks.getBoundClient.mockReturnValue({});+ mocks.downloadAttachments.mockImplementationOnce(() => {+ downloadStarted();+ return new Promise((resolve) => {+ releaseDownload = resolve;+ });+ });+ await connect();+ const handling = mocks.eventHandlers['im.message.receive_v1'](+ groupTopicImageMessage('omt_existing', 'om_topic_img_switch_gap'),+ );+ await started;+ // unbindClient 位于 stop() 尾部;这里同步放行下载,让旧 handler 恰好在+ // currentBotAppId 已清空、新账号尚未装入的微任务空窗恢复。+ mocks.unbindClient.mockImplementationOnce(() => {+ releaseDownload?.({+ attachments: [+ {+ kind: 'image',+ absPath: '/tmp/cindy-feishu-topic.png',+ originalName: 'topic.png',+ mimeType: 'image/png',+ },+ ],+ unsupported: [],+ });+ });+ wsClient.setBotOpenIdForTest(BOT);+ const connecting = wsClient.start(+ { appId: 'cli_other_bot', appSecret: 'secret', service: 'feishu' },+ { announceLifecycle: false },+ );+ await vi.waitFor(() => expect(mocks.options).toHaveLength(2));+ mocks.options.at(-1)?.onReady?.();+ await connecting;+ await handling;++ expect(events).toHaveLength(0);+ expect(pendingTopicLeaseCountForTest()).toBe(0);+ });++ it('keeps the topic lease across same-account reconnect during attachment download', async () => {+ const events = collectMessages();+ let releaseDownload: ((value: {+ attachments: IMMessageEvent['attachments'];+ unsupported: IMMessageEvent['unsupported'];+ }) => void) | undefined;+ let downloadStarted!: () => void;+ const started = new Promise<void>((resolve) => {+ downloadStarted = resolve;+ });+ mocks.getBoundClient.mockReturnValue({});+ mocks.downloadAttachments.mockImplementationOnce(() => {+ downloadStarted();+ return new Promise((resolve) => {+ releaseDownload = resolve;+ });+ });+ await connect();+ const handling = mocks.eventHandlers['im.message.receive_v1'](+ groupTopicImageMessage('omt_existing', 'om_topic_img_reconnect'),+ );+ await started;+ mocks.unbindClient.mockImplementationOnce(() => {+ releaseDownload?.({+ attachments: [+ {+ kind: 'image',+ absPath: '/tmp/cindy-feishu-topic.png',+ originalName: 'topic.png',+ mimeType: 'image/png',+ },+ ],+ unsupported: [],+ });+ });+ await wsClient.stop({+ announceOffline: false,+ reason: 'test-reconnect',+ nextAccount: credentials,+ });+ await handling;+ await connect();++ expect(events).toHaveLength(0);+ expect(pendingTopicLeaseCountForTest()).toBe(1);+ });++ it('abandons the topic lease when credentials are cleared during attachment download', async () => {+ const events = collectMessages();+ let releaseDownload: ((value: {+ attachments: IMMessageEvent['attachments'];+ unsupported: IMMessageEvent['unsupported'];+ }) => void) | undefined;+ let downloadStarted!: () => void;+ const started = new Promise<void>((resolve) => {+ downloadStarted = resolve;+ });+ mocks.getBoundClient.mockReturnValue({});+ mocks.downloadAttachments.mockImplementationOnce(() => {+ downloadStarted();+ return new Promise((resolve) => {+ releaseDownload = resolve;+ });+ });+ await connect();+ const handling = mocks.eventHandlers['im.message.receive_v1'](+ groupTopicImageMessage('omt_existing', 'om_topic_img_logout'),+ );+ await started;+ mocks.unbindClient.mockImplementationOnce(() => {+ releaseDownload?.({+ attachments: [+ {+ kind: 'image',+ absPath: '/tmp/cindy-feishu-topic.png',+ originalName: 'topic.png',+ mimeType: 'image/png',+ },+ ],+ unsupported: [],+ });+ });+ await wsClient.stop({+ announceOffline: false,+ reason: 'test-credentials-cleared',+ discardPendingTopicLeases: true,+ });+ await handling;++ expect(events).toHaveLength(0);+ expect(pendingTopicLeaseCountForTest()).toBe(0);+ });++ it('late topic after the cache TTL still takes over while the flat route is uncommitted', async () => {+ vi.useFakeTimers();+ let releaseOpenThread: ((value: { kind: 'opened'; messageId: string; threadId: string }) => void) | undefined;+ mocks.openThread.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ releaseOpenThread = resolve;+ }),+ );+ mocks.recallOwnMessage.mockResolvedValue(true);+ const events = collectMessages();+ await connect();+ const topic = groupTopicMessage('迟到话题', 'omt_existing') as {+ message: Record<string, unknown>;+ };+ topic.message.create_time = '1788000000000';+ topic.message.message_id = 'om_topic_late';+ const flat = groupMainFlowMessage('迟到话题', 'om_flat_late') as {+ message: Record<string, unknown>;+ };+ flat.message.create_time = '1788000000000';++ const flatHandling = mocks.eventHandlers['im.message.receive_v1'](flat);+ await vi.advanceTimersByTimeAsync(1_000);+ await vi.advanceTimersByTimeAsync(25_001);+ await mocks.eventHandlers['im.message.receive_v1'](topic);+ expect(releaseOpenThread).toBeDefined();+ releaseOpenThread?.({ kind: 'opened', messageId: 'om_bot_opener', threadId: 'omt_bot' });+ await flatHandling;++ 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();+ });++ it('retries a late-takeover opener recall when Feishu returns a business rejection', async () => {+ vi.useFakeTimers();+ let releaseOpenThread:+ | ((value: { kind: 'opened'; messageId: string; threadId: string }) => void)+ | undefined;+ mocks.openThread+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ releaseOpenThread = resolve;+ }),+ )+ .mockResolvedValueOnce({+ kind: 'opened',+ messageId: 'om_bot_opener_retry',+ threadId: 'omt_bot_retry',+ });+ mocks.recallOwnMessage.mockResolvedValueOnce(false).mockResolvedValueOnce(true);+ const events = collectMessages();+ await connect();+ const topic = groupTopicMessage('迟到话题撤回重试', 'omt_existing') as {+ message: Record<string, unknown>;+ };+ topic.message.create_time = '1788000009000';+ topic.message.message_id = 'om_topic_recall_retry';+ const flat = groupMainFlowMessage('迟到话题撤回重试', 'om_flat_recall_retry') as {+ message: Record<string, unknown>;+ };+ flat.message.create_time = '1788000009000';++ const flatHandling = mocks.eventHandlers['im.message.receive_v1'](flat);+ await vi.advanceTimersByTimeAsync(1_000);+ await mocks.eventHandlers['im.message.receive_v1'](topic);+ expect(releaseOpenThread).toBeDefined();+ releaseOpenThread?.({+ kind: 'opened',+ messageId: 'om_bot_opener_retry',+ threadId: 'omt_bot_retry',+ });+ await flatHandling;++ expect(events).toHaveLength(1);+ expect(events[0]?.senderId).toBe('g/oc_chat1/omt_existing');+ expect(mocks.recallOwnMessage).toHaveBeenCalledTimes(1);+ expect(mocks.recallOwnMessage).toHaveBeenLastCalledWith('om_bot_opener_retry');++ await vi.advanceTimersByTimeAsync(10_000);++ expect(mocks.openThread).toHaveBeenCalledTimes(2);+ expect(mocks.openThread).toHaveBeenLastCalledWith('om_flat_recall_retry');+ expect(mocks.recallOwnMessage).toHaveBeenCalledTimes(2);+ expect(mocks.recallOwnMessage).toHaveBeenLastCalledWith('om_bot_opener_retry');+ expect(events).toHaveLength(1);+ expect(mocks.pushPatchableOpener).not.toHaveBeenCalled();+ });++ it('does not revive a pending takeover recall after credentials are cleared', async () => {+ vi.useFakeTimers();+ let releaseOpenThread:+ | ((value: { kind: 'opened'; messageId: string; threadId: string }) => void)+ | undefined;+ let releaseRecall: ((value: boolean) => void) | undefined;+ mocks.openThread.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ releaseOpenThread = resolve;+ }),+ );+ mocks.recallOwnMessage.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ releaseRecall = resolve;+ }),+ );+ const events = collectMessages();+ await connect();+ const topic = groupTopicMessage('撤回在途时清凭证', 'omt_existing') as {+ message: Record<string, unknown>;+ };+ topic.message.create_time = '1788000010000';+ topic.message.message_id = 'om_topic_clear_during_recall';+ const flat = groupMainFlowMessage('撤回在途时清凭证', 'om_flat_clear_during_recall') as {+ message: Record<string, unknown>;+ };+ flat.message.create_time = '1788000010000';++ const flatHandling = mocks.eventHandlers['im.message.receive_v1'](flat);+ await vi.advanceTimersByTimeAsync(1_000);+ await mocks.eventHandlers['im.message.receive_v1'](topic);+ expect(releaseOpenThread).toBeDefined();+ releaseOpenThread?.({+ kind: 'opened',+ messageId: 'om_bot_clear_during_recall',+ threadId: 'omt_bot_clear_during_recall',+ });+ await Promise.resolve();+ expect(releaseRecall).toBeDefined();++ await wsClient.stop({ announceOffline: false, reason: 'clear-credentials' });+ wsClient.clearOrphanRetriesForCredentialClear();+ releaseRecall?.(false);+ await flatHandling;++ await connect();+ await vi.advanceTimersByTimeAsync(10_000 + 30_000 + 90_000 + 1_000);++ expect(events).toHaveLength(1);+ expect(mocks.openThread).toHaveBeenCalledTimes(1);+ expect(mocks.recallOwnMessage).toHaveBeenCalledTimes(1);+ expect(mocks.pushPatchableOpener).not.toHaveBeenCalled();+ });++ it('committed unpaired flat still mirrors parent chat when a late topic is suppressed', async () => {+ vi.useFakeTimers();+ mocks.openThread.mockResolvedValueOnce({+ kind: 'opened',+ messageId: 'om_bot_committed',+ threadId: 'omt_bot_committed',+ });+ const events = collectMessages();+ await connect();+ const topic = groupTopicMessage('已提交后迟到话题', 'omt_existing') as {+ message: Record<string, unknown>;+ };+ topic.message.create_time = '1788000007000';+ topic.message.message_id = 'om_topic_after_commit';+ const flat = groupMainFlowMessage('已提交后迟到话题', 'om_flat_committed') as {+ message: Record<string, unknown>;+ };+ flat.message.create_time = '1788000007000';++ const flatHandling = mocks.eventHandlers['im.message.receive_v1'](flat);+ await vi.advanceTimersByTimeAsync(1_000);+ await flatHandling;++ 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',+ 'om_bot_committed',+ 'om_flat_committed',+ );++ await mocks.eventHandlers['im.message.receive_v1'](topic);++ expect(events).toHaveLength(1);+ expect(events[0]?.senderId).toBe('g/oc_chat1/omt_bot_committed');+ expect(mocks.recallOwnMessage).not.toHaveBeenCalled();+ vi.useRealTimers();+ });++ it('recovered unconfirmed flat keeps its mirror when the native topic arrives afterward', async () => {+ vi.useFakeTimers();+ mocks.openThread+ .mockResolvedValueOnce({ kind: 'unconfirmed' })+ .mockResolvedValueOnce({+ kind: 'opened',+ messageId: 'om_bot_recovered_committed',+ threadId: 'omt_bot_recovered_committed',+ });+ const events = collectMessages();+ await connect();+ const topic = groupTopicMessage('恢复提交后迟到话题', 'omt_existing') as {+ message: Record<string, unknown>;+ };+ topic.message.create_time = '1788000008000';+ topic.message.message_id = 'om_topic_after_recovered_commit';+ const flat = groupMainFlowMessage(+ '恢复提交后迟到话题',+ 'om_flat_recovered_committed',+ ) as { message: Record<string, unknown> };+ flat.message.create_time = '1788000008000';++ const flatHandling = mocks.eventHandlers['im.message.receive_v1'](flat);+ await vi.advanceTimersByTimeAsync(1_000);+ await flatHandling;+ expect(events).toHaveLength(0);++ await vi.advanceTimersByTimeAsync(10_000);++ 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);++ expect(events).toHaveLength(1);+ expect(mocks.recallOwnMessage).not.toHaveBeenCalled();+ vi.useRealTimers();+ });++ it('orphaned unpaired flat stays takeable so a late topic still dispatches', async () => {+ vi.useFakeTimers();+ mocks.openThread.mockResolvedValueOnce({+ kind: 'orphaned',+ openerMessageId: 'om_orphan_opener',+ });+ const events = collectMessages();+ await connect();+ const topic = groupTopicMessage('孤儿后迟到话题', 'omt_existing') as {+ message: Record<string, unknown>;+ };+ topic.message.create_time = '1788000003000';+ topic.message.message_id = 'om_topic_after_orphan';+ const flat = groupMainFlowMessage('孤儿后迟到话题', 'om_flat_after_orphan') as {+ message: Record<string, unknown>;+ };+ flat.message.create_time = '1788000003000';++ const flatHandling = mocks.eventHandlers['im.message.receive_v1'](flat);+ await vi.advanceTimersByTimeAsync(1_000);+ await flatHandling;++ expect(events).toHaveLength(0);+ expect(mocks.replyText).toHaveBeenCalledWith('om_orphan_opener', expect.any(String));++ await mocks.eventHandlers['im.message.receive_v1'](topic);++ 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();+ });++ it('unconfirmed unpaired flat stays takeable so a late topic still dispatches', async () => {+ vi.useFakeTimers();+ mocks.openThread+ .mockResolvedValueOnce({ kind: 'unconfirmed' })+ .mockResolvedValueOnce({+ kind: 'opened',+ messageId: 'om_recovered_after_unconfirmed',+ threadId: 'omt_bot_unconfirmed',+ });+ mocks.recallOwnMessage.mockResolvedValue(true);+ const events = collectMessages();+ await connect();+ const topic = groupTopicMessage('未确认后迟到话题', 'omt_existing') as {+ message: Record<string, unknown>;+ };+ topic.message.create_time = '1788000005000';+ topic.message.message_id = 'om_topic_after_unconfirmed';+ const flat = groupMainFlowMessage('未确认后迟到话题', 'om_flat_after_unconfirmed') as {+ message: Record<string, unknown>;+ };+ flat.message.create_time = '1788000005000';++ const flatHandling = mocks.eventHandlers['im.message.receive_v1'](flat);+ await vi.advanceTimersByTimeAsync(1_000);+ await flatHandling;++ expect(events).toHaveLength(0);++ await mocks.eventHandlers['im.message.receive_v1'](topic);++ 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);+ expect(mocks.openThread).toHaveBeenCalledTimes(2);+ expect(mocks.recallOwnMessage).toHaveBeenCalledWith('om_recovered_after_unconfirmed');+ expect(events).toHaveLength(1);+ });++ it('late topic takeover during orphaned openThread recalls the opener without a second turn', async () => {+ vi.useFakeTimers();+ let releaseOpenThread: ((value: { kind: 'orphaned'; openerMessageId: string }) => void) | undefined;+ mocks.openThread.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ releaseOpenThread = resolve;+ }),+ );+ mocks.recallOwnMessage.mockResolvedValue(true);+ const events = collectMessages();+ await connect();+ const topic = groupTopicMessage('孤儿途中接管', 'omt_existing') as {+ message: Record<string, unknown>;+ };+ topic.message.create_time = '1788000004000';+ topic.message.message_id = 'om_topic_during_orphan';+ const flat = groupMainFlowMessage('孤儿途中接管', 'om_flat_during_orphan') as {+ message: Record<string, unknown>;+ };+ flat.message.create_time = '1788000004000';++ const flatHandling = mocks.eventHandlers['im.message.receive_v1'](flat);+ await vi.advanceTimersByTimeAsync(1_000);+ await mocks.eventHandlers['im.message.receive_v1'](topic);+ expect(releaseOpenThread).toBeDefined();+ releaseOpenThread?.({ kind: 'orphaned', openerMessageId: 'om_orphan_during' });+ await flatHandling;++ expect(events).toHaveLength(1);+ expect(events[0]?.senderId).toBe('g/oc_chat1/omt_existing');+ expect(mocks.recallOwnMessage).toHaveBeenCalledWith('om_orphan_during');+ expect(mocks.pushPatchableOpener).not.toHaveBeenCalled();+ });++ it('late topic takeover recovers unconfirmed opener uuid and recalls it without a second turn', async () => {+ vi.useFakeTimers();+ let releaseOpenThread: ((value: { kind: 'unconfirmed' }) => void) | undefined;+ mocks.openThread+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ releaseOpenThread = resolve;+ }),+ )+ .mockResolvedValueOnce({+ kind: 'opened',+ messageId: 'om_recovered_opener',+ threadId: 'omt_bot',+ });+ mocks.recallOwnMessage.mockResolvedValue(true);+ const events = collectMessages();+ await connect();+ const topic = groupTopicMessage('迟到话题未确认', 'omt_existing') as {+ message: Record<string, unknown>;+ };+ topic.message.create_time = '1788000001000';+ topic.message.message_id = 'om_topic_late_unconfirmed';+ const flat = groupMainFlowMessage('迟到话题未确认', 'om_flat_late_unconfirmed') as {+ message: Record<string, unknown>;+ };+ flat.message.create_time = '1788000001000';++ const flatHandling = mocks.eventHandlers['im.message.receive_v1'](flat);+ await vi.advanceTimersByTimeAsync(1_000);+ await mocks.eventHandlers['im.message.receive_v1'](topic);+ expect(releaseOpenThread).toBeDefined();+ releaseOpenThread?.({ kind: 'unconfirmed' });+ await flatHandling;++ expect(events).toHaveLength(1);+ expect(events[0].senderId).toBe('g/oc_chat1/omt_existing');+ expect(mocks.recallOwnMessage).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(10_000);+ expect(mocks.openThread).toHaveBeenCalledTimes(2);+ expect(mocks.recallOwnMessage).toHaveBeenCalledWith('om_recovered_opener');+ expect(events).toHaveLength(1);+ expect(mocks.pushPatchableOpener).not.toHaveBeenCalled();+ });+it('开话题失败时降级回群 lane(锚点 = 触发消息)', async () => {mocks.openThread.mockResolvedValueOnce({ kind: 'degraded' });const events = collectMessages();@@ -435,4 +1154,57 @@ describe('feishu group thread routing', () => {expect(mocks.pushReplyAnchor).not.toHaveBeenCalled();vi.useRealTimers();});++ it('openThread 在途换代后不提交双投路由、不用新连接撤回旧开场白', async () => {+ vi.useFakeTimers();+ let resolveOpen!: (value: {+ kind: 'opened';+ messageId: string;+ threadId: string;+ }) => void;+ mocks.openThread.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveOpen = resolve;+ }),+ );+ const events = collectMessages();+ await connect();+ const flat = groupMainFlowMessage('换代中的副本', 'om_flat_stale') as {+ message: Record<string, unknown>;+ };+ flat.message.create_time = '1788000000000';++ const flatHandling = mocks.eventHandlers['im.message.receive_v1'](flat);+ await vi.advanceTimersByTimeAsync(1_000);+ expect(resolveOpen).toBeDefined();++ await wsClient.stop({ announceOffline: false, reason: 'same-account-reconnect' });+ await connect();++ resolveOpen({ kind: 'opened', messageId: 'om_stale_opener', threadId: 'omt_stale' });+ await flatHandling;++ expect(events).toHaveLength(0);+ expect(mocks.recallOwnMessage).not.toHaveBeenCalled();+ expect(mocks.pushPatchableOpener).not.toHaveBeenCalled();++ const topic = groupTopicMessage('换代中的副本', 'omt_existing') as {+ message: Record<string, unknown>;+ };+ topic.message.create_time = '1788000000000';+ topic.message.message_id = 'om_topic_after_reconnect';+ await mocks.eventHandlers['im.message.receive_v1'](topic);++ 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/__tests__/wsClientInboundDedupe.test.ts b/packages/lizi-im/src/feishu/__tests__/wsClientInboundDedupe.test.tsindex 13f65260dd..ca95c4b35f 100644--- a/packages/lizi-im/src/feishu/__tests__/wsClientInboundDedupe.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/wsClientInboundDedupe.test.ts@@ -77,6 +77,7 @@ vi.doMock('../outbound.js', () => ({bindClient: mocks.bindClient,unbindClient: mocks.unbindClient,getBoundClient: mocks.getBoundClient,+ getAccountEpoch: () => 1,sendText: mocks.sendText,replyText: mocks.replyText,openThread: mocks.openThread,diff --git a/packages/lizi-im/src/feishu/dualDelivery.ts b/packages/lizi-im/src/feishu/dualDelivery.tsnew file mode 100644index 0000000000..9952898b9a--- /dev/null+++ b/packages/lizi-im/src/feishu/dualDelivery.ts@@ -0,0 +1,521 @@+import { createHash } from 'node:crypto';++/**+ * Feishu's native “同时发送到群聊” option can deliver one logical user send as+ * 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.+ */++const PAIR_WINDOW_MS = 1_000;+const LATE_COPY_TTL_MS = 25_000;+const CONFIRMED_TTL_MS = 2 * 60 * 60 * 1000;+const MAX_PENDING = 512;+const MAX_RECENT = 1_000;+const MAX_CONFIRMED = 2_000;++interface PendingLogicalSend {+ threadMessageId: string | null;+ flatMessageIds: Set<string>;+ decision: Promise<boolean>;+ resolveDecision: (confirmed: boolean) => void;+ timer: ReturnType<typeof setTimeout>;+ flatLease?: RecentFlatRecord;+}++export interface DualDeliveryInput {+ appId: string;+ chatId: string;+ senderOpenId: string;+ createTime: string;+ messageType: string;+ rawContent: string;+ messageId: string;+ threadId: string;+}++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.+ * `false` means a late topic already claimed the route — recall the+ * bot-created opener and abort instead of emitting.+ */+ commitUnpairedFlat?: () => boolean;+ /**+ * Peek without committing. Orphaned / unconfirmed openers that will not+ * dispatch still need to recall when a late topic already took over.+ */+ isUnpairedFlatTakenOver?: () => boolean;+ /** Release an uncommitted flat route that will never emit an Agent turn. */+ abandonUnpairedFlat?: () => void;+ /**+ * Uncommitted elected-topic routes call this when the Agent event is+ * actually about to emit. `false` means a previous topic delivery already+ * committed — abort instead of starting a second turn.+ */+ commitTopic?: () => boolean;+ /** Release an uncommitted topic route that will never emit an Agent turn. */+ abandonTopic?: () => void;+ }+ | { kind: 'suppress-main-copy' };++interface RecentFlatRecord {+ ts: number;+ state: 'pending' | 'committed' | 'taken-over' | 'abandoned';+}++const pending = new Map<string, PendingLogicalSend>();+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;+ return createHash('sha256')+ .update(input.appId)+ .update('\0')+ .update(input.chatId)+ .update('\0')+ .update(input.senderOpenId)+ .update('\0')+ .update(input.createTime)+ .update('\0')+ .update(input.messageType)+ .update('\0')+ .update(input.rawContent)+ .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);+ }+}++function rememberRecent(map: Map<string, number>, key: string, now: number): void {+ map.delete(key);+ map.set(key, now);+ pruneTtlMap(map, now);+}++function pruneRecentFlats(now: number): void {+ // An uncommitted flat record is a live route lease, not a cache entry. It may+ // outlive the normal late-copy TTL while openThread UUID recovery is still+ // deciding whether this path can emit a turn. Only explicit lifecycle+ // transitions make it eligible for eviction.+ for (const [key, rec] of recentFlats) {+ if (rec.state === 'pending') continue;+ if (now - rec.ts > LATE_COPY_TTL_MS) {+ recentFlats.delete(key);+ dropDeferredMirrors(key);+ }+ }+ if (recentFlats.size <= MAX_RECENT) return;+ for (const [key, rec] of recentFlats) {+ if (recentFlats.size <= MAX_RECENT) break;+ if (rec.state === 'pending') continue;+ recentFlats.delete(key);+ dropDeferredMirrors(key);+ }+}++function rememberRecentFlat(key: string, now: number): RecentFlatRecord {+ const rec: RecentFlatRecord = { ts: now, state: 'pending' };+ recentFlats.delete(key);+ recentFlats.set(key, rec);+ pruneRecentFlats(now);+ return rec;+}++function commitUnpairedFlatRoute(key: string, rec: RecentFlatRecord): boolean {+ if (rec.state === 'taken-over' || rec.state === 'abandoned') return false;+ if (rec.state === 'committed') return true;+ rec.state = 'committed';+ rec.ts = Date.now();+ if (recentFlats.get(key) === rec) {+ recentFlats.delete(key);+ recentFlats.set(key, rec);+ pruneRecentFlats(rec.ts);+ }+ return true;+}++function isUnpairedFlatTakenOver(rec: RecentFlatRecord): boolean {+ return rec.state === 'taken-over';+}++function pruneTopicLeases(now: number): void {+ for (const [key, rec] of topicLeases) {+ if (rec.state === 'pending') continue;+ if (now - rec.ts > LATE_COPY_TTL_MS) topicLeases.delete(key);+ }+ if (topicLeases.size <= MAX_RECENT) return;+ for (const [key, rec] of topicLeases) {+ if (topicLeases.size <= MAX_RECENT) break;+ if (rec.state === 'pending') continue;+ topicLeases.delete(key);+ }+}++function rememberTopicLease(key: string, now: number): RecentFlatRecord {+ const rec: RecentFlatRecord = { ts: now, state: 'pending' };+ topicLeases.delete(key);+ topicLeases.set(key, rec);+ pruneTopicLeases(now);+ return rec;+}++function commitTopicRoute(key: string, rec: RecentFlatRecord): boolean {+ if (rec.state !== 'pending') return false;+ rec.state = 'committed';+ rec.ts = Date.now();+ if (topicLeases.get(key) === rec) {+ topicLeases.delete(key);+ topicLeases.set(key, rec);+ pruneTopicLeases(rec.ts);+ }+ return true;+}++function abandonTopicRoute(key: string, rec: RecentFlatRecord): void {+ if (rec.state !== 'pending') return;+ rec.state = 'abandoned';+ rec.ts = Date.now();+ if (topicLeases.get(key) === rec) {+ topicLeases.delete(key);+ topicLeases.set(key, rec);+ pruneTopicLeases(rec.ts);+ }+}++function topicRouteCallbacks(+ key: string,+ existingLease?: RecentFlatRecord,+): { commitTopic: () => boolean; abandonTopic: () => void } {+ const existing = existingLease ?? topicLeases.get(key);+ // A committed lease must keep suppressing later topic message ids until+ // `confirmPair`. Replacing it with a fresh pending rec would let a second+ // delivery call `commitTopic()` and start another Agent turn.+ const lease =+ existing?.state === 'pending' || existing?.state === 'committed'+ ? existing+ : rememberTopicLease(key, Date.now());+ return {+ commitTopic: () => commitTopicRoute(key, lease),+ abandonTopic: () => abandonTopicRoute(key, lease),+ };+}++function abandonUnpairedFlatRoute(key: string, rec: RecentFlatRecord): void {+ if (rec.state !== 'pending') return;+ rec.state = 'abandoned';+ rec.ts = Date.now();+ if (recentFlats.get(key) === rec) {+ recentFlats.delete(key);+ 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'> = {},+): DualDeliveryDecision {+ return {+ kind: 'dispatch',+ mirrorKey: key,+ ...(confirmed.has(key) ? { alreadyConfirmed: true } : {}),+ ...extra,+ };+}++function settleUnpairedPending(key: string, entry: PendingLogicalSend): void {+ const now = Date.now();+ if (entry.threadMessageId) rememberRecent(recentThreads, key, now);+ else if (entry.flatMessageIds.size > 0) entry.flatLease = rememberRecentFlat(key, now);+ entry.resolveDecision(false);+}++function prunePending(): void {+ while (pending.size > MAX_PENDING) {+ const oldestKey = pending.keys().next().value;+ if (typeof oldestKey !== 'string') break;+ const entry = pending.get(oldestKey);+ pending.delete(oldestKey);+ if (entry) {+ clearTimeout(entry.timer);+ settleUnpairedPending(oldestKey, entry);+ }+ }+}++function createPending(key: string): PendingLogicalSend {+ let resolveDecision!: (confirmed: boolean) => void;+ const decision = new Promise<boolean>((resolve) => {+ resolveDecision = resolve;+ });+ const entry: PendingLogicalSend = {+ threadMessageId: null,+ flatMessageIds: new Set(),+ decision,+ resolveDecision,+ timer: setTimeout(() => {+ if (pending.get(key) !== entry) return;+ pending.delete(key);+ settleUnpairedPending(key, entry);+ }, PAIR_WINDOW_MS),+ };+ pending.set(key, entry);+ prunePending();+ return entry;+}++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 {+ if (pending.get(key) === entry) pending.delete(key);+ clearTimeout(entry.timer);+ const now = Date.now();+ // Topic already dispatched. Keep a recent-thread tombstone so a later+ // distinct-id main-feed copy cannot mint a second pending/Agent turn after+ // `pending` is deleted. `confirmed` is the durable suppress key; the+ // tombstone is consumed by the first extra flat like other late copies.+ if (entry.threadMessageId) rememberRecent(recentThreads, key, now);+ confirmLogicalSend(key, now);+ entry.resolveDecision(true);+}++export async function coordinateDualDelivery(+ input: DualDeliveryInput,+): Promise<DualDeliveryDecision> {+ const key = logicalSendKey(input);+ if (!key) return { kind: 'dispatch' };++ const now = Date.now();+ pruneTtlMap(recentThreads, now);+ pruneRecentFlats(now);+ pruneTopicLeases(now);+ pruneConfirmed(now);+ // Once a logical send has paired, later flats are duplicates even when+ // Feishu assigns a fresh message_id. An elected topic that never committed+ // (inbound claim abandon / reconnect retry) must still be allowed to emit.+ if (confirmed.has(key)) {+ if (input.threadId) {+ const lease = topicLeases.get(key);+ if (lease?.state === 'pending') {+ return dispatchWithMirror(key, topicRouteCallbacks(key, lease));+ }+ }+ return { kind: 'suppress-main-copy' };+ }+ if (input.threadId && topicLeases.get(key)?.state === 'committed') {+ return { kind: 'suppress-main-copy' };+ }+ if (!input.threadId && recentThreads.has(key)) {+ recentThreads.delete(key);+ confirmLogicalSend(key, now);+ return { kind: 'suppress-main-copy' };+ }+ const recentFlat = recentFlats.get(key);+ if (input.threadId && recentFlat) {+ if (recentFlat.state === 'committed' || recentFlat.state === 'taken-over') {+ confirmLogicalSend(key, now);+ rememberRecent(recentThreads, key, now);+ return { kind: 'suppress-main-copy' };+ }+ recentFlat.state = 'taken-over';+ recentFlat.ts = now;+ recentFlats.delete(key);+ recentFlats.set(key, recentFlat);+ confirmLogicalSend(key, now);+ rememberRecent(recentThreads, key, now);+ return dispatchWithMirror(key, topicRouteCallbacks(key));+ }+ if (!input.threadId && recentFlat) {+ if (recentFlat.state === 'abandoned') {+ recentFlats.delete(key);+ } else {+ // A live or committed flat route already owns this logical send. Feishu+ // retries normally keep the same message id and are stopped upstream, but+ // a second flat id must not mint a parallel route lease here.+ return { kind: 'suppress-main-copy' };+ }+ }++ let entry = pending.get(key);+ if (!entry) entry = createPending(key);++ if (input.threadId) {+ entry.threadMessageId ??= input.messageId;+ if (entry.flatMessageIds.size > 0) confirmPair(key, entry);+ // Topic input is always the preferred Agent route and must not wait. A flat+ // 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));+ }++ entry.flatMessageIds.add(input.messageId);+ if (entry.threadMessageId && entry.threadMessageId !== input.messageId) {+ confirmPair(key, entry);+ return { kind: 'suppress-main-copy' };+ }++ if (await entry.decision) return { kind: 'suppress-main-copy' };+ if (entry.flatMessageIds.values().next().value !== input.messageId) {+ return { kind: 'suppress-main-copy' };+ }+ const lease = entry.flatLease;+ return lease+ ? dispatchWithMirror(key, {+ 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);+}++/** Test-only: pending elected-topic leases that pruneTopicLeases will not expire. */+export function pendingTopicLeaseCountForTest(): number {+ let count = 0;+ for (const rec of topicLeases.values()) {+ if (rec.state === 'pending') count += 1;+ }+ return count;+}++/** Test-only reset. Production state intentionally survives transport reconnects. */+export function resetDualDeliveryForTest(): void {+ for (const entry of pending.values()) {+ clearTimeout(entry.timer);+ entry.resolveDecision(false);+ }+ pending.clear();+ recentThreads.clear();+ 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 821f01b5ea..294999c70e 100644--- a/packages/lizi-im/src/feishu/index.ts+++ b/packages/lizi-im/src/feishu/index.ts@@ -20,6 +20,7 @@ import type { ChannelIM } from '../channelIM.js';import type {IMHost,IMCardActionEvent,+ IMFinalReplyMirror,IMMessageEvent,IMStatus,InteractiveCardSpec,@@ -35,6 +36,7 @@ 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';@@ -363,6 +365,7 @@ export class FeishuIM extends BaseIM implements ChannelIM {await wsClient.stop({offlineTimeoutMs: wsClient.QUIT_OFFLINE_ANNOUNCE_TIMEOUT_MS,reason: 'transport-dispose',+ discardPendingTopicLeases: true,});}@@ -431,10 +434,43 @@ export class FeishuIM extends BaseIM implements ChannelIM {);}- startStreamingText(userId: string, initial?: string): Promise<StreamingTextHandle> {+ startStreamingText(+ userId: string,+ initial?: string,+ ): Promise<StreamingTextHandle> {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/ipc.ts b/packages/lizi-im/src/feishu/ipc.tsindex abd3f7caa9..edfb7b7903 100644--- a/packages/lizi-im/src/feishu/ipc.ts+++ b/packages/lizi-im/src/feishu/ipc.ts@@ -214,6 +214,7 @@ export async function saveAndConnect(await wsClient.stop({reason: 'credentials-replaced',clearOwnerBeforeIdle: saved?.appId !== appId || saved.service !== service,+ nextAccount: { appId, service },});if (options.replacementOwnerOpenId) {persistReplacementOwner(options.replacementOwnerOpenId);@@ -241,7 +242,11 @@ export async function reconnectSavedCredentials(): Promise<{if (!creds) {throw new Error('[NO_CREDENTIALS] IM bot credentials are not configured');}- await wsClient.stop({ announceOffline: false, reason: 'manual-reconnect' });+ await wsClient.stop({+ announceOffline: false,+ reason: 'manual-reconnect',+ nextAccount: { appId: creds.appId, service: creds.service },+ });const verdict = await wsClient.start(creds, {announceLifecycle: false,reason: 'manual-reconnect',@@ -387,6 +392,7 @@ export async function clearAndDisconnect(): Promise<void> {await wsClient.stop({reason: 'credentials-cleared',clearOwnerBeforeIdle: true,+ discardPendingTopicLeases: true,});// 逻辑凭证清除(而非 transport 重连): 清掉账号态并重置 lastBoundCreds —// 之后重新保存相同 appId/service 不会被误判为同账号重连, 登出前的diff --git a/packages/lizi-im/src/feishu/outbound.ts b/packages/lizi-im/src/feishu/outbound.tsindex 4b22290d3b..e9f64aee54 100644--- a/packages/lizi-im/src/feishu/outbound.ts+++ b/packages/lizi-im/src/feishu/outbound.ts@@ -18,7 +18,10 @@* `img` elements directly.*/+import { AsyncLocalStorage } from 'node:async_hooks';+import { spawn } from 'node:child_process';import fs from 'node:fs';+import { open as openFile, type FileHandle } from 'node:fs/promises';import path from 'node:path';import * as Lark from '@larksuiteoapi/node-sdk';@@ -40,6 +43,303 @@ import type { BotCredentials } from './internal-types.js';const FEISHU_FILE_SIZE_LIMIT = 30 * 1024 * 1024;/** 10 MB per image when sending as `msg_type:image`. */const FEISHU_IMAGE_MAX_BYTES = 10 * 1024 * 1024;+const HANDLE_PATH_HELPER_TIMEOUT_MS = 5_000;+const HANDLE_PATH_HELPER_MAX_BYTES = 256 * 1024;++/**+ * Windows does not expose a `/proc/self/fd` equivalent to Node. The helper gets+ * the already-open file as stdin, then asks the kernel for that inherited+ * handle's final path. It never accepts an Agent-controlled path argument.+ */+const WINDOWS_HANDLE_PATH_SCRIPT = String.raw`+$utf8 = [System.Text.UTF8Encoding]::new($false)+[Console]::OutputEncoding = $utf8+Add-Type -TypeDefinition @'+using System;+using System.Text;+using System.Runtime.InteropServices;+public static class CindyHandlePath {+ [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]+ public static extern uint GetFinalPathNameByHandle(IntPtr handle, StringBuilder path, uint size, uint flags);+ [DllImport("kernel32.dll")]+ public static extern IntPtr GetStdHandle(int kind);+}+'@+$handle = [CindyHandlePath]::GetStdHandle(-10)+$path = New-Object System.Text.StringBuilder 32768+$length = [CindyHandlePath]::GetFinalPathNameByHandle($handle, $path, $path.Capacity, 0)+if ($length -eq 0 -or $length -ge $path.Capacity) { exit 1 }+[Console]::Out.Write($path.ToString())+`;+const WINDOWS_HANDLE_PATH_COMMAND = Buffer.from(+ WINDOWS_HANDLE_PATH_SCRIPT,+ 'utf16le',+).toString('base64');++/**+ * Prove that an already-open source handle is reachable from an already-open+ * directory handle without resolving any Agent-controlled absolute path. Each+ * component is opened relative to the previous handle with reparse traversal+ * disabled; the final native file identity must equal the source handle.+ */+const WINDOWS_HANDLE_CONTAINMENT_SCRIPT = String.raw`+$utf8 = [System.Text.UTF8Encoding]::new($false)+[Console]::OutputEncoding = $utf8+Add-Type -TypeDefinition @'+using System;+using System.Collections.Generic;+using System.Runtime.InteropServices;+using Microsoft.Win32.SafeHandles;++public static class CindyHandleContainment {+ private const uint FILE_READ_ATTRIBUTES = 0x00000080;+ private const uint SYNCHRONIZE = 0x00100000;+ private const uint FILE_SHARE_ALL = 0x00000007;+ private const uint FILE_SHARE_READ_WRITE = 0x00000003;+ private const uint FILE_OPEN = 0x00000001;+ private const uint FILE_DIRECTORY_FILE = 0x00000001;+ private const uint FILE_NON_DIRECTORY_FILE = 0x00000040;+ private const uint FILE_SYNCHRONOUS_IO_NONALERT = 0x00000020;+ private const uint FILE_OPEN_REPARSE_POINT = 0x00200000;+ private const uint FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400;++ [StructLayout(LayoutKind.Sequential)]+ private struct UNICODE_STRING {+ public ushort Length;+ public ushort MaximumLength;+ public IntPtr Buffer;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct OBJECT_ATTRIBUTES {+ public int Length;+ public IntPtr RootDirectory;+ public IntPtr ObjectName;+ public uint Attributes;+ public IntPtr SecurityDescriptor;+ public IntPtr SecurityQualityOfService;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct IO_STATUS_BLOCK {+ public IntPtr Status;+ public IntPtr Information;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct FILE_ATTRIBUTE_TAG_INFO {+ public uint FileAttributes;+ public uint ReparseTag;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct BY_HANDLE_FILE_INFORMATION {+ public uint FileAttributes;+ public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime;+ public System.Runtime.InteropServices.ComTypes.FILETIME LastAccessTime;+ public System.Runtime.InteropServices.ComTypes.FILETIME LastWriteTime;+ public uint VolumeSerialNumber;+ public uint FileSizeHigh;+ public uint FileSizeLow;+ public uint NumberOfLinks;+ public uint FileIndexHigh;+ public uint FileIndexLow;+ }++ [DllImport("kernel32.dll")]+ private static extern IntPtr GetStdHandle(int kind);++ [DllImport("kernel32.dll", SetLastError=true)]+ private static extern bool GetFileInformationByHandle(+ IntPtr handle,+ out BY_HANDLE_FILE_INFORMATION info+ );++ [DllImport("kernel32.dll", SetLastError=true)]+ private static extern bool GetFileInformationByHandleEx(+ IntPtr handle,+ int infoClass,+ out FILE_ATTRIBUTE_TAG_INFO info,+ uint size+ );++ [DllImport("ntdll.dll")]+ private static extern int NtCreateFile(+ out SafeFileHandle fileHandle,+ uint desiredAccess,+ ref OBJECT_ATTRIBUTES objectAttributes,+ out IO_STATUS_BLOCK ioStatusBlock,+ IntPtr allocationSize,+ uint fileAttributes,+ uint shareAccess,+ uint createDisposition,+ uint createOptions,+ IntPtr eaBuffer,+ uint eaLength+ );++ private static SafeFileHandle OpenRelative(IntPtr root, string name, bool directory) {+ IntPtr nameBuffer = IntPtr.Zero;+ IntPtr unicodePointer = IntPtr.Zero;+ try {+ nameBuffer = Marshal.StringToHGlobalUni(name);+ var unicode = new UNICODE_STRING {+ Length = checked((ushort)(name.Length * 2)),+ MaximumLength = checked((ushort)((name.Length + 1) * 2)),+ Buffer = nameBuffer+ };+ unicodePointer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UNICODE_STRING)));+ Marshal.StructureToPtr(unicode, unicodePointer, false);+ var attributes = new OBJECT_ATTRIBUTES {+ Length = Marshal.SizeOf(typeof(OBJECT_ATTRIBUTES)),+ RootDirectory = root,+ ObjectName = unicodePointer,+ Attributes = 0,+ SecurityDescriptor = IntPtr.Zero,+ SecurityQualityOfService = IntPtr.Zero+ };+ IO_STATUS_BLOCK statusBlock;+ SafeFileHandle opened;+ uint options = FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_REPARSE_POINT |+ (directory ? FILE_DIRECTORY_FILE : FILE_NON_DIRECTORY_FILE);+ int status = NtCreateFile(+ out opened,+ FILE_READ_ATTRIBUTES | SYNCHRONIZE,+ ref attributes,+ out statusBlock,+ IntPtr.Zero,+ 0,+ directory ? FILE_SHARE_READ_WRITE : FILE_SHARE_ALL,+ FILE_OPEN,+ options,+ IntPtr.Zero,+ 0+ );+ if (status < 0 || opened == null || opened.IsInvalid) {+ if (opened != null) opened.Dispose();+ return null;+ }+ FILE_ATTRIBUTE_TAG_INFO tag;+ if (!GetFileInformationByHandleEx(+ opened.DangerousGetHandle(),+ 9,+ out tag,+ (uint)Marshal.SizeOf(typeof(FILE_ATTRIBUTE_TAG_INFO))) ||+ (tag.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) {+ opened.Dispose();+ return null;+ }+ return opened;+ } catch {+ return null;+ } finally {+ if (unicodePointer != IntPtr.Zero) Marshal.FreeHGlobal(unicodePointer);+ if (nameBuffer != IntPtr.Zero) Marshal.FreeHGlobal(nameBuffer);+ }+ }++ private static bool SameFile(IntPtr left, IntPtr right) {+ BY_HANDLE_FILE_INFORMATION a;+ BY_HANDLE_FILE_INFORMATION b;+ if (!GetFileInformationByHandle(left, out a) || !GetFileInformationByHandle(right, out b)) {+ return false;+ }+ if (a.FileIndexHigh == 0 && a.FileIndexLow == 0) return false;+ if (b.FileIndexHigh == 0 && b.FileIndexLow == 0) return false;+ return a.VolumeSerialNumber == b.VolumeSerialNumber &&+ a.FileIndexHigh == b.FileIndexHigh &&+ a.FileIndexLow == b.FileIndexLow;+ }++ public static bool Check(string[] segments) {+ if (segments == null || segments.Length == 0) return false;+ IntPtr root = GetStdHandle(-10);+ IntPtr source = GetStdHandle(-12);+ if (root == IntPtr.Zero || root == new IntPtr(-1) ||+ source == IntPtr.Zero || source == new IntPtr(-1)) return false;++ var opened = new List<SafeFileHandle>();+ try {+ IntPtr parent = root;+ for (int i = 0; i < segments.Length; i++) {+ string segment = segments[i];+ if (String.IsNullOrEmpty(segment) || segment == "." || segment == ".." ||+ segment.IndexOf('\0') >= 0 || segment.IndexOf('\\') >= 0 ||+ segment.IndexOf('/') >= 0 || segment.IndexOf(':') >= 0) return false;+ SafeFileHandle next = OpenRelative(parent, segment, i < segments.Length - 1);+ if (next == null) return false;+ opened.Add(next);+ parent = next.DangerousGetHandle();+ }+ return opened.Count > 0 && SameFile(opened[opened.Count - 1].DangerousGetHandle(), source);+ } finally {+ for (int i = opened.Count - 1; i >= 0; i--) opened[i].Dispose();+ }+ }+}+'@+try {+ $json = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($env:CINDY_HANDLE_SEGMENTS))+ $segments = @((ConvertFrom-Json -InputObject $json))+ if ([CindyHandleContainment]::Check([string[]]$segments)) {+ [Console]::Out.Write('1')+ exit 0+ }+} catch {}+exit 1+`;+const WINDOWS_HANDLE_CONTAINMENT_COMMAND = Buffer.from(+ WINDOWS_HANDLE_CONTAINMENT_SCRIPT,+ 'utf16le',+).toString('base64');++/**+ * Darwin `/dev/fd` is fdescfs: `chdir("/dev/fd/N")` is ENOTDIR even when N is+ * a directory fd. Walk with `openat` from the inherited root handle instead.+ */+const DARWIN_HANDLE_CONTAINMENT_SCRIPT = String.raw`+use strict;+use warnings;+use Fcntl qw(O_RDONLY O_NONBLOCK O_DIRECTORY O_NOFOLLOW :mode);++use constant SYS_openat => 463;++sub fail_closed { exit 1; }++my @segments = @ARGV;+fail_closed() unless @segments;+for my $segment (@segments) {+ fail_closed() if !defined($segment) || $segment eq '' || $segment eq '.' ||+ $segment eq '..' || index($segment, '/') >= 0 || index($segment, "\0") >= 0;+}++my @source = stat(STDERR);+fail_closed() unless @source && S_ISREG($source[2]) && $source[1] != 0;+my $parent = fileno(STDIN);+fail_closed() unless defined $parent && $parent >= 0;++my @opened;+for (my $index = 0; $index < @segments; $index += 1) {+ my $directory = $index < @segments - 1;+ my $flags = O_RDONLY | O_NOFOLLOW | O_NONBLOCK;+ $flags |= O_DIRECTORY if $directory;+ my $fd = syscall(SYS_openat, $parent, $segments[$index], $flags, 0);+ fail_closed() if !defined($fd) || $fd < 0;+ open(my $handle, '<&=', $fd) or fail_closed();+ push @opened, $handle;+ my @opened_stat = stat($handle);+ fail_closed() unless @opened_stat;+ if ($directory) {+ fail_closed() unless S_ISDIR($opened_stat[2]);+ $parent = $fd;+ } else {+ fail_closed() unless S_ISREG($opened_stat[2]) && $opened_stat[1] != 0 &&+ $opened_stat[0] == $source[0] && $opened_stat[1] == $source[1];+ }+}++print STDOUT '1';+`;let client: Lark.Client | null = null;let creds: BotCredentials | null = null;@@ -354,6 +654,7 @@ async function createMessage(target: SendTarget,msgType: string,content: string,+ uuid?: string,): Promise<{ messageId: string }> {const c = ensureClient();if (target.kind === 'reply') {@@ -372,7 +673,7 @@ async function createMessage(}const res = await c.im.v1.message.create({params: { receive_id_type: target.kind },- data: { receive_id: target.id, msg_type: msgType, content },+ data: { receive_id: target.id, msg_type: msgType, content, ...(uuid ? { uuid } : {}) },});const id = res.data?.message_id ?? '';if (!id) throw new Error('[feishu/outbound] create: no message_id in response');@@ -397,7 +698,38 @@ export function getBoundCreds(): BotCredentials | null {return creds;}+interface PinnedAccount {+ client: Lark.Client;+ epoch: number;+}++const pinnedAccount = new AsyncLocalStorage<PinnedAccount>();++/** Run outbound work against the client captured at schedule time. */+export function runWithPinnedAccount<T>(+ pin: PinnedAccount,+ fn: () => Promise<T> | T,+): Promise<T> | T {+ return pinnedAccount.run(pin, fn);+}++/** `true` when no pin is active, or the pin still matches the current account epoch. */+export function isPinnedAccountCurrent(): boolean {+ const pin = pinnedAccount.getStore();+ if (!pin) return true;+ return pin.epoch === accountEpoch;+}+function ensureClient(): Lark.Client {+ const pin = pinnedAccount.getStore();+ if (pin) {+ if (pin.epoch !== accountEpoch) {+ throw new Error(+ '[feishu/outbound] pinned Feishu account was replaced — send aborted',+ );+ }+ return pin.client;+ }if (!client)throw new Error('[feishu/outbound] Lark.Client not bound — feishu connection not established');return client;@@ -843,6 +1175,20 @@ export async function sendCardRaw();}+/** Send a terminal-output mirror directly to a parent group main timeline. */+export async function sendCardToChat(+ chatId: string,+ cardJson: unknown,+ uuid: string,+): Promise<{ messageId: string }> {+ return createMessage(+ { kind: 'chat_id', id: chatId },+ 'interactive',+ JSON.stringify(cardJson),+ uuid,+ );+}+// ── file send ────────────────────────────────────────────────────────────────const FEISHU_IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp']);@@ -864,42 +1210,439 @@ function inferFeishuFileType(return 'stream';}+/** A Feishu upload reference that can be sent again without reading the source file. */+export interface ReusableFeishuFileMessage {+ msgType: 'file' | 'image';+ content: string;+}++export interface FeishuUploadedFileSource {+ realPath: string;+ /** Exact decimal identities; strings avoid truncating 64-bit Windows file IDs. */+ dev: string;+ ino: string;+ /**+ * Compatibility-only diagnostic. Parent-chat authorization ignores caller-+ * supplied ancestry and walks from the live pinned root handle instead.+ */+ ancestors: ReadonlyArray<{ dev: string; ino: string }>;+}++export interface FeishuSendFileResult extends SendFileResult {+ reusableMessage?: ReusableFeishuFileMessage;+ /** Identity of the bytes that were uploaded; authorizes parent-chat key reuse. */+ uploadedSource?: FeishuUploadedFileSource;+}+export async function sendFile(userId: string,absPath: string,displayName?: string,+): Promise<FeishuSendFileResult> {+ const target = resolveSendTarget(userId);+ if (!target) {+ getLog().error(`[feishu/outbound] sendFile: no reply anchor for topic lane ...${userId.slice(-8)}`);+ return { ok: false, reason: 'SEND_FAIL' };+ }+ return sendFileToTarget(target, absPath, displayName);+}++/** Re-send an already uploaded terminal-output file to a parent group main timeline. */+export async function sendFileToChat(+ chatId: string,+ message: ReusableFeishuFileMessage,+ uuid: string,): Promise<SendFileResult> {- const log = getLog();+ try {+ const res = await createMessage(+ { kind: 'chat_id', id: chatId },+ message.msgType,+ message.content,+ uuid,+ );+ return { ok: true, messageId: res.messageId };+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ getLog().error(`[feishu/outbound] sendFileToChat SEND_FAIL: ${msg}`);+ return { ok: false, reason: 'SEND_FAIL' };+ }+}++interface OutboundFileSource {+ absPath: string;+ size: number;+ createReadStream(): fs.ReadStream;+}++function isSyntheticFdPath(resolved: string): boolean {+ const normalized = resolved.replaceAll('\\', '/');+ return /(?:^|\/)(?:proc\/self\/fd|dev\/fd)\/\d+$/.test(normalized);+}++function realPathIfInode(+ candidate: string,+ identity: { dev: string; ino: string },+): string | null {+ try {+ const realPath = fs.realpathSync.native(candidate);+ if (isSyntheticFdPath(realPath)) return null;+ const leaf = fs.statSync(realPath, { bigint: true });+ if (String(leaf.dev) === identity.dev && String(leaf.ino) === identity.ino) return realPath;+ } catch {+ /* candidate no longer names this inode */+ }+ return null;+}++function runHandlePathHelper(+ command: string,+ args: readonly string[],+ stdin: number | 'ignore',+ stderr: number | 'ignore' = 'ignore',+ env?: NodeJS.ProcessEnv,+): Promise<Buffer | null> {+ return new Promise((resolve) => {+ let child: ReturnType<typeof spawn>;+ try {+ child = spawn(command, args, {+ stdio: [stdin, 'pipe', stderr],+ windowsHide: true,+ ...(env ? { env } : {}),+ });+ } catch {+ resolve(null);+ return;+ }++ let settled = false;+ const finish = (value: Buffer | null): void => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ resolve(value);+ };+ const chunks: Buffer[] = [];+ let total = 0;+ child.stdout?.on('data', (chunk: Buffer | string) => {+ const next = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);+ total += next.length;+ if (total > HANDLE_PATH_HELPER_MAX_BYTES) {+ child.stdout?.destroy();+ child.kill();+ finish(null);+ return;+ }+ chunks.push(next);+ });+ child.once('error', () => finish(null));+ child.once('close', (code) => finish(code === 0 ? Buffer.concat(chunks) : null));++ const timer = setTimeout(() => {+ child.stdout?.destroy();+ child.kill();+ finish(null);+ }, HANDLE_PATH_HELPER_TIMEOUT_MS);+ timer.unref?.();+ });+}++function windowsPowerShellPath(): string | null {+ const systemRoot = process.env.SystemRoot ?? process.env.WINDIR;+ if (!systemRoot || !path.win32.isAbsolute(systemRoot)) return null;+ const executable = path.win32.join(+ systemRoot,+ 'System32',+ 'WindowsPowerShell',+ 'v1.0',+ 'powershell.exe',+ );+ try {+ return fs.statSync(executable).isFile() ? executable : null;+ } catch {+ return null;+ }+}++function normalizeWindowsHandlePath(raw: string): string | null {+ const value = raw.replace(/^\uFEFF/, '');+ if (!value || /[\0\r\n]/.test(value)) return null;+ const extendedPrefix = '\\\\?\\';+ if (!value.startsWith(extendedPrefix)) return null;+ const unprefixed = value.slice(extendedPrefix.length);+ if (unprefixed.startsWith('UNC\\')) return `\\\\${unprefixed.slice(4)}`;+ return /^[A-Za-z]:\\/.test(unprefixed) ? unprefixed : null;+}++async function windowsHandlePath(fd: number): Promise<string | null> {+ const powershell = windowsPowerShellPath();+ if (!powershell) return null;+ const output = await runHandlePathHelper(+ powershell,+ ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', WINDOWS_HANDLE_PATH_COMMAND],+ fd,+ );+ return output ? normalizeWindowsHandlePath(output.toString('utf8')) : null;+}++function decodeLsofFileName(raw: string): string {+ if (!raw.includes('\\')) return raw;+ const bytes: number[] = [];+ for (let i = 0; i < raw.length; ) {+ if (raw.startsWith('\\x', i) && /^[0-9a-fA-F]{2}/.test(raw.slice(i + 2, i + 4))) {+ bytes.push(Number.parseInt(raw.slice(i + 2, i + 4), 16));+ i += 4;+ continue;+ }+ const code = raw.charCodeAt(i);+ if (code > 255) {+ bytes.push(...Buffer.from(raw[i]!, 'utf8'));+ } else {+ bytes.push(code);+ }+ i += 1;+ }+ return Buffer.from(bytes).toString('utf8');+}++async function darwinHandlePath(fd: number): Promise<string | null> {+ const output = await runHandlePathHelper(+ '/usr/sbin/lsof',+ ['-w', '-a', '-p', String(process.pid), '-d', String(fd), '-F0n'],+ 'ignore',+ 'ignore',+ { ...process.env, LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8' },+ );+ if (!output) return null;+ for (const rawField of output.toString('utf8').split('\0')) {+ const field = rawField.startsWith('\n') ? rawField.slice(1) : rawField;+ if (field.startsWith('n') && field.length > 1) {+ return decodeLsofFileName(field.slice(1));+ }+ }+ return null;+}++/**+ * Native canonical path for the opened handle. A later lookup of `absPath` is+ * a separate operation that can be retargeted. Linux binds through procfs;+ * macOS asks `lsof` for the live vnode path; Windows passes the opened handle+ * to a fixed PowerShell/GetFinalPathNameByHandle helper. Any unavailable or+ * unverifiable helper fails closed.+ */+export async function attestedRealPath(+ fd: number,+ identity: { dev: string; ino: string },+): Promise<string> {+ const candidate =+ process.platform === 'linux'+ ? `/proc/self/fd/${fd}`+ : process.platform === 'darwin'+ ? await darwinHandlePath(fd)+ : process.platform === 'win32'+ ? await windowsHandlePath(fd)+ : null;+ return candidate ? (realPathIfInode(candidate, identity) ?? '') : '';+}++function validContainmentSegments(segments: readonly string[]): boolean {+ if (segments.length === 0) return false;+ return segments.every(+ (segment) =>+ segment.length > 0 &&+ segment !== '.' &&+ segment !== '..' &&+ !segment.includes('\0') &&+ !segment.includes('/'),+ );+}++function sameOpenFile(leftFd: number, rightFd: number): boolean {+ try {+ const left = fs.fstatSync(leftFd, { bigint: true });+ const right = fs.fstatSync(rightFd, { bigint: true });+ if (!left.isFile() || !right.isFile() || left.ino === 0n || right.ino === 0n) return false;+ return left.dev === right.dev && left.ino === right.ino;+ } catch {+ return false;+ }+}++function linuxHandleContainment(+ sourceFd: number,+ rootFd: number,+ segments: readonly string[],+): boolean {+ if (!fs.constants.O_NOFOLLOW || !validContainmentSegments(segments)) return false;+ const opened: number[] = [];+ let parentFd = rootFd;+ try {+ for (let index = 0; index < segments.length; index += 1) {+ const directory = index < segments.length - 1;+ let flags = fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW;+ if (fs.constants.O_NONBLOCK) flags |= fs.constants.O_NONBLOCK;+ if (directory && fs.constants.O_DIRECTORY) flags |= fs.constants.O_DIRECTORY;+ const fd = fs.openSync(`/proc/self/fd/${parentFd}/${segments[index]}`, flags);+ opened.push(fd);+ const stat = fs.fstatSync(fd, { bigint: true });+ if (directory) {+ if (!stat.isDirectory()) return false;+ parentFd = fd;+ } else if (!sameOpenFile(fd, sourceFd)) {+ return false;+ }+ }+ return true;+ } catch {+ return false;+ } finally {+ for (const fd of opened.reverse()) {+ try {+ fs.closeSync(fd);+ } catch {+ /* best-effort close */+ }+ }+ }+}++async function windowsHandleContainment(+ sourceFd: number,+ rootFd: number,+ segments: readonly string[],+): Promise<boolean> {+ if (!validContainmentSegments(segments) || segments.some((segment) => segment.includes('\\'))) {+ return false;+ }+ const powershell = windowsPowerShellPath();+ if (!powershell) return false;+ const encodedSegments = Buffer.from(JSON.stringify(segments), 'utf8').toString('base64');+ const output = await runHandlePathHelper(+ powershell,+ [+ '-NoLogo',+ '-NoProfile',+ '-NonInteractive',+ '-EncodedCommand',+ WINDOWS_HANDLE_CONTAINMENT_COMMAND,+ ],+ rootFd,+ sourceFd,+ { ...process.env, CINDY_HANDLE_SEGMENTS: encodedSegments },+ );+ return output?.toString('utf8') === '1';+}++async function darwinHandleContainment(+ sourceFd: number,+ rootFd: number,+ segments: readonly string[],+): Promise<boolean> {+ if (!validContainmentSegments(segments)) return false;+ const output = await runHandlePathHelper(+ '/usr/bin/perl',+ ['-e', DARWIN_HANDLE_CONTAINMENT_SCRIPT, '--', ...segments],+ rootFd,+ sourceFd,+ {},+ );+ return output?.toString('utf8') === '1';+}++/**+ * Object-chain containment proof. `sourceFd` and `rootFd` stay open throughout+ * the check; every child is opened relative to the preceding directory handle+ * with symlink/reparse traversal disabled, then the final handle is compared+ * to `sourceFd`. No absolute path is re-resolved by the helper.+ */+export async function attestOpenFileWithinDirectory(+ sourceFd: number,+ rootFd: number,+ segments: readonly string[],+): Promise<boolean> {+ if (process.platform === 'linux') {+ return linuxHandleContainment(sourceFd, rootFd, segments);+ }+ if (process.platform === 'darwin') {+ return darwinHandleContainment(sourceFd, rootFd, segments);+ }+ if (process.platform === 'win32') {+ return windowsHandleContainment(sourceFd, rootFd, segments);+ }+ return false;+}++async function sendFileToTarget(+ target: SendTarget,+ absPath: string,+ displayName?: string,+ uuid?: string,+): Promise<FeishuSendFileResult> {const c = ensureClient();- const baseName = path.basename(absPath);- const showName = displayName?.length ? displayName : baseName;- if (!fs.existsSync(absPath)) return { ok: false, reason: 'NOT_FOUND' };- const stat = fs.statSync(absPath);- if (stat.size === 0) return { ok: false, reason: 'EMPTY' };- if (stat.size > FEISHU_FILE_SIZE_LIMIT) return { ok: false, reason: 'TOO_LARGE' };+ let handle: FileHandle;+ try {+ handle = await openFile(absPath, 'r');+ } catch {+ return { ok: false, reason: 'NOT_FOUND' };+ }- const target = resolveSendTarget(userId);- if (!target) {- log.error(`[feishu/outbound] sendFile: no reply anchor for topic lane ...${userId.slice(-8)}`);- return { ok: false, reason: 'SEND_FAIL' };+ try {+ const stat = await handle.stat({ bigint: true });+ const identity = { dev: String(stat.dev), ino: String(stat.ino) };+ const realPath = await attestedRealPath(handle.fd, identity);+ const result = await sendFileSourceToTarget(+ c,+ target,+ {+ absPath,+ size: Number(stat.size),+ createReadStream: () => handle.createReadStream({ autoClose: false }),+ },+ displayName,+ uuid,+ );+ if (result.ok) {+ result.uploadedSource = {+ realPath,+ ...identity,+ ancestors: [],+ };+ }+ return result;+ } finally {+ await handle.close().catch(() => undefined);}+}++async function sendFileSourceToTarget(+ c: Lark.Client,+ target: SendTarget,+ source: OutboundFileSource,+ displayName?: string,+ uuid?: string,+): Promise<FeishuSendFileResult> {+ const log = getLog();+ const baseName = path.basename(source.absPath);+ const showName = displayName?.length ? displayName : baseName;++ if (source.size === 0) return { ok: false, reason: 'EMPTY' };+ if (source.size > FEISHU_FILE_SIZE_LIMIT) return { ok: false, reason: 'TOO_LARGE' };// Image fast-path: if the file is a feishu-supported image type and within// the image-msg size cap, send as msg_type:image so it previews inline.- if (isFeishuImageExt(absPath) && stat.size <= FEISHU_IMAGE_MAX_BYTES) {- return sendImageMessage(c, target, absPath);+ if (isFeishuImageExt(source.absPath) && source.size <= FEISHU_IMAGE_MAX_BYTES) {+ return sendImageMessage(c, target, source.createReadStream, uuid);}// 1. Upload to obtain file_key.let fileKey: string;try {- const fileType = inferFeishuFileType(absPath);+ const fileType = inferFeishuFileType(source.absPath);const res = await c.im.file.create({data: {file_type: fileType,file_name: showName,- file: fs.createReadStream(absPath),+ file: source.createReadStream(),},});const key = (res as { file_key?: string } | null)?.file_key;@@ -913,8 +1656,13 @@ export async function sendFile(// 2. Send message referencing file_key.try {- const res = await createMessage(target, 'file', JSON.stringify({ file_key: fileKey }));- return { ok: true, messageId: res.messageId };+ const content = JSON.stringify({ file_key: fileKey });+ const res = await createMessage(target, 'file', content, uuid);+ return {+ ok: true,+ messageId: res.messageId,+ reusableMessage: { msgType: 'file', content },+ };} catch (err) {const msg = err instanceof Error ? err.message : String(err);log.error(`[feishu/outbound] sendFile SEND_FAIL: ${msg}`);@@ -1166,21 +1914,27 @@ export async function getChatName(chatId: string): Promise<string | null> {async function sendImageMessage(c: Lark.Client,target: SendTarget,- absPath: string,-): Promise<SendFileResult> {+ createReadStream: () => fs.ReadStream,+ uuid?: string,+): Promise<FeishuSendFileResult> {const log = getLog();try {const upRes = await c.im.v1.image.create({data: {image_type: 'message',- image: fs.createReadStream(absPath),+ image: createReadStream(),},});const imageKey = (upRes as { image_key?: string }).image_key;if (!imageKey) return { ok: false, reason: 'UPLOAD_FAIL' };- const res = await createMessage(target, 'image', JSON.stringify({ image_key: imageKey }));- return { ok: true, messageId: res.messageId };+ const content = JSON.stringify({ image_key: imageKey });+ const res = await createMessage(target, 'image', content, uuid);+ return {+ ok: true,+ messageId: res.messageId,+ reusableMessage: { msgType: 'image', content },+ };} catch (err) {const msg = err instanceof Error ? err.message : String(err);log.error(`[feishu/outbound] sendImageMessage failed: ${msg}`);diff --git a/packages/lizi-im/src/feishu/streamingText.ts b/packages/lizi-im/src/feishu/streamingText.tsindex bafdc02946..ef3e48c59a 100644--- a/packages/lizi-im/src/feishu/streamingText.ts+++ b/packages/lizi-im/src/feishu/streamingText.ts@@ -24,23 +24,43 @@* `[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 { getLog } from './moduleScope.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 { StreamingTextHandle } from '../types.js';+import type { IMFinalReplyMirror, StreamingTextHandle } from '../types.js';// xdt-* 引用解析抽到渠道无关模块(slack streamingText 共用同一套语义)import {stripXdtForStreaming,classifyXdtOnly,stripXdtFileLinks,+ stripXdtImageLinks,collectXdtFileLinks,collectXdtImageUrls,} from '../xdtRefs.js';@@ -81,6 +101,158 @@ 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) => {+ try {+ return await uploadImage(absPath);+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ getLog().warn(`[feishu/streamingText] uploadImage extra ${absPath} failed: ${msg}`);+ return null;+ }+ }),+ );+ const keys: string[] = [];+ for (const key of results) {+ if (key) keys.push(key);+ }+ return 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;@@ -128,7 +300,10 @@ class FeishuStreamingTextHandle implements StreamingTextHandle {}, PATCH_THROTTLE_MS);}- async finalize(finalText: string): Promise<void> {+ async finalize(+ finalText: string,+ opts?: { finalReplyMirror?: IMFinalReplyMirror },+ ): Promise<void> {if (this.finalized) return;this.finalized = true;if (this.pending) {@@ -143,7 +318,14 @@ class FeishuStreamingTextHandle implements StreamingTextHandle {}}this.buffer = finalText;- await this.doFinalize();+ const mirror = opts?.finalReplyMirror;+ try {+ await this.doFinalize(mirror);+ } finally {+ if (mirror?.kind === 'parent-chat') {+ releaseMirrorConfirmation(mirror.idempotencyKey);+ }+ }}close(): void {@@ -200,7 +382,7 @@ class FeishuStreamingTextHandle implements StreamingTextHandle {// ── finalize: upload images, send files, patch with mixed elements ────────- private async doFinalize(): Promise<void> {+ private async doFinalize(finalReplyMirror?: IMFinalReplyMirror): Promise<void> {const log = getLog();const text = this.buffer;@@ -220,8 +402,6 @@ class FeishuStreamingTextHandle implements StreamingTextHandle {// uploadImage takes an absPath, so we resolve here.// cindy-media(媒体总仓新地址)优先走 host 注入的解析回调;老// xdt-image 仍走 feishu 专属目录解析。- const { resolveFeishuMediaUrl } = await import('./mediaCache.js');- const { getHost } = await import('./moduleScope.js');let absPath: string;try {const hostResolved = getHost().media?.resolveMediaUrl(url) ?? null;@@ -236,8 +416,14 @@ class FeishuStreamingTextHandle implements StreamingTextHandle {return null;}bodyImageAbsPaths.add(absPath);- const key = await uploadImage(absPath);- return key ? ([url, key] as const) : null;+ try {+ const key = await uploadImage(absPath);+ return key ? ([url, key] as const) : null;+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ log.warn(`[feishu/streamingText] uploadImage ${absPath} failed: ${msg}`);+ return null;+ }}),);for (const r of results) {@@ -249,46 +435,48 @@ class FeishuStreamingTextHandle implements StreamingTextHandle {// 同一条 uploadImage 通道, 但 path 由 host 主进程已经解好直接传 absPath,// 这里不再过 resolveFeishuMediaUrl (@cindy/im 包对其它 host namespace 不感知)。// 正文里已内联的同图(按 absPath)跳过,防"正文一张 + 尾部一张"双份。- const extraImageKeys: string[] = [];const extrasToUpload = this.extraImageAbsPaths.filter((p) => !bodyImageAbsPaths.has(p));if (extrasToUpload.length > 0) {log.debug(`[feishu/streamingText] uploading ${extrasToUpload.length} extra image(s) from tool_result`,);- const results = await Promise.all(- extrasToUpload.map(async (absPath) => {- try {- return await uploadImage(absPath);- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- log.warn(- `[feishu/streamingText] uploadImage extra ${absPath} failed: ${msg}`,- );- return null;- }- }),- );- for (const k of results) {- if (k) extraImageKeys.push(k);- }}+ const extraImageKeys = await uploadExtraImageKeys(extrasToUpload);// 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)`);- await Promise.all(- fileLinks.map(async (link) => {+ const results = await Promise.all(+ fileLinks.map(async (link, sourceIndex) => {try {- await sendFile(this.openId, link.absPath, link.alt || undefined);+ 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 };+ }} 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).@@ -301,9 +489,12 @@ class FeishuStreamingTextHandle implements StreamingTextHandle {// c) empty text + only files → "🎉 N 个文件已送达" placeholder// 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 (cardTextTrimmed.length === 0 && !hasAnyImage && fileLinks.length > 0) {+ if (fileOnly) {card = buildMarkdownCardV2(transportMessages.streaming.fileSentDone(fileLinks.length));} else if (hasAnyImage) {// 文本空但有图(画完图没说话) — 不要在图上面塞 "(空回复)" 占位, 让图自己说话。@@ -318,9 +509,47 @@ 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;@@ -337,8 +566,71 @@ 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);+ }}export async function start(@@ -348,7 +640,9 @@ export async function start(// 群主流 @ 开话题时, 开场白卡就是本轮流式卡(openThread 已用它开好话题) —// 认领后直接 patch, 不再新建一条「开个话题」占位回复。const claimed = claimPatchableOpener(openId);- if (claimed) return new FeishuStreamingTextHandle(claimed, openId, initial);+ if (claimed) {+ return new FeishuStreamingTextHandle(claimed, openId, initial);+ }const { messageId } = await sendCardRaw(openId, buildMarkdownCardV2(initial));return new FeishuStreamingTextHandle(messageId, openId, initial);}@@ -360,3 +654,185 @@ 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 9730a981a5..03b50a834a 100644--- a/packages/lizi-im/src/feishu/wsClient.ts+++ b/packages/lizi-im/src/feishu/wsClient.ts@@ -57,11 +57,15 @@ import * as storage from './storage.js';import { parseIncoming } from './incomingContent.js';import { downloadAttachments } from './attachmentDownloader.js';import { parseCardAction } from './cardActionParser.js';-import { encodeLaneUserId } from './codec.js';+import { decodeLaneUserId, encodeLaneUserId } from './codec.js';+import {+ coordinateDualDelivery,+ resetDualDeliveryForTest,+} from './dualDelivery.js';import { getLog } from './moduleScope.js';import { messages as transportMessages } from './messages.js';import type { BotCredentials, FeishuConnectionStatus } from './internal-types.js';-import type { IMMessageEvent } from '../types.js';+import type { IMFinalReplyMirror, IMMessageEvent } from '../types.js';// ── module state ──────────────────────────────────────────────────────────────@@ -70,6 +74,13 @@ let detector: ConflictDetector | null = null;let currentBotAppId: string | null = null;/** 当前连接的 service(feishu/lark)— 账号边界含 service, 同名 appId 也不可串。 */let currentService: BotCredentials['service'] | null = null;+/**+ * start() 等待旧连接 stop() 时即发布下一账号身份。旧入站 await 若在+ * currentBotAppId 已清空、新账号尚未装入的空窗恢复,仍能区分同账号重连与换号。+ */+let pendingStartAccount: Pick<BotCredentials, 'appId' | 'service'> | null = null;+/** Latest connection generation invalidated by an explicit logical logout/shutdown. */+let topicLeaseDiscardThroughGeneration = 0;let currentStatus: FeishuConnectionStatus = 'idle';let acceptingInbound = false;let lifecycleGeneration = 0;@@ -258,16 +269,44 @@ interface UnconfirmedOpenRetry {replyContext?: NonNullable<IMMessageEvent['replyContext']>;raw: RawMessageEvent;attempt: number;+ /** 迟到话题已接管路由: 只恢复 UUID 并撤回开场白, 不再派 turn。 */+ recallOnly?: boolean;+ /** 未配对群副本: 恢复链真正要派 turn 时才提交路由。 */+ 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);+ retry.abandonUnpairedFlat?.();}unconfirmedOpenRetries.clear();+ for (const retry of suspendedUnconfirmedOpens) retry.abandonUnpairedFlat?.();suspendedUnconfirmedOpens.length = 0;}@@ -294,11 +333,46 @@ function resumeUnconfirmedOpenRetriesFor(for (let i = suspendedUnconfirmedOpens.length - 1; i >= 0; i--) {const entry = suspendedUnconfirmedOpens[i]!;suspendedUnconfirmedOpens.splice(i, 1);- if (entry.botAppId !== botAppId || entry.service !== service) continue;+ if (entry.botAppId !== botAppId || entry.service !== service) {+ entry.abandonUnpairedFlat?.();+ continue;+ }scheduleUnconfirmedOpenRetry(entry);}}+async function recallRecoveredOpener(+ messageId: string,+ kind: 'opened' | 'orphaned',+): Promise<boolean> {+ const log = getLog();+ try {+ const recalled = await outbound.recallOwnMessage(messageId);+ if (!recalled) {+ log.warn(+ `[feishu/wsClient] recall ${kind} opener after late topic takeover was rejected (non-fatal)`,+ );+ }+ return recalled;+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ log.warn(+ `[feishu/wsClient] recall ${kind} opener after late topic takeover failed (non-fatal): ${msg}`,+ );+ return false;+ }+}++function scheduleTakeoverRecallRetry(entry: UnconfirmedOpenRetry, epoch: number): void {+ if (orphanRetryEpoch !== epoch) {+ getLog().info(+ '[feishu/wsClient] late-takeover opener recall stale after credential clear — dropping retry',+ );+ return;+ }+ scheduleUnconfirmedOpenRetry({ ...entry, timer: undefined, recallOnly: true });+}+function scheduleUnconfirmedOpenRetry(entry: UnconfirmedOpenRetry): void {const delay = ORPHAN_NOTICE_RETRY_DELAYS_MS[entry.attempt];if (delay === undefined) {@@ -331,6 +405,7 @@ async function retryUnconfirmedOpen((currentBotAppId !== entry.botAppId || currentService !== entry.service);if (accountChanged) {log.info('[feishu/wsClient] unconfirmed openThread retry skipped: account changed');+ entry.abandonUnpairedFlat?.();return;}suspendUnconfirmedOpenRetry({ ...entry, timer: undefined });@@ -338,7 +413,10 @@ async function retryUnconfirmedOpen(return;}const opener = await outbound.openThread(entry.messageId);- if (orphanRetryEpoch !== epoch) return;+ if (orphanRetryEpoch !== epoch) {+ entry.abandonUnpairedFlat?.();+ return;+ }// saveAndConnect 的普通换账号只 stop/start, 不推进 orphanRetryEpoch —// await 后必须再核当前 bot, 否则会把 A 的 opener/turn 写进 B 的 outbound。if (!isSameBotActive(entry.botAppId, entry.service)) {@@ -347,6 +425,7 @@ async function retryUnconfirmedOpen((currentBotAppId !== entry.botAppId || currentService !== entry.service);if (accountChanged) {log.info('[feishu/wsClient] unconfirmed openThread dropped after await: account changed');+ entry.abandonUnpairedFlat?.();return;}suspendUnconfirmedOpenRetry({ ...entry, timer: undefined });@@ -358,6 +437,16 @@ async function retryUnconfirmedOpen(return;}if (opener.kind === 'orphaned') {+ if (entry.recallOnly || entry.isUnpairedFlatTakenOver?.()) {+ const recalled = await recallRecoveredOpener(opener.openerMessageId, 'orphaned');+ if (!recalled) {+ scheduleTakeoverRecallRetry(+ { ...entry, attempt: entry.attempt + 1 },+ epoch,+ );+ }+ return;+ }log.error(`[feishu/wsClient] unconfirmed openThread recovered as orphaned opener=...${opener.openerMessageId.slice(-8)}`,);@@ -367,11 +456,22 @@ async function retryUnconfirmedOpen(entry.messageId,opener.openerMessageId,);+ entry.abandonUnpairedFlat?.();return;}let laneUserId: string;let groupContextLane: { chatId: string; threadId: string } | undefined;if (opener.kind === 'opened') {+ if (entry.recallOnly || (entry.commitUnpairedFlat && !entry.commitUnpairedFlat())) {+ const recalled = await recallRecoveredOpener(opener.messageId, 'opened');+ if (!recalled) {+ scheduleTakeoverRecallRetry(+ { ...entry, attempt: entry.attempt + 1 },+ epoch,+ );+ }+ return;+ }laneUserId = encodeLaneUserId(entry.chatId, opener.threadId);outbound.pushReplyAnchor(laneUserId, opener.messageId);outbound.pushPatchableOpener(laneUserId, opener.messageId, entry.messageId);@@ -388,6 +488,12 @@ 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,@@ -397,6 +503,7 @@ 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,@@ -449,6 +556,28 @@ function isSameBotActive(botAppId: string, service: BotCredentials['service']):return acceptingInbound && currentBotAppId === botAppId && currentService === service;}+/**+ * 入站 await 恢复时是否应放弃 topic lease。明确登出/销毁会按 connection+ * generation 永久作废旧 lease;transport 重连则保留。账号替换的 stop/start+ * 空窗优先比较待启动账号,同账号保留、跨账号放弃。否则+ * pruneTopicLeases 永久跳过 pending, 反复换号会让 Map 无界增长, 切回旧账号+ * 还能沿旧 lease 起 turn。+ */+function shouldAbandonTopicLease(+ botAppId: string,+ service: BotCredentials['service'],+ generation: number,+): boolean {+ if (generation <= topicLeaseDiscardThroughGeneration) return true;+ if (pendingStartAccount) {+ return pendingStartAccount.appId !== botAppId || pendingStartAccount.service !== service;+ }+ return (+ currentBotAppId !== null &&+ (currentBotAppId !== botAppId || currentService !== service)+ );+}+/*** 该 opener 当前**正在执行**的提示发送(in-flight 去重)。重试的 timer 条目* 在 setTimeout 回调里先删后发 — 仅凭 orphanNoticeRetries 看不到执行中的@@ -762,6 +891,7 @@ function abandonInboundTurn(botAppId: string, messageId: string): void {/** 测试注入口 — 生产代码不要调用(生产语义就是跨 stop/start 不清空)。 */export function resetInboundDedupeForTest(): void {seenInboundMessages.clear();+ resetDualDeliveryForTest();}const DEFAULT_OFFLINE_ANNOUNCE_TIMEOUT_MS = 1500;@@ -982,17 +1112,26 @@ export async function start(log.info(`[feishu/wsClient] start requested reason=${opts.reason ?? 'unspecified'} announceLifecycle=${opts.announceLifecycle === false ? 'no' : 'yes'}`,);- if (client) {- await stop({- announceOffline: opts.announceLifecycle !== false,- reason: `${opts.reason ?? 'start'}:replace-existing-client`,- });+ const pendingAccount = { appId: creds.appId, service: creds.service };+ pendingStartAccount = pendingAccount;+ try {+ if (client) {+ await stop({+ announceOffline: opts.announceLifecycle !== false,+ reason: `${opts.reason ?? 'start'}:replace-existing-client`,+ });+ }+ } catch (err) {+ if (pendingStartAccount === pendingAccount) pendingStartAccount = null;+ throw err;}const startedGeneration = ++lifecycleGeneration;acceptingInbound = true;currentBotAppId = creds.appId;currentService = creds.service;+ // 并发 start 时只清自己的标记,不覆盖更新一轮已经发布的待启动身份。+ if (pendingStartAccount === pendingAccount) pendingStartAccount = null;setStatus('testing');const startDetector = new ConflictDetector({@@ -1103,11 +1242,40 @@ interface StopOptions {announceOffline?: boolean;/** Clear the owner after any offline notice, before broadcasting idle. */clearOwnerBeforeIdle?: boolean;+ /** Publish the account that will start immediately after this stop completes. */+ nextAccount?: Pick<BotCredentials, 'appId' | 'service'>;+ /** Logical logout/shutdown: old in-flight topic leases must never survive. */+ discardPendingTopicLeases?: boolean;reason?: string;}export async function stop(opts: StopOptions = {}): Promise<void> {+ const pendingAccount = opts.nextAccount+ ? { appId: opts.nextAccount.appId, service: opts.nextAccount.service }+ : null;+ if (opts.discardPendingTopicLeases) {+ // Explicit logout wins over any stale replacement intent.+ pendingStartAccount = null;+ } else if (pendingAccount) {+ pendingStartAccount = pendingAccount;+ }+ try {+ await stopCurrentClient(opts);+ } catch (err) {+ if (pendingAccount && pendingStartAccount === pendingAccount) pendingStartAccount = null;+ throw err;+ }+}++async function stopCurrentClient(opts: StopOptions): Promise<void> {const log = getLog();+ const stoppedGeneration = lifecycleGeneration;+ if (opts.discardPendingTopicLeases) {+ topicLeaseDiscardThroughGeneration = Math.max(+ topicLeaseDiscardThroughGeneration,+ stoppedGeneration,+ );+ }// Close the logical ingress gate before awaiting the offline announcement.// Lark may still deliver callbacks while stop is waiting on network I/O;// those callbacks must never reach account-scoped host state after logout.@@ -1251,6 +1419,7 @@ interface RawMessageEvent {message_id?: string;root_id?: string;parent_id?: string;+ create_time?: string;chat_id?: string;thread_id?: string;chat_type?: string;@@ -1330,8 +1499,6 @@ async function handleIncomingMessage(const senderOpenId = data.sender.sender_id?.open_id;const messageId = data.message.message_id;const chatId = data.message.chat_id;- const msgType = data.message.message_type ?? '';- const rawContent = data.message.content ?? '';if (!senderOpenId || !messageId || !chatId) return;// 重推闸门 —— 必须在第一个 await 之前同步认领(见 claimInboundMessage), 也必须@@ -1379,6 +1546,13 @@ 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;+ let commitTopic: (() => boolean) | undefined;+ let abandonTopic: (() => void) | undefined;if (isGroup) {// 没 @ 到本 bot 的群消息一律丢(bot open_id 未知时也丢 — 惰性失效)。if (!mentionsSelf(data.message?.mentions, botOpenId)) return;@@ -1401,6 +1575,31 @@ async function processClaimedMessage(}return;}++ const createTime = data.message?.create_time ?? '';+ if (createTime) {+ const paired = await coordinateDualDelivery({+ appId: botAppId,+ chatId,+ senderOpenId,+ createTime,+ messageType: msgType,+ rawContent,+ messageId,+ threadId: data.message?.thread_id ?? '',+ });+ if (paired.kind === 'suppress-main-copy') {+ 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;+ commitTopic = paired.commitTopic;+ abandonTopic = paired.abandonTopic;+ }} else {// TOFU: first p2p sender becomes owner. Send welcome and continue// processing this very message (so the user's first ask isn't lost).@@ -1460,6 +1659,8 @@ async function processClaimedMessage(// Drop entirely only when there's literally nothing to relay.if (!text && attachments.length === 0 && unsupported.length === 0) {+ abandonUnpairedFlat?.();+ abandonTopic?.();return;}@@ -1481,6 +1682,8 @@ async function processClaimedMessage(abandonInboundTurn(botAppId, messageId);}log.info('[feishu/wsClient] drop inbound message: connection changed during processing');+ abandonUnpairedFlat?.();+ if (shouldAbandonTopicLease(botAppId, service, generation)) abandonTopic?.();return;}@@ -1492,6 +1695,13 @@ async function processClaimedMessage(let groupContextLane: { chatId: string; threadId: string } | undefined;if (isGroup) {if (incomingThreadId) {+ // Commit before the FIFO reply-anchor: two topic deliveries of the same+ // logical send can both pass the coordinator while the lease is pending.+ // The loser must not enqueue an anchor that a later streaming reply would claim.+ if (commitTopic && !commitTopic()) {+ log.info('[feishu/wsClient] elected topic aborted: another topic delivery already committed');+ return;+ }laneUserId = encodeLaneUserId(chatId, incomingThreadId);outbound.pushReplyAnchor(laneUserId, messageId);} else {@@ -1501,8 +1711,9 @@ async function processClaimedMessage(// 会话(用户感知: 不管在哪问, 工作目录都是绑定那个项目)。要跟接管会话// 说话就在那个话题里说。const opener = await outbound.openThread(messageId);- // 开话题是一次跨网络的 await — 期间用户可能断开/换账号: 复查门禁,- // 防止旧连接的锚点与事件漏进新连接(或已停机的编排状态)。+ // 开话题是一次跨网络的 await — 期间用户可能断开/换账号: 先复查门禁,+ // 再提交双投路由或撤回 opener。失效连接不得改跨重连保留的 dual-delivery+ // 状态, 也不得用新绑定的 client 去撤回旧连接发出的消息。if (!isActiveConnection(generation, botAppId)) {// 同上: stop() 已释放认领时不重复释放; 记账还在才 abandon(释放 +// evict 开话题缓存, 让重推在新连接上用新客户端重试 API)。@@ -1510,32 +1721,70 @@ async function processClaimedMessage(abandonInboundTurn(botAppId, messageId);}log.info('[feishu/wsClient] drop group message: connection changed while opening thread');+ abandonUnpairedFlat?.();+ if (shouldAbandonTopicLease(botAppId, service, generation)) abandonTopic?.();return;}- if (opener.kind === 'opened') {- laneUserId = encodeLaneUserId(chatId, opener.threadId);- outbound.pushReplyAnchor(laneUserId, opener.messageId);- // 开场白卡是本轮流式卡: streamingText.start 认领后直接 patch,- // 话题里不会多出一条占位消息。trigger 一并登记 — patch 失败撤回- // 开场白卡时锚点回拨到触发消息(reply_in_thread 落回话题)。- outbound.pushPatchableOpener(laneUserId, opener.messageId, messageId);- // 上下文取数 lane 与路由 lane 分离: 新话题是空的, 群历史前缀仍按- // 触发时所在的群主流拉取(「总结上面」等依赖上文的消息才能拿到- // 群主流历史), 由 host adapter 消费(IMMessageEvent.groupContextLane)。- groupContextLane = { chatId, threadId: '' };- } else if (opener.kind === 'orphaned') {+ // 孤儿开场白不会派发副本 turn: 先 peek 是否已被迟到话题接管, 再决定+ // 撤回或发故障提示。不要 commitUnpairedFlat — 提交会让迟到窗口内的+ // 真实话题被抑制, 用户请求整轮丢掉。+ if (opener.kind === 'orphaned') {+ if (isUnpairedFlatTakenOver?.()) {+ log.info('[feishu/wsClient] unpaired flat aborted: late topic took over routing');+ const recallEpoch = orphanRetryEpoch;+ const recalled = await recallRecoveredOpener(opener.openerMessageId, 'orphaned');+ if (!recalled) {+ scheduleTakeoverRecallRetry(+ {+ botAppId,+ service,+ messageId,+ chatId,+ senderOpenId,+ text,+ attachments,+ unsupported,+ raw: data,+ attempt: 0,+ recallOnly: true,+ },+ recallEpoch,+ );+ }+ return;+ }// 开场白卡已发出但话题 id 恢复失败、撤回也失败: 降级群 lane 会一边// 留着「思考中」的开场白卡、一边把回答刷进群主流。不起 turn, 回复- // 开场白(落回话题)说明失败 — 宁可丢一轮, 不误导 + 不刷屏。+ // 开场白(落回话题)说明失败 — 宁可丢一轮, 不误导 + 不刷屏。迟到话题+ // 仍可在 LATE_COPY_TTL 内接管这条尚未提交的路由。log.error(`[feishu/wsClient] openThread orphaned opener=...${opener.openerMessageId.slice(-8)} — turn dropped with in-topic notice`,);await sendOrphanOpenerNotice(botAppId, service, messageId, opener.openerMessageId);+ abandonUnpairedFlat?.();return;- } else if (opener.kind === 'unconfirmed') {+ }+ if (opener.kind === 'unconfirmed') {// 三次即时 uuid 重试仍无回执: 服务端可能已发出思考卡。事件会在 3s- // 内 ACK, 不能指望平台重投。不释放认领、不降级群主流, 改走 ACK 后- // 定时再用同一 uuid 取回 — 恢复 turn 或 orphan 收口。+ // 内 ACK, 不能指望平台重投。不释放认领、不降级群主流, 也不提交副本+ // 路由 — unconfirmed 还没派 turn, 迟到话题仍可在 LATE_COPY_TTL 内接管。+ if (isUnpairedFlatTakenOver?.()) {+ log.info('[feishu/wsClient] unpaired flat aborted: late topic took over routing');+ scheduleUnconfirmedOpenRetry({+ botAppId,+ service,+ messageId,+ chatId,+ senderOpenId,+ text,+ attachments,+ unsupported,+ raw: data,+ attempt: 0,+ recallOnly: true,+ });+ return;+ }log.error('[feishu/wsClient] openThread reply unconfirmed — scheduling delayed uuid recovery, not degrading',);@@ -1551,8 +1800,58 @@ async function processClaimedMessage(...(resolvedReply ? { replyContext: resolvedReply.replyContext } : {}),raw: data,attempt: 0,+ commitUnpairedFlat,+ isUnpairedFlatTakenOver,+ abandonUnpairedFlat,+ ...(finalReplyMirrorKey+ ? {+ mirrorKey: finalReplyMirrorKey,+ mirrorAccountEpoch: outbound.getAccountEpoch(),+ ...(finalReplyMirrorConfirmed ? { mirrorConfirmed: true } : {}),+ }+ : {}),});return;+ }+ // 仍是本连接: 迟到的真实话题可能已经接管本轮路由, 不再把回答落进这份+ // 群主流副本刚建的机器人话题。只在即将派发副本 turn 时提交。+ if (commitUnpairedFlat && !commitUnpairedFlat()) {+ log.info('[feishu/wsClient] unpaired flat aborted: late topic took over routing');+ if (opener.kind === 'opened') {+ const recallEpoch = orphanRetryEpoch;+ const recalled = await recallRecoveredOpener(opener.messageId, 'opened');+ if (!recalled) {+ scheduleTakeoverRecallRetry(+ {+ botAppId,+ service,+ messageId,+ chatId,+ senderOpenId,+ text,+ attachments,+ unsupported,+ raw: data,+ attempt: 0,+ recallOnly: true,+ },+ recallEpoch,+ );+ }+ }+ return;+ }+ if (opener.kind === 'opened') {+ laneUserId = encodeLaneUserId(chatId, opener.threadId);+ outbound.pushReplyAnchor(laneUserId, opener.messageId);+ // 开场白卡是本轮流式卡: streamingText.start 认领后直接 patch,+ // 话题里不会多出一条占位消息。trigger 一并登记 — patch 失败撤回+ // 开场白卡时锚点回拨到触发消息(reply_in_thread 落回话题)。+ outbound.pushPatchableOpener(laneUserId, opener.messageId, messageId);+ // 上下文取数 lane 与路由 lane 分离: 新话题是空的, 群历史前缀仍按+ // 触发时所在的群主流拉取(「总结上面」等依赖上文的消息才能拿到+ // 群主流历史), 由 host adapter 消费(IMMessageEvent.groupContextLane)。+ groupContextLane = { chatId, threadId: '' };} else {laneUserId = encodeLaneUserId(chatId, null);outbound.pushReplyAnchor(laneUserId, messageId);@@ -1562,6 +1861,14 @@ 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,@@ -1577,6 +1884,7 @@ 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 9ede48c670..ed5718b0c0 100644--- a/packages/lizi-im/src/index.ts+++ b/packages/lizi-im/src/index.ts@@ -25,6 +25,7 @@ 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 b8fe714add..01c213f41a 100644--- a/packages/lizi-im/src/types.ts+++ b/packages/lizi-im/src/types.ts@@ -164,6 +164,43 @@ 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). */@@ -233,6 +270,11 @@ 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@@ -321,8 +363,18 @@ export interface StreamingTextHandle {* text) and append-deltas don't fit naturally.*/replace(fullText: string): void;- /** Replace card with `finalText` and stop throttling. */- finalize(finalText: string): Promise<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>;/** Cancel without finalising (still leaves the last rendered text on screen). */close(): void;/**