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.

πŸ› fix(hetero): notify once when a heterogeneous run completes (#22641)

Arvin Xu77ed55f79f28
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
index fc20be90455..3f29e9b12ac 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
@@ -263,7 +263,7 @@ describe('HeterogeneousAgentService', () => {
buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'hi' }),
buildEvent('tool_start', 2, { parentMessageId: 'asst-1' }),
buildEvent('tool_result', 3, { toolCallId: 'tc-1' }),
- buildEvent('agent_runtime_end', 4, { reason: 'success' }),
+ buildEvent('agent_runtime_end', 4, { reason: 'interrupted' }),
];
await service.heteroIngest({
@@ -392,7 +392,7 @@ describe('HeterogeneousAgentService', () => {
const events: AgentStreamEvent[] = [
buildEvent('stream_start', 0, { assistantMessage: { id: 'asst-1' } }),
buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'hello' }),
- buildEvent('agent_runtime_end', 2, { reason: 'success' }),
+ buildEvent('agent_runtime_end', 2, { reason: 'interrupted' }),
];
await expect(
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/ingestRuntimeEnd.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/ingestRuntimeEnd.test.ts
new file mode 100644
index 00000000000..090fbc79094
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/ingestRuntimeEnd.test.ts
@@ -0,0 +1,101 @@
+// @vitest-environment node
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { describe, expect, it, vi } from 'vitest';
+
+import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';
+
+import { HeterogeneousAgentService } from '..';
+
+const buildEnd = (data: Record<string, unknown>): AgentStreamEvent => ({
+ data,
+ operationId: 'op-1',
+ stepIndex: 1,
+ timestamp: 1_700_000_000_000,
+ type: 'agent_runtime_end',
+});
+
+const createService = () => {
+ const publishStreamEvent = vi.fn(async () => 'ok');
+ const persistenceHandler = {
+ filterUnpublishedEvents: vi.fn((_operationId: string, events: AgentStreamEvent[]) => events),
+ finish: vi.fn(async () => undefined),
+ ingest: vi.fn(async () => undefined),
+ markEventPublished: vi.fn(),
+ publishData: vi.fn((_operationId: string, event: AgentStreamEvent) => event.data),
+ };
+ const service = new HeterogeneousAgentService({} as any, 'user-1', {
+ agentOperationModel: {
+ findById: vi.fn(async () => ({ metadata: {} })),
+ touchRunning: vi.fn(async () => true),
+ } as any,
+ persistenceHandler: persistenceHandler as any,
+ snapshotStore: null,
+ streamEventManager: { publishStreamEvent } as any,
+ topicModel: {
+ settleRunningOperation: vi.fn(async () => ({ status: 'settled' })),
+ updateMetadata: vi.fn(async () => undefined),
+ } as any,
+ });
+ return { persistenceHandler, publishStreamEvent, service };
+};
+
+const ingest = (service: HeterogeneousAgentService, event: AgentStreamEvent) =>
+ service.heteroIngest({
+ agentType: 'claude-code',
+ events: [event],
+ operationId: 'op-1',
+ topicId: 'tpc-1',
+ });
+
+/**
+ * The CLI's own end lands before heteroFinish clears the topic's running marker,
+ * so publishing it finishes the run for clients while the server still says it
+ * is running.
+ */
+describe('HeterogeneousAgentService.heteroIngest β€” in-stream agent_runtime_end', () => {
+ it.each([[{}], [{ reason: 'success' }], [{ reason: 'complete' }]])(
+ 'leaves a clean end %j for heteroFinish to publish',
+ async (data) => {
+ const { persistenceHandler, publishStreamEvent, service } = createService();
+ const event = buildEnd(data);
+
+ await ingest(service, event);
+
+ expect(persistenceHandler.ingest).toHaveBeenCalledOnce();
+ expect(publishStreamEvent).not.toHaveBeenCalled();
+ expect(persistenceHandler.markEventPublished).toHaveBeenCalledWith('op-1', event);
+ },
+ );
+
+ it.each(['interrupted', 'cancelled'])(
+ 'still publishes a %s end, which heteroFinish cannot report',
+ async (reason) => {
+ const { publishStreamEvent, service } = createService();
+
+ await ingest(service, buildEnd({ reason }));
+
+ expect(publishStreamEvent).toHaveBeenCalledWith(
+ 'op-1',
+ expect.objectContaining({ type: 'agent_runtime_end' }),
+ );
+ },
+ );
+
+ it('publishes exactly one end across a clean ingest and heteroFinish', async () => {
+ vi.spyOn(CompletionLifecycle.prototype, 'completeOperation').mockResolvedValue(
+ undefined as any,
+ );
+ const { publishStreamEvent, service } = createService();
+
+ await ingest(service, buildEnd({}));
+ await service.heteroFinish({
+ agentType: 'claude-code',
+ operationId: 'op-1',
+ result: 'success',
+ topicId: 'tpc-1',
+ });
+
+ expect(publishStreamEvent).toHaveBeenCalledOnce();
+ vi.restoreAllMocks();
+ });
+});
diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.ts
index 3deed7429a0..e9d5f5b8625 100644
--- a/apps/server/src/services/heterogeneousAgent/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/index.ts
@@ -97,6 +97,20 @@ export interface HeterogeneousFinishParams {
type HeterogeneousFinishError = NonNullable<HeterogeneousFinishParams['error']>;
+/**
+ * A producer's clean `agent_runtime_end` must stay off the stream: heteroFinish
+ * publishes the run's end after clearing the topic's running marker, and an
+ * earlier end lets a client reconnect on that marker and complete the run twice.
+ * A stop stays published because a CLI that exits 0 reports it to heteroFinish
+ * as `success`, so this event is the only signal that the user stopped the run.
+ */
+const isCleanRuntimeEnd = (event: AgentStreamEvent): boolean => {
+ if (event.type !== 'agent_runtime_end') return false;
+
+ const reason = (event.data as { reason?: string } | undefined)?.reason;
+ return !reason || reason === 'success' || reason === 'complete';
+};
+
/**
* Older or partially upgraded `lh hetero exec` producers can flatten an
* adapter-classified terminal error before calling `heteroFinish`. Reclassify
@@ -299,6 +313,10 @@ export class HeterogeneousAgentService {
);
}
for (const event of unpublished) {
+ if (isCleanRuntimeEnd(event)) {
+ this.persistenceHandler.markEventPublished(operationId, event);
+ continue;
+ }
// Each event already carries operationId; the wire shape matches
// gateway-driven runs, which also name the step's assistant row on
// `stream_start` (see `publishData`).
diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts
index 83112ae8df1..007302d9083 100644
--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts
@@ -419,6 +419,67 @@ describe('buildRunLifecycle.afterRunComplete β€” failed run notification', () =>
});
});
+describe('buildRunLifecycle.afterRunComplete β€” one notification per server operation', () => {
+ const RECONNECT_OP = 'op-reconnect';
+
+ // A hetero run's in-stream end reaches the primary handler before heteroFinish
+ // clears the marker, so a reconnect can attach under a new local operation and
+ // see the same server run end again.
+ const makeAttachedStore = (serverOperationId: string) => {
+ const { get, store } = makeStore();
+ const operations = store.operations as Record<string, any>;
+ operations[OP].metadata = { serverOperationId };
+ operations[RECONNECT_OP] = { ...operations[OP], id: RECONNECT_OP };
+ return get;
+ };
+
+ beforeEach(() => {
+ desktopNotificationMock.notifyDesktopAgentCompleted.mockClear();
+ desktopNotificationMock.notifyDesktopAgentFailed.mockClear();
+ });
+
+ it('announces a completion once when a reconnect handler ends the same server run', async () => {
+ const get = makeAttachedStore('server-op-completed');
+ const notification = { content: 'done' };
+
+ await lifecycle('gateway', get).afterRunComplete(
+ completeEvent('gateway', { notification, status: 'completed' }),
+ );
+ await lifecycle('gateway', get).afterRunComplete(
+ completeEvent('gateway', { notification, operationId: RECONNECT_OP, status: 'completed' }),
+ );
+
+ expect(desktopNotificationMock.notifyDesktopAgentCompleted).toHaveBeenCalledTimes(1);
+ });
+
+ it('announces a failure once when a reconnect handler ends the same server run', async () => {
+ const get = makeAttachedStore('server-op-failed');
+ const notification = { error: { message: 'boom' } as any };
+
+ await lifecycle('gateway', get).afterRunComplete(
+ completeEvent('gateway', { notification, status: 'failed' }),
+ );
+ await lifecycle('gateway', get).afterRunComplete(
+ completeEvent('gateway', { notification, operationId: RECONNECT_OP, status: 'failed' }),
+ );
+
+ expect(desktopNotificationMock.notifyDesktopAgentFailed).toHaveBeenCalledTimes(1);
+ });
+
+ it('still announces each distinct server run', async () => {
+ const notification = { content: 'done' };
+
+ await lifecycle('gateway', makeAttachedStore('server-op-first')).afterRunComplete(
+ completeEvent('gateway', { notification, status: 'completed' }),
+ );
+ await lifecycle('gateway', makeAttachedStore('server-op-second')).afterRunComplete(
+ completeEvent('gateway', { notification, status: 'completed' }),
+ );
+
+ expect(desktopNotificationMock.notifyDesktopAgentCompleted).toHaveBeenCalledTimes(2);
+ });
+});
+
describe('buildRunLifecycle.afterRunComplete β€” client desktop notification body', () => {
const KEY = messageMapKey(CONTEXT);
// parentMessageId for the run under test is 'u1' (see `lifecycle` helper), so
diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts
index f8c317e000c..bec6d42cee4 100644
--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts
@@ -37,6 +37,27 @@ import type {
const log = debug('lobe-store:run-lifecycle');
+const MAX_NOTIFIED_SERVER_OPERATIONS = 200;
+const notifiedServerOperationIds = new Set<string>();
+
+/**
+ * Claim the single desktop notification of a server run. One server run can
+ * reach this renderer through several local operations: a hetero run's in-stream
+ * end arrives before heteroFinish clears the topic marker, so a reconnect can
+ * attach and see that run end again. Local-only runs have no server id to claim.
+ */
+const claimServerRunNotification = (serverOperationId: string | undefined): boolean => {
+ if (!serverOperationId) return true;
+ if (notifiedServerOperationIds.has(serverOperationId)) return false;
+
+ notifiedServerOperationIds.add(serverOperationId);
+ if (notifiedServerOperationIds.size > MAX_NOTIFIED_SERVER_OPERATIONS) {
+ const [oldest] = notifiedServerOperationIds;
+ notifiedServerOperationIds.delete(oldest);
+ }
+ return true;
+};
+
/**
* Normalize the runtime/operation status into the cross-runtime
* `client.runtime.complete` signal status.
@@ -286,8 +307,10 @@ export const buildRunLifecycle = (
if (get().operations[event.operationId]?.metadata.terminalReconciled) return;
if (adapter.runScope === 'sub_agent') return;
+ const serverOperationId = get().operations[event.operationId]?.metadata.serverOperationId;
const disposition = resolveTerminalDisposition(event);
if (disposition === 'failed' && event.notification) {
+ if (!claimServerRunNotification(serverOperationId)) return;
await notifyDesktopAgentFailed(get, {
context: { agentId, groupId, topicId, workspaceSlug },
error: event.notification.error,
@@ -311,6 +334,7 @@ export const buildRunLifecycle = (
// completion β€” the parent run is still going, so it must not fire a
// "generation finished" notification / badge. See RunScope.
if (!isDesktop) return;
+ if (!claimServerRunNotification(serverOperationId)) return;
const notificationContext = { agentId, groupId, topicId, workspaceSlug };