π€― 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): characterize parked states + post-persist title wiring (#15847)
Arvin Xu66370675abc3
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.tsindex 02906c488fd..05cf5cc224e 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts@@ -1789,4 +1789,207 @@ describe('ConversationLifecycle actions', () => {});});});++ // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ // Characterization net for the POST-PERSIST topic-title auto-generation hook.+ //+ // After the user message is persisted (client mode), sendMessage fires a+ // fire-and-forget `summaryTitle()` (conversationLifecycle.ts ~L1004-1024) that+ // calls `summaryTopicTitle(topicId, messages)` when the gate is met:+ // - data.isCreateNewTopic === true β always summarize the new topic, OR+ // - existing topic whose `title` is empty/falsy β summarize it.+ // These tests lock the PER-PATH WIRING (which path triggers the hook), not the+ // title generation mechanism itself (that's unit-tested in topic/action.test.ts).+ // They must keep passing across the upcoming lifecycle refactor.+ //+ // NOTE on async: summaryTitle() is dispatched WITHOUT await inside sendMessage.+ // Because the spy resolves synchronously and `act(async () => await ...)` flushes+ // the microtask queue, asserting on the spy right after the awaited sendMessage+ // is reliable here.+ // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ describe('post-persist title auto-gen characterization (lifecycle refactor regression net)', () => {+ it('CLIENT new-topic path: summaryTopicTitle IS invoked with the new topicId + persisted messages', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = TEST_IDS.SESSION_ID;+ const newTopicId = TEST_IDS.NEW_TOPIC_ID;++ const summaryTopicTitleSpy = vi.fn().mockResolvedValue(undefined);+ act(() => {+ useChatStore.setState({ summaryTopicTitle: summaryTopicTitleSpy });+ });++ const persistedMessages = [+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user', topicId: newTopicId }),+ createMockMessage({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ parentId: TEST_IDS.USER_MESSAGE_ID,+ role: 'assistant',+ topicId: newTopicId,+ }),+ ];++ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ isCreateNewTopic: true,+ messages: persistedMessages,+ topicId: newTopicId,+ topics: undefined,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);++ await act(async () => {+ await result.current.sendMessage({+ context: { agentId, threadId: null, topicId: null },+ message: TEST_CONTENT.USER_MESSAGE,+ });+ });++ // new-topic gate (data.isCreateNewTopic) β summarize the freshly created topic,+ // passing data.topicId and data.messages straight through.+ expect(summaryTopicTitleSpy).toHaveBeenCalledTimes(1);+ expect(summaryTopicTitleSpy).toHaveBeenCalledWith(+ newTopicId,+ expect.arrayContaining([+ expect.objectContaining({ id: TEST_IDS.USER_MESSAGE_ID }),+ expect.objectContaining({ id: TEST_IDS.ASSISTANT_MESSAGE_ID }),+ ]),+ );+ });++ it('CLIENT existing-topic with EMPTY title: summaryTopicTitle IS invoked', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = TEST_IDS.SESSION_ID;+ const topicId = TEST_IDS.TOPIC_ID;+ const key = messageMapKey({ agentId, topicId });++ const summaryTopicTitleSpy = vi.fn().mockResolvedValue(undefined);++ // Seed an existing topic whose title is empty β this is the second gate branch.+ // currentTopicData() keys on activeAgentId, which resetTestEnvironment set to SESSION_ID.+ act(() => {+ useChatStore.setState({+ summaryTopicTitle: summaryTopicTitleSpy,+ topicDataMap: {+ [topicMapKey({ agentId })]: {+ items: [{ id: topicId, title: '' }],+ total: 1,+ },+ } as any,+ });+ });++ const persistedMessages = [+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user', topicId }),+ createMockMessage({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ parentId: TEST_IDS.USER_MESSAGE_ID,+ role: 'assistant',+ topicId,+ }),+ ];++ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ isCreateNewTopic: false,+ messages: persistedMessages,+ topicId,+ topics: undefined,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);++ await act(async () => {+ await result.current.sendMessage({+ context: { agentId, threadId: null, topicId },+ message: TEST_CONTENT.USER_MESSAGE,+ });+ });++ // empty-title gate β summarize the existing topic.+ expect(summaryTopicTitleSpy).toHaveBeenCalledTimes(1);+ // First arg is the existing topic id; messages come from the display selector+ // for the topic's message key (assistant message id filtered out).+ expect(summaryTopicTitleSpy.mock.calls[0][0]).toBe(topicId);+ // sanity: the message key exists so the selector path is real+ expect(key).toBe(messageMapKey({ agentId, topicId }));+ });++ it('CLIENT existing-topic that ALREADY has a title: summaryTopicTitle is NOT invoked (gate not met)', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = TEST_IDS.SESSION_ID;+ const topicId = TEST_IDS.TOPIC_ID;++ const summaryTopicTitleSpy = vi.fn().mockResolvedValue(undefined);++ // Existing topic WITH a non-empty title β neither gate branch fires.+ act(() => {+ useChatStore.setState({+ summaryTopicTitle: summaryTopicTitleSpy,+ topicDataMap: {+ [topicMapKey({ agentId })]: {+ items: [{ id: topicId, title: 'Already has a title' }],+ total: 1,+ },+ } as any,+ });+ });++ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ isCreateNewTopic: false,+ messages: [+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user', topicId }),+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant', topicId }),+ ],+ topics: undefined,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);++ await act(async () => {+ await result.current.sendMessage({+ context: { agentId, threadId: null, topicId },+ message: TEST_CONTENT.USER_MESSAGE,+ });+ });++ expect(summaryTopicTitleSpy).not.toHaveBeenCalled();+ });++ it('GATEWAY path: summaryTopicTitle is NOT invoked on the client sendMessage lifecycle (persistence happens inside executeGatewayAgent)', async () => {+ // OBSERVED behavior: in gateway mode sendMessage delegates to+ // `executeGatewayAgent` and `return`s early (~conversationLifecycle.ts L738),+ // BEFORE reaching the post-persist summaryTitle() block (~L1024). Message+ // creation / persistence β and any title summarization β happen server-side+ // inside the gateway run, not on this client lifecycle. So the client-side+ // summaryTopicTitle hook is NOT exercised here. Locking this no-op so the+ // refactor doesn't accidentally double-fire title generation for gateway runs.+ const { result } = renderHook(() => useChatStore());++ const summaryTopicTitleSpy = vi.fn().mockResolvedValue(undefined);+ const executeGatewayAgentSpy = vi.fn().mockResolvedValue({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ operationId: 'op-gateway',+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ });++ act(() => {+ useChatStore.setState({+ executeGatewayAgent: executeGatewayAgentSpy,+ isGatewayModeEnabled: () => true,+ summaryTopicTitle: summaryTopicTitleSpy,+ });+ });++ await act(async () => {+ await result.current.sendMessage({+ context: createTestContext(),+ message: TEST_CONTENT.USER_MESSAGE,+ });+ });++ // gateway routing was actually taken (precondition for the assertion below)+ expect(executeGatewayAgentSpy).toHaveBeenCalled();+ // and the client-side post-persist title hook was NOT reached+ expect(summaryTopicTitleSpy).not.toHaveBeenCalled();+ });+ });});diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.tsindex a5f105009b8..033a846d692 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts@@ -1240,4 +1240,143 @@ describe('createGatewayEventHandler', () => {expect(toolsDispatch![0].id).toBe('ast-new');});});++ describe('waiting_for_async_tool parked characterization (lifecycle refactor regression net)', () => {+ // CURRENT BEHAVIOR (gatewayEventHandler.ts:568-589): the `agent_runtime_end`+ // message-reconciliation branch special-cases BOTH `reason='interrupted'`+ // and `reason='waiting_for_async_tool'` together, gated by+ // `hasStreamedContent`. A `waiting_for_async_tool` terminal is a deferred-+ // tool PAUSE (the run parks waiting for an out-of-band async tool result),+ // and the server's `AgentRuntimeCoordinator.resolveUiMessages` deliberately+ // omits the uiMessages snapshot for this status. These tests lock the exact+ // client-side reconciliation the refactor must preserve.++ // (1) Parked WITH streamed content β preserve in-memory streamed content.+ // When the run parks after some server-confirmed state has landed+ // (server-assigned assistant id from stream_start + a text chunk), the+ // handler does NOT refetch from DB and does NOT replace messages β the+ // executor's partial-finalize catch is still racing to write the real+ // content, so a fetch here would clobber it with the LOADING placeholder.+ // This mirrors the `interrupted` skip exactly (same branch).+ it('should NOT refetch from DB when reason=waiting_for_async_tool AND stream had progressed (preserves streamed content)', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ // Simulate a stream that had progressed: server-assigned assistant id+ // arrived via stream_start, then a text chunk landed (hasStreamedContent).+ handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-server' } }));+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'partial answer' }));+ await flush();+ vi.mocked(messageService.getMessages).mockClear();+ store.replaceMessages.mockClear();++ handler(makeEvent('agent_runtime_end', { reason: 'waiting_for_async_tool' }));+ await flush();++ expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ // Streamed content is preserved: no DB read, no replace.+ expect(messageService.getMessages).not.toHaveBeenCalled();+ expect(store.replaceMessages).not.toHaveBeenCalled();+ });++ // (2) Parked WITHOUT streamed content β fall back to DB refetch.+ // If the run parks BEFORE any server-confirmed state landed (no+ // stream_start id, no chunks β hasStreamedContent stays false), the+ // `(interrupted || waiting_for_async_tool) && hasStreamedContent` guard is+ // false, so control falls to the `else` DB-refetch branch. This reconciles+ // the optimistic tmp_* placeholders against server rows. CURRENT BEHAVIOR β+ // verified: the refetch DOES fire here.+ it('should refetch from DB when reason=waiting_for_async_tool but stream never progressed', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ // No stream_start / stream_chunk before the park β hasStreamedContent+ // is still false.+ handler(makeEvent('agent_runtime_end', { reason: 'waiting_for_async_tool' }));+ await flush();++ expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ // Refetch IS called (falls through to the else branch).+ expect(messageService.getMessages).toHaveBeenCalled();+ expect(store.replaceMessages).toHaveBeenCalled();+ });++ // (3) uiMessages SoT still wins for a parked terminal. The+ // `Array.isArray(data?.uiMessages)` branch is checked FIRST (line 563),+ // BEFORE the `waiting_for_async_tool && hasStreamedContent` skip. So if a+ // server build DOES attach a snapshot on the park event, it takes+ // precedence over the preserve-streamed-content skip, even though the+ // stream had progressed.+ it('should use uiMessages SoT when reason=waiting_for_async_tool but server included a snapshot (precedence over the skip)', async () => {+ const store = createMockStore();+ const handler = createHandler(store);+ const uiMessages = [{ id: 'msg-server', role: 'assistant', content: 'partial' }];++ // Make the stream progress so hasStreamedContent is true β proving the+ // uiMessages branch wins even when the skip branch would otherwise apply.+ handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-server' } }));+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'partial' }));+ await flush();+ vi.mocked(messageService.getMessages).mockClear();+ store.replaceMessages.mockClear();++ handler(makeEvent('agent_runtime_end', { reason: 'waiting_for_async_tool', uiMessages }));+ await flush();++ expect(store.replaceMessages).toHaveBeenCalledWith(uiMessages, {+ action: 'gateway/agent_runtime_end',+ context: expect.any(Object),+ });+ expect(messageService.getMessages).not.toHaveBeenCalled();+ });++ // (4) Operation lifecycle on the parked terminal. CURRENT BEHAVIOR+ // (gatewayEventHandler.ts:550-557): `agent_runtime_end` ALWAYS runs the+ // same terminal sequence regardless of `reason` β it does NOT short-circuit+ // for `waiting_for_async_tool`. So a parked run still:+ // - completes the operation (completeOperation), AND+ // - marks the agent's unread state completed (markUnreadCompleted),+ // because operations['op-1'].context.agentId is present. This is arguably+ // surprising for a PAUSE (the run isn't truly finished β it's parked+ // waiting for an async tool), but it is the behavior as written. Locking it+ // here so the lifecycle refactor surfaces any change to whether a parked+ // run is treated as a completed/unread run.+ it('completes the operation AND marks unread completed on a waiting_for_async_tool park (does NOT short-circuit for the pause)', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-server' } }));+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'partial' }));+ await flush();++ handler(makeEvent('agent_runtime_end', { reason: 'waiting_for_async_tool' }));+ await flush();++ // The parked terminal runs the full agent_runtime_end sequence:+ expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ expect(store.markUnreadCompleted).toHaveBeenCalledWith('agent-1', 'topic-1');+ // It also tears down tool-calling streaming for the current assistant.+ expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith(+ 'msg-server',+ undefined,+ );+ });++ // (5) Contrast probe (mirrors the interrupted symmetry): a parked terminal+ // with NO streamed content still marks unread completed β the+ // markUnreadCompleted call is unconditional on `reason`/`hasStreamedContent`,+ // it depends ONLY on the completed op having a context.agentId. This proves+ // assertion (4) is the reason-agnostic terminal contract, not a side effect+ // of the streamed-content path.+ it('marks unread completed on a waiting_for_async_tool park even with NO streamed content', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('agent_runtime_end', { reason: 'waiting_for_async_tool' }));+ await flush();++ expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ expect(store.markUnreadCompleted).toHaveBeenCalledWith('agent-1', '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 fd7a202ab09..d1649f496b1 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts@@ -2567,6 +2567,79 @@ describe('StreamingExecutor actions', () => {expect(result.current.operations[operationId].status).toBe('completed');});+ // Parked states (run β operation). These lock the CURRENT per-state handling that+ // the unified run-lifecycle + normalized parked signal (LOBE-10382) will rewrite.+ const pinStep = (operationId: string, status: AgentState['status']) => {+ vi.spyOn(agentRuntime.AgentRuntime.prototype, 'step').mockResolvedValue({+ events: [],+ newState: createMockRuntimeState(operationId, status),+ nextContext: undefined,+ });+ };++ it('on waiting_for_async_tool: leaves the op uncompleted and emits an undefined complete-signal status', async () => {+ const { result } = renderHook(() => useChatStore());+ const drainQueuedMessages = vi.fn(() => []);+ restoreExecutor();+ act(() => {+ useChatStore.setState({ drainQueuedMessages });+ });++ let operationId!: string;+ act(() => {+ operationId = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ }).operationId;+ });++ driveTerminal(operationId, 'waiting_for_async_tool');+ pinStep(operationId, 'waiting_for_async_tool');+ await runExecutor(result, operationId);++ // CURRENT BEHAVIOR (suspected gap, locked for LOBE-10382): the completion switch+ // has no `waiting_for_async_tool` case, so the op is never completed (stays+ // 'running') and the queue is not drained.+ expect(result.current.operations[operationId].status).toBe('running');+ expect(drainQueuedMessages).not.toHaveBeenCalled();++ // normalizeClientRuntimeCompleteStatus falls through for async_tool β undefined.+ const completeCall = agentSignalBridgeMock.emitClientAgentSignalSourceEvent.mock.calls.find(+ (c: any) => c[0]?.sourceType === 'client.runtime.complete',+ );+ expect(completeCall).toBeTruthy();+ expect(completeCall![0].payload.status).toBeUndefined();+ });++ it('on waiting_for_human (parked): completes the op for the UI but does NOT drain queue or mark unread', async () => {+ const { result } = renderHook(() => useChatStore());+ const drainQueuedMessages = vi.fn(() => []);+ const markUnreadCompleted = vi.fn();+ restoreExecutor();+ act(() => {+ useChatStore.setState({ drainQueuedMessages, 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, 'waiting_for_human');+ pinStep(operationId, 'waiting_for_human');+ await runExecutor(result, operationId);++ // Parked β terminal: the op is completed so the loading UI clears, but the+ // success-only terminal effects (queue drain, unread marker) MUST NOT fire β a+ // new operation runs them when the user approves/rejects.+ expect(result.current.operations[operationId].status).toBe('completed');+ expect(drainQueuedMessages).not.toHaveBeenCalled();+ expect(markUnreadCompleted).not.toHaveBeenCalled();+ });+describe('desktop notification gating', () => {afterEach(() => {desktopFlag.value = false;