🤯 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
🐛 fix(notification): announce failed agent runs instead of an empty completion (#21279)
Arvin Xucc25f2a91b4f
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex bd3c95ee6bb..50034190f18 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -369,10 +369,14 @@"defaultGroupChat": "Group","defaultList": "Default List","defaultSession": "Default Agent",+ "desktopNotification.agentFailed.body": "Open the conversation for details",+ "desktopNotification.agentFailed.title": "{{name}} ran into a problem","desktopNotification.aiReplyCompleted.body": "Agent reply is ready","desktopNotification.aiReplyCompleted.title": "Reply completed","desktopNotification.humanApprovalRequired.body": "An Agent needs your approval to continue","desktopNotification.humanApprovalRequired.title": "Approval required",+ "desktopNotification.workingDirectoryUnavailable.body": "Working directory unavailable: {{path}}",+ "desktopNotification.workingDirectoryUnavailable.bodyWithoutPath": "Working directory unavailable: the folder saved for this conversation no longer exists","devinInstallGuide.actions.openDocs": "Open Install Guide","devinInstallGuide.actions.openSystemTools": "Open System Tools","devinInstallGuide.afterInstall": "After installing, run `devin auth login`, then retry your message or click Re-detect in System Tools.",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex bc3cee528c6..3841939fc0f 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -369,10 +369,14 @@"defaultGroupChat": "群组","defaultList": "默认列表","defaultSession": "自定义助理",+ "desktopNotification.agentFailed.body": "打开会话查看详情",+ "desktopNotification.agentFailed.title": "{{name}} 遇到了执行问题","desktopNotification.aiReplyCompleted.body": "AI 回复生成完成","desktopNotification.aiReplyCompleted.title": "AI 回复完成","desktopNotification.humanApprovalRequired.body": "Agent 需要你的批准后才能继续","desktopNotification.humanApprovalRequired.title": "需要你的批准",+ "desktopNotification.workingDirectoryUnavailable.body": "工作目录不可用:{{path}}",+ "desktopNotification.workingDirectoryUnavailable.bodyWithoutPath": "工作目录不可用:此会话保存的目录已不存在","devinInstallGuide.actions.openDocs": "打开安装指南","devinInstallGuide.actions.openSystemTools": "打开系统工具","devinInstallGuide.afterInstall": "安装完成后,请运行 `devin auth login` 登录,然后重试刚才的消息,或在系统工具中点击“重新检测”。",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex eae41749a00..699aa9a9bdc 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -339,10 +339,15 @@ export default {'defaultGroupChat': 'Group','defaultList': 'Default List','defaultSession': 'Default Agent',+ 'desktopNotification.agentFailed.body': 'Open the conversation for details',+ 'desktopNotification.agentFailed.title': '{{name}} ran into a problem','desktopNotification.aiReplyCompleted.body': 'Agent reply is ready','desktopNotification.aiReplyCompleted.title': 'Reply completed','desktopNotification.humanApprovalRequired.body': 'An Agent needs your approval to continue','desktopNotification.humanApprovalRequired.title': 'Approval required',+ 'desktopNotification.workingDirectoryUnavailable.body': 'Working directory unavailable: {{path}}',+ 'desktopNotification.workingDirectoryUnavailable.bodyWithoutPath':+ 'Working directory unavailable: the folder saved for this conversation no longer exists','cliDetectionTimeoutGuide.actions.openSystemTools': 'Open System Tools','cliDetectionTimeoutGuide.actions.retry': 'Detect again','cliDetectionTimeoutGuide.desc':diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.tsdeleted file mode 100644index 7a6b6b7c339..00000000000--- a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts+++ /dev/null@@ -1,1870 +0,0 @@-import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';-import { createAdapter } from '@lobechat/heterogeneous-agents';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { messageService } from '@/services/message';-import type * as WorkServiceModule from '@/services/work';-import { workService } from '@/services/work';-import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge';-import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';--import { buildRunLifecycle } from '../lifecycle/buildRunLifecycle';-import { createGatewayEventHandler } from '../transports/gateway/gatewayEventHandler';--vi.mock('@/services/message', () => ({- messageService: {- getMessages: vi.fn().mockResolvedValue([]),- updateMessageError: vi.fn().mockResolvedValue({ success: true }),- },-}));-vi.mock('@/services/work', async (importOriginal) => {- const actual = await importOriginal<typeof WorkServiceModule>();- return {- ...actual,- workService: {- refreshConversationViews: vi.fn().mockResolvedValue(undefined),- },- };-});-vi.mock('@/store/chat/utils/desktopNotification', () => ({- notifyDesktopHumanApprovalRequired: vi.fn().mockResolvedValue(undefined),-}));-vi.mock('@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge', () => ({- emitClientAgentSignalSourceEvent: vi.fn().mockResolvedValue(undefined),-}));--const getExecutorMock = vi.fn();-vi.mock('@/store/tool/slices/builtin/executors', () => ({- getExecutor: (...args: unknown[]) => getExecutorMock(...args),- registerBuiltinToolExecutors: vi.fn().mockResolvedValue(undefined),-}));--// ─── Test Helpers ───--function createMockStore() {- let reasoningCounter = 0;- return {- associateMessageWithOperation: vi.fn(),- completeOperation: vi.fn(),- // completeRun (via buildRunLifecycle) drains the input queue on a successful- // terminal and fails the op on an errored terminal.- dbMessagesMap: {} as Record<string, any>,- drainQueuedMessages: vi.fn(() => [] as any[]),- failOperation: vi.fn(),- internal_dispatchMessage: vi.fn(),- internal_executeClientTool: vi.fn().mockResolvedValue(undefined),- internal_toggleToolCallingStreaming: vi.fn(),- markTopicUnread: vi.fn(),- messagesMap: {} as Record<string, any>,- topicDataMap: {},- operations: {- 'op-1': {- context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' },- metadata: { startTime: 0 },- },- } as Record<string, any>,- operationsByContext: {},- replaceMessages: vi.fn(),- startOperation: vi.fn(() => {- reasoningCounter += 1;- return {- abortController: new AbortController(),- operationId: `op-reasoning-${reasoningCounter}`,- };- }),- updateOperationMetadata: vi.fn(),- updateTopicStatus: vi.fn().mockResolvedValue(undefined),- };-}--function createHandler(- store: ReturnType<typeof createMockStore>,- overrides?: { assistantMessageId?: string; gatewayOperationId?: string },-) {- const get = vi.fn(() => store) as any;- const assistantMessageId = overrides?.assistantMessageId ?? 'msg-initial';- const context = { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' } as any;- return createGatewayEventHandler(get, {- assistantMessageId,- context,- gatewayOperationId: overrides?.gatewayOperationId,- operationId: 'op-1',- // The gateway transport injects the shared run lifecycle (built once per run- // in gateway.ts). Build the real one here so the terminal completeRun /- // afterRunComplete path under test runs against the mock store.- runLifecycle: buildRunLifecycle(get, {- context,- parentMessageId: assistantMessageId,- parentMessageType: 'assistant',- runId: 'op-1',- runScope: 'top_level',- runtimeType: 'gateway',- }),- });-}--function makeEvent(type: AgentStreamEvent['type'], data?: any): AgentStreamEvent {- return { data, id: '1', operationId: 'op-1', stepIndex: 0, timestamp: Date.now(), type };-}--/** Flush the async processing queue by draining microtasks + setTimeout queue */-const flush = async () => {- for (let i = 0; i < 5; i++) {- await new Promise((r) => setTimeout(r, 15));- }-};--// ─── Tests ───--describe('createGatewayEventHandler', () => {- beforeEach(() => {- vi.clearAllMocks();- });-- describe('stream_start', () => {- it('should associate new message with operation and skip the DB refetch', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(- makeEvent('stream_start', {- assistantMessage: { id: 'msg-step2', role: 'assistant' },- }),- );- await flush();-- expect(store.associateMessageWithOperation).toHaveBeenCalledWith('msg-step2', 'op-1');- // Native gateway ships the assistant seed on stream_start, so the client- // inserts the message shell locally (createMessage) and must NOT trigger a- // DB refetch — the refetch is what clobbered the streamed assistantGroup- // with a stale placeholder.- expect(store.internal_dispatchMessage).toHaveBeenCalledWith(- expect.objectContaining({ id: 'msg-step2', type: 'createMessage' }),- { operationId: 'op-1' },- );- expect(messageService.getMessages).not.toHaveBeenCalled();- expect(store.replaceMessages).not.toHaveBeenCalled();- expect(emitClientAgentSignalSourceEvent).toHaveBeenCalledWith(- expect.objectContaining({- payload: expect.objectContaining({- anchorMessageId: 'msg-step2',- assistantMessageId: 'msg-step2',- operationId: 'op-1',- stepIndex: 0,- }),- sourceType: 'client.gateway.stream_start',- }),- );- });-- it('should keep current ID if event data has no assistantMessage', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('stream_start', {}));- await flush();-- // No new message to associate, but fetch still happens- expect(store.associateMessageWithOperation).not.toHaveBeenCalled();- expect(store.replaceMessages).toHaveBeenCalled();- });-- it('should resolve the new assistant from DB on hetero newStep when the event has no assistantMessage id', async () => {- const store = createMockStore();- const handler = createHandler(store);-- vi.mocked(messageService.getMessages).mockResolvedValueOnce([- { id: 'msg-initial', role: 'assistant' } as any,- { id: 'tool-1', role: 'tool' } as any,- { id: 'msg-step2', role: 'assistant' } as any,- ]);-- handler(makeEvent('stream_start', { newStep: true }));- handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'world' }));- await flush();-- expect(store.associateMessageWithOperation).toHaveBeenCalledWith('msg-step2', 'op-1');- expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(- expect.objectContaining({- id: 'msg-step2',- value: { content: 'world' },- }),- { operationId: 'op-1' },- );- });-- it('should reset accumulators on each stream_start', async () => {- const store = createMockStore();- const handler = createHandler(store);-- // Accumulate some content- handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'hello' }));- await flush();- expect(store.internal_dispatchMessage).toHaveBeenCalledWith(- expect.objectContaining({ value: { content: 'hello' } }),- { operationId: 'op-1' },- );-- // New stream_start resets- handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-step2' } }));- handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'world' }));- await flush();-- // Content should be 'world', not 'helloworld'- expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(- expect.objectContaining({- id: 'msg-step2',- value: { content: 'world' },- }),- { operationId: 'op-1' },- );- });- });-- describe('stream_chunk', () => {- it('should accumulate text content and pass operationId context', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'Hello' }));- handler(makeEvent('stream_chunk', { chunkType: 'text', content: ' world' }));- await flush();-- expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(- {- id: 'msg-initial',- type: 'updateMessage',- value: { content: 'Hello world' },- },- { operationId: 'op-1' },- );- });-- it('applies replace snapshots and drops redelivered snapshot seqs', async () => {- const store = createMockStore();- const handler = createHandler(store);-- // `lh hetero exec` sends full-text snapshots: each carries the WHOLE- // message so far and must replace, not append.- handler(- makeEvent('stream_chunk', {- chunkType: 'text',- content: 'Hello',- snapshotMode: 'replace',- snapshotSeq: 1,- }),- );- handler(- makeEvent('stream_chunk', {- chunkType: 'text',- content: 'Hello world',- snapshotMode: 'replace',- snapshotSeq: 2,- }),- );- // Redelivery of seq 2 (server-side batch retry) — must be dropped, not- // appended: appending would render "Hello worldHello world".- handler(- makeEvent('stream_chunk', {- chunkType: 'text',- content: 'Hello world',- snapshotMode: 'replace',- snapshotSeq: 2,- }),- );- await flush();-- expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(- {- id: 'msg-initial',- type: 'updateMessage',- value: { content: 'Hello world' },- },- { operationId: 'op-1' },- );- const textDispatches = store.internal_dispatchMessage.mock.calls.filter(- ([action]: any[]) => action.type === 'updateMessage' && 'content' in action.value,- );- expect(textDispatches).toHaveLength(2); // the redelivered snapshot dispatched nothing- });-- it('applies reasoning replace snapshots and drops redelivered seqs', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(- makeEvent('stream_chunk', {- chunkType: 'reasoning',- reasoning: 'thinking',- snapshotMode: 'replace',- snapshotSeq: 1,- }),- );- handler(- makeEvent('stream_chunk', {- chunkType: 'reasoning',- reasoning: 'thinking done',- snapshotMode: 'replace',- snapshotSeq: 2,- }),- );- // Redelivered seq 2 — appending it would render "thinking donethinking done".- handler(- makeEvent('stream_chunk', {- chunkType: 'reasoning',- reasoning: 'thinking done',- snapshotMode: 'replace',- snapshotSeq: 2,- }),- );- await flush();-- const reasoningDispatches = store.internal_dispatchMessage.mock.calls.filter(- ([action]: any[]) => action.type === 'updateMessage' && 'reasoning' in action.value,- );- expect(reasoningDispatches).toHaveLength(2); // duplicate dropped- expect(reasoningDispatches.at(-1)?.[0].value).toEqual({- reasoning: { content: 'thinking done' },- });- });-- it('a snapshot replaces text accumulated from plain deltas', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'Hel' }));- handler(- makeEvent('stream_chunk', {- chunkType: 'text',- content: 'Hello world',- snapshotMode: 'replace',- snapshotSeq: 1,- }),- );- await flush();-- // Replace, not append — appending would render "HelHello world".- expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(- {- id: 'msg-initial',- type: 'updateMessage',- value: { content: 'Hello world' },- },- { operationId: 'op-1' },- );- });-- it('should accumulate reasoning content', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'Think' }));- handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'ing...' }));- await flush();-- expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(- {- id: 'msg-initial',- type: 'updateMessage',- value: { reasoning: { content: 'Thinking...' } },- },- { operationId: 'op-1' },- );- });-- it('should dispatch tools and toggle tool calling streaming', async () => {- const store = createMockStore();- const handler = createHandler(store);-- const toolsCalling = [{ id: 'tc-1' }, { id: 'tc-2' }];- handler(makeEvent('stream_chunk', { chunkType: 'tools_calling', toolsCalling }));- await flush();-- expect(store.internal_dispatchMessage).toHaveBeenCalledWith(- {- id: 'msg-initial',- type: 'updateMessage',- value: { tools: toolsCalling },- },- { operationId: 'op-1' },- );-- expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith('msg-initial', [- true,- true,- ]);- });-- it('should ignore chunk with no data', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('stream_chunk', undefined));- await flush();-- expect(store.internal_dispatchMessage).not.toHaveBeenCalled();- });-- it('should DROP subagent-tagged tool chunks so they do not leak into the main bubble', async () => {- // Regression: on a live gateway / remote-CC stream, a subagent (Agent/Task)- // inner tool chunk is tagged with `data.subagent`. It belongs to an- // isolation Thread, not the main assistant. If dispatched here it appends- // to the MAIN assistant's tools[] until the terminal DB refetch corrects it- // ("流式时漏出来、结束后正常"). It must be dropped before any dispatch.- const store = createMockStore();- const handler = createHandler(store);-- handler(- makeEvent('stream_chunk', {- chunkType: 'tools_calling',- subagent: { parentToolCallId: 'toolu_agent', subagentMessageId: 'sub-1' },- toolsCalling: [{ id: 'inner-1' }],- }),- );- await flush();-- // Not dispatched onto the main assistant, and no tool-calling spinner.- expect(store.internal_dispatchMessage).not.toHaveBeenCalled();- expect(store.internal_toggleToolCallingStreaming).not.toHaveBeenCalled();- });-- it('should still dispatch a NON-subagent tool chunk (drop is scoped to subagent)', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(- makeEvent('stream_chunk', { chunkType: 'tools_calling', toolsCalling: [{ id: 'm-1' }] }),- );- await flush();-- expect(store.internal_dispatchMessage).toHaveBeenCalledWith(- { id: 'msg-initial', type: 'updateMessage', value: { tools: [{ id: 'm-1' }] } },- { operationId: 'op-1' },- );- });- });-- describe('reasoning operation lifecycle', () => {- it('starts a reasoning op on the first reasoning chunk and associates it with the current assistant', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'pondering' }));- handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: '...' }));- await flush();-- // Only one startOperation call — second chunk reuses the existing op- expect(store.startOperation).toHaveBeenCalledTimes(1);- expect(store.startOperation).toHaveBeenCalledWith({- context: expect.objectContaining({- agentId: 'agent-1',- messageId: 'msg-initial',- topicId: 'topic-1',- }),- parentOperationId: 'op-1',- type: 'reasoning',- });- expect(store.associateMessageWithOperation).toHaveBeenCalledWith(- 'msg-initial',- 'op-reasoning-1',- );- // The reasoning op is NOT completed while only reasoning chunks have arrived- expect(store.completeOperation).not.toHaveBeenCalled();- });-- it('completes the reasoning op when text starts streaming', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'thinking' }));- handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'answer' }));- await flush();-- expect(store.completeOperation).toHaveBeenCalledWith('op-reasoning-1');- });-- it('completes the reasoning op when tools_calling starts', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'thinking' }));- handler(- makeEvent('stream_chunk', {- chunkType: 'tools_calling',- toolsCalling: [{ id: 'tc-1' }],- }),- );- await flush();-- expect(store.completeOperation).toHaveBeenCalledWith('op-reasoning-1');- });-- it('starts a new reasoning op when reasoning resumes after text in the same stream', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'first pass' }));- handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'partial' }));- handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'second pass' }));- await flush();-- expect(store.startOperation).toHaveBeenCalledTimes(2);- expect(store.completeOperation).toHaveBeenCalledWith('op-reasoning-1');- expect(store.completeOperation).not.toHaveBeenCalledWith('op-reasoning-2');- });-- it('completes any open reasoning op on stream_end', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'thinking' }));- handler(makeEvent('stream_end'));- await flush();-- expect(store.completeOperation).toHaveBeenCalledWith('op-reasoning-1');- });-- it('completes any open reasoning op on stream_start (carry-over between steps)', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'thinking' }));- handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-step2' } }));- await flush();-- expect(store.completeOperation).toHaveBeenCalledWith('op-reasoning-1');- });-- it('completes any open reasoning op on agent_runtime_end', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'thinking' }));- handler(makeEvent('agent_runtime_end'));- await flush();-- expect(store.completeOperation).toHaveBeenCalledWith('op-reasoning-1');- });-- it('completes any open reasoning op on error', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'thinking' }));- handler(makeEvent('error', { message: 'boom' }));- await flush();-- expect(store.completeOperation).toHaveBeenCalledWith('op-reasoning-1');- });-- it('does not start a reasoning op for text-only streams', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'hello' }));- handler(makeEvent('stream_end'));- await flush();-- expect(store.startOperation).not.toHaveBeenCalled();- });- });-- describe('stream_end', () => {- it('keeps visible loading for a plain no-tool stream boundary', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'hello back' }));- handler(makeEvent('stream_end'));- await flush();-- expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith(- 'msg-initial',- undefined,- );- expect(store.updateOperationMetadata).not.toHaveBeenCalledWith('op-1', {- visibleLoadingDone: true,- });- expect(store.completeOperation).not.toHaveBeenCalledWith('op-1');- });-- it('keeps visible loading after stream_end when tool calls need another step', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(- makeEvent('stream_chunk', {- chunkType: 'tools_calling',- toolsCalling: [{ id: 'tc-1' }],- }),- );- handler(makeEvent('stream_end'));- await flush();-- expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith(- 'msg-initial',- undefined,- );- expect(store.updateOperationMetadata).not.toHaveBeenCalledWith('op-1', {- visibleLoadingDone: true,- });- expect(store.completeOperation).not.toHaveBeenCalledWith('op-1');- });-- it('applies finalContent before ending a reasoning-only stream', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'thinking text' }));- handler(makeEvent('stream_end', { finalContent: 'final answer' }));- await flush();-- expect(store.internal_dispatchMessage).toHaveBeenCalledWith(- {- id: 'msg-initial',- type: 'updateMessage',- value: { content: 'final answer' },- },- { operationId: 'op-1' },- );- expect(store.completeOperation).toHaveBeenCalledWith('op-reasoning-1');- expect(store.updateOperationMetadata).not.toHaveBeenCalledWith('op-1', {- visibleLoadingDone: true,- });- });-- it('should clear tool streaming', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('stream_end'));- await flush();-- expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith(- 'msg-initial',- undefined,- );- });- });-- describe('visible_output_end', () => {- it('marks visible loading done without completing the operation or clearing topic loading', async () => {- const store = createMockStore();- // The streamed content has landed in the store — the visible_output_end- // guard only clears loading once the assistant row is present- // with its content, so seed it here to represent that state.- store.dbMessagesMap['main_agent-1_topic-1'] = [- { content: 'hello back', id: 'msg-initial', role: 'assistant' },- ];- const handler = createHandler(store);-- handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'hello back' }));- handler(makeEvent('visible_output_end'));- await flush();-- expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith(- 'msg-initial',- undefined,- );- expect(store.updateOperationMetadata).toHaveBeenCalledWith('op-1', {- visibleLoadingDone: true,- });- expect(store.completeOperation).not.toHaveBeenCalledWith('op-1');- });- });-- describe('tool_start', () => {- it('should be a no-op (loading already active from stream_start)', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('tool_start', { parentMessageId: 'msg-initial', toolCalling: {} }));- await flush();-- expect(store.internal_dispatchMessage).not.toHaveBeenCalled();- expect(store.replaceMessages).not.toHaveBeenCalled();- });- });-- describe('step_start', () => {- it('should notify desktop when human approval is required', () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(- makeEvent('step_start', {- pendingToolsCalling: [{ id: 'tool-1' }],- phase: 'human_approval',- requiresApproval: true,- }),- );-- expect(notifyDesktopHumanApprovalRequired).toHaveBeenCalledWith(- expect.any(Function),- expect.objectContaining({- agentId: 'agent-1',- topicId: 'topic-1',- }),- );- expect(store.updateTopicStatus).toHaveBeenCalledWith(- expect.objectContaining({- agentId: 'agent-1',- status: 'waitingForHuman',- topicId: 'topic-1',- }),- );- });- });-- describe('tool_execute', () => {- const toolExecuteData = {- apiName: 'readFile',- arguments: '{"path":"/tmp/a.txt"}',- executionTimeoutMs: 60_000,- identifier: 'local-system',- toolCallId: 'call_1',- };-- it('forwards the payload to internal_executeClientTool with operationId', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('tool_execute', toolExecuteData));- await flush();-- expect(store.internal_executeClientTool).toHaveBeenCalledWith(toolExecuteData, {- localOperationId: 'op-1',- operationId: 'op-1',- });- });-- it('uses gatewayOperationId (WS key) when distinct from local operationId', async () => {- // Locally the handler tracks `op-1` (used for message dispatch), but- // the Agent Gateway WS is keyed on the server-side id `gw-op-server`.- // The action must receive the latter so it can look up the live- // AgentStreamClient in `gatewayConnections` and reply with tool_result.- const store = createMockStore();- const handler = createHandler(store, { gatewayOperationId: 'gw-op-server' });-- handler(makeEvent('tool_execute', toolExecuteData));- await flush();-- expect(store.internal_executeClientTool).toHaveBeenCalledWith(toolExecuteData, {- localOperationId: 'op-1',- operationId: 'gw-op-server',- });- });-- it('is fire-and-forget — does not block the event pipeline', async () => {- const store = createMockStore();- // Simulate a slow tool execution that never resolves- store.internal_executeClientTool.mockImplementation(() => new Promise(() => {}));- const handler = createHandler(store);-- handler(makeEvent('tool_execute', toolExecuteData));- // If the handler awaited the action, this subsequent stream_chunk would- // be queued behind the pending promise forever. We assert it still runs.- handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'hi' }));- await flush();-- expect(store.internal_dispatchMessage).toHaveBeenCalledWith(- expect.objectContaining({ value: { content: 'hi' } }),- expect.any(Object),- );- });-- it('ignores tool_execute events without data', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('tool_execute'));- await flush();-- expect(store.internal_executeClientTool).not.toHaveBeenCalled();- });- });-- describe('tool_end', () => {- it('should refresh messages to pull tool results', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('tool_end', { isSuccess: true }));- await flush();-- expect(store.replaceMessages).toHaveBeenCalled();- });-- it('should dispatch onAfterCall when payload is wrapped as { parentMessageId, toolCalling } (real gateway shape)', async () => {- const store = createMockStore();- const handler = createHandler(store);- const onAfterCall = vi.fn().mockResolvedValue(undefined);- getExecutorMock.mockReturnValueOnce({ onAfterCall });-- handler(- makeEvent('tool_end', {- isSuccess: true,- payload: {- parentMessageId: 'msg-parent',- toolCalling: {- apiName: 'deleteTask',- arguments: JSON.stringify({ identifier: 'T-3' }),- id: 'tc-1',- identifier: 'lobe-task',- },- },- result: { content: 'Task deleted', success: true },- }),- );- await flush();-- expect(getExecutorMock).toHaveBeenCalledWith('lobe-task');- expect(onAfterCall).toHaveBeenCalledWith({- apiName: 'deleteTask',- identifier: 'lobe-task',- params: { identifier: 'T-3' },- result: { content: 'Task deleted', success: true },- toolCallId: 'tc-1',- topicId: 'topic-1',- });- });-- it('should also dispatch onAfterCall when payload is the flat ChatToolPayload', async () => {- const store = createMockStore();- const handler = createHandler(store);- const onAfterCall = vi.fn().mockResolvedValue(undefined);- getExecutorMock.mockReturnValueOnce({ onAfterCall });-- handler(- makeEvent('tool_end', {- isSuccess: true,- payload: {- apiName: 'createTask',- arguments: JSON.stringify({ name: 'New', instruction: 'do thing' }),- id: 'tc-2',- identifier: 'lobe-task',- },- result: { success: true },- }),- );- await flush();-- expect(onAfterCall).toHaveBeenCalledWith(- expect.objectContaining({- apiName: 'createTask',- identifier: 'lobe-task',- toolCallId: 'tc-2',- }),- );- });-- it('dispatches a Kimi Code Shell result through the registered renderer hook contract', async () => {- const store = createMockStore();- const handler = createHandler(store);- const onAfterCall = vi.fn().mockResolvedValue(undefined);- getExecutorMock.mockReturnValueOnce({ onAfterCall });- const adapter = createAdapter('kimi-code');-- adapter.adapt({- role: 'assistant',- tool_calls: [- {- function: {- arguments: JSON.stringify({ command: 'git worktree add /tmp/kimi-wt' }),- name: 'Shell',- },- id: 'kimi-shell-1',- type: 'function',- },- ],- });- const toolEnd = adapter- .adapt({ content: 'created', role: 'tool', tool_call_id: 'kimi-shell-1' })- .find((event) => event.type === 'tool_end');-- expect(toolEnd).toBeDefined();- handler(makeEvent('tool_end', toolEnd!.data));- await flush();-- expect(getExecutorMock).toHaveBeenCalledWith('kimi-code');- expect(onAfterCall).toHaveBeenCalledWith({- apiName: 'Shell',- identifier: 'kimi-code',- params: { command: 'git worktree add /tmp/kimi-wt' },- result: { content: 'created', success: true },- toolCallId: 'kimi-shell-1',- topicId: 'topic-1',- });- });-- it('should skip onAfterCall when payload identifier/apiName are missing', async () => {- const store = createMockStore();- const handler = createHandler(store);- const onAfterCall = vi.fn();- getExecutorMock.mockReturnValue({ onAfterCall });-- handler(makeEvent('tool_end', { isSuccess: true, payload: { parentMessageId: 'x' } }));- await flush();-- expect(onAfterCall).not.toHaveBeenCalled();- });- });-- describe('tool_start', () => {- it('should dispatch onBeforeCall with the unwrapped ChatToolPayload', async () => {- const store = createMockStore();- const handler = createHandler(store);- const onBeforeCall = vi.fn().mockResolvedValue(undefined);- getExecutorMock.mockReturnValueOnce({ onBeforeCall });-- handler(- makeEvent('tool_start', {- parentMessageId: 'msg-parent',- toolCalling: {- apiName: 'editTask',- arguments: JSON.stringify({ identifier: 'T-5', name: 'renamed' }),- id: 'tc-3',- identifier: 'lobe-task',- },- }),- );- await flush();-- expect(onBeforeCall).toHaveBeenCalledWith({- apiName: 'editTask',- identifier: 'lobe-task',- params: { identifier: 'T-5', name: 'renamed' },- toolCallId: 'tc-3',- topicId: 'topic-1',- });- });- });-- describe('step_complete', () => {- it('should refresh on execution_complete phase', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('step_complete', { phase: 'execution_complete', reason: 'done' }));- await flush();-- expect(store.replaceMessages).toHaveBeenCalled();- });-- it('should not refresh on other phases', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('step_complete', { phase: 'human_approval' }));- await flush();-- expect(store.replaceMessages).not.toHaveBeenCalled();- });- });-- describe('agent_runtime_end', () => {- it('should complete operation and refresh messages', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('agent_runtime_end'));- await flush();-- expect(store.completeOperation).toHaveBeenCalledWith('op-1');- expect(store.replaceMessages).toHaveBeenCalled();- expect(workService.refreshConversationViews).not.toHaveBeenCalled();- });-- it('should refresh Work views once after a run with a Work-mutating tool', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(- makeEvent('tool_end', {- isSuccess: true,- payload: {- parentMessageId: 'msg-parent',- toolCalling: {- apiName: 'createTask',- arguments: '{}',- id: 'tool-call-1',- identifier: 'lobe-task',- },- },- result: { success: true, workRegistration: { type: 'task' } },- }),- );- handler(makeEvent('agent_runtime_end', { uiMessages: [] }));- await flush();-- expect(workService.refreshConversationViews).toHaveBeenCalledTimes(1);- expect(workService.refreshConversationViews).toHaveBeenCalledWith('topic-1', undefined);- });-- it('should emit runtime end signal with the current assistant message id', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-step2' } }));- handler(makeEvent('agent_runtime_end'));- await flush();-- expect(emitClientAgentSignalSourceEvent).toHaveBeenLastCalledWith(- expect.objectContaining({- payload: expect.objectContaining({- anchorMessageId: 'msg-step2',- assistantMessageId: 'msg-step2',- operationId: 'op-1',- }),- sourceType: 'client.gateway.runtime_end',- }),- );- });-- // MID-stream cancel. The server-side coordinator skips the- // uiMessages snapshot when state.status='interrupted' to avoid pushing- // a LOADING_FLAT placeholder. The client must mirror that intent: when- // `reason='interrupted'` arrives without uiMessages AND we already have- // server-confirmed streamed state, do NOT fall back to a DB refetch —- // the executor's partial-finalize catch is still racing to write the- // real content, and a fetch here would return placeholder and clobber- // in-memory streamed content.- it('should NOT refetch from DB when reason=interrupted AND stream had progressed', 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.- 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: 'interrupted' }));- await flush();-- expect(store.completeOperation).toHaveBeenCalledWith('op-1');- expect(messageService.getMessages).not.toHaveBeenCalled();- expect(store.replaceMessages).not.toHaveBeenCalled();- });-- // Reviewer feedback on PR #15173: if cancel arrives BEFORE any- // stream activity (no server-assigned assistant id, no chunks), the- // optimistic `tmp_*` placeholder messages are the only client-side- // state and they need the DB refetch to be reconciled with the- // server-side rows. Skipping the fallback would leave the tmp_*- // ids stuck in the store indefinitely.- it('should refetch from DB when reason=interrupted but stream never progressed', async () => {- const store = createMockStore();- const handler = createHandler(store);-- // No stream_start / stream_chunk before the cancel — only optimistic- // local state exists, no server-confirmed assistant id, no chunks.- handler(makeEvent('agent_runtime_end', { reason: 'interrupted' }));- await flush();-- expect(store.completeOperation).toHaveBeenCalledWith('op-1');- // Refetch IS called so the tmp_* placeholders get reconciled.- expect(messageService.getMessages).toHaveBeenCalled();- expect(store.replaceMessages).toHaveBeenCalled();- });-- it('should still use uiMessages SoT when reason=interrupted but server included a snapshot', async () => {- const store = createMockStore();- const handler = createHandler(store);- const uiMessages = [{ id: 'msg-initial', role: 'assistant', content: 'partial' }];-- handler(- makeEvent('agent_runtime_end', {- reason: 'interrupted',- uiMessages,- }),- );- await flush();-- // uiMessages present takes precedence over the interrupted skip — the- // SoT push is authoritative when server chose to send it.- expect(store.replaceMessages).toHaveBeenCalledWith(uiMessages, {- action: 'gateway/agent_runtime_end',- context: expect.any(Object),- });- expect(messageService.getMessages).not.toHaveBeenCalled();- });- });-- describe('error', () => {- it('should dispatch inline error, complete operation, and refresh messages', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('error', { message: 'Something went wrong' }));- await flush();-- expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith(- 'msg-initial',- undefined,- );- // error→fail: an errored gateway run FAILS the op (not complete).- expect(store.failOperation).toHaveBeenCalledWith('op-1', expect.anything());- expect(store.completeOperation).not.toHaveBeenCalled();- expect(messageService.updateMessageError).toHaveBeenCalledWith(- 'msg-initial',- expect.objectContaining({- body: { message: 'Something went wrong' },- message: 'Something went wrong',- type: 'AgentRuntimeError',- }),- {- agentId: 'agent-1',- groupId: undefined,- threadId: undefined,- topicId: 'topic-1',- },- );-- // Should dispatch inline error immediately- expect(store.internal_dispatchMessage).toHaveBeenCalledWith(- {- id: 'msg-initial',- type: 'updateMessage',- value: {- error: expect.objectContaining({- body: { message: 'Something went wrong' },- message: 'Something went wrong',- type: 'AgentRuntimeError',- }),- },- },- { operationId: 'op-1' },- );-- // Should also refresh messages- expect(store.replaceMessages).toHaveBeenCalled();- });-- it('should dispatch inline error with switched message ID', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-step2' } }));- handler(makeEvent('error', { error: 'Timeout' }));- await flush();-- expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith(- 'msg-step2',- undefined,- );- expect(store.failOperation).toHaveBeenCalledWith('op-1', expect.anything());- expect(store.completeOperation).not.toHaveBeenCalled();- expect(messageService.updateMessageError).toHaveBeenCalledWith(- 'msg-step2',- expect.objectContaining({- body: { error: 'Timeout' },- message: 'Timeout',- type: 'AgentRuntimeError',- }),- {- agentId: 'agent-1',- groupId: undefined,- threadId: undefined,- topicId: 'topic-1',- },- );-- // Should dispatch inline error with the switched message ID- expect(store.internal_dispatchMessage).toHaveBeenCalledWith(- expect.objectContaining({- id: 'msg-step2',- value: expect.objectContaining({- error: expect.objectContaining({- message: 'Timeout',- body: { error: 'Timeout' },- }),- }),- }),- { operationId: 'op-1' },- );- expect(store.replaceMessages).toHaveBeenCalled();- });-- it('should preserve structured heterogeneous agent error payloads', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(- makeEvent('error', {- body: {- agentType: 'codex',- code: 'cli_not_found',- docsUrl: 'https://github.com/openai/codex',- installCommands: ['npm install -g @openai/codex'],- message: 'Codex CLI was not found',- },- message: 'Codex CLI was not found',- type: 'AgentRuntimeError',- }),- );- await flush();-- expect(messageService.updateMessageError).toHaveBeenCalledWith(- 'msg-initial',- expect.objectContaining({- errorRef: 'H8001',- body: {- agentType: 'codex',- code: 'cli_not_found',- details: { kind: 'cli_not_found' },- docsUrl: 'https://github.com/openai/codex',- installCommands: ['npm install -g @openai/codex'],- message: 'Codex CLI was not found',- },- message: 'Codex CLI was not found',- type: 'AgentRuntimeError',- }),- expect.any(Object),- );- expect(store.internal_dispatchMessage).toHaveBeenCalledWith(- expect.objectContaining({- value: {- error: expect.objectContaining({- errorRef: 'H8001',- body: {- agentType: 'codex',- code: 'cli_not_found',- details: { kind: 'cli_not_found' },- docsUrl: 'https://github.com/openai/codex',- installCommands: ['npm install -g @openai/codex'],- message: 'Codex CLI was not found',- },- message: 'Codex CLI was not found',- type: 'AgentRuntimeError',- }),- },- }),- { operationId: 'op-1' },- );- });-- it('should prefer updateMessageError returned messages over an extra refetch', async () => {- const store = createMockStore();- const handler = createHandler(store);- const persistedMessages = [{ id: 'msg-initial', role: 'assistant' }];-- vi.mocked(messageService.updateMessageError).mockResolvedValueOnce({- messages: persistedMessages as any,- success: true,- });-- handler(makeEvent('error', { message: 'Something went wrong' }));- await flush();-- expect(store.replaceMessages).toHaveBeenCalledWith(persistedMessages, {- context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' },- });- expect(messageService.getMessages).not.toHaveBeenCalled();- });-- it('should ignore late events after an error so the inline error is not overwritten', async () => {- const store = createMockStore();- const handler = createHandler(store);- const persistedMessages = [{ id: 'msg-initial', role: 'assistant' }];-- vi.mocked(messageService.updateMessageError).mockResolvedValueOnce({- messages: persistedMessages as any,- success: true,- });-- handler(makeEvent('error', { message: 'Something went wrong' }));- handler(makeEvent('tool_end', { isSuccess: true }));- handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'late chunk' }));- await flush();-- expect(messageService.getMessages).not.toHaveBeenCalled();- expect(store.internal_dispatchMessage).not.toHaveBeenCalledWith(- expect.objectContaining({- value: { content: 'late chunk' },- }),- expect.any(Object),- );- expect(store.replaceMessages).toHaveBeenCalledTimes(1);- });- });-- describe('sequential processing', () => {- it('should dispatch stream_chunk to the new assistant id after stream_start switches it', async () => {- // Native gateway streams no longer await a DB fetch on stream_start- // — but stream_chunk must still queue behind stream_start- // so the chunk targets the NEW assistant id (from stream_start.data),- // not the previous one.- const store = createMockStore();- const callOrder: string[] = [];-- store.internal_dispatchMessage.mockImplementation(() => {- callOrder.push('dispatch');- });- store.associateMessageWithOperation.mockImplementation(() => {- callOrder.push('associate');- });-- const handler = createHandler(store);-- handler(- makeEvent('stream_start', { assistantMessage: { id: 'msg-new', role: 'assistant' } }),- );- handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'Hello' }));- await flush();-- // associate (from stream_start) precedes dispatch (from stream_chunk)- const associateIdx = callOrder.indexOf('associate');- const dispatchIdx = callOrder.indexOf('dispatch');- expect(associateIdx).toBeGreaterThan(-1);- expect(dispatchIdx).toBeGreaterThan(associateIdx);-- // Chunk targets the new id, proving the queue ordering held- expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(- expect.objectContaining({ id: 'msg-new', value: { content: 'Hello' } }),- { operationId: 'op-1' },- );- // And no DB refetch was issued for the native stream- expect(messageService.getMessages).not.toHaveBeenCalled();- });-- it('should still fetch from DB on stream_start when assistantMessage id is absent (hetero CLI)', async () => {- // Hetero CLI adapters (Claude Code / Codex) never set- // `assistantMessage.id` on stream_start, so the DB read is still- // mandatory — it pulls the executor-created placeholder into- // `dbMessagesMap` so subsequent chunks have a target.- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('stream_start', {}));- await flush();-- expect(messageService.getMessages).toHaveBeenCalled();- expect(store.replaceMessages).toHaveBeenCalled();- });- });-- describe('multi-step integration', () => {- it('should handle full LLM → tools → LLM cycle', async () => {- const store = createMockStore();- const handler = createHandler(store);-- // Step 1: LLM call- handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-1', role: 'assistant' } }));- await flush();- expect(store.associateMessageWithOperation).toHaveBeenCalledWith('msg-1', 'op-1');-- handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'Let me search.' }));- await flush();- expect(store.internal_dispatchMessage).toHaveBeenCalledWith(- expect.objectContaining({ id: 'msg-1', value: { content: 'Let me search.' } }),- { operationId: 'op-1' },- );-- const tools = [{ id: 'tc-1' }];- handler(makeEvent('stream_chunk', { chunkType: 'tools_calling', toolsCalling: tools }));- await flush();- expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith('msg-1', [true]);-- handler(makeEvent('stream_end'));- await flush();- // Loading stays active between steps — only tool streaming is cleared- expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith('msg-1', undefined);-- // Tool execution — tool_end still refreshes from DB to pick up the- // server-created tool message row.- handler(makeEvent('tool_start', { parentMessageId: 'msg-1', toolCalling: tools[0] }));- handler(makeEvent('tool_end', { isSuccess: true }));- await flush();- expect(store.replaceMessages).toHaveBeenCalled();-- // Step 2: Next LLM call with new assistant message — native stream_start- // carries the id directly, so it must NOT trigger a DB refetch- // Only the association switch happens.- vi.clearAllMocks();- handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-2', role: 'assistant' } }));- await flush();- expect(store.associateMessageWithOperation).toHaveBeenCalledWith('msg-2', 'op-1');- expect(messageService.getMessages).not.toHaveBeenCalled();- expect(store.replaceMessages).not.toHaveBeenCalled();-- handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'Here are the results.' }));- await flush();- expect(store.internal_dispatchMessage).toHaveBeenCalledWith(- expect.objectContaining({ id: 'msg-2', value: { content: 'Here are the results.' } }),- { operationId: 'op-1' },- );-- handler(makeEvent('stream_end'));- handler(makeEvent('agent_runtime_end'));- await flush();- expect(store.completeOperation).toHaveBeenCalledWith('op-1');- });- });-- // ─── 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)', () => {- // CONTRACT: the `error` event FAILS the operation- // (`failOperation`) via the shared run lifecycle — an errored run is a failed- // run, not a completed one. Like `agent_runtime_end`'s cancel/park endings it- // does NOT mark the topic unread (no unread badge for a failed generation).- it('error event FAILS the operation and does NOT call markTopicUnread', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('error', { message: 'kaboom' }));- await flush();-- // failOperation IS called on error; completeOperation is NOT.- expect(store.failOperation).toHaveBeenCalledWith('op-1', expect.anything());- expect(store.completeOperation).not.toHaveBeenCalled();- // markTopicUnread is NOT — even though operations['op-1'] has a- // context.agentId (which WOULD trigger it on a clean agent_runtime_end).- expect(store.markTopicUnread).not.toHaveBeenCalled();- });-- it.each(['no_executor', 'claim_timeout', 'not_delivered'])(- 'leaves a relay call no client took (%s) to the server: no failure, no row write',- async (reason) => {- const store = createMockStore();- const handler = createHandler(store);-- // What a replay on reconnect delivers long after the run parked.- handler(- makeEvent('error', {- error: { reason, recoverable: true },- errorType: 'ClientLlmExecutorUnavailable',- provider: 'lmstudio',- }),- );- await flush();-- expect(store.failOperation).not.toHaveBeenCalled();- expect(store.completeOperation).not.toHaveBeenCalled();- expect(messageService.updateMessageError).not.toHaveBeenCalled();- expect(store.internal_dispatchMessage).not.toHaveBeenCalledWith(- expect.objectContaining({ value: expect.objectContaining({ error: expect.anything() }) }),- expect.anything(),- );- // It shows what the server wrote instead (the waiting notice).- expect(messageService.getMessages).toHaveBeenCalled();- },- );-- it('still fails the run on a relay error no client can fix (wait_timeout)', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(- makeEvent('error', {- error: { reason: 'wait_timeout', recoverable: true },- errorType: 'ClientLlmExecutorUnavailable',- provider: 'lmstudio',- }),- );- await flush();-- expect(store.failOperation).toHaveBeenCalledWith('op-1', expect.anything());- expect(messageService.updateMessageError).toHaveBeenCalled();- });-- it('error event preserves runtime payload errorType and budget context', async () => {- const store = createMockStore();- const handler = createHandler(store);- const budget = { required: 12 };-- handler(- makeEvent('error', {- budget,- error: { message: 'Budget exceeded' },- errorType: 'FreePlanLimit',- provider: 'lobehub',- }),- );- await flush();-- expect(messageService.updateMessageError).toHaveBeenCalledWith(- 'msg-initial',- expect.objectContaining({- body: expect.objectContaining({- budget,- message: 'Budget exceeded',- provider: 'lobehub',- }),- message: 'Budget exceeded',- type: 'FreePlanLimit',- }),- expect.anything(),- );- });-- it('error event preserves _responseBody while merging payload error metadata', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(- makeEvent('error', {- _responseBody: {- error: { message: 'Payment required' },- provider: 'lobehub',- },- error: { status: 402 },- errorType: 'ProviderBizError',- }),- );- await flush();-- expect(messageService.updateMessageError).toHaveBeenCalledWith(- 'msg-initial',- expect.objectContaining({- body: expect.objectContaining({- error: { message: 'Payment required', status: 402 },- message: 'Payment required',- provider: 'lobehub',- }),- message: 'Payment required',- type: 'InsufficientQuota',- }),- expect.anything(),- );- });-- it('error event preserves normalized body fields for trace-id error UI', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(- makeEvent('error', {- body: {- message: 'Upstream failed',- traceId: 'trace-123',- },- error: 'Upstream failed',- errorType: 'ProviderBizError',- phase: 'llm_execution',- }),- );- await flush();-- expect(messageService.updateMessageError).toHaveBeenCalledWith(- 'msg-initial',- expect.objectContaining({- body: expect.objectContaining({- message: 'Upstream failed',- traceId: 'trace-123',- }),- message: 'Upstream failed',- type: 'ProviderBizError',- }),- expect.anything(),- );- });-- // 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 markTopicUnread', async () => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('agent_runtime_end'));- await flush();-- expect(store.completeOperation).toHaveBeenCalledWith('op-1');- expect(store.markTopicUnread).toHaveBeenCalledWith(- expect.objectContaining({ agentId: 'agent-1', topicId: 'topic-1' }),- );- });-- it.each(['interrupted', 'waiting_for_async_tool'])(- 'agent_runtime_end with reason "%s" completes the op but does NOT mark unread (cancel/park)',- async (reason) => {- const store = createMockStore();- const handler = createHandler(store);-- handler(makeEvent('agent_runtime_end', { reason }));- await flush();-- expect(store.completeOperation).toHaveBeenCalledWith('op-1');- expect(store.markTopicUnread).not.toHaveBeenCalled();- },- );-- // the agent_runtime_end handler completes the op once via- // the shared run lifecycle, and gateway.ts onSessionComplete no longer- // double-completes (it only completes as the terminal-missing fallback). The- // reducer is still idempotent (a stray second completeOperation on an- // already-'completed' op is a no-throw, no-flip no-op) — locked here as a- // safety net in case any path issues a redundant completion.- 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',- runLifecycle: buildRunLifecycle(get, {- context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' } as any,- parentMessageId: 'msg-initial',- parentMessageType: 'assistant',- runId: 'op-1',- runScope: 'top_level',- runtimeType: 'gateway',- }),- });-- // 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',- runLifecycle: buildRunLifecycle(get, {- context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' } as any,- parentMessageId: 'msg-initial',- parentMessageType: 'assistant',- runId: 'op-1',- runScope: 'top_level',- runtimeType: 'gateway',- }),- });-- 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 step- * boundaries arrive AFTER stream_start (correct order).- *- * Previously, the executor forwarded stream_chunk(tools_calling) sync- * while stream_start was deferred via persistQueue — handler dispatched- * tools to the OLD assistant. The fix defers all events during step- * transition through persistQueue, guaranteeing correct ordering.- */- it('should dispatch new-step tools to the NEW assistant when events arrive in correct order', async () => {- const store = createMockStore();- const handler = createHandler(store, { assistantMessageId: 'ast-old' });-- // Step 1 init- handler(makeEvent('stream_start', {}));- await flush();-- handler(makeEvent('stream_end'));- await flush();- vi.clearAllMocks();-- // ── Step boundary: executor now guarantees stream_start arrives FIRST ──- handler(makeEvent('stream_start', { assistantMessage: { id: 'ast-new' } }));- await flush();-- handler(- makeEvent('stream_chunk', {- chunkType: 'tools_calling',- toolsCalling: [{ id: 'toolu_new' }],- }),- );- await flush();-- // ── Assert: tools dispatched to the NEW assistant ──- const toolsDispatch = store.internal_dispatchMessage.mock.calls.find(- ([action]: any) => action.value?.tools,- );- expect(toolsDispatch).toBeDefined();- 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. A `waiting_for_async_tool`- // park still completes the operation and tears down tool-calling streaming,- // but it must NOT mark the topic unread — a park is not a finished- // generation, and persisting it as `unread` would leave a stale badge on a- // run that's only paused waiting for an async tool. (See `isCompletedRuntimeEnd`.)- it('completes the operation but does NOT mark unread on a waiting_for_async_tool park', 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 still completes the op + tears down tool streaming,- expect(store.completeOperation).toHaveBeenCalledWith('op-1');- expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith(- 'msg-server',- undefined,- );- // …but does NOT surface an unread badge for the pause.- expect(store.markTopicUnread).not.toHaveBeenCalled();- });-- // (5) Contrast probe: the no-mark behavior is driven by the park `reason`,- // not by whether content streamed — a parked terminal with NO streamed- // content also skips the unread mark.- it('does NOT mark unread 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.markTopicUnread).not.toHaveBeenCalled();- });- });-});diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.tsindex 12b92747a9a..481ec70dcaa 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -102,10 +102,6 @@ vi.mock('@/services/agentQuota', () => ({// Gateway event handler — we spy on it but let it run (it calls getMessages)vi.mock('../transports/gateway/gatewayEventHandler', () => ({createGatewayEventHandler: vi.fn(() => vi.fn()),- // Faithful re-impl (the real one is unmocked to keep the import cycle out of- // this test): only 'interrupted' / 'waiting_for_async_tool' are non-clean.- isCompletedRuntimeEnd: (reason?: string | null) =>- reason !== 'interrupted' && reason !== 'waiting_for_async_tool',}));// isDesktop — defaults to `false` (matching the real test env / __ELECTRON__@@ -6003,18 +5999,20 @@ describe('heterogeneousAgentExecutor DB persistence', () => {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+ // ── 4. error terminal → failure notification, no drain (the onError branch) ──+ it('an error terminal fires a FAILURE notification and NO queue drain', async () => {+ desktopFlag.value = true;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();+ // One failure banner, never the "finished" one (no completion badge).+ expect(mockShowNotification).toHaveBeenCalledTimes(1);+ expect(mockShowNotification).toHaveBeenCalledWith(+ expect.objectContaining({ body: expect.stringContaining('the run failed') }),+ );expect(mockSetBadgeCount).not.toHaveBeenCalled();// No queue drain on the error path (gated by terminalEvent?.type !== 'error').expect(store.drainQueuedMessages).not.toHaveBeenCalled();diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.tsindex be61a5575f2..97a0ae186e6 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts@@ -19,10 +19,12 @@ vi.mock('@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge', () =const desktopNotificationMock = vi.hoisted(() => ({notifyDesktopAgentCompleted: vi.fn().mockResolvedValue(undefined),+ notifyDesktopAgentFailed: vi.fn().mockResolvedValue(undefined),}));vi.mock('@/store/chat/utils/desktopNotification', () => ({notifyDesktopAgentCompleted: desktopNotificationMock.notifyDesktopAgentCompleted,+ notifyDesktopAgentFailed: desktopNotificationMock.notifyDesktopAgentFailed,}));// Force the desktop branch of afterRunComplete on (isDesktop is false in the@@ -379,6 +381,35 @@ describe('buildRunLifecycle — sub-agent runs skip top-level effects', () => {});});+describe('buildRunLifecycle.afterRunComplete — failed run notification', () => {+ beforeEach(() => vi.clearAllMocks());++ const error = { message: 'boom', type: 'AgentRuntimeError' };++ it('announces a failed run with its error instead of a completion', async () => {+ const { get } = makeStore();+ await lifecycle('gateway', get).afterRunComplete(+ completeEvent('gateway', { notification: { error }, status: 'failed' }),+ );++ expect(desktopNotificationMock.notifyDesktopAgentFailed).toHaveBeenCalledWith(get, {+ context: { agentId: 'a1', groupId: undefined, topicId: 't1', workspaceSlug: 'team' },+ error,+ });+ expect(desktopNotificationMock.notifyDesktopAgentCompleted).not.toHaveBeenCalled();+ });++ it('stays silent for a failed run the transport did not ask to announce', async () => {+ const { get } = makeStore();+ await lifecycle('client', get).afterRunComplete(+ completeEvent('client', { runtimeStatus: 'error' }),+ );++ expect(desktopNotificationMock.notifyDesktopAgentFailed).not.toHaveBeenCalled();+ expect(desktopNotificationMock.notifyDesktopAgentCompleted).not.toHaveBeenCalled();+ });+});+describe('buildRunLifecycle.afterRunComplete — client desktop notification body', () => {const KEY = messageMapKey(CONTEXT);// parentMessageId for the run under test is 'u1' (see `lifecycle` helper), sodiff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.tsindex af0ef1c5bf8..1d847953856 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts@@ -9,7 +9,10 @@ import type { AgentRuntimeType } from '@/store/chat/slices/agentRun/actions/dispimport { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge';import { snapshotTopicWorkingDirGit } from '@/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit';import type { ChatStore } from '@/store/chat/store';-import { notifyDesktopAgentCompleted } from '@/store/chat/utils/desktopNotification';+import {+ notifyDesktopAgentCompleted,+ notifyDesktopAgentFailed,+} from '@/store/chat/utils/desktopNotification';import {hasCompletedAssistantText,isAudioOnlyFirstUserMessage,@@ -281,8 +284,17 @@ export const buildRunLifecycle = (},afterRunComplete: async (event: RunCompleteEvent) => {if (get().operations[event.operationId]?.metadata.terminalReconciled) return;- if (adapter.runScope === 'sub_agent' || resolveTerminalDisposition(event) !== 'success')+ if (adapter.runScope === 'sub_agent') return;++ const disposition = resolveTerminalDisposition(event);+ if (disposition === 'failed' && event.notification) {+ await notifyDesktopAgentFailed(get, {+ context: { agentId, groupId, topicId, workspaceSlug },+ error: event.notification.error,+ });return;+ }+ if (disposition !== 'success') return;// A voice-only first message cannot be summarized at the post-persist seam:// its content is empty and the assistant row is still a loading placeholder.diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/types.ts b/src/store/chat/slices/agentRun/actions/lifecycle/types.tsindex 2d2927eeb7a..812920f3199 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/types.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/types.ts@@ -1,5 +1,5 @@import type { AgentState } from '@lobechat/agent-runtime';-import type { ConversationContext, UIChatMessage } from '@lobechat/types';+import type { ChatMessageError, ConversationContext, UIChatMessage } from '@lobechat/types';import type { AgentRuntimeType } from '@/store/chat/slices/agentRun/actions/dispatch/agentDispatcher';import type { OperationStatus } from '@/store/chat/slices/operation/types';@@ -71,9 +71,10 @@ export interface RunCompleteEvent extends RunLifecycleEventBase {* executor memory rather than the store (hetero's `accContent`). When present,* {@link AgentRunLifecycle.afterRunComplete} feeds it to the notification body* instead of deriving from `messagesMap`. The client adapter omits it (it reads- * the store); hetero supplies it.+ * the store); hetero supplies it. A `failed` run announces its failure only+ * when the transport supplies this, with `error` (when known) as the reason.*/- notification?: { content?: string };+ notification?: { content?: string; error?: ChatMessageError };operationStatus?: OperationStatus;/*** Raw runtime terminal/parked status (client `AgentState['status']`), used todiff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex c698dec7924..08d2c3c3708 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -85,7 +85,7 @@ import { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';import { scheduleQueuedFollowUp } from '../../lifecycle/queuedFollowUp';import type { RunScope } from '../../lifecycle/types';import { createGatewayEventBuffer } from './gatewayEventBuffer';-import { createGatewayEventHandler, isCompletedRuntimeEnd } from './gatewayEventHandler';+import { createGatewayEventHandler } from './gatewayEventHandler';import { createGatewayEventRouter } from './gatewayEventRouter';import { createGatewayMemberStreamHandler, mergeGroupSnapshot } from './gatewayMemberStreamHandler';import {@@ -95,6 +95,7 @@ import {markGatewayMuxUnavailable,} from './muxRegistry';import { flagQueuedMessagesOnRunStart, syncQueuedMessagesFlag } from './queuedMessagesFlag';+import { isCompletedRuntimeEnd } from './runtimeEndReason';const getGatewayServerConfig = () =>(typeof window !== 'undefined'@@ -741,10 +742,9 @@ export class GatewayActionImpl {if (isOwnOp && isSessionTerminalEvent(event)) {receivedTerminalEvent = true;}- // Only a clean completion counts as success — a cancel ('interrupted') or- // deferred-tool park ('waiting_for_async_tool') must take the non-success- // branch so onSessionComplete clears the run back to 'active' instead of- // leaving the topic persisted as an unread completion.+ // Only a clean completion counts as success — a cancel, park or failure+ // (see `isCompletedRuntimeEnd`) takes the non-success branch so the topic+ // settles back to 'active' instead of persisting as an unread completion.if (isOwnOp &&event.type === 'agent_runtime_end' &&diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.failedRun.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.failedRun.test.tsnew file mode 100644index 00000000000..5d61d2d7e07--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.failedRun.test.ts@@ -0,0 +1,169 @@+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';+import type { ConversationContext, UIChatMessage } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { messageService } from '@/services/message';+import * as agentSignalBridge from '@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge';+import type { ChatStore } from '@/store/chat/store';++import { createGatewayEventHandler } from './gatewayEventHandler';++vi.mock('@/store/tool/slices/builtin/executors', () => ({+ getExecutor: vi.fn(() => ({})),+ registerBuiltinToolExecutors: vi.fn(),+}));++const context = { agentId: 'agent-1', topicId: 'topic-1' } as ConversationContext;++const makeEvent = (type: AgentStreamEvent['type'], data?: AgentStreamEvent['data']) =>+ ({ data, id: 'e', operationId: 'op-1', stepIndex: 1, timestamp: 0, type }) as AgentStreamEvent;++const createStore = () =>+ ({+ associateMessageWithOperation: vi.fn(),+ completeOperation: vi.fn(),+ dbMessagesMap: {},+ internal_dispatchMessage: vi.fn(),+ internal_toggleToolCallingStreaming: vi.fn(),+ operations: {},+ operationsByContext: {},+ replaceMessages: vi.fn(),+ updateOperationMetadata: vi.fn(),+ }) as unknown as ChatStore;++const createLifecycle = () => ({+ afterRunComplete: vi.fn().mockResolvedValue(undefined),+ completeRun: vi.fn().mockResolvedValue({ requeued: false }),+});++const flush = async () => {+ for (let i = 0; i < 50; i += 1) await Promise.resolve();+};++const workingDirectoryError = {+ body: {+ agentType: 'claude-code',+ code: 'working_directory_not_found',+ message: 'Working directory does not exist: /gone',+ },+ message: 'Working directory does not exist: /gone',+ type: 'AgentRuntimeError',+};++describe('createGatewayEventHandler — failed run terminal', () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ vi.spyOn(agentSignalBridge, 'emitClientAgentSignalSourceEvent').mockResolvedValue(undefined);+ vi.spyOn(messageService, 'getMessages').mockResolvedValue([] as unknown as UIChatMessage[]);+ });++ it('settles a `reason: error` end as failed and notifies with the persisted error', async () => {+ const lifecycle = createLifecycle();+ const handler = createGatewayEventHandler(createStore, {+ assistantMessageId: 'answer-msg',+ context,+ operationId: 'op-1',+ runLifecycle: lifecycle as any,+ runtimeType: 'gateway',+ });++ handler(+ makeEvent('agent_runtime_end', {+ reason: 'error',+ uiMessages: [+ {+ children: [{ content: '...', error: workingDirectoryError, id: 'answer-msg' }],+ content: '...',+ id: 'answer-msg',+ role: 'assistantGroup',+ },+ ] as unknown as UIChatMessage[],+ }),+ );+ await flush();++ expect(lifecycle.completeRun).toHaveBeenCalledWith(+ expect.objectContaining({ status: 'failed' }),+ );+ expect(lifecycle.afterRunComplete).toHaveBeenCalledTimes(1);+ expect(lifecycle.afterRunComplete).toHaveBeenCalledWith(+ expect.objectContaining({+ notification: { error: workingDirectoryError },+ status: 'failed',+ }),+ );+ });++ it('announces a run that fails with an `error` event, once, before the dropped end event', async () => {+ const updateMessageError = vi+ .spyOn(messageService, 'updateMessageError')+ .mockResolvedValue({ success: true } as any);+ const lifecycle = createLifecycle();+ const store = createStore();+ const handler = createGatewayEventHandler(() => store, {+ assistantMessageId: 'answer-msg',+ context,+ operationId: 'op-1',+ runLifecycle: lifecycle as any,+ runtimeType: 'gateway',+ });++ handler(makeEvent('error', { message: 'Provider quota exceeded', type: 'ProviderBizError' }));+ handler(makeEvent('agent_runtime_end', { reason: 'error' }));+ await flush();++ expect(lifecycle.completeRun).toHaveBeenCalledWith(+ expect.objectContaining({ status: 'failed' }),+ );+ expect(lifecycle.afterRunComplete).toHaveBeenCalledTimes(1);+ expect(lifecycle.afterRunComplete).toHaveBeenCalledWith(+ expect.objectContaining({+ notification: {+ error: expect.objectContaining({ message: 'Provider quota exceeded' }),+ },+ status: 'failed',+ }),+ );+ // The error the banner points to is persisted and shown before it fires.+ const notifiedAt = lifecycle.afterRunComplete.mock.invocationCallOrder[0];+ expect(updateMessageError.mock.invocationCallOrder[0]).toBeLessThan(notifiedAt);+ const overlayAt = vi.mocked(store.internal_dispatchMessage).mock.invocationCallOrder.at(-1)!;+ expect(overlayAt).toBeLessThan(notifiedAt);+ });++ it('still announces a failed run whose snapshot carries no error', async () => {+ const lifecycle = createLifecycle();+ const handler = createGatewayEventHandler(createStore, {+ assistantMessageId: 'answer-msg',+ context,+ operationId: 'op-1',+ runLifecycle: lifecycle as any,+ runtimeType: 'gateway',+ });++ handler(makeEvent('agent_runtime_end', { reason: 'error' }));+ await flush();++ expect(lifecycle.afterRunComplete).toHaveBeenCalledWith(+ expect.objectContaining({ notification: { error: undefined }, status: 'failed' }),+ );+ });++ it('does not mark a failed hetero-reconciled run unread', async () => {+ const store = createStore();+ (store as any).operations = { 'op-1': { context } };+ (store as any).markTopicUnread = vi.fn();+ const handler = createGatewayEventHandler(() => store, {+ assistantMessageId: 'answer-msg',+ context,+ operationId: 'op-1',+ runtimeType: 'hetero',+ });++ handler(makeEvent('agent_runtime_end', { reason: 'error' }));+ await flush();++ expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ expect((store as any).markTopicUnread).not.toHaveBeenCalled();+ });+});diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.lifecycle.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.lifecycle.test.tsnew file mode 100644index 00000000000..833fc4736f6--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.lifecycle.test.ts@@ -0,0 +1,463 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { messageService } from '@/services/message';+import type * as WorkServiceModule from '@/services/work';++import { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';+import { createGatewayEventHandler } from './gatewayEventHandler';+import { createHandler, createMockStore, flush, makeEvent } from './testUtils';++vi.mock('@/services/message', () => ({+ messageService: {+ getMessages: vi.fn().mockResolvedValue([]),+ updateMessageError: vi.fn().mockResolvedValue({ success: true }),+ },+}));+vi.mock('@/services/work', async (importOriginal) => {+ const actual = await importOriginal<typeof WorkServiceModule>();+ return {+ ...actual,+ workService: {+ refreshConversationViews: vi.fn().mockResolvedValue(undefined),+ },+ };+});+vi.mock('@/store/chat/utils/desktopNotification', () => ({+ notifyDesktopAgentFailed: vi.fn().mockResolvedValue(undefined),+ notifyDesktopHumanApprovalRequired: vi.fn().mockResolvedValue(undefined),+}));+vi.mock('@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge', () => ({+ emitClientAgentSignalSourceEvent: vi.fn().mockResolvedValue(undefined),+}));+const getExecutorMock = vi.fn();+vi.mock('@/store/tool/slices/builtin/executors', () => ({+ getExecutor: (...args: unknown[]) => getExecutorMock(...args),+ registerBuiltinToolExecutors: vi.fn().mockResolvedValue(undefined),+}));++describe('createGatewayEventHandler — run lifecycle characterization', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ // ─── 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)', () => {+ // CONTRACT: the `error` event FAILS the operation+ // (`failOperation`) via the shared run lifecycle — an errored run is a failed+ // run, not a completed one. Like `agent_runtime_end`'s cancel/park endings it+ // does NOT mark the topic unread (no unread badge for a failed generation).+ it('error event FAILS the operation and does NOT call markTopicUnread', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('error', { message: 'kaboom' }));+ await flush();++ // failOperation IS called on error; completeOperation is NOT.+ expect(store.failOperation).toHaveBeenCalledWith('op-1', expect.anything());+ expect(store.completeOperation).not.toHaveBeenCalled();+ // markTopicUnread is NOT — even though operations['op-1'] has a+ // context.agentId (which WOULD trigger it on a clean agent_runtime_end).+ expect(store.markTopicUnread).not.toHaveBeenCalled();+ });++ it.each(['no_executor', 'claim_timeout', 'not_delivered'])(+ 'leaves a relay call no client took (%s) to the server: no failure, no row write',+ async (reason) => {+ const store = createMockStore();+ const handler = createHandler(store);++ // What a replay on reconnect delivers long after the run parked.+ handler(+ makeEvent('error', {+ error: { reason, recoverable: true },+ errorType: 'ClientLlmExecutorUnavailable',+ provider: 'lmstudio',+ }),+ );+ await flush();++ expect(store.failOperation).not.toHaveBeenCalled();+ expect(store.completeOperation).not.toHaveBeenCalled();+ expect(messageService.updateMessageError).not.toHaveBeenCalled();+ expect(store.internal_dispatchMessage).not.toHaveBeenCalledWith(+ expect.objectContaining({ value: expect.objectContaining({ error: expect.anything() }) }),+ expect.anything(),+ );+ // It shows what the server wrote instead (the waiting notice).+ expect(messageService.getMessages).toHaveBeenCalled();+ },+ );++ it('still fails the run on a relay error no client can fix (wait_timeout)', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(+ makeEvent('error', {+ error: { reason: 'wait_timeout', recoverable: true },+ errorType: 'ClientLlmExecutorUnavailable',+ provider: 'lmstudio',+ }),+ );+ await flush();++ expect(store.failOperation).toHaveBeenCalledWith('op-1', expect.anything());+ expect(messageService.updateMessageError).toHaveBeenCalled();+ });++ it('error event preserves runtime payload errorType and budget context', async () => {+ const store = createMockStore();+ const handler = createHandler(store);+ const budget = { required: 12 };++ handler(+ makeEvent('error', {+ budget,+ error: { message: 'Budget exceeded' },+ errorType: 'FreePlanLimit',+ provider: 'lobehub',+ }),+ );+ await flush();++ expect(messageService.updateMessageError).toHaveBeenCalledWith(+ 'msg-initial',+ expect.objectContaining({+ body: expect.objectContaining({+ budget,+ message: 'Budget exceeded',+ provider: 'lobehub',+ }),+ message: 'Budget exceeded',+ type: 'FreePlanLimit',+ }),+ expect.anything(),+ );+ });++ it('error event preserves _responseBody while merging payload error metadata', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(+ makeEvent('error', {+ _responseBody: {+ error: { message: 'Payment required' },+ provider: 'lobehub',+ },+ error: { status: 402 },+ errorType: 'ProviderBizError',+ }),+ );+ await flush();++ expect(messageService.updateMessageError).toHaveBeenCalledWith(+ 'msg-initial',+ expect.objectContaining({+ body: expect.objectContaining({+ error: { message: 'Payment required', status: 402 },+ message: 'Payment required',+ provider: 'lobehub',+ }),+ message: 'Payment required',+ type: 'InsufficientQuota',+ }),+ expect.anything(),+ );+ });++ it('error event preserves normalized body fields for trace-id error UI', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(+ makeEvent('error', {+ body: {+ message: 'Upstream failed',+ traceId: 'trace-123',+ },+ error: 'Upstream failed',+ errorType: 'ProviderBizError',+ phase: 'llm_execution',+ }),+ );+ await flush();++ expect(messageService.updateMessageError).toHaveBeenCalledWith(+ 'msg-initial',+ expect.objectContaining({+ body: expect.objectContaining({+ message: 'Upstream failed',+ traceId: 'trace-123',+ }),+ message: 'Upstream failed',+ type: 'ProviderBizError',+ }),+ expect.anything(),+ );+ });++ // 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 markTopicUnread', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('agent_runtime_end'));+ await flush();++ expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ expect(store.markTopicUnread).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'agent-1', topicId: 'topic-1' }),+ );+ });++ it.each(['interrupted', 'waiting_for_async_tool'])(+ 'agent_runtime_end with reason "%s" completes the op but does NOT mark unread (cancel/park)',+ async (reason) => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('agent_runtime_end', { reason }));+ await flush();++ expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ expect(store.markTopicUnread).not.toHaveBeenCalled();+ },+ );++ // the agent_runtime_end handler completes the op once via+ // the shared run lifecycle, and gateway.ts onSessionComplete no longer+ // double-completes (it only completes as the terminal-missing fallback). The+ // reducer is still idempotent (a stray second completeOperation on an+ // already-'completed' op is a no-throw, no-flip no-op) — locked here as a+ // safety net in case any path issues a redundant completion.+ 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',+ runLifecycle: buildRunLifecycle(get, {+ context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' } as any,+ parentMessageId: 'msg-initial',+ parentMessageType: 'assistant',+ runId: 'op-1',+ runScope: 'top_level',+ runtimeType: 'gateway',+ }),+ });++ // 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',+ runLifecycle: buildRunLifecycle(get, {+ context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' } as any,+ parentMessageId: 'msg-initial',+ parentMessageType: 'assistant',+ runId: 'op-1',+ runScope: 'top_level',+ runtimeType: 'gateway',+ }),+ });++ handler(makeEvent('agent_runtime_end', { reason: 'interrupted' }));+ await flush();++ expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ expect(operations['op-1'].status).toBe('cancelled');+ });+ });++ 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. A `waiting_for_async_tool`+ // park still completes the operation and tears down tool-calling streaming,+ // but it must NOT mark the topic unread — a park is not a finished+ // generation, and persisting it as `unread` would leave a stale badge on a+ // run that's only paused waiting for an async tool. (See `isCompletedRuntimeEnd`.)+ it('completes the operation but does NOT mark unread on a waiting_for_async_tool park', 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 still completes the op + tears down tool streaming,+ expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith(+ 'msg-server',+ undefined,+ );+ // …but does NOT surface an unread badge for the pause.+ expect(store.markTopicUnread).not.toHaveBeenCalled();+ });++ // (5) Contrast probe: the no-mark behavior is driven by the park `reason`,+ // not by whether content streamed — a parked terminal with NO streamed+ // content also skips the unread mark.+ it('does NOT mark unread 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.markTopicUnread).not.toHaveBeenCalled();+ });+ });+});diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.streaming.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.streaming.test.tsnew file mode 100644index 00000000000..491c5bb6801--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.streaming.test.ts@@ -0,0 +1,592 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { messageService } from '@/services/message';+import type * as WorkServiceModule from '@/services/work';+import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge';++import { createHandler, createMockStore, flush, makeEvent } from './testUtils';++vi.mock('@/services/message', () => ({+ messageService: {+ getMessages: vi.fn().mockResolvedValue([]),+ updateMessageError: vi.fn().mockResolvedValue({ success: true }),+ },+}));+vi.mock('@/services/work', async (importOriginal) => {+ const actual = await importOriginal<typeof WorkServiceModule>();+ return {+ ...actual,+ workService: {+ refreshConversationViews: vi.fn().mockResolvedValue(undefined),+ },+ };+});+vi.mock('@/store/chat/utils/desktopNotification', () => ({+ notifyDesktopAgentFailed: vi.fn().mockResolvedValue(undefined),+ notifyDesktopHumanApprovalRequired: vi.fn().mockResolvedValue(undefined),+}));+vi.mock('@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge', () => ({+ emitClientAgentSignalSourceEvent: vi.fn().mockResolvedValue(undefined),+}));+const getExecutorMock = vi.fn();+vi.mock('@/store/tool/slices/builtin/executors', () => ({+ getExecutor: (...args: unknown[]) => getExecutorMock(...args),+ registerBuiltinToolExecutors: vi.fn().mockResolvedValue(undefined),+}));++describe('createGatewayEventHandler — stream lifecycle events', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });+ describe('stream_start', () => {+ it('should associate new message with operation and skip the DB refetch', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(+ makeEvent('stream_start', {+ assistantMessage: { id: 'msg-step2', role: 'assistant' },+ }),+ );+ await flush();++ expect(store.associateMessageWithOperation).toHaveBeenCalledWith('msg-step2', 'op-1');+ // Native gateway ships the assistant seed on stream_start, so the client+ // inserts the message shell locally (createMessage) and must NOT trigger a+ // DB refetch — the refetch is what clobbered the streamed assistantGroup+ // with a stale placeholder.+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'msg-step2', type: 'createMessage' }),+ { operationId: 'op-1' },+ );+ expect(messageService.getMessages).not.toHaveBeenCalled();+ expect(store.replaceMessages).not.toHaveBeenCalled();+ expect(emitClientAgentSignalSourceEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({+ anchorMessageId: 'msg-step2',+ assistantMessageId: 'msg-step2',+ operationId: 'op-1',+ stepIndex: 0,+ }),+ sourceType: 'client.gateway.stream_start',+ }),+ );+ });++ it('should keep current ID if event data has no assistantMessage', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('stream_start', {}));+ await flush();++ // No new message to associate, but fetch still happens+ expect(store.associateMessageWithOperation).not.toHaveBeenCalled();+ expect(store.replaceMessages).toHaveBeenCalled();+ });++ it('should resolve the new assistant from DB on hetero newStep when the event has no assistantMessage id', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ vi.mocked(messageService.getMessages).mockResolvedValueOnce([+ { id: 'msg-initial', role: 'assistant' } as any,+ { id: 'tool-1', role: 'tool' } as any,+ { id: 'msg-step2', role: 'assistant' } as any,+ ]);++ handler(makeEvent('stream_start', { newStep: true }));+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'world' }));+ await flush();++ expect(store.associateMessageWithOperation).toHaveBeenCalledWith('msg-step2', 'op-1');+ expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(+ expect.objectContaining({+ id: 'msg-step2',+ value: { content: 'world' },+ }),+ { operationId: 'op-1' },+ );+ });++ it('should reset accumulators on each stream_start', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ // Accumulate some content+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'hello' }));+ await flush();+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ expect.objectContaining({ value: { content: 'hello' } }),+ { operationId: 'op-1' },+ );++ // New stream_start resets+ handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-step2' } }));+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'world' }));+ await flush();++ // Content should be 'world', not 'helloworld'+ expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(+ expect.objectContaining({+ id: 'msg-step2',+ value: { content: 'world' },+ }),+ { operationId: 'op-1' },+ );+ });+ });++ describe('stream_chunk', () => {+ it('should accumulate text content and pass operationId context', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'Hello' }));+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: ' world' }));+ await flush();++ expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(+ {+ id: 'msg-initial',+ type: 'updateMessage',+ value: { content: 'Hello world' },+ },+ { operationId: 'op-1' },+ );+ });++ it('applies replace snapshots and drops redelivered snapshot seqs', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ // `lh hetero exec` sends full-text snapshots: each carries the WHOLE+ // message so far and must replace, not append.+ handler(+ makeEvent('stream_chunk', {+ chunkType: 'text',+ content: 'Hello',+ snapshotMode: 'replace',+ snapshotSeq: 1,+ }),+ );+ handler(+ makeEvent('stream_chunk', {+ chunkType: 'text',+ content: 'Hello world',+ snapshotMode: 'replace',+ snapshotSeq: 2,+ }),+ );+ // Redelivery of seq 2 (server-side batch retry) — must be dropped, not+ // appended: appending would render "Hello worldHello world".+ handler(+ makeEvent('stream_chunk', {+ chunkType: 'text',+ content: 'Hello world',+ snapshotMode: 'replace',+ snapshotSeq: 2,+ }),+ );+ await flush();++ expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(+ {+ id: 'msg-initial',+ type: 'updateMessage',+ value: { content: 'Hello world' },+ },+ { operationId: 'op-1' },+ );+ const textDispatches = store.internal_dispatchMessage.mock.calls.filter(+ ([action]: any[]) => action.type === 'updateMessage' && 'content' in action.value,+ );+ expect(textDispatches).toHaveLength(2); // the redelivered snapshot dispatched nothing+ });++ it('applies reasoning replace snapshots and drops redelivered seqs', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(+ makeEvent('stream_chunk', {+ chunkType: 'reasoning',+ reasoning: 'thinking',+ snapshotMode: 'replace',+ snapshotSeq: 1,+ }),+ );+ handler(+ makeEvent('stream_chunk', {+ chunkType: 'reasoning',+ reasoning: 'thinking done',+ snapshotMode: 'replace',+ snapshotSeq: 2,+ }),+ );+ // Redelivered seq 2 — appending it would render "thinking donethinking done".+ handler(+ makeEvent('stream_chunk', {+ chunkType: 'reasoning',+ reasoning: 'thinking done',+ snapshotMode: 'replace',+ snapshotSeq: 2,+ }),+ );+ await flush();++ const reasoningDispatches = store.internal_dispatchMessage.mock.calls.filter(+ ([action]: any[]) => action.type === 'updateMessage' && 'reasoning' in action.value,+ );+ expect(reasoningDispatches).toHaveLength(2); // duplicate dropped+ expect(reasoningDispatches.at(-1)?.[0].value).toEqual({+ reasoning: { content: 'thinking done' },+ });+ });++ it('a snapshot replaces text accumulated from plain deltas', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'Hel' }));+ handler(+ makeEvent('stream_chunk', {+ chunkType: 'text',+ content: 'Hello world',+ snapshotMode: 'replace',+ snapshotSeq: 1,+ }),+ );+ await flush();++ // Replace, not append — appending would render "HelHello world".+ expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(+ {+ id: 'msg-initial',+ type: 'updateMessage',+ value: { content: 'Hello world' },+ },+ { operationId: 'op-1' },+ );+ });++ it('should accumulate reasoning content', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'Think' }));+ handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'ing...' }));+ await flush();++ expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(+ {+ id: 'msg-initial',+ type: 'updateMessage',+ value: { reasoning: { content: 'Thinking...' } },+ },+ { operationId: 'op-1' },+ );+ });++ it('should dispatch tools and toggle tool calling streaming', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ const toolsCalling = [{ id: 'tc-1' }, { id: 'tc-2' }];+ handler(makeEvent('stream_chunk', { chunkType: 'tools_calling', toolsCalling }));+ await flush();++ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ {+ id: 'msg-initial',+ type: 'updateMessage',+ value: { tools: toolsCalling },+ },+ { operationId: 'op-1' },+ );++ expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith('msg-initial', [+ true,+ true,+ ]);+ });++ it('should ignore chunk with no data', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('stream_chunk', undefined));+ await flush();++ expect(store.internal_dispatchMessage).not.toHaveBeenCalled();+ });++ it('should DROP subagent-tagged tool chunks so they do not leak into the main bubble', async () => {+ // Regression: on a live gateway / remote-CC stream, a subagent (Agent/Task)+ // inner tool chunk is tagged with `data.subagent`. It belongs to an+ // isolation Thread, not the main assistant. If dispatched here it appends+ // to the MAIN assistant's tools[] until the terminal DB refetch corrects it+ // ("流式时漏出来、结束后正常"). It must be dropped before any dispatch.+ const store = createMockStore();+ const handler = createHandler(store);++ handler(+ makeEvent('stream_chunk', {+ chunkType: 'tools_calling',+ subagent: { parentToolCallId: 'toolu_agent', subagentMessageId: 'sub-1' },+ toolsCalling: [{ id: 'inner-1' }],+ }),+ );+ await flush();++ // Not dispatched onto the main assistant, and no tool-calling spinner.+ expect(store.internal_dispatchMessage).not.toHaveBeenCalled();+ expect(store.internal_toggleToolCallingStreaming).not.toHaveBeenCalled();+ });++ it('should still dispatch a NON-subagent tool chunk (drop is scoped to subagent)', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(+ makeEvent('stream_chunk', { chunkType: 'tools_calling', toolsCalling: [{ id: 'm-1' }] }),+ );+ await flush();++ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ { id: 'msg-initial', type: 'updateMessage', value: { tools: [{ id: 'm-1' }] } },+ { operationId: 'op-1' },+ );+ });+ });++ describe('reasoning operation lifecycle', () => {+ it('starts a reasoning op on the first reasoning chunk and associates it with the current assistant', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'pondering' }));+ handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: '...' }));+ await flush();++ // Only one startOperation call — second chunk reuses the existing op+ expect(store.startOperation).toHaveBeenCalledTimes(1);+ expect(store.startOperation).toHaveBeenCalledWith({+ context: expect.objectContaining({+ agentId: 'agent-1',+ messageId: 'msg-initial',+ topicId: 'topic-1',+ }),+ parentOperationId: 'op-1',+ type: 'reasoning',+ });+ expect(store.associateMessageWithOperation).toHaveBeenCalledWith(+ 'msg-initial',+ 'op-reasoning-1',+ );+ // The reasoning op is NOT completed while only reasoning chunks have arrived+ expect(store.completeOperation).not.toHaveBeenCalled();+ });++ it('completes the reasoning op when text starts streaming', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'thinking' }));+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'answer' }));+ await flush();++ expect(store.completeOperation).toHaveBeenCalledWith('op-reasoning-1');+ });++ it('completes the reasoning op when tools_calling starts', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'thinking' }));+ handler(+ makeEvent('stream_chunk', {+ chunkType: 'tools_calling',+ toolsCalling: [{ id: 'tc-1' }],+ }),+ );+ await flush();++ expect(store.completeOperation).toHaveBeenCalledWith('op-reasoning-1');+ });++ it('starts a new reasoning op when reasoning resumes after text in the same stream', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'first pass' }));+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'partial' }));+ handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'second pass' }));+ await flush();++ expect(store.startOperation).toHaveBeenCalledTimes(2);+ expect(store.completeOperation).toHaveBeenCalledWith('op-reasoning-1');+ expect(store.completeOperation).not.toHaveBeenCalledWith('op-reasoning-2');+ });++ it('completes any open reasoning op on stream_end', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'thinking' }));+ handler(makeEvent('stream_end'));+ await flush();++ expect(store.completeOperation).toHaveBeenCalledWith('op-reasoning-1');+ });++ it('completes any open reasoning op on stream_start (carry-over between steps)', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'thinking' }));+ handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-step2' } }));+ await flush();++ expect(store.completeOperation).toHaveBeenCalledWith('op-reasoning-1');+ });++ it('completes any open reasoning op on agent_runtime_end', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'thinking' }));+ handler(makeEvent('agent_runtime_end'));+ await flush();++ expect(store.completeOperation).toHaveBeenCalledWith('op-reasoning-1');+ });++ it('completes any open reasoning op on error', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'thinking' }));+ handler(makeEvent('error', { message: 'boom' }));+ await flush();++ expect(store.completeOperation).toHaveBeenCalledWith('op-reasoning-1');+ });++ it('does not start a reasoning op for text-only streams', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'hello' }));+ handler(makeEvent('stream_end'));+ await flush();++ expect(store.startOperation).not.toHaveBeenCalled();+ });+ });++ describe('stream_end', () => {+ it('keeps visible loading for a plain no-tool stream boundary', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'hello back' }));+ handler(makeEvent('stream_end'));+ await flush();++ expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith(+ 'msg-initial',+ undefined,+ );+ expect(store.updateOperationMetadata).not.toHaveBeenCalledWith('op-1', {+ visibleLoadingDone: true,+ });+ expect(store.completeOperation).not.toHaveBeenCalledWith('op-1');+ });++ it('keeps visible loading after stream_end when tool calls need another step', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(+ makeEvent('stream_chunk', {+ chunkType: 'tools_calling',+ toolsCalling: [{ id: 'tc-1' }],+ }),+ );+ handler(makeEvent('stream_end'));+ await flush();++ expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith(+ 'msg-initial',+ undefined,+ );+ expect(store.updateOperationMetadata).not.toHaveBeenCalledWith('op-1', {+ visibleLoadingDone: true,+ });+ expect(store.completeOperation).not.toHaveBeenCalledWith('op-1');+ });++ it('applies finalContent before ending a reasoning-only stream', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'thinking text' }));+ handler(makeEvent('stream_end', { finalContent: 'final answer' }));+ await flush();++ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ {+ id: 'msg-initial',+ type: 'updateMessage',+ value: { content: 'final answer' },+ },+ { operationId: 'op-1' },+ );+ expect(store.completeOperation).toHaveBeenCalledWith('op-reasoning-1');+ expect(store.updateOperationMetadata).not.toHaveBeenCalledWith('op-1', {+ visibleLoadingDone: true,+ });+ });++ it('should clear tool streaming', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('stream_end'));+ await flush();++ expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith(+ 'msg-initial',+ undefined,+ );+ });+ });++ describe('visible_output_end', () => {+ it('marks visible loading done without completing the operation or clearing topic loading', async () => {+ const store = createMockStore();+ // The streamed content has landed in the store — the visible_output_end+ // guard only clears loading once the assistant row is present+ // with its content, so seed it here to represent that state.+ store.dbMessagesMap['main_agent-1_topic-1'] = [+ { content: 'hello back', id: 'msg-initial', role: 'assistant' },+ ];+ const handler = createHandler(store);++ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'hello back' }));+ handler(makeEvent('visible_output_end'));+ await flush();++ expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith(+ 'msg-initial',+ undefined,+ );+ expect(store.updateOperationMetadata).toHaveBeenCalledWith('op-1', {+ visibleLoadingDone: true,+ });+ expect(store.completeOperation).not.toHaveBeenCalledWith('op-1');+ });+ });+});diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.terminal.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.terminal.test.tsnew file mode 100644index 00000000000..0831f84bba4--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.terminal.test.ts@@ -0,0 +1,484 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { messageService } from '@/services/message';+import type * as WorkServiceModule from '@/services/work';+import { workService } from '@/services/work';+import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge';++import { createHandler, createMockStore, flush, makeEvent } from './testUtils';++vi.mock('@/services/message', () => ({+ messageService: {+ getMessages: vi.fn().mockResolvedValue([]),+ updateMessageError: vi.fn().mockResolvedValue({ success: true }),+ },+}));+vi.mock('@/services/work', async (importOriginal) => {+ const actual = await importOriginal<typeof WorkServiceModule>();+ return {+ ...actual,+ workService: {+ refreshConversationViews: vi.fn().mockResolvedValue(undefined),+ },+ };+});+vi.mock('@/store/chat/utils/desktopNotification', () => ({+ notifyDesktopAgentFailed: vi.fn().mockResolvedValue(undefined),+ notifyDesktopHumanApprovalRequired: vi.fn().mockResolvedValue(undefined),+}));+vi.mock('@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge', () => ({+ emitClientAgentSignalSourceEvent: vi.fn().mockResolvedValue(undefined),+}));+const getExecutorMock = vi.fn();+vi.mock('@/store/tool/slices/builtin/executors', () => ({+ getExecutor: (...args: unknown[]) => getExecutorMock(...args),+ registerBuiltinToolExecutors: vi.fn().mockResolvedValue(undefined),+}));++describe('createGatewayEventHandler — terminal and error events', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe('agent_runtime_end', () => {+ it('should complete operation and refresh messages', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('agent_runtime_end'));+ await flush();++ expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ expect(store.replaceMessages).toHaveBeenCalled();+ expect(workService.refreshConversationViews).not.toHaveBeenCalled();+ });++ it('should refresh Work views once after a run with a Work-mutating tool', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(+ makeEvent('tool_end', {+ isSuccess: true,+ payload: {+ parentMessageId: 'msg-parent',+ toolCalling: {+ apiName: 'createTask',+ arguments: '{}',+ id: 'tool-call-1',+ identifier: 'lobe-task',+ },+ },+ result: { success: true, workRegistration: { type: 'task' } },+ }),+ );+ handler(makeEvent('agent_runtime_end', { uiMessages: [] }));+ await flush();++ expect(workService.refreshConversationViews).toHaveBeenCalledTimes(1);+ expect(workService.refreshConversationViews).toHaveBeenCalledWith('topic-1', undefined);+ });++ it('should emit runtime end signal with the current assistant message id', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-step2' } }));+ handler(makeEvent('agent_runtime_end'));+ await flush();++ expect(emitClientAgentSignalSourceEvent).toHaveBeenLastCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({+ anchorMessageId: 'msg-step2',+ assistantMessageId: 'msg-step2',+ operationId: 'op-1',+ }),+ sourceType: 'client.gateway.runtime_end',+ }),+ );+ });++ // MID-stream cancel. The server-side coordinator skips the+ // uiMessages snapshot when state.status='interrupted' to avoid pushing+ // a LOADING_FLAT placeholder. The client must mirror that intent: when+ // `reason='interrupted'` arrives without uiMessages AND we already have+ // server-confirmed streamed state, do NOT fall back to a DB refetch —+ // the executor's partial-finalize catch is still racing to write the+ // real content, and a fetch here would return placeholder and clobber+ // in-memory streamed content.+ it('should NOT refetch from DB when reason=interrupted AND stream had progressed', 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.+ 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: 'interrupted' }));+ await flush();++ expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ expect(messageService.getMessages).not.toHaveBeenCalled();+ expect(store.replaceMessages).not.toHaveBeenCalled();+ });++ // Reviewer feedback on PR #15173: if cancel arrives BEFORE any+ // stream activity (no server-assigned assistant id, no chunks), the+ // optimistic `tmp_*` placeholder messages are the only client-side+ // state and they need the DB refetch to be reconciled with the+ // server-side rows. Skipping the fallback would leave the tmp_*+ // ids stuck in the store indefinitely.+ it('should refetch from DB when reason=interrupted but stream never progressed', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ // No stream_start / stream_chunk before the cancel — only optimistic+ // local state exists, no server-confirmed assistant id, no chunks.+ handler(makeEvent('agent_runtime_end', { reason: 'interrupted' }));+ await flush();++ expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ // Refetch IS called so the tmp_* placeholders get reconciled.+ expect(messageService.getMessages).toHaveBeenCalled();+ expect(store.replaceMessages).toHaveBeenCalled();+ });++ it('should still use uiMessages SoT when reason=interrupted but server included a snapshot', async () => {+ const store = createMockStore();+ const handler = createHandler(store);+ const uiMessages = [{ id: 'msg-initial', role: 'assistant', content: 'partial' }];++ handler(+ makeEvent('agent_runtime_end', {+ reason: 'interrupted',+ uiMessages,+ }),+ );+ await flush();++ // uiMessages present takes precedence over the interrupted skip — the+ // SoT push is authoritative when server chose to send it.+ expect(store.replaceMessages).toHaveBeenCalledWith(uiMessages, {+ action: 'gateway/agent_runtime_end',+ context: expect.any(Object),+ });+ expect(messageService.getMessages).not.toHaveBeenCalled();+ });+ });++ describe('error', () => {+ it('should dispatch inline error, complete operation, and refresh messages', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('error', { message: 'Something went wrong' }));+ await flush();++ expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith(+ 'msg-initial',+ undefined,+ );+ // error→fail: an errored gateway run FAILS the op (not complete).+ expect(store.failOperation).toHaveBeenCalledWith('op-1', expect.anything());+ expect(store.completeOperation).not.toHaveBeenCalled();+ expect(messageService.updateMessageError).toHaveBeenCalledWith(+ 'msg-initial',+ expect.objectContaining({+ body: { message: 'Something went wrong' },+ message: 'Something went wrong',+ type: 'AgentRuntimeError',+ }),+ {+ agentId: 'agent-1',+ groupId: undefined,+ threadId: undefined,+ topicId: 'topic-1',+ },+ );++ // Should dispatch inline error immediately+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ {+ id: 'msg-initial',+ type: 'updateMessage',+ value: {+ error: expect.objectContaining({+ body: { message: 'Something went wrong' },+ message: 'Something went wrong',+ type: 'AgentRuntimeError',+ }),+ },+ },+ { operationId: 'op-1' },+ );++ // Should also refresh messages+ expect(store.replaceMessages).toHaveBeenCalled();+ });++ it('should dispatch inline error with switched message ID', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-step2' } }));+ handler(makeEvent('error', { error: 'Timeout' }));+ await flush();++ expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith(+ 'msg-step2',+ undefined,+ );+ expect(store.failOperation).toHaveBeenCalledWith('op-1', expect.anything());+ expect(store.completeOperation).not.toHaveBeenCalled();+ expect(messageService.updateMessageError).toHaveBeenCalledWith(+ 'msg-step2',+ expect.objectContaining({+ body: { error: 'Timeout' },+ message: 'Timeout',+ type: 'AgentRuntimeError',+ }),+ {+ agentId: 'agent-1',+ groupId: undefined,+ threadId: undefined,+ topicId: 'topic-1',+ },+ );++ // Should dispatch inline error with the switched message ID+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ id: 'msg-step2',+ value: expect.objectContaining({+ error: expect.objectContaining({+ message: 'Timeout',+ body: { error: 'Timeout' },+ }),+ }),+ }),+ { operationId: 'op-1' },+ );+ expect(store.replaceMessages).toHaveBeenCalled();+ });++ it('should preserve structured heterogeneous agent error payloads', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(+ makeEvent('error', {+ body: {+ agentType: 'codex',+ code: 'cli_not_found',+ docsUrl: 'https://github.com/openai/codex',+ installCommands: ['npm install -g @openai/codex'],+ message: 'Codex CLI was not found',+ },+ message: 'Codex CLI was not found',+ type: 'AgentRuntimeError',+ }),+ );+ await flush();++ expect(messageService.updateMessageError).toHaveBeenCalledWith(+ 'msg-initial',+ expect.objectContaining({+ errorRef: 'H8001',+ body: {+ agentType: 'codex',+ code: 'cli_not_found',+ details: { kind: 'cli_not_found' },+ docsUrl: 'https://github.com/openai/codex',+ installCommands: ['npm install -g @openai/codex'],+ message: 'Codex CLI was not found',+ },+ message: 'Codex CLI was not found',+ type: 'AgentRuntimeError',+ }),+ expect.any(Object),+ );+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ value: {+ error: expect.objectContaining({+ errorRef: 'H8001',+ body: {+ agentType: 'codex',+ code: 'cli_not_found',+ details: { kind: 'cli_not_found' },+ docsUrl: 'https://github.com/openai/codex',+ installCommands: ['npm install -g @openai/codex'],+ message: 'Codex CLI was not found',+ },+ message: 'Codex CLI was not found',+ type: 'AgentRuntimeError',+ }),+ },+ }),+ { operationId: 'op-1' },+ );+ });++ it('should prefer updateMessageError returned messages over an extra refetch', async () => {+ const store = createMockStore();+ const handler = createHandler(store);+ const persistedMessages = [{ id: 'msg-initial', role: 'assistant' }];++ vi.mocked(messageService.updateMessageError).mockResolvedValueOnce({+ messages: persistedMessages as any,+ success: true,+ });++ handler(makeEvent('error', { message: 'Something went wrong' }));+ await flush();++ expect(store.replaceMessages).toHaveBeenCalledWith(persistedMessages, {+ context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' },+ });+ expect(messageService.getMessages).not.toHaveBeenCalled();+ });++ it('should ignore late events after an error so the inline error is not overwritten', async () => {+ const store = createMockStore();+ const handler = createHandler(store);+ const persistedMessages = [{ id: 'msg-initial', role: 'assistant' }];++ vi.mocked(messageService.updateMessageError).mockResolvedValueOnce({+ messages: persistedMessages as any,+ success: true,+ });++ handler(makeEvent('error', { message: 'Something went wrong' }));+ handler(makeEvent('tool_end', { isSuccess: true }));+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'late chunk' }));+ await flush();++ expect(messageService.getMessages).not.toHaveBeenCalled();+ expect(store.internal_dispatchMessage).not.toHaveBeenCalledWith(+ expect.objectContaining({+ value: { content: 'late chunk' },+ }),+ expect.any(Object),+ );+ expect(store.replaceMessages).toHaveBeenCalledTimes(1);+ });+ });++ describe('sequential processing', () => {+ it('should dispatch stream_chunk to the new assistant id after stream_start switches it', async () => {+ // Native gateway streams no longer await a DB fetch on stream_start+ // — but stream_chunk must still queue behind stream_start+ // so the chunk targets the NEW assistant id (from stream_start.data),+ // not the previous one.+ const store = createMockStore();+ const callOrder: string[] = [];++ store.internal_dispatchMessage.mockImplementation(() => {+ callOrder.push('dispatch');+ });+ store.associateMessageWithOperation.mockImplementation(() => {+ callOrder.push('associate');+ });++ const handler = createHandler(store);++ handler(+ makeEvent('stream_start', { assistantMessage: { id: 'msg-new', role: 'assistant' } }),+ );+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'Hello' }));+ await flush();++ // associate (from stream_start) precedes dispatch (from stream_chunk)+ const associateIdx = callOrder.indexOf('associate');+ const dispatchIdx = callOrder.indexOf('dispatch');+ expect(associateIdx).toBeGreaterThan(-1);+ expect(dispatchIdx).toBeGreaterThan(associateIdx);++ // Chunk targets the new id, proving the queue ordering held+ expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(+ expect.objectContaining({ id: 'msg-new', value: { content: 'Hello' } }),+ { operationId: 'op-1' },+ );+ // And no DB refetch was issued for the native stream+ expect(messageService.getMessages).not.toHaveBeenCalled();+ });++ it('should still fetch from DB on stream_start when assistantMessage id is absent (hetero CLI)', async () => {+ // Hetero CLI adapters (Claude Code / Codex) never set+ // `assistantMessage.id` on stream_start, so the DB read is still+ // mandatory — it pulls the executor-created placeholder into+ // `dbMessagesMap` so subsequent chunks have a target.+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('stream_start', {}));+ await flush();++ expect(messageService.getMessages).toHaveBeenCalled();+ expect(store.replaceMessages).toHaveBeenCalled();+ });+ });++ describe('multi-step integration', () => {+ it('should handle full LLM → tools → LLM cycle', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ // Step 1: LLM call+ handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-1', role: 'assistant' } }));+ await flush();+ expect(store.associateMessageWithOperation).toHaveBeenCalledWith('msg-1', 'op-1');++ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'Let me search.' }));+ await flush();+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'msg-1', value: { content: 'Let me search.' } }),+ { operationId: 'op-1' },+ );++ const tools = [{ id: 'tc-1' }];+ handler(makeEvent('stream_chunk', { chunkType: 'tools_calling', toolsCalling: tools }));+ await flush();+ expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith('msg-1', [true]);++ handler(makeEvent('stream_end'));+ await flush();+ // Loading stays active between steps — only tool streaming is cleared+ expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith('msg-1', undefined);++ // Tool execution — tool_end still refreshes from DB to pick up the+ // server-created tool message row.+ handler(makeEvent('tool_start', { parentMessageId: 'msg-1', toolCalling: tools[0] }));+ handler(makeEvent('tool_end', { isSuccess: true }));+ await flush();+ expect(store.replaceMessages).toHaveBeenCalled();++ // Step 2: Next LLM call with new assistant message — native stream_start+ // carries the id directly, so it must NOT trigger a DB refetch+ // Only the association switch happens.+ vi.clearAllMocks();+ handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-2', role: 'assistant' } }));+ await flush();+ expect(store.associateMessageWithOperation).toHaveBeenCalledWith('msg-2', 'op-1');+ expect(messageService.getMessages).not.toHaveBeenCalled();+ expect(store.replaceMessages).not.toHaveBeenCalled();++ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'Here are the results.' }));+ await flush();+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'msg-2', value: { content: 'Here are the results.' } }),+ { operationId: 'op-1' },+ );++ handler(makeEvent('stream_end'));+ handler(makeEvent('agent_runtime_end'));+ await flush();+ expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ });+ });+});diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.toolEvents.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.toolEvents.test.tsnew file mode 100644index 00000000000..2a5e3cb19fa--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.toolEvents.test.ts@@ -0,0 +1,373 @@+import { createAdapter } from '@lobechat/heterogeneous-agents';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type * as WorkServiceModule from '@/services/work';+import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';++import { createHandler, createMockStore, flush, makeEvent } from './testUtils';++vi.mock('@/services/message', () => ({+ messageService: {+ getMessages: vi.fn().mockResolvedValue([]),+ updateMessageError: vi.fn().mockResolvedValue({ success: true }),+ },+}));+vi.mock('@/services/work', async (importOriginal) => {+ const actual = await importOriginal<typeof WorkServiceModule>();+ return {+ ...actual,+ workService: {+ refreshConversationViews: vi.fn().mockResolvedValue(undefined),+ },+ };+});+vi.mock('@/store/chat/utils/desktopNotification', () => ({+ notifyDesktopAgentFailed: vi.fn().mockResolvedValue(undefined),+ notifyDesktopHumanApprovalRequired: vi.fn().mockResolvedValue(undefined),+}));+vi.mock('@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge', () => ({+ emitClientAgentSignalSourceEvent: vi.fn().mockResolvedValue(undefined),+}));+const getExecutorMock = vi.fn();+vi.mock('@/store/tool/slices/builtin/executors', () => ({+ getExecutor: (...args: unknown[]) => getExecutorMock(...args),+ registerBuiltinToolExecutors: vi.fn().mockResolvedValue(undefined),+}));++describe('createGatewayEventHandler — tool and step events', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe('tool_start', () => {+ it('should be a no-op (loading already active from stream_start)', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('tool_start', { parentMessageId: 'msg-initial', toolCalling: {} }));+ await flush();++ expect(store.internal_dispatchMessage).not.toHaveBeenCalled();+ expect(store.replaceMessages).not.toHaveBeenCalled();+ });+ });++ describe('step_start', () => {+ it('should notify desktop when human approval is required', () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(+ makeEvent('step_start', {+ pendingToolsCalling: [{ id: 'tool-1' }],+ phase: 'human_approval',+ requiresApproval: true,+ }),+ );++ expect(notifyDesktopHumanApprovalRequired).toHaveBeenCalledWith(+ expect.any(Function),+ expect.objectContaining({+ agentId: 'agent-1',+ topicId: 'topic-1',+ }),+ );+ expect(store.updateTopicStatus).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-1',+ status: 'waitingForHuman',+ topicId: 'topic-1',+ }),+ );+ });+ });++ describe('tool_execute', () => {+ const toolExecuteData = {+ apiName: 'readFile',+ arguments: '{"path":"/tmp/a.txt"}',+ executionTimeoutMs: 60_000,+ identifier: 'local-system',+ toolCallId: 'call_1',+ };++ it('forwards the payload to internal_executeClientTool with operationId', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('tool_execute', toolExecuteData));+ await flush();++ expect(store.internal_executeClientTool).toHaveBeenCalledWith(toolExecuteData, {+ localOperationId: 'op-1',+ operationId: 'op-1',+ });+ });++ it('uses gatewayOperationId (WS key) when distinct from local operationId', async () => {+ // Locally the handler tracks `op-1` (used for message dispatch), but+ // the Agent Gateway WS is keyed on the server-side id `gw-op-server`.+ // The action must receive the latter so it can look up the live+ // AgentStreamClient in `gatewayConnections` and reply with tool_result.+ const store = createMockStore();+ const handler = createHandler(store, { gatewayOperationId: 'gw-op-server' });++ handler(makeEvent('tool_execute', toolExecuteData));+ await flush();++ expect(store.internal_executeClientTool).toHaveBeenCalledWith(toolExecuteData, {+ localOperationId: 'op-1',+ operationId: 'gw-op-server',+ });+ });++ it('is fire-and-forget — does not block the event pipeline', async () => {+ const store = createMockStore();+ // Simulate a slow tool execution that never resolves+ store.internal_executeClientTool.mockImplementation(() => new Promise(() => {}));+ const handler = createHandler(store);++ handler(makeEvent('tool_execute', toolExecuteData));+ // If the handler awaited the action, this subsequent stream_chunk would+ // be queued behind the pending promise forever. We assert it still runs.+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'hi' }));+ await flush();++ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ expect.objectContaining({ value: { content: 'hi' } }),+ expect.any(Object),+ );+ });++ it('ignores tool_execute events without data', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('tool_execute'));+ await flush();++ expect(store.internal_executeClientTool).not.toHaveBeenCalled();+ });+ });++ describe('tool_end', () => {+ it('should refresh messages to pull tool results', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('tool_end', { isSuccess: true }));+ await flush();++ expect(store.replaceMessages).toHaveBeenCalled();+ });++ it('should dispatch onAfterCall when payload is wrapped as { parentMessageId, toolCalling } (real gateway shape)', async () => {+ const store = createMockStore();+ const handler = createHandler(store);+ const onAfterCall = vi.fn().mockResolvedValue(undefined);+ getExecutorMock.mockReturnValueOnce({ onAfterCall });++ handler(+ makeEvent('tool_end', {+ isSuccess: true,+ payload: {+ parentMessageId: 'msg-parent',+ toolCalling: {+ apiName: 'deleteTask',+ arguments: JSON.stringify({ identifier: 'T-3' }),+ id: 'tc-1',+ identifier: 'lobe-task',+ },+ },+ result: { content: 'Task deleted', success: true },+ }),+ );+ await flush();++ expect(getExecutorMock).toHaveBeenCalledWith('lobe-task');+ expect(onAfterCall).toHaveBeenCalledWith({+ apiName: 'deleteTask',+ identifier: 'lobe-task',+ params: { identifier: 'T-3' },+ result: { content: 'Task deleted', success: true },+ toolCallId: 'tc-1',+ topicId: 'topic-1',+ });+ });++ it('should also dispatch onAfterCall when payload is the flat ChatToolPayload', async () => {+ const store = createMockStore();+ const handler = createHandler(store);+ const onAfterCall = vi.fn().mockResolvedValue(undefined);+ getExecutorMock.mockReturnValueOnce({ onAfterCall });++ handler(+ makeEvent('tool_end', {+ isSuccess: true,+ payload: {+ apiName: 'createTask',+ arguments: JSON.stringify({ name: 'New', instruction: 'do thing' }),+ id: 'tc-2',+ identifier: 'lobe-task',+ },+ result: { success: true },+ }),+ );+ await flush();++ expect(onAfterCall).toHaveBeenCalledWith(+ expect.objectContaining({+ apiName: 'createTask',+ identifier: 'lobe-task',+ toolCallId: 'tc-2',+ }),+ );+ });++ it('dispatches a Kimi Code Shell result through the registered renderer hook contract', async () => {+ const store = createMockStore();+ const handler = createHandler(store);+ const onAfterCall = vi.fn().mockResolvedValue(undefined);+ getExecutorMock.mockReturnValueOnce({ onAfterCall });+ const adapter = createAdapter('kimi-code');++ adapter.adapt({+ role: 'assistant',+ tool_calls: [+ {+ function: {+ arguments: JSON.stringify({ command: 'git worktree add /tmp/kimi-wt' }),+ name: 'Shell',+ },+ id: 'kimi-shell-1',+ type: 'function',+ },+ ],+ });+ const toolEnd = adapter+ .adapt({ content: 'created', role: 'tool', tool_call_id: 'kimi-shell-1' })+ .find((event) => event.type === 'tool_end');++ expect(toolEnd).toBeDefined();+ handler(makeEvent('tool_end', toolEnd!.data));+ await flush();++ expect(getExecutorMock).toHaveBeenCalledWith('kimi-code');+ expect(onAfterCall).toHaveBeenCalledWith({+ apiName: 'Shell',+ identifier: 'kimi-code',+ params: { command: 'git worktree add /tmp/kimi-wt' },+ result: { content: 'created', success: true },+ toolCallId: 'kimi-shell-1',+ topicId: 'topic-1',+ });+ });++ it('should skip onAfterCall when payload identifier/apiName are missing', async () => {+ const store = createMockStore();+ const handler = createHandler(store);+ const onAfterCall = vi.fn();+ getExecutorMock.mockReturnValue({ onAfterCall });++ handler(makeEvent('tool_end', { isSuccess: true, payload: { parentMessageId: 'x' } }));+ await flush();++ expect(onAfterCall).not.toHaveBeenCalled();+ });+ });++ describe('tool_start', () => {+ it('should dispatch onBeforeCall with the unwrapped ChatToolPayload', async () => {+ const store = createMockStore();+ const handler = createHandler(store);+ const onBeforeCall = vi.fn().mockResolvedValue(undefined);+ getExecutorMock.mockReturnValueOnce({ onBeforeCall });++ handler(+ makeEvent('tool_start', {+ parentMessageId: 'msg-parent',+ toolCalling: {+ apiName: 'editTask',+ arguments: JSON.stringify({ identifier: 'T-5', name: 'renamed' }),+ id: 'tc-3',+ identifier: 'lobe-task',+ },+ }),+ );+ await flush();++ expect(onBeforeCall).toHaveBeenCalledWith({+ apiName: 'editTask',+ identifier: 'lobe-task',+ params: { identifier: 'T-5', name: 'renamed' },+ toolCallId: 'tc-3',+ topicId: 'topic-1',+ });+ });+ });++ describe('step_complete', () => {+ it('should refresh on execution_complete phase', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('step_complete', { phase: 'execution_complete', reason: 'done' }));+ await flush();++ expect(store.replaceMessages).toHaveBeenCalled();+ });++ it('should not refresh on other phases', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('step_complete', { phase: 'human_approval' }));+ await flush();++ expect(store.replaceMessages).not.toHaveBeenCalled();+ });+ });++ describe('step transition timing (orphan tool regression)', () => {+ /**+ * Verifies that after the executor fix, tools_calling events at step+ * boundaries arrive AFTER stream_start (correct order).+ *+ * Previously, the executor forwarded stream_chunk(tools_calling) sync+ * while stream_start was deferred via persistQueue — handler dispatched+ * tools to the OLD assistant. The fix defers all events during step+ * transition through persistQueue, guaranteeing correct ordering.+ */+ it('should dispatch new-step tools to the NEW assistant when events arrive in correct order', async () => {+ const store = createMockStore();+ const handler = createHandler(store, { assistantMessageId: 'ast-old' });++ // Step 1 init+ handler(makeEvent('stream_start', {}));+ await flush();++ handler(makeEvent('stream_end'));+ await flush();+ vi.clearAllMocks();++ // ── Step boundary: executor now guarantees stream_start arrives FIRST ──+ handler(makeEvent('stream_start', { assistantMessage: { id: 'ast-new' } }));+ await flush();++ handler(+ makeEvent('stream_chunk', {+ chunkType: 'tools_calling',+ toolsCalling: [{ id: 'toolu_new' }],+ }),+ );+ await flush();++ // ── Assert: tools dispatched to the NEW assistant ──+ const toolsDispatch = store.internal_dispatchMessage.mock.calls.find(+ ([action]: any) => action.value?.tools,+ );+ expect(toolsDispatch).toBeDefined();+ expect(toolsDispatch![0].id).toBe('ast-new');+ });+ });+});diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.tsindex d11dbe6c591..137af28c761 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts@@ -38,20 +38,11 @@ import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNoimport { messageMapKey } from '@/store/chat/utils/messageMapKey';import { applyMessagePatch } from './messagePatch';--// `agent_runtime_end` reasons that are NOT a clean completion: a mid-stream-// cancel and a deferred-tool park. These must NOT mark the topic unread, and-// must take the non-success branch in `onSessionComplete` so the run clears-// back to 'active' rather than persisting as an unread completion.-const NON_COMPLETION_RUNTIME_END_REASONS = new Set(['interrupted', 'waiting_for_async_tool']);--/**- * Whether an `agent_runtime_end` event represents a clean completion (vs. a- * cancel / park). A clean completion is the only ending that should surface an- * unread badge.- */-export const isCompletedRuntimeEnd = (reason?: string | null): boolean =>- !NON_COMPLETION_RUNTIME_END_REASONS.has(reason ?? '');+import {+ findTerminalAssistantError,+ isCompletedRuntimeEnd,+ resolveRuntimeEndStatus,+} from './runtimeEndReason';// Lazy-loaded to break the import cycle:// gateway.ts → gatewayEventHandler.ts → executors/index.ts (which pulls in@@ -1370,15 +1361,24 @@ export const createGatewayEventHandler = (// • completed → completeRun completes the op, marks the topic unread,// drains the input queue, then afterRunComplete fires the desktop// notification (skipped if a queued follow-up was scheduled).+ // • failed → completeRun lands the op in `failed`; afterRunComplete+ // fires the failure notification.// • cancelled → completeRun only completes the op (no unread badge,// no queue drain, no notification) — same as the old inline path.if (runtimeType === 'gateway' && runLifecycle) {- const status = isCompletedRuntimeEnd(data?.reason) ? 'completed' : 'cancelled';+ const status = resolveRuntimeEndStatus(data?.reason);const { requeued } = await runLifecycle.completeRun({...lifecycleEventBase,status,});- if (!requeued && status === 'completed') {+ if (status === 'failed') {+ // The failed row's content is the loading placeholder: announce the error.+ await runLifecycle.afterRunComplete({+ ...lifecycleEventBase,+ notification: { error: findTerminalAssistantError(terminalMessages) },+ status,+ });+ } else if (!requeued && status === 'completed') {// Notification body, resolved most-authoritative first://// 1. the terminal snapshot's final assistant text — server-@@ -1465,15 +1465,10 @@ export const createGatewayEventHandler = (get().internal_toggleToolCallingStreaming(currentAssistantMessageId, undefined);endReasoningIfNeeded();- // An errored run is a FAILED run, not a completed one — failed runs- // receive no unread badge, no queue drain, and no notification.- // For gateway, drive the terminal disposition through the- // shared lifecycle so the op lands in `failed` (no unread badge, no queue- // drain, no notification). hetero never forwards `error` to this handler- // (its executor routes errors through persistTerminalError), but keep the- // legacy completeOperation for any other caller for safety.+ // Failed run: no unread badge or queue drain. hetero never forwards `error`.+ const failedEvent = { ...lifecycleEventBase, status: 'failed' as const };if (runtimeType === 'gateway' && runLifecycle) {- await runLifecycle.completeRun({ ...lifecycleEventBase, status: 'failed' });+ await runLifecycle.completeRun(failedEvent);} else {get().completeOperation(operationId);}@@ -1516,6 +1511,11 @@ export const createGatewayEventHandler = (},dispatchContext,);++ // Notify after the error shows; this event ends the session (end is dropped).+ const notification = { error: messageError };+ if (runtimeType === 'gateway')+ await runLifecycle?.afterRunComplete({ ...failedEvent, notification });});break;}diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/runtimeEndReason.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/runtimeEndReason.test.tsnew file mode 100644index 00000000000..b388cec42fe--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/runtimeEndReason.test.ts@@ -0,0 +1,51 @@+import type { UIChatMessage } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import {+ findTerminalAssistantError,+ isCompletedRuntimeEnd,+ resolveRuntimeEndStatus,+} from './runtimeEndReason';++describe('runtimeEndReason', () => {+ it.each([+ ['completed', 'completed'],+ ['done', 'completed'],+ ['success', 'completed'],+ [undefined, 'completed'],+ ['error', 'failed'],+ ['cancelled', 'cancelled'],+ ['interrupted', 'cancelled'],+ ['waiting_for_async_tool', 'cancelled'],+ ])('settles reason %s as %s', (reason, status) => {+ expect(resolveRuntimeEndStatus(reason)).toBe(status);+ expect(isCompletedRuntimeEnd(reason)).toBe(status === 'completed');+ });++ it('reads the error from the last step of a grouped hetero run', () => {+ const error = { message: 'boom', type: 'AgentRuntimeError' };+ const messages = [+ { content: 'hi', id: 'u', role: 'user' },+ {+ children: [{ id: 'a1' }, { error, id: 'a2' }],+ content: '...',+ id: 'a1',+ role: 'assistantGroup',+ },+ ] as unknown as UIChatMessage[];++ expect(findTerminalAssistantError(messages)).toBe(error);+ });++ it('reads the error from a plain assistant row and ignores null', () => {+ const error = { message: 'boom', type: 'AgentRuntimeError' };++ expect(+ findTerminalAssistantError([{ error, id: 'a', role: 'assistant' }] as UIChatMessage[]),+ ).toBe(error);+ expect(+ findTerminalAssistantError([{ error: null, id: 'a', role: 'assistant' }] as UIChatMessage[]),+ ).toBeUndefined();+ expect(findTerminalAssistantError(undefined)).toBeUndefined();+ });+});diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/runtimeEndReason.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/runtimeEndReason.tsnew file mode 100644index 00000000000..949d35a0a9d--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/runtimeEndReason.ts@@ -0,0 +1,45 @@+import type { ChatMessageError, UIChatMessage } from '@lobechat/types';++// `agent_runtime_end` reasons that are NOT a clean completion: a mid-stream+// cancel, a deferred-tool park, and a failed run (the server runtime ends an+// errored op with its `error` status; `heteroFinish` reports `error` /+// `cancelled`). These must NOT mark the topic unread, and must take the+// non-success branch in `onSessionComplete` so the run clears back to 'active'+// rather than persisting as an unread completion.+const NON_COMPLETION_RUNTIME_END_REASONS = new Set([+ 'cancelled',+ 'error',+ 'interrupted',+ 'waiting_for_async_tool',+]);++/**+ * Whether an `agent_runtime_end` event represents a clean completion (vs. a+ * cancel / park / failure). A clean completion is the only ending that should+ * surface an unread badge.+ */+export const isCompletedRuntimeEnd = (reason?: string | null): boolean =>+ !NON_COMPLETION_RUNTIME_END_REASONS.has(reason ?? '');++/** Terminal run status an `agent_runtime_end` reason settles to. */+export const resolveRuntimeEndStatus = (+ reason?: string | null,+): 'cancelled' | 'completed' | 'failed' => {+ if (reason === 'error') return 'failed';++ return isCompletedRuntimeEnd(reason) ? 'completed' : 'cancelled';+};++/**+ * Error persisted on the run's last assistant row. A hetero run arrives as one+ * `assistantGroup` whose failed step is its last child.+ */+export const findTerminalAssistantError = (+ messages: UIChatMessage[] | undefined,+): ChatMessageError | undefined => {+ const last = messages?.findLast(+ (message) => message.role === 'assistant' || message.role === 'assistantGroup',+ );++ return (last?.children?.at(-1)?.error ?? last?.error) || undefined;+};diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/testUtils.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/testUtils.tsnew file mode 100644index 00000000000..d746c2edb42--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/testUtils.ts@@ -0,0 +1,78 @@+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';+import { vi } from 'vitest';++import { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';+import { createGatewayEventHandler } from './gatewayEventHandler';++export function createMockStore() {+ let reasoningCounter = 0;+ return {+ associateMessageWithOperation: vi.fn(),+ completeOperation: vi.fn(),+ // completeRun (via buildRunLifecycle) drains the input queue on a successful+ // terminal and fails the op on an errored terminal.+ dbMessagesMap: {} as Record<string, any>,+ drainQueuedMessages: vi.fn(() => [] as any[]),+ failOperation: vi.fn(),+ internal_dispatchMessage: vi.fn(),+ internal_executeClientTool: vi.fn().mockResolvedValue(undefined),+ internal_toggleToolCallingStreaming: vi.fn(),+ markTopicUnread: vi.fn(),+ messagesMap: {} as Record<string, any>,+ topicDataMap: {},+ operations: {+ 'op-1': {+ context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' },+ metadata: { startTime: 0 },+ },+ } as Record<string, any>,+ operationsByContext: {},+ replaceMessages: vi.fn(),+ startOperation: vi.fn(() => {+ reasoningCounter += 1;+ return {+ abortController: new AbortController(),+ operationId: `op-reasoning-${reasoningCounter}`,+ };+ }),+ updateOperationMetadata: vi.fn(),+ updateTopicStatus: vi.fn().mockResolvedValue(undefined),+ };+}++export function createHandler(+ store: ReturnType<typeof createMockStore>,+ overrides?: { assistantMessageId?: string; gatewayOperationId?: string },+) {+ const get = vi.fn(() => store) as any;+ const assistantMessageId = overrides?.assistantMessageId ?? 'msg-initial';+ const context = { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' } as any;+ return createGatewayEventHandler(get, {+ assistantMessageId,+ context,+ gatewayOperationId: overrides?.gatewayOperationId,+ operationId: 'op-1',+ // The gateway transport injects the shared run lifecycle (built once per run+ // in gateway.ts). Build the real one here so the terminal completeRun /+ // afterRunComplete path under test runs against the mock store.+ runLifecycle: buildRunLifecycle(get, {+ context,+ parentMessageId: assistantMessageId,+ parentMessageType: 'assistant',+ runId: 'op-1',+ runScope: 'top_level',+ runtimeType: 'gateway',+ }),+ });+}++export function makeEvent(type: AgentStreamEvent['type'], data?: any): AgentStreamEvent {+ return { data, id: '1', operationId: 'op-1', stepIndex: 0, timestamp: Date.now(), type };+}++/** Flush the async processing queue by draining microtasks + setTimeout queue */+export const flush = async () => {+ for (let i = 0; i < 5; i++) {+ await new Promise((r) => setTimeout(r, 15));+ }+};diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heteroResume.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heteroResume.tsindex 39935c7ce8b..970a7d67ac1 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heteroResume.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heteroResume.ts@@ -1,3 +1,5 @@+import type { HeterogeneousAgentSessionError } from '@lobechat/electron-client-ipc';+import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';import type { ChatTopicMetadata } from '@lobechat/types';import {@@ -117,3 +119,19 @@ export const resolveHeteroResume = (return resolveBinding(savedSessionId, metadata?.heteroSessionBindingKey);};++/** Session errors a fresh (non-resumed) CLI session recovers from. */+export const isRecoverableResumeError = (+ error: unknown,+): error is HeterogeneousAgentSessionError & {+ code:+ | typeof HeterogeneousAgentSessionErrorCode.ResumeCwdMismatch+ | typeof HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound;+} => {+ if (!error || typeof error !== 'object' || !('code' in error)) return false;++ return (+ error.code === HeterogeneousAgentSessionErrorCode.ResumeCwdMismatch ||+ error.code === HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound+ );+};diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex 2569632d3c1..e514fa98b58 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -90,9 +90,10 @@ import { labPreferSelectors, userProfileSelectors } from '@/store/user/selectorsimport { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';import type { RunScope } from '../../lifecycle/types';-import { createGatewayEventHandler, isCompletedRuntimeEnd } from '../gateway/gatewayEventHandler';+import { createGatewayEventHandler } from '../gateway/gatewayEventHandler';+import { isCompletedRuntimeEnd } from '../gateway/runtimeEndReason';import { withHeteroContext } from '../viewedTaskPrompt';-import { getNativeHeteroSessionBindingKey } from './heteroResume';+import { getNativeHeteroSessionBindingKey, isRecoverableResumeError } from './heteroResume';import { createMessageWriteBatcher, type ToolMessageUpdateOperation } from './messageWriteBatcher';import { createPendingCreateLedger } from './pendingCreateLedger';import { resolveQuotaAccountSpawnPlan } from './resolveQuotaAccountEnv';@@ -216,21 +217,6 @@ const toHeterogeneousAgentMessageError = (error: unknown, agentType?: string): CagentType,);-const isRecoverableResumeError = (- error: unknown,-): error is HeterogeneousAgentSessionError & {- code:- | typeof HeterogeneousAgentSessionErrorCode.ResumeCwdMismatch- | typeof HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound;-} => {- if (!error || typeof error !== 'object' || !('code' in error)) return false;-- return (- error.code === HeterogeneousAgentSessionErrorCode.ResumeCwdMismatch ||- error.code === HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound- );-};-export interface HeterogeneousAgentExecutorParams {assistantMessageId: string;/**@@ -637,6 +623,7 @@ export const executeHeterogeneousAgent = async (messageError: ChatMessageError,options?: { clearContent?: boolean },) => {+ const firstTerminalError = !terminalErrorPersisted;terminalErrorPersisted = true;writeTopicStatus('failed');get().internal_toggleToolCallingStreaming(mainState.currentAssistantId, undefined);@@ -681,6 +668,18 @@ export const executeHeterogeneousAgent = async (},{ operationId },);++ if (firstTerminalError && !isAborted()) {+ await runLifecycle.afterRunComplete({+ context,+ notification: { error: messageError },+ operationId,+ runId: operationId,+ runScope,+ runtimeType: 'hetero',+ status: 'failed',+ });+ }};let ipcRunSessionId: string | undefined;diff --git a/src/store/chat/utils/desktopNotification.test.ts b/src/store/chat/utils/desktopNotification.test.tsindex 3cb06ec790e..46969a016d1 100644--- a/src/store/chat/utils/desktopNotification.test.ts+++ b/src/store/chat/utils/desktopNotification.test.ts@@ -10,9 +10,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import type { ChatStore } from '@/store/chat/store';import {+ buildFailureNotificationBody,+ buildFailureNotificationTitle,buildNotificationBody,buildNotificationSender,notifyDesktopAgentCompleted,+ notifyDesktopAgentFailed,resolveNotificationNavigate,resolveNotificationNavigatePath,resolveNotificationTitle,@@ -202,6 +205,10 @@ describe('buildNotificationBody', () => {expect(body.endsWith('…')).toBe(true);});+ it('treats the loading placeholder as no reply', () => {+ expect(buildNotificationBody('...', FALLBACK)).toBe(FALLBACK);+ });+it('returns the fallback for empty / undefined content', () => {expect(buildNotificationBody(undefined, FALLBACK)).toBe(FALLBACK);expect(buildNotificationBody(' ', FALLBACK)).toBe(FALLBACK);@@ -245,3 +252,62 @@ describe('buildNotificationSender', () => {});});});++describe('failed run notification', () => {+ beforeEach(() => {+ showNotification.mockReset().mockResolvedValue({ success: true });+ });++ const workingDirectoryError = {+ body: { code: 'working_directory_not_found', workingDirectory: '/Users/me/gone' },+ message: 'Working directory does not exist: /Users/me/gone',+ type: 'AgentRuntimeError',+ };++ it('names the missing working directory in the body', () => {+ expect(buildFailureNotificationBody(workingDirectoryError)).toBe(+ 'Working directory unavailable: /Users/me/gone',+ );+ });++ it('does not pass fallback prose off as a path when the error has none', () => {+ expect(+ buildFailureNotificationBody({+ body: { agentType: 'claude-code', code: 'working_directory_not_found' },+ message: 'Working directory does not exist: /Users/me/gone',+ type: 'AgentRuntimeError',+ }),+ ).toBe(+ 'Working directory unavailable: the folder saved for this conversation no longer exists',+ );+ });++ it('uses the error message, falling back to a generic line', () => {+ expect(buildFailureNotificationBody({ message: 'Quota exceeded', type: 'x' } as any)).toBe(+ 'Quota exceeded',+ );+ expect(buildFailureNotificationBody(undefined)).toBe('Open the conversation for details');+ });++ it('titles the banner after the agent that hit the problem', () => {+ expect(buildFailureNotificationTitle({ agentId: 'agent-named' })).toBe(+ 'My Agent ran into a problem',+ );+ expect(buildFailureNotificationTitle({})).toBe('Default Agent ran into a problem');+ });++ it('sends the failure banner deep-linked to the topic', async () => {+ await notifyDesktopAgentFailed(() => ({}) as ChatStore, {+ context: { agentId: 'agent-named', topicId: 'topic-1' },+ error: workingDirectoryError,+ });++ expect(showNotification).toHaveBeenCalledWith(+ expect.objectContaining({+ body: 'Working directory unavailable: /Users/me/gone',+ navigate: { escape: true, path: AGENT_CHAT_TOPIC_URL('agent-named', 'topic-1') },+ title: 'My Agent ran into a problem',+ }),+ );+ });+});diff --git a/src/store/chat/utils/desktopNotification.ts b/src/store/chat/utils/desktopNotification.tsindex 96e38f2c315..5bb2d7e879b 100644--- a/src/store/chat/utils/desktopNotification.ts+++ b/src/store/chat/utils/desktopNotification.ts@@ -4,9 +4,13 @@ import {GROUP_CHAT_TOPIC_URL,GROUP_CHAT_URL,isDesktop,+ LOADING_FLAT,} from '@lobechat/const';-import type { DesktopNotificationSender } from '@lobechat/electron-client-ipc';-import type { ConversationContext } from '@lobechat/types';+import {+ type DesktopNotificationSender,+ HeterogeneousAgentSessionErrorCode,+} from '@lobechat/electron-client-ipc';+import type { ChatMessageError, ConversationContext } from '@lobechat/types';import { agentDisplayName } from '@lobechat/types';import { t } from 'i18next';@@ -125,7 +129,8 @@ export const buildNotificationBody = (fallbackBody: string,): string => {const text = content ? markdownToTxt(content).trim() : '';- if (!text) return fallbackBody;+ // The assistant row still holding the loading placeholder means the run produced no reply.+ if (!text || text === LOADING_FLAT) return fallbackBody;return text.length > NOTIFICATION_BODY_MAX_LENGTH? `${text.slice(0, NOTIFICATION_BODY_MAX_LENGTH)}…`: text;@@ -225,3 +230,62 @@ export const notifyDesktopAgentCompleted = async (console.error('Agent completion desktop notification failed:', error);}};++/**+ * Plain-text reason for a failed run. Errors that render a dedicated guide card+ * get localized wording; anything else surfaces the error's own message.+ */+export const buildFailureNotificationBody = (error: ChatMessageError | undefined): string => {+ const fallback = t('desktopNotification.agentFailed.body', { ns: 'chat' });++ if (error?.body?.code === HeterogeneousAgentSessionErrorCode.WorkingDirectoryNotFound) {+ // Gateway/CLI-classified errors carry the path only inside their raw message.+ const path: string | undefined = error.body.workingDirectory;+ return path+ ? t('desktopNotification.workingDirectoryUnavailable.body', { ns: 'chat', path })+ : t('desktopNotification.workingDirectoryUnavailable.bodyWithoutPath', { ns: 'chat' });+ }++ return buildNotificationBody(error?.message, fallback);+};++/** "<agent> ran into a problem" — names the agent rather than the topic. */+export const buildFailureNotificationTitle = (context: DesktopNotificationContext): string => {+ const agentMeta = context.agentId+ ? agentSelectors.getAgentMetaById(context.agentId)(getAgentStoreState())+ : undefined;+ const name = agentDisplayName(agentMeta) || t('defaultAgent', { ns: 'chat' });++ return t('desktopNotification.agentFailed.title', { name, ns: 'chat' });+};++export interface AgentFailedNotificationOptions {+ context: DesktopNotificationContext;+ error?: ChatMessageError;+}++/**+ * "Agent run failed" desktop notification. Shares the completion notification's+ * sender and click-through, so a failure in a background conversation is+ * announced instead of staying silent (or reading as a finished, empty reply).+ */+export const notifyDesktopAgentFailed = async (+ _get: () => ChatStore,+ { context, error }: AgentFailedNotificationOptions,+): Promise<void> => {+ if (!isDesktop) return;++ try {+ const { desktopNotificationService } = await import('@/services/electron/desktopNotification');+ const sender = await buildNotificationSender(context);++ await desktopNotificationService.showNotification({+ body: buildFailureNotificationBody(error),+ navigate: resolveNotificationNavigate(context),+ sender,+ title: buildFailureNotificationTitle(context),+ });+ } catch (err) {+ console.error('Agent failure desktop notification failed:', err);+ }+};