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 loading tail (#16518)

YuTengjing74c9fa4c36ec
diff --git a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
index 71a7afbc336..033236feb5c 100644
--- a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
@@ -147,6 +147,25 @@ export class AgentRuntimeCoordinator {
}
}
+ private async publishVisibleOutputEnd(
+ operationId: string,
+ state: AgentState,
+ stepIndex: number,
+ ): Promise<void> {
+ try {
+ await this.streamEventManager.publishStreamEvent(operationId, {
+ data: { reason: state.status },
+ stepIndex,
+ type: 'visible_output_end',
+ });
+ } catch (error) {
+ // Example: a transient Redis write failure may drop the early UI hint.
+ // Keep publishing agent_runtime_end because it is the authoritative
+ // terminal event that drains queues and reconciles final state.
+ console.error('Failed to publish visible_output_end:', error);
+ }
+ }
+
/**
* Save Agent state and handle corresponding events
*/
@@ -159,11 +178,13 @@ 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);
await this.streamEventManager.publishAgentRuntimeEnd({
finalState: state,
operationId,
reason: state.status,
- stepIndex: state.stepCount ?? previousState?.stepCount ?? 0,
+ stepIndex,
uiMessages: await this.resolveUiMessages(state),
});
log('[%s] Agent runtime reached terminal state: %s', operationId, state.status);
@@ -187,12 +208,14 @@ export class AgentRuntimeCoordinator {
// This ensures agent_runtime_end is sent after all step events.
if (hasEnteredStreamEndState(previousState?.status, stepResult.newState.status)) {
+ const stepIndex =
+ stepResult.newState.stepCount ?? stepResult.stepIndex ?? previousState?.stepCount ?? 0;
+ await this.publishVisibleOutputEnd(operationId, stepResult.newState, stepIndex);
await this.streamEventManager.publishAgentRuntimeEnd({
finalState: stepResult.newState,
operationId,
reason: stepResult.newState.status,
- stepIndex:
- stepResult.newState.stepCount ?? stepResult.stepIndex ?? previousState?.stepCount ?? 0,
+ stepIndex,
uiMessages: await this.resolveUiMessages(stepResult.newState),
});
log(
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
index a2aae2a9f87..e06393887c9 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
@@ -104,6 +104,31 @@ describe('AgentRuntimeCoordinator', () => {
});
});
+ it('should still publish end event when visible output event publish fails', async () => {
+ const operationId = 'test-operation-id';
+ const previousState = { status: 'running', stepCount: 3 };
+ const newState = { status: 'done', stepCount: 5 };
+ const error = new Error('redis down');
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ mockStateManager.loadAgentState.mockResolvedValue(previousState);
+ mockStreamManager.publishStreamEvent.mockRejectedValueOnce(error);
+
+ try {
+ await coordinator.saveAgentState(operationId, newState as any);
+ } finally {
+ consoleError.mockRestore();
+ }
+
+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({
+ finalState: newState,
+ operationId,
+ reason: 'done',
+ stepIndex: newState.stepCount,
+ uiMessages: undefined,
+ });
+ });
+
it('should publish end event when status changes to error', async () => {
const operationId = 'test-operation-id';
const previousState = { status: 'running', stepCount: 3 };
@@ -241,6 +266,34 @@ describe('AgentRuntimeCoordinator', () => {
});
});
+ it('should still publish step-result end event when visible output event publish fails', async () => {
+ const operationId = 'test-operation-id';
+ const stepResult = {
+ executionTime: 1000,
+ newState: { status: 'done', stepCount: 5 },
+ stepIndex: 5,
+ };
+ const error = new Error('redis down');
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 4 });
+ mockStreamManager.publishStreamEvent.mockRejectedValueOnce(error);
+
+ try {
+ await coordinator.saveStepResult(operationId, stepResult as any);
+ } finally {
+ consoleError.mockRestore();
+ }
+
+ 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 = {
@@ -439,6 +492,41 @@ describe('AgentRuntimeCoordinator', () => {
// when a resolver is wired so the client can use the pushed payload as
// Source of Truth instead of refetching from DB.
describe('uiMessagesResolver on agent_runtime_end', () => {
+ it('publishes visible_output_end before waiting for the terminal uiMessages resolver', async () => {
+ let resolveUiMessages!: (messages: any[]) => void;
+ const resolver = vi.fn(
+ () =>
+ new Promise<any[]>((resolve) => {
+ resolveUiMessages = resolve;
+ }),
+ );
+ const coordinatorWithResolver = new AgentRuntimeCoordinator({
+ stateManager: mockStateManager,
+ streamEventManager: mockStreamManager,
+ uiMessagesResolver: resolver,
+ });
+
+ const previousState = { status: 'running', stepCount: 3 };
+ const newState = { status: 'done', stepCount: 5 };
+ mockStateManager.loadAgentState.mockResolvedValue(previousState);
+
+ const savePromise = coordinatorWithResolver.saveAgentState('op-1', newState as any);
+
+ await vi.waitFor(() => {
+ expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith('op-1', {
+ data: { reason: 'done' },
+ stepIndex: 5,
+ type: 'visible_output_end',
+ });
+ });
+ expect(mockStreamManager.publishAgentRuntimeEnd).not.toHaveBeenCalled();
+
+ resolveUiMessages([{ id: 'msg_1', role: 'assistant' }]);
+ await savePromise;
+
+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalled();
+ });
+
it('passes resolver result through saveAgentState terminal publish', async () => {
const uiMessages = [{ id: 'msg_1', role: 'user' }] as any[];
const resolver = vi.fn().mockResolvedValue(uiMessages);
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts
index 0f0388606ce..da4844195de 100644
--- a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts
@@ -73,6 +73,8 @@ describe('aiAgentRouter.heteroIngest / heteroFinish', () => {
const events = [
buildEvent('stream_start', 0),
buildEvent('stream_chunk', 1),
+ buildEvent('stream_end', 2),
+ buildEvent('visible_output_end', 2),
buildEvent('agent_runtime_end', 2),
];
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index 312a00003b0..22b53fdc18b 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -364,6 +364,7 @@ const AgentStreamEventSchema = z.object({
'stream_start',
'stream_chunk',
'stream_end',
+ 'visible_output_end',
'stream_retry',
'tool_start',
'tool_end',
diff --git a/eslint-suppressions.json b/eslint-suppressions.json
index e002e8bbd32..01c7ffb8579 100644
--- a/eslint-suppressions.json
+++ b/eslint-suppressions.json
@@ -84,11 +84,6 @@
"count": 1
}
},
- "src/components/SplitButton/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"src/features/AgentDocumentsExplorer/ConvertToSkillModal.tsx": {
"no-restricted-imports": {
"count": 1
@@ -1259,11 +1254,6 @@
"count": 1
}
},
- "src/routes/(main)/eval/bench/[benchmarkId]/features/TestCasesTab/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/features/BatchResumeModal/Footer.tsx": {
"no-restricted-imports": {
"count": 1
diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.ts
index 25a2fe03f26..733aad7125a 100644
--- a/packages/agent-gateway-client/src/types.ts
+++ b/packages/agent-gateway-client/src/types.ts
@@ -6,6 +6,12 @@ export type AgentStreamEventType =
| 'stream_start'
| 'stream_chunk'
| 'stream_end'
+ /**
+ * Producer-side boundary meaning this operation will not emit more visible
+ * assistant/tool/intervention output. The operation may still wait for
+ * `agent_runtime_end` to finish terminal bookkeeping.
+ */
+ | 'visible_output_end'
| 'stream_retry'
| 'tool_start'
| 'tool_end'
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.e2e.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.e2e.test.ts
index 7f1e93e553c..6e1e923c79c 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.e2e.test.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.e2e.test.ts
@@ -204,9 +204,9 @@ describe('ClaudeCodeAdapter E2E', () => {
// No `result.usage` in this fixture, so none emitted either.
expect(resultUsage.length).toBe(0);
- // 6. Should end with stream_end + agent_runtime_end (from result)
+ // 6. Should end with visible_output_end + agent_runtime_end (from result)
const lastTwo = types.slice(-2);
- expect(lastTwo).toEqual(['stream_end', 'agent_runtime_end']);
+ expect(lastTwo).toEqual(['visible_output_end', 'agent_runtime_end']);
// 7. Session ID should be captured
expect(adapter.sessionId).toBe('sess_abc123');
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
index d65c05b5544..105ee262345 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
@@ -18,19 +18,23 @@ describe('ClaudeCodeAdapter', () => {
expect(adapter.sessionId).toBe('sess_123');
});
- it('emits stream_end + agent_runtime_end on success result', () => {
+ it('emits visible_output_end before agent_runtime_end on success result', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
const events = adapter.adapt({ is_error: false, result: 'done', type: 'result' });
- expect(events.map((e) => e.type)).toEqual(['stream_end', 'agent_runtime_end']);
+ expect(events.map((e) => e.type)).toEqual([
+ 'stream_end',
+ 'visible_output_end',
+ 'agent_runtime_end',
+ ]);
});
it('emits error on failed result', () => {
const adapter = new ClaudeCodeAdapter();
adapter.adapt({ subtype: 'init', type: 'system' });
const events = adapter.adapt({ is_error: true, result: 'boom', type: 'result' });
- expect(events.map((e) => e.type)).toEqual(['stream_end', 'error']);
- expect(events[1].data.message).toBe('boom');
+ expect(events.map((e) => e.type)).toEqual(['stream_end', 'visible_output_end', 'error']);
+ expect(events[2].data.message).toBe('boom');
});
it('classifies auth failures from failed result events', () => {
@@ -41,15 +45,15 @@ describe('ClaudeCodeAdapter', () => {
adapter.adapt({ subtype: 'init', type: 'system' });
const events = adapter.adapt({ is_error: true, result: rawError, type: 'result' });
- expect(events.map((e) => e.type)).toEqual(['stream_end', 'error']);
- expect(events[1].data).toMatchObject({
+ expect(events.map((e) => e.type)).toEqual(['stream_end', 'visible_output_end', 'error']);
+ expect(events[2].data).toMatchObject({
agentType: 'claude-code',
clearEchoedContent: true,
code: 'auth_required',
docsUrl: 'https://docs.anthropic.com/en/docs/claude-code/setup',
stderr: rawError,
});
- expect(events[1].data.message).toBe(
+ expect(events[2].data.message).toBe(
'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',
);
});
@@ -67,8 +71,8 @@ describe('ClaudeCodeAdapter', () => {
type: 'result',
});
- expect(events.map((e) => e.type)).toEqual(['stream_end', 'error']);
- expect(events[1].data).toMatchObject({
+ expect(events.map((e) => e.type)).toEqual(['stream_end', 'visible_output_end', 'error']);
+ expect(events[2].data).toMatchObject({
agentType: 'claude-code',
clearEchoedContent: true,
code: 'overloaded',
@@ -88,8 +92,8 @@ describe('ClaudeCodeAdapter', () => {
type: 'result',
});
- expect(events.map((e) => e.type)).toEqual(['stream_end', 'error']);
- expect(events[1].data).toMatchObject({
+ expect(events.map((e) => e.type)).toEqual(['stream_end', 'visible_output_end', 'error']);
+ expect(events[2].data).toMatchObject({
agentType: 'claude-code',
code: 'overloaded',
message: rawError,
@@ -117,8 +121,8 @@ describe('ClaudeCodeAdapter', () => {
type: 'result',
});
- expect(events.map((e) => e.type)).toEqual(['stream_end', 'error']);
- expect(events[1].data).toMatchObject({
+ expect(events.map((e) => e.type)).toEqual(['stream_end', 'visible_output_end', 'error']);
+ expect(events[2].data).toMatchObject({
agentType: 'claude-code',
clearEchoedContent: true,
code: 'overloaded',
@@ -148,8 +152,8 @@ describe('ClaudeCodeAdapter', () => {
type: 'result',
});
- expect(events.map((e) => e.type)).toEqual(['stream_end', 'error']);
- expect(events[1].data).toMatchObject({ code: 'overloaded', message: rawError });
+ expect(events.map((e) => e.type)).toEqual(['stream_end', 'visible_output_end', 'error']);
+ expect(events[2].data).toMatchObject({ code: 'overloaded', message: rawError });
});
it('replays a real session that streamed a turn then overloaded β†’ overloaded + clears echo', () => {
@@ -218,7 +222,7 @@ describe('ClaudeCodeAdapter', () => {
type: 'result',
});
- expect(events[1].data).toMatchObject({
+ expect(events[2].data).toMatchObject({
code: 'rate_limit',
rateLimitInfo: { rateLimitType: 'seven_day' },
});
@@ -250,10 +254,10 @@ describe('ClaudeCodeAdapter', () => {
type: 'result',
});
- expect(events.map((e) => e.type)).toEqual(['stream_end', 'error']);
- expect(events[1].data).toMatchObject({ error: rawError, message: rawError });
- expect(events[1].data).not.toHaveProperty('code', 'rate_limit');
- expect(events[1].data).not.toHaveProperty('rateLimitInfo');
+ expect(events.map((e) => e.type)).toEqual(['stream_end', 'visible_output_end', 'error']);
+ expect(events[2].data).toMatchObject({ error: rawError, message: rawError });
+ expect(events[2].data).not.toHaveProperty('code', 'rate_limit');
+ expect(events[2].data).not.toHaveProperty('rateLimitInfo');
});
it('classifies rate-limit failures from paired rate_limit_event + result events', () => {
@@ -282,8 +286,8 @@ describe('ClaudeCodeAdapter', () => {
type: 'result',
});
- expect(events.map((e) => e.type)).toEqual(['stream_end', 'error']);
- expect(events[1].data).toMatchObject({
+ expect(events.map((e) => e.type)).toEqual(['stream_end', 'visible_output_end', 'error']);
+ expect(events[2].data).toMatchObject({
agentType: 'claude-code',
clearEchoedContent: true,
code: 'rate_limit',
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
index 310d4633c8d..02e37a6c3ae 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
@@ -1383,7 +1383,12 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
// wrongly inherit the previous run's task-completion tag).
this.pendingTaskCompletion = undefined;
- return [...events, this.makeEvent('stream_end', {}), finalEvent];
+ return [
+ ...events,
+ this.makeEvent('stream_end', {}),
+ this.makeEvent('visible_output_end', {}),
+ finalEvent,
+ ];
}
/**
diff --git a/packages/heterogeneous-agents/src/adapters/codex.test.ts b/packages/heterogeneous-agents/src/adapters/codex.test.ts
index 7ca22fbb6ca..a7ab7bd1db0 100644
--- a/packages/heterogeneous-agents/src/adapters/codex.test.ts
+++ b/packages/heterogeneous-agents/src/adapters/codex.test.ts
@@ -97,8 +97,12 @@ describe('CodexAdapter', () => {
type: 'error',
});
- expect(events.map((event) => event.type)).toEqual(['stream_end', 'error']);
- expect(events[1].data).toMatchObject({
+ expect(events.map((event) => event.type)).toEqual([
+ 'stream_end',
+ 'visible_output_end',
+ 'error',
+ ]);
+ expect(events[2].data).toMatchObject({
agentType: 'codex',
clearEchoedContent: true,
message:
@@ -123,8 +127,12 @@ describe('CodexAdapter', () => {
type: 'error',
});
- expect(events.map((event) => event.type)).toEqual(['stream_end', 'error']);
- expect(events[1].data).toMatchObject({
+ expect(events.map((event) => event.type)).toEqual([
+ 'stream_end',
+ 'visible_output_end',
+ 'error',
+ ]);
+ expect(events[2].data).toMatchObject({
agentType: 'codex',
clearEchoedContent: true,
code: 'rate_limit',
@@ -157,7 +165,7 @@ describe('CodexAdapter', () => {
type: 'error',
});
- expect(events[1].data).toMatchObject({
+ expect(events[2].data).toMatchObject({
code: 'rate_limit',
rateLimitInfo: {
resetsAt: expectedResetAt,
@@ -187,7 +195,7 @@ describe('CodexAdapter', () => {
type: 'error',
});
- expect(events[1].data).toMatchObject({
+ expect(events[2].data).toMatchObject({
code: 'rate_limit',
rateLimitInfo: {
resetsAt: expectedResetAt,
@@ -219,13 +227,13 @@ describe('CodexAdapter', () => {
type: 'error',
});
- expect(events[1].data).toMatchObject({
+ expect(events[2].data).toMatchObject({
code: 'rate_limit',
rateLimitInfo: {
status: 'rejected',
},
});
- expect(events[1].data.rateLimitInfo).not.toHaveProperty('resetsAt');
+ expect(events[2].data.rateLimitInfo).not.toHaveProperty('resetsAt');
} finally {
vi.useRealTimers();
}
@@ -908,7 +916,7 @@ describe('CodexAdapter', () => {
expect(flushed).toEqual([]);
});
- it('emits stream_end + agent_runtime_end on successful turn completion', () => {
+ it('emits visible_output_end before agent_runtime_end on successful turn completion', () => {
const adapter = new CodexAdapter();
adapter.adapt({ type: 'turn.started' });
@@ -923,6 +931,7 @@ describe('CodexAdapter', () => {
expect(events.map((event) => event.type)).toEqual([
'step_complete',
'stream_end',
+ 'visible_output_end',
'agent_runtime_end',
]);
});
@@ -956,6 +965,9 @@ describe('CodexAdapter', () => {
expect.objectContaining({
type: 'stream_end',
}),
+ expect.objectContaining({
+ type: 'visible_output_end',
+ }),
expect.objectContaining({
type: 'agent_runtime_end',
}),
diff --git a/packages/heterogeneous-agents/src/adapters/codex.ts b/packages/heterogeneous-agents/src/adapters/codex.ts
index 7e1dbd15fd4..9587b344ea4 100644
--- a/packages/heterogeneous-agents/src/adapters/codex.ts
+++ b/packages/heterogeneous-agents/src/adapters/codex.ts
@@ -819,7 +819,10 @@ export class CodexAdapter implements AgentEventAdapter {
events.push(this.makeEvent('step_complete', data));
}
- if (this.started) events.push(this.makeEvent('stream_end', {}));
+ if (this.started) {
+ events.push(this.makeEvent('stream_end', {}));
+ events.push(this.makeEvent('visible_output_end', {}));
+ }
events.push(this.makeEvent('agent_runtime_end', {}));
return events;
@@ -847,7 +850,7 @@ export class CodexAdapter implements AgentEventAdapter {
};
const events: HeterogeneousAgentEvent[] = this.started
- ? [this.makeEvent('stream_end', {})]
+ ? [this.makeEvent('stream_end', {}), this.makeEvent('visible_output_end', {})]
: [];
events.push(this.makeEvent('error', data));
diff --git a/packages/heterogeneous-agents/src/types.ts b/packages/heterogeneous-agents/src/types.ts
index 5b70fea0907..8cccf1678d8 100644
--- a/packages/heterogeneous-agents/src/types.ts
+++ b/packages/heterogeneous-agents/src/types.ts
@@ -19,6 +19,12 @@ export type HeterogeneousEventType =
| 'stream_start'
| 'stream_chunk'
| 'stream_end'
+ /**
+ * Producer-side boundary meaning this operation will not emit more visible
+ * assistant/tool output. The operation may still wait for `agent_runtime_end`
+ * to finish terminal bookkeeping.
+ */
+ | 'visible_output_end'
| 'tool_start'
| 'tool_end'
/**
diff --git a/src/features/Conversation/ChatInput/OpStatusTray.tsx b/src/features/Conversation/ChatInput/OpStatusTray.tsx
index 535e7a6056f..7ef17d222cd 100644
--- a/src/features/Conversation/ChatInput/OpStatusTray.tsx
+++ b/src/features/Conversation/ChatInput/OpStatusTray.tsx
@@ -250,7 +250,8 @@ const OpStatusTray = memo<OpStatusTrayProps>(({ seamless, topAttached }) => {
const runtimeOperationIds: string[] = [];
for (const op of ops) {
- if (op.status !== 'running' || op.metadata.isAborting) continue;
+ if (op.status !== 'running' || op.metadata.isAborting || op.metadata.visibleLoadingDone)
+ continue;
const mapped = resolveOperationActivity(op.type);
if (mapped && op.metadata.startTime > latestActivityStart) {
diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsx
index 68fe3e4ce0b..47896650e2b 100644
--- a/src/features/Conversation/ChatInput/index.tsx
+++ b/src/features/Conversation/ChatInput/index.tsx
@@ -272,7 +272,10 @@ const ChatInput = memo<ChatInputProps>(
}, [setChatInputOverlayHeight]);
// Loading state from ConversationStore (bridged from ChatStore)
- const isInputLoading = useConversationStore(messageStateSelectors.isInputLoading);
+ const isInputLoading = useConversationStore(messageStateSelectors.isInputVisiblyLoading);
+ const isInputQueueBlocked = useChatStore((s) =>
+ operationSelectors.isInputLoadingByContext(context)(s),
+ );
// Pending interventions β€” use custom equality to prevent infinite re-render loop.
// The selector creates new array/object refs each call; without equality check,
@@ -317,7 +320,7 @@ const ChatInput = memo<ChatInputProps>(
// When disableQueue is set (e.g. onboarding), block sending while loading.
// disableSend hard-blocks regardless of content (host surface is read-only).
const disabled =
- isInputEmpty || isUploadingFiles || (!!disableQueue && isInputLoading) || !!disableSend;
+ isInputEmpty || isUploadingFiles || (!!disableQueue && isInputQueueBlocked) || !!disableSend;
const shouldUsePlainSendButton = !showSendMenu && !!sendMenu;
const businessCostEstimateAlert = useBusinessChatInputCostEstimateAlert();
const businessSendAreaPrefix = getBusinessChatInputSendAreaPrefix(sendAreaPrefix);
@@ -339,7 +342,7 @@ const ChatInput = memo<ChatInputProps>(
// Onboarding-style surfaces opt out of message queuing β€” pressing Enter
// while the agent is streaming should be a no-op rather than enqueue.
- if (disableQueue && isInputLoading) return;
+ if (disableQueue && isInputQueueBlocked) return;
// Get content before clearing
const message = getMarkdownContent();
@@ -365,7 +368,7 @@ const ChatInput = memo<ChatInputProps>(
// Fire and forget - send with captured message
await sendMessage({ editorData, files: currentFileList, message, pageSelections });
},
- [sendMessage, disableQueue, disableSend, isInputLoading],
+ [sendMessage, disableQueue, disableSend, isInputQueueBlocked],
);
const sendButtonProps: SendButtonProps = {
diff --git a/src/features/Conversation/store/slices/messageState/selectors.ts b/src/features/Conversation/store/slices/messageState/selectors.ts
index d0dde06a76a..6ada36494e7 100644
--- a/src/features/Conversation/store/slices/messageState/selectors.ts
+++ b/src/features/Conversation/store/slices/messageState/selectors.ts
@@ -59,10 +59,15 @@ const selectedMessageCount = (s: State) => s.selectedMessageIds.length;
const isAIGenerating = (s: State) => s.operationState.isAIGenerating;
/**
- * Check if input should be in loading state (from sendMessage through AI generation)
+ * Check if input actions should stay blocked until operation bookkeeping ends.
*/
const isInputLoading = (s: State) => s.operationState.isInputLoading;
+/**
+ * Check if input should show visible loading controls.
+ */
+const isInputVisiblyLoading = (s: State) => s.operationState.isInputVisiblyLoading;
+
/**
* Get send message error for this context (if any)
*/
@@ -189,6 +194,7 @@ export const messageStateSelectors = {
isAIGenerating,
isAssistantGroupItemGenerating,
isInputLoading,
+ isInputVisiblyLoading,
isMessageCollapsed,
isMessageContinuing,
isMessageCreating,
diff --git a/src/features/Conversation/types/operation.ts b/src/features/Conversation/types/operation.ts
index e4ec259d4f9..6af588dc6dd 100644
--- a/src/features/Conversation/types/operation.ts
+++ b/src/features/Conversation/types/operation.ts
@@ -93,10 +93,15 @@ export interface OperationState {
isAIGenerating: boolean;
/**
- * Check if input should be in loading state (from sendMessage through AI generation)
+ * Check if input actions should stay blocked until operation bookkeeping ends.
*/
isInputLoading: boolean;
+ /**
+ * Check if input should still show visible loading controls.
+ */
+ isInputVisiblyLoading: boolean;
+
/**
* Send message error for this context (if any)
*/
@@ -132,5 +137,6 @@ export const DEFAULT_OPERATION_STATE: OperationState = {
getToolOperationState: () => DEFAULT_TOOL_OPERATION_STATE,
isAIGenerating: false,
isInputLoading: false,
+ isInputVisiblyLoading: false,
sendMessageError: undefined,
};
diff --git a/src/features/Electron/titlebar/TabBar/hooks/useTabRunning.ts b/src/features/Electron/titlebar/TabBar/hooks/useTabRunning.ts
index 39009506fd3..98c666bfe06 100644
--- a/src/features/Electron/titlebar/TabBar/hooks/useTabRunning.ts
+++ b/src/features/Electron/titlebar/TabBar/hooks/useTabRunning.ts
@@ -8,7 +8,7 @@ export const useTabRunning = (tab: TabItem): boolean =>
useChatStore((s) => {
const ctx = parseAgentTabContext(tab.url);
if (!ctx) return false;
- return operationSelectors.isAgentRuntimeRunningByContext({
+ return operationSelectors.isAgentRuntimeVisiblyRunningByContext({
agentId: ctx.agentId,
topicId: ctx.topicId,
})(s);
diff --git a/src/features/Fleet/RunningTaskSidebar.tsx b/src/features/Fleet/RunningTaskSidebar.tsx
index fecb7ba9f23..0c7d4bea5d5 100644
--- a/src/features/Fleet/RunningTaskSidebar.tsx
+++ b/src/features/Fleet/RunningTaskSidebar.tsx
@@ -20,6 +20,7 @@ import { type ChatTopicStatus } from '@/types/topic';
import { getIdleColumnKeys } from './idleColumns';
import RowsSwitcher from './RowsSwitcher';
+import { getFleetSidebarStatus } from './runningStatus';
import { useFleetStore } from './store';
import { type FleetColumn } from './types';
@@ -71,12 +72,19 @@ interface RunningStatusProps {
*/
const RunningStatus = memo<RunningStatusProps>(({ agentId, status, topicId }) => {
const { isDarkMode } = useTheme();
+ const context = useMemo(() => ({ agentId, topicId }), [agentId, topicId]);
const startedAt = useChatStore(
- operationSelectors.getAgentRuntimeStartTimeByContext({ agentId, topicId }),
+ operationSelectors.getVisibleAgentRuntimeStartTimeByContext(context),
);
+ const isRuntimeRunning = useChatStore(operationSelectors.isAgentRuntimeRunningByContext(context));
const elapsed = useElapsedClock(startedAt);
+ const sidebarStatus = getFleetSidebarStatus({
+ isRuntimeRunning,
+ status,
+ visibleStartedAt: startedAt,
+ });
- if (!elapsed) return <StatusDot status={status} />;
+ if (!elapsed) return <StatusDot status={sidebarStatus} />;
const ringColor = isDarkMode
? cssVar.colorWarningBorder
diff --git a/src/features/Fleet/runningStatus.test.ts b/src/features/Fleet/runningStatus.test.ts
new file mode 100644
index 00000000000..160626ec108
--- /dev/null
+++ b/src/features/Fleet/runningStatus.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+
+import { getFleetSidebarStatus } from './runningStatus';
+
+describe('getFleetSidebarStatus', () => {
+ it('masks running topic status after visible output ended but runtime is still bookkeeping', () => {
+ expect(
+ getFleetSidebarStatus({
+ isRuntimeRunning: true,
+ status: 'running',
+ visibleStartedAt: undefined,
+ }),
+ ).toBe('completed');
+ });
+
+ it('keeps running topic status when no local runtime operation is loaded', () => {
+ expect(
+ getFleetSidebarStatus({
+ isRuntimeRunning: false,
+ status: 'running',
+ visibleStartedAt: undefined,
+ }),
+ ).toBe('running');
+ });
+
+ it('keeps running topic status while visible runtime elapsed time is available', () => {
+ expect(
+ getFleetSidebarStatus({
+ isRuntimeRunning: true,
+ status: 'running',
+ visibleStartedAt: 1000,
+ }),
+ ).toBe('running');
+ });
+});
diff --git a/src/features/Fleet/runningStatus.ts b/src/features/Fleet/runningStatus.ts
new file mode 100644
index 00000000000..abf02a3be0e
--- /dev/null
+++ b/src/features/Fleet/runningStatus.ts
@@ -0,0 +1,22 @@
+import type { ChatTopicStatus } from '@/types/topic';
+
+interface GetFleetSidebarStatusParams {
+ isRuntimeRunning: boolean;
+ status: ChatTopicStatus | undefined;
+ visibleStartedAt: number | undefined;
+}
+
+export const getFleetSidebarStatus = ({
+ isRuntimeRunning,
+ status,
+ visibleStartedAt,
+}: GetFleetSidebarStatusParams): ChatTopicStatus | undefined => {
+ // Example: visible_output_end hides the elapsed timer while the runtime still
+ // waits for terminal bookkeeping. Topic status can remain "running", but the
+ // Fleet sidebar should not keep showing a spinning running dot in that tail.
+ if (isRuntimeRunning && visibleStartedAt === undefined && status === 'running') {
+ return 'completed';
+ }
+
+ return status;
+};
diff --git a/src/hooks/useOperationState.test.ts b/src/hooks/useOperationState.test.ts
index 9ef106b056b..15e00cb56fe 100644
--- a/src/hooks/useOperationState.test.ts
+++ b/src/hooks/useOperationState.test.ts
@@ -292,9 +292,35 @@ describe('useOperationState', () => {
expect(useChatStore.getState().operationsByContext[messageMapKey(context)]).toHaveLength(1);
expect(result.current.isInputLoading).toBe(true);
+ expect(result.current.isInputVisiblyLoading).toBe(true);
expect(result.current.isAIGenerating).toBe(true);
});
+ it('should keep input blocked after visible loading ends before terminal bookkeeping', () => {
+ const context = {
+ agentId: 'test-agent-id',
+ topicId: 'test-topic-id',
+ threadId: null,
+ } as const;
+
+ const { result } = renderHook(() => useOperationState(context));
+
+ act(() => {
+ useChatStore.getState().startOperation({
+ context,
+ metadata: { visibleLoadingDone: true },
+ type: 'execAgentRuntime',
+ });
+ });
+
+ // Example: visible_output_end arrived, but agent_runtime_end has not
+ // drained queue/cache/unread side effects yet. UI loading can stop, but
+ // edit-confirm regenerate must still stay blocked.
+ expect(result.current.isInputLoading).toBe(true);
+ expect(result.current.isInputVisiblyLoading).toBe(false);
+ expect(result.current.isAIGenerating).toBe(false);
+ });
+
it('should clear loading after cancelling an operation in a null-topic context', () => {
const context = {
agentId: 'test-agent-id',
@@ -332,6 +358,7 @@ describe('useOperationState', () => {
expect(useChatStore.getState().operations[operationId!].status).toBe('cancelled');
expect(result.current.isInputLoading).toBe(false);
+ expect(result.current.isInputVisiblyLoading).toBe(false);
});
});
});
diff --git a/src/hooks/useOperationState.ts b/src/hooks/useOperationState.ts
index 91f21563ee3..7e531222f0d 100644
--- a/src/hooks/useOperationState.ts
+++ b/src/hooks/useOperationState.ts
@@ -36,14 +36,19 @@ export const useOperationState = (context: ConversationContext): OperationState
// Check if AI is generating in this context
const isAIGenerating = useChatStore((s) =>
- operationSelectors.isAgentRuntimeRunningByContext(context)(s),
+ operationSelectors.isAgentRuntimeVisiblyRunningByContext(context)(s),
);
- // Check if input should show loading (sendMessage + AI runtime)
+ // Check if input actions should stay blocked until operation bookkeeping ends.
const isInputLoading = useChatStore((s) =>
operationSelectors.isInputLoadingByContext(context)(s),
);
+ // Check if input should still show visible loading controls.
+ const isInputVisiblyLoading = useChatStore((s) =>
+ operationSelectors.isInputVisiblyLoadingByContext(context)(s),
+ );
+
// Get send message error for this context
const sendMessageError = useMemo(() => {
const operationIds = operationsByContext[contextKey] || [];
@@ -73,7 +78,11 @@ export const useOperationState = (context: ConversationContext): OperationState
const messageOps = operationIds.map((id) => operations[id]).filter(Boolean);
const runningOps = messageOps.filter((op) => op.status === 'running');
- const isGenerating = runningOps.some((op) => AI_RUNTIME_OPERATION_TYPES.includes(op.type));
+ const visibleRunningOps = runningOps.filter((op) => !op.metadata.visibleLoadingDone);
+
+ const isGenerating = visibleRunningOps.some((op) =>
+ AI_RUNTIME_OPERATION_TYPES.includes(op.type),
+ );
// A message is interrupted only if the latest AI runtime operation was cancelled.
// Using .some() would incorrectly flag messages where a stale cancelled op
@@ -85,15 +94,15 @@ export const useOperationState = (context: ConversationContext): OperationState
!isGenerating && !!latestRuntimeOp && latestRuntimeOp.status === 'cancelled';
return {
- isContinuing: runningOps.some((op) => op.type === 'continue'),
- isCreating: runningOps.some(
+ isContinuing: visibleRunningOps.some((op) => op.type === 'continue'),
+ isCreating: visibleRunningOps.some(
(op) => op.type === 'sendMessage' || op.type === 'createAssistantMessage',
),
isGenerating,
- isInReasoning: runningOps.some((op) => op.type === 'reasoning'),
+ isInReasoning: visibleRunningOps.some((op) => op.type === 'reasoning'),
isInterrupted,
isProcessing: operationSelectors.isMessageProcessing(messageId)(state),
- isRegenerating: runningOps.some((op) => op.type === 'regenerate'),
+ isRegenerating: visibleRunningOps.some((op) => op.type === 'regenerate'),
};
},
@@ -118,6 +127,7 @@ export const useOperationState = (context: ConversationContext): OperationState
},
isAIGenerating,
isInputLoading,
+ isInputVisiblyLoading,
sendMessageError,
};
}, [
@@ -126,6 +136,7 @@ export const useOperationState = (context: ConversationContext): OperationState
toolCallingStreamIds,
isAIGenerating,
isInputLoading,
+ isInputVisiblyLoading,
sendMessageError,
]);
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx
index 4f9f5ddaee3..a217e4a5955 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx
@@ -93,6 +93,9 @@ vi.mock('@/store/chat', () => ({
vi.mock('@/store/chat/selectors', () => ({
operationSelectors: {
getAgentRuntimeStartTimeByContext: () => () => runningStartTimeMock.value,
+ getVisibleAgentRuntimeStartTimeByContext: () => () => runningStartTimeMock.value,
+ isAgentRuntimeRunningByContext: () => () => false,
+ isAgentRuntimeVisiblyRunningByContext: () => () => false,
isTopicUnreadCompleted: () => () => false,
},
}));
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
index a5bd44c158a..08e7da311ca 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
@@ -112,7 +112,7 @@ interface RunningElapsedTimeProps {
const RunningElapsedTime = memo<RunningElapsedTimeProps>(({ agentId, topicId }) => {
const startTime = useChatStore(
agentId
- ? operationSelectors.getAgentRuntimeStartTimeByContext({ agentId, topicId })
+ ? operationSelectors.getVisibleAgentRuntimeStartTimeByContext({ agentId, topicId })
: () => undefined,
);
const [now, setNow] = useState(() => Date.now());
@@ -180,6 +180,19 @@ const TopicItem = memo<TopicItemProps>(
const isUnreadCompleted = useChatStore(
id ? operationSelectors.isTopicUnreadCompleted(id) : () => false,
);
+ const hasLocalRunningRuntime = useChatStore(
+ id && activeAgentId
+ ? operationSelectors.isAgentRuntimeRunningByContext({ agentId: activeAgentId, topicId: id })
+ : () => false,
+ );
+ const isRuntimeVisiblyRunning = useChatStore(
+ id && activeAgentId
+ ? operationSelectors.isAgentRuntimeVisiblyRunningByContext({
+ agentId: activeAgentId,
+ topicId: id,
+ })
+ : () => false,
+ );
const {
focusTopicPopup,
@@ -238,6 +251,8 @@ const TopicItem = memo<TopicItemProps>(
const isFailed = status === 'failed';
const isRunning = status === 'running';
const isWaitingForHuman = status === 'waitingForHuman';
+ const shouldShowRunningIcon =
+ isLoading || (isRunning && (!hasLocalRunningRuntime || isRuntimeVisiblyRunning));
// By-status grouping mixes topics from different projects, so surface each
// topic's working directory as a muted second line. Data is already on the
@@ -331,7 +346,7 @@ const TopicItem = memo<TopicItemProps>(
if (isWaitingForHuman) {
return <Icon icon={Hand} size={'small'} style={{ color: cssVar.colorInfo }} />;
}
- if (isLoading || isRunning) {
+ if (shouldShowRunningIcon) {
return (
<RingLoadingIcon
ringColor={loadingRingColor}
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/TestCasePreviewPanel.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/TestCasePreviewPanel.tsx
index b8edb8d807e..9eef17500ed 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/TestCasePreviewPanel.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/DatasetsTab/TestCasePreviewPanel.tsx
@@ -1,4 +1,4 @@
-import { ActionIcon, CopyButton, Flexbox, Text } from '@lobehub/ui';
+import { ActionIcon, CopyButton, Flexbox } from '@lobehub/ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { X } from 'lucide-react';
import { memo } from 'react';
@@ -21,8 +21,8 @@ const styles = createStaticStyles(({ css }) => ({
font-size: ${cssVar.fontSizeSM};
font-weight: 600;
color: ${cssVar.colorTextTertiary};
- letter-spacing: 0.02em;
text-transform: uppercase;
+ letter-spacing: 0.02em;
`,
fieldValue: css`
padding-block: 8px;
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCards/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCards/index.tsx
index 1a6391808d5..5f13432f973 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCards/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCards/index.tsx
@@ -1,6 +1,7 @@
'use client';
-import { ActionIcon, Button, Flexbox, Icon, Text } from '@lobehub/ui';
+import { ActionIcon, Flexbox, Icon, Text } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { Play, Plus } from 'lucide-react';
import { memo } from 'react';
@@ -72,7 +73,7 @@ const RunCards = memo<RunCardsProps>(({ datasetId, onCreateRun, benchmarkId }) =
{t('run.empty.description')}
</Text>
</Flexbox>
- <Button icon={Plus} size="small" variant="filled" onClick={onCreateRun}>
+ <Button icon={<Plus size={14} />} size="small" type="primary" onClick={onCreateRun}>
{t('run.actions.create')}
</Button>
</Flexbox>
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Footer.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Footer.tsx
index ff18ce51f54..9a4355ef95e 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Footer.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Footer.tsx
@@ -1,7 +1,7 @@
'use client';
-import { Button, type DropdownItem, DropdownMenu, Flexbox } from '@lobehub/ui';
-import { ModalFooter, useModalContext } from '@lobehub/ui/base-ui';
+import { type DropdownItem, DropdownMenu, Flexbox } from '@lobehub/ui';
+import { Button, ModalFooter, useModalContext } from '@lobehub/ui/base-ui';
import { createStaticStyles } from 'antd-style';
import { ChevronDown } from 'lucide-react';
import { type FC } from 'react';
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/RunCard.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/RunCard.tsx
index a88a654d29a..b473570e35f 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/RunCard.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunsTab/RunCard.tsx
@@ -1,5 +1,5 @@
import type { AgentEvalRunListItem } from '@lobechat/types';
-import { type DropdownItem, DropdownMenu, Flexbox, Icon, Text } from '@lobehub/ui';
+import { type DropdownItem, DropdownMenu, Flexbox, Icon } from '@lobehub/ui';
import { confirmModal } from '@lobehub/ui/base-ui';
import { App } from 'antd';
import { createStaticStyles, cssVar } from 'antd-style';
@@ -28,7 +28,6 @@ const styles = createStaticStyles(({ css }) => ({
arrowIcon: css`
flex-shrink: 0;
color: ${cssVar.colorTextTertiary};
-
transition: transform 0.15s ease;
@media (prefers-reduced-motion: reduce) {
@@ -102,7 +101,6 @@ const styles = createStaticStyles(({ css }) => ({
hero: css`
padding: 16px;
border-radius: ${cssVar.borderRadius};
-
background: ${cssVar.colorFillQuaternary};
`,
heroValue: css`
@@ -135,9 +133,7 @@ const styles = createStaticStyles(({ css }) => ({
progressFill: css`
height: 100%;
border-radius: 999px;
-
background: ${cssVar.colorPrimary};
-
transition: width 0.3s ease;
@media (prefers-reduced-motion: reduce) {
diff --git a/src/routes/(main)/eval/features/DatasetEditModal/Content.tsx b/src/routes/(main)/eval/features/DatasetEditModal/Content.tsx
index 4e999bd73d2..4bc4a3e30a8 100644
--- a/src/routes/(main)/eval/features/DatasetEditModal/Content.tsx
+++ b/src/routes/(main)/eval/features/DatasetEditModal/Content.tsx
@@ -10,7 +10,7 @@ import { useTranslation } from 'react-i18next';
import { agentEvalService } from '@/services/agentEval';
-import { DATASET_PRESETS, getPresetsByCategory } from '../../config/datasetPresets';
+import { getPresetsByCategory } from '../../config/datasetPresets';
const CATEGORY_LABELS: Record<string, string> = {
'custom': 'Custom',
@@ -66,8 +66,8 @@ const styles = createStaticStyles(({ css }) => ({
`,
presetGrid: css`
display: grid;
- gap: 8px;
grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 8px;
`,
presetIcon: css`
border: 1px solid ${cssVar.colorBorderSecondary};
diff --git a/src/routes/(main)/eval/features/DatasetImportModal/UploadStep.tsx b/src/routes/(main)/eval/features/DatasetImportModal/UploadStep.tsx
index f613f4ce629..4af851209fe 100644
--- a/src/routes/(main)/eval/features/DatasetImportModal/UploadStep.tsx
+++ b/src/routes/(main)/eval/features/DatasetImportModal/UploadStep.tsx
@@ -1,7 +1,7 @@
'use client';
import { type FileUploadState } from '@lobechat/types';
-import { Center, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
+import { Center, Flexbox, Icon, Tag } from '@lobehub/ui';
import { Progress, Upload } from 'antd';
import { createStaticStyles } from 'antd-style';
import { CloudUpload, ImportIcon } from 'lucide-react';
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx
index d95d47a8a2b..24d452f7c9b 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx
@@ -93,7 +93,7 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate })
const isUpdating = useHomeStore((s) => s.agentUpdatingId === id);
// Separate loading state from chat store - only show loading for this specific agent
- const isLoading = useChatStore(operationSelectors.isAgentRunning(id));
+ const isLoading = useChatStore(operationSelectors.isAgentVisiblyRunning(id));
// Get display title with fallback
const displayTitle = title || t('untitledAgent');
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/InboxItem.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/InboxItem.tsx
index 09598d5b39e..fa2751c4a84 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/InboxItem.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/InboxItem.tsx
@@ -54,7 +54,7 @@ const InboxItem = memo<InboxItemProps>(({ className, style }) => {
const inboxMeta = useAgentStore(agentSelectors.getAgentMetaById(inboxAgentId!));
const isLoading = useChatStore(
- inboxAgentId ? operationSelectors.isAgentRunning(inboxAgentId) : () => false,
+ inboxAgentId ? operationSelectors.isAgentVisiblyRunning(inboxAgentId) : () => false,
);
const prefetchAgent = usePrefetchAgent();
const inboxAgentTitle = inboxMeta.title || 'Lobe AI';
diff --git a/src/routes/(main)/home/_layout/Body/InboxEntry.tsx b/src/routes/(main)/home/_layout/Body/InboxEntry.tsx
index 4d55cc7acd2..bba013f2bb8 100644
--- a/src/routes/(main)/home/_layout/Body/InboxEntry.tsx
+++ b/src/routes/(main)/home/_layout/Body/InboxEntry.tsx
@@ -47,7 +47,7 @@ const InboxEntry = memo(() => {
const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
const inboxMeta = useAgentStore(agentSelectors.getAgentMetaById(inboxAgentId!));
const isLoading = useChatStore(
- inboxAgentId ? operationSelectors.isAgentRunning(inboxAgentId) : () => false,
+ inboxAgentId ? operationSelectors.isAgentVisiblyRunning(inboxAgentId) : () => false,
);
const title = inboxMeta.title || 'Lobe AI';
diff --git a/src/routes/(mobile)/(home)/features/SessionListContent/List/Item/index.tsx b/src/routes/(mobile)/(home)/features/SessionListContent/List/Item/index.tsx
index 65e6ef2a3bf..51a73cb3cb0 100644
--- a/src/routes/(mobile)/(home)/features/SessionListContent/List/Item/index.tsx
+++ b/src/routes/(mobile)/(home)/features/SessionListContent/List/Item/index.tsx
@@ -32,7 +32,7 @@ const SessionItem = memo<SessionItemProps>(({ id }) => {
const [active] = useSessionStore((s) => [s.activeId === id]);
const [loading] = useChatStore((s) => [
- operationSelectors.isAgentRuntimeRunning(s) && id === s.activeAgentId,
+ operationSelectors.isAgentRuntimeVisiblyRunning(s) && id === s.activeAgentId,
]);
const [pin, title, avatar, avatarBackground, updateAt, members, model, group, sessionType] =
diff --git a/src/services/agentRuntime/type.ts b/src/services/agentRuntime/type.ts
index fa9d4433a01..df9fe233a06 100644
--- a/src/services/agentRuntime/type.ts
+++ b/src/services/agentRuntime/type.ts
@@ -12,6 +12,7 @@ export interface StreamEvent {
| 'stream_start'
| 'stream_chunk'
| 'stream_end'
+ | 'visible_output_end'
| 'stream_retry'
| 'step_start'
| 'step_complete'
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts
index 238709c1ba9..4a858cbcdd1 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { messageService } from '@/services/message';
import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge';
import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { buildRunLifecycle } from '../lifecycle/buildRunLifecycle';
import { createGatewayEventHandler } from '../transports/gateway/gatewayEventHandler';
@@ -41,6 +42,7 @@ function createMockStore() {
internal_dispatchMessage: vi.fn(),
internal_executeClientTool: vi.fn().mockResolvedValue(undefined),
internal_toggleToolCallingStreaming: vi.fn(),
+ internal_updateTopicLoading: vi.fn(),
markTopicUnread: vi.fn(),
messagesMap: {} as Record<string, any>,
operations: {
@@ -432,10 +434,11 @@ describe('createGatewayEventHandler', () => {
});
describe('stream_end', () => {
- it('should clear tool streaming only', async () => {
+ it('keeps visible loading for a plain no-tool stream boundary', async () => {
const store = createMockStore();
const handler = createHandler(store);
+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'hello back' }));
handler(makeEvent('stream_end'));
await flush();
@@ -443,6 +446,109 @@ describe('createGatewayEventHandler', () => {
'msg-initial',
undefined,
);
+ expect(store.updateOperationMetadata).not.toHaveBeenCalledWith('op-1', {
+ visibleLoadingDone: true,
+ });
+ expect(store.completeOperation).not.toHaveBeenCalledWith('op-1');
+ expect(store.internal_updateTopicLoading).not.toHaveBeenCalledWith('topic-1', false);
+ });
+
+ it('keeps visible loading after stream_end when tool calls need another step', async () => {
+ const store = createMockStore();
+ const handler = createHandler(store);
+
+ handler(
+ makeEvent('stream_chunk', {
+ chunkType: 'tools_calling',
+ toolsCalling: [{ id: 'tc-1' }],
+ }),
+ );
+ handler(makeEvent('stream_end'));
+ await flush();
+
+ expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith(
+ 'msg-initial',
+ undefined,
+ );
+ expect(store.updateOperationMetadata).not.toHaveBeenCalledWith('op-1', {
+ visibleLoadingDone: true,
+ });
+ expect(store.completeOperation).not.toHaveBeenCalledWith('op-1');
+ expect(store.internal_updateTopicLoading).not.toHaveBeenCalledWith('topic-1', false);
+ });
+
+ it('applies finalContent before ending a reasoning-only stream', async () => {
+ const store = createMockStore();
+ const handler = createHandler(store);
+
+ handler(makeEvent('stream_chunk', { chunkType: 'reasoning', reasoning: 'thinking text' }));
+ handler(makeEvent('stream_end', { finalContent: 'final answer' }));
+ await flush();
+
+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(
+ {
+ id: 'msg-initial',
+ type: 'updateMessage',
+ value: { content: 'final answer' },
+ },
+ { operationId: 'op-1' },
+ );
+ expect(store.completeOperation).toHaveBeenCalledWith('op-reasoning-1');
+ expect(store.updateOperationMetadata).not.toHaveBeenCalledWith('op-1', {
+ visibleLoadingDone: true,
+ });
+ });
+
+ it('should clear tool streaming', async () => {
+ const store = createMockStore();
+ const handler = createHandler(store);
+
+ handler(makeEvent('stream_end'));
+ await flush();
+
+ expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith(
+ 'msg-initial',
+ undefined,
+ );
+ });
+ });
+
+ describe('visible_output_end', () => {
+ it('clears visible loading without completing the operation', async () => {
+ const store = createMockStore();
+ const handler = createHandler(store);
+
+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'hello back' }));
+ handler(makeEvent('visible_output_end'));
+ await flush();
+
+ expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith(
+ 'msg-initial',
+ undefined,
+ );
+ expect(store.updateOperationMetadata).toHaveBeenCalledWith('op-1', {
+ visibleLoadingDone: true,
+ });
+ expect(store.completeOperation).not.toHaveBeenCalledWith('op-1');
+ expect(store.internal_updateTopicLoading).toHaveBeenCalledWith('topic-1', false);
+ });
+
+ it('keeps topic loading when another message is queued in the same context', async () => {
+ const store = createMockStore();
+ (store as any).queuedMessages = {
+ [messageMapKey({ agentId: 'agent-1', scope: 'session', topicId: 'topic-1' } as any)]: [
+ { content: 'next' },
+ ],
+ };
+ const handler = createHandler(store);
+
+ handler(makeEvent('visible_output_end'));
+ await flush();
+
+ expect(store.updateOperationMetadata).toHaveBeenCalledWith('op-1', {
+ visibleLoadingDone: true,
+ });
+ expect(store.internal_updateTopicLoading).not.toHaveBeenCalledWith('topic-1', false);
});
});
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
index fb05a387f66..6efb6b44eb4 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
@@ -24,6 +24,7 @@ import type {
} from '@/store/chat/slices/agentRun/actions/lifecycle/types';
import type { ChatStore } from '@/store/chat/store';
import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
// `agent_runtime_end` reasons that are NOT a clean completion: a mid-stream
// cancel and a deferred-tool park. These must NOT mark the topic unread, and
@@ -429,6 +430,7 @@ export const createGatewayEventHandler = (
// Reset accumulators for the new stream
accumulatedContent = '';
accumulatedReasoning = '';
+ get().updateOperationMetadata(operationId, { visibleLoadingDone: false });
// Skip the DB read ONLY for native gateway streams β€” those carry
// `assistantMessage.id` directly on stream_start AND the preceding
@@ -550,11 +552,43 @@ export const createGatewayEventHandler = (
case 'stream_end': {
enqueue(() => {
- // Only clear tool calling streaming β€” keep message loading active
- // until agent_runtime_end so users don't think the session ended
- // during tool execution gaps between steps
+ const data = toRecord(event.data);
+ const finalContent = pickNonEmptyString(data?.finalContent);
+ if (finalContent !== undefined) {
+ // Example: reasoning-only answers stream as reasoning chunks, then
+ // the server promotes that text into stream_end.finalContent. Apply
+ // it before ending reasoning so visible_output_end cannot leave an
+ // empty completed assistant bubble while waiting for terminal SoT.
+ accumulatedContent = finalContent;
+ hasStreamedContent = true;
+ get().internal_dispatchMessage(
+ {
+ id: currentAssistantMessageId,
+ type: 'updateMessage',
+ value: { content: accumulatedContent },
+ },
+ dispatchContext,
+ );
+ }
+ get().internal_toggleToolCallingStreaming(currentAssistantMessageId, undefined);
+ endReasoningIfNeeded();
+ });
+ break;
+ }
+
+ case 'visible_output_end': {
+ enqueue(() => {
get().internal_toggleToolCallingStreaming(currentAssistantMessageId, undefined);
endReasoningIfNeeded();
+ // Example: CC/Codex may emit stream_end -> stream_start(newStep) for
+ // assistant-assistant transitions. Only this explicit producer signal
+ // means visible output is done; the operation still waits for
+ // agent_runtime_end to preserve terminal side-effect ordering.
+ get().updateOperationMetadata(operationId, { visibleLoadingDone: true });
+ const hasQueuedMessage =
+ (get().queuedMessages?.[messageMapKey(context)]?.length ?? 0) > 0;
+ if (context.topicId && !hasQueuedMessage)
+ get().internal_updateTopicLoading(context.topicId, false);
});
break;
}
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.test.ts
new file mode 100644
index 00000000000..935bf23384e
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.test.ts
@@ -0,0 +1,57 @@
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import type { ConversationContext } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { ChatStore } from '@/store/chat/store';
+
+import { createGatewayMemberStreamHandler } from './gatewayMemberStreamHandler';
+
+const context = {
+ agentId: 'member-agent',
+ groupId: 'group-1',
+ scope: 'group',
+ topicId: 'topic-1',
+} as ConversationContext;
+
+const makeEvent = (type: AgentStreamEvent['type'], data?: AgentStreamEvent['data']) =>
+ ({
+ data,
+ id: 'event-1',
+ operationId: 'server-member-op',
+ stepIndex: 0,
+ timestamp: 0,
+ type,
+ }) as AgentStreamEvent;
+
+const createStore = () =>
+ ({
+ associateMessageWithOperation: vi.fn(),
+ completeOperation: vi.fn(),
+ dbMessagesMap: {},
+ internal_dispatchMessage: vi.fn(),
+ startOperation: vi.fn(() => ({
+ abortController: new AbortController(),
+ operationId: 'local-member-op',
+ })),
+ updateOperationMetadata: vi.fn(),
+ }) as unknown as ChatStore;
+
+describe('createGatewayMemberStreamHandler', () => {
+ it('clears visible loading for the local member op without completing it', () => {
+ const store = createStore();
+ const handler = createGatewayMemberStreamHandler(() => store, {
+ context,
+ ensureGroupHydrated: vi.fn().mockResolvedValue(undefined),
+ memberOperationId: 'server-member-op',
+ parentOperationId: 'owner-op',
+ });
+
+ handler(makeEvent('stream_start', { assistantMessage: { id: 'member-msg' } }));
+ handler(makeEvent('visible_output_end'));
+
+ expect(store.updateOperationMetadata).toHaveBeenCalledWith('local-member-op', {
+ visibleLoadingDone: true,
+ });
+ expect(store.completeOperation).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.ts
index 32397f3c67c..44e22b789fa 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.ts
@@ -148,6 +148,17 @@ export const createGatewayMemberStreamHandler = (
break;
}
+ case 'visible_output_end': {
+ // Example: forwarded member streams can finish text before the
+ // supervisor's terminal barrier refetches the group tree. Clear only
+ // the member column's visible loading; terminal reconciliation still
+ // belongs to agent_runtime_end/error.
+ if (localOperationId) {
+ get().updateOperationMetadata(localOperationId, { visibleLoadingDone: true });
+ }
+ break;
+ }
+
case 'agent_runtime_end':
case 'error': {
ended = true;
diff --git a/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts b/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts
index 3d25259a464..b8c4a88cd3d 100644
--- a/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts
+++ b/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts
@@ -16,6 +16,7 @@ vi.mock('@/store/chat/utils/desktopNotification', () => ({
const TEST_IDS = {
ASSISTANT_MESSAGE_ID: 'test-assistant-id',
OPERATION_ID: 'test-operation-id',
+ PARENT_OPERATION_ID: 'test-parent-operation-id',
TMP_ASSISTANT_ID: 'tmp-assistant-id',
} as const;
@@ -67,6 +68,7 @@ describe('runAgent actions', () => {
act(() => {
useChatStore.setState({
internal_dispatchMessage: vi.fn(),
+ completeOperation: vi.fn(),
optimisticUpdateMessageContent: vi.fn(),
refreshMessages: vi.fn(),
updateOperationMetadata: vi.fn(),
@@ -489,6 +491,84 @@ describe('runAgent actions', () => {
});
});
+ describe('visible_output_end event', () => {
+ it('clears visible loading without completing the operation', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const event: StreamEvent = {
+ data: { reason: 'completed' },
+ operationId: TEST_IDS.OPERATION_ID,
+ stepIndex: 1,
+ timestamp: Date.now(),
+ type: 'visible_output_end',
+ };
+
+ await act(async () => {
+ await result.current.internal_handleAgentStreamEvent(
+ TEST_IDS.OPERATION_ID,
+ event,
+ createStreamingContext({ assistantId: TEST_IDS.ASSISTANT_MESSAGE_ID }),
+ );
+ });
+
+ expect(result.current.updateOperationMetadata).toHaveBeenCalledWith(TEST_IDS.OPERATION_ID, {
+ visibleLoadingDone: true,
+ });
+ expect(result.current.completeOperation).not.toHaveBeenCalled();
+ });
+
+ it('also clears the parent server runtime visible loading for group SSE streams', async () => {
+ act(() => {
+ useChatStore.setState({
+ operations: {
+ [TEST_IDS.PARENT_OPERATION_ID]: {
+ abortController: new AbortController(),
+ context: { agentId: 'agent-1', groupId: 'group-1', topicId: 'topic-1' },
+ id: TEST_IDS.PARENT_OPERATION_ID,
+ metadata: { lastEventId: '0', startTime: Date.now(), stepCount: 0 },
+ status: 'running',
+ type: 'execServerAgentRuntime',
+ },
+ [TEST_IDS.OPERATION_ID]: {
+ abortController: new AbortController(),
+ context: { agentId: 'agent-1', groupId: 'group-1', topicId: 'topic-1' },
+ id: TEST_IDS.OPERATION_ID,
+ metadata: { lastEventId: '0', startTime: Date.now(), stepCount: 0 },
+ parentOperationId: TEST_IDS.PARENT_OPERATION_ID,
+ status: 'running',
+ type: 'groupAgentStream',
+ },
+ },
+ });
+ });
+
+ const { result } = renderHook(() => useChatStore());
+ const event: StreamEvent = {
+ data: { reason: 'completed' },
+ operationId: TEST_IDS.OPERATION_ID,
+ stepIndex: 1,
+ timestamp: Date.now(),
+ type: 'visible_output_end',
+ };
+
+ await act(async () => {
+ await result.current.internal_handleAgentStreamEvent(
+ TEST_IDS.OPERATION_ID,
+ event,
+ createStreamingContext({ assistantId: TEST_IDS.ASSISTANT_MESSAGE_ID }),
+ );
+ });
+
+ expect(result.current.updateOperationMetadata).toHaveBeenCalledWith(TEST_IDS.OPERATION_ID, {
+ visibleLoadingDone: true,
+ });
+ expect(result.current.updateOperationMetadata).toHaveBeenCalledWith(
+ TEST_IDS.PARENT_OPERATION_ID,
+ { visibleLoadingDone: true },
+ );
+ expect(result.current.completeOperation).not.toHaveBeenCalled();
+ });
+ });
+
describe('step_complete event', () => {
// The previous DB-refetch on tool_execution was the source of the
// assistantGroup-clobber regression β€” tool results are
diff --git a/src/store/chat/slices/aiAgent/actions/runAgent.ts b/src/store/chat/slices/aiAgent/actions/runAgent.ts
index e188a66b9e5..353b92d11a5 100644
--- a/src/store/chat/slices/aiAgent/actions/runAgent.ts
+++ b/src/store/chat/slices/aiAgent/actions/runAgent.ts
@@ -264,6 +264,19 @@ export class AgentActionImpl {
break;
}
+ case 'visible_output_end': {
+ // Example: no-tool answers can finish visible text several seconds
+ // before agent_runtime_end reconciles cache, queue, unread, and
+ // notification side effects. Retire only visible loading here.
+ this.#get().updateOperationMetadata(operationId, { visibleLoadingDone: true });
+ if (operation.parentOperationId) {
+ this.#get().updateOperationMetadata(operation.parentOperationId, {
+ visibleLoadingDone: true,
+ });
+ }
+ break;
+ }
+
case 'step_start': {
const { phase, toolCall, pendingToolsCalling, requiresApproval, uiMessages } =
event.data || {};
diff --git a/src/store/chat/slices/operation/__tests__/selectors.test.ts b/src/store/chat/slices/operation/__tests__/selectors.test.ts
index 19ab9d8fb03..8c6b117adab 100644
--- a/src/store/chat/slices/operation/__tests__/selectors.test.ts
+++ b/src/store/chat/slices/operation/__tests__/selectors.test.ts
@@ -575,6 +575,66 @@ describe('Operation Selectors', () => {
});
});
+ describe('visible loading selectors', () => {
+ it('should hide a no-tool terminal tail without unblocking the operation', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ useChatStore.setState({ activeAgentId: 'agent1', activeTopicId: 'topic1' });
+
+ result.current.startOperation({
+ type: 'execAgentRuntime',
+ context: { agentId: 'agent1', topicId: 'topic1' },
+ metadata: { startTime: 1000, visibleLoadingDone: true },
+ });
+ });
+
+ const context = { agentId: 'agent1', topicId: 'topic1' };
+
+ expect(operationSelectors.isAgentRunning('agent1')(result.current)).toBe(true);
+ expect(operationSelectors.isAgentRuntimeRunning(result.current)).toBe(true);
+ expect(operationSelectors.isMainWindowAgentRuntimeRunning(result.current)).toBe(true);
+ expect(operationSelectors.isAgentRuntimeRunningByContext(context)(result.current)).toBe(true);
+ expect(operationSelectors.isInputLoadingByContext(context)(result.current)).toBe(true);
+ expect(operationSelectors.canSendMessage(result.current)).toBe(false);
+
+ expect(operationSelectors.isAgentVisiblyRunning('agent1')(result.current)).toBe(false);
+ expect(operationSelectors.isAgentRuntimeVisiblyRunning(result.current)).toBe(false);
+ expect(operationSelectors.isMainWindowAgentRuntimeVisiblyRunning(result.current)).toBe(false);
+ expect(
+ operationSelectors.isAgentRuntimeVisiblyRunningByContext(context)(result.current),
+ ).toBe(false);
+ expect(operationSelectors.isInputVisiblyLoadingByContext(context)(result.current)).toBe(
+ false,
+ );
+ expect(
+ operationSelectors.getVisibleAgentRuntimeStartTimeByContext(context)(result.current),
+ ).toBeUndefined();
+ });
+
+ it('should keep visible loading for a normal running runtime operation', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ result.current.startOperation({
+ type: 'execAgentRuntime',
+ context: { agentId: 'agent1', topicId: 'topic1' },
+ metadata: { startTime: 1000 },
+ });
+ });
+
+ const context = { agentId: 'agent1', topicId: 'topic1' };
+
+ expect(
+ operationSelectors.isAgentRuntimeVisiblyRunningByContext(context)(result.current),
+ ).toBe(true);
+ expect(operationSelectors.isInputVisiblyLoadingByContext(context)(result.current)).toBe(true);
+ expect(
+ operationSelectors.getVisibleAgentRuntimeStartTimeByContext(context)(result.current),
+ ).toBe(1000);
+ });
+ });
+
describe('getRunningToolCallStartTime', () => {
it('should prefer the running executeToolCall start time', () => {
const { result } = renderHook(() => useChatStore());
diff --git a/src/store/chat/slices/operation/selectors.ts b/src/store/chat/slices/operation/selectors.ts
index 4d1417b0271..95f19e55097 100644
--- a/src/store/chat/slices/operation/selectors.ts
+++ b/src/store/chat/slices/operation/selectors.ts
@@ -32,6 +32,12 @@ const getRunningOperations = (s: ChatStoreState): Operation[] => {
return Object.values(s.operations).filter((op) => op.status === 'running');
};
+const isRunningOperation = (op: Operation): boolean =>
+ op.status === 'running' && !op.metadata.isAborting;
+
+const isVisiblyRunningOperation = (op: Operation): boolean =>
+ isRunningOperation(op) && !op.metadata.visibleLoadingDone;
+
/**
* Get operation by ID
*/
@@ -221,6 +227,23 @@ const isAgentRuntimeRunningByContext =
);
};
+/**
+ * Check if agent runtime should still show visible loading in a specific context.
+ * The underlying operation may remain running for terminal bookkeeping after a
+ * producer has emitted visible_output_end.
+ */
+const isAgentRuntimeVisiblyRunningByContext =
+ (context: MessageMapKeyInput) =>
+ (s: ChatStoreState): boolean => {
+ if (!context.agentId) return false;
+
+ const operations = getOperationsByContext(context)(s);
+
+ return operations.some(
+ (op) => AI_RUNTIME_OPERATION_TYPES.includes(op.type) && isVisiblyRunningOperation(op),
+ );
+ };
+
/**
* Get the earliest start time for a running agent runtime operation in a
* specific context. This anchors visible elapsed-time UI to the top-level
@@ -252,6 +275,31 @@ const getAgentRuntimeStartTimeByContext =
return startTime;
};
+/**
+ * Get the earliest start time for a visibly running agent runtime operation.
+ */
+const getVisibleAgentRuntimeStartTimeByContext =
+ (context: MessageMapKeyInput) =>
+ (s: ChatStoreState): number | undefined => {
+ if (!context.agentId) return undefined;
+
+ const operations = getOperationsByContext(context)(s);
+ let startTime: number | undefined;
+
+ for (const op of operations) {
+ if (!AI_RUNTIME_OPERATION_TYPES.includes(op.type) || !isVisiblyRunningOperation(op)) {
+ continue;
+ }
+
+ startTime =
+ startTime === undefined
+ ? op.metadata.startTime
+ : Math.min(startTime, op.metadata.startTime);
+ }
+
+ return startTime;
+ };
+
/**
* Check if input should show loading state in a specific context
* Includes sendMessage in addition to AI runtime operations,
@@ -272,6 +320,21 @@ const isInputLoadingByContext =
);
};
+/**
+ * Check if input should show visible loading state in a specific context.
+ */
+const isInputVisiblyLoadingByContext =
+ (context: MessageMapKeyInput) =>
+ (s: ChatStoreState): boolean => {
+ if (!context.agentId) return false;
+
+ const operations = getOperationsByContext(context)(s);
+
+ return operations.some(
+ (op) => INPUT_LOADING_OPERATION_TYPES.includes(op.type) && isVisiblyRunningOperation(op),
+ );
+ };
+
// === Backward Compatibility ===
/**
@@ -285,9 +348,24 @@ const isAgentRunning =
const operationIds = s.operationsByType[type] || [];
const hasRunning = operationIds.some((id) => {
const op = s.operations[id];
- return (
- op && op.status === 'running' && !op.metadata.isAborting && op.context.agentId === agentId
- );
+ return op && isRunningOperation(op) && op.context.agentId === agentId;
+ });
+ if (hasRunning) return true;
+ }
+ return false;
+ };
+
+/**
+ * Check if a specific agent should still show visible runtime loading.
+ */
+const isAgentVisiblyRunning =
+ (agentId: string) =>
+ (s: ChatStoreState): boolean => {
+ for (const type of AI_RUNTIME_OPERATION_TYPES) {
+ const operationIds = s.operationsByType[type] || [];
+ const hasRunning = operationIds.some((id) => {
+ const op = s.operations[id];
+ return op && isVisiblyRunningOperation(op) && op.context.agentId === agentId;
});
if (hasRunning) return true;
}
@@ -306,7 +384,22 @@ const isAgentRuntimeRunning = (s: ChatStoreState): boolean => {
const hasRunning = operationIds.some((id) => {
const op = s.operations[id];
// Exclude operations that are aborting (user already cancelled, just cleaning up)
- return op && op.status === 'running' && !op.metadata.isAborting;
+ return op && isRunningOperation(op);
+ });
+ if (hasRunning) return true;
+ }
+ return false;
+};
+
+/**
+ * Check if any AI runtime operation should still show visible loading.
+ */
+const isAgentRuntimeVisiblyRunning = (s: ChatStoreState): boolean => {
+ for (const type of AI_RUNTIME_OPERATION_TYPES) {
+ const operationIds = s.operationsByType[type] || [];
+ const hasRunning = operationIds.some((id) => {
+ const op = s.operations[id];
+ return op && isVisiblyRunningOperation(op);
});
if (hasRunning) return true;
}
@@ -325,7 +418,7 @@ const isMainWindowAgentRuntimeRunning = (s: ChatStoreState): boolean => {
const hasRunning = operationIds.some((id) => {
const op = s.operations[id];
- if (!op || op.status !== 'running' || op.metadata.isAborting || op.metadata.inThread) {
+ if (!op || !isRunningOperation(op) || op.metadata.inThread) {
return false;
}
@@ -352,6 +445,37 @@ const isMainWindowAgentRuntimeRunning = (s: ChatStoreState): boolean => {
return false;
};
+/**
+ * Check if a main-window AI runtime operation should still show visible loading.
+ */
+const isMainWindowAgentRuntimeVisiblyRunning = (s: ChatStoreState): boolean => {
+ for (const type of AI_RUNTIME_OPERATION_TYPES) {
+ const operationIds = s.operationsByType[type] || [];
+
+ const hasRunning = operationIds.some((id) => {
+ const op = s.operations[id];
+ if (!op || !isVisiblyRunningOperation(op) || op.metadata.inThread) {
+ return false;
+ }
+
+ if (op.context.groupId) {
+ return s.activeGroupId === op.context.groupId;
+ }
+
+ if (s.activeAgentId !== op.context.agentId) return false;
+
+ const activeTopicId = s.activeTopicId ?? null;
+ const opTopicId = op.context.topicId ?? null;
+
+ return activeTopicId === opTopicId;
+ });
+
+ if (hasRunning) return true;
+ }
+
+ return false;
+};
+
/**
* Check if continuing (for backward compatibility)
*/
@@ -661,6 +785,7 @@ export const operationSelectors = {
getCurrentOperationLabel,
getCurrentOperationProgress,
getDeepestRunningOperationByMessage,
+ getVisibleAgentRuntimeStartTimeByContext,
getOperationById,
getOperationContextFromMessage,
getAgentRuntimeStartTimeByContext,
@@ -680,14 +805,19 @@ export const operationSelectors = {
isAborting,
isAgentRunning,
+ isAgentVisiblyRunning,
isAgentRuntimeRunning,
+ isAgentRuntimeVisiblyRunning,
isAgentUnreadCompleted,
isAgentRuntimeRunningByContext,
+ isAgentRuntimeVisiblyRunningByContext,
isInputLoadingByContext,
+ isInputVisiblyLoadingByContext,
isAnyMessageLoading,
isContinuing,
isInSearchWorkflow,
isMainWindowAgentRuntimeRunning,
+ isMainWindowAgentRuntimeVisiblyRunning,
isMessageAborting,
isMessageContinuing,
isMessageCreating,
diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.ts
index 4e3ac7c2cfd..26fca6bb9f9 100644
--- a/src/store/chat/slices/operation/types.ts
+++ b/src/store/chat/slices/operation/types.ts
@@ -149,12 +149,18 @@ export interface OperationMetadata {
total: number;
percentage?: number;
};
-
// Runtime hooks (collected during execution, executed after completion)
runtimeHooks?: RuntimeHooks;
// Performance information
startTime: number;
+
+ /**
+ * The model text stream has finished and there is no visible follow-up phase
+ * to wait for, but the runtime operation still needs its terminal lifecycle
+ * (`agent_runtime_end`) for cache, queue, unread, and notification effects.
+ */
+ visibleLoadingDone?: boolean;
}
/**