The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(chat): preserve stopped assistant turns
Steven Enamakel7eb87f51e1aa
diff --git a/app/src/features/conversations/Conversations.tsx b/app/src/features/conversations/Conversations.tsxindex e47bc80196..3fc57ada9a 100644--- a/app/src/features/conversations/Conversations.tsx+++ b/app/src/features/conversations/Conversations.tsx@@ -76,7 +76,6 @@ import { useAppDispatch, useAppSelector } from '../../store/hooks';import { pendingFollowupAdded } from '../../store/queueSlice';import { selectSocketStatus } from '../../store/socketSelectors';import {- addInferenceResponse,addMessageLocal,clearCreateThreadError,clearThreadInferenceActive,@@ -510,7 +509,6 @@ const Conversations = ({// ids whose partial reply has already been persisted, so a repeated Stop/ESC// fired before the `cancelled` event clears the live stream can't append the// same partial twice.- const stoppedRequestIdsRef = useRef<Set<string>>(new Set());// Threads with an in-flight send, guarding against double-submit to the SAME// thread. Per-thread (a Set) so a send to thread B isn't blocked by an// in-flight send to thread A.@@ -1301,40 +1299,16 @@ const Conversations = ({// Cancel control (mic-cloud / voice modes) so the cancel path lives in one// place.//- // Any assistant text already streamed for this turn is persisted as its own- // message flagged `stopped: true` so the partial output stays in the- // transcript (clearly marked) instead of vanishing when the `cancelled`- // chat_error clears the live streaming preview (#4862). The matching- // `onError` path deliberately appends no message for `cancelled`, so this can- // never double-render the partial reply.- //- // Persistence is gated on the cancel actually being accepted: `chatCancel`- // resolves `false` (no throw) when the socket is down or the RPC is rejected,- // and in that case the original turn may keep running and later append its- // own final response — so persisting a partial here would leave a- // misleading/duplicate bubble. On failure we release the one-shot claim so a- // retry can still preserve the partial once cancellation succeeds.+ // `ChatRuntimeProvider.onCancelled` persists the partial and its processing+ // trail after the core confirms cancellation. Keeping that in one place also+ // covers turns superseded without a local Stop click.const handleStopGeneration = useCallback(() => {if (!selectedThreadId) {debug('[chat] stop generation: no selected thread — noop');return;}const threadId = selectedThreadId;- const streaming = streamingAssistantByThread[threadId];- const partial = streaming?.content ?? '';- const requestId = streaming?.requestId;- // Claim the turn synchronously so a second Stop/ESC in the same tick (before- // the cancel round-trips) can't queue a duplicate persist.- const shouldPersist =- partial.trim().length > 0 && (!requestId || !stoppedRequestIdsRef.current.has(requestId));- if (shouldPersist && requestId) stoppedRequestIdsRef.current.add(requestId);- debug(- '[chat] stop generation: thread=%s request=%s partialLen=%d willPersist=%s',- threadId,- requestId ?? 'none',- partial.trim().length,- shouldPersist- );+ debug('[chat] stop generation: thread=%s', threadId);void chatCancel(threadId).then(outcome => {const accepted = outcome?.accepted === true;const turnCancelled = outcome?.turnCancelled === true;@@ -1344,12 +1318,6 @@ const Conversations = ({accepted,turnCancelled);- if (!accepted || !turnCancelled) {- // Cancel not accepted, or the core had no turn to tear down: don't leave- // a misleading partial, and release the claim so a later Stop/ESC can- // persist once cancellation goes through.- if (shouldPersist && requestId) stoppedRequestIdsRef.current.delete(requestId);- }if (!accepted) return;if (!turnCancelled) {// The core has nothing running on this thread, so no `cancelled`@@ -1372,26 +1340,8 @@ const Conversations = ({dispatch(clearThreadInferenceActive(threadId));return;}- if (shouldPersist) {- void dispatch(- addInferenceResponse({- content: partial,- threadId,- // `cancelReason: 'user_stop'` is what the vendored `StoppedRun`- // element's reason chip reads (`thread.tsx`'s `StoppedRunSlot`);- // this is the user-initiated Stop path, as opposed to the core- // superseding the turn (`chat_cancelled{cancel_reason:- // "superseded"}`, handled in `ChatRuntimeProvider`).- extraMetadata: {- stopped: true,- cancelReason: 'user_stop',- ...(requestId ? { requestId } : {}),- },- })- ).then(() => debug('[chat] stop generation: persisted stopped reply thread=%s', threadId));- }});- }, [selectedThreadId, streamingAssistantByThread, dispatch, clearSilenceTimer]);+ }, [selectedThreadId, dispatch, clearSilenceTimer]);handleStopGenerationRef.current = handleStopGeneration;diff --git a/app/src/providers/ChatRuntimeProvider.tsx b/app/src/providers/ChatRuntimeProvider.tsxindex 287073660a..7898c5e13b 100644--- a/app/src/providers/ChatRuntimeProvider.tsx+++ b/app/src/providers/ChatRuntimeProvider.tsx@@ -1476,18 +1476,13 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {},/*** `chat_cancelled` (wire-contract.md) — the core-authoritative sibling- * of the local Stop path in `Conversations.tsx`'s `handleStopGeneration`- * (which persists a `cancelReason: 'user_stop'` partial optimistically,- * before the core confirms). This handler is what also covers a turn- * the core cancels on its OWN initiative — `cancel_reason: 'superseded'`- * when a newer send interrupts it — which has no local Stop click to- * persist from.+ * of the Stop path in `Conversations.tsx`. It persists the partial+ * after core confirmation, including `cancel_reason: 'superseded'`+ * when a newer send interrupts the turn without a Stop click.** The core keeps emitting `chat_error{error_type:"cancelled"}`- * alongside this for one release (that path appends no message — see- * its own comment below), so this dedupes on `request_id` against- * whatever `handleStopGeneration` already persisted rather than- * assuming it is the only writer.+ * alongside this for one release. That earlier compatibility event+ * must leave the stream intact until this handler saves it.*/onCancelled: (event: ChatCancelledEvent) => {const eventKey = `cancelled:${event.thread_id}:${event.request_id ?? 'none'}`;@@ -1507,8 +1502,39 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {// any runtime state below — those dispatches are what the partial and// the "already persisted?" check would otherwise be racing against.const stateBefore = store.getState();- const partial =- stateBefore.chatRuntime.streamingAssistantByThread[event.thread_id]?.content ?? '';+ if (+ event.request_id &&+ stateBefore.chatRuntime.parallelRequestThreads[event.request_id] !== undefined+ ) {+ const requestId = event.request_id;+ const parallelPartial =+ stateBefore.chatRuntime.parallelStreamsByThread[event.thread_id]?.[requestId]+ ?.content ?? '';+ if (parallelPartial.trim()) {+ void dispatch(+ addInferenceResponse({+ content: parallelPartial,+ threadId: event.thread_id,+ extraMetadata: chatCancelledExtraMetadata(event),+ })+ ).then(() => dispatch(clearParallelRequest({ requestId })));+ } else {+ dispatch(clearParallelRequest({ requestId }));+ }+ return;+ }+ const liveRequestId =+ stateBefore.chatRuntime.liveRequestIdByThread[event.thread_id] ??+ stateBefore.chatRuntime.streamingAssistantByThread[event.thread_id]?.requestId;+ const sameTurn =+ !event.request_id || !liveRequestId || event.request_id === liveRequestId;+ const partial = sameTurn+ ? (stateBefore.chatRuntime.streamingAssistantByThread[event.thread_id]?.content ?? '')+ : '';+ const hasProcessing =+ sameTurn &&+ ((stateBefore.chatRuntime.processingByThread[event.thread_id]?.length ?? 0) > 0 ||+ (stateBefore.chatRuntime.toolTimelineByThread[event.thread_id]?.length ?? 0) > 0);const threadMessages = stateBefore.thread.messagesByThreadId[event.thread_id] ?? [];const alreadyStopped = event.request_id? threadMessages.some(message => {@@ -1519,23 +1545,26 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {}): false;- dispatch(clearInferenceStatusForThread({ threadId: event.thread_id }));- dispatch(clearStreamingAssistantForThread({ threadId: event.thread_id }));- dispatch(clearPendingApprovalForThread({ threadId: event.thread_id }));- dispatch(clearPendingPlanReviewForThread({ threadId: event.thread_id }));-- if (!alreadyStopped && partial.trim().length > 0) {+ const settle = () => {+ if (sameTurn) {+ dispatch(cancelUnresolvedTurnTimeline({ threadId: event.thread_id }));+ }+ dispatch(turnSettled({ threadId: event.thread_id, requestId: event.request_id }));+ if (sameTurn) dispatch(clearThreadInferenceActive(event.thread_id));+ };+ // An answer can consist entirely of reasoning, narration or tool+ // activity. Persist an empty stopped row to anchor that trail too.+ if (!alreadyStopped && (partial.trim().length > 0 || hasProcessing)) {void dispatch(addInferenceResponse({content: partial,threadId: event.thread_id,extraMetadata: chatCancelledExtraMetadata(event),})- );+ ).then(settle);+ } else {+ settle();}-- dispatch(endInferenceTurn({ threadId: event.thread_id }));- dispatch(clearThreadInferenceActive(event.thread_id));},onDone: event => {const eventKey = `done:${event.thread_id}:${event.request_id ?? 'none'}`;@@ -1784,6 +1813,10 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {}}+ // The core sends this compatibility event before `chat_cancelled`.+ // Leave the live stream and turn intact for that authoritative event.+ if (event.error_type === 'cancelled') return;+// Parallel (forked) turn error: resolve only its lane, leaving the// primary turn untouched. Surface a non-cancellation error as a message// so the failed branch is visible.@@ -1795,17 +1828,15 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {segmentDeliveriesRef.current,segmentDeliveryKey(event.thread_id, event.request_id));- if (event.error_type !== 'cancelled') {- const errorContent = event.message || '';- void dispatch(- addInferenceResponse({- content: errorContent,- threadId: event.thread_id,- extraMetadata: chatErrorExtraMetadata(event),- })- );- requestUsageRefresh();- }+ const errorContent = event.message || '';+ void dispatch(+ addInferenceResponse({+ content: errorContent,+ threadId: event.thread_id,+ extraMetadata: chatErrorExtraMetadata(event),+ })+ );+ requestUsageRefresh();dispatch(clearParallelRequest({ requestId: event.request_id }));return;}@@ -1827,48 +1858,46 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {dispatch(setToolTimelineForThread({ threadId: event.thread_id, entries }));}- if (event.error_type !== 'cancelled') {- const currentState = store.getState();- const threadMessages = currentState.thread.messagesByThreadId[event.thread_id] ?? [];- const lastMsg = threadMessages[threadMessages.length - 1];- // Every error_type — including the generic 'inference' fallback — carries a- // user-facing `message` produced by classify_inference_error() in web_errors.rs.- // For 'inference' that message is the friendly summary PLUS the real, sanitized- // upstream provider error appended as a `> quote` block (secret-scrubbed and- // length-capped server-side via with_provider_detail()/sanitize_api_error()), so- // surfacing it tells the user *why* the turn failed instead of a blanket apology.- // An empty message still becomes an error-status row; assistant-ui- // supplies its own fallback in the error card.- const errorContent = event.message || '';- // A core-owned failure carries a deterministic id, so dedupe on that- // rather than on the text. Two runs can fail with byte-identical- // content — the same upstream provider message, or the generic- // fallback above — and a text check would then read the previous- // run's row as this one and drop the current failure from the cache.- // Interactive turns have no pre-persisted id and keep the text check.- const errorMessageId = corePersistedMessageId(event);- const alreadyPresent = errorMessageId- ? threadMessages.some(message => message.id === errorMessageId)- : lastMsg?.sender === 'agent' && lastMsg?.content === errorContent;- if (!alreadyPresent) {- void dispatch(- addInferenceResponse({- content: errorContent,- threadId: event.thread_id,- messageId: errorMessageId,- extraMetadata: chatErrorExtraMetadata(event),- })- );- }-- rtLog('refresh_usage_counter', {- thread: event.thread_id,- request: event.request_id,- reason: 'chat_error',- });- requestUsageRefresh();+ const currentState = store.getState();+ const threadMessages = currentState.thread.messagesByThreadId[event.thread_id] ?? [];+ const lastMsg = threadMessages[threadMessages.length - 1];+ // Every error_type — including the generic 'inference' fallback — carries a+ // user-facing `message` produced by classify_inference_error() in web_errors.rs.+ // For 'inference' that message is the friendly summary PLUS the real, sanitized+ // upstream provider error appended as a `> quote` block (secret-scrubbed and+ // length-capped server-side via with_provider_detail()/sanitize_api_error()), so+ // surfacing it tells the user *why* the turn failed instead of a blanket apology.+ // An empty message still becomes an error-status row; assistant-ui+ // supplies its own fallback in the error card.+ const errorContent = event.message || '';+ // A core-owned failure carries a deterministic id, so dedupe on that+ // rather than on the text. Two runs can fail with byte-identical+ // content — the same upstream provider message, or the generic+ // fallback above — and a text check would then read the previous+ // run's row as this one and drop the current failure from the cache.+ // Interactive turns have no pre-persisted id and keep the text check.+ const errorMessageId = corePersistedMessageId(event);+ const alreadyPresent = errorMessageId+ ? threadMessages.some(message => message.id === errorMessageId)+ : lastMsg?.sender === 'agent' && lastMsg?.content === errorContent;+ if (!alreadyPresent) {+ void dispatch(+ addInferenceResponse({+ content: errorContent,+ threadId: event.thread_id,+ messageId: errorMessageId,+ extraMetadata: chatErrorExtraMetadata(event),+ })+ );}+ rtLog('refresh_usage_counter', {+ thread: event.thread_id,+ request: event.request_id,+ reason: 'chat_error',+ });+ requestUsageRefresh();+// The backend drains + dispatches queued follow-ups even when the turn// errored, so flush them to the transcript here too (otherwise their// prompts are lost). Mirrors the done path (sequential internally).diff --git a/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx b/app/src/providers/__tests__/ChatRuntimeProvider.test.tsxindex a81b8c8bdc..b2d61054b8 100644--- a/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx+++ b/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx@@ -14,6 +14,7 @@ import {resetSessionTokenUsage,setPendingPlanReviewForThread,setStreamingAssistantForThread,+ streamDeltaReceived,} from '../../store/chatRuntimeSlice';import { pendingFollowupAdded } from '../../store/queueSlice';import { setStatusForUser } from '../../store/socketSlice';@@ -2479,6 +2480,145 @@ describe('ChatRuntimeProvider — chat_cancelled (wire-contract.md)', () => {);});+ it('keeps the partial when the core sends cancelled chat_error before chat_cancelled', async () => {+ const listeners = renderProvider();+ const threadId = 't-stop-event-order';++ act(() => {+ store.dispatch(+ setStreamingAssistantForThread({+ threadId,+ streaming: { content: 'answer so far', thinking: '', requestId: 'r-stop' },+ })+ );+ listeners.onError?.({+ thread_id: threadId,+ request_id: 'r-stop',+ message: 'Cancelled',+ error_type: 'cancelled',+ round: 0,+ });+ listeners.onCancelled?.({+ thread_id: threadId,+ request_id: 'r-stop',+ cancel_reason: 'user_stop',+ });+ });++ await waitFor(() =>+ expect(threadApi.appendMessage).toHaveBeenCalledWith(+ threadId,+ expect.objectContaining({+ content: 'answer so far',+ extraMetadata: expect.objectContaining({+ stopped: true,+ cancelReason: 'user_stop',+ requestId: 'r-stop',+ }),+ })+ )+ );+ expect(threadApi.appendMessage).toHaveBeenCalledTimes(1);+ });++ it('anchors a stopped turn whose output was only processing activity', async () => {+ const listeners = renderProvider();+ const threadId = 't-processing-stop';++ act(() => {+ store.dispatch(+ streamDeltaReceived({+ threadId,+ requestId: 'r-thinking',+ round: 1,+ delta: 'considering the request',+ channel: 'thinking',+ at: Date.now(),+ })+ );+ listeners.onError?.({+ thread_id: threadId,+ request_id: 'r-thinking',+ message: 'Cancelled',+ error_type: 'cancelled',+ round: 1,+ });+ listeners.onCancelled?.({+ thread_id: threadId,+ request_id: 'r-thinking',+ cancel_reason: 'user_stop',+ });+ });++ await waitFor(() =>+ expect(threadApi.appendMessage).toHaveBeenCalledWith(+ threadId,+ expect.objectContaining({+ content: '',+ extraMetadata: expect.objectContaining({ stopped: true, requestId: 'r-thinking' }),+ })+ )+ );+ await waitFor(() =>+ expect(store.getState().chatRuntime.settledTurnsByThread[threadId]?.['r-thinking']).toEqual(+ expect.objectContaining({+ transcript: expect.arrayContaining([+ expect.objectContaining({ kind: 'thinking', text: 'considering the request' }),+ ]),+ })+ )+ );+ });++ it('stops a parallel branch without clearing the primary turn', async () => {+ const listeners = renderProvider();+ const threadId = 't-parallel-stop';++ act(() => {+ store.dispatch(registerParallelRequest({ threadId, requestId: 'r-branch' }));+ store.dispatch(+ setStreamingAssistantForThread({+ threadId,+ streaming: { content: 'primary continues', thinking: '', requestId: 'r-primary' },+ })+ );+ store.dispatch(+ streamDeltaReceived({+ threadId,+ requestId: 'r-branch',+ round: 1,+ delta: 'branch partial',+ channel: 'content',+ })+ );+ listeners.onError?.({+ thread_id: threadId,+ request_id: 'r-branch',+ message: 'Cancelled',+ error_type: 'cancelled',+ round: 1,+ });+ listeners.onCancelled?.({+ thread_id: threadId,+ request_id: 'r-branch',+ cancel_reason: 'user_stop',+ });+ });++ await waitFor(() =>+ expect(threadApi.appendMessage).toHaveBeenCalledWith(+ threadId,+ expect.objectContaining({ content: 'branch partial' })+ )+ );+ await waitFor(() =>+ expect(store.getState().chatRuntime.parallelRequestThreads['r-branch']).toBeUndefined()+ );+ expect(store.getState().chatRuntime.streamingAssistantByThread[threadId]?.content).toBe(+ 'primary continues'+ );+ });+it('does not double-persist a partial the local Stop path already saved for the same request', async () => {const listeners = renderProvider();const threadId = 't-chat-cancelled-dedupe';diff --git a/app/test/e2e/specs/chat-harness-cancel.spec.ts b/app/test/e2e/specs/chat-harness-cancel.spec.tsindex 826bf4b97c..0b46b6b25b 100644--- a/app/test/e2e/specs/chat-harness-cancel.spec.ts+++ b/app/test/e2e/specs/chat-harness-cancel.spec.ts@@ -18,8 +18,8 @@* - IN_FLIGHT clears (Rust side).* - The DOM never accumulates the final two chunks.* - Send button becomes enabled again.- * 5. The conversation file on disk does NOT contain the full reply- * (the cancel happened before the assistant finished).+ * 5. The early partial remains visible and persisted, while the late+ * chunks never land.** This is the second hardest scenario in the chat pipeline — the first* being the streaming reply itself. If cancel breaks, in-flight chats@@ -59,6 +59,7 @@ const SLOW_SCRIPT = [const EARLY_PIECES = ['one ', 'two '];const LATE_PIECES = ['five ', 'six.'];let cancelAttempted = false;+let sawEarlyDelta = false;/*** Click the composer's mid-stream cancel control. In the text composer the Send@@ -116,6 +117,7 @@ describe('Chat harness — mid-stream cancel', () => {it('sends → IN_FLIGHT populates → Cancel clears it before late chunks land', async () => {cancelAttempted = false;+ sawEarlyDelta = false;setMockBehavior('llmStreamScript', JSON.stringify(SLOW_SCRIPT));setMockBehavior('llmStreamChunkDelayMs', '500');@@ -182,6 +184,7 @@ describe('Chat harness — mid-stream cancel', () => {timeoutMsg: 'first delta never landed before cancel attempt',}).catch(() => false);+ sawEarlyDelta = sawFirstDelta;if (!sawFirstDelta) {console.warn('[chat-harness-cancel] first delta was not visible before cancel; attempting cancel from in-flight state'@@ -208,6 +211,9 @@ describe('Chat harness — mid-stream cancel', () => {const present = await textExists(piece);expect(present).toBe(false);}+ if (sawFirstDelta) {+ expect(await textExists(EARLY_PIECES[0])).toBe(true);+ }});it('after cancel, the composer (textarea + send button) is interactive again', async () => {@@ -249,15 +255,17 @@ describe('Chat harness — mid-stream cancel', () => {expect(typeof threadId).toBe('string');const relPath = `memory/conversations/threads/${hexEncodeThreadId(threadId as string)}.jsonl`;- // The store may or may not record the partial assistant turn — both- // are acceptable. What we lock down is the contract that the- // LATE_PIECES never reach the persisted file.+ // The stopped reply should be durable, with no chunks after Stop.const read = await callOpenhumanRpc<{ result: { content_utf8: string } }>('openhuman.test_support_read_workspace_file',{ rel_path: relPath, max_bytes: 131_072 });- if (!read.ok) return; // No file yet → nothing to violate, also fine.+ if (sawEarlyDelta) expect(read.ok).toBe(true);+ if (!read.ok) return;const content = read.result?.result?.content_utf8 ?? '';+ if (sawEarlyDelta) {+ expect(content.includes(EARLY_PIECES[0])).toBe(true);+ }for (const piece of LATE_PIECES) {expect(content.includes(piece)).toBe(false);}