Skip to content

🀯 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.

♻️ refactor(chat): extract client run-completion into buildRunLifecycle (#15854)

Arvin Xu5770ba67a8af
diff --git a/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.ts b/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.ts
new file mode 100644
index 00000000000..f92076f3e2f
--- /dev/null
+++ b/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.ts
@@ -0,0 +1,270 @@
+import type { AgentState } from '@lobechat/agent-runtime';
+import { isDesktop } from '@lobechat/const';
+import type { ConversationContext, UIChatMessage } from '@lobechat/types';
+import { t } from 'i18next';
+
+import { getAgentStoreState } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import type { AgentRuntimeType } from '@/store/chat/slices/aiChat/actions/agentDispatcher';
+import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/aiChat/actions/agentSignalBridge';
+import { type ChatStore, useChatStore } from '@/store/chat/store';
+import { resolveNotificationNavigatePath } from '@/store/chat/utils/desktopNotification';
+import { markdownToTxt } from '@/utils/markdownToTxt';
+
+import { messageMapKey } from '../../../../utils/messageMapKey';
+import { topicMapKey } from '../../../../utils/topicMapKey';
+import type { OperationStatus } from '../../../operation/types';
+import { mergeQueuedMessages, reconstructUploadFilesFromQueue } from '../../../operation/types';
+import type { AgentRunLifecycle, RunCompleteEvent, RunCompleteResult, RunScope } from './types';
+
+/**
+ * Normalize the runtime/operation status into the cross-runtime
+ * `client.runtime.complete` signal status. Relocated verbatim from
+ * `streamingExecutor` β€” kept identical for behavior preservation.
+ *
+ * NOTE (LOBE-10382): `waiting_for_human` is encoded as `cancelled` and
+ * `waiting_for_async_tool` falls through to `undefined`. Both are parked, not
+ * terminal β€” this mis-encoding is locked by characterization tests and fixed
+ * when the parked/resumed signal is unified.
+ */
+const normalizeClientRuntimeCompleteStatus = (
+ runtimeStatus: AgentState['status'] | undefined,
+ operationStatus?: OperationStatus,
+): 'cancelled' | 'completed' | 'failed' | undefined => {
+ if (operationStatus === 'cancelled') return 'cancelled';
+ if (operationStatus === 'failed') return 'failed';
+ if (runtimeStatus === 'waiting_for_human') return 'cancelled';
+ if (operationStatus === 'completed') return 'completed';
+ if (runtimeStatus === 'done') return 'completed';
+ if (runtimeStatus === 'error' || runtimeStatus === 'interrupted') return 'failed';
+ return undefined;
+};
+
+const findCompletionAssistantMessageId = (
+ messages: UIChatMessage[],
+ parentMessageId: string,
+ parentMessageType: 'user' | 'assistant' | 'tool',
+) => {
+ const messagesById = new Map(messages.map((message) => [message.id, message]));
+ const parentMessage = messagesById.get(parentMessageId);
+ const isDescendantOfParent = (message: UIChatMessage) => {
+ let currentParentId = message.parentId;
+ const visited = new Set<string>();
+
+ while (currentParentId && !visited.has(currentParentId)) {
+ if (currentParentId === parentMessageId) return true;
+ visited.add(currentParentId);
+ currentParentId = messagesById.get(currentParentId)?.parentId;
+ }
+
+ return false;
+ };
+
+ return (
+ messages.findLast((message) => message.role === 'assistant' && isDescendantOfParent(message))
+ ?.id ??
+ (parentMessageType === 'assistant' && parentMessage?.role === 'assistant'
+ ? parentMessage.id
+ : undefined)
+ );
+};
+
+/**
+ * Per-run context resolved at the dispatch seam (or, transitionally, inside the
+ * executor). Carries everything the lifecycle hooks need beyond the per-call
+ * event so they can be assembled ONCE and called at runtime boundaries.
+ */
+export interface RunAdapterContext {
+ context: ConversationContext;
+ parentMessageId: string;
+ parentMessageType: 'user' | 'assistant' | 'tool';
+ runId: string;
+ runScope: RunScope;
+ runtimeType: AgentRuntimeType;
+}
+
+const NOOP = async () => {};
+
+/**
+ * Assemble the store/UI run-lifecycle hooks for a single run.
+ *
+ * Phase 1 (LOBE-10378, behavior-preserving): the implementations are the CLIENT
+ * completion effects relocated verbatim from `streamingExecutor`, so wiring the
+ * client executor to these hooks keeps the characterization net green. The
+ * gateway/hetero adapters are wired in LOBE-10379, where the currently-missing
+ * effects (title / notification / queue on gateway) are folded in.
+ */
+export const buildRunLifecycle = (
+ get: () => ChatStore,
+ adapter: RunAdapterContext,
+): AgentRunLifecycle => {
+ const { context, parentMessageId, parentMessageType } = adapter;
+ const { agentId, topicId, threadId, groupId } = context;
+ const messageKey = messageMapKey(context);
+ const contextKey = messageKey;
+
+ const emitComplete = (operationId: string, runtimeStatus: AgentState['status'] | undefined) => {
+ const finalMessages = get().messagesMap[messageKey] || [];
+ const assistantMessageId =
+ findCompletionAssistantMessageId(finalMessages, parentMessageId, parentMessageType) ??
+ findCompletionAssistantMessageId(
+ get().dbMessagesMap[messageKey] || [],
+ parentMessageId,
+ parentMessageType,
+ );
+ const operationStatus = get().operations[operationId]?.status;
+
+ void emitClientAgentSignalSourceEvent({
+ payload: {
+ agentId,
+ ...(assistantMessageId ? { anchorMessageId: assistantMessageId } : {}),
+ assistantMessageId,
+ operationId,
+ status: normalizeClientRuntimeCompleteStatus(runtimeStatus, operationStatus),
+ threadId: threadId ?? undefined,
+ topicId: topicId ?? undefined,
+ ...(parentMessageType === 'user' ? { triggerMessageId: parentMessageId } : {}),
+ },
+ sourceId: `${operationId}:client:complete`,
+ sourceType: 'client.runtime.complete',
+ });
+ };
+
+ return {
+ afterUserMessagePersisted: NOOP,
+ afterRunComplete: async ({ operationId }: RunCompleteEvent) => {
+ // Desktop notification (only outside tool-calling mode). Relocated verbatim.
+ if (!isDesktop) return;
+ try {
+ const finalMessages = get().messagesMap[messageKey] || [];
+ const lastAssistant = finalMessages.findLast((m) => m.role === 'assistant');
+
+ if (lastAssistant?.content && !lastAssistant?.tools) {
+ const { desktopNotificationService } =
+ await import('@/services/electron/desktopNotification');
+
+ let notificationTitle = t('notification.finishChatGeneration', { ns: 'electron' });
+ if (topicId) {
+ const key = topicMapKey({ agentId, groupId });
+ const topicData = get().topicDataMap[key];
+ const topic = topicData?.items?.find((item) => item.id === topicId);
+ if (topic?.title) notificationTitle = topic.title;
+ } else {
+ const agentMeta = agentSelectors.getAgentMetaById(agentId)(getAgentStoreState());
+ if (agentMeta?.title) notificationTitle = agentMeta.title;
+ }
+
+ const navigatePath = resolveNotificationNavigatePath({ agentId, groupId, topicId });
+
+ await desktopNotificationService.showNotification({
+ body: markdownToTxt(lastAssistant.content),
+ navigate: navigatePath ? { path: navigatePath } : undefined,
+ title: notificationTitle,
+ });
+ }
+ } catch (error) {
+ console.error('Desktop notification error:', error);
+ }
+ void operationId;
+ },
+ beforeRunComplete: NOOP,
+ completeRun: async ({
+ operationId,
+ runtimeStatus,
+ }: RunCompleteEvent): Promise<RunCompleteResult> => {
+ // 1. afterCompletion callbacks β€” fire on ALL terminal states (tools that
+ // registered post-run actions: speak / broadcast / delegate).
+ const operation = get().operations[operationId];
+ const afterCompletionCallbacks = operation?.metadata?.runtimeHooks?.afterCompletionCallbacks;
+ if (afterCompletionCallbacks && afterCompletionCallbacks.length > 0) {
+ for (const callback of afterCompletionCallbacks) {
+ try {
+ await callback();
+ } catch (error) {
+ // Keep the original log prefix β€” characterization tests lock it (behavior-preserving).
+ console.error('[executeClientAgent] afterCompletion callback error:', error);
+ }
+ }
+ }
+
+ // 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') {
+ 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().markUnreadCompleted(completedOp.context.agentId, completedOp.context.topicId);
+ }
+
+ emitComplete(operationId, runtimeStatus);
+
+ const execContext = { ...context };
+ const mergedContent = merged.content;
+ const mergedFiles =
+ merged.filesPreview.length > 0
+ ? reconstructUploadFilesFromQueue(merged.filesPreview)
+ : merged.files.length > 0
+ ? (merged.files.map((id) => ({ id })) as any)
+ : undefined;
+
+ setTimeout(() => {
+ useChatStore
+ .getState()
+ .sendMessage({
+ context: execContext,
+ editorData: merged.editorData,
+ files: mergedFiles,
+ ...(merged.forceRuntime ? { forceRuntime: merged.forceRuntime } : {}),
+ message: mergedContent,
+ metadata: merged.metadata,
+ })
+ .catch((e: unknown) => {
+ console.error('[executeClientAgent] sendMessage for queued content failed:', e);
+ });
+ }, 100);
+
+ return { requeued: true };
+ }
+ }
+
+ // 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().markUnreadCompleted(completedOp.context.agentId, completedOp.context.topicId);
+ }
+ break;
+ }
+ case 'error': {
+ get().failOperation(operationId, {
+ type: 'runtime_error',
+ message: 'Agent runtime execution failed',
+ });
+ break;
+ }
+ case 'waiting_for_human': {
+ // Parked for human intervention: complete this op so the loading UI
+ // clears; a new operation runs when the user approves/rejects.
+ get().completeOperation(operationId);
+ break;
+ }
+ }
+
+ emitComplete(operationId, runtimeStatus);
+
+ return { requeued: false };
+ },
+ onRunError: NOOP,
+ onRunParked: NOOP,
+ onRunResumed: NOOP,
+ onRunStarted: NOOP,
+ onTerminalPersisted: NOOP,
+ };
+};
diff --git a/src/store/chat/slices/aiChat/actions/runLifecycle/types.ts b/src/store/chat/slices/aiChat/actions/runLifecycle/types.ts
new file mode 100644
index 00000000000..a216b324a66
--- /dev/null
+++ b/src/store/chat/slices/aiChat/actions/runLifecycle/types.ts
@@ -0,0 +1,123 @@
+import type { AgentState } from '@lobechat/agent-runtime';
+import type { ConversationContext } from '@lobechat/types';
+
+import type { AgentRuntimeType } from '@/store/chat/slices/aiChat/actions/agentDispatcher';
+import type { OperationStatus } from '@/store/chat/slices/operation/types';
+
+/**
+ * Whether a run is the user-facing top-level run or a nested sub-agent run.
+ * Top-level-only side effects (title generation, input-queue drain, desktop
+ * notification) are gated OFF for `sub_agent`.
+ */
+export type RunScope = 'sub_agent' | 'top_level';
+
+/** Terminal disposition, normalized across the three runtimes. */
+export type RunTerminalStatus = 'cancelled' | 'completed' | 'failed';
+
+/** The two non-terminal parked states a run can enter and later resume from. */
+export type RunParkedReason = 'waiting_for_async_tool' | 'waiting_for_human';
+
+/**
+ * Identity + scope of a single logical run.
+ *
+ * A run can span MULTIPLE operations: when it parks (`waiting_for_human` /
+ * `waiting_for_async_tool`) and the user approves / rejects / submits / skips, a
+ * NEW operation resumes the same logical run. Terminal side effects fire once per
+ * logical run β€” keyed by `runId` β€” not once per operation.
+ */
+export interface RunLifecycleContext {
+ context: ConversationContext;
+ runId: string;
+ runScope: RunScope;
+ runtimeType: AgentRuntimeType;
+}
+
+interface RunLifecycleEventBase extends RunLifecycleContext {
+ operationId: string;
+}
+
+export interface UserMessagePersistedEvent extends RunLifecycleEventBase {
+ isCreateNewTopic: boolean;
+ topicId?: string;
+}
+
+export type RunStartedEvent = RunLifecycleEventBase;
+
+export interface RunParkedEvent extends RunLifecycleEventBase {
+ reason: RunParkedReason;
+}
+
+export interface RunResumedEvent extends RunLifecycleEventBase {
+ /** The operationId of the new operation that resumes the parked run. */
+ resumedOperationId: string;
+}
+
+export interface TerminalPersistedEvent extends RunLifecycleEventBase {
+ assistantMessageId?: string;
+}
+
+export interface RunCompleteEvent extends RunLifecycleEventBase {
+ assistantMessageId?: string;
+ operationStatus?: OperationStatus;
+ /**
+ * Raw runtime terminal/parked status (client `AgentState['status']`), used to
+ * reproduce the exact per-status completion branch. Optional β€” gateway/hetero
+ * adapters that don't expose it rely on `status` instead.
+ */
+ runtimeStatus?: AgentState['status'];
+ /**
+ * Normalized cross-runtime terminal disposition. Optional: the client adapter
+ * drives completion off {@link runtimeStatus}; gateway/hetero adapters supply
+ * this instead.
+ */
+ status?: RunTerminalStatus;
+}
+
+/**
+ * Result of `completeRun`. `requeued` is true when the input-queue drain
+ * scheduled a follow-up `sendMessage` β€” the caller then SKIPS `afterRunComplete`
+ * (no desktop notification for a run that immediately continues), matching the
+ * current early-return behavior.
+ */
+export interface RunCompleteResult {
+ requeued: boolean;
+}
+
+export interface RunErrorEvent extends RunLifecycleEventBase {
+ error?: unknown;
+}
+
+/**
+ * Store/UI-layer, single-direction (broadcast) run lifecycle.
+ *
+ * Assembled ONCE per run at the dispatch seam (`buildRunLifecycle`, next to
+ * `selectRuntimeType`) and injected into whichever runtime adapter executes the
+ * run. Runtimes only CALL these hooks at their own boundaries; they no longer
+ * decide where title / signal / queue-drain / notification / metadata effects run.
+ *
+ * NOT to be confused with the runtime-internal, bidirectional, BLOCKING hooks in
+ * `@lobechat/agent-runtime` (`beforeStep` / `beforeToolCall` / `onComplete` …)
+ * that intercept execution and can mock/halt it. This layer is one-way and only
+ * reacts to a run's lifecycle β€” the two must not be conflated.
+ */
+export interface AgentRunLifecycle {
+ /** UI side effects after completion: desktop notification + dock badge. */
+ afterRunComplete: (event: RunCompleteEvent) => Promise<void>;
+ /** post-persist: topic title auto-generation (top-level, gated on the title rule). */
+ afterUserMessagePersisted: (event: UserMessagePersistedEvent) => Promise<void>;
+ beforeRunComplete: (event: RunCompleteEvent) => Promise<void>;
+ /**
+ * Core completion, in a fixed order across all three runtimes:
+ * afterCompletion callbacks β†’ completeOperation β†’ markUnread β†’ normalized
+ * `client.runtime.complete` signal β†’ queue drain (success terminal only).
+ * Returns whether a queued follow-up was scheduled (see {@link RunCompleteResult}).
+ */
+ completeRun: (event: RunCompleteEvent) => Promise<RunCompleteResult>;
+ onRunError: (event: RunErrorEvent) => Promise<void>;
+ /** Entered a parked state. Terminal effects MUST NOT fire here. */
+ onRunParked: (event: RunParkedEvent) => Promise<void>;
+ /** A new operation resumes the same logical run after a park. */
+ onRunResumed: (event: RunResumedEvent) => Promise<void>;
+ onRunStarted: (event: RunStartedEvent) => Promise<void>;
+ onTerminalPersisted: (event: TerminalPersistedEvent) => Promise<void>;
+}
diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
index 099b0fcaf09..fcea20ad1e5 100644
--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
@@ -21,7 +21,6 @@ import {
type UIChatMessage,
} from '@lobechat/types';
import debug from 'debug';
-import { t } from 'i18next';
import { createAgentToolsEngine } from '@/helpers/toolEngineering';
import { aiAgentService } from '@/services/aiAgent';
@@ -36,12 +35,8 @@ import { aiModelSelectors } from '@/store/aiInfra/selectors';
import { getAiInfraStoreState } from '@/store/aiInfra/store';
import { createAgentExecutors } from '@/store/chat/agents/createAgentExecutors';
import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/aiChat/actions/agentSignalBridge';
-import { type OperationStatus } from '@/store/chat/slices/operation/types';
-import { type ChatStore, useChatStore } from '@/store/chat/store';
-import {
- notifyDesktopHumanApprovalRequired,
- resolveNotificationNavigatePath,
-} from '@/store/chat/utils/desktopNotification';
+import { type ChatStore } from '@/store/chat/store';
+import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';
import { getElectronStoreState } from '@/store/electron';
import { getServerConfigStoreState, serverConfigSelectors } from '@/store/serverConfig';
import { getTaskStoreState } from '@/store/task';
@@ -49,17 +44,16 @@ import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-pag
import { type StoreSetter } from '@/store/types';
import { toolInterventionSelectors } from '@/store/user/selectors';
import { getUserStoreState } from '@/store/user/store';
-import { markdownToTxt } from '@/utils/markdownToTxt';
import { topicSelectors } from '../../../selectors';
import { messageMapKey } from '../../../utils/messageMapKey';
-import { topicMapKey } from '../../../utils/topicMapKey';
import {
selectActivatedSkillsFromMessages,
selectActivatedToolIdsFromMessages,
selectTodosFromMessages,
} from '../../message/selectors/dbMessage';
-import { mergeQueuedMessages, reconstructUploadFilesFromQueue } from '../../operation/types';
+import { buildRunLifecycle } from './runLifecycle/buildRunLifecycle';
+import type { RunScope } from './runLifecycle/types';
const log = debug('lobe-store:streaming-executor');
@@ -90,59 +84,6 @@ const getVisualMediaAvailability = (messages: UIChatMessage[]) => ({
hasVideos: messages.some((message) => message.role === 'user' && !!message.videoList?.length),
});
-/**
- * Normalizes AgentRuntime terminal status into client runtime completion status.
- *
- * Before:
- * - "done"
- * - "waiting_for_human"
- *
- * After:
- * - "completed"
- * - "cancelled"
- */
-const normalizeClientRuntimeCompleteStatus = (
- runtimeStatus: AgentState['status'],
- operationStatus?: OperationStatus,
-): 'cancelled' | 'completed' | 'failed' | undefined => {
- if (operationStatus === 'cancelled') return 'cancelled';
- if (operationStatus === 'failed') return 'failed';
- if (runtimeStatus === 'waiting_for_human') return 'cancelled';
- if (operationStatus === 'completed') return 'completed';
- if (runtimeStatus === 'done') return 'completed';
- if (runtimeStatus === 'error' || runtimeStatus === 'interrupted') return 'failed';
- return undefined;
-};
-
-const findCompletionAssistantMessageId = (
- messages: UIChatMessage[],
- parentMessageId: string,
- parentMessageType: 'user' | 'assistant' | 'tool',
-) => {
- const messagesById = new Map(messages.map((message) => [message.id, message]));
- const parentMessage = messagesById.get(parentMessageId);
- const isDescendantOfParent = (message: UIChatMessage) => {
- let currentParentId = message.parentId;
- const visited = new Set<string>();
-
- while (currentParentId && !visited.has(currentParentId)) {
- if (currentParentId === parentMessageId) return true;
- visited.add(currentParentId);
- currentParentId = messagesById.get(currentParentId)?.parentId;
- }
-
- return false;
- };
-
- return (
- messages.findLast((message) => message.role === 'assistant' && isDescendantOfParent(message))
- ?.id ??
- (parentMessageType === 'assistant' && parentMessage?.role === 'assistant'
- ? parentMessage.id
- : undefined)
- );
-};
-
/**
* Core streaming execution actions for AI chat
*/
@@ -645,33 +586,6 @@ export class StreamingExecutorActionImpl {
// Compute contextKey for message queue (per-context, not per-operation)
const contextKey = messageKey;
- const emitRuntimeCompleteSource = () => {
- const finalMessages = this.#get().messagesMap[messageKey] || [];
- const assistantMessageId =
- findCompletionAssistantMessageId(finalMessages, parentMessageId, parentMessageType) ??
- findCompletionAssistantMessageId(
- this.#get().dbMessagesMap[messageKey] || [],
- parentMessageId,
- parentMessageType,
- );
- const operationStatus = this.#get().operations[operationId]?.status;
-
- void emitClientAgentSignalSourceEvent({
- payload: {
- agentId,
- ...(assistantMessageId ? { anchorMessageId: assistantMessageId } : {}),
- assistantMessageId,
- operationId,
- status: normalizeClientRuntimeCompleteStatus(state.status, operationStatus),
- threadId: threadId ?? undefined,
- topicId: topicId ?? undefined,
- ...(parentMessageType === 'user' ? { triggerMessageId: parentMessageId } : {}),
- },
- sourceId: `${operationId}:client:complete`,
- sourceType: 'client.runtime.complete',
- });
- };
-
// Execute the agent runtime loop
let stepCount = 0;
while (state.status !== 'done' && state.status !== 'error') {
@@ -839,149 +753,32 @@ export class StreamingExecutorActionImpl {
stepCount,
);
- // Execute afterCompletion hooks before completing operation
- // These are registered by tools (e.g., speak/broadcast/delegate) that need to
- // trigger actions after the AgentRuntime finishes
- const operation = this.#get().operations[operationId];
- const afterCompletionCallbacks = operation?.metadata?.runtimeHooks?.afterCompletionCallbacks;
- if (afterCompletionCallbacks && afterCompletionCallbacks.length > 0) {
- log(
- '[executeClientAgent] Executing %d afterCompletion callbacks',
- afterCompletionCallbacks.length,
- );
-
- for (const callback of afterCompletionCallbacks) {
- try {
- await callback();
- } catch (error) {
- console.error('[executeClientAgent] afterCompletion callback error:', error);
- }
- }
-
- log('[executeClientAgent] afterCompletion callbacks executed');
- }
-
- // If completed successfully and queue has messages, drain and trigger new sendMessage.
- // Only drain on success β€” on error the queue is left intact so messages aren't lost.
- if (state.status === 'done') {
- const remainingQueued = this.#get().drainQueuedMessages(contextKey);
- if (remainingQueued.length > 0) {
- const merged = mergeQueuedMessages(remainingQueued);
- log(
- '[executeClientAgent] %d queued messages after completion, triggering new sendMessage',
- remainingQueued.length,
- );
-
- this.#get().completeOperation(operationId);
-
- const completedOp = this.#get().operations[operationId];
- if (completedOp?.context.agentId) {
- this.#get().markUnreadCompleted(completedOp.context.agentId, completedOp.context.topicId);
- }
-
- emitRuntimeCompleteSource();
-
- const execContext = { ...context };
- const mergedContent = merged.content;
- // Rebuild UploadFileItem-shaped objects from the queued file previews so
- // sendMessage can both pass file ids to the server AND construct
- // imageList/videoList for the optimistic temp message. Falls back to
- // id-only wrappers if no preview metadata was captured.
- const mergedFiles =
- merged.filesPreview.length > 0
- ? reconstructUploadFilesFromQueue(merged.filesPreview)
- : merged.files.length > 0
- ? (merged.files.map((id) => ({ id })) as any)
- : undefined;
-
- setTimeout(() => {
- useChatStore
- .getState()
- .sendMessage({
- context: execContext,
- editorData: merged.editorData,
- files: mergedFiles,
- ...(merged.forceRuntime ? { forceRuntime: merged.forceRuntime } : {}),
- message: mergedContent,
- metadata: merged.metadata,
- })
- .catch((e: unknown) => {
- console.error('[executeClientAgent] sendMessage for queued content failed:', e);
- });
- }, 100);
-
- return; // Skip the normal completion below
- }
- }
-
- // Complete operation based on final state
- switch (state.status) {
- case 'done': {
- this.#get().completeOperation(operationId);
- log('[executeClientAgent] Operation completed successfully');
-
- // Mark unread completion for background conversations
- const completedOp = this.#get().operations[operationId];
- if (completedOp?.context.agentId) {
- this.#get().markUnreadCompleted(completedOp.context.agentId, completedOp.context.topicId);
- }
- break;
- }
- case 'error': {
- this.#get().failOperation(operationId, {
- type: 'runtime_error',
- message: 'Agent runtime execution failed',
- });
- log('[executeClientAgent] Operation failed');
- break;
- }
- case 'waiting_for_human': {
- // When waiting for human intervention, complete the current operation
- // A new operation will be created when user approves/rejects
- this.#get().completeOperation(operationId);
- log('[executeClientAgent] Operation paused for human intervention');
- break;
- }
- }
-
- log('[executeClientAgent] completed');
- emitRuntimeCompleteSource();
-
- // Desktop notification (if not in tools calling mode)
- if (isDesktop) {
- try {
- const finalMessages = this.#get().messagesMap[messageKey] || [];
- const lastAssistant = finalMessages.findLast((m) => m.role === 'assistant');
-
- // Only show notification if there's content and no tools
- if (lastAssistant?.content && !lastAssistant?.tools) {
- const { desktopNotificationService } =
- await import('@/services/electron/desktopNotification');
-
- // Use topic title or agent title as notification title
- let notificationTitle = t('notification.finishChatGeneration', { ns: 'electron' });
- if (topicId) {
- const key = topicMapKey({ agentId, groupId });
- const topicData = this.#get().topicDataMap[key];
- const topic = topicData?.items?.find((item) => item.id === topicId);
- if (topic?.title) notificationTitle = topic.title;
- } else {
- const agentMeta = agentSelectors.getAgentMetaById(agentId)(getAgentStoreState());
- if (agentMeta?.title) notificationTitle = agentMeta.title;
- }
+ // Run-completion side effects are assembled once (LOBE-10378) and invoked at
+ // this boundary. The bodies are relocated verbatim into `buildRunLifecycle`,
+ // so the streamingExecutor characterization net stays green (behavior-preserving).
+ const runScope: RunScope = scope === 'sub_agent' ? 'sub_agent' : 'top_level';
+ const runLifecycle = buildRunLifecycle(this.#get, {
+ context,
+ parentMessageId,
+ parentMessageType,
+ runId: operationId,
+ runScope,
+ runtimeType: 'client',
+ });
+ const completeEvent = {
+ context,
+ operationId,
+ runId: operationId,
+ runScope,
+ runtimeStatus: state.status,
+ runtimeType: 'client' as const,
+ };
- const navigatePath = resolveNotificationNavigatePath({ agentId, groupId, topicId });
+ const { requeued } = await runLifecycle.completeRun(completeEvent);
+ // A queued follow-up sendMessage was scheduled β€” skip the post-run notification.
+ if (requeued) return;
- await desktopNotificationService.showNotification({
- body: markdownToTxt(lastAssistant.content),
- navigate: navigatePath ? { path: navigatePath } : undefined,
- title: notificationTitle,
- });
- }
- } catch (error) {
- console.error('Desktop notification error:', error);
- }
- }
+ await runLifecycle.afterRunComplete(completeEvent);
// Return usage and cost data for caller to use
return { cost: state.cost, model, provider: provider ?? undefined, usage: state.usage };