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(notification): stop completion pushes for background task/bot/eval runs (#18866)

Tsuki2bbc2fb68eb9
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
index c5c991ae783..eebde940719 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
@@ -1,4 +1,5 @@
import { isParkedStatus } from '@lobechat/agent-runtime';
+import { RequestTrigger } from '@lobechat/types';
import { deserializeParts } from '@lobechat/utils';
import { isRecord } from '@lobechat/utils/object';
import debug from 'debug';
@@ -39,6 +40,21 @@ const log = debug('lobe-server:completion-lifecycle');
export const isSuccessLikeCompletionReason = (reason: string): boolean =>
reason === 'done' || reason === 'max_steps' || reason === 'cost_limit';
+/**
+ * Triggers whose completion recalls the user with a push notification. Beyond
+ * plain chat: `Scheduled` is a user-deferred chat turn ("send this in 3
+ * hours"), and `Cron` is today stamped only by the rate-limit auto-resume of a
+ * user's own chat turn (see scheduledRunKinds) β€” both are exactly the "user
+ * walked away mid-conversation" case the recall exists for. Everything else
+ * (task runner, bots, evals, API, agent-signal self-iterations, …) is
+ * background work and stays silent.
+ */
+const USER_RECALLABLE_TRIGGERS = new Set<string>([
+ RequestTrigger.Chat,
+ RequestTrigger.Cron,
+ RequestTrigger.Scheduled,
+]);
+
/**
* A parked human-approval run is not safely published until its generic Review
* batch is durable. Unlike ordinary notification fanout, this error must reach
@@ -619,6 +635,68 @@ export class CompletionLifecycle {
};
}
+ /**
+ * The facts the recall gate needs. The trigger rides on `state.metadata` for
+ * in-process runs (the appContext spread); synthetic terminals
+ * ({@link buildStateFromInput}) have none, so fall back to the op row
+ * `recordStart` stamped β€” which also reveals `parentOperationId`, marking
+ * internal child runs (verifier/repair/evidence pass it without `isSubAgent`).
+ * `trigger: undefined` means neither source knows.
+ */
+ private async resolveRunRecallFacts(
+ operationId: string,
+ metadata: { trigger?: unknown } | undefined,
+ ): Promise<{ isChildRun: boolean; trigger: string | undefined }> {
+ if (typeof metadata?.trigger === 'string')
+ return { isChildRun: false, trigger: metadata.trigger };
+
+ try {
+ const operation = await this.agentOperationModel.findById(operationId);
+ return {
+ isChildRun: Boolean(operation?.parentOperationId),
+ trigger: operation?.trigger ?? undefined,
+ };
+ } catch (error) {
+ log('[%s] Failed to resolve run trigger from op row: %O', operationId, error);
+ return { isChildRun: false, trigger: undefined };
+ }
+ }
+
+ /**
+ * Push a completion recall β€” but only for runs the user is waiting on.
+ * Background executions (scheduled tasks, bots, evals, …) complete constantly
+ * and would spam the OS banner. An unknown trigger passes: human-approval
+ * chat continuations can reach here without one, and dropping a chat push is
+ * worse than a rare stray banner.
+ */
+ private async recallUserOnCompletion(
+ operationId: string,
+ event: { agentId?: string; duration?: number; lastAssistantContent?: string; topicId?: string },
+ metadata: { trigger?: unknown; userId?: string } | undefined,
+ ): Promise<void> {
+ const { isChildRun, trigger } = await this.resolveRunRecallFacts(operationId, metadata);
+ if (isChildRun) {
+ log('[%s] Skipping completion push for internal child run', operationId);
+ return;
+ }
+ if (trigger !== undefined && !USER_RECALLABLE_TRIGGERS.has(trigger)) {
+ log('[%s] Skipping completion push for non-interactive trigger %s', operationId, trigger);
+ return;
+ }
+
+ await notifyAgentRunCompleted({
+ agentId: event.agentId || undefined,
+ duration: event.duration,
+ lastAssistantContent: event.lastAssistantContent,
+ operationId,
+ topicId: event.topicId,
+ userId: metadata?.userId || this.userId,
+ // Personal runs leave this undefined β‡’ bare deep link; workspace
+ // runs carry the id so the business slot can slug-prefix the URL.
+ workspaceId: this.workspaceId,
+ });
+ }
+
/**
* Register the operation's Works: entity files edited this round
* (pptx/xlsx/docx/pdf, …) as `file` Works β€” one version per operation,
@@ -774,23 +852,15 @@ export class CompletionLifecycle {
// `@/business` slot; the default implementation is a no-op. Sub-agent /
// group-member completions are internal steps of a parent run, never a
// user-facing recall β€” in-group members carry `orchestrationRole: 'member'`
- // WITHOUT `isSubAgent` (see execAgentMember), so guard both.
+ // WITHOUT `isSubAgent` (see execAgentMember), so guard both. The
+ // remaining condition β€” only interactive chat runs recall the user β€”
+ // lives in recallUserOnCompletion.
if (
isSuccessLikeCompletionReason(reason) &&
metadata?.isSubAgent !== true &&
metadata?.orchestrationRole !== 'member'
) {
- void notifyAgentRunCompleted({
- agentId: event.agentId || undefined,
- duration: event.duration,
- lastAssistantContent: event.lastAssistantContent,
- operationId,
- topicId: event.topicId,
- userId: metadata?.userId || this.userId,
- // Personal runs leave this undefined β‡’ bare deep link; workspace
- // runs carry the id so the business slot can slug-prefix the URL.
- workspaceId: this.workspaceId,
- }).catch((error) =>
+ void this.recallUserOnCompletion(operationId, event, metadata).catch((error) =>
log('[%s] Completion notification failed (non-fatal): %O', operationId, error),
);
}
diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
index 75e3161548c..6ef7f010ec8 100644
--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment node
import { type Message, parse } from '@lobechat/conversation-flow';
-import { ChatErrorType } from '@lobechat/types';
+import { ChatErrorType, RequestTrigger } from '@lobechat/types';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { NotifyAgentInterventionRequiredParams } from '@/business/server/agent-run/agentInterventionReview';
@@ -693,20 +693,23 @@ describe('CompletionLifecycle.dispatchHooks β€” completion notification', () =>
vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
vi.spyOn(hookDispatcher, 'unregister').mockImplementation(() => {});
vi.spyOn(verifyServices, 'runVerifyOnCompletion').mockResolvedValue(undefined);
+ // The recall gate falls back to the op row when metadata carries no trigger.
+ (lifecycle as any).agentOperationModel = { findById: vi.fn(async () => null) };
};
+ const buildDoneState = (metadata: Record<string, unknown> = {}) => ({
+ createdAt: new Date(Date.now() - 90_000).toISOString(),
+ messages: [{ content: 'final reply', role: 'assistant' }],
+ metadata: { _hooks: [], agentId: 'agt_1', topicId: 'tpc_1', ...metadata },
+ status: 'done',
+ });
+
it('notifies with fields mapped from the lifecycle event on a done completion', async () => {
const lifecycle = buildLifecycle();
stubSideEffects(lifecycle);
- const createdAt = new Date(Date.now() - 90_000).toISOString();
- const doneState = {
- createdAt,
- messages: [{ content: 'final reply', role: 'assistant' }],
- metadata: { _hooks: [], agentId: 'agt_1', topicId: 'tpc_1', userId: 'user-2' },
- status: 'done',
- };
- await lifecycle.dispatchHooks('op-1', doneState, 'done');
+ await lifecycle.dispatchHooks('op-1', buildDoneState({ userId: 'user-2' }), 'done');
+ await flushMicrotasks();
expect(mockNotifyAgentRunCompleted).toHaveBeenCalledTimes(1);
expect(mockNotifyAgentRunCompleted).toHaveBeenCalledWith(
@@ -727,28 +730,76 @@ describe('CompletionLifecycle.dispatchHooks β€” completion notification', () =>
const lifecycle = new CompletionLifecycle({} as any, 'user-1', 'ws_1');
stubSideEffects(lifecycle);
- const doneState = {
- createdAt: new Date(Date.now() - 90_000).toISOString(),
- messages: [{ content: 'final reply', role: 'assistant' }],
- metadata: { _hooks: [], agentId: 'agt_1', topicId: 'tpc_1', userId: 'user-2' },
- status: 'done',
- };
- await lifecycle.dispatchHooks('op-1', doneState, 'done');
+ await lifecycle.dispatchHooks('op-1', buildDoneState({ userId: 'user-2' }), 'done');
+ await flushMicrotasks();
expect(mockNotifyAgentRunCompleted).toHaveBeenCalledWith(
expect.objectContaining({ workspaceId: 'ws_1' }),
);
});
- it('does not notify for sub-agent completions', async () => {
+ // 'task' is TopicTrigger.RunTask (the task-runner funnel), not a RequestTrigger member.
+ it.each(['task', RequestTrigger.Bot, RequestTrigger.Eval, RequestTrigger.Api])(
+ 'does not notify for background %s-triggered completions',
+ async (trigger) => {
+ const lifecycle = buildLifecycle();
+ stubSideEffects(lifecycle);
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState({ trigger }), 'done');
+ await flushMicrotasks();
+
+ expect(mockNotifyAgentRunCompleted).not.toHaveBeenCalled();
+ },
+ );
+
+ // Scheduled = a user-deferred chat turn; Cron = the rate-limit auto-resume of
+ // a user's chat turn. Both are "user walked away" runs the recall exists for.
+ it.each([RequestTrigger.Chat, RequestTrigger.Scheduled, RequestTrigger.Cron])(
+ 'notifies for a user-recallable %s-triggered completion',
+ async (trigger) => {
+ const lifecycle = buildLifecycle();
+ stubSideEffects(lifecycle);
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState({ trigger }), 'done');
+ await flushMicrotasks();
+
+ expect(mockNotifyAgentRunCompleted).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it('falls back to the op row trigger when metadata carries none (synthetic hetero path)', async () => {
const lifecycle = buildLifecycle();
stubSideEffects(lifecycle);
+ (lifecycle as any).agentOperationModel = {
+ findById: vi.fn(async () => ({ trigger: RequestTrigger.Bot })),
+ };
+
+ // heteroFinish/agentNotify build metadata via buildStateFromInput β€” no trigger.
+ await lifecycle.dispatchHooks('op-1', buildDoneState(), 'done');
+ await flushMicrotasks();
- const doneState = {
- metadata: { _hooks: [], agentId: 'agt_1', isSubAgent: true, topicId: 'tpc_1' },
- status: 'done',
+ expect(mockNotifyAgentRunCompleted).not.toHaveBeenCalled();
+ });
+
+ it('does not notify for internal child runs (verifier/repair pass parentOperationId only)', async () => {
+ const lifecycle = buildLifecycle();
+ stubSideEffects(lifecycle);
+ (lifecycle as any).agentOperationModel = {
+ findById: vi.fn(async () => ({ parentOperationId: 'op-parent', trigger: null })),
};
- await lifecycle.dispatchHooks('op-1', doneState, 'done');
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState(), 'done');
+ await flushMicrotasks();
+
+ expect(mockNotifyAgentRunCompleted).not.toHaveBeenCalled();
+ });
+
+ it('does not notify for sub-agent completions', async () => {
+ const lifecycle = buildLifecycle();
+ stubSideEffects(lifecycle);
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState({ isSubAgent: true }), 'done');
+ await flushMicrotasks();
expect(mockNotifyAgentRunCompleted).not.toHaveBeenCalled();
});
@@ -759,11 +810,8 @@ describe('CompletionLifecycle.dispatchHooks β€” completion notification', () =>
// execAgentMember stamps in-group members with orchestrationRole: 'member'
// but NOT isSubAgent β€” they are internal steps of the supervisor run.
- const doneState = {
- metadata: { _hooks: [], agentId: 'agt_1', orchestrationRole: 'member', topicId: 'tpc_1' },
- status: 'done',
- };
- await lifecycle.dispatchHooks('op-1', doneState, 'done');
+ await lifecycle.dispatchHooks('op-1', buildDoneState({ orchestrationRole: 'member' }), 'done');
+ await flushMicrotasks();
expect(mockNotifyAgentRunCompleted).not.toHaveBeenCalled();
});
@@ -785,13 +833,8 @@ describe('CompletionLifecycle.dispatchHooks β€” completion notification', () =>
const lifecycle = buildLifecycle();
stubSideEffects(lifecycle);
- const doneState = {
- createdAt: new Date(Date.now() - 90_000).toISOString(),
- messages: [{ content: 'final reply', role: 'assistant' }],
- metadata: { _hooks: [], agentId: 'agt_1', topicId: 'tpc_1' },
- status: 'done',
- };
- await lifecycle.dispatchHooks('op-1', doneState, reason);
+ await lifecycle.dispatchHooks('op-1', buildDoneState(), reason);
+ await flushMicrotasks();
expect(mockNotifyAgentRunCompleted).toHaveBeenCalledTimes(1);
},