π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β test(chat): characterization net for agent runtime run-lifecycle (#15843)
Arvin Xuf9e7ca5b68af
diff --git a/src/features/Conversation/store/slices/generation/action.test.ts b/src/features/Conversation/store/slices/generation/action.test.tsindex fa472b8c175..89c60e808c9 100644--- a/src/features/Conversation/store/slices/generation/action.test.ts+++ b/src/features/Conversation/store/slices/generation/action.test.ts@@ -2,6 +2,10 @@ import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-managemeimport { act } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { messageService } from '@/services/message';+import { agentSelectors } from '@/store/agent/selectors';+import * as agentDispatcher from '@/store/chat/slices/aiChat/actions/agentDispatcher';+import * as heterogeneousAgentExecutor from '@/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor';import { INPUT_LOADING_OPERATION_TYPES } from '@/store/chat/slices/operation/types';import { type ConversationContext, type ConversationHooks } from '../../../types';@@ -1025,4 +1029,267 @@ describe('Generation Actions', () => {expect(mockStartOperation).not.toHaveBeenCalled();});});++ // ===========================================================================+ // CHARACTERIZATION TESTS (lifecycle refactor regression net)+ //+ // These lock the CURRENT behavior of the non-sendMessage entry points so an+ // upcoming lifecycle refactor cannot silently change them. They assert what+ // the code does NOW β including behavior that looks buggy (called out inline).+ // ===========================================================================+ describe('regenerate hetero branch characterization (lifecycle refactor regression net)', () => {+ // The hetero regenerate path lives behind `runtimeType === 'hetero'`. We+ // force that decision (it normally requires desktop + a local CLI provider)+ // by stubbing `selectRuntimeType`, and supply a `heterogeneousProvider` via+ // the agent config selector so the `runtimeType === 'hetero' && provider`+ // guard passes.+ const heterogeneousProvider = { type: 'claude-code' } as any;++ const setupHeteroChatStore = async (overrides: Record<string, any> = {}) => {+ const mockRefreshMessages = vi.fn().mockResolvedValue(undefined);+ const mockInternalUpdateTopicLoading = vi.fn();+ const mockAssociateMessageWithOperation = vi.fn();+ const mockHeteroStartOperation = vi+ .fn()+ .mockReturnValueOnce({ operationId: 'regen-op-id' }) // parent regenerate op+ .mockReturnValueOnce({ operationId: 'hetero-op-id' }); // child execHeterogeneousAgent op++ const { useChatStore } = await import('@/store/chat');+ vi.mocked(useChatStore.getState).mockReturnValue({+ messagesMap: {},+ operations: {},+ operationsByMessage: {},+ // topicSelectors.getTopicById reads topicDataMap during workingDirectory+ // resolution; an empty map keeps the selector chain from throwing.+ topicDataMap: {},++ startOperation: mockHeteroStartOperation,+ completeOperation: mockCompleteOperation,+ failOperation: mockFailOperation,+ isGatewayModeEnabled: vi.fn(() => false),+ switchMessageBranch: mockSwitchMessageBranch,+ refreshMessages: mockRefreshMessages,+ internal_updateTopicLoading: mockInternalUpdateTopicLoading,+ associateMessageWithOperation: mockAssociateMessageWithOperation,+ executeClientAgent: mockExecuteClientAgent,+ executeGatewayAgent: mockExecuteGatewayAgent,+ ...overrides,+ } as any);++ return {+ mockAssociateMessageWithOperation,+ mockHeteroStartOperation,+ mockInternalUpdateTopicLoading,+ mockRefreshMessages,+ };+ };++ let executeHeterogeneousAgentSpy: ReturnType<typeof vi.spyOn>;+ let createMessageSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ // Force the hetero routing decision.+ vi.spyOn(agentDispatcher, 'selectRuntimeType').mockReturnValue('hetero');+ // Supply a config that carries the hetero provider used by the branch.+ vi.spyOn(agentSelectors, 'getAgentConfigById').mockReturnValue(+ () => ({ agencyConfig: { heterogeneousProvider } }) as any,+ );++ createMessageSpy = vi+ .spyOn(messageService, 'createMessage')+ .mockResolvedValue({ id: 'hetero-assistant-msg', messages: [] } as any) as any;++ executeHeterogeneousAgentSpy = vi+ .spyOn(heterogeneousAgentExecutor, 'executeHeterogeneousAgent')+ .mockResolvedValue(undefined) as any;+ });++ it('routes regenerateUserMessage through executeHeterogeneousAgent with imageList + parentOperationId', async () => {+ const { mockRefreshMessages } = await setupHeteroChatStore();++ const context: ConversationContext = {+ agentId: 'session-1',+ topicId: 'topic-1',+ threadId: null,+ };++ const store = createStore({ context });++ const originalImageList = [{ id: 'img-1', url: 'data:image/png;base64,xxx' }];+ act(() => {+ store.setState({+ displayMessages: [+ {+ id: 'msg-1',+ role: 'user',+ content: 'Draw a cat',+ imageList: originalImageList,+ },+ ],+ } as any);+ });++ await act(async () => {+ await store.getState().regenerateUserMessage('msg-1');+ });++ // A fresh assistant row is created branched off the user message.+ expect(createMessageSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ parentId: 'msg-1',+ role: 'assistant',+ provider: 'claude-code',+ }),+ );++ // Store is refreshed so the loading bubble shows while the CLI streams.+ expect(mockRefreshMessages).toHaveBeenCalled();++ // The executor receives the new assistant row id, the original user+ // message's images, the original prompt, and the child hetero op id.+ expect(executeHeterogeneousAgentSpy).toHaveBeenCalledWith(+ expect.any(Function),+ expect.objectContaining({+ assistantMessageId: 'hetero-assistant-msg',+ heterogeneousProvider,+ imageList: originalImageList,+ message: 'Draw a cat',+ operationId: 'hetero-op-id',+ }),+ );+ });++ it('creates the child execHeterogeneousAgent op as a child of the parent regenerate op', async () => {+ const { mockHeteroStartOperation, mockAssociateMessageWithOperation } =+ await setupHeteroChatStore();++ const context: ConversationContext = {+ agentId: 'session-1',+ topicId: 'topic-1',+ threadId: null,+ };++ const store = createStore({ context });++ act(() => {+ store.setState({+ displayMessages: [{ id: 'msg-1', role: 'user', content: 'Hello' }],+ } as any);+ });++ await act(async () => {+ await store.getState().regenerateUserMessage('msg-1');+ });++ // First op: the regenerate op for the user message.+ expect(mockHeteroStartOperation).toHaveBeenNthCalledWith(1, {+ context: { ...context, messageId: 'msg-1' },+ type: 'regenerate',+ });++ // Second op: the execHeterogeneousAgent op parented to the regenerate op.+ expect(mockHeteroStartOperation).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({+ parentOperationId: 'regen-op-id',+ type: 'execHeterogeneousAgent',+ }),+ );++ // The new assistant row is associated with the child hetero op.+ expect(mockAssociateMessageWithOperation).toHaveBeenCalledWith(+ 'hetero-assistant-msg',+ 'hetero-op-id',+ );+ });++ it('CURRENT BEHAVIOR: completes the regenerate op AND calls onRegenerateComplete in the hetero branch', async () => {+ // NOTE: This characterizes the actual current behavior of the hetero+ // branch (action.ts ~548-549): after `runHeterogeneousFromExistingMessage`+ // resolves it DOES call `completeOperation(operationId)` and DOES invoke+ // `hooks.onRegenerateComplete(messageId)` β synchronously, unlike the+ // gateway branch which defers both to an async `onComplete` callback.+ // Locked here so the refactor cannot silently flip this without a failing+ // test forcing a deliberate decision.+ const { mockHeteroStartOperation } = await setupHeteroChatStore();+ void mockHeteroStartOperation;++ const onRegenerateComplete = vi.fn();+ const context: ConversationContext = {+ agentId: 'session-1',+ topicId: 'topic-1',+ threadId: null,+ };++ const store = createStore({ context, hooks: { onRegenerateComplete } });++ act(() => {+ store.setState({+ displayMessages: [{ id: 'msg-1', role: 'user', content: 'Hello' }],+ } as any);+ });++ await act(async () => {+ await store.getState().regenerateUserMessage('msg-1');+ });++ // The parent regenerate op is completed synchronously after the executor.+ expect(mockCompleteOperation).toHaveBeenCalledWith('regen-op-id');+ // And the hook fires synchronously (no deferred onComplete like gateway).+ expect(onRegenerateComplete).toHaveBeenCalledWith('msg-1');+ });+ });++ describe('continue hetero early-return characterization (lifecycle refactor regression net)', () => {+ // continueGenerationMessage bails out early for hetero agents (action.ts+ // ~336): CLIs have no "continue a cut-off response" primitive, so the+ // button is a documented no-op. Lock that no runtime is dispatched.+ beforeEach(() => {+ vi.spyOn(agentDispatcher, 'selectRuntimeType').mockReturnValue('hetero');+ vi.spyOn(agentSelectors, 'getAgentConfigById').mockReturnValue(+ () =>+ ({+ agencyConfig: { heterogeneousProvider: { type: 'claude-code' } },+ }) as any,+ );+ });++ it('returns early without starting an operation or dispatching any runtime', async () => {+ const { useChatStore } = await import('@/store/chat');+ vi.mocked(useChatStore.getState).mockReturnValue({+ messagesMap: {},+ operations: {},+ operationsByMessage: {},+ startOperation: mockStartOperation,+ completeOperation: mockCompleteOperation,+ failOperation: mockFailOperation,+ executeClientAgent: mockExecuteClientAgent,+ executeGatewayAgent: mockExecuteGatewayAgent,+ isGatewayModeEnabled: vi.fn(() => false),+ } as any);++ const context: ConversationContext = {+ agentId: 'session-1',+ topicId: 'topic-1',+ threadId: null,+ };++ const store = createStore({ context });++ act(() => {+ store.setState({+ displayMessages: [{ id: 'block-1', role: 'assistant', content: 'partial' }],+ } as any);+ });++ await act(async () => {+ await store.getState().continueGenerationMessage('block-1', 'block-1');+ });++ // Hetero short-circuits BEFORE creating the continue operation.+ expect(mockStartOperation).not.toHaveBeenCalled();+ expect(mockExecuteClientAgent).not.toHaveBeenCalled();+ expect(mockExecuteGatewayAgent).not.toHaveBeenCalled();+ });+ });});diff --git a/src/store/chat/slices/aiChat/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/conversationControl.test.tsindex 1356964bfeb..fa8438dbb38 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/conversationControl.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/conversationControl.test.ts@@ -2,6 +2,8 @@ import { type ConversationContext, RequestTrigger } from '@lobechat/types';import { act, renderHook } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';+import { useChatStore } from '../../../../store';import { messageMapKey } from '../../../../utils/messageMapKey';import { createMockMessage, createMockResolvedAgentConfig, TEST_IDS } from './fixtures';@@ -1783,4 +1785,233 @@ describe('ConversationControl actions', () => {);});});++ // ===========================================================================+ // CHARACTERIZATION TESTS (lifecycle refactor regression net)+ //+ // Lock the CURRENT behavior of these non-sendMessage entry points so an+ // upcoming lifecycle refactor cannot silently change them. They assert what+ // the code does NOW.+ // ===========================================================================+ describe('rejectAndContinueToolCalling client characterization (lifecycle refactor regression net)', () => {+ it('runs rejectToolCalling (one op completes) then starts a NEW op and executes client agent with phase=user_input', async () => {+ const { result } = renderHook(() => useChatStore());++ const agentId = 'client-agent';+ const topicId = 'client-topic';+ const chatKey = messageMapKey({ agentId, topicId });++ const toolMessage = createMockMessage({+ id: 'tool-msg-1',+ plugin: { apiName: 'test', arguments: '{}', identifier: 'test-plugin', type: 'default' },+ role: 'tool',+ tool_call_id: 'call_client',+ } as any);++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ activeThreadId: undefined,+ dbMessagesMap: { [chatKey]: [toolMessage] },+ messagesMap: { [chatKey]: [toolMessage] },+ });+ });++ // Client-mode (no Gateway resume): let the real rejectToolCalling chain+ // run so we can observe the dual-op sequence. Only stub the persistence+ // primitives and the runtime executor.+ vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(false);+ vi.spyOn(result.current, 'optimisticUpdateMessagePlugin').mockResolvedValue(undefined);+ vi.spyOn(result.current, 'optimisticUpdateMessageContent').mockResolvedValue(undefined);+ const rejectToolCallingSpy = vi.spyOn(result.current, 'rejectToolCalling');+ vi.spyOn(result.current, 'internal_createAgentState').mockReturnValue({+ agentConfig: createMockResolvedAgentConfig(),+ context: { phase: 'init' } as any,+ state: {} as any,+ });+ const executeClientAgentSpy = vi+ .spyOn(result.current, 'executeClientAgent')+ .mockResolvedValue(undefined);++ await act(async () => {+ await result.current.rejectAndContinueToolCalling('tool-msg-1', 'not safe');+ });++ // 1) The halting reject runs first (it creates + completes its own op).+ expect(rejectToolCallingSpy).toHaveBeenCalledWith('tool-msg-1', 'not safe', undefined);++ // 2) Then a SECOND op is created and the client runtime continues with+ // phase overridden to 'user_input', resuming from the tool message.+ expect(executeClientAgentSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ initialContext: expect.objectContaining({ phase: 'user_input' }),+ parentMessageId: 'tool-msg-1',+ parentMessageType: 'tool',+ }),+ );++ // Two 'rejectToolCalling' ops exist (the halting reject's own op + the+ // continue op). Both reach 'completed' on the happy path.+ const rejectOps = Object.values(result.current.operations).filter(+ (op: any) => op.type === 'rejectToolCalling',+ );+ expect(rejectOps).toHaveLength(2);+ expect(rejectOps.every((op: any) => op.status === 'completed')).toBe(true);+ });+ });++ describe('submitHeteroIntervention characterization (lifecycle refactor regression net)', () => {+ it('submits via IPC, persists optimistic intervention, and flips topic status to running (submit)', async () => {+ const { result } = renderHook(() => useChatStore());++ const agentId = 'hetero-agent';+ const topicId = 'hetero-topic';+ const chatKey = messageMapKey({ agentId, topicId });++ const assistantMessage = createMockMessage({+ id: 'assistant-msg-1',+ role: 'assistant',+ });+ const toolMessage = createMockMessage({+ id: 'tool-msg-1',+ parentId: assistantMessage.id,+ plugin: {+ apiName: 'askUserQuestion',+ arguments: '{}',+ identifier: 'lobe-claude-code',+ type: 'default',+ },+ role: 'tool',+ tool_call_id: 'cc_call_1',+ } as any);++ let assistantOpId!: string;+ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ activeThreadId: undefined,+ dbMessagesMap: { [chatKey]: [assistantMessage, toolMessage] },+ messagesMap: { [chatKey]: [assistantMessage, toolMessage] },+ });++ // The running CC stream op is associated with the assistant that owns+ // the tool message; submitHeteroIntervention walks up to find it.+ assistantOpId = result.current.startOperation({+ context: { agentId, topicId, threadId: null },+ type: 'execHeterogeneousAgent',+ }).operationId;++ useChatStore.setState((s) => ({+ messageOperationMap: { ...s.messageOperationMap, [assistantMessage.id]: assistantOpId },+ }));+ });++ vi.spyOn(result.current, 'optimisticUpdateMessagePlugin').mockResolvedValue(undefined);+ vi.spyOn(result.current, 'optimisticUpdateMessageContent').mockResolvedValue(undefined);+ const updateTopicStatusSpy = vi+ .spyOn(result.current, 'updateTopicStatus')+ .mockResolvedValue(undefined as any);+ const submitInterventionSpy = vi+ .spyOn(heterogeneousAgentService, 'submitIntervention')+ .mockResolvedValue(undefined as any);++ const payload = { 'Which color?': 'Blue' };+ await act(async () => {+ await result.current.submitHeteroIntervention('tool-msg-1', 'submit', payload);+ });++ // Optimistic approval runs against the resolved op (operationId carried).+ expect(result.current.optimisticUpdateMessagePlugin).toHaveBeenCalledWith(+ 'tool-msg-1',+ { intervention: { status: 'approved' } },+ { operationId: assistantOpId },+ );++ // IPC submit forwards the resolved operationId + toolCallId + result.+ expect(submitInterventionSpy).toHaveBeenCalledWith({+ operationId: assistantOpId,+ result: payload,+ toolCallId: 'cc_call_1',+ });++ // Topic row flips back from waitingForHuman to running.+ expect(updateTopicStatusSpy).toHaveBeenCalledWith(+ expect.objectContaining({ status: 'running', topicId }),+ );+ });++ it("CURRENT BEHAVIOR: falls back to global-state optimistic context (empty op) and still submits when the operation is GC'd", async () => {+ // Characterizes action.ts ~735/~758: when the resolved op has already been+ // garbage-collected (not present in `operations`), the optimistic context+ // is the empty object `{}` (global-state fallback) rather than carrying the+ // stale operationId β but the IPC submit STILL fires with that operationId,+ // and the call does NOT throw. Locked as-is.+ const { result } = renderHook(() => useChatStore());++ const agentId = 'hetero-agent';+ const topicId = 'hetero-topic';+ const chatKey = messageMapKey({ agentId, topicId });++ const assistantMessage = createMockMessage({ id: 'assistant-msg-1', role: 'assistant' });+ const toolMessage = createMockMessage({+ id: 'tool-msg-1',+ parentId: assistantMessage.id,+ plugin: {+ apiName: 'askUserQuestion',+ arguments: '{}',+ identifier: 'lobe-claude-code',+ type: 'default',+ },+ role: 'tool',+ tool_call_id: 'cc_call_1',+ } as any);++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ activeThreadId: undefined,+ dbMessagesMap: { [chatKey]: [assistantMessage, toolMessage] },+ messagesMap: { [chatKey]: [assistantMessage, toolMessage] },+ // Point the assistant at an opId that does NOT exist in `operations`+ // (simulating a garbage-collected / completed-and-pruned op).+ messageOperationMap: { [assistantMessage.id]: 'gc-op-id' },+ operations: {},+ });+ });++ const pluginSpy = vi+ .spyOn(result.current, 'optimisticUpdateMessagePlugin')+ .mockResolvedValue(undefined);+ vi.spyOn(result.current, 'optimisticUpdateMessageContent').mockResolvedValue(undefined);+ vi.spyOn(result.current, 'updateTopicStatus').mockResolvedValue(undefined as any);+ const submitInterventionSpy = vi+ .spyOn(heterogeneousAgentService, 'submitIntervention')+ .mockResolvedValue(undefined as any);++ await act(async () => {+ await expect(+ result.current.submitHeteroIntervention('tool-msg-1', 'cancel'),+ ).resolves.toBeUndefined();+ });++ // Optimistic write uses the empty global-state fallback context.+ expect(pluginSpy).toHaveBeenCalledWith(+ 'tool-msg-1',+ expect.objectContaining({ intervention: expect.objectContaining({ status: 'rejected' }) }),+ {},+ );++ // IPC submit still fires with the (stale) resolved operationId + cancel.+ expect(submitInterventionSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ cancelled: true,+ operationId: 'gc-op-id',+ toolCallId: 'cc_call_1',+ }),+ );+ });+ });});diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.tsindex 57165aeca10..a5f105009b8 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts@@ -1071,6 +1071,133 @@ describe('createGatewayEventHandler', () => {});});+ // βββ Characterization net (LOCKS CURRENT BEHAVIOR for an upcoming+ // lifecycle refactor). These tests must PASS against the code as-is.+ // They describe what the gateway terminal path does NOW, not ideal+ // behavior. If something reads like a bug it is locked as-is with a note.+ describe('gateway terminal characterization (lifecycle refactor regression net)', () => {+ // CURRENT BEHAVIOR (gatewayEventHandler.ts ~622-624): the `error` event+ // handler completes the operation but, UNLIKE `agent_runtime_end`+ // (~552-557 which calls markUnreadCompleted when the operation has a+ // context.agentId), the error path NEVER calls markUnreadCompleted.+ // This is an intentional asymmetry to lock: an errored run does not get+ // marked as an unread "completed" agent run. If a future refactor unifies+ // the terminal paths, revisit whether errors SHOULD mark unread β+ // changing this assertion is the signal that the contract moved.+ it('error event completes the operation but does NOT call markUnreadCompleted (asymmetry vs agent_runtime_end)', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('error', { message: 'kaboom' }));+ await flush();++ // completeOperation IS called on error.+ expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ // markUnreadCompleted is NOT β even though operations['op-1'] has a+ // context.agentId (which WOULD trigger it on agent_runtime_end).+ expect(store.markUnreadCompleted).not.toHaveBeenCalled();+ });++ // Contrast probe: agent_runtime_end on the SAME operation (which has a+ // context.agentId) DOES mark unread completed β proving the negative+ // assertion above is the error path's own behavior, not a missing agentId.+ it('agent_runtime_end (same op, has context.agentId) DOES call markUnreadCompleted', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('agent_runtime_end'));+ await flush();++ expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ expect(store.markUnreadCompleted).toHaveBeenCalledWith('agent-1', 'topic-1');+ });++ // CURRENT BEHAVIOR: completeOperation runs once in the agent_runtime_end+ // handler (gatewayEventHandler.ts:552) and again in gateway.ts+ // onSessionComplete (gateway.ts:532) for the same operationId. The+ // underlying reducer (operation/actions.ts:281-306) is idempotent: a+ // second completeOperation on an already-'completed' op leaves status as+ // 'completed' (it only refuses to overwrite a 'cancelled' status). This+ // models the real reducer so the double-call is locked as a no-throw,+ // no-flip stable terminal state.+ it('completeOperation is idempotent: double-calling the same op leaves status=completed (no throw, no flip)', async () => {+ // Local harness whose completeOperation MIRRORS the real reducer+ // (operation/actions.ts completeOperation): set status to 'completed'+ // unless the op was 'cancelled'.+ const operations: Record<string, any> = {+ 'op-1': {+ context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' },+ metadata: { startTime: 0 },+ status: 'running',+ },+ };+ const completeOperation = vi.fn((operationId: string) => {+ const op = operations[operationId];+ if (!op) return;+ if (op.status !== 'cancelled') op.status = 'completed';+ op.metadata.endTime = Date.now();+ });+ const store = {+ ...createMockStore(),+ completeOperation,+ operations,+ } as ReturnType<typeof createMockStore>;+ const get = vi.fn(() => store) as any;+ const handler = createGatewayEventHandler(get, {+ assistantMessageId: 'msg-initial',+ context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' } as any,+ operationId: 'op-1',+ });++ // First terminal completion (agent_runtime_end handler).+ handler(makeEvent('agent_runtime_end'));+ await flush();+ expect(operations['op-1'].status).toBe('completed');++ // Second completion (as onSessionComplete in gateway.ts would issue).+ store.completeOperation('op-1');+ expect(operations['op-1'].status).toBe('completed');+ expect(completeOperation).toHaveBeenCalledTimes(2);+ });++ // CURRENT BEHAVIOR: if the op was cancelled mid-flight, completeOperation+ // does NOT flip it to 'completed' (operation/actions.ts:288-291 preserves+ // the user's interruption state). Lock this so the refactor can't quietly+ // resurrect a cancelled op into 'completed' on a stray terminal event.+ it('completeOperation preserves a cancelled op (does not flip cancelled β completed)', async () => {+ const operations: Record<string, any> = {+ 'op-1': {+ context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' },+ metadata: { startTime: 0 },+ status: 'cancelled',+ },+ };+ const completeOperation = vi.fn((operationId: string) => {+ const op = operations[operationId];+ if (!op) return;+ if (op.status !== 'cancelled') op.status = 'completed';+ op.metadata.endTime = Date.now();+ });+ const store = {+ ...createMockStore(),+ completeOperation,+ operations,+ } as ReturnType<typeof createMockStore>;+ const get = vi.fn(() => store) as any;+ const handler = createGatewayEventHandler(get, {+ assistantMessageId: 'msg-initial',+ context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' } as any,+ operationId: 'op-1',+ });++ handler(makeEvent('agent_runtime_end', { reason: 'interrupted' }));+ await flush();++ expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ expect(operations['op-1'].status).toBe('cancelled');+ });+ });+describe('step transition timing (orphan tool regression)', () => {/*** Verifies that after the executor fix, tools_calling events at stepdiff --git a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.tsindex e2bd40d5c3d..61ea7c02daa 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -11,12 +11,15 @@*/import path from 'node:path';+import type * as LobeChatConst from '@lobechat/const';import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';import type { AgentEventAdapter } from '@lobechat/heterogeneous-agents';import { createAdapter } from '@lobechat/heterogeneous-agents';import { ThreadStatus } from '@lobechat/types';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { useChatStore } from '@/store/chat/store';+import { createGatewayEventHandler } from '../gatewayEventHandler';import type { HeterogeneousAgentExecutorParams } from '../heterogeneousAgentExecutor';import { executeHeterogeneousAgent } from '../heterogeneousAgentExecutor';@@ -70,6 +73,33 @@ vi.mock('../gatewayEventHandler', () => ({createGatewayEventHandler: vi.fn(() => vi.fn()),}));+// isDesktop β defaults to `false` (matching the real test env / __ELECTRON__+// undefined) so the existing suite is unaffected. The completion-notification+// characterization tests flip `desktopFlag.value` to `true` to exercise the+// desktop-only `notifyCompletion` branch, then restore it in afterEach.+// `vi.hoisted` so the flag exists when the hoisted `vi.mock` factory runs at+// module-evaluation time (which happens during collection, before any test).+const desktopFlag = vi.hoisted(() => ({ value: false }));+vi.mock('@lobechat/const', async (importOriginal) => {+ const actual = await importOriginal<typeof LobeChatConst>();+ return {+ ...actual,+ get isDesktop() {+ return desktopFlag.value;+ },+ };+});++// Desktop notification IPC β dynamically imported inside `notifyCompletion`.+const mockShowNotification = vi.fn(async (..._args: any[]) => {});+const mockSetBadgeCount = vi.fn(async (..._args: any[]) => {});+vi.mock('@/services/electron/desktopNotification', () => ({+ desktopNotificationService: {+ setBadgeCount: (...args: any[]) => mockSetBadgeCount(...args),+ showNotification: (...args: any[]) => mockShowNotification(...args),+ },+}));+// βββ Helpers βββfunction setupIpcCapture() {@@ -3655,4 +3685,350 @@ describe('heterogeneousAgentExecutor DB persistence', () => {for (const id of toolIds) expect(writtenIds).toContain(id);});});++ // ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ // Characterization tests locking the CURRENT hetero-completion lifecycle.+ //+ // These are a REGRESSION NET ahead of the send-message run-lifecycle refactor:+ // they pin what the code does NOW (notifyCompletion fan-out, metadata-save+ // isolation, queue-drain gating, the onError/abort skips), not idealized+ // behavior. If something here looks like a bug it is intentionally locked+ // as-is so the refactor surfaces any behavior change as a failing test.+ // ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ describe('hetero completion characterization (lifecycle refactor regression net)', () => {+ afterEach(() => {+ // Restore the global default so the rest of the suite keeps seeing the+ // non-desktop env that every other test assumes.+ desktopFlag.value = false;+ });++ /**+ * Drive a full run to a non-error terminal (`ccResult()` β agent_runtime_end)+ * with a caller-supplied store, mirroring the error-handling tests' manual+ * harness so per-test store overrides (abortController / drainQueuedMessages /+ * updateTopicStatus) are observable.+ */+ async function runToComplete(+ store: any,+ ccEvents: any[],+ paramOverrides: Partial<typeof defaultParams> = {},+ ) {+ const get = vi.fn(() => store);+ let resolveSendPrompt: () => void;+ mockSendPrompt.mockReturnValue(+ new Promise<void>((r) => {+ resolveSendPrompt = r;+ }),+ );++ const executorPromise = executeHeterogeneousAgent(get, {+ ...defaultParams,+ ...paramOverrides,+ });+ await flush();++ for (const event of ccEvents) ipc.emitRawLine('ipc-sess-1', event);+ ipc.emitComplete('ipc-sess-1');+ await flush();++ resolveSendPrompt!();+ // Clean-completion helper: a successful run MUST resolve. Do NOT swallow the+ // rejection here β otherwise a regression that makes the happy path reject+ // (e.g. before the notification side effect runs) would spuriously satisfy the+ // negative assertions (e.g. isDesktop=false β notification NOT called). Let it+ // propagate so such a regression fails the test instead of passing silently.+ await executorPromise;+ await flush();++ return { get, store };+ }++ /**+ * Like `runToComplete` but ends the stream with a TRUE error terminal+ * (`ccResult(true)` β `deferredTerminalEvent.type === 'error'`). This is the+ * event-shape that drives the error branch in onComplete (isErrorTerminal)+ * AND gates the linear-flow queue drain off via `terminalEvent?.type !== 'error'`.+ */+ async function runToError(store: any, paramOverrides: Partial<typeof defaultParams> = {}) {+ const get = vi.fn(() => store);+ let resolveSendPrompt: () => void;+ mockSendPrompt.mockReturnValue(+ new Promise<void>((r) => {+ resolveSendPrompt = r;+ }),+ );++ const executorPromise = executeHeterogeneousAgent(get, {+ ...defaultParams,+ ...paramOverrides,+ });+ await flush();++ ipc.emitRawLine('ipc-sess-1', ccInit());+ ipc.emitRawLine('ipc-sess-1', ccText('msg_01', 'partial content'));+ ipc.emitRawLine('ipc-sess-1', ccResult(true, 'the run failed'));+ ipc.emitComplete('ipc-sess-1');+ await flush();++ resolveSendPrompt!();+ // An error TERMINAL is still handled internally (onError / persistTerminalError):+ // the executor RESOLVES, it does not reject. Don't swallow a rejection β if a+ // regression makes the error path reject, the negative assertions (no notification,+ // no drain) must fail rather than be satisfied by an early bail-out.+ await executorPromise;+ await flush();++ return { get, store };+ }++ // ββ 1. onComplete success β notifyCompletion (notification + dock badge) ββ+ it('fires the desktop notification AND dock badge on a successful non-aborted completion', async () => {+ desktopFlag.value = true;+ const store = createMockStore();++ await runToComplete(store, [+ ccInit(),+ ccText('msg_01', 'All done with the task.'),+ ccResult(),+ ]);++ // notifyCompletion = Promise.allSettled([showNotification(...), setBadgeCount(1)]).+ expect(mockShowNotification).toHaveBeenCalledTimes(1);+ expect(mockShowNotification).toHaveBeenCalledWith(+ expect.objectContaining({+ // body = markdownToTxt(finalContent)+ body: expect.stringContaining('All done with the task'),+ // navigate path resolved from agentId + topicId+ navigate: { path: expect.any(String) },+ title: expect.any(String),+ }),+ );+ expect(mockSetBadgeCount).toHaveBeenCalledTimes(1);+ expect(mockSetBadgeCount).toHaveBeenCalledWith(1);+ });++ it('does NOT touch the desktop notification IPC when isDesktop is false (web/default env)', async () => {+ // desktopFlag.value stays false here β the early `if (!isDesktop) return` guard.+ const store = createMockStore();++ await runToComplete(store, [ccInit(), ccText('msg_01', 'done'), ccResult()]);++ expect(mockShowNotification).not.toHaveBeenCalled();+ expect(mockSetBadgeCount).not.toHaveBeenCalled();+ });++ // ββ 2. metadata-save failure isolation (CURRENT behavior, locked as-is) ββ+ it('swallows an updateTopicMetadata REJECTION without surfacing an error to the caller', async () => {+ // CHARACTERIZATION β locks ACTUAL current behavior, which DIFFERS from the+ // intended acceptance criterion ("metadata failure must not block the+ // drain"):+ //+ // const sessionInfo = await getSessionInfo(...).catch(() => undefined);+ // if (sessionInfo?.agentSessionId && context.topicId)+ // await updateTopicMetadata?.(...); // β NO .catch here+ // if (!isAborted() && terminalEvent?.type !== 'error') { ...drain... }+ //+ // Because the `updateTopicMetadata` await is UNGUARDED, a rejection throws+ // past the drain block into the function's outer try/catch. `completed` is+ // already `true` (onComplete ran), so `catch { if (!completed) ... }` is a+ // no-op: the executor resolves cleanly (no error escapes to the caller),+ // BUT the queue drain is SKIPPED. The completion notification still fired+ // (it runs inside onComplete, before this metadata await). Pinned here so+ // the lifecycle refactor surfaces any change to this latent edge.+ desktopFlag.value = true;+ const queued = [+ {+ content: 'follow-up please',+ editorData: undefined,+ files: [],+ id: 'q1',+ metadata: {},+ },+ ];+ const store = createMockStore({+ drainQueuedMessages: vi.fn(() => queued),+ updateTopicMetadata: vi.fn().mockRejectedValue(new Error('metadata save boom')),+ });+ const get = vi.fn(() => store);++ let resolveSendPrompt: () => void;+ mockSendPrompt.mockReturnValue(+ new Promise<void>((r) => {+ resolveSendPrompt = r;+ }),+ );++ let threw = false;+ const executorPromise = executeHeterogeneousAgent(get, defaultParams).catch(() => {+ threw = true;+ });+ await flush();++ ipc.emitRawLine('ipc-sess-1', ccInit());+ ipc.emitRawLine('ipc-sess-1', ccText('msg_01', 'done'));+ ipc.emitRawLine('ipc-sess-1', ccResult());+ ipc.emitComplete('ipc-sess-1');+ await flush();++ resolveSendPrompt!();+ await executorPromise;+ await flush();++ // The metadata save was attempted (and rejected)...+ expect(store.updateTopicMetadata).toHaveBeenCalled();+ // ...and the rejection did NOT escape to the caller (executor resolved).+ expect(threw).toBe(false);+ // The completion notification still fired (runs in onComplete, BEFORE the+ // unguarded metadata await throws).+ expect(mockSetBadgeCount).toHaveBeenCalledWith(1);+ // Current behavior: the unguarded throw bypasses the drain β it is SKIPPED.+ expect(store.drainQueuedMessages).not.toHaveBeenCalled();+ });++ // ββ 3. queue-drain gating ββ+ it('(success + queued) drains, marks unread completed, and schedules a delayed sendMessage', async () => {+ const queued = [+ {+ content: 'next message',+ editorData: undefined,+ files: [],+ id: 'q1',+ metadata: {},+ },+ ];+ const store = createMockStore({+ drainQueuedMessages: vi.fn(() => queued),+ });+ const get = vi.fn(() => store);++ // The delayed drain dispatch goes through the SINGLETON store+ // (`useChatStore.getState().sendMessage`), NOT the per-call `get()` mock β+ // so spy on the real store's sendMessage to observe it.+ const realSendMessage = vi+ .spyOn(useChatStore.getState(), 'sendMessage')+ .mockResolvedValue(undefined as any);++ let resolveSendPrompt: () => void;+ mockSendPrompt.mockReturnValue(+ new Promise<void>((r) => {+ resolveSendPrompt = r;+ }),+ );++ const executorPromise = executeHeterogeneousAgent(get, defaultParams);+ await flush();++ ipc.emitRawLine('ipc-sess-1', ccInit());+ ipc.emitRawLine('ipc-sess-1', ccText('msg_01', 'done'));+ ipc.emitRawLine('ipc-sess-1', ccResult());+ ipc.emitComplete('ipc-sess-1');+ await flush();++ resolveSendPrompt!();+ await executorPromise;+ // Extra real-time wait so the drain's `setTimeout(() => sendMessage, 100)`+ // fires before we assert on it.+ await new Promise((r) => setTimeout(r, 200));+ await flush();++ expect(store.drainQueuedMessages).toHaveBeenCalled();+ expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ // op-1 context carries agentId/topicId β markUnreadCompleted fires.+ expect(store.markUnreadCompleted).toHaveBeenCalledWith('agent-1', 'topic-1');++ // The merged follow-up is dispatched via the setTimeout(100) sendMessage.+ expect(realSendMessage).toHaveBeenCalledTimes(1);+ expect(realSendMessage).toHaveBeenCalledWith(+ expect.objectContaining({ message: 'next message' }),+ );++ realSendMessage.mockRestore();+ });++ it('(terminal type "error") does NOT drain the queue', async () => {+ const store = createMockStore({+ drainQueuedMessages: vi.fn(() => [{ content: 'queued', id: 'q1' }]),+ });++ await runToError(store);++ // Gate is `terminalEvent?.type !== 'error'` β drainQueuedMessages is never+ // even consulted, so no merged follow-up can be dispatched.+ expect(store.drainQueuedMessages).not.toHaveBeenCalled();+ });++ it('(aborted) does NOT drain the queue even on an otherwise-clean stream end', async () => {+ const abortController = new AbortController();+ abortController.abort();+ const store = createMockStore({+ drainQueuedMessages: vi.fn(() => [{ content: 'queued', id: 'q1' }]),+ operations: {+ 'op-1': {+ abortController,+ context: { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },+ metadata: { startTime: 0 },+ },+ },+ });++ await runToComplete(store, [ccInit(), ccText('msg_01', 'done'), ccResult()]);++ // Gate is `!isAborted()` β drainQueuedMessages is never consulted.+ expect(store.drainQueuedMessages).not.toHaveBeenCalled();+ });++ // ββ 4. error terminal β no notification, no drain (the onError branch) ββ+ it('an error terminal fires NO completion notification and NO queue drain', async () => {+ desktopFlag.value = true; // even on desktop, the error terminal must stay silent+ const store = createMockStore({+ drainQueuedMessages: vi.fn(() => [{ content: 'queued', id: 'q1' }]),+ });++ await runToError(store);++ // No completion signal on the error path (onComplete skips notifyCompletion+ // when isErrorTerminal).+ expect(mockShowNotification).not.toHaveBeenCalled();+ expect(mockSetBadgeCount).not.toHaveBeenCalled();+ // No queue drain on the error path (gated by terminalEvent?.type !== 'error').+ expect(store.drainQueuedMessages).not.toHaveBeenCalled();+ // The error itself is still persisted as a terminal error (persistTerminalError).+ expect(mockUpdateMessageError).toHaveBeenCalled();+ });++ // ββ 5. abort path β no notification, no drain, topic status 'active' ββ+ it('user abort fires NO notification, NO drain, and writes topic status "active"', async () => {+ desktopFlag.value = true;+ const updateTopicStatus = vi.fn();+ const abortController = new AbortController();+ abortController.abort();+ const store = createMockStore({+ drainQueuedMessages: vi.fn(() => [{ content: 'queued', id: 'q1' }]),+ operations: {+ 'op-1': {+ abortController,+ context: { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },+ metadata: { startTime: 0 },+ },+ },+ updateTopicStatus,+ });++ await runToComplete(store, [ccInit(), ccText('msg_01', 'partial'), ccResult()]);++ expect(mockShowNotification).not.toHaveBeenCalled();+ expect(mockSetBadgeCount).not.toHaveBeenCalled();+ expect(store.drainQueuedMessages).not.toHaveBeenCalled();++ // Characterize the actual behavior: onComplete's non-error branch still+ // writes 'active' (the abort gate only guards the notification + drain,+ // not the writeTopicStatus('active') call on a clean stream end).+ expect(updateTopicStatus).toHaveBeenCalledWith(+ expect.objectContaining({+ status: 'active',+ topicId: 'topic-1',+ }),+ );+ });+ });});diff --git a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.tsindex 4013d552fab..fd7a202ab09 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts@@ -1,5 +1,6 @@import type { AgentState } from '@lobechat/agent-runtime';import * as agentRuntime from '@lobechat/agent-runtime';+import type * as LobeChatConst from '@lobechat/const';import { type UIChatMessage } from '@lobechat/types';import { act, renderHook } from '@testing-library/react';import { type EnabledAiModel, ModelProvider } from 'model-bank';@@ -93,6 +94,23 @@ vi.mock('zustand/traditional');vi.mock('@/store/chat/slices/aiChat/actions/agentSignalBridge', () => ({emitClientAgentSignalSourceEvent: agentSignalBridgeMock.emitClientAgentSignalSourceEvent,}));+// Desktop notification gating: isDesktop defaults to false (web/test env), matching+// the real env so the existing suite is unaffected; flipped true per-test to exercise+// the notification branch. The service is dynamically imported inside executeClientAgent.+const desktopFlag = vi.hoisted(() => ({ value: false }));+const desktopNotificationMock = vi.hoisted(() => ({ showNotification: vi.fn() }));+vi.mock('@lobechat/const', async (importOriginal) => {+ const actual = await importOriginal<typeof LobeChatConst>();+ return {+ ...actual,+ get isDesktop() {+ return desktopFlag.value;+ },+ };+});+vi.mock('@/services/electron/desktopNotification', () => ({+ desktopNotificationService: desktopNotificationMock,+}));vi.mock('@/store/serverConfig', () => ({getServerConfigStoreState: () => ({serverConfig: { enableVisualUnderstanding: serverConfigMock.enableVisualUnderstanding },@@ -2394,4 +2412,225 @@ describe('StreamingExecutor actions', () => {resolveAgentConfigSpy.mockRestore();});});++ // Characterization net for the upcoming unified run-lifecycle refactor (LOBE-10377).+ // These lock the CURRENT client completion behavior across terminal branches so the+ // refactor can't silently drift queue-drain gating, unread marking, afterCompletion+ // timing, or the normalized client.runtime.complete signal status.+ describe('terminal-branch characterization (lifecycle refactor regression net)', () => {+ const driveTerminal = (operationId: string, status: AgentState['status']) => {+ mockInternalCreateAgentState({+ state: createMockRuntimeState(operationId, status),+ context: {+ phase: 'init',+ payload: { model: 'gpt-4o-mini', provider: 'openai' },+ session: {+ sessionId: TEST_IDS.SESSION_ID,+ messageCount: 0,+ status,+ stepCount: 1,+ },+ },+ agentConfig: createMockResolvedAgentConfig(),+ });+ };++ const restoreExecutor = () =>+ act(() => {+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });+ });++ const runExecutor = async (result: any, operationId: string) => {+ await act(async () => {+ await result.current.executeClientAgent({+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ messages: [],+ parentMessageId: TEST_IDS.USER_MESSAGE_ID,+ parentMessageType: 'user',+ operationId,+ });+ });+ };++ beforeEach(() => {+ vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({+ agentConfig: createMockAgentConfig(),+ chatConfig: createMockChatConfig(),+ isBuiltinAgent: false,+ plugins: [],+ });+ });++ it('runs afterCompletion callbacks even when the run terminates in error', async () => {+ const { result } = renderHook(() => useChatStore());+ restoreExecutor();++ let operationId!: string;+ const afterCompletion = vi.fn();+ act(() => {+ operationId = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ }).operationId;+ result.current.registerAfterCompletionCallback(operationId, afterCompletion);+ });++ driveTerminal(operationId, 'error');+ await runExecutor(result, operationId);++ expect(afterCompletion).toHaveBeenCalledTimes(1);+ expect(result.current.operations[operationId].status).toBe('failed');+ });++ it('emits client.runtime.complete with status "failed" on runtime error', async () => {+ const { result } = renderHook(() => useChatStore());+ restoreExecutor();++ let operationId!: string;+ act(() => {+ operationId = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ }).operationId;+ });++ driveTerminal(operationId, 'error');+ await runExecutor(result, operationId);++ expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({ operationId, status: 'failed' }),+ sourceId: `${operationId}:client:complete`,+ sourceType: 'client.runtime.complete',+ }),+ );+ });++ it('does NOT drain the input queue or mark unread when the run errors', async () => {+ const { result } = renderHook(() => useChatStore());+ const contextKey = messageMapKey({+ agentId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,+ });+ const drainQueuedMessages = vi.fn(() => []);+ const markUnreadCompleted = vi.fn();++ restoreExecutor();+ act(() => {+ useChatStore.setState({+ drainQueuedMessages,+ markUnreadCompleted,+ queuedMessages: {+ [contextKey]: [+ { content: 'queued', createdAt: Date.now(), id: 'q1', interruptMode: 'soft' },+ ],+ },+ });+ });++ let operationId!: string;+ act(() => {+ operationId = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ }).operationId;+ });++ driveTerminal(operationId, 'error');+ await runExecutor(result, operationId);++ expect(drainQueuedMessages).not.toHaveBeenCalled();+ expect(markUnreadCompleted).not.toHaveBeenCalled();+ });++ it('marks unread on a successful (done) terminal with an empty queue', async () => {+ const { result } = renderHook(() => useChatStore());+ const markUnreadCompleted = vi.fn();++ restoreExecutor();+ act(() => {+ useChatStore.setState({ markUnreadCompleted });+ });++ let operationId!: string;+ act(() => {+ operationId = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ }).operationId;+ });++ driveTerminal(operationId, 'done');+ await runExecutor(result, operationId);++ expect(markUnreadCompleted).toHaveBeenCalledWith(TEST_IDS.SESSION_ID, TEST_IDS.TOPIC_ID);+ expect(result.current.operations[operationId].status).toBe('completed');+ });++ describe('desktop notification gating', () => {+ afterEach(() => {+ desktopFlag.value = false;+ desktopNotificationMock.showNotification.mockClear();+ });++ const seedAssistant = (overrides: any) => {+ act(() => {+ useChatStore.setState((state) => ({+ messagesMap: {+ ...state.messagesMap,+ [messageMapKey({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID })]: [+ {+ ...createMockMessage({ id: 'assistant-notif', role: 'assistant' }),+ ...overrides,+ },+ ],+ },+ }));+ });+ };++ it('shows a desktop notification on success when the last assistant message has content and no tools', async () => {+ const { result } = renderHook(() => useChatStore());+ restoreExecutor();+ desktopFlag.value = true;++ let operationId!: string;+ act(() => {+ operationId = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ }).operationId;+ });++ seedAssistant({ content: 'hello world', tools: undefined });+ driveTerminal(operationId, 'done');+ await runExecutor(result, operationId);++ expect(desktopNotificationMock.showNotification).toHaveBeenCalledTimes(1);+ expect(desktopNotificationMock.showNotification).toHaveBeenCalledWith(+ expect.objectContaining({ body: expect.stringContaining('hello world') }),+ );+ });++ it('suppresses the notification when the last assistant message is still in tool-calling mode', async () => {+ const { result } = renderHook(() => useChatStore());+ restoreExecutor();+ desktopFlag.value = true;++ let operationId!: string;+ act(() => {+ operationId = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ }).operationId;+ });++ seedAssistant({ content: 'partial', tools: [{ id: 'tool-1' }] });+ driveTerminal(operationId, 'done');+ await runExecutor(result, operationId);++ expect(desktopNotificationMock.showNotification).not.toHaveBeenCalled();+ });+ });+ });});