diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerCompanionRouting.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerCompanionRouting.test.ts index 57b676f2df..9ef2374e12 100644 --- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerCompanionRouting.test.ts +++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerCompanionRouting.test.ts @@ -303,6 +303,183 @@ async function runTurn(userId: string, text = 'hello'): Promise { } describe('turnRunner: connection handed to a companion bot', () => { + // Durable transports settle receipts only from dispatch outcomes. Preparation + // must reject before provider start even when there is no TurnState to clean up. + it.each([ + { failure: 'prepare', external: false }, + { failure: 'read', external: false }, + { failure: 'missing', external: false }, + { failure: 'prepare', external: true }, + { failure: 'read', external: true }, + { failure: 'missing', external: true }, + ])('settles cold preparation failure and clears the handed-over ack: %j', async ({ failure, external }) => { + companion.prepareSend.mockImplementation(async () => { + if (failure === 'prepare') throw new Error('MODEL_ROUTE_FAILED'); + if (failure === 'read') vi.mocked(fakeRepo.peekSessionById).mockRejectedValueOnce(new Error('DB_READ_FAILED')); + else vi.mocked(fakeRepo.peekSessionById).mockResolvedValueOnce(null); + return null; + }); + const beforeProviderStart = vi.fn(async () => undefined); + const onEarlyReject = vi.fn(() => true); + const args = { + botContextId: BOT_CONTEXT, userId: OWNER, requesterIsOwner: true, + userMessageId: 'cold-failure', text: 'hello', attachments: [], + ackReactionIdPromise: Promise.resolve('ack'), onEarlyReject, + }; + + if (external) { + await expect(runner.dispatchAgentTurn({ ...args, queueMode: 'external', beforeProviderStart })) + .resolves.toMatchObject({ kind: 'rejected', reason: expect.any(String) }); + expect(onEarlyReject).not.toHaveBeenCalled(); + expect(mocks.im.sendText).not.toHaveBeenCalled(); + } else { + await expect(runner.runAgentTurn(args)).resolves.toBeUndefined(); + expect(onEarlyReject).toHaveBeenCalledOnce(); + } + expect(mocks.im.removeMessageReaction).toHaveBeenCalledWith('cold-failure', 'ack'); + expect(beforeProviderStart).not.toHaveBeenCalled(); + expect(createSessionArgs).toHaveLength(0); + expect(mocks.persistUserMessage).not.toHaveBeenCalled(); + }); + + it('does not reserve a chunked reply for rejected auth or consume it on the next turn', async () => { + const id = 'mimi-main'; + const h = makeSessionHarness(id); + harnesses.set(id, h); + const beginReply = vi.fn(async () => undefined); + const commitFinal = vi.fn(async () => undefined); + runner = createTurnRunner({ + ...fakeAdapter, + channel: 'wecom', + output: { kind: 'chunked-text', im: fakeAdapter.im, beginReply, commitFinal }, + }, fakeRepo, fakeCards, { companion: companion as unknown as ImCompanionRouteDeps }); + companion.prepareSend.mockImplementation(async () => { + botRows.set(id, rowFor(id, { model: 'unavailable', providerId: 'disconnected' })); + return null; + }); + + await runTurn(OWNER, 'rejected'); + expect(h.send).not.toHaveBeenCalled(); + expect(beginReply).not.toHaveBeenCalled(); + expect(commitFinal).not.toHaveBeenCalled(); + expect(mocks.im.sendText).toHaveBeenCalledWith(OWNER, expect.stringContaining('unavailable'), expect.anything()); + + companion.prepareSend.mockImplementation(async () => { + botRows.set(id, rowFor(id, { model: 'bot-model', providerId: 'xd' })); + return null; + }); + await runTurn(OWNER, 'accepted'); + expect(h.send).toHaveBeenCalledOnce(); + expect(beginReply).toHaveBeenCalledOnce(); + expect(beginReply.mock.invocationCallOrder[0]!).toBeLessThan(h.send.mock.invocationCallOrder[0]!); + h.emit({ type: 'text', data: { text: 'answer', isFinal: true } } as AgentEvent); + h.emit({ type: 'done', data: {} } as AgentEvent); + await vi.waitFor(() => expect(commitFinal).toHaveBeenCalledOnce()); + expect(commitFinal).toHaveBeenCalledWith(expect.objectContaining({ userId: OWNER, text: 'answer', terminal: 'done' })); + }); + + it.each([ + { userId: OWNER, warm: false }, + { userId: 'g/-100123', warm: false }, + { userId: OWNER, warm: true }, + { userId: 'g/-100123', warm: true }, + ])('uses the newly selected companion route after the old provider disconnects: %j', async ({ userId, warm }) => { + const id = userId === OWNER ? 'mimi-main' : 'lane:im:telegram:777:g:-100123'; + const originalResolve = companion.resolveSession.getMockImplementation()!; + companion.resolveSession.mockImplementation(async (input) => { + const result = await originalResolve(input); + botRows.set(id, rowFor(id, { model: 'old-model', providerId: 'disconnected' })); + return result; + }); + const oldSession = warm ? makeSessionHarness(id) : null; + if (oldSession) harnesses.set(id, oldSession); + const selected = rowFor(id, { model: 'bot-model', providerId: 'xd', sdkSessionId: null }); + companion.prepareSend.mockImplementation(async () => { + botRows.set(id, selected); + return null; + }); + const maker = mocks.getMaker(); + const create = maker.createSession.getMockImplementation(); + maker.createSession.mockImplementation(async (args: { id: string; model: string }) => { + // A cold start against the disconnected route must not be attempted. + // Warm createSession calls reuse Maker's existing singleton without booting. + if (!warm) expect(args.model).toBe('bot-model'); + return create(args); + }); + mocks.dbSelect.mockImplementation(() => ({ from: () => ({ where: () => ({ + limit: async () => [{ ...botRows.get(id), status: 'active' }], + }) }) })); + runner = createTurnRunner(fakeAdapter, fakeRepo, fakeCards, { + companion: companion as unknown as ImCompanionRouteDeps, + acquirePendingAgentSwitch, + }); + + await runTurn(userId); + + expect(companion.prepareSend).toHaveBeenCalledWith(id); + expect(harnesses.get(id)!.send).toHaveBeenCalledTimes(1); + expect(mocks.persistUserMessage).toHaveBeenCalledTimes(1); + expect(mocks.im.sendText).not.toHaveBeenCalledWith( + userId, expect.stringContaining('old-model'), expect.anything(), + ); + expect(acquirePendingAgentSwitch).toHaveBeenCalledWith(id, { channelOwned: false }); + }); + + it('checks the landed companion route even if it changed again under the send lock', async () => { + const id = 'mimi-main'; + harnesses.set(id, makeSessionHarness(id)); + acquirePendingAgentSwitch.mockImplementation(async () => { + botRows.set(id, rowFor(id, { model: 'latest-unavailable', providerId: 'disconnected' })); + return () => undefined; + }); + mocks.dbSelect.mockImplementation(() => ({ from: () => ({ where: () => ({ + limit: async () => [{ ...botRows.get(id), status: 'active' }], + }) }) })); + runner = createTurnRunner(fakeAdapter, fakeRepo, fakeCards, { + companion: companion as unknown as ImCompanionRouteDeps, + acquirePendingAgentSwitch, + }); + + await runTurn(OWNER); + + expect(harnesses.get(id)!.send).not.toHaveBeenCalled(); + expect(mocks.persistUserMessage).not.toHaveBeenCalled(); + expect(mocks.im.sendText).toHaveBeenCalledWith( + OWNER, expect.stringContaining('latest-unavailable'), expect.anything(), + ); + }); + + it('queues input while the old companion turn runs and authenticates the new route only at dispatch', async () => { + const id = 'mimi-main'; + const h = makeSessionHarness(id); + harnesses.set(id, h); + botRows.set(id, rowFor(id, { model: 'old-model', providerId: 'disconnected' })); + vi.mocked(h.session.isTurnRunning).mockReturnValue(true); + companion.prepareSend.mockImplementation(async () => { + botRows.set(id, rowFor(id, { model: 'bot-model', providerId: 'xd' })); + return null; + }); + mocks.dbSelect.mockImplementation(() => ({ from: () => ({ where: () => ({ + limit: async () => [{ ...botRows.get(id), status: 'active' }], + }) }) })); + runner = createTurnRunner(fakeAdapter, fakeRepo, fakeCards, { + companion: companion as unknown as ImCompanionRouteDeps, + acquirePendingAgentSwitch, + }); + + await runTurn(OWNER); + expect(h.send).not.toHaveBeenCalled(); + expect(companion.prepareSend).not.toHaveBeenCalled(); + expect(mocks.im.sendText).not.toHaveBeenCalled(); + + vi.mocked(h.session.isTurnRunning).mockReturnValue(false); + h.emit({ type: 'done', data: {} } as AgentEvent); + + await vi.waitFor(() => expect(h.send).toHaveBeenCalledTimes(1)); + expect(companion.prepareSend).toHaveBeenCalledWith(id); + expect(mocks.persistUserMessage).toHaveBeenCalledTimes(1); + }); + it('keeps the channel’s own routing for an unbound connection', async () => { binding = null; await runTurn(OWNER, 'first'); @@ -394,6 +571,7 @@ describe('turnRunner: connection handed to a companion bot', () => { // the send lock's own suppression window. The runner must not forget the task. const listeners: Array<(event: MakerEvent) => void> = []; const switched = makeSessionHarness('mimi-main'); + harnesses.set('mimi-main', makeSessionHarness('mimi-main')); let live: Session | undefined; const base = mocks.getMaker() as { createSession: (args: { id?: string }) => Promise; @@ -540,7 +718,8 @@ describe('turnRunner: connection handed to a companion bot', () => { it('replies with a notice and does not send when the bot guard blocks the turn', async () => { companion.prepareSend.mockResolvedValue('Bot 当前未启用,请先恢复 Bot 后再发送消息'); await runTurn(OWNER); - expect(harnesses.get('mimi-main')!.send).not.toHaveBeenCalled(); + expect(harnesses.has('mimi-main')).toBe(false); + expect(createSessionArgs).toHaveLength(0); expect(mocks.im.sendText).toHaveBeenCalledWith( OWNER, expect.stringContaining('伙伴现在接不了消息'), diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts index 821971b060..fda66528f1 100644 --- a/apps/desktop/src/main/im/shared/turnRunner.ts +++ b/apps/desktop/src/main/im/shared/turnRunner.ts @@ -1064,6 +1064,57 @@ export function createTurnRunner( } target = created.target; } + // A cold companion task must reconcile its saved model before starting an + // agent. Otherwise a disconnected old provider can prevent both wiring and + // the later prepareSend guard from ever applying the new selection. + const coldCompanion = target.botOwned && !sessionStates.has(target.row.id) + && !wiringInFlight.has(target.row.id) && !getMaker().getSession(target.row.id); + if (coldCompanion && deps.companion?.prepareSend) { + let blocked: string | null; + try { + if (target.botOwned?.lane === 'channel') { + coldWiringVendorOptions.set(target.row.id, adapter.buildVendorOptions(userId, target.scopeKey)); + } + blocked = await deps.companion.prepareSend(target.row.id); + if (!blocked) { + const refreshed = await repo.peekSessionById(target.row.id); + if (!refreshed) throw new Error(`companion session ${target.row.id} missing after route preparation`); + target = { ...target, row: refreshed }; + } + } catch (err) { + if (isImAccountScopeClosedError(err)) throw err; + const normalized = normalizeSendError(err); + log.error(`${channel} companion preparation failed before dispatch`, { + kind: 'session-dispatch', + source: 'companion.prepareSend', + sessionId: hashLogSessionId(target.row.id), + reason: normalized.reason, + error: normalized.error, + }); + await waitForAckCleanupBounded(discardHandedOverAck(userMessageId, args.ackReactionIdPromise)); + if (args.queueMode === 'internal') { + try { + const text = ui.agent.sendInternalError(normalized.reason); + const consumed = (await args.onEarlyReject?.(normalized.reason, text)) ?? false; + if (!consumed) await sendTextClaimingOpener(userId, text, target.scopeKey); + } catch { + /* A failed notice must still return a definite pre-dispatch rejection. */ + } + } + return { kind: 'rejected', reason: normalized.reason }; + } finally { + coldWiringVendorOptions.delete(target.row.id); + } + if (blocked) { + const text = ui.agent.companionUnavailable?.(blocked) ?? ui.agent.runtimeError(blocked); + if (args.queueMode === 'internal') { + const consumed = (await args.onEarlyReject?.('companion_unavailable', text)) ?? false; + if (!consumed) await sendTextClaimingOpener(userId, text, target.scopeKey); + } + await discardHandedOverAck(userMessageId, args.ackReactionIdPromise); + return { kind: 'rejected', reason: 'companion_unavailable' }; + } + } const row = target.row; const allowedFileRoots = resolveTurnFileRoots(row.workingDir, row.remoteHostId); let followTarget: ImDefaultRoute | null | undefined = null; @@ -1071,7 +1122,10 @@ export function createTurnRunner( const sharedSession = target.attached || target.notificationReply === true || target.botOwned?.lane === 'canonical'; const authNoticeAttached = target.attached || target.botOwned !== undefined; - if (!target.authChecked) { + // Live companion tasks may still be running on the previous selection. + // Authenticate them after prepareSend + the locked switch at dispatch, not + // against the stale row before their input has even reached the queue. + if (!target.authChecked && (!target.botOwned || coldCompanion)) { // 渠道默认跟随: 本条消息会在 send 锁内切到新默认时, 按新路由检查授权 —— // 否则旧默认坏掉(如供应商断开)时, 消息会先被「缺授权」挡掉, 永远换不过去。 followTarget = @@ -1472,7 +1526,6 @@ export function createTurnRunner( await item.turn.revalidateNotificationReply?.(); await resolveNotificationTarget(rowId, item.turn.scopeKey); } - await beginChunkedReply(item.turn); // 伙伴任务: 与桌面发送同源的伙伴守卫(暂停 / 归档 → 回一句提示不发送), // 再对齐伙伴模型链、刷新能力纪元。要在拿 send 锁之前做 —— 对齐登记的切换 // 意图由下面的锁内应用落实。 @@ -1555,19 +1608,24 @@ export function createTurnRunner( // 失败被吞后这条消息会按旧路由发送 —— 按实际路由补一次授权检查, 旧供应商断开 // 时在这里给出缺授权提示, 而不是进发送流程运行时失败(PR #5155 review P2)。 // 冷路径在接线前已查过一次, 这里兜的是接线后切换才失败 / 热任务的切换失败。 + // 伙伴任务始终在守卫与锁内切换完成后检查实际路由, 不复用入队时的旧选择。 const followAuthRoute = item.turn.followAuthRoute; - if (followAuthRoute) { + if (followAuthRoute || state.botLane) { const landed = await repo.peekSessionById(rowId); - if (landed && !sameImDefaultRoute(routeOfRow(landed), followAuthRoute)) { + if (state.botLane && !landed) { + throw new Error(`companion session ${rowId} missing before route authentication`); + } + if (landed && (state.botLane || (followAuthRoute && !sameImDefaultRoute(routeOfRow(landed), followAuthRoute)))) { const auth = await checkImRouteAuthDetailed(landed, undefined, authCheckDeps()); if (!auth.ok) { + const attached = state.attached || !!state.botLane; const authStatus = { ...auth, agentKind: landed.agentKind, model: landed.model }; if (item.turn.queueMode === 'internal') { const text = - ui.agent.authMissing?.({ ...authStatus, attached: state.attached }) ?? + ui.agent.authMissing?.({ ...authStatus, attached }) ?? ui.agent.apiKeyMissing; const consumed = (await item.onEarlyReject?.('missing_auth', text)) ?? false; - if (!consumed) await replyMissingAuth(userId, authStatus, item.turn.scopeKey, state.attached); + if (!consumed) await replyMissingAuth(userId, authStatus, item.turn.scopeKey, attached); } // 文案已在上面按缺授权发过(外部队列由调用方消费), 这里只走收口。 await handleSendPreDispatchFailure(state, userId, { @@ -1582,6 +1640,10 @@ export function createTurnRunner( } } + // Only claim a passive reply after preparation and route authentication. + // Rejected input must not leave a pending chunked response for the next turn. + await beginChunkedReply(item.turn); + // session-agent-switch:本路径直发 session.send(不经 makerSendTransaction), // 交接注入自己接——切换后首条消息若来自 IM 渠道,新引擎同样需要交接上下文 // (2026-07-20 审计)。落库(persistUserMessage)仍是渠道原文。