π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(chat): let a message send once the run's visible output ends (#18230)
Arvin Xu485f890486b6
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex 990041e59bc..0d2484616ec 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -256,6 +256,8 @@ const ExecAgentSchema = zfileIds: z.array(z.string()).optional(),/** Parent message ID for regeneration/continue (skip user message creation, branch from this message) */parentMessageId: z.string().optional(),+ /** Existing gateway operation this fresh turn atomically supersedes. */+ replacesOperationId: z.string().optional(),/** The user input/prompt */prompt: z.string(),/**diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.tsindex 5794720ec3e..e5a3583c777 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts@@ -201,7 +201,11 @@ describe('AiAgentService.execAgent - user turn spine anchoring', () => {expect(userMessageCall()![0]).toMatchObject({ parentId: 'spine-head-1', role: 'user' });// No spine candidate is missing, so the fallback must not be queried.expect(mockGetLatestNonToolMessageId).not.toHaveBeenCalled();- expect(mockTryReserve).toHaveBeenCalledWith('topic-1', expect.stringMatching(/^agent-start-/));+ expect(mockTryReserve).toHaveBeenCalledWith(+ 'topic-1',+ expect.stringMatching(/^agent-start-/),+ undefined,+ );expect(mockReleaseReservation).toHaveBeenCalledWith('topic-1',expect.stringMatching(/^agent-start-/),diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex a284740651d..db9f88df76c 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -1255,6 +1255,7 @@ export class AiAgentService {const reservationId = params.topicStartReservationId ?? `agent-start-${nanoid()}`;const reserved = await acquireTopicStartReservation({+ replacesOperationId: params.replacesOperationId,reservationId,topicId,topicModel: this.topicModel,diff --git a/apps/server/src/services/aiAgent/topicStartReservation.test.ts b/apps/server/src/services/aiAgent/topicStartReservation.test.tsindex e47c8195117..f4fa4c2e732 100644--- a/apps/server/src/services/aiAgent/topicStartReservation.test.ts+++ b/apps/server/src/services/aiAgent/topicStartReservation.test.ts@@ -41,4 +41,18 @@ describe('acquireTopicStartReservation', () => {}),).resolves.toBe(false);});++ it('forwards the operation id used for an atomic topic handoff', async () => {+ const tryReserveTaskCallback = vi.fn().mockResolvedValue(true);+ const topicModel = { tryReserveTaskCallback } as unknown as TopicModel;++ await acquireTopicStartReservation({+ replacesOperationId: 'old-operation',+ reservationId: 'new-start',+ topicId: 'topic-1',+ topicModel,+ });++ expect(tryReserveTaskCallback).toHaveBeenCalledWith('topic-1', 'new-start', 'old-operation');+ });});diff --git a/apps/server/src/services/aiAgent/topicStartReservation.ts b/apps/server/src/services/aiAgent/topicStartReservation.tsindex 3ccd094d895..f0ce652ee9e 100644--- a/apps/server/src/services/aiAgent/topicStartReservation.ts+++ b/apps/server/src/services/aiAgent/topicStartReservation.ts@@ -18,16 +18,22 @@ const delay = (milliseconds: number): Promise<void> =>* 500 response, while interactive callers receive a finite busy failure.*/export const acquireTopicStartReservation = async ({+ replacesOperationId,reservationId,topicId,topicModel,}: {+ replacesOperationId?: string;reservationId: string;topicId: string;topicModel: TopicModel;}): Promise<boolean> => {for (let attempt = 0; attempt < MAX_RESERVATION_ATTEMPTS; attempt += 1) {- const reservation = await topicModel.tryReserveTaskCallback(topicId, reservationId);+ const reservation = await topicModel.tryReserveTaskCallback(+ topicId,+ reservationId,+ replacesOperationId,+ );if (reservation === null) return false;if (reservation) return true;diff --git a/packages/database/src/models/__tests__/topics/topic.update.test.ts b/packages/database/src/models/__tests__/topics/topic.update.test.tsindex 20b5e0f26aa..b09cd2474a9 100644--- a/packages/database/src/models/__tests__/topics/topic.update.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.update.test.ts@@ -170,6 +170,32 @@ describe('TopicModel - Update', () => {await expect(topicModel.tryReserveTaskCallback(topicId, 'callback-1')).resolves.toBe(true);});+ it('atomically hands a topic from the matching visible-finished operation to a new start', async () => {+ const topicId = 'topic-start-operation-handoff';+ await serverDB.insert(topics).values({+ userId,+ id: topicId,+ title: 'Test',+ metadata: {+ runningOperation: {+ assistantMessageId: 'assistant-1',+ operationId: 'old-operation',+ },+ },+ });++ await expect(+ topicModel.tryReserveTaskCallback(topicId, 'new-start', 'different-operation'),+ ).resolves.toBe(false);+ await expect(+ topicModel.tryReserveTaskCallback(topicId, 'new-start', 'old-operation'),+ ).resolves.toBe(true);++ const topic = await serverDB.query.topics.findFirst({ where: eq(topics.id, topicId) });+ expect(topic?.metadata?.runningOperation).toBeNull();+ expect(topic?.metadata?.taskCallbackReservation?.messageId).toBe('new-start');+ });+it('recovers a stale reservation left by a crashed delivery worker', async () => {const topicId = 'task-callback-stale-reservation';await serverDB.insert(topics).values({diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex ac73fdeca5f..06a2e503213 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -1426,7 +1426,11 @@ export class TopicModel {* callback can claim the topic, so the callback always re-anchors on the* completed turn's latest spine.*/- tryReserveTaskCallback = async (id: string, messageId: string): Promise<boolean | null> =>+ tryReserveTaskCallback = async (+ id: string,+ messageId: string,+ replacesOperationId?: string,+ ): Promise<boolean | null> =>this.db.transaction(async (tx) => {const [existing] = await tx.select({ metadata: topics.metadata })@@ -1444,13 +1448,17 @@ export class TopicModel {Date.now() - reservedAt < TASK_CALLBACK_RESERVATION_TTL_MS;if (reservation?.messageId === messageId && hasLiveReservation) return true;- if (existing.metadata?.runningOperation || hasLiveReservation) return false;+ const runningOperation = existing.metadata?.runningOperation;+ const canReplaceRunningOperation =+ !!replacesOperationId && runningOperation?.operationId === replacesOperationId;+ if ((runningOperation && !canReplaceRunningOperation) || hasLiveReservation) return false;await tx.update(topics).set({metadata: {...existing.metadata,+ ...(canReplaceRunningOperation && { runningOperation: null }),taskCallbackReservation: {messageId,reservedAt: new Date().toISOString(),diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex 97fe0cc7cb8..1274b7d18a8 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -230,6 +230,11 @@ export interface ExecAgentParams {prompt: string;/** Override the agent's default provider */provider?: string;+ /**+ * Existing topic operation this fresh turn atomically supersedes. The server+ * accepts the handoff only while the topic marker still belongs to this id.+ */+ replacesOperationId?: string;/** The agent slug to run (either agentId or slug is required) */slug?: string;/**diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.tsindex 3b751298795..8a1a1880e11 100644--- a/src/services/aiAgent.ts+++ b/src/services/aiAgent.ts@@ -78,6 +78,8 @@ export interface ExecAgentTaskParams {/** Parent message ID for regeneration/continue (skip user message creation, branch from this message) */parentMessageId?: string;prompt: string;+ /** Existing gateway operation this fresh turn atomically supersedes. */+ replacesOperationId?: string;/** Resume a previous op paused on `human_approve_required` instead of starting from a fresh user prompt. */resumeApproval?: ResumeApprovalParam;/**diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex 078134a55f5..c2a226b798b 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -2366,6 +2366,178 @@ describe('ConversationLifecycle actions', () => {);});+ it('should NOT enqueue once the run finished its visible output', async () => {+ // Regression: the enqueue check only asked `status === 'running'`, while the+ // composer flips back to Send on `visibleLoadingDone`. The answer is complete+ // on screen and the button says Send, so the next message must start a fresh+ // turn β not park in a tray the user has no reason to expect, and one that+ // never empties at all when `agent_runtime_end` is lost over a still-open WS+ // (neither the run lifecycle nor onSessionComplete's fallback fires, and the+ // queue drains on success only).+ const { result } = renderHook(() => useChatStore());+ const context = createTestContext();+ const contextKey = messageMapKey(context);++ act(() => {+ useChatStore.setState({+ operations: {+ 'op-visible-done': {+ childOperationIds: [],+ context,+ id: 'op-visible-done',+ metadata: { visibleLoadingDone: true },+ status: 'running',+ type: 'execServerAgentRuntime',+ },+ } as any,+ operationsByContext: {+ [contextKey]: ['op-visible-done'],+ },+ });+ });++ const enqueueMessageSpy = vi.spyOn(result.current, 'enqueueMessage');++ await act(async () => {+ await result.current.sendMessage({+ context,+ message: 'follow-up after the run visibly ended',+ });+ });++ expect(enqueueMessageSpy).not.toHaveBeenCalled();+ });++ it('should NOT enqueue behind an aborting op (Stop already pressed)', async () => {+ // Stop flips the composer back to Send immediately via `isAborting`. The+ // queue drains on success only, so queueing behind an aborting run would+ // strand the message with no run left to send it.+ const { result } = renderHook(() => useChatStore());+ const context = createTestContext();+ const contextKey = messageMapKey(context);++ act(() => {+ useChatStore.setState({+ operations: {+ 'op-aborting': {+ childOperationIds: [],+ context,+ id: 'op-aborting',+ metadata: { isAborting: true },+ status: 'running',+ type: 'execServerAgentRuntime',+ },+ } as any,+ operationsByContext: {+ [contextKey]: ['op-aborting'],+ },+ });+ });++ const enqueueMessageSpy = vi.spyOn(result.current, 'enqueueMessage');++ await act(async () => {+ await result.current.sendMessage({ context, message: 'send after stop' });+ });++ expect(enqueueMessageSpy).not.toHaveBeenCalled();+ });++ it('should restart the existing queue in FIFO order when Stop already cancelled its owner', async () => {+ vi.useFakeTimers();+ const { result } = renderHook(() => useChatStore());+ const context = createTestContext();+ const contextKey = messageMapKey(context);++ act(() => {+ useChatStore.setState({+ operations: {+ 'op-cancelled': {+ childOperationIds: [],+ context,+ id: 'op-cancelled',+ metadata: { isAborting: true },+ status: 'cancelled',+ type: 'execServerAgentRuntime',+ },+ } as any,+ operationsByContext: { [contextKey]: ['op-cancelled'] },+ queuedMessages: {+ [contextKey]: [+ {+ content: 'queued A',+ createdAt: Date.now(),+ id: 'queued-1',+ interruptMode: 'soft',+ },+ ],+ },+ });+ });++ const sendMessageSpy = vi.spyOn(result.current, 'sendMessage');++ await act(async () => {+ await result.current.sendMessage({ context, message: 'new B' });+ await vi.runAllTimersAsync();+ });++ expect(sendMessageSpy).toHaveBeenLastCalledWith(+ expect.objectContaining({ message: expect.stringMatching(/queued A[\s\S]*new B/) }),+ );+ expect(useChatStore.getState().queuedMessages[contextKey]).toEqual([]);+ vi.useRealTimers();+ });++ it('should still enqueue past visible end when follow-ups are already queued', async () => {+ // Order beats latency: those queued items belong to the terminal drain, so a+ // newer send must join the queue instead of jumping it β otherwise the drain+ // fires a second, older turn right behind this one.+ const { result } = renderHook(() => useChatStore());+ const context = createTestContext();+ const contextKey = messageMapKey(context);++ act(() => {+ useChatStore.setState({+ operations: {+ 'op-finishing': {+ childOperationIds: [],+ context,+ id: 'op-finishing',+ metadata: { visibleLoadingDone: true },+ status: 'running',+ type: 'execServerAgentRuntime',+ },+ } as any,+ operationsByContext: {+ [contextKey]: ['op-finishing'],+ },+ queuedMessages: {+ [contextKey]: [+ {+ content: 'queued before the visible end',+ createdAt: Date.now(),+ id: 'queued-1',+ interruptMode: 'soft',+ },+ ],+ },+ });+ });++ const enqueueMessageSpy = vi.spyOn(result.current, 'enqueueMessage');++ await act(async () => {+ await result.current.sendMessage({ context, message: 'follow-up mid-terminal' });+ });++ expect(enqueueMessageSpy).toHaveBeenCalledWith(+ contextKey,+ expect.objectContaining({ content: 'follow-up mid-terminal' }),+ 'op-finishing',+ );+ });+it('should enqueue behind a running interim approve/retry op (preflight window)', async () => {// Interim ops (approve/submit/skip/regenerate) show input loading the// instant the user clicks, but the real runtime op is only created 2β4diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.tsindex b8202008f40..fd8d518b2b5 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts@@ -1345,12 +1345,17 @@ describe('GatewayActionImpl', () => {});});- // A late close of a finished op must NOT wipe the marker of a NEWER operation- // that a racing retry/send already wrote β that would break reconnect-after-reload- // for the live run. Only a marker matching the completed op's id gets cleared.- it('does not clear the local marker when it already belongs to a newer operation', async () => {+ // A late close of a finished op must NOT retire a NEWER operation that a+ // racing retry/send already wrote β that would break reconnect-after-reload+ // for the live run AND flip its topic out of the running state. None of the+ // three writes (local marker, server marker, topic status) may fire when the+ // topic has moved on. Reachable whenever a follow-up starts before the+ // previous session closes: the terminal queue drain does it 100ms after the+ // terminal, and a send right after `visible_output_end` does it sooner still.+ it('does not retire the topic when its marker already belongs to a newer operation', async () => {const connectToGateway = vi.fn();const internalDispatchTopic = vi.fn();+ const updateTopicStatus = vi.fn();const startOperation = vi.fn(() => ({ operationId: 'gw-op-1' }));const state: Record<string, any> = {activeAgentId: 'agent-1',@@ -1385,7 +1390,7 @@ describe('GatewayActionImpl', () => {moveVoiceMessages: vi.fn(),onOperationCancel: vi.fn(),startOperation,- updateTopicStatus: vi.fn(),+ updateTopicStatus,})) as any;(globalThis as any).window = {@@ -1418,13 +1423,17 @@ describe('GatewayActionImpl', () => {});const { onSessionComplete } = connectToGateway.mock.calls[0][0];- // Ignore any dispatches from the optimistic-update path during setup.+ // Ignore any dispatches / writes from the optimistic-update path during setup.internalDispatchTopic.mockClear();+ updateTopicStatus.mockClear();+ vi.mocked(topicService.updateTopicMetadata).mockClear();vi.mocked(topicService.updateTopicMetadata).mockResolvedValue(undefined as never);onSessionComplete({ succeeded: false, terminalReceived: true });expect(internalDispatchTopic).not.toHaveBeenCalled();+ expect(topicService.updateTopicMetadata).not.toHaveBeenCalled();+ expect(updateTopicStatus).not.toHaveBeenCalled();});// When the desktop runs against ζ¬ζΊ (effective runtime mode 'local'), thediff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex f3bbb483127..4def3a43b7e 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -60,8 +60,12 @@ import { executeDirectMention } from '@/store/chat/slices/agentRun/actions/dispaimport { buildRunLifecycle } from '@/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle';import type { RunScope } from '@/store/chat/slices/agentRun/actions/lifecycle/types';import { resolveHeteroResume } from '@/store/chat/slices/agentRun/actions/transports/hetero/heteroResume';-import type { OperationType, QueuedFile } from '@/store/chat/slices/operation/types';-import { QUEUE_BLOCKING_OPERATION_TYPES } from '@/store/chat/slices/operation/types';+import type { QueuedFile } from '@/store/chat/slices/operation/types';+import {+ isQueueBlockingOperation,+ mergeQueuedMessages,+ reconstructUploadFilesFromQueue,+} from '@/store/chat/slices/operation/types';import { PortalViewType } from '@/store/chat/slices/portal/initialState';import { chatPortalSelectors } from '@/store/chat/slices/portal/selectors';import { type ChatStore } from '@/store/chat/store';@@ -179,8 +183,6 @@ const isAbortError = (error: unknown, abortController?: AbortController) =>const createAbortError = () =>Object.assign(new Error('Compression cancelled'), { name: 'AbortError' });-const QUEUE_BLOCKING_OPERATION_TYPE_SET = new Set<OperationType>(QUEUE_BLOCKING_OPERATION_TYPES);-const throwIfSendAborted = (signal?: AbortSignal) => {if (!signal?.aborted) return;@@ -602,6 +604,7 @@ export class ConversationLifecycleActionImpl {];const findRunningBlockingOp = (key: string) => {const contextOpIds = this.#get().operationsByContext[key] || [];+ const hasQueuedMessages = (this.#get().queuedMessages[key]?.length ?? 0) > 0;const ownVoiceUploadIndex = optimisticUserMessageId? contextOpIds.findIndex((id) => {const operation = this.#get().operations[id];@@ -617,8 +620,10 @@ export class ConversationLifecycleActionImpl {.find(({ index, operation }) =>operation &&- QUEUE_BLOCKING_OPERATION_TYPE_SET.has(operation.type) &&- operation.status === 'running' &&+ // Shared predicate β an op the composer already treats as finished+ // (aborting, or done with its visible output) must NOT swallow this+ // send into the tray.+ isQueueBlockingOperation(operation, { hasQueuedMessages }) &&// The upload transaction calls this lifecycle after its own binary is ready. It must// not queue behind itself (or a later voice upload); earlier voice uploads still block.!(@@ -669,6 +674,72 @@ export class ConversationLifecycleActionImpl {return;}+ // Stop may already have moved the old operation to `cancelled`, so there is+ // no live blocker left to drain follow-ups that were queued before Stop.+ // Fold the new send into that FIFO and immediately restart the whole batch;+ // otherwise the new message jumps ahead and the older queue drains after it.+ const orphanedQueueKey = queueCandidateKeys.find((key) => {+ if ((this.#get().queuedMessages[key]?.length ?? 0) === 0) return false;+ return (this.#get().operationsByContext[key] || []).some((id) => {+ const operation = this.#get().operations[id];+ return operation?.status === 'cancelled' && operation.metadata.isAborting;+ });+ });+ if (orphanedQueueKey && !onlyAddUserMessage) {+ const filesPreview: QueuedFile[] = (files ?? []).map((file) => ({+ audioMetadata: file.audioMetadata,+ id: file.id,+ mimeType: file.file?.type ?? '',+ name: file.file?.name ?? file.id,+ url: file.fileUrl || file.base64Url || file.previewUrl || '',+ }));+ this.#get().enqueueMessage(orphanedQueueKey, {+ content: message,+ createdAt: Date.now(),+ editorData: editorData ?? undefined,+ files: fileIdList,+ filesPreview: filesPreview.length > 0 ? filesPreview : undefined,+ ...(forceRuntime ? { forceRuntime } : {}),+ id: nanoid(),+ interruptMode: 'soft',+ metadata: userMessageMetadata,+ });+ const merged = mergeQueuedMessages(this.#get().drainQueuedMessages(orphanedQueueKey));+ notifyMessageAccepted();++ setTimeout(() => {+ this.#get()+ .sendMessage({+ context: operationContext,+ editorData: merged.editorData,+ files:+ merged.filesPreview.length > 0+ ? reconstructUploadFilesFromQueue(merged.filesPreview)+ : merged.files.length > 0+ ? (merged.files.map((id) => ({ id })) as any)+ : undefined,+ ...(merged.forceRuntime ? { forceRuntime: merged.forceRuntime } : {}),+ message: merged.content,+ metadata: merged.metadata,+ })+ .catch((error: unknown) => {+ console.error('[sendMessage] restarting queued content after Stop failed:', error);+ });+ }, 0);++ return;+ }++ const replaceableGatewayOperationId = queueCandidateKeys+ .flatMap((key) => this.#get().operationsByContext[key] || [])+ .map((id) => this.#get().operations[id])+ .findLast(+ (operation) =>+ operation?.type === 'execServerAgentRuntime' &&+ operation.status === 'running' &&+ (operation.metadata.isAborting || operation.metadata.visibleLoadingDone),+ )?.metadata.serverOperationId;+if (onlyAddUserMessage) {await this.#get().addUserMessage({message,@@ -1508,6 +1579,7 @@ export class ConversationLifecycleActionImpl {metadata: requestMetadata,onMessageAccepted: notifyMessageAccepted,parentOperationId: operationId,+ replacesOperationId: replaceableGatewayOperationId,optimisticTopic,// Forward @-mentioned tool ids so the server runtime enables them for// this run β the gateway/server path otherwise never sees the mentiondiff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.tsindex 8565a375399..cd61ef0989b 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts@@ -181,6 +181,23 @@ describe('buildRunLifecycle.completeRun β client resets a viewed topic out of);});+ it('does not reset a viewed topic after a newer client run starts', async () => {+ const { get, store } = makeStore();+ Object.assign(store.operations, {+ op2: {+ context: CONTEXT,+ id: 'op2',+ metadata: {},+ status: 'running',+ type: 'execAgentRuntime',+ },+ });++ await lifecycle('client', get).completeRun(completeEvent('client', { runtimeStatus: 'done' }));++ expect(store.updateTopicStatus).not.toHaveBeenCalled();+ });+it('client success on a VIEWED group topic routes the reset to the group bucket (scope: group)', async () => {// A group run's start-write passes scope: 'group'; the reset must too, or the// optimistic patch derives `group_agent` and misses the visible group row.diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.tsindex fcd685d7136..da22c60089a 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts@@ -13,7 +13,11 @@ import { markdownToTxt } from '@/utils/markdownToTxt';import { messageMapKey } from '../../../../utils/messageMapKey';import { displayMessageSelectors } from '../../../message/selectors/displayMessage';import type { OperationStatus } from '../../../operation/types';-import { mergeQueuedMessages, reconstructUploadFilesFromQueue } from '../../../operation/types';+import {+ AI_RUNTIME_OPERATION_TYPES,+ mergeQueuedMessages,+ reconstructUploadFilesFromQueue,+} from '../../../operation/types';import { topicSelectors } from '../../../topic/selectors';import type {AgentRunLifecycle,@@ -337,6 +341,17 @@ export const buildRunLifecycle = (if (adapter.runtimeType !== 'client') return;if (adapter.runScope === 'sub_agent') return;if (!topicId) return;+ const hasNewerRuntime = Object.values(get().operations).some(+ (candidate) =>+ candidate.id !== operationId &&+ candidate.status === 'running' &&+ AI_RUNTIME_OPERATION_TYPES.includes(candidate.type) &&+ candidate.context.topicId === topicId &&+ candidate.context.agentId === agentId &&+ candidate.context.groupId === groupId &&+ !candidate.parentOperationId,+ );+ if (hasNewerRuntime) return;const viewing = get().activeTopicId === topicId;// Not-viewing clean success is owned by `markTopicUnread` (β 'unread');// skip so the two never race over the status field.diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 5be68c5b03a..44c92414f6e 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -434,6 +434,8 @@ export class GatewayActionImpl {optimisticTopic?: { id: string; metadata?: ChatTopicMetadata; title: string };/** Parent message ID for regeneration/continue (skip user message creation, branch from this message) */parentMessageId?: string;+ /** Server operation whose visible output ended before this fresh turn. */+ replacesOperationId?: string;/*** Caller-owned operation that should be completed once the gateway side* has finished phase-1 init (network round-trip + child@@ -500,6 +502,7 @@ export class GatewayActionImpl {optimisticTopic,parentMessageId,parentOperationId,+ replacesOperationId,resumeApproval,resumeApprovals,resumeToolResult,@@ -618,6 +621,7 @@ export class GatewayActionImpl {},...desktopDeviceHints,fileIds,+ replacesOperationId,mentionedAgents,parentMessageId,prompt: message,@@ -846,12 +850,25 @@ export class GatewayActionImpl {// terminal-missing fallback so the op never sticks `running`.if (!terminalReceived) this.#get().completeOperation(gatewayOpId);if (result.topicId) {+ // A later run already took this topic over β its start wrote the new+ // `runningOperation`, and this close is just our own session winding+ // down. Both writes below are unconditional stomps, so they'd retire a+ // run that is still going: the status write kills its sidebar/home+ // "running" state and the metadata clear drops the marker+ // `useGatewayReconnect` needs to resume it after a reload.+ const superseded = this.#isSupersededRunningOperation({+ agentId: resolvedMessageContext.agentId,+ groupId: resolvedMessageContext.groupId,+ operationId: result.operationId,+ topicId: result.topicId,+ });+// A clean completion the user isn't watching is owned by// `markTopicUnread` (status: 'unread'); skip the 'active' write so// the two never race over the status field. Every other case (viewing,// error, abort) clears the running state back to 'active' as before.const viewing = this.#get().activeTopicId === result.topicId;- if (viewing || !succeeded) {+ if (!superseded && (viewing || !succeeded)) {void this.#get().updateTopicStatus?.({agentId: resolvedMessageContext.agentId,groupId: resolvedMessageContext.groupId,@@ -861,11 +878,14 @@ export class GatewayActionImpl {}// Clear running operation from topic metadata (best-effort from frontend;// if browser was closed, reconnect logic will handle stale entries)- topicService- .updateTopicMetadata(result.topicId, { runningOperation: null })- .catch(() => {});+ if (!superseded) {+ topicService+ .updateTopicMetadata(result.topicId, { runningOperation: null })+ .catch(() => {});+ }// Also clear the local store copy β the server clear above does NOT touch- // the Zustand topic map that useGatewayReconnect reads.+ // the Zustand topic map that useGatewayReconnect reads. Ownership-guarded+ // on its own, so it is safe to call either way.this.clearLocalRunningOperation({agentId: resolvedMessageContext.agentId,groupId: resolvedMessageContext.groupId,@@ -1047,10 +1067,19 @@ export class GatewayActionImpl {// the local op never sticks `running`.if (authFailed) this.#get().completeOperation(gatewayOpId);+ // Same supersede guard as executeGatewayAgent's onSessionComplete: a+ // newer run may own this topic by now, and both writes below are+ // unconditional stomps that would retire it mid-flight.+ const superseded = this.#isSupersededRunningOperation({+ agentId: context.agentId,+ operationId,+ topicId,+ });+// See executeGatewayAgent's onSessionComplete: a clean background// completion is left to markTopicUnread (status: 'unread').const viewing = this.#get().activeTopicId === topicId;- if (viewing || !succeeded) {+ if (!superseded && (viewing || !succeeded)) {void this.#get().updateTopicStatus?.({agentId: context.agentId,status: 'active',@@ -1059,7 +1088,9 @@ export class GatewayActionImpl {}// Clear the persisted marker useGatewayReconnect keys off so a dead op// doesn't get reconnected on every reload / task-drawer open.- topicService.updateTopicMetadata(topicId, { runningOperation: null }).catch(() => {});+ if (!superseded) {+ topicService.updateTopicMetadata(topicId, { runningOperation: null }).catch(() => {});+ }// Mirror the clear into the local store β the server clear above leaves the// Zustand topic map stale, which useGatewayReconnect keys off.this.clearLocalRunningOperation({ agentId: context.agentId, operationId, topicId });@@ -1127,6 +1158,35 @@ export class GatewayActionImpl {* user switched agent/group, when the active-bucket `getTopicById` would miss the topic* and leave its marker stale.*/+ /**+ * Whether a DIFFERENT run has since claimed this topic's `runningOperation`.+ *+ * Read from the local topic map, which every run's start writes optimistically+ * β so a session closing after a newer run began can tell "my run ended" from+ * "the topic is idle" and keep its hands off the newer run's markers.+ *+ * Deliberately false when the topic carries no marker at all (not loaded into+ * `topicDataMap`, or already cleared): there is nothing to protect, and the+ * caller's clear must still run so a dead marker never survives.+ */+ #isSupersededRunningOperation = (params: {+ agentId?: string;+ groupId?: string;+ operationId: string;+ topicId: string;+ }): boolean => {+ const { agentId, groupId, operationId, topicId } = params;+ const state = this.#get();+ const key = topicMapKey({+ agentId: agentId ?? state.activeAgentId,+ groupId: groupId ?? state.activeGroupId,+ });+ const owner = state.topicDataMap[key]?.items?.find((t) => t.id === topicId)?.metadata+ ?.runningOperation?.operationId;++ return !!owner && owner !== operationId;+ };+private clearLocalRunningOperation = (params: {agentId?: string;groupId?: string;diff --git a/src/store/chat/slices/operation/__tests__/selectors.test.ts b/src/store/chat/slices/operation/__tests__/selectors.test.tsindex 59d33ad0a3e..41d9cfd4ed7 100644--- a/src/store/chat/slices/operation/__tests__/selectors.test.ts+++ b/src/store/chat/slices/operation/__tests__/selectors.test.ts@@ -55,6 +55,99 @@ describe('Operation Selectors', () => {expect(ids).toEqual(expect.arrayContaining([outerId, innerId]));});+ // Regression: the enqueue check used a bare `status === 'running'` while every+ // loading UI used `isRunningOperation` (which excludes isAborting) and+ // `isVisiblyRunningOperation` (which also excludes visibleLoadingDone). The two+ // definitions of "finished" differed by exactly those two fields, so a composer+ // showing Send would silently drop the next message into the tray β forever when+ // the terminal never landed, since the queue only drains on success.+ it('excludes an aborting op β Stop means the next send starts a fresh turn', () => {+ const { result } = renderHook(() => useChatStore());+ const context = { agentId: 'agent1', topicId: 'topic1' };+ let opId = '';++ act(() => {+ opId = result.current.startOperation({ type: 'execAgentRuntime', context }).operationId;+ result.current.updateOperationMetadata(opId, { isAborting: true });+ });++ expect(+ operationSelectors.getRunningQueueBlockingOperationIds(context)(result.current),+ ).toEqual([]);+ });++ it('keeps an aborting op blocking while older follow-ups are queued', () => {+ const { result } = renderHook(() => useChatStore());+ const context = { agentId: 'agent1', topicId: 'topic1' };+ let opId = '';++ act(() => {+ opId = result.current.startOperation({ type: 'execAgentRuntime', context }).operationId;+ result.current.updateOperationMetadata(opId, { isAborting: true });+ result.current.enqueueMessage(messageMapKey(context), {+ content: 'queued first',+ createdAt: Date.now(),+ id: 'queued-1',+ interruptMode: 'soft',+ });+ });++ expect(+ operationSelectors.getRunningQueueBlockingOperationIds(context)(result.current),+ ).toEqual([opId]);+ });++ it('stops blocking once visible output ends β the composer already shows Send', () => {+ const { result } = renderHook(() => useChatStore());+ const context = { agentId: 'agent1', topicId: 'topic1' };+ let opId = '';++ act(() => {+ opId = result.current.startOperation({+ type: 'execServerAgentRuntime',+ context,+ }).operationId;+ });++ expect(+ operationSelectors.getRunningQueueBlockingOperationIds(context)(result.current),+ ).toEqual([opId]);++ act(() => {+ result.current.updateOperationMetadata(opId, { visibleLoadingDone: true });+ });++ expect(+ operationSelectors.getRunningQueueBlockingOperationIds(context)(result.current),+ ).toEqual([]);+ });++ it('keeps blocking past visible output end while follow-ups are already queued', () => {+ // The terminal drain owns those queued items; letting a newer send jump ahead+ // would reorder the conversation and run two turns at once.+ const { result } = renderHook(() => useChatStore());+ const context = { agentId: 'agent1', topicId: 'topic1' };+ let opId = '';++ act(() => {+ opId = result.current.startOperation({+ type: 'execServerAgentRuntime',+ context,+ }).operationId;+ result.current.updateOperationMetadata(opId, { visibleLoadingDone: true });+ result.current.enqueueMessage(messageMapKey(context), {+ content: 'queued before the visible end',+ createdAt: Date.now(),+ id: 'queued-1',+ interruptMode: 'soft',+ });+ });++ expect(+ operationSelectors.getRunningQueueBlockingOperationIds(context)(result.current),+ ).toEqual([opId]);+ });+it('excludes non-running and non-blocking ops', () => {const { result } = renderHook(() => useChatStore());const context = { agentId: 'agent1', topicId: 'topic1' };diff --git a/src/store/chat/slices/operation/selectors.ts b/src/store/chat/slices/operation/selectors.tsindex 1680b0b8001..c174e26c783 100644--- a/src/store/chat/slices/operation/selectors.ts+++ b/src/store/chat/slices/operation/selectors.ts@@ -6,7 +6,7 @@ import { type Operation, type OperationType } from './types';import {AI_RUNTIME_OPERATION_TYPES,INPUT_LOADING_OPERATION_TYPES,- QUEUE_BLOCKING_OPERATION_TYPES,+ isQueueBlockingOperation,} from './types';// === Basic Queries ===@@ -275,8 +275,11 @@ const isAgentRuntimeVisiblyRunningByContext =};/**- * All running queue-blocking operation ids in a context (see- * QUEUE_BLOCKING_OPERATION_TYPES). "Send now" cancels every one of them, not just+ * All live queue-blocking operation ids in a context (see+ * `isQueueBlockingOperation` β the same predicate the enqueue check uses, so+ * "Send now" cancels exactly what a fresh send would have queued behind and+ * never fires at an op that already stopped holding the queue). "Send now"+ * cancels every one of them, not just* the first: a retry via delAndRegenerate/delAndResendThread runs an outer* wrapper `regenerate` op AND an inner regenerateUserMessage `regenerate` op at* once, so cancelling only one would leave the queue blocked and make "Send now"@@ -286,8 +289,9 @@ const getRunningQueueBlockingOperationIds =(context: MessageMapKeyInput) =>(s: ChatStoreState): string[] => {if (!context.agentId) return [];+ const hasQueuedMessages = getQueuedMessages(context)(s).length > 0;return getOperationsByContext(context)(s)- .filter((op) => QUEUE_BLOCKING_OPERATION_TYPES.includes(op.type) && op.status === 'running')+ .filter((op) => isQueueBlockingOperation(op, { hasQueuedMessages })).map((op) => op.id);};diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.tsindex c721771ed69..35ea6f9ff00 100644--- a/src/store/chat/slices/operation/types.ts+++ b/src/store/chat/slices/operation/types.ts@@ -511,3 +511,49 @@ export const QUEUE_BLOCKING_OPERATION_TYPES: OperationType[] = ['uploadVoiceMessage',...INTERIM_LOADING_OPERATION_TYPES,];++const QUEUE_BLOCKING_OPERATION_TYPE_SET = new Set<OperationType>(QUEUE_BLOCKING_OPERATION_TYPES);++/**+ * Single source of truth for "a fresh send must queue behind this op instead of+ * starting a concurrent run" β shared by the enqueue check+ * (`conversationLifecycle`) and the QueueTray "Send now" cancel path, so both+ * agree on what a follow-up is queued behind.+ *+ * Deliberately mirrors what the composer shows rather than a bare+ * `status === 'running'`: the Send button comes back on `isAborting` /+ * `visibleLoadingDone`, and when the enqueue check disagreed, an idle-looking+ * composer silently swallowed messages into the tray β permanently when the+ * terminal event never landed, since the queue only drains on success.+ */+export const isQueueBlockingOperation = (+ operation: Operation,+ options?: {+ /**+ * Whether this run's bucket already holds queued follow-ups. See below β+ * order beats latency once a queue exists.+ */+ hasQueuedMessages?: boolean;+ },+): boolean => {+ if (!QUEUE_BLOCKING_OPERATION_TYPE_SET.has(operation.type)) return false;+ if (operation.status !== 'running') return false;++ // Stop was pressed. With no older queue, this run cannot absorb a follow-up,+ // so let the next send start fresh. When older items already exist, keep the+ // operation blocking until cancellation completes; the send lifecycle then+ // restarts that orphaned FIFO as one ordered batch.+ if (operation.metadata.isAborting && !options?.hasQueuedMessages) return false;++ // Visible output is done and the op is only finishing terminal bookkeeping+ // (DB reconciliation, title, drain). The answer is complete on screen and the+ // composer says Send, so honor that: start a fresh turn instead of parking the+ // message in a tray the user has no reason to expect.+ //+ // Unless this run already has follow-ups queued behind it: the terminal drain+ // will send those, so jumping ahead of them would both reorder the+ // conversation and run two turns at once. Order beats latency there.+ if (operation.metadata.visibleLoadingDone && !options?.hasQueuedMessages) return false;++ return true;+};