π€― 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): wire gateway and hetero into the shared run lifecycle (#16102)
Arvin Xude51d13d583d
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.tsindex 95786770a6d..d3a069f3a3f 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts@@ -6,6 +6,7 @@ import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/aiChat/actimport { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';import { createGatewayEventHandler } from '../gatewayEventHandler';+import { buildRunLifecycle } from '../runLifecycle/buildRunLifecycle';vi.mock('@/services/message', () => ({messageService: {@@ -32,10 +33,16 @@ function createMockStore() {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>,operations: {'op-1': {context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' },@@ -59,11 +66,24 @@ function createHandler(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: overrides?.assistantMessageId ?? 'msg-initial',- context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' } as any,+ 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',+ }),});}@@ -781,7 +801,9 @@ describe('createGatewayEventHandler', () => {'msg-initial',undefined,);- expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ // 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',{@@ -829,7 +851,8 @@ describe('createGatewayEventHandler', () => {'msg-step2',undefined,);- expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ expect(store.failOperation).toHaveBeenCalledWith('op-1', expect.anything());+ expect(store.completeOperation).not.toHaveBeenCalled();expect(messageService.updateMessageError).toHaveBeenCalledWith('msg-step2',{@@ -1076,25 +1099,22 @@ describe('createGatewayEventHandler', () => {// 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)', () => {- // CURRENT BEHAVIOR (gatewayEventHandler.ts ~622-624): the `error` event- // handler completes the operation but, UNLIKE `agent_runtime_end`- // (~552-557 which calls markTopicUnread when the operation has a- // context.agentId), the error path NEVER calls markTopicUnread.- // This is an intentional asymmetry to lock: an errored run does not get- // marked as an unread "completed" agent run. If a future refactor unifies- // the terminal paths, revisit whether errors SHOULD mark unread β- // changing this assertion is the signal that the contract moved.- it('error event completes the operation but does NOT call markTopicUnread (asymmetry vs agent_runtime_end)', async () => {+ // POST-LOBE-10379 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();- // completeOperation IS called on error.- expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ // 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 agent_runtime_end).+ // context.agentId (which WOULD trigger it on a clean agent_runtime_end).expect(store.markTopicUnread).not.toHaveBeenCalled();});@@ -1220,14 +1240,12 @@ describe('createGatewayEventHandler', () => {},);- // CURRENT BEHAVIOR: completeOperation runs once in the agent_runtime_end- // handler (gatewayEventHandler.ts:552) and again in gateway.ts- // onSessionComplete (gateway.ts:532) for the same operationId. The- // underlying reducer (operation/actions.ts:281-306) is idempotent: a- // second completeOperation on an already-'completed' op leaves status as- // 'completed' (it only refuses to overwrite a 'cancelled' status). This- // models the real reducer so the double-call is locked as a no-throw,- // no-flip stable terminal state.+ // POST-LOBE-10379: 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'@@ -1255,6 +1273,14 @@ describe('createGatewayEventHandler', () => {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).@@ -1296,6 +1322,14 @@ describe('createGatewayEventHandler', () => {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' }));diff --git a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.tsindex 002eee987ab..2c07f7280c3 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -3801,24 +3801,13 @@ describe('heterogeneousAgentExecutor DB persistence', () => {expect(mockSetBadgeCount).not.toHaveBeenCalled();});- // ββ 2. metadata-save failure isolation (CURRENT behavior, locked as-is) ββ- it('swallows an updateTopicMetadata REJECTION without surfacing an error to the caller', async () => {- // CHARACTERIZATION β locks ACTUAL current behavior, which DIFFERS from the- // intended acceptance criterion ("metadata failure must not block the- // drain"):- //- // const sessionInfo = await getSessionInfo(...).catch(() => undefined);- // if (sessionInfo?.agentSessionId && context.topicId)- // await updateTopicMetadata?.(...); // β NO .catch here- // if (!isAborted() && terminalEvent?.type !== 'error') { ...drain... }- //- // Because the `updateTopicMetadata` await is UNGUARDED, a rejection throws- // past the drain block into the function's outer try/catch. `completed` is- // already `true` (onComplete ran), so `catch { if (!completed) ... }` is a- // no-op: the executor resolves cleanly (no error escapes to the caller),- // BUT the queue drain is SKIPPED. The completion notification still fired- // (it runs inside onComplete, before this metadata await). Pinned here so- // the lifecycle refactor surfaces any change to this latent edge.+ // ββ 2. metadata-save failure isolation (POST-LOBE-10379: guarded) ββ+ it('a rejected updateTopicMetadata is swallowed and no longer blocks the queue drain', async () => {+ // POST-LOBE-10379 ("heteroSessionId δΏεβ¦ε€±θ΄₯δΈι»ζ core"): the metadata save+ // is now `.catch`-guarded, so a rejection is logged but does NOT throw past+ // the drain block. The executor still resolves cleanly (no error escapes),+ // the completion notification still fires, AND β unlike the old unguarded+ // behavior β the queue drain now proceeds.desktopFlag.value = true;const queued = [{@@ -3862,11 +3851,10 @@ describe('heterogeneousAgentExecutor DB persistence', () => {expect(store.updateTopicMetadata).toHaveBeenCalled();// ...and the rejection did NOT escape to the caller (executor resolved).expect(threw).toBe(false);- // The completion notification still fired (runs in onComplete, BEFORE the- // unguarded metadata await throws).+ // The completion notification still fired (afterRunComplete in onComplete).expect(mockSetBadgeCount).toHaveBeenCalledWith(1);- // Current behavior: the unguarded throw bypasses the drain β it is SKIPPED.- expect(store.drainQueuedMessages).not.toHaveBeenCalled();+ // POST-LOBE-10379: the guarded metadata save no longer bypasses the drain.+ expect(store.drainQueuedMessages).toHaveBeenCalled();});// ββ 3. queue-drain gating ββdiff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.tsindex b96371092fb..eafa4a18821 100644--- a/src/store/chat/slices/aiChat/actions/gateway.ts+++ b/src/store/chat/slices/aiChat/actions/gateway.ts@@ -21,6 +21,8 @@ import { useUserStore } from '@/store/user';import { settingsSelectors } from '@/store/user/selectors';import { createGatewayEventHandler, isCompletedRuntimeEnd } from './gatewayEventHandler';+import { buildRunLifecycle } from './runLifecycle/buildRunLifecycle';+import type { RunScope } from './runLifecycle/types';/*** When the agent runs against the local machine, resolve this desktop's@@ -89,12 +91,20 @@ export interface ConnectGatewayParams {onEvent?: (event: AgentStreamEvent) => void;/*** Called when the session completes (agent_runtime_end or session_complete).+ ** `succeeded` is true only for a clean `agent_runtime_end`; callers use it to* avoid stomping the `unread` status a background completion writes (the* completion's `markTopicUnread` and this terminal `active` write* partition the cases by `succeeded && !viewing`).+ *+ * `terminalReceived` is true when a terminal agent event (`agent_runtime_end` /+ * `error`) was processed β meaning the gateway event handler already completed+ * the op via the shared run lifecycle, so `onSessionComplete` is pure transport+ * cleanup. When false (terminal-missing: `session_complete` / `auth_failed` /+ * token-refresh failure arrived with no terminal agent event), the callback must+ * itself complete the op as the explicit fallback so it never sticks `running`.*/- onSessionComplete?: (info: { succeeded: boolean }) => void;+ onSessionComplete?: (info: { succeeded: boolean; terminalReceived: boolean }) => void;/*** The operation ID returned by execAgent*/@@ -180,7 +190,10 @@ export class GatewayActionImpl {const fireSessionComplete = () => {if (sessionCompleted) return;sessionCompleted = true;- onSessionComplete?.({ succeeded: terminalSucceeded });+ onSessionComplete?.({+ succeeded: terminalSucceeded,+ terminalReceived: receivedTerminalEvent,+ });};// Forward agent events to caller, and track terminal events@@ -552,13 +565,27 @@ export class GatewayActionImpl {// the same WS that gatewayConnections is keyed on.gatewayOperationId: result.operationId,operationId: gatewayOpId,+ // Shared run lifecycle: drives the terminal completeRun / afterRunComplete+ // for the gateway transport (op completion + unread + queue drain ++ // notification) at `agent_runtime_end` / `error`.+ runLifecycle: buildRunLifecycle(this.#get, {+ context: execContext,+ parentMessageId: result.assistantMessageId,+ parentMessageType: 'assistant',+ runId: gatewayOpId,+ runScope: (execContext.scope === 'sub_agent' ? 'sub_agent' : 'top_level') as RunScope,+ runtimeType: 'gateway',+ }),});this.#get().connectToGateway({gatewayUrl: agentGatewayUrl,onEvent: eventHandler,- onSessionComplete: ({ succeeded }) => {- this.#get().completeOperation(gatewayOpId);+ onSessionComplete: ({ succeeded, terminalReceived }) => {+ // The gateway event handler already completed the op via the shared run+ // lifecycle on `agent_runtime_end` / `error`. Only complete here as the+ // terminal-missing fallback so the op never sticks `running`.+ if (!terminalReceived) this.#get().completeOperation(gatewayOpId);if (result.topicId) {this.#get().internal_updateTopicLoading(result.topicId, false);// A clean completion the user isn't watching is owned by@@ -689,13 +716,24 @@ export class GatewayActionImpl {// the same WS that gatewayConnections is keyed on.gatewayOperationId: operationId,operationId: gatewayOpId,+ runLifecycle: buildRunLifecycle(this.#get, {+ context,+ parentMessageId: assistantMessageId,+ parentMessageType: 'assistant',+ runId: gatewayOpId,+ runScope: (context.scope === 'sub_agent' ? 'sub_agent' : 'top_level') as RunScope,+ runtimeType: 'gateway',+ }),});this.#get().connectToGateway({gatewayUrl: agentGatewayUrl,onEvent: eventHandler,- onSessionComplete: ({ succeeded }) => {- this.#get().completeOperation(gatewayOpId);+ onSessionComplete: ({ succeeded, terminalReceived }) => {+ // See executeGatewayAgent's onSessionComplete: the handler owns op+ // completion via the run lifecycle; complete here only as the+ // terminal-missing fallback.+ if (!terminalReceived) this.#get().completeOperation(gatewayOpId);this.#get().internal_updateTopicLoading(topicId, false);// See executeGatewayAgent's onSessionComplete: a clean background// completion is left to markTopicUnread (status: 'unread').diff --git a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.tsindex 5592a9ec4ad..6bf0183e242 100644--- a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts+++ b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts@@ -18,6 +18,10 @@ import { isRecord, pickNonEmptyString, toRecord } from '@lobechat/utils/object';import { messageService } from '@/services/message';import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/aiChat/actions/agentSignalBridge';+import type {+ AgentRunLifecycle,+ RunScope,+} from '@/store/chat/slices/aiChat/actions/runLifecycle/types';import type { ChatStore } from '@/store/chat/store';import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';@@ -300,10 +304,39 @@ export const createGatewayEventHandler = (*/gatewayOperationId?: string;operationId: string;+ /**+ * Shared run lifecycle for this run, assembled by the caller (gateway.ts).+ * Only the gateway transport supplies it β it drives the terminal lifecycle+ * (completeRun / afterRunComplete) here. hetero reuses this handler ONLY for+ * per-event message reconciliation; its executor owns the terminal lifecycle+ * (completeRun + notification + queue drain) in `onComplete`, so it omits this+ * and the handler must NOT double-complete or double-notify.+ *+ * Injected (not built here) to avoid statically importing `buildRunLifecycle`+ * β which pulls `@/store/chat/store` into this module's evaluation and breaks+ * the gateway.ts β gatewayEventHandler import cycle.+ */+ runLifecycle?: AgentRunLifecycle;+ /**+ * Which transport owns this handler. `gateway` (default) drives the terminal+ * run lifecycle here (completeRun / afterRunComplete). `hetero` reuses the+ * handler ONLY for per-event message reconciliation.+ */+ runtimeType?: 'gateway' | 'hetero';},) => {- const { context, operationId } = params;+ const { context, operationId, runLifecycle } = params;const gatewayOperationId = params.gatewayOperationId ?? operationId;+ const runtimeType = params.runtimeType ?? 'gateway';++ const runScope: RunScope = context.scope === 'sub_agent' ? 'sub_agent' : 'top_level';+ const lifecycleEventBase = {+ context,+ operationId,+ runId: operationId,+ runScope,+ runtimeType: 'gateway' as const,+ };// Dispatch context β ensures internal_dispatchMessage resolves the correct messageMapKeyconst dispatchContext = { operationId };@@ -646,20 +679,10 @@ export const createGatewayEventHandler = (});get().internal_toggleToolCallingStreaming(currentAssistantMessageId, undefined);endReasoningIfNeeded();- get().completeOperation(operationId);-- // Only a clean completion surfaces an unread badge β a mid-stream- // cancel ('interrupted') or deferred-tool park ('waiting_for_async_tool')- // must not. Those endings clear back to 'active' in onSessionComplete.- const completedOp = get().operations[operationId];- if (completedOp?.context.agentId && isCompletedRuntimeEnd(data?.reason)) {- get().markTopicUnread({- agentId: completedOp.context.agentId,- groupId: completedOp.context.groupId,- topicId: completedOp.context.topicId,- });- }+ // Reconcile messages FIRST so the terminal run lifecycle's notification+ // (afterRunComplete) can read the final assistant content from the store.+ //// Terminal step has no later step_start to carry SoT β server// pushes the canonical snapshot directly on this event. Fall back// to a DB refetch only if the snapshot is absent (older server@@ -694,6 +717,39 @@ export const createGatewayEventHandler = (} else {await fetchAndReplaceMessages(get, context).catch(console.error);}++ // Terminal run lifecycle. `isCompletedRuntimeEnd` is the clean-vs-not+ // gate (a mid-stream cancel 'interrupted' or deferred-tool park+ // 'waiting_for_async_tool' is NOT a clean completion):+ // β’ 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).+ // β’ 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 { requeued } = await runLifecycle.completeRun({+ ...lifecycleEventBase,+ status,+ });+ if (!requeued && status === 'completed') {+ await runLifecycle.afterRunComplete({ ...lifecycleEventBase, status });+ }+ } else {+ // hetero reuses this handler only for message reconciliation; its+ // executor owns completeRun + notification + queue drain. Complete the+ // op here so loading clears, and mark unread on a clean completion β+ // matching the legacy inline path the hetero executor still relies on.+ get().completeOperation(operationId);+ const completedOp = get().operations[operationId];+ if (completedOp?.context.agentId && isCompletedRuntimeEnd(data?.reason)) {+ get().markTopicUnread({+ agentId: completedOp.context.agentId,+ groupId: completedOp.context.groupId,+ topicId: completedOp.context.topicId,+ });+ }+ }});break;}@@ -725,7 +781,18 @@ export const createGatewayEventHandler = (get().internal_toggleToolCallingStreaming(currentAssistantMessageId, undefined);endReasoningIfNeeded();- get().completeOperation(operationId);++ // An errored run is a FAILED run, not a completed one (LOBE-10379+ // "errorβfail"). 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.+ if (runtimeType === 'gateway' && runLifecycle) {+ await runLifecycle.completeRun({ ...lifecycleEventBase, status: 'failed' });+ } else {+ get().completeOperation(operationId);+ }const updateResult = await messageService.updateMessageError(currentAssistantMessageId, messageError, {diff --git a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.tsindex 6fdf65b708d..448ea5e4364 100644--- a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts@@ -3,7 +3,6 @@ import type {AgentInterventionResponseData,AgentStreamEvent,} from '@lobechat/agent-gateway-client';-import { isDesktop } from '@lobechat/const';import {CLAUDE_CODE_CLI_INSTALL_DOCS_URL,CODEX_CLI_INSTALL_DOCS_URL,@@ -36,43 +35,17 @@ import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgenimport { messageService } from '@/services/message';import { threadService } from '@/services/thread';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 { mergeQueuedMessages, reconstructUploadFilesFromQueue } from '../../operation/types';import { createGatewayEventHandler } from './gatewayEventHandler';+import { buildRunLifecycle } from './runLifecycle/buildRunLifecycle';+import type { RunScope } from './runLifecycle/types';/** Mirrors `idGenerator('threads', 16)` on the server so sync-allocated ids have the same shape. */const generateThreadId = () => `thd_${createNanoId(16)()}`;-/**- * Fire desktop notification + dock badge when a CC/Codex/ACP run finishes.- * Notification only shows when the window is hidden (enforced in main); the- * badge is always set so a minimized/backgrounded app still signals completion.- */-const notifyCompletion = async (title: string, body: string, context: ConversationContext) => {- if (!isDesktop) return;- try {- const { desktopNotificationService } = await import('@/services/electron/desktopNotification');- const navigatePath = resolveNotificationNavigatePath({- agentId: context.agentId,- groupId: context.groupId,- topicId: context.topicId,- });- await Promise.allSettled([- desktopNotificationService.showNotification({- body,- navigate: navigatePath ? { path: navigatePath } : undefined,- title,- }),- desktopNotificationService.setBadgeCount(1),- ]);- } catch (error) {- console.error('[HeterogeneousAgent] Desktop notification failed:', error);- }-};-const CLI_AUTH_REQUIRED_PATTERNS = [/failed to authenticate/i,/invalid authentication credentials/i,@@ -374,11 +347,30 @@ export const executeHeterogeneousAgent = async (const adapterType = resolveAdapterType(heterogeneousProvider);- // Create the unified event handler (same one Gateway uses)+ // Shared run lifecycle (LOBE-10379). Hetero owns its terminal lifecycle here+ // (the desktop notification via `afterRunComplete`); the queue drain + op+ // completion stay in this executor's flow because the resume-session-id save+ // must run before the drain. `parentMessage*` are unused for non-client.+ const runScope: RunScope = context.scope === 'sub_agent' ? 'sub_agent' : 'top_level';+ const runLifecycle = buildRunLifecycle(get, {+ context,+ parentMessageId: assistantMessageId,+ parentMessageType: 'assistant',+ runId: operationId,+ runScope,+ runtimeType: 'hetero',+ });++ // Create the unified event handler (same one Gateway uses). `runtimeType:+ // 'hetero'` keeps the handler to per-event message reconciliation only β this+ // executor owns the terminal lifecycle (notification + queue drain), so the+ // handler must NOT double-notify or drain. It still completes the op + marks+ // unread on a clean terminal (the legacy reconciliation path this flow relies on).const eventHandler = createGatewayEventHandler(get, {assistantMessageId,context,operationId,+ runtimeType: 'hetero',});const persistTerminalError = async (messageError: ChatMessageError,@@ -1365,16 +1357,23 @@ export const executeHeterogeneousAgent = async (}// Signal completion to the user β dock badge + (window-hidden) notification.+ // Relocated into the shared `afterRunComplete` hook (LOBE-10379 "ιη₯η»δΈε°+ // afterRunComplete"): it does the same showNotification + setBadgeCount+ // fan-out for non-client runtimes. The body is resolved here from the+ // in-memory accumulated content (the store snapshot isn't durable yet).// Skip for aborted runs and for error terminations.if (!isAborted() && !isErrorTerminal) {const body = finalContent? markdownToTxt(finalContent): t('notification.finishChatGeneration', { ns: 'electron' });- notifyCompletion(- t('notification.finishChatGeneration', { ns: 'electron' }),- body,+ await runLifecycle.afterRunComplete({context,- );+ notification: { body },+ operationId,+ runId: operationId,+ runScope,+ runtimeType: 'hetero',+ });}},@@ -1439,10 +1438,17 @@ export const executeHeterogeneousAgent = async (.getSessionInfo(agentSessionId).catch(() => undefined);if (sessionInfo?.agentSessionId && context.topicId) {+ // Best-effort (LOBE-10379 "heteroSessionId δΏεβ¦ε€±θ΄₯δΈι»ζ core"): a rejected+ // metadata save must NOT throw past the queue drain below β guarding the+ // await here keeps the resume-id persistence from blocking the follow-up+ // send. The save still runs BEFORE the drain so the next turn's+ // `resolveHeteroResume` reads the just-finished session id.await updateTopicMetadata?.(context.topicId, {heteroSessionId: sessionInfo.agentSessionId,workingDirectory: workingDirectory ?? '',- });+ }).catch((err) =>+ console.error('[HeterogeneousAgent] Failed to persist resume session id:', err),+ );}// βββ Drain queued messages after a successful CC turn βββdiff --git a/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.test.ts b/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.test.tsindex 02157d1a7c7..647c9a9698e 100644--- a/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.test.ts+++ b/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.test.ts@@ -37,13 +37,17 @@ const makeStore = (afterCompletionCallbacks?: Array<() => void>) => {return { get: (() => store) as unknown as () => ChatStore, store };};-const lifecycle = (runtimeType: AgentRuntimeType, get: () => ChatStore) =>+const lifecycle = (+ runtimeType: AgentRuntimeType,+ get: () => ChatStore,+ runScope: 'sub_agent' | 'top_level' = 'top_level',+) =>buildRunLifecycle(get, {context: CONTEXT,parentMessageId: 'u1',parentMessageType: 'user',runId: OP,- runScope: 'top_level',+ runScope,runtimeType,});@@ -99,15 +103,29 @@ describe('buildRunLifecycle.completeRun β transport-driven disposition', () =>},);- it('gateway `status: cancelled` neither completes nor fails the op, and emits nothing', async () => {+ it('gateway `status: cancelled` completes the op (cancel reaches this boundary still running) but does NOT fail it or emit', async () => {const { get, store } = makeStore();await lifecycle('gateway', get).completeRun(completeEvent('gateway', { status: 'cancelled' }));- expect(store.completeOperation).not.toHaveBeenCalled();+ // Unlike the client (whose cancel path completes the op out of band),+ // gateway/hetero reach completeRun with the op still `running`, so cancelled+ // must move it to terminal here. No markUnread, no failOperation, no signal.+ expect(store.completeOperation).toHaveBeenCalledWith(OP);+ expect(store.markTopicUnread).not.toHaveBeenCalled();expect(store.failOperation).not.toHaveBeenCalled();expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).not.toHaveBeenCalled();});+ it('client `runtimeStatus: interrupted` does NOT complete the op (cancel already moved it out of band)', async () => {+ const { get, store } = makeStore();+ await lifecycle('client', get).completeRun(+ completeEvent('client', { runtimeStatus: 'interrupted' }),+ );++ expect(store.completeOperation).not.toHaveBeenCalled();+ expect(store.failOperation).not.toHaveBeenCalled();+ });+it('runs afterCompletion callbacks on every terminal regardless of transport', async () => {const cb = vi.fn();const { get } = makeStore([cb]);@@ -116,3 +134,43 @@ describe('buildRunLifecycle.completeRun β transport-driven disposition', () =>expect(cb).toHaveBeenCalledTimes(1);});});++describe('buildRunLifecycle β sub-agent runs skip top-level effects', () => {+ it('a sub_agent success completes the op but does NOT drain the parent input queue', async () => {+ const { get, store } = makeStore();+ // Even with a queued follow-up present, a nested sub-agent completion must+ // NOT drain it β the queue belongs to the parent run.+ store.drainQueuedMessages = vi.fn(() => [{ content: 'queued', id: 'q1' } as any]);++ const { requeued } = await lifecycle('gateway', get, 'sub_agent').completeRun(+ completeEvent('gateway', { runScope: 'sub_agent', status: 'completed' }),+ );++ expect(requeued).toBe(false);+ expect(store.drainQueuedMessages).not.toHaveBeenCalled();+ // The op still completes so its loading clears.+ expect(store.completeOperation).toHaveBeenCalledWith(OP);+ });++ it('a top_level success DOES drain the queue (contrast probe)', async () => {+ const { get, store } = makeStore();+ store.drainQueuedMessages = vi.fn(() => []);++ await lifecycle('gateway', get, 'top_level').completeRun(+ completeEvent('gateway', { status: 'completed' }),+ );++ expect(store.drainQueuedMessages).toHaveBeenCalled();+ });++ it('afterRunComplete is a no-op for a sub_agent run (no notification)', async () => {+ const { get } = makeStore();+ // Resolves without touching the desktop notification path (early return on+ // runScope === 'sub_agent', before the isDesktop / dynamic-import branch).+ await expect(+ lifecycle('gateway', get, 'sub_agent').afterRunComplete(+ completeEvent('gateway', { runScope: 'sub_agent', status: 'completed' }),+ ),+ ).resolves.toBeUndefined();+ });+});diff --git a/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.ts b/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.tsindex 0081843b3f8..3eb1be2af77 100644--- a/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.ts+++ b/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.ts@@ -7,7 +7,7 @@ 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 type { ChatStore } from '@/store/chat/store';import { resolveNotificationNavigatePath } from '@/store/chat/utils/desktopNotification';import { markdownToTxt } from '@/utils/markdownToTxt';@@ -52,10 +52,11 @@ type TerminalDisposition = 'cancelled' | 'failed' | 'success';* / 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.+ * `cancelled` completes the operation for gateway/hetero (their cancel reaches+ * this boundary with the op still `running`, so it must be moved to a terminal+ * state here) but NOT for the client (its cancel path already moved the op out+ * of band before reaching `completeRun`). `undefined` never completes β it means+ * the transport reached an unrecognized status and falls through untouched.*/const resolveTerminalDisposition = (event: Pick<RunCompleteEvent, 'runtimeStatus' | 'status'>,@@ -169,16 +170,27 @@ export const buildRunLifecycle = (return {afterUserMessagePersisted: NOOP,- afterRunComplete: async ({ operationId }: RunCompleteEvent) => {- // Desktop notification (only outside tool-calling mode). Relocated verbatim.+ afterRunComplete: async (event: RunCompleteEvent) => {+ // Desktop notification + dock badge. Single home for all three runtimes'+ // completion notification (LOBE-10379 "ιη₯ε»ιοΌη»δΈε° afterRunComplete").+ // Top-level-only: a nested sub-agent finishing is not a user-facing run+ // completion β the parent run is still going, so it must not fire a+ // "generation finished" notification / badge. See RunScope.+ if (adapter.runScope === 'sub_agent') return;if (!isDesktop) return;try {- const finalMessages = get().messagesMap[messageKey] || [];- const lastAssistant = finalMessages.findLast((m) => m.role === 'assistant');+ const { desktopNotificationService } =+ await import('@/services/electron/desktopNotification');+ const navigatePath = resolveNotificationNavigatePath({ agentId, groupId, topicId });+ const navigate = navigatePath ? { path: navigatePath } : undefined;- if (lastAssistant?.content && !lastAssistant?.tools) {- const { desktopNotificationService } =- await import('@/services/electron/desktopNotification');+ if (adapter.runtimeType === 'client') {+ // CLIENT: notify only OUTSIDE tool-calling mode; title + body derived+ // from the in-memory store. Relocated verbatim β no badge (preserves+ // the prior client behavior).+ const finalMessages = get().messagesMap[messageKey] || [];+ const lastAssistant = finalMessages.findLast((m) => m.role === 'assistant');+ if (!lastAssistant?.content || lastAssistant?.tools) return;let notificationTitle = t('notification.finishChatGeneration', { ns: 'electron' });if (topicId) {@@ -191,18 +203,43 @@ export const buildRunLifecycle = (if (agentMeta?.title) notificationTitle = agentMeta.title;}- const navigatePath = resolveNotificationNavigatePath({ agentId, groupId, topicId });-await desktopNotificationService.showNotification({body: markdownToTxt(lastAssistant.content),- navigate: navigatePath ? { path: navigatePath } : undefined,+ navigate,title: notificationTitle,});+ return;}++ // GATEWAY / HETERO: the run-complete title is the generic completion+ // string; the body is executor-resolved (hetero's `accContent`) when+ // supplied, else derived from the store's final assistant content+ // (gateway, after its terminal DB reconciliation). Dock badge is set so a+ // backgrounded app still signals completion. Mirrors the prior+ // `notifyCompletion` fan-out.+ const fallbackContent = (+ get().messagesMap?.[messageKey] ||+ get().dbMessagesMap?.[messageKey] ||+ []+ ).findLast((m) => m.role === 'assistant')?.content;+ const body =+ event.notification?.body ??+ (fallbackContent+ ? markdownToTxt(fallbackContent)+ : t('notification.finishChatGeneration', { ns: 'electron' }));+ await Promise.allSettled([+ desktopNotificationService.showNotification({+ body,+ navigate,+ title:+ event.notification?.title ??+ t('notification.finishChatGeneration', { ns: 'electron' }),+ }),+ desktopNotificationService.setBadgeCount?.(1),+ ]);} catch (error) {console.error('Desktop notification error:', error);}- void operationId;},beforeRunComplete: NOOP,completeRun: async (event: RunCompleteEvent): Promise<RunCompleteResult> => {@@ -241,7 +278,10 @@ 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 (disposition === 'success') {+ // Gated to TOP-LEVEL runs only: the input queue belongs to the parent+ // run, so a nested sub-agent completion must never drain it (it would+ // re-trigger the user's queued message mid-parent-run). See RunScope.+ if (disposition === 'success' && adapter.runScope !== 'sub_agent') {const remainingQueued = get().drainQueuedMessages(contextKey);if (remainingQueued.length > 0) {const merged = mergeQueuedMessages(remainingQueued);@@ -259,8 +299,12 @@ export const buildRunLifecycle = (: undefined;setTimeout(() => {- useChatStore- .getState()+ // Use the passed `get` (the live chat-store getter) rather than a+ // direct `useChatStore` import: in prod they resolve to the same+ // singleton sendMessage, and avoiding the value import keeps the chat+ // store out of this module's graph β so gateway.ts can statically+ // import buildRunLifecycle without re-entering the store mid-eval.+ get().sendMessage({context: execContext,editorData: merged.editorData,@@ -291,9 +335,18 @@ export const buildRunLifecycle = (});break;}- // `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`.+ case 'cancelled': {+ // Gateway / hetero reach this boundary with the op still `running`+ // (their interrupt ends the run segment server- / CLI-side), so the op+ // must be moved to terminal here. The client is exempt: its cancel+ // path already set the op to `cancelled` out of band, and+ // `completeOperation` deliberately preserves a `cancelled` status.+ if (adapter.runtimeType !== 'client') get().completeOperation(operationId);+ break;+ }+ // `undefined`: unrecognized terminal status β fall through untouched.+ // Parked states never reach `completeRun` β the executor routes them to+ // `onRunParked`.}emitComplete(operationId, runtimeStatus);diff --git a/src/store/chat/slices/aiChat/actions/runLifecycle/types.ts b/src/store/chat/slices/aiChat/actions/runLifecycle/types.tsindex a216b324a66..20872e83279 100644--- a/src/store/chat/slices/aiChat/actions/runLifecycle/types.ts+++ b/src/store/chat/slices/aiChat/actions/runLifecycle/types.ts@@ -58,6 +58,14 @@ export interface TerminalPersistedEvent extends RunLifecycleEventBase {export interface RunCompleteEvent extends RunLifecycleEventBase {assistantMessageId?: string;+ /**+ * Pre-resolved desktop-notification payload for transports whose final content+ * lives in executor memory rather than the store (hetero's `accContent`). When+ * present, {@link AgentRunLifecycle.afterRunComplete} shows it verbatim instead+ * of deriving the body from `messagesMap`. The client adapter omits it (it reads+ * the store); gateway/hetero supply it.+ */+ notification?: { body: string; title?: string };operationStatus?: OperationStatus;/*** Raw runtime terminal/parked status (client `AgentState['status']`), used to