π€― 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): converge remaining run entries onto the unified lifecycle (#16151)
Arvin Xu7937401eb27f
diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.tsindex 68329c6bdaf..13f50633424 100644--- a/src/features/Conversation/store/slices/generation/action.ts+++ b/src/features/Conversation/store/slices/generation/action.ts@@ -61,6 +61,28 @@ const buildRetryInitialContext = (editorData: Record<string, any> | null | undef};};+/**+ * Settle a regenerate / continue entry's OUTER tracking operation and fire its+ * thin UI completion hook (`onRegenerateComplete` / `onContinueComplete`).+ *+ * Each of these entries owns an outer tracking op distinct from the executor's+ * run op (`${messageKey}/${parentMessageId}`). The unified run lifecycle+ * (`buildRunLifecycle`, inside the executor) already drove the run-level terminal+ * side effects β title / queue drain / notification / complete signal β so the+ * entry only retires its own tracking op and broadcasts the UI hook. Five runtime+ * branches (regenerate Γ client/gateway/hetero, continue Γ client/gateway) shared+ * this identical two-line tail; centralized here so they converge on one adapter+ * instead of hand-rolling completion at each call site.+ */+const settleGenerationEntry = (+ chatStore: ReturnType<typeof useChatStore.getState>,+ operationId: string,+ notify?: () => void,+) => {+ chatStore.completeOperation(operationId);+ notify?.();+};+/*** Branch a hetero (Claude Code / Codex) turn off an existing user message.*@@ -350,10 +372,10 @@ export const generationSlice: StateCreator<await chatStore.executeGatewayAgent({context,message: '',- onComplete: () => {- chatStore.completeOperation(operationId);- if (hooks.onContinueComplete) hooks.onContinueComplete(displayMessageId);- },+ onComplete: () =>+ settleGenerationEntry(chatStore, operationId, () =>+ hooks.onContinueComplete?.(displayMessageId),+ ),parentMessageId: dbMessageId,});return;@@ -368,12 +390,9 @@ export const generationSlice: StateCreator<parentOperationId: operationId,});- chatStore.completeOperation(operationId);-- // ===== Hook: onContinueComplete =====- if (hooks.onContinueComplete) {- hooks.onContinueComplete(displayMessageId);- }+ settleGenerationEntry(chatStore, operationId, () =>+ hooks.onContinueComplete?.(displayMessageId),+ );} catch (error) {chatStore.failOperation(operationId, {message: error instanceof Error ? error.message : String(error),@@ -515,12 +534,10 @@ export const generationSlice: StateCreator<await chatStore.executeGatewayAgent({context,message: item.content,- onComplete: () => {- chatStore.completeOperation(operationId);- if (hooks.onRegenerateComplete) {- hooks.onRegenerateComplete(messageId);- }- },+ onComplete: () =>+ settleGenerationEntry(chatStore, operationId, () =>+ hooks.onRegenerateComplete?.(messageId),+ ),parentMessageId: messageId,});@@ -545,8 +562,9 @@ export const generationSlice: StateCreator<parentOperationId: operationId,prompt: item.content,});- chatStore.completeOperation(operationId);- if (hooks.onRegenerateComplete) hooks.onRegenerateComplete(messageId);+ settleGenerationEntry(chatStore, operationId, () =>+ hooks.onRegenerateComplete?.(messageId),+ );return;}@@ -561,12 +579,7 @@ export const generationSlice: StateCreator<parentOperationId: operationId,});- chatStore.completeOperation(operationId);-- // ===== Hook: onRegenerateComplete =====- if (hooks.onRegenerateComplete) {- hooks.onRegenerateComplete(messageId);- }+ settleGenerationEntry(chatStore, operationId, () => hooks.onRegenerateComplete?.(messageId));} catch (error) {chatStore.failOperation(operationId, {message: error instanceof Error ? error.message : String(error),diff --git a/src/store/chat/slices/aiChat/actions/conversationControl.ts b/src/store/chat/slices/aiChat/actions/conversationControl.tsindex 3b76721cb5d..21cf2dedb32 100644--- a/src/store/chat/slices/aiChat/actions/conversationControl.ts+++ b/src/store/chat/slices/aiChat/actions/conversationControl.ts@@ -9,7 +9,10 @@ import {import { getAgentStoreState } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';-import { selectRuntimeType } from '@/store/chat/slices/aiChat/actions/agentDispatcher';+import {+ type AgentRuntimeType,+ selectRuntimeType,+} from '@/store/chat/slices/aiChat/actions/agentDispatcher';import { operationSelectors } from '@/store/chat/slices/operation/selectors';import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation/types';import { type ChatStore } from '@/store/chat/store';@@ -19,6 +22,8 @@ import { displayMessageSelectors } from '../../../selectors';import { messageMapKey } from '../../../utils/messageMapKey';import { type OptimisticUpdateContext } from '../../message/actions/optimisticUpdate';import { dbMessageSelectors } from '../../message/selectors';+import { buildRunLifecycle } from './runLifecycle/buildRunLifecycle';+import { type RunScope } from './runLifecycle/types';/*** Actions for controlling conversation operations like cancellation and error handling@@ -220,6 +225,41 @@ export class ConversationControlActionImpl {);};+ /**+ * Broadcast that a parked run is resuming under a NEW operation. The resume+ * entries (approve / reject / reject-continue / submit / skip) call this at+ * dispatch so the park β resume transition flows through the unified run+ * lifecycle's `onRunResumed` seam instead of being invisible to it.+ *+ * Behavior-neutral: fires no terminal side effects and mutates no store state+ * (see `buildRunLifecycle.onRunResumed`). `buildRunLifecycle` is a pure factory,+ * so constructing a throwaway instance here purely to broadcast the resume is+ * cheap and side-effect-free; `[6]` AgentRunner is where the lifecycle becomes a+ * single per-run instance threaded through dispatch.+ */+ #emitRunResumed = (+ context: ConversationContext,+ params: { operationId: string; parentMessageId: string; runtimeType: AgentRuntimeType },+ ) => {+ const { operationId, parentMessageId, runtimeType } = params;+ const runScope: RunScope = context.scope === 'sub_agent' ? 'sub_agent' : 'top_level';+ void buildRunLifecycle(this.#get, {+ context,+ parentMessageId,+ parentMessageType: 'tool',+ runId: operationId,+ runScope,+ runtimeType,+ }).onRunResumed({+ context,+ operationId,+ resumedOperationId: operationId,+ runId: operationId,+ runScope,+ runtimeType,+ });+ };+approveToolCalling = async (toolMessageId: string,_assistantGroupId: string,@@ -255,6 +295,13 @@ export class ConversationControlActionImpl {const optimisticContext = { operationId };+ // Park β resume: a new op continues the run paused on this tool's approval.+ this.#emitRunResumed(effectiveContext, {+ operationId,+ parentMessageId: toolMessageId,+ runtimeType: this.#shouldUseGatewayResume(effectiveContext) ? 'gateway' : 'client',+ });+// 2. Update intervention status to approvedawait this.#get().optimisticUpdateMessagePlugin(toolMessageId,@@ -398,6 +445,13 @@ export class ConversationControlActionImpl {const optimisticContext: OptimisticUpdateContext = { operationId };const shouldCreateUserMessage = options?.createUserMessage !== false;+ // Park β resume: a new op continues the run paused on this tool interaction.+ this.#emitRunResumed(effectiveContext, {+ operationId,+ parentMessageId: toolMessageId,+ runtimeType: 'client',+ });+// 1. Mark intervention as approved and set tool result to user's responseawait this.#get().optimisticUpdateMessagePlugin(toolMessageId,@@ -570,6 +624,13 @@ export class ConversationControlActionImpl {const optimisticContext: OptimisticUpdateContext = { operationId };+ // Park β resume: a new op continues the run paused on this tool interaction.+ this.#emitRunResumed(effectiveContext, {+ operationId,+ parentMessageId: toolMessageId,+ runtimeType: 'client',+ });+// 1. Mark intervention as rejected (skipped) with reasonawait this.#get().optimisticUpdateMessagePlugin(toolMessageId,@@ -961,6 +1022,12 @@ export class ConversationControlActionImpl {return;}const pausedOpIds = this.#getRunningServerOps(effectiveContext).map((op) => op.id);+ // Park β resume: the new gateway op continues the run paused on this tool.+ this.#emitRunResumed(effectiveContext, {+ operationId,+ parentMessageId: messageId,+ runtimeType: 'gateway',+ });try {await this.#get().executeGatewayAgent({context: effectiveContext,@@ -1031,6 +1098,12 @@ export class ConversationControlActionImpl {});const optimisticContext = { operationId };+ // Park β resume: the new gateway op continues the run paused on this tool.+ this.#emitRunResumed(effectiveContext, {+ operationId,+ parentMessageId: messageId,+ runtimeType: 'gateway',+ });await this.#get().optimisticUpdateMessagePlugin(messageId,{ intervention: { rejectedReason: reason, status: 'rejected' } as any },@@ -1088,6 +1161,13 @@ export class ConversationControlActionImpl {},});+ // Park β resume: this local op continues the run paused on the rejected tool.+ this.#emitRunResumed(effectiveContext, {+ operationId,+ parentMessageId: messageId,+ runtimeType: 'client',+ });+// Get current messages for state construction using contextconst chatKey = messageMapKey({ agentId, topicId, threadId, scope });const currentMessages = displayMessageSelectors.getDisplayMessagesByKey(chatKey)(this.#get());diff --git a/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.test.ts b/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.test.tsindex ba4bbf2fd08..d1a79c011c7 100644--- a/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.test.ts+++ b/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.test.ts@@ -248,3 +248,44 @@ describe('buildRunLifecycle.afterUserMessagePersisted β topic title (all runtiexpect(store.summaryTopicTitle).not.toHaveBeenCalled();});});++describe('buildRunLifecycle.onRunResumed β park β resume broadcast seam', () => {+ const resumedEvent = (runtimeType: AgentRuntimeType, runScope: 'sub_agent' | 'top_level') => ({+ context: CONTEXT,+ operationId: OP,+ resumedOperationId: 'op2',+ runId: OP,+ runScope,+ runtimeType,+ });++ it.each<AgentRuntimeType>(['client', 'gateway', 'hetero'])(+ 'is behavior-neutral for %s: fires NO terminal side effects and emits no completion signal',+ async (runtimeType) => {+ const { get, store } = makeStore();++ await expect(+ lifecycle(runtimeType, get).onRunResumed(resumedEvent(runtimeType, 'top_level')),+ ).resolves.toBeUndefined();++ // The run is continuing, not completing β none of the terminal mutations+ // (op completion / unread / queue drain) nor the completion signal may fire.+ expect(store.completeOperation).not.toHaveBeenCalled();+ expect(store.failOperation).not.toHaveBeenCalled();+ expect(store.markTopicUnread).not.toHaveBeenCalled();+ expect(store.drainQueuedMessages).not.toHaveBeenCalled();+ expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).not.toHaveBeenCalled();+ },+ );++ it('is a no-op for a sub_agent resume (top-level only, like the other run-scoped hooks)', async () => {+ const { get, store } = makeStore();++ await expect(+ lifecycle('client', get, 'sub_agent').onRunResumed(resumedEvent('client', 'sub_agent')),+ ).resolves.toBeUndefined();++ expect(store.completeOperation).not.toHaveBeenCalled();+ expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).not.toHaveBeenCalled();+ });+});diff --git a/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.ts b/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.tsindex 45c2d9029fa..60111bc5fb0 100644--- a/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.ts+++ b/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.ts@@ -1,6 +1,7 @@import type { AgentState } from '@lobechat/agent-runtime';import { isDesktop } from '@lobechat/const';import type { ConversationContext, UIChatMessage } from '@lobechat/types';+import debug from 'debug';import { t } from 'i18next';import { getAgentStoreState } from '@/store/agent';@@ -22,10 +23,13 @@ import type {RunCompleteEvent,RunCompleteResult,RunParkedEvent,+ RunResumedEvent,RunScope,UserMessagePersistedEvent,} from './types';+const log = debug('lobe-store:run-lifecycle');+/*** Normalize the runtime/operation status into the cross-runtime* `client.runtime.complete` signal status.@@ -428,7 +432,23 @@ export const buildRunLifecycle = (get().completeOperation(operationId);}},- onRunResumed: NOOP,+ onRunResumed: async ({ operationId, resumedOperationId, runId }: RunResumedEvent) => {+ // A NEW operation resumes the SAME logical run after a park+ // (`waiting_for_human` β approve / reject / reject-continue / submit / skip).+ // This is the single broadcast seam for that transition: it fires NO terminal+ // side effects (the run is continuing, not completing) and mutates NO store+ // state β the resume operation is already started by its entry. Behavior-+ // neutral today; the structural marker is what `[6]` AgentRunner builds on to+ // thread a stable cross-operation `runId`. Top-level only, mirroring the other+ // run-scoped hooks (a parked sub-agent is not a user-facing resume).+ if (adapter.runScope === 'sub_agent') return;+ log(+ 'run resumed (parkedOp=%s β resumeOp=%s, runId=%s)',+ operationId,+ resumedOperationId,+ runId,+ );+ },onRunStarted: NOOP,onTerminalPersisted: NOOP,};