π€― 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
β»οΈ refactor(chat): make run-lifecycle completeRun transport-driven (#16083)
Arvin Xud37ebb2922a2
diff --git a/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.test.ts b/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.test.tsnew file mode 100644index 00000000000..02157d1a7c7--- /dev/null+++ b/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.test.ts@@ -0,0 +1,118 @@+import type { ConversationContext } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { ChatStore } from '@/store/chat/store';++import type { AgentRuntimeType } from '../agentDispatcher';+import { buildRunLifecycle } from './buildRunLifecycle';+import type { RunCompleteEvent, RunTerminalStatus } from './types';++const agentSignalBridgeMock = vi.hoisted(() => ({+ emitClientAgentSignalSourceEvent: vi.fn().mockResolvedValue(undefined),+}));++vi.mock('@/store/chat/slices/aiChat/actions/agentSignalBridge', () => ({+ emitClientAgentSignalSourceEvent: agentSignalBridgeMock.emitClientAgentSignalSourceEvent,+}));++const OP = 'op1';+const CONTEXT: ConversationContext = { agentId: 'a1', topicId: 't1' } as ConversationContext;++const makeStore = (afterCompletionCallbacks?: Array<() => void>) => {+ const store = {+ completeOperation: vi.fn(),+ dbMessagesMap: {},+ drainQueuedMessages: vi.fn(() => []),+ failOperation: vi.fn(),+ markTopicUnread: vi.fn(),+ messagesMap: {},+ operations: {+ [OP]: {+ context: { agentId: 'a1', topicId: 't1' },+ metadata: afterCompletionCallbacks ? { runtimeHooks: { afterCompletionCallbacks } } : {},+ status: 'running',+ },+ },+ };+ return { get: (() => store) as unknown as () => ChatStore, store };+};++const lifecycle = (runtimeType: AgentRuntimeType, get: () => ChatStore) =>+ buildRunLifecycle(get, {+ context: CONTEXT,+ parentMessageId: 'u1',+ parentMessageType: 'user',+ runId: OP,+ runScope: 'top_level',+ runtimeType,+ });++const completeEvent = (+ runtimeType: AgentRuntimeType,+ fields: Partial<RunCompleteEvent>,+): RunCompleteEvent => ({+ context: CONTEXT,+ operationId: OP,+ runId: OP,+ runScope: 'top_level',+ runtimeType,+ ...fields,+});++beforeEach(() => {+ agentSignalBridgeMock.emitClientAgentSignalSourceEvent.mockClear();+});++describe('buildRunLifecycle.completeRun β transport-driven disposition', () => {+ it('client `runtimeStatus: done` completes the op, marks unread, and emits client.runtime.complete', async () => {+ const { get, store } = makeStore();+ await lifecycle('client', get).completeRun(completeEvent('client', { runtimeStatus: 'done' }));++ expect(store.completeOperation).toHaveBeenCalledWith(OP);+ expect(store.markTopicUnread).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'a1', topicId: 't1' }),+ );+ expect(store.failOperation).not.toHaveBeenCalled();+ expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({ operationId: OP, status: 'completed' }),+ sourceType: 'client.runtime.complete',+ }),+ );+ });++ it.each<[RunTerminalStatus, 'completeOperation' | 'failOperation']>([+ ['completed', 'completeOperation'],+ ['failed', 'failOperation'],+ ])(+ 'gateway normalized `status: %s` drives the same op completion WITHOUT emitting client.runtime.complete',+ async (status, completer) => {+ const { get, store } = makeStore();+ await lifecycle('gateway', get).completeRun(completeEvent('gateway', { status }));++ expect(store[completer]).toHaveBeenCalledWith(+ OP,+ ...(completer === 'failOperation' ? [expect.anything()] : []),+ );+ // The client-only signal must NOT fire for gateway.+ expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).not.toHaveBeenCalled();+ },+ );++ it('gateway `status: cancelled` neither completes nor fails the op, and emits nothing', async () => {+ const { get, store } = makeStore();+ await lifecycle('gateway', get).completeRun(completeEvent('gateway', { status: 'cancelled' }));++ expect(store.completeOperation).not.toHaveBeenCalled();+ expect(store.failOperation).not.toHaveBeenCalled();+ expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).not.toHaveBeenCalled();+ });++ it('runs afterCompletion callbacks on every terminal regardless of transport', async () => {+ const cb = vi.fn();+ const { get } = makeStore([cb]);+ await lifecycle('hetero', get).completeRun(completeEvent('hetero', { status: 'completed' }));++ expect(cb).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.ts b/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.tsindex da172987fb2..0081843b3f8 100644--- a/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.ts+++ b/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.ts@@ -43,6 +43,35 @@ const normalizeClientRuntimeCompleteStatus = (return undefined;};+/** The effective terminal disposition a run ended on, transport-agnostic. */+type TerminalDisposition = 'cancelled' | 'failed' | 'success';++/**+ * Resolve the terminal disposition from EITHER the client's raw `runtimeStatus`+ * (`AgentState['status']`) OR the normalized cross-runtime `status` that gateway+ * / hetero supply. This lets `completeRun` drive the same store/UI side effects+ * regardless of which transport reached the terminal boundary.+ *+ * `cancelled` / `undefined` deliberately do not complete the operation here β the+ * client cancel path already moves the operation to its terminal state out of+ * band; gateway/hetero cancel completion is handled when those transports are+ * wired in.+ */+const resolveTerminalDisposition = (+ event: Pick<RunCompleteEvent, 'runtimeStatus' | 'status'>,+): TerminalDisposition | undefined => {+ const { runtimeStatus, status } = event;+ // Client drives off the raw runtime status.+ if (runtimeStatus === 'done') return 'success';+ if (runtimeStatus === 'error') return 'failed';+ if (runtimeStatus === 'interrupted') return 'cancelled';+ // Gateway / hetero drive off the normalized terminal status.+ if (status === 'completed') return 'success';+ if (status === 'failed') return 'failed';+ if (status === 'cancelled') return 'cancelled';+ return undefined;+};+const findCompletionAssistantMessageId = (messages: UIChatMessage[],parentMessageId: string,@@ -107,6 +136,11 @@ export const buildRunLifecycle = (const contextKey = messageKey;const emitComplete = (operationId: string, runtimeStatus: AgentState['status'] | undefined) => {+ // `client.runtime.complete` is a CLIENT-only source event (browser β server+ // policy pipeline). Gateway / hetero emit their own `client.gateway.*` events+ // at their transport boundaries, so the shared lifecycle must not emit it for+ // them.+ if (adapter.runtimeType !== 'client') return;const finalMessages = get().messagesMap[messageKey] || [];const assistantMessageId =findCompletionAssistantMessageId(finalMessages, parentMessageId, parentMessageType) ??@@ -171,10 +205,25 @@ export const buildRunLifecycle = (void operationId;},beforeRunComplete: NOOP,- completeRun: async ({- operationId,- runtimeStatus,- }: RunCompleteEvent): Promise<RunCompleteResult> => {+ completeRun: async (event: RunCompleteEvent): Promise<RunCompleteResult> => {+ const { operationId, runtimeStatus } = event;+ // Effective terminal disposition, resolved from the client `runtimeStatus`+ // OR the normalized `status` gateway/hetero pass β so the same side effects+ // fire regardless of which transport reached this boundary.+ const disposition = resolveTerminalDisposition(event);++ const completeSuccess = () => {+ get().completeOperation(operationId);+ const completedOp = get().operations[operationId];+ if (completedOp?.context.agentId) {+ get().markTopicUnread({+ agentId: completedOp.context.agentId,+ groupId: completedOp.context.groupId,+ topicId: completedOp.context.topicId,+ });+ }+ };+// 1. afterCompletion callbacks β fire on ALL terminal states (tools that// registered post-run actions: speak / broadcast / delegate).const operation = get().operations[operationId];@@ -192,22 +241,12 @@ export const buildRunLifecycle = (// 2. On success with queued messages: drain, complete, and re-trigger a new// sendMessage. Only drain on success β on error the queue is preserved.- if (runtimeStatus === 'done') {+ if (disposition === 'success') {const remainingQueued = get().drainQueuedMessages(contextKey);if (remainingQueued.length > 0) {const merged = mergeQueuedMessages(remainingQueued);- get().completeOperation(operationId);-- const completedOp = get().operations[operationId];- if (completedOp?.context.agentId) {- get().markTopicUnread({- agentId: completedOp.context.agentId,- groupId: completedOp.context.groupId,- topicId: completedOp.context.topicId,- });- }-+ completeSuccess();emitComplete(operationId, runtimeStatus);const execContext = { ...context };@@ -239,29 +278,22 @@ export const buildRunLifecycle = (}}- // 3. Complete the operation based on the terminal state.- switch (runtimeStatus) {- case 'done': {- get().completeOperation(operationId);- const completedOp = get().operations[operationId];- if (completedOp?.context.agentId) {- get().markTopicUnread({- agentId: completedOp.context.agentId,- groupId: completedOp.context.groupId,- topicId: completedOp.context.topicId,- });- }+ // 3. Complete the operation based on the terminal disposition.+ switch (disposition) {+ case 'success': {+ completeSuccess();break;}- case 'error': {+ case 'failed': {get().failOperation(operationId, {type: 'runtime_error',message: 'Agent runtime execution failed',});break;}- // Parked states (`waiting_for_human` / `waiting_for_async_tool`) never- // reach `completeRun` β the executor routes them to `onRunParked`.+ // `cancelled` / `undefined`: the operation already reached its terminal+ // state out of band (client cancel path). Parked states never reach+ // `completeRun` β the executor routes them to `onRunParked`.}emitComplete(operationId, runtimeStatus);