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(task): reconcile terminal runs to stop stale timers (#20559)

AmAzing-60334f2bd677
diff --git a/src/store/chat/slices/agentRun/actions/index.ts b/src/store/chat/slices/agentRun/actions/index.ts
index 5786ada0caa..f570b8e0b56 100644
--- a/src/store/chat/slices/agentRun/actions/index.ts
+++ b/src/store/chat/slices/agentRun/actions/index.ts
@@ -11,6 +11,10 @@ import {
type QuestionSubmissionAction,
QuestionSubmissionActionImpl,
} from './entries/questionSubmission';
+import {
+ type ServerOperationReconciliationAction,
+ ServerOperationReconciliationActionImpl,
+} from './state/serverOperationReconciliation';
import { type StreamingStatesAction } from './state/streamingStates';
import { StreamingStatesActionImpl } from './state/streamingStates';
import { type ClientToolExecutionAction } from './transports/client/clientToolExecution';
@@ -25,6 +29,7 @@ export type ChatAgentRunAction = ClientToolExecutionAction &
ConversationControlAction &
QuestionSubmissionAction &
GatewayAction &
+ ServerOperationReconciliationAction &
StreamingExecutorAction &
StreamingStatesAction;
@@ -44,6 +49,7 @@ export const chatAgentRun: StateCreator<
new ConversationControlActionImpl(...params),
new QuestionSubmissionActionImpl(...params),
new GatewayActionImpl(...params),
+ new ServerOperationReconciliationActionImpl(...params),
new StreamingExecutorActionImpl(...params),
new StreamingStatesActionImpl(...params),
]);
diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts
index bd4c4a4ec4a..be61a5575f2 100644
--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts
@@ -53,8 +53,10 @@ const makeStore = (afterCompletionCallbacks?: Array<() => void>) => {
internal_updateTopic: vi.fn(),
markTopicUnread: vi.fn(),
messagesMap: {},
+ operationsByContext: { [messageMapKey(CONTEXT)]: [OP] },
operations: {
[OP]: {
+ id: OP,
context: CONTEXT,
metadata: afterCompletionCallbacks ? { runtimeHooks: { afterCompletionCallbacks } } : {},
status: 'running',
diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts
index 74e9b5ad527..af0ef1c5bf8 100644
--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts
@@ -19,12 +19,9 @@ import { markdownToTxt } from '@/utils/markdownToTxt';
import { messageMapKey } from '../../../../utils/messageMapKey';
import { displayMessageSelectors } from '../../../message/selectors/displayMessage';
import type { OperationStatus } from '../../../operation/types';
-import {
- AI_RUNTIME_OPERATION_TYPES,
- mergeQueuedMessages,
- reconstructUploadFilesFromQueue,
-} from '../../../operation/types';
+import { AI_RUNTIME_OPERATION_TYPES } from '../../../operation/types';
import { topicSelectors } from '../../../topic/selectors';
+import { scheduleQueuedFollowUp } from './queuedFollowUp';
import type {
AgentRunLifecycle,
RunCompleteEvent,
@@ -283,6 +280,7 @@ export const buildRunLifecycle = (
}
},
afterRunComplete: async (event: RunCompleteEvent) => {
+ if (get().operations[event.operationId]?.metadata.terminalReconciled) return;
if (adapter.runScope === 'sub_agent' || resolveTerminalDisposition(event) !== 'success')
return;
@@ -352,6 +350,7 @@ export const buildRunLifecycle = (
beforeRunComplete: NOOP,
completeRun: async (event: RunCompleteEvent): Promise<RunCompleteResult> => {
const { operationId, runtimeStatus } = event;
+ if (get().operations[operationId]?.metadata.terminalReconciled) return { requeued: false };
// Effective terminal disposition, resolved from the client `runtimeStatus`
// OR the normalized `status` gateway/hetero pass β€” so the same side effects
// fire regardless of which transport reached this boundary.
@@ -433,6 +432,9 @@ export const buildRunLifecycle = (
}
}
+ // A server snapshot may have settled the run while a callback awaited IO.
+ if (get().operations[operationId]?.metadata.terminalReconciled) return { requeued: false };
+
// 2. On success with queued messages: drain, complete, and re-trigger a new
// sendMessage. Only drain on success β€” on error the queue is preserved.
// Gated to TOP-LEVEL runs only: the input queue belongs to the parent
@@ -446,43 +448,7 @@ export const buildRunLifecycle = (
completeSuccess();
emitComplete(operationId, runtimeStatus);
- const execContext = { ...context };
-
- // Drain only when the send takes the queue: until then the tray and
- // the composer's busy state keep covering the hand-off window.
- setTimeout(() => {
- const remainingQueued = get().drainQueuedMessages(contextKey);
- if (remainingQueued.length === 0) {
- resetActiveTopicRunningStatus();
- return;
- }
-
- const merged = mergeQueuedMessages(remainingQueued);
- const mergedFiles =
- merged.filesPreview.length > 0
- ? reconstructUploadFilesFromQueue(merged.filesPreview)
- : merged.files.length > 0
- ? (merged.files.map((id) => ({ id })) as any)
- : undefined;
-
- // Use the passed `get` (the live chat-store getter) rather than a
- // direct `useChatStore` import: in prod they resolve to the same
- // singleton sendMessage, and avoiding the value import keeps the chat
- // store out of this module's graph β€” so gateway.ts can statically
- // import buildRunLifecycle without re-entering the store mid-eval.
- get()
- .sendMessage({
- context: execContext,
- editorData: merged.editorData,
- files: mergedFiles,
- ...(merged.forceRuntime ? { forceRuntime: merged.forceRuntime } : {}),
- message: merged.content,
- metadata: { ...merged.metadata, steer: true },
- })
- .catch((e: unknown) => {
- console.error('[executeClientAgent] sendMessage for queued content failed:', e);
- });
- }, 100);
+ scheduleQueuedFollowUp(get, context, operationId, resetActiveTopicRunningStatus);
return { requeued: true };
}
diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/queuedFollowUp.ts b/src/store/chat/slices/agentRun/actions/lifecycle/queuedFollowUp.ts
new file mode 100644
index 00000000000..a2ace09d87f
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/lifecycle/queuedFollowUp.ts
@@ -0,0 +1,52 @@
+import type { ConversationContext, UploadFileItem } from '@lobechat/types';
+
+import { operationSelectors } from '@/store/chat/slices/operation/selectors';
+import {
+ mergeQueuedMessages,
+ reconstructUploadFilesFromQueue,
+} from '@/store/chat/slices/operation/types';
+import type { ChatStore } from '@/store/chat/store';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+/** Shared by streamed completion and recovery from a server terminal snapshot. */
+export const scheduleQueuedFollowUp = (
+ get: () => ChatStore,
+ context: ConversationContext,
+ operationId: string,
+ onEmpty?: () => void,
+): void => {
+ const contextKey = messageMapKey(context);
+ const execContext = { ...context };
+
+ // Keep the queue visible until the send takes ownership of it. Recheck the
+ // owner at that point: a user can start another turn during this hand-off.
+ setTimeout(() => {
+ if (operationSelectors.hasNewerConversationOperation(operationId, context)(get())) return;
+ const remainingQueued = get().drainQueuedMessages(contextKey);
+ if (remainingQueued.length === 0) {
+ onEmpty?.();
+ return;
+ }
+
+ const merged = mergeQueuedMessages(remainingQueued);
+ const mergedFiles =
+ merged.filesPreview.length > 0
+ ? reconstructUploadFilesFromQueue(merged.filesPreview)
+ : merged.files.length > 0
+ ? (merged.files.map((id) => ({ id })) as UploadFileItem[])
+ : undefined;
+
+ get()
+ .sendMessage({
+ context: execContext,
+ editorData: merged.editorData,
+ files: mergedFiles,
+ ...(merged.forceRuntime ? { forceRuntime: merged.forceRuntime } : {}),
+ message: merged.content,
+ metadata: { ...merged.metadata, steer: true },
+ })
+ .catch((error: unknown) => {
+ console.error('[executeClientAgent] sendMessage for queued content failed:', error);
+ });
+ }, 100);
+};
diff --git a/src/store/chat/slices/agentRun/actions/state/serverOperationReconciliation.ts b/src/store/chat/slices/agentRun/actions/state/serverOperationReconciliation.ts
new file mode 100644
index 00000000000..6171c2f5538
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/state/serverOperationReconciliation.ts
@@ -0,0 +1,100 @@
+import type { ConversationContext } from '@lobechat/types';
+import { produce } from 'immer';
+
+import { operationSelectors } from '@/store/chat/slices/operation/selectors';
+import type { Operation, OperationStatus } from '@/store/chat/slices/operation/types';
+import type { ChatStore } from '@/store/chat/store';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+import type { StoreSetter } from '@/store/types';
+
+import { scheduleQueuedFollowUp } from '../lifecycle/queuedFollowUp';
+
+const isUnsettled = (operation: Operation) =>
+ operation.status === 'running' || operation.status === 'pending' || operation.status === 'paused';
+
+export class ServerOperationReconciliationActionImpl {
+ readonly #get: () => ChatStore;
+ readonly #set: StoreSetter<ChatStore>;
+
+ constructor(set: StoreSetter<ChatStore>, get: () => ChatStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ /**
+ * A persisted terminal snapshot can outlive its Gateway completion event.
+ * Retire only that server run's local operations; never interrupt the server
+ * or replay notifications, tool callbacks, or topic-status writes.
+ */
+ reconcileServerOperation = (params: {
+ operationId: string;
+ status: Extract<OperationStatus, 'completed' | 'cancelled' | 'failed'>;
+ topicId: string;
+ }): void => {
+ const state = this.#get();
+ const roots = Object.values(state.operations).filter(
+ (op) =>
+ op.type === 'execServerAgentRuntime' &&
+ op.context.topicId === params.topicId &&
+ op.metadata.serverOperationId === params.operationId,
+ );
+ if (roots.length === 0) return;
+
+ const owned = new Set(roots.map((op) => op.id));
+ const visit = (id: string) => {
+ for (const child of state.operations[id]?.childOperationIds ?? []) {
+ if (owned.has(child)) continue;
+ owned.add(child);
+ visit(child);
+ }
+ };
+ roots.forEach((op) => visit(op.id));
+ if (![...owned].some((id) => state.operations[id] && isUnsettled(state.operations[id]))) return;
+
+ const now = Date.now();
+ this.#set(
+ produce((draft: ChatStore) => {
+ for (const id of owned) {
+ const op = draft.operations[id];
+ if (!op || !isUnsettled(op)) continue;
+ op.status = params.status;
+ op.metadata.terminalReconciled = true;
+ op.metadata.endTime = now;
+ op.metadata.duration = now - op.metadata.startTime;
+ }
+ // Streaming tool indicators are keyed by assistant message, separately
+ // from the operation tree. Do not clear an indicator a newer run owns.
+ for (const [messageId, operationId] of Object.entries(draft.messageOperationMap)) {
+ if (owned.has(operationId)) delete draft.toolCallingStreamIds[messageId];
+ }
+ }),
+ false,
+ 'reconcileServerOperation',
+ );
+
+ if (params.status !== 'completed') return;
+ const scheduled = new Set<string>();
+ for (const root of roots) {
+ // A completed root may still have stale children; do not drain its queue
+ // twice when only those children needed repair.
+ if (!isUnsettled(root) || !root.context.agentId || root.context.scope === 'sub_agent')
+ continue;
+ const context = root.context as ConversationContext;
+ const key = messageMapKey(context);
+ if (
+ scheduled.has(key) ||
+ !state.queuedMessages[key]?.length ||
+ operationSelectors.hasNewerConversationOperation(root.id, context)(this.#get())
+ )
+ continue;
+ scheduled.add(key);
+ scheduleQueuedFollowUp(this.#get, context, root.id);
+ }
+ };
+}
+
+export type ServerOperationReconciliationAction = Pick<
+ ServerOperationReconciliationActionImpl,
+ keyof ServerOperationReconciliationActionImpl
+>;
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index 0fd5700c12b..8194845a3c3 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -1778,6 +1778,10 @@ export class GatewayActionImpl {
throw error;
}
+ // A task-detail refresh may have confirmed this run ended during token IO.
+ // Do not attach a fresh stream after its local operation was reconciled.
+ if (this.#get().operations?.[gatewayOpId]?.metadata.terminalReconciled) return;
+
// Re-check after the async token refresh: a newer executeGatewayAgent call may have
// taken over for this topic while we were waiting. If so, bail to avoid a duplicate stream.
// (disconnectFromGateway on the stale op is a no-op here because we haven't connected yet.)
diff --git a/src/store/chat/slices/operation/actions.ts b/src/store/chat/slices/operation/actions.ts
index c2ce61ab453..dc27f658751 100644
--- a/src/store/chat/slices/operation/actions.ts
+++ b/src/store/chat/slices/operation/actions.ts
@@ -281,6 +281,9 @@ export class OperationActionsImpl {
completeOperation = (operationId: string, metadata?: Partial<OperationMetadata>): void => {
const operation = this.#get().operations[operationId];
+ // Late stream/session callbacks cannot overwrite the persisted terminal
+ // outcome (or reset its duration) after snapshot reconciliation.
+ if (operation?.metadata.terminalReconciled) return;
if (operation) {
log(
'[completeOperation] operation %s (type=%s) completed, duration=%dms',
@@ -524,6 +527,7 @@ export class OperationActionsImpl {
error: { code?: string; details?: any; message: string; type: string },
): void => {
const operation = this.#get().operations[operationId];
+ if (operation?.metadata.terminalReconciled) return;
if (operation) {
log(
'[failOperation] operation %s (type=%s) failed: %s',
diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.ts
index 01229b7e039..5b1b587dcbc 100644
--- a/src/store/chat/slices/operation/types.ts
+++ b/src/store/chat/slices/operation/types.ts
@@ -171,6 +171,9 @@ export interface OperationMetadata {
*/
streamRetry?: StreamRetryMetadata;
+ /** A persisted server terminal snapshot already retired this local operation. */
+ terminalReconciled?: boolean;
+
/**
* Start of the turn a steered run continues. Elapsed timers count from here so
* a queued follow-up reads as one continuous turn; inherited by child operations.
diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.ts
index a66467b0047..ea177f002bb 100644
--- a/src/store/task/slices/detail/action.ts
+++ b/src/store/task/slices/detail/action.ts
@@ -278,6 +278,32 @@ export class TaskDetailSliceActionImpl {
);
}
+ // Reconcile at the server-read boundary, even when the live chat panel has
+ // unmounted. A missing running marker alone is not proof of completion.
+ const terminalActivities = detail.activities?.filter(
+ (activity) =>
+ activity.type === 'topic' &&
+ activity.id &&
+ activity.operationId &&
+ ['completed', 'failed', 'canceled', 'timeout'].includes(activity.status ?? '') &&
+ activity.runningOperation?.operationId !== activity.operationId,
+ );
+ if (terminalActivities?.length) {
+ const { getChatStoreState } = await import('@/store/chat');
+ for (const activity of terminalActivities) {
+ getChatStoreState().reconcileServerOperation({
+ operationId: activity.operationId!,
+ status:
+ activity.status === 'completed'
+ ? 'completed'
+ : activity.status === 'canceled'
+ ? 'cancelled'
+ : 'failed',
+ topicId: activity.id!,
+ });
+ }
+ }
+
return detail;
};
diff --git a/src/store/task/slices/detail/runReconciliation.test.ts b/src/store/task/slices/detail/runReconciliation.test.ts
new file mode 100644
index 00000000000..f00286f7681
--- /dev/null
+++ b/src/store/task/slices/detail/runReconciliation.test.ts
@@ -0,0 +1,247 @@
+import type { TaskDetailActivity, TaskDetailData } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { aiAgentService } from '@/services/aiAgent';
+import { taskService } from '@/services/task';
+import { useChatStore } from '@/store/chat';
+import { buildRunLifecycle } from '@/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle';
+import { initialOperationState } from '@/store/chat/slices/operation/initialState';
+import { operationSelectors } from '@/store/chat/slices/operation/selectors';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+import { createServerConfigStore } from '@/store/serverConfig/store';
+import { useTaskStore } from '@/store/task';
+
+const context = { agentId: 'agent-1', scope: 'main' as const, topicId: 'topic-1' };
+const marker = { assistantMessageId: 'assistant-1', heteroType: null, operationId: 'server-1' };
+const completedAt = '2026-10-08T13:45:12.419Z';
+const visiblyRunning = () =>
+ operationSelectors.isAgentRuntimeVisiblyRunningByContext(context)(useChatStore.getState());
+
+const fetchDetail = async (activity: Partial<TaskDetailActivity> = {}) => {
+ vi.mocked(taskService.getDetail).mockResolvedValue({
+ data: {
+ activities: [
+ {
+ completedAt,
+ id: context.topicId,
+ operationId: marker.operationId,
+ runningOperation: null,
+ status: 'completed',
+ type: 'topic',
+ ...activity,
+ },
+ ],
+ identifier: 'T-3',
+ status: 'scheduled',
+ } as TaskDetailData,
+ success: true,
+ });
+ await useTaskStore.getState().fetchTaskDetail('T-3');
+};
+
+describe('task run terminal reconciliation', () => {
+ beforeEach(() => {
+ useChatStore.setState({
+ ...initialOperationState,
+ activeAgentId: context.agentId,
+ activeTopicId: context.topicId,
+ gatewayConnections: {},
+ messagesMap: {},
+ topicDataMap: {},
+ toolCallingStreamIds: {},
+ });
+ useTaskStore.setState({ taskDetailMap: {} });
+ const server = createServerConfigStore();
+ server.setState({
+ serverConfig: {
+ ...server.getState().serverConfig,
+ agentGatewayUrl: 'https://gateway.invalid',
+ },
+ });
+ vi.spyOn(aiAgentService, 'refreshGatewayToken').mockResolvedValue({ token: 'test-token' });
+ vi.spyOn(aiAgentService, 'interruptTask').mockRejectedValue(new Error('must not interrupt'));
+ vi.spyOn(taskService, 'getDetail');
+ // Drop all socket events, including the terminal frame. Reconnect and both
+ // stores remain real: the detail response must retire the stranded runtime.
+ vi.spyOn(useChatStore.getState(), 'connectToGateway').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ const reconnect = async () => {
+ await useChatStore.getState().reconnectToGatewayOperation({ ...marker, ...context });
+ return Object.values(useChatStore.getState().operations).find(
+ (op) => op.metadata.serverOperationId === marker.operationId,
+ )!;
+ };
+
+ it('ends the timer and owned loading after a completed detail response without a socket terminal', async () => {
+ const root = await reconnect();
+ const { operationId: childId } = useChatStore
+ .getState()
+ .startOperation({ parentOperationId: root.id, type: 'reasoning' });
+ expect(visiblyRunning()).toBe(true);
+
+ await fetchDetail();
+
+ expect(visiblyRunning()).toBe(false);
+ expect(useChatStore.getState().operations[root.id].status).toBe('completed');
+ expect(useChatStore.getState().operations[childId].status).toBe('completed');
+ expect(root.abortController.signal.aborted).toBe(false);
+ expect(aiAgentService.interruptTask).not.toHaveBeenCalled();
+ });
+
+ it.each(['running', 'pending', 'waiting_for_human', undefined])(
+ 'does not infer completion from an absent marker (%s)',
+ async (status) => {
+ await reconnect();
+ await fetchDetail({ status });
+ expect(visiblyRunning()).toBe(true);
+ },
+ );
+
+ it('requires the completed run identity', async () => {
+ await reconnect();
+ await fetchDetail({ operationId: null });
+ expect(visiblyRunning()).toBe(true);
+ });
+
+ it('does not settle a contradictory snapshot that still marks the same run live', async () => {
+ await reconnect();
+ await fetchDetail({ runningOperation: marker });
+ expect(visiblyRunning()).toBe(true);
+ });
+
+ it('does not touch another topic or revive an already failed child', async () => {
+ const root = await reconnect();
+ const { operationId: childId } = useChatStore
+ .getState()
+ .startOperation({ parentOperationId: root.id, type: 'reasoning' });
+ useChatStore.getState().failOperation(childId, { message: 'existing failure', type: 'test' });
+ const { operationId: otherId } = useChatStore.getState().startOperation({
+ context: { ...context, topicId: 'other-topic' },
+ metadata: { serverOperationId: marker.operationId },
+ type: 'execServerAgentRuntime',
+ });
+ await fetchDetail();
+ expect(useChatStore.getState().operations[otherId].status).toBe('running');
+ expect(useChatStore.getState().operations[childId].status).toBe('failed');
+ expect(visiblyRunning()).toBe(false);
+ });
+
+ it('leaves a successor and its queued input alone when an older run finishes', async () => {
+ const old = await reconnect();
+ const { operationId: next } = useChatStore.getState().startOperation({
+ context,
+ metadata: { serverOperationId: 'server-2' },
+ type: 'execServerAgentRuntime',
+ });
+ useChatStore.getState().enqueueMessage(messageMapKey(context), {
+ content: 'for the new run',
+ createdAt: Date.now(),
+ id: 'queued-new',
+ interruptMode: 'hard',
+ });
+ await fetchDetail();
+ expect(useChatStore.getState().operations[old.id].status).toBe('completed');
+ expect(useChatStore.getState().operations[next].status).toBe('running');
+ expect(visiblyRunning()).toBe(true);
+ expect(useChatStore.getState().queuedMessages[messageMapKey(context)]).toHaveLength(1);
+ });
+
+ it.each([
+ ['failed', 'failed'],
+ ['timeout', 'failed'],
+ ['canceled', 'cancelled'],
+ ])('preserves a %s outcome', async (status, expected) => {
+ const root = await reconnect();
+ await fetchDetail({ status });
+ expect(useChatStore.getState().operations[root.id].status).toBe(expected);
+ // Transport completion can still arrive after the authoritative read.
+ useChatStore.getState().completeOperation(root.id);
+ expect(useChatStore.getState().operations[root.id].status).toBe(expected);
+ expect(visiblyRunning()).toBe(false);
+ });
+
+ it('does not reconnect a run that finished while its token was refreshing', async () => {
+ let resolveToken!: (value: { token: string }) => void;
+ vi.mocked(aiAgentService.refreshGatewayToken).mockReturnValue(
+ new Promise((resolve) => {
+ resolveToken = resolve;
+ }),
+ );
+ const pending = useChatStore.getState().reconnectToGatewayOperation({ ...marker, ...context });
+ expect(visiblyRunning()).toBe(true);
+ await fetchDetail();
+ resolveToken({ token: 'late-token' });
+ await pending;
+ expect(visiblyRunning()).toBe(false);
+ expect(useChatStore.getState().connectToGateway).not.toHaveBeenCalled();
+ });
+
+ it('continues queued input once and ignores a late terminal lifecycle', async () => {
+ vi.useFakeTimers();
+ const root = await reconnect();
+ const send = vi.spyOn(useChatStore.getState(), 'sendMessage').mockResolvedValue(undefined);
+ const hook = vi.fn();
+ useChatStore
+ .getState()
+ .updateOperationMetadata(root.id, { runtimeHooks: { afterCompletionCallbacks: [hook] } });
+ useChatStore.getState().enqueueMessage(messageMapKey(context), {
+ content: 'queued follow-up',
+ createdAt: Date.now(),
+ id: 'queued-1',
+ interruptMode: 'hard',
+ });
+ await fetchDetail();
+ await fetchDetail();
+ await vi.advanceTimersByTimeAsync(100);
+ expect(send).toHaveBeenCalledOnce();
+ expect(useChatStore.getState().queuedMessages[messageMapKey(context)]).toHaveLength(0);
+
+ const lifecycle = buildRunLifecycle(useChatStore.getState, {
+ context,
+ parentMessageId: marker.assistantMessageId,
+ parentMessageType: 'assistant',
+ runId: root.id,
+ runScope: 'top_level',
+ runtimeType: 'gateway',
+ });
+ await lifecycle.completeRun({
+ context,
+ operationId: root.id,
+ runId: root.id,
+ runScope: 'top_level',
+ runtimeType: 'gateway',
+ status: 'completed',
+ });
+ expect(hook).not.toHaveBeenCalled();
+ expect(send).toHaveBeenCalledOnce();
+ });
+
+ it('keeps newly queued input with a successor started during the recovery hand-off', async () => {
+ vi.useFakeTimers();
+ await reconnect();
+ const send = vi.spyOn(useChatStore.getState(), 'sendMessage').mockResolvedValue(undefined);
+ const key = messageMapKey(context);
+ useChatStore.getState().enqueueMessage(key, {
+ content: 'follow up',
+ createdAt: Date.now(),
+ id: 'queued',
+ interruptMode: 'hard',
+ });
+ await fetchDetail();
+ useChatStore.getState().startOperation({
+ context,
+ metadata: { serverOperationId: 'server-next' },
+ type: 'execServerAgentRuntime',
+ });
+ await vi.advanceTimersByTimeAsync(100);
+ expect(send).not.toHaveBeenCalled();
+ expect(useChatStore.getState().queuedMessages[key]).toHaveLength(1);
+ expect(visiblyRunning()).toBe(true);
+ });
+});