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(chat): keep a turn stopped before its first token sent and marked stopped (#22899)

Arvin Xudef853d3c78c
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/assistantMessage.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/assistantMessage.ts
index a40cde05dac..a5f89245836 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/assistantMessage.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/assistantMessage.ts
@@ -110,3 +110,31 @@ export async function resolveErrorMessageId(
return undefined;
}
}
+
+/**
+ * Mark the assistant row of the step a Stop interrupted, so every client can
+ * render the turn as stopped after a refresh: the run's newest row (the step
+ * that was streaming or calling tools, not an earlier completed one), or the
+ * placeholder the send created when the run stopped before step 0 stamped any
+ * row. The `call_llm` finalizer marks a Stop that ends its stream; this covers
+ * every other way an interrupted run settles. Non-fatal.
+ */
+export async function markInterruptedTurn(
+ deps: CompletionLifecycleDeps,
+ operationId: string,
+ state: { metadata?: { assistantMessageId?: string }; origin?: { assistantMessageId?: string } },
+ runOrigin: { topicId?: string; userId?: string },
+): Promise<void> {
+ const assistantMessageId =
+ (await resolveErrorMessageId(deps, operationId, state?.metadata, runOrigin)) ??
+ state?.origin?.assistantMessageId;
+ if (!assistantMessageId) return;
+
+ try {
+ await deps.messageModel.update(assistantMessageId, {
+ metadata: { interruptedMidStream: true },
+ });
+ } catch (error) {
+ log('[%s] Failed to mark the interrupted turn (non-fatal): %O', operationId, error);
+ }
+}
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.interruptedTurn.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.interruptedTurn.test.ts
new file mode 100644
index 00000000000..f6a73b9a260
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.interruptedTurn.test.ts
@@ -0,0 +1,84 @@
+// @vitest-environment node
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { hookDispatcher } from '../hooks';
+import { CompletionLifecycle } from '.';
+
+vi.mock('@/database/models/work', () => import('./testUtils').then((m) => m.workModelModule()));
+vi.mock('@/database/models/topic', () => import('./testUtils').then((m) => m.topicModelModule()));
+vi.mock('@/business/server/agent-run/agentInterventionReview', () =>
+ import('./testUtils').then((m) => m.agentInterventionReviewModule()),
+);
+vi.mock('@/business/server/agent-run/notifyAgentRunCompleted', () =>
+ import('./testUtils').then((m) => m.notifyAgentRunCompletedModule()),
+);
+vi.mock('../agentInterventionNotification', () =>
+ import('./testUtils').then((m) => m.agentInterventionNotificationModule()),
+);
+
+// The state a run stopped before step 0 (or during its deferred init) carries:
+// no assistant turn yet, only the placeholder the send created on `origin`.
+const stoppedState = {
+ host: { hooks: [] },
+ messages: [{ content: 'write me a poem', id: 'msg-user', role: 'user' }],
+ origin: { agentId: 'agent-1', assistantMessageId: 'msg-ast', topicId: 'tpc-1', userId: 'user-1' },
+ status: 'interrupted',
+};
+
+const marker = { metadata: { interruptedMidStream: true } };
+
+const run = async (latestRunRow: { id: string } | undefined, reason = 'interrupted') => {
+ const lifecycle = new CompletionLifecycle({} as any, 'user-1');
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+ const update = vi.fn().mockResolvedValue({ success: true });
+ // `call_llm` stamps `metadata.operationId` on every row a step creates or reuses.
+ const findLatestAssistantByOperationId = vi.fn().mockResolvedValue(latestRunRow);
+ (lifecycle as any).messageModel = {
+ findById: vi.fn().mockResolvedValue(undefined),
+ findLatestAssistantByOperationId,
+ update,
+ };
+
+ await lifecycle.dispatchHooks('op-1', stoppedState, reason);
+
+ return { update };
+};
+
+describe('CompletionLifecycle.dispatchHooks β€” interrupted turn marker', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ // ROOT CAUSE:
+ //
+ // A stop that lands before the first token (before step 0 runs, during a
+ // deferred init) settles the operation but never touches the assistant row.
+ // It keeps the `...` placeholder with no marker, so every client renders an
+ // empty bubble.
+ //
+ // Before: the row stayed a bare placeholder. After: it carries the persisted
+ // stopped marker the clients render.
+ it('marks the placeholder when the run stopped before any step stamped a row', async () => {
+ const { update } = await run(undefined);
+
+ expect(update).toHaveBeenCalledWith('msg-ast', marker);
+ });
+
+ // A Stop during a later step (a tool call, or a stream that did not end
+ // through the finalizer) left the interrupted step's row unmarked, so after a
+ // refresh the turn read as finished.
+ it('marks the row of the interrupted step, not the placeholder of an earlier step', async () => {
+ const { update } = await run({ id: 'msg-step-3' });
+
+ expect(update).toHaveBeenCalledWith('msg-step-3', marker);
+ expect(update).not.toHaveBeenCalledWith('msg-ast', marker);
+ });
+
+ it('does not mark a run that finished normally', async () => {
+ const { update } = await run({ id: 'msg-step-3' }, 'done');
+
+ expect(update).not.toHaveBeenCalledWith(expect.anything(), marker);
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts
index 66e8d2db590..36da3cfaf18 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts
@@ -19,7 +19,11 @@ import {
import { after } from '@/server/utils/scheduleAfterResponse';
import { CriticalHookDeliveryError, hookDispatcher } from '../hooks';
-import { recoverLastAssistantContent, resolveErrorMessageId } from './assistantMessage';
+import {
+ markInterruptedTurn,
+ recoverLastAssistantContent,
+ resolveErrorMessageId,
+} from './assistantMessage';
import { registerFileWorks } from './fileWorks';
import {
CriticalAgentInterventionPersistenceError,
@@ -402,6 +406,12 @@ export class CompletionLifecycle {
// Before the hooks, so a parent resumed by the bridge reads a closed thread.
await settleRunThread(this.deps(), operationId, state, reason);
+ // Every stop (before step 0, during a deferred init, mid-stream, during a
+ // tool call) marks the turn it interrupted; a run that finished is untouched.
+ if (reason === 'interrupted') {
+ await markInterruptedTurn(this.deps(), operationId, state, runOrigin);
+ }
+
// The run tree no longer works, so its concurrency slot frees now rather
// than when the lease lapses. A run parked on a human decision frees it
// too; its continuation takes a slot of its own.
diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
index d82d276ee2d..7a655a2f7f3 100644
--- a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
@@ -634,7 +634,7 @@ describe('callLlmFinalizer', () => {
{ text: 'Image answer', type: 'text' },
{ image: 'https://example.com/image.png', type: 'image' },
]),
- metadata: { isMultimodal: true },
+ metadata: { interruptedMidStream: false, isMultimodal: true },
reasoning: {
content: JSON.stringify([
{ text: 'Visual reasoning', type: 'text' },
@@ -676,10 +676,13 @@ describe('callLlmFinalizer', () => {
state: AgentRuntime.createInitialState({ operationId: 'operation-1' }),
});
+ // Before: a Stop mid-stream persisted the partial with no stopped marker,
+ // so after a refresh the turn read as finished. After: it carries one.
expect(messages.update).toHaveBeenCalledWith(
'assistant-1',
expect.objectContaining({
- metadata: { finishType: 'abort' },
+ content: 'Partial answer',
+ metadata: { finishType: 'abort', interruptedMidStream: true },
observationId: 'observation-1',
reasoning: { content: 'Reasoning', duration: 120, signature: 'signature-1' },
traceId: 'trace-1',
@@ -694,6 +697,49 @@ describe('callLlmFinalizer', () => {
});
});
+ it('keeps the placeholder and marks a turn stopped before its first token', async () => {
+ const messages = createMessageTransport();
+
+ await finalizeCallLlmTurn({
+ assistantMessageId: 'assistant-1',
+ events: [],
+ host: createHost(messages),
+ model: 'claude',
+ output: createOutput({ content: '', finishReason: 'abort', thinkingContent: '' }),
+ provider: 'anthropic',
+ shouldReplayAssistantReasoning: false,
+ state: AgentRuntime.createInitialState({ operationId: 'operation-1' }),
+ });
+
+ const [, update] = vi.mocked(messages.update).mock.calls[0];
+ expect(update.content).toBeUndefined();
+ expect(update.metadata).toMatchObject({ interruptedMidStream: true });
+ });
+
+ // A row stopped earlier keeps `interruptedMidStream` when it is written again,
+ // because the message model merges metadata. A continuation that finished
+ // normally therefore still read as stopped.
+ //
+ // Before: the marker survived. After: a normal final write clears it.
+ it('clears the stopped marker when the row then finishes normally', async () => {
+ const messages = createMessageTransport();
+
+ await finalizeCallLlmTurn({
+ assistantMessageId: 'assistant-1',
+ events: [],
+ host: createHost(messages),
+ model: 'claude',
+ output: createOutput({ finishReason: 'stop' }),
+ provider: 'anthropic',
+ shouldReplayAssistantReasoning: false,
+ state: AgentRuntime.createInitialState({ operationId: 'operation-1' }),
+ });
+
+ const [, update] = vi.mocked(messages.update).mock.calls[0];
+ expect(update.content).toBe('Answer');
+ expect(update.metadata).toMatchObject({ interruptedMidStream: false });
+ });
+
it('records a client-executed attempt and its estimated usage on the message', async () => {
const messages = createMessageTransport();
diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.ts
index d24aff96805..a478d79c03f 100644
--- a/packages/agent-runtime/src/executors/callLlmFinalizer.ts
+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.ts
@@ -188,6 +188,9 @@ const persistFinalMessage = async ({
? serializePartsForStorage(output.contentParts)
: output.content;
const finalReasoning = buildFinalReasoning(output);
+ // A Stop ends the stream gracefully with `finishReason: 'abort'`, so this is
+ // the write a mid-stream Stop lands on: mark it like the error-path partial.
+ const aborted = output.finishReason === 'abort';
const metadata = buildMessageMetadata({
answerSalvagedFromReasoning: output.answerSalvagedFromReasoning,
currentStepSpeed: output.speed,
@@ -195,6 +198,7 @@ const persistFinalMessage = async ({
executionSite: output.executionSite,
finishType: output.finishReason,
hasContentImages: output.hasContentImages,
+ interruptedMidStream: aborted,
usageEstimated: output.usageEstimated,
});
const workAnchor = buildWorkAnchor({
@@ -205,9 +209,17 @@ const persistFinalMessage = async ({
try {
await host.transports.messages.update(assistantMessageId, {
- content: finalContent,
+ // Stopped before any text: keep the placeholder, which renders as stopped
+ // (an empty string renders as still loading).
+ content: aborted && !finalContent ? undefined : finalContent,
imageList: output.imageList.length > 0 ? output.imageList : undefined,
- metadata: workAnchor ? { ...metadata, work: workAnchor } : metadata,
+ metadata: {
+ ...metadata,
+ ...(workAnchor && { work: workAnchor }),
+ // A row stopped earlier and now written to completion is no longer stopped;
+ // the model merges metadata, so the stale marker is cleared explicitly.
+ ...(!aborted && { interruptedMidStream: false }),
+ },
observationId: output.observationId,
reasoning: finalReasoning,
search: output.grounding,
diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.ts
index 5df2de96239..d5022dcac3f 100644
--- a/packages/types/src/message/common/metadata.ts
+++ b/packages/types/src/message/common/metadata.ts
@@ -685,6 +685,11 @@ export interface MessageMetadata {
* Thread's sourceMessageId links back to this message for status tracking
*/
instruction?: string;
+ /**
+ * The run was stopped while generating this assistant turn. Set by the server
+ * runtime, including on a placeholder stopped before its first output.
+ */
+ interruptedMidStream?: boolean;
/**
* Flag indicating if message content is multimodal (serialized MessageContentPart[])
*/
diff --git a/src/features/Conversation/store/slices/messageState/selectors.test.ts b/src/features/Conversation/store/slices/messageState/selectors.test.ts
index 84c89e85731..4c75cfb1908 100644
--- a/src/features/Conversation/store/slices/messageState/selectors.test.ts
+++ b/src/features/Conversation/store/slices/messageState/selectors.test.ts
@@ -96,3 +96,42 @@ describe('selectedDeletableMessageIds', () => {
).toEqual(['u1', 'g1', 'c2', 'tool-result-1', 's1', 'a2']);
});
});
+
+describe('isMessageInterrupted', () => {
+ const withRow = (row: Record<string, unknown>, generating = false) =>
+ ({
+ dbMessages: [{ id: 'a1', role: 'assistant', ...row }],
+ operationState: {
+ getMessageOperationState: () => ({ isGenerating: generating, isInterrupted: false }),
+ },
+ }) as unknown as State;
+
+ // ROOT CAUSE:
+ //
+ // The "interrupted" hint only read the in-session cancelled operation. A run
+ // stopped before its first output keeps the `...` placeholder, which renders
+ // nothing, so after a reload (or on a late cancel that never opened a socket)
+ // the turn showed as an empty bubble with no stopped state.
+ //
+ // Before: false. After: the server's persisted marker shows it stopped.
+ it('reads the persisted marker on a placeholder stopped before its first output', () => {
+ const row = { content: '...', metadata: { interruptedMidStream: true } };
+
+ expect(messageStateSelectors.isMessageInterrupted('a1')(withRow(row))).toBe(true);
+ });
+
+ it('reads the persisted marker on a turn stopped mid-stream', () => {
+ const row = { content: 'Roses are', metadata: { interruptedMidStream: true } };
+
+ expect(messageStateSelectors.isMessageInterrupted('a1')(withRow(row))).toBe(true);
+ });
+
+ it('ignores the marker while the row is generating again, and rows without it', () => {
+ const row = { content: '...', metadata: { interruptedMidStream: true } };
+
+ expect(messageStateSelectors.isMessageInterrupted('a1')(withRow(row, true))).toBe(false);
+ expect(messageStateSelectors.isMessageInterrupted('a1')(withRow({ content: 'done' }))).toBe(
+ false,
+ );
+ });
+});
diff --git a/src/features/Conversation/store/slices/messageState/selectors.ts b/src/features/Conversation/store/slices/messageState/selectors.ts
index a0ce4242d9e..2fdb5204350 100644
--- a/src/features/Conversation/store/slices/messageState/selectors.ts
+++ b/src/features/Conversation/store/slices/messageState/selectors.ts
@@ -135,10 +135,17 @@ const isMessageContinuing = (id: string) => (s: State) =>
s.operationState.getMessageOperationState(id).isContinuing;
/**
- * Check if a message generation was interrupted by user
+ * Check if a message generation was interrupted by user: its operation was
+ * cancelled in this session, or the server persisted the stopped marker (which
+ * is what survives a refresh, on partial output and on a bare placeholder).
*/
-const isMessageInterrupted = (id: string) => (s: State) =>
- s.operationState.getMessageOperationState(id).isInterrupted;
+const isMessageInterrupted = (id: string) => (s: State) => {
+ const { isGenerating, isInterrupted } = s.operationState.getMessageOperationState(id);
+ if (isInterrupted || isGenerating) return isInterrupted;
+
+ const message = dataSelectors.getDbMessageById(id)(s);
+ return !!message?.metadata?.interruptedMidStream;
+};
/**
* Check if a message is in reasoning state
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.gatewayStopInFlight.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.gatewayStopInFlight.test.ts
new file mode 100644
index 00000000000..96142bb0998
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.gatewayStopInFlight.test.ts
@@ -0,0 +1,262 @@
+import { MESSAGE_CANCEL_FLAT } from '@lobechat/const';
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentService } from '@/services/agent';
+import { INPUT_LOADING_OPERATION_TYPES } from '@/store/chat/slices/operation/types';
+import { getElectronStoreState } from '@/store/electron/store';
+import { getSessionStoreState } from '@/store/session';
+import { useUserStore } from '@/store/user';
+
+import { useChatStore } from '../../../../store';
+import { createMockAgentConfig, TEST_IDS } from './fixtures';
+import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';
+
+vi.mock('../transports/hetero/heterogeneousAgentExecutor', () => ({
+ executeHeterogeneousAgent: vi.fn(),
+}));
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ session: { updateSession: { mutate: vi.fn().mockResolvedValue(undefined) } },
+ },
+}));
+
+const typedDraft = { root: { children: [], type: 'root' } };
+const agentId = TEST_IDS.SESSION_ID;
+const topicId = 'tpc_existing';
+
+beforeEach(() => {
+ resetTestEnvironment();
+ setupMockSelectors();
+ spyOnMessageService();
+ vi.spyOn(getSessionStoreState(), 'triggerSessionUpdate').mockResolvedValue(undefined);
+ vi.spyOn(agentService, 'getAgentConfigById').mockResolvedValue(createMockAgentConfig() as any);
+ useUserStore.setState({ workspaceUserPreference: {} });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+/**
+ * Sends through a gateway transport that parks before (or, with `sendRequest`,
+ * after) sending its start request, presses Stop there (the ChatInput
+ * `stopGenerating` sequence), then lets the transport `finish`.
+ */
+const sendAndStop = async ({
+ draftAfterStop = '',
+ finish,
+ sendRequest,
+}: {
+ /** What the user typed into the composer after pressing Stop. */
+ draftAfterStop?: string;
+ finish: (params: any) => Promise<unknown>;
+ sendRequest: boolean;
+}) => {
+ const { result } = renderHook(() => useChatStore());
+ const editor = {
+ clearContent: vi.fn(),
+ getJSONState: vi.fn(() => typedDraft),
+ getMarkdownContent: vi.fn(() => ''),
+ setDocument: vi.fn(),
+ setJSONState: vi.fn(),
+ };
+ let parked!: () => void;
+ const reached = new Promise<void>((resolve) => {
+ parked = resolve;
+ });
+ let release!: () => void;
+ const released = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeTopicId: topicId,
+ executeClientAgent: vi.fn(),
+ executeGatewayAgent: vi.fn(async (params: any) => {
+ if (sendRequest) params.onStartRequestSent?.();
+ parked();
+ await released;
+ return finish(params);
+ }) as any,
+ isGatewayModeEnabled: () => true,
+ mainInputEditor: editor as any,
+ refreshMessages: vi.fn(),
+ refreshTopic: vi.fn(),
+ });
+ });
+
+ const context = { agentId, threadId: null, topicId };
+ let sending!: Promise<unknown>;
+ await act(async () => {
+ sending = result.current.sendMessage({ context, message: 'hello' });
+ await reached;
+ });
+
+ act(() => {
+ const store = useChatStore.getState();
+ store.cancelOperations(
+ { ...context, status: 'running', type: INPUT_LOADING_OPERATION_TYPES },
+ MESSAGE_CANCEL_FLAT,
+ );
+ store.cancelSendMessageInServer(context, editor as any);
+ });
+ editor.getMarkdownContent.mockReturnValue(draftAfterStop);
+
+ await act(async () => {
+ release();
+ await sending;
+ });
+
+ return editor;
+};
+
+describe('Stop while a gateway send is starting', () => {
+ // ROOT CAUSE:
+ //
+ // The gateway start request is never aborted: the server persists the turn
+ // whatever the client does. A Stop while it was in flight still replayed the
+ // pre-send editor snapshot, so the composer held the text again while the
+ // persisted user message was back in the conversation: a duplicate.
+ //
+ // Before: the composer was restored. After: the message stays sent.
+ it('does not hand the text back once the start request is sent', async () => {
+ const editor = await sendAndStop({
+ finish: async () => ({ assistantMessageId: 'ast-1', topicId, userMessageId: 'usr-1' }),
+ sendRequest: true,
+ });
+
+ expect(editor.setJSONState).not.toHaveBeenCalled();
+ expect(editor.setDocument).not.toHaveBeenCalled();
+ });
+
+ // ROOT CAUSE:
+ //
+ // Before the request is sent, `executeGatewayAgent` rethrows the signal's
+ // abort reason (`'canceled'`, a string). The failed-send restore only knew
+ // `AbortError`s, so it also recorded the Stop as an "Unknown error" notice.
+ //
+ // Before: the composer came back with a send-error banner. After: silently.
+ it('still restores the composer silently when Stop lands before the request is sent', async () => {
+ const editor = await sendAndStop({
+ finish: (params) =>
+ Promise.reject(
+ useChatStore.getState().getOperationAbortSignal(params.parentOperationId).reason,
+ ),
+ sendRequest: false,
+ });
+
+ expect(editor.setJSONState).toHaveBeenCalledWith(typedDraft);
+ expect(editor.setDocument).not.toHaveBeenCalled();
+ const send = Object.values(useChatStore.getState().operations).find(
+ (operation) => operation.type === 'sendMessage',
+ );
+ expect(send?.status).toBe('cancelled');
+ expect(send?.metadata.inputSendErrorMsg).toBeUndefined();
+ });
+
+ it('hands the text back when the server refuses a turn stopped in flight', async () => {
+ const editor = await sendAndStop({
+ finish: () => Promise.reject(new Error('AgentConcurrencyLimitExceeded')),
+ sendRequest: true,
+ });
+
+ expect(editor.setDocument).toHaveBeenCalledWith('markdown', 'hello');
+ });
+
+ // ROOT CAUSE:
+ //
+ // The refusal now arrives after Stop, so the user may already be typing the
+ // next message. The restore wrote the refused text over that new draft.
+ //
+ // Before: the new draft was replaced. After: it is kept.
+ it('keeps a draft typed after Stop when the server later refuses the turn', async () => {
+ const editor = await sendAndStop({
+ draftAfterStop: 'a new draft',
+ finish: () => Promise.reject(new Error('AgentConcurrencyLimitExceeded')),
+ sendRequest: true,
+ });
+
+ expect(editor.setDocument).not.toHaveBeenCalled();
+ expect(editor.setJSONState).not.toHaveBeenCalled();
+ });
+
+ // ROOT CAUSE:
+ //
+ // The restorable snapshot was written only after the send's preflight awaits
+ // (topic lookup, device id). A Stop there found no snapshot to replay, and
+ // the abort that later reached the failed-send restore is skipped as a Stop,
+ // so the draft was never handed back.
+ //
+ // Before: the composer stayed empty. After: the exact draft comes back.
+ it('hands the draft back when Stop lands during the preflight awaits', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const editor = {
+ clearContent: vi.fn(),
+ getJSONState: vi.fn(() => typedDraft),
+ getMarkdownContent: vi.fn(() => ''),
+ setDocument: vi.fn(),
+ setJSONState: vi.fn(),
+ };
+ let releasePreflight!: () => void;
+ const preflight = new Promise<void>((resolve) => {
+ releasePreflight = resolve;
+ });
+ const resolveGatewayDeviceId = vi.fn(async () => {
+ await preflight;
+ return undefined;
+ });
+ vi.spyOn(getElectronStoreState(), 'resolveGatewayDeviceId').mockImplementation(
+ resolveGatewayDeviceId as any,
+ );
+ // Before sending, the real transport rethrows the aborted signal's reason.
+ const executeGatewayAgent = vi.fn(async (params: any) => {
+ const signal = useChatStore.getState().getOperationAbortSignal(params.parentOperationId);
+ if (signal.aborted) throw signal.reason;
+ return { topicId };
+ });
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeTopicId: topicId,
+ executeGatewayAgent: executeGatewayAgent as any,
+ isGatewayModeEnabled: () => true,
+ mainInputEditor: editor as any,
+ });
+ });
+
+ const context = { agentId, threadId: null, topicId };
+ let sending!: Promise<unknown>;
+ await act(async () => {
+ sending = result.current.sendMessage({ context, message: 'hello' });
+ await vi.waitFor(() => expect(resolveGatewayDeviceId).toHaveBeenCalled());
+ });
+
+ act(() => {
+ const store = useChatStore.getState();
+ store.cancelOperations(
+ { ...context, status: 'running', type: INPUT_LOADING_OPERATION_TYPES },
+ MESSAGE_CANCEL_FLAT,
+ );
+ store.cancelSendMessageInServer(context, editor as any);
+ });
+ expect(editor.setJSONState).toHaveBeenCalledWith(typedDraft);
+
+ await act(async () => {
+ releasePreflight();
+ await sending;
+ });
+
+ expect(executeGatewayAgent).toHaveBeenCalledOnce();
+ expect(editor.setJSONState).toHaveBeenCalledOnce();
+ expect(editor.setDocument).not.toHaveBeenCalled();
+ const send = Object.values(useChatStore.getState().operations).find(
+ (operation) => operation.type === 'sendMessage',
+ );
+ expect(send?.status).toBe('cancelled');
+ expect(send?.metadata.inputSendErrorMsg).toBeUndefined();
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.stopReclaim.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.stopReclaim.test.ts
index fce863f1823..7f852d753f7 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.stopReclaim.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.stopReclaim.test.ts
@@ -192,6 +192,7 @@ const startRun = async (
connectToGateway: vi.fn(),
getOperationAbortSignal: vi.fn(() => AbortSignal.abort()),
internal_pinTopicStatus: vi.fn(),
+ internal_dispatchMessage: vi.fn(),
internal_dispatchTopic: vi.fn(),
moveQueuedMessages: vi.fn(),
moveVoiceMessages: vi.fn(),
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
index 57c804096ae..4392983d95e 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -2163,8 +2163,7 @@ describe('GatewayActionImpl', () => {
// task exists and this client already knows its operation id.
const onMessageAccepted = vi.fn(() => controller.abort('user cancelled'));
const replaceMessages = vi.fn();
-
- const mockClient = createMockClient();
+ const internalDispatchMessage = vi.fn();
const internalDispatchTopic = vi.fn();
const internalPinTopicStatus = vi.fn();
// `refreshTopic` has already pulled in the server's running row: this
@@ -2198,6 +2197,7 @@ describe('GatewayActionImpl', () => {
completeOperation,
connectToGateway,
getOperationAbortSignal: vi.fn(() => controller.signal),
+ internal_dispatchMessage: internalDispatchMessage,
internal_dispatchTopic: internalDispatchTopic,
internal_pinTopicStatus: internalPinTopicStatus,
moveQueuedMessages,
@@ -2207,15 +2207,13 @@ describe('GatewayActionImpl', () => {
startOperation,
switchTopic: vi.fn(),
})) as any;
-
(globalThis as any).window = {
global_serverConfigStore: {
getState: () => ({ serverConfig: { agentGatewayUrl: 'https://gateway.test.com' } }),
},
};
-
const action = new GatewayActionImpl(set as any, get, undefined);
- action.createClient = vi.fn(() => mockClient);
+ action.createClient = vi.fn(() => createMockClient());
const interruptTaskSpy = vi
.mocked(aiAgentService.interruptTask)
.mockResolvedValue({ operationId: 'server-op-cancel', success: true });
@@ -2279,6 +2277,8 @@ describe('GatewayActionImpl', () => {
value: { metadata: { runningOperation: null } },
}),
);
+ const [mirrored] = internalDispatchMessage.mock.calls[0];
+ expect(mirrored).toMatchObject({ id: 'ast-1', value: { interruptedMidStream: true } });
});
/**
@@ -2333,6 +2333,7 @@ describe('GatewayActionImpl', () => {
completeOperation: vi.fn(),
connectToGateway: vi.fn(),
getOperationAbortSignal: vi.fn(() => controller.signal),
+ internal_dispatchMessage: vi.fn(),
internal_dispatchTopic: internalDispatchTopic,
internal_pinTopicStatus: internalPinTopicStatus,
internal_replaceTopicId: vi.fn(),
@@ -2344,13 +2345,11 @@ describe('GatewayActionImpl', () => {
startOperation: vi.fn(),
switchTopic: vi.fn(),
})) as any;
-
(globalThis as any).window = {
global_serverConfigStore: {
getState: () => ({ serverConfig: { agentGatewayUrl: 'https://gateway.test.com' } }),
},
};
-
const action = new GatewayActionImpl(set as any, get, undefined);
action.createClient = vi.fn(() => createMockClient());
vi.mocked(aiAgentService.interruptTask).mockResolvedValue({
@@ -2410,7 +2409,7 @@ describe('GatewayActionImpl', () => {
});
/**
- * @example A Stop while the start request is in flight still stops the run the server creates.
+ * @example A Stop while the start request is in flight stops the run and keeps the turn.
*/
it.each(['owner', 'share'] as const)(
'interrupts the %s server run when cancel aborts the in-flight start request',
@@ -2425,11 +2424,11 @@ describe('GatewayActionImpl', () => {
// thread failed with "already has an active writer".
//
// Before: no interrupt ever reached the orphaned server run.
- // After: the send still rejects at once, and the run is interrupted
- // when the server result arrives.
+ // After: it is interrupted when the result arrives, and the send keeps the
+ // persisted turn (rejecting it put the sent text back in the composer).
const controller = new AbortController();
const connectToGateway = vi.fn();
- const onMessageAccepted = vi.fn();
+ const [onMessageAccepted, onStartRequestSent] = [vi.fn(), vi.fn()];
const state: Record<string, any> = { gatewayConnections: {}, topicDataMap: {} };
const set = vi.fn((updater: any) => {
if (typeof updater === 'function') Object.assign(state, updater(state));
@@ -2441,6 +2440,7 @@ describe('GatewayActionImpl', () => {
completeOperation: vi.fn(),
connectToGateway,
getOperationAbortSignal: vi.fn(() => controller.signal),
+ internal_dispatchMessage: vi.fn(),
internal_dispatchTopic: vi.fn(),
internal_pinTopicStatus: vi.fn(),
moveQueuedMessages: vi.fn(),
@@ -2504,19 +2504,19 @@ describe('GatewayActionImpl', () => {
},
message: 'Hello',
onMessageAccepted,
+ onStartRequestSent,
parentOperationId: 'parent-send-msg-op',
});
const start =
surface === 'share' ? shareChatService.execAgentTask : aiAgentService.execAgentTask;
await vi.waitFor(() => expect(start).toHaveBeenCalledOnce());
+ expect(onStartRequestSent).toHaveBeenCalledOnce();
controller.abort('user cancelled');
- /** @example The send still settles as cancelled right away. */
- await expect(execution).rejects.toMatchObject({ name: 'AbortError' });
- expect(connectToGateway).not.toHaveBeenCalled();
- expect(onMessageAccepted).not.toHaveBeenCalled();
-
finishOnServer();
+ await expect(execution).resolves.toEqual(persisted);
+ expect(connectToGateway).not.toHaveBeenCalled();
+ expect(onMessageAccepted).toHaveBeenCalledOnce();
/** @example The orphaned server run is interrupted by its real operation id. */
if (surface === 'share') {
await vi.waitFor(() =>
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts
index add96592eaa..7bdb377afe8 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts
@@ -830,6 +830,11 @@ export class ConversationLifecycleActionImpl {
const steeredTurnStartTime = (metadata as Pick<MessageMetadata, 'steer'> | undefined)?.steer
? operationSelectors.getLatestAgentRuntimeTurnStartTime(operationContext)(this.#get())
: undefined;
+ // Editor state for cancel restoration, on the op from its start: a Stop during
+ // the preflight awaits below must find it, or the draft is never handed back.
+ const jsonState = preserveComposer
+ ? undefined
+ : (inputEditorData ?? targetInputEditor?.getJSONState());
const { operationId, abortController } = this.#get().startOperation({
type: 'sendMessage',
context: { ...operationContext, messageId: tempId },
@@ -837,6 +842,7 @@ export class ConversationLifecycleActionImpl {
metadata: {
// Mark this as thread operation if threadId exists
inThread: !!operationContext.threadId,
+ inputEditorTempState: jsonState,
...(steeredTurnStartTime === undefined ? {} : { turnStartTime: steeredTurnStartTime }),
},
});
@@ -865,12 +871,12 @@ export class ConversationLifecycleActionImpl {
const restoreComposerAfterFailedSend = (error: unknown) => {
if (preserveComposer || hasNotifiedMessageAccepted) return;
- // Cancellation is a deliberate user action with its own restore path
- // (`inputEditorTempState` is replayed by the cancel flow); re-filling the
- // composer here would fight it.
+ // A Stop (an AbortError, or the signal's own reason a transport rethrows) has its
+ // own restore path (the cancel flow replays `inputEditorTempState`); don't fight it.
const isAbort =
- error instanceof Error &&
- (error.message.includes('aborted') || error.name === 'AbortError');
+ (abortController.signal.aborted && error === abortController.signal.reason) ||
+ (error instanceof Error &&
+ (error.message.includes('aborted') || error.name === 'AbortError'));
if (isAbort) return;
this.#get().updateOperationMetadata(operationId, {
@@ -1367,15 +1373,6 @@ export class ConversationLifecycleActionImpl {
optimisticTopicActive = true;
}
- // Store editor state in operation metadata for cancel restoration
- const jsonState = preserveComposer
- ? undefined
- : (inputEditorData ?? targetInputEditor?.getJSONState());
- this.#get().updateOperationMetadata(operationId, {
- inputEditorTempState: jsonState,
- inputSendErrorMsg: undefined,
- });
-
// ── External agent mode: delegate to heterogeneous agent CLI (desktop only) ──
// Per-agent heterogeneousProvider config takes priority over the global gateway mode.
if (runtimeType === 'hetero' && heterogeneousProvider) {
@@ -1722,11 +1719,10 @@ export class ConversationLifecycleActionImpl {
// ── Gateway mode: skip sendMessageInServer, let execAgentTask handle everything ──
if (runtimeType === 'gateway' && !directMentionRoute) {
try {
- // Pass `sendMessage` as `parentOperationId` so executeGatewayAgent
- // completes it the instant phase-1 init finishes (after the child
- // `execServerAgentRuntime` op starts). Without this hand-off the
- // input loading state would drop during the execAgentTask round-trip
- // and the send button would flicker back to "send".
+ // Pass `sendMessage` as `parentOperationId`: executeGatewayAgent completes it once
+ // phase-1 init finishes, so the send button doesn't flicker back during the
+ // round-trip. Once the request is out the server persists the turn, so a Stop
+ // keeps it in the chat instead of handing the text back to the composer.
const result = await this.#get().executeGatewayAgent({
// Ids and branch tail the optimistic rows render under; the server honours
// them like sendMessageInServer, so the turn stays on the visible branch.
@@ -1753,6 +1749,8 @@ export class ConversationLifecycleActionImpl {
? { ...requestMetadata, steer: true }
: requestMetadata,
onMessageAccepted: notifyMessageAccepted,
+ onStartRequestSent: () =>
+ this.#get().updateOperationMetadata(operationId, { inputEditorTempState: null }),
onTopicCreated: context.isolatedTopic ? onTopicCreated : undefined,
parentOperationId: operationId,
clientOperations,
@@ -1842,11 +1840,10 @@ export class ConversationLifecycleActionImpl {
userMessageId: result.userMessageId,
};
} catch (e) {
- // User cancelled during phase-1 init β€” `cancelOperation` already set
- // the op to 'cancelled' and `executeGatewayAgent` cleaned up the
- // server task. Don't clobber that with 'failed'.
+ // A Stop keeps 'cancelled'; a refused turn gets its text back unless typed over.
const op = this.#get().operations[operationId];
if (op?.status === 'cancelled') {
+ if (!targetInputEditor?.getMarkdownContent?.().trim()) restoreComposerAfterFailedSend(e);
cleanupTempMessages({
preserveOptimisticUser: Boolean(optimisticUserMessageId && !hasNotifiedMessageAccepted),
});
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 ccf66f47c84..b09a575f1ab 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -73,7 +73,7 @@ import { createGatewayEventBuffer } from './gatewayEventBuffer';
import { createGatewayEventHandler } from './gatewayEventHandler';
import { createGatewayEventRouter } from './gatewayEventRouter';
import { createGatewayMemberStreamHandler, mergeGroupSnapshot } from './gatewayMemberStreamHandler';
-import { awaitStartRequest, interruptGatewayTaskOrThrow } from './gatewayStartRequest';
+import { interruptGatewayTaskOrThrow } from './gatewayStartRequest';
import { resolveInitialTopicMetadata } from './initialTopicMetadata';
import {
type GatewayMuxIdentity,
@@ -940,6 +940,8 @@ export class GatewayActionImpl {
metadata?: Pick<MessageMetadata, 'steer' | 'trigger'>;
/** Called as soon as phase-1 returns with a persisted user message. */
onMessageAccepted?: () => void;
+ /** Called once the start request is sent: a Stop can no longer take the turn back. */
+ onStartRequestSent?: () => void;
/** Called when a new topic is persisted, before UI hydration and stream setup. */
onTopicCreated?: (topicId: string) => void | Promise<void>;
/** Called when the gateway session completes (agent finished running) */
@@ -1035,6 +1037,7 @@ export class GatewayActionImpl {
metadata,
onComplete,
onMessageAccepted,
+ onStartRequestSent,
newTopicMetadata,
onTopicCreated,
optimisticTopic,
@@ -1078,12 +1081,11 @@ export class GatewayActionImpl {
// Honour user-initiated cancel during phase-1 init: while we await the
// execAgentTask round-trip the caller's loading state is still running, so
- // the ChatInput stop button is active. Forward the abort into the
- // round-trip wait (never into the fetch itself, see `awaitStartRequest`):
- // the send rejects at once and the run the server still creates is
- // interrupted when its result arrives, as is a run the intervention claim
- // already precreated. If the server has already persisted the turn,
- // interrupt generation but still reconcile the message locally.
+ // the ChatInput stop button is active. A Stop before the request is sent
+ // rejects the send. After that the abort never reaches the fetch: the server
+ // persists the turn regardless, so the run it creates (or the intervention
+ // claim already precreated) is interrupted when its result arrives and the
+ // persisted turn is reconciled locally.
const abortSignal = parentOperationId
? this.#get().getOperationAbortSignal(parentOperationId)
: undefined;
@@ -1108,73 +1110,61 @@ export class GatewayActionImpl {
// config, never by this client.
const agentShareId = executionContext.agentShareId;
- const serverResult =
- precreatedResult ??
- (agentShareId
- ? await awaitStartRequest(
- shareChatService.execAgentTask({
- clientIds,
- fileIds,
- parentMessageId,
- prompt: message,
- resumeApproval,
- resumeApprovals,
- resumeToolResult,
- shareId: agentShareId,
- steer: metadata?.steer,
- topicId: executionContext.topicId,
- userInterventionConfig,
+ const startRequest = precreatedResult
+ ? undefined
+ : agentShareId
+ ? shareChatService.execAgentTask({
+ clientIds,
+ fileIds,
+ parentMessageId,
+ prompt: message,
+ resumeApproval,
+ resumeApprovals,
+ resumeToolResult,
+ shareId: agentShareId,
+ steer: metadata?.steer,
+ topicId: executionContext.topicId,
+ userInterventionConfig,
+ })
+ : aiAgentService.execAgentTask({
+ agentId: executionContext.agentId,
+ // Fresh sends only β€” resume flows never pass this, and the server drops
+ // it defensively on resume-like params anyway.
+ clientIds,
+ appContext: buildExecAppContext(this.#get, {
+ executionContext,
+ initialTopicMetadata,
+ messageContext,
+ newTopicProject: isCreateNewTopic ? { projectId, projectWorkingDirectoryId } : {},
}),
- abortSignal,
- (abandoned) =>
- shareChatService.interruptTask(
- agentShareId,
- abandoned.topicId,
- abandoned.operationId,
- ),
- )
- : await awaitStartRequest(
- aiAgentService.execAgentTask({
- agentId: executionContext.agentId,
- // Fresh sends only β€” resume flows never pass this, and the server drops
- // it defensively on resume-like params anyway.
- clientIds,
- appContext: buildExecAppContext(this.#get, {
- executionContext,
- initialTopicMetadata,
- messageContext,
- newTopicProject: isCreateNewTopic ? { projectId, projectWorkingDirectoryId } : {},
- }),
- ...desktopDeviceHints,
- clientOperations,
- fileIds,
- replacesOperationId,
- mentionedAgents,
- parentMessageId,
- prompt: message,
- resumeApproval,
- resumeApprovals,
- resumeToolResult,
- selectedSkillIds,
- selectedToolIds,
- // A queued follow-up keeps its continuation mark on the row the
- // server persists, which replaces the optimistic one.
- steer: metadata?.steer,
- trigger: metadata?.trigger,
- userInterventionConfig,
- userMessage,
- // Dual-write for servers that predate `userMessage` (they read only these
- // top-level fields and strip the rest); a current server folds them in.
- contextSelections: userMessage?.metadata?.contextSelections,
- pageSelections: userMessage?.metadata?.pageSelections,
- }),
- abortSignal,
- (abandoned) =>
- interruptGatewayTaskOrThrow({
- operationId: abandoned.operationId,
- topicId: abandoned.topicId,
- }),
- ));
+ ...desktopDeviceHints,
+ clientOperations,
+ fileIds,
+ replacesOperationId,
+ mentionedAgents,
+ parentMessageId,
+ prompt: message,
+ resumeApproval,
+ resumeApprovals,
+ resumeToolResult,
+ selectedSkillIds,
+ selectedToolIds,
+ // A queued follow-up keeps its continuation mark on the row the
+ // server persists, which replaces the optimistic one.
+ steer: metadata?.steer,
+ trigger: metadata?.trigger,
+ userInterventionConfig,
+ userMessage,
+ // Dual-write for servers that predate `userMessage` (they read only these
+ // top-level fields and strip the rest); a current server folds them in.
+ contextSelections: userMessage?.metadata?.contextSelections,
+ pageSelections: userMessage?.metadata?.pageSelections,
+ });
+ // Once sent, the server persists the turn whatever the caller does, so a
+ // Stop from here on is a late cancel: the interrupt below stops the run and
+ // the persisted turn is reconciled instead of being taken back.
+ if (startRequest) onStartRequestSent?.();
+ const serverResult = precreatedResult ?? (await startRequest!);
// A member continuation names the supervisor's run as `operationId` (safe
// for older clients); this run is the member's continuation.
const result: ExecAgentResult =
@@ -1386,6 +1376,16 @@ export class GatewayActionImpl {
operationId: result.operationId,
topicId,
});
+ // No socket reports the end: mirror the server's stopped-placeholder marker.
+ if (cancelledAfterPersistence && result.assistantMessageId)
+ this.#get().internal_dispatchMessage(
+ {
+ id: result.assistantMessageId,
+ type: 'updateMessageMetadata',
+ value: { interruptedMidStream: true },
+ },
+ { conversationContext: resolvedMessageContext },
+ );
});
}
if (parentOperationId) this.#get().completeOperation(parentOperationId);
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayStartRequest.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayStartRequest.ts
index 5ef53b49e74..3692d0e7f07 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayStartRequest.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayStartRequest.ts
@@ -19,48 +19,3 @@ export const interruptGatewayTaskOrThrow = async (
);
}
};
-
-/**
- * Waits for a server start request while honoring a caller abort locally.
- *
- * Use when:
- * - The ChatInput Stop can fire while `execAgentTask` is still in flight.
- *
- * Expects:
- * - `request` was issued WITHOUT the abort signal. Aborting the fetch only
- * drops the response: the server still persists the turn and dispatches the
- * run (for a connected device, it spawns the native CLI), and the client
- * would never learn the operation id needed to stop it.
- *
- * Returns:
- * - The server result, or rejects with an AbortError as soon as the caller
- * aborts. After such an abort, `onAbandoned` receives the result the server
- * eventually returns so the caller can interrupt that orphaned run.
- */
-export const awaitStartRequest = <T>(
- request: Promise<T>,
- signal: AbortSignal | undefined,
- onAbandoned: (result: T) => Promise<unknown>,
-): Promise<T> => {
- if (!signal) return request;
-
- return new Promise<T>((resolve, reject) => {
- const onAbort = () => {
- reject(new DOMException('Message send was cancelled', 'AbortError'));
- request
- .then(onAbandoned)
- .catch((error) => console.error('[Gateway] interrupt after aborted start failed:', error));
- };
- signal.addEventListener('abort', onAbort, { once: true });
- request.then(
- (result) => {
- signal.removeEventListener('abort', onAbort);
- resolve(result);
- },
- (error) => {
- signal.removeEventListener('abort', onAbort);
- reject(error);
- },
- );
- });
-};