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: clear gateway visible loading earlier (#16576)

YuTengjinga95381d9022a
diff --git a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
index 033236feb5c..ed282eb8b2e 100644
--- a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
@@ -5,6 +5,7 @@ import debug from 'debug';
import { type AgentOperationMetadata, type StepResult } from './AgentStateManager';
import { createAgentStateManager, createStreamEventManager } from './factory';
import { type IAgentStateManager, type IStreamEventManager } from './types';
+import { hasVisibleOutputEndPublished } from './visibleOutputEnd';
const log = debug('lobe-server:agent-runtime:coordinator');
@@ -179,7 +180,9 @@ export class AgentRuntimeCoordinator {
// Send a terminal event once the operation first enters a terminal state.
if (hasEnteredStreamEndState(previousState?.status, state.status)) {
const stepIndex = state.stepCount ?? previousState?.stepCount ?? 0;
- await this.publishVisibleOutputEnd(operationId, state, stepIndex);
+ if (!hasVisibleOutputEndPublished(state)) {
+ await this.publishVisibleOutputEnd(operationId, state, stepIndex);
+ }
await this.streamEventManager.publishAgentRuntimeEnd({
finalState: state,
operationId,
@@ -208,9 +211,14 @@ export class AgentRuntimeCoordinator {
// This ensures agent_runtime_end is sent after all step events.
if (hasEnteredStreamEndState(previousState?.status, stepResult.newState.status)) {
+ // Example: call_llm step 3 can early-publish visible_output_end, then
+ // finish step 4 enters done. Keep terminal stepIndex for end payloads,
+ // but suppress visible_output_end once the operation marker exists.
const stepIndex =
- stepResult.newState.stepCount ?? stepResult.stepIndex ?? previousState?.stepCount ?? 0;
- await this.publishVisibleOutputEnd(operationId, stepResult.newState, stepIndex);
+ stepResult.stepIndex ?? stepResult.newState.stepCount ?? previousState?.stepCount ?? 0;
+ if (!hasVisibleOutputEndPublished(stepResult.newState)) {
+ await this.publishVisibleOutputEnd(operationId, stepResult.newState, stepIndex);
+ }
await this.streamEventManager.publishAgentRuntimeEnd({
finalState: stepResult.newState,
operationId,
diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
index 466831e346c..91378daa3dd 100644
--- a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
@@ -70,7 +70,15 @@ export class GatewayStreamNotifier implements IStreamEventManager {
event: Omit<StreamEvent, 'operationId' | 'timestamp'>,
): Promise<string> {
const result = await this.inner.publishStreamEvent(operationId, event);
- this.pushEvent(operationId, { ...event, operationId, timestamp: Date.now() });
+ const gatewayEvent = { ...event, operationId, timestamp: Date.now() };
+ if (event.type === 'stream_end') {
+ // `visible_output_end` may be published immediately after `stream_end`.
+ // Await the Gateway push for this boundary so the client applies
+ // stream_end.finalContent before closing visible loading/reasoning.
+ await this.pushEvent(operationId, gatewayEvent);
+ } else {
+ void this.pushEvent(operationId, gatewayEvent);
+ }
return result;
}
@@ -80,7 +88,7 @@ export class GatewayStreamNotifier implements IStreamEventManager {
chunkData: StreamChunkData,
): Promise<string> {
const result = await this.inner.publishStreamChunk(operationId, stepIndex, chunkData);
- this.pushEvent(operationId, {
+ void this.pushEvent(operationId, {
data: chunkData,
operationId,
stepIndex,
@@ -107,7 +115,7 @@ export class GatewayStreamNotifier implements IStreamEventManager {
userId: initialState?.userId || 'unknown',
});
- this.pushEvent(operationId, {
+ void this.pushEvent(operationId, {
data: initialState,
operationId,
stepIndex: 0,
@@ -125,7 +133,7 @@ export class GatewayStreamNotifier implements IStreamEventManager {
const effectiveReasonDetail = reasonDetail || getDefaultReasonDetail(finalState, reason);
const errorType = finalState?.error?.type || finalState?.error?.errorType;
- this.pushEvent(operationId, {
+ void this.pushEvent(operationId, {
// Forward `uiMessages` to the gateway push channel so terminal-state
// clients consuming /push-event get the canonical UIChatMessage[]
// snapshot β€” the final step has no later step_start to carry a fresh
@@ -192,7 +200,7 @@ export class GatewayStreamNotifier implements IStreamEventManager {
// ─── Gateway HTTP helpers ───
- private pushEvent(operationId: string, event: Record<string, unknown>) {
+ private async pushEvent(operationId: string, event: Record<string, unknown>): Promise<void> {
// Mirror the Redis publisher's chokepoint β€” strip
// `finalState.messages` + tool-set fields off the gateway WS push
// payload too. The gateway forwards events verbatim to clients, and
@@ -201,10 +209,12 @@ export class GatewayStreamNotifier implements IStreamEventManager {
// crashed the xadd path.
const sanitizedEvent =
event.data === undefined ? event : { ...event, data: stripFinalStateInEventData(event.data) };
- this.httpPost('/api/operations/push-event', {
- event: sanitizedEvent,
- operationId,
- }).catch(() => {});
+ const pushes: Promise<void>[] = [
+ this.httpPost('/api/operations/push-event', {
+ event: sanitizedEvent,
+ operationId,
+ }),
+ ];
// Single-connection multiplexing: also deliver to the mirror op's channel so
// the event rides down that connection's WebSocket. The event payload keeps
@@ -212,21 +222,29 @@ export class GatewayStreamNotifier implements IStreamEventManager {
// back to the right member column. Only the delivery channel changes.
const mirrorTo = this.mirrorTargets.get(operationId);
if (mirrorTo) {
- this.mirrorPush(mirrorTo, sanitizedEvent);
+ pushes.push(this.mirrorPush(mirrorTo, sanitizedEvent));
+ await Promise.all(pushes);
return;
}
// Queue worker: target not in the in-process map. Resolve it from persisted
// metadata once, then mirror this (and future) events. Concurrent events for
// the same op share one resolution and fire their mirror pushes in order.
if (!this.mirrorResolved.has(operationId)) {
- void this.resolveMirror(operationId).then((target) => {
- if (target) this.mirrorPush(target, sanitizedEvent);
- });
+ pushes.push(
+ this.resolveMirror(operationId).then(async (target) => {
+ if (target) await this.mirrorPush(target, sanitizedEvent);
+ }),
+ );
}
+
+ await Promise.all(pushes);
}
- private mirrorPush(mirrorTo: string, event: Record<string, unknown>) {
- this.httpPost('/api/operations/push-event', { event, operationId: mirrorTo }).catch(() => {});
+ private mirrorPush(mirrorTo: string, event: Record<string, unknown>): Promise<void> {
+ return this.httpPost('/api/operations/push-event', {
+ event,
+ operationId: mirrorTo,
+ });
}
/**
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
index e06393887c9..415aeb15dee 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
import { AgentRuntimeCoordinator } from '../AgentRuntimeCoordinator';
import { createAgentStateManager, createStreamEventManager } from '../factory';
+import { VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY } from '../visibleOutputEnd';
// Mock factory module to avoid Redis/env access
vi.mock('../factory', () => ({
@@ -294,6 +295,93 @@ describe('AgentRuntimeCoordinator', () => {
});
});
+ it('does not republish visible_output_end when the step already published it', async () => {
+ const operationId = 'test-operation-id';
+ const stepResult = {
+ executionTime: 1000,
+ newState: {
+ metadata: { [VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY]: 5 },
+ status: 'done',
+ stepCount: 5,
+ },
+ stepIndex: 5,
+ };
+
+ mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 4 });
+
+ await coordinator.saveStepResult(operationId, stepResult as any);
+
+ expect(mockStreamManager.publishStreamEvent).not.toHaveBeenCalledWith(
+ operationId,
+ expect.objectContaining({ type: 'visible_output_end' }),
+ );
+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({
+ finalState: stepResult.newState,
+ operationId,
+ reason: 'done',
+ stepIndex: 5,
+ uiMessages: undefined,
+ });
+ });
+
+ it('does not republish visible_output_end when AgentRuntime.step advanced stepCount', async () => {
+ const operationId = 'test-operation-id';
+ const stepResult = {
+ executionTime: 1000,
+ newState: {
+ metadata: { [VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY]: 0 },
+ status: 'done',
+ stepCount: 1,
+ },
+ stepIndex: 0,
+ };
+
+ mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 0 });
+
+ await coordinator.saveStepResult(operationId, stepResult as any);
+
+ expect(mockStreamManager.publishStreamEvent).not.toHaveBeenCalledWith(
+ operationId,
+ expect.objectContaining({ type: 'visible_output_end' }),
+ );
+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({
+ finalState: stepResult.newState,
+ operationId,
+ reason: 'done',
+ stepIndex: 0,
+ uiMessages: undefined,
+ });
+ });
+
+ it('does not republish visible_output_end when a following finish step enters done', async () => {
+ const operationId = 'test-operation-id';
+ const stepResult = {
+ executionTime: 1000,
+ newState: {
+ metadata: { [VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY]: 3 },
+ status: 'done',
+ stepCount: 5,
+ },
+ stepIndex: 5,
+ };
+
+ mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 4 });
+
+ await coordinator.saveStepResult(operationId, stepResult as any);
+
+ expect(mockStreamManager.publishStreamEvent).not.toHaveBeenCalledWith(
+ operationId,
+ expect.objectContaining({ type: 'visible_output_end' }),
+ );
+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({
+ finalState: stepResult.newState,
+ operationId,
+ reason: 'done',
+ stepIndex: 5,
+ uiMessages: undefined,
+ });
+ });
+
it('should publish end event when status becomes error', async () => {
const operationId = 'test-operation-id';
const stepResult = {
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
index 025d7869445..4f50edd7309 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
@@ -79,6 +79,39 @@ describe('GatewayStreamNotifier', () => {
);
});
+ it('awaits stream_end gateway push before resolving', async () => {
+ let resolveFetch!: () => void;
+ mockFetch.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveFetch = () => resolve({ ok: true, text: () => Promise.resolve('') });
+ }),
+ );
+
+ const result = notifier.publishStreamEvent('op-1', {
+ data: { finalContent: 'final answer' },
+ stepIndex: 0,
+ type: 'stream_end' as const,
+ });
+ let resolved = false;
+ void result.then(() => {
+ resolved = true;
+ });
+
+ await Promise.resolve();
+
+ expect(mockFetch).toHaveBeenCalledWith(
+ `${gatewayUrl}/api/operations/push-event`,
+ expect.objectContaining({ method: 'POST' }),
+ );
+ expect(resolved).toBe(false);
+
+ resolveFetch();
+
+ await expect(result).resolves.toBe('publishStreamEvent-result');
+ expect(resolved).toBe(true);
+ });
+
it('still returns inner result even if gateway fails', async () => {
mockFetch.mockRejectedValueOnce(new Error('network error'));
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index 251306e3bda..ce3e6f50cec 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -7,6 +7,11 @@ import * as ContextEngineering from '@/server/modules/Mecha/ContextEngineering';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { createRuntimeExecutors, type RuntimeExecutorContext } from '../RuntimeExecutors';
+import type { StreamEvent } from '../StreamEventManager';
+import { VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY } from '../visibleOutputEnd';
+
+type PublishedStreamEvent = Omit<StreamEvent, 'operationId' | 'timestamp'>;
+type PublishStreamEventCall = [string, PublishedStreamEvent];
const mockCreateCompressionGroup = vi.fn();
const mockFinalizeCompression = vi.fn();
@@ -439,6 +444,108 @@ describe('RuntimeExecutors', () => {
);
});
+ it('publishes visible_output_end before persistence for no-tool final answers', async () => {
+ const executors = createRuntimeExecutors(ctx);
+ const state = createMockState();
+
+ const result = await executors.call_llm!(
+ {
+ payload: {
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'gpt-4',
+ provider: 'openai',
+ tools: [],
+ },
+ type: 'call_llm' as const,
+ },
+ state,
+ );
+
+ const calls = mockStreamManager.publishStreamEvent.mock.calls as PublishStreamEventCall[];
+ const streamEndIndex = calls.findIndex(([, event]) => event.type === 'stream_end');
+ const visibleEndIndex = calls.findIndex(([, event]) => event.type === 'visible_output_end');
+
+ expect(streamEndIndex).toBeGreaterThanOrEqual(0);
+ expect(visibleEndIndex).toBeGreaterThan(streamEndIndex);
+ expect(
+ mockStreamManager.publishStreamEvent.mock.invocationCallOrder[visibleEndIndex],
+ ).toBeLessThan(mockMessageModel.update.mock.invocationCallOrder[0]);
+ expect(result.newState.metadata).toMatchObject({
+ [VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY]: ctx.stepIndex,
+ });
+ });
+
+ it('does not publish early visible_output_end for tool-call steps', async () => {
+ const toolCallPayload = [
+ {
+ function: { arguments: '{}', name: 'search' },
+ id: 'call_1',
+ type: 'function',
+ },
+ ];
+ const mockChat = vi.fn().mockImplementation(async (_payload, options) => {
+ await options?.callback?.onToolsCalling?.({ toolsCalling: toolCallPayload });
+ return new Response('done');
+ });
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValueOnce({ chat: mockChat } as any);
+
+ const executors = createRuntimeExecutors(ctx);
+ const state = createMockState();
+ const result = await executors.call_llm!(
+ {
+ payload: {
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'gpt-4',
+ provider: 'openai',
+ tools: [],
+ },
+ type: 'call_llm' as const,
+ },
+ state,
+ );
+
+ expect(
+ (mockStreamManager.publishStreamEvent.mock.calls as PublishStreamEventCall[]).some(
+ ([, event]) => event.type === 'visible_output_end',
+ ),
+ ).toBe(false);
+ expect(
+ result.newState.metadata?.[VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY],
+ ).toBeUndefined();
+ });
+
+ it('does not publish early visible_output_end for injected multi-step agents', async () => {
+ const executors = createRuntimeExecutors({
+ ...ctx,
+ allowEarlyFinalAnswerVisibleOutputEnd: false,
+ });
+ const state = createMockState();
+
+ const result = await executors.call_llm!(
+ {
+ payload: {
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'gpt-4',
+ provider: 'openai',
+ tools: [],
+ },
+ // GraphAgent extraction calls can have tools: [] and still continue to the next node.
+ stepLabel: 'research:extract',
+ type: 'call_llm' as const,
+ },
+ state,
+ );
+
+ expect(
+ (mockStreamManager.publishStreamEvent.mock.calls as PublishStreamEventCall[]).some(
+ ([, event]) => event.type === 'visible_output_end',
+ ),
+ ).toBe(false);
+ expect(
+ result.newState.metadata?.[VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY],
+ ).toBeUndefined();
+ });
+
// preserveThinking gates whether reasoning is replayed into the next LLM
// payload (state.messages). The DB copy powers UI display after refresh and
// is always persisted regardless of the gate.
diff --git a/apps/server/src/modules/AgentRuntime/context.ts b/apps/server/src/modules/AgentRuntime/context.ts
index b1fa2bd0a1c..c8869e4267d 100644
--- a/apps/server/src/modules/AgentRuntime/context.ts
+++ b/apps/server/src/modules/AgentRuntime/context.ts
@@ -16,6 +16,13 @@ import { type IStreamEventManager } from './types';
export interface RuntimeExecutorContext {
agentConfig?: any;
+ /**
+ * Allows call_llm to publish visible_output_end immediately after a no-tool
+ * LLM stream_end. Only the default GeneralChatAgent treats no-tool llm_result
+ * as a final answer; injected multi-step agents such as GraphAgent can emit
+ * tools: [] for an intermediate graph node and continue to another node.
+ */
+ allowEarlyFinalAnswerVisibleOutputEnd?: boolean;
botContext?: unknown;
botPlatformContext?: BotPlatformContext;
discordContext?: any;
diff --git a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts b/apps/server/src/modules/AgentRuntime/executors/callLlm.ts
index ab736a38e10..41a8dcf8306 100644
--- a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts
+++ b/apps/server/src/modules/AgentRuntime/executors/callLlm.ts
@@ -99,6 +99,7 @@ import {
import { formatErrorEventData } from '../formatErrorEventData';
import { classifyLLMError } from '../llmErrorClassification';
import { createConversationParentMissingError } from '../messagePersistErrors';
+import { VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY } from '../visibleOutputEnd';
export const callLlm =
(ctx: RuntimeExecutorContext): InstructionExecutor =>
@@ -107,6 +108,7 @@ export const callLlm =
const llmPayload = payload as CallLLMPayload;
const { operationId, stepIndex, streamManager } = ctx;
const events: AgentEvent[] = [];
+ let visibleOutputEndPublishedStepIndex: number | undefined;
// Fallback to state's modelRuntimeConfig if not in payload
const model = llmPayload.model || state.modelRuntimeConfig?.model;
@@ -122,8 +124,7 @@ export const callLlm =
// was populated by a bug or a mid-run side effect. Plans absent on old /
// resumed operations fall back to the policy-only gate.
const devicePolicy = state.metadata?.deviceAccessPolicy as
- | { canUseDevice: boolean; reason: DeviceAccessReason }
- | undefined;
+ { canUseDevice: boolean; reason: DeviceAccessReason } | undefined;
const executionPlan = state.metadata?.executionPlan as ExecutionPlan | undefined;
const planAllowsDevice = !executionPlan || isDeviceCapablePlan(executionPlan);
const activeDeviceId =
@@ -490,8 +491,7 @@ export const callLlm =
const lobehubSkillAgentId = state.metadata?.agentId;
const lobehubSkillTopicId = state.metadata?.topicId;
const lobehubSkillAgentMeta = state.metadata?.agentConfig as
- | { description?: string | null; title?: string | null }
- | undefined;
+ { description?: string | null; title?: string | null } | undefined;
let lobehubSkillTopicTitle = '';
if (lobehubSkillTopicId && ctx.serverDB && ctx.userId) {
@@ -574,14 +574,12 @@ export const callLlm =
const credsResult = await marketService.market.creds.list();
const userCreds = (credsResult as any)?.data ?? [];
credsListStr = generateCredsList(
- userCreds.map(
- (cred: any): CredSummary => ({
- description: cred.description,
- key: cred.key,
- name: cred.name,
- type: cred.type,
- }),
- ),
+ userCreds.map((cred: any): CredSummary => ({
+ description: cred.description,
+ key: cred.key,
+ name: cred.name,
+ type: cred.type,
+ })),
);
log('Fetched %d creds for {{CREDS_LIST}} substitution', userCreds.length);
} catch (error) {
@@ -1438,6 +1436,29 @@ export const callLlm =
type: 'stream_end',
});
+ const canPublishEarlyFinalAnswerVisibleEnd =
+ ctx.allowEarlyFinalAnswerVisibleOutputEnd ?? true;
+ if (
+ canPublishEarlyFinalAnswerVisibleEnd &&
+ toolsCalling.length === 0 &&
+ tool_calls.length === 0
+ ) {
+ try {
+ // Example: a no-tool answer can publish stream_end, then spend
+ // several seconds in DB/Redis persistence before terminal done.
+ // Clear visible loading once no more text/tool output can appear.
+ await streamManager.publishStreamEvent(operationId, {
+ data: { reason: 'final_answer' },
+ stepIndex,
+ type: 'visible_output_end',
+ });
+ visibleOutputEndPublishedStepIndex = stepIndex;
+ } catch (error) {
+ // Terminal saveStepResult still publishes the same hint as a fallback.
+ console.error('Failed to publish visible_output_end:', error);
+ }
+ }
+
log('[%s:%d] call_llm completed', operationId, stepIndex);
// ===== 1. First save original usage to message.metadata =====
@@ -1554,9 +1575,14 @@ export const callLlm =
}
// Propagate stepLabel from instruction to state metadata for hook consumers
- if (stepLabel) {
- if (!newState.metadata) newState.metadata = {};
- newState.metadata._stepLabel = stepLabel;
+ if (stepLabel || visibleOutputEndPublishedStepIndex !== undefined) {
+ const stateMetadata = { ...newState.metadata };
+ if (stepLabel) stateMetadata._stepLabel = stepLabel;
+ if (visibleOutputEndPublishedStepIndex !== undefined) {
+ stateMetadata[VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY] =
+ visibleOutputEndPublishedStepIndex;
+ }
+ newState.metadata = stateMetadata;
}
// Record chat response attributes on the OTel span.
diff --git a/apps/server/src/modules/AgentRuntime/visibleOutputEnd.ts b/apps/server/src/modules/AgentRuntime/visibleOutputEnd.ts
new file mode 100644
index 00000000000..75b0d402515
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/visibleOutputEnd.ts
@@ -0,0 +1,9 @@
+import type { AgentState } from '@lobechat/agent-runtime';
+
+export const VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY =
+ 'visibleOutputEndPublishedStepIndex';
+
+export const hasVisibleOutputEndPublished = (state: AgentState): boolean =>
+ // Example: call_llm step 3 can publish visible_output_end, then finish step 4
+ // enters done. The marker is operation-wide, not tied to the terminal step.
+ typeof state.metadata?.[VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY] === 'number';
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index 136924ccdfe..34d30b8a006 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -761,8 +761,7 @@ export class AgentRuntimeService {
// Enrich invoke_agent span with agent identity now that state is loaded.
const stateAgentConfig = agentState.metadata?.agentConfig as
- | { description?: string | null; title?: string | null }
- | undefined;
+ { description?: string | null; title?: string | null } | undefined;
const stateModel =
agentState.modelRuntimeConfig?.model ?? agentState.metadata?.modelRuntimeConfig?.model;
const stateProvider =
@@ -2424,6 +2423,7 @@ export class AgentRuntimeService {
// Create streaming executor context
const executorContext: RuntimeExecutorContext = {
agentConfig: metadata?.agentConfig,
+ allowEarlyFinalAnswerVisibleOutputEnd: !this.agentFactory,
botContext: metadata?.botContext,
botPlatformContext: metadata?.botPlatformContext,
discordContext: metadata?.discordContext,
@@ -2479,8 +2479,7 @@ export class AgentRuntimeService {
activeDeviceId,
devicePlatform: msg.pluginState?.metadata?.devicePlatform as string | undefined,
deviceSystemInfo: msg.pluginState?.metadata?.deviceSystemInfo as
- | Record<string, string>
- | undefined,
+ Record<string, string> | undefined,
};
}
},
diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
index 256a9f8db0c..d0cd8408821 100644
--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
@@ -193,6 +193,28 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
);
});
+ it('disables early final visible output end for custom multi-step agents', async () => {
+ vi.mocked(createRuntimeExecutors).mockClear();
+ const service = new AgentRuntimeService({} as any, 'user-1', {
+ agentFactory: () => ({ runner: vi.fn() }) as any,
+ queueService: null,
+ });
+
+ await (service as any).createAgentRuntime({
+ metadata: {
+ agentConfig: {},
+ modelRuntimeConfig: { model: 'gpt-test', provider: 'lobehub' },
+ userId: 'user-1',
+ },
+ operationId: 'op-custom-agent',
+ stepIndex: 0,
+ });
+
+ expect(createRuntimeExecutors).toHaveBeenCalledWith(
+ expect.objectContaining({ allowEarlyFinalAnswerVisibleOutputEnd: false }),
+ );
+ });
+
it('should NOT skip step when operation status is "running"', async () => {
const service = createService();