Skip to content

The agent that grows with you

fix(desktop): a steer flushes buffered text first, and a lost tool result can't outlive the turn

Tekniumf14699a13798
diff --git a/apps/desktop/src/app/chat/session-tile-actions.ts b/apps/desktop/src/app/chat/session-tile-actions.ts
index 960212037a8..a248b165be8 100644
--- a/apps/desktop/src/app/chat/session-tile-actions.ts
+++ b/apps/desktop/src/app/chat/session-tile-actions.ts
@@ -39,6 +39,7 @@ import {
sessionTileOwnerRoute
} from '@/store/session-states'
import { broadcastSessionsChanged } from '@/store/session-sync'
+import { flushStreamDeltas } from '@/store/stream-delta-flush'
import { clearSessionSubagents } from '@/store/subagents'
import { clearSessionTodos } from '@/store/todos'
import { setSessionDraftingTool } from '@/store/tool-drafting'
@@ -477,6 +478,7 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored
if (result?.status === 'redirected') {
if (mode === 'interrupt') {
+ flushStreamDeltas(sessionId)
mutate(state => sealAcceptedCorrection(state, messageId))
}
@@ -489,6 +491,7 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored
// A redirect queued in the build window is the next turn; an
// accepted steer joins this one after its running tool.
if (mode === 'steer') {
+ flushStreamDeltas(sessionId)
mutate(state => sealAcceptedCorrection(state, messageId, { keepRunningTools: true }))
} else {
moveOptimisticMessageToEnd()
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/index.ts b/apps/desktop/src/app/session/hooks/use-message-stream/index.ts
index 539c287f6d2..4035aaaa1eb 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/index.ts
@@ -34,6 +34,7 @@ import type { ScopedServerRequest } from '@/store/gateway'
import { dispatchNativeNotification } from '@/store/native-notifications'
import { isDiskFullErrorMessage, notifyError } from '@/store/notifications'
import { broadcastSessionsChanged } from '@/store/session-sync'
+import { registerStreamDeltaFlush } from '@/store/stream-delta-flush'
import { upsertSubagent } from '@/store/subagents'
import { $todosBySession, setSessionTodos } from '@/store/todos'
import { broadcastTranscriptChanged } from '@/store/transcript-sync'
@@ -482,6 +483,9 @@ export function useMessageStream({
[flushQueuedDeltas]
)
+ // A steer seals the live bubble from outside this hook; it flushes our buffer first.
+ useEffect(() => registerStreamDeltaFlush(sessionId => flushQueuedDeltas(sessionId)), [flushQueuedDeltas])
+
// Page Visibility does not report every Windows/Linux focus transition.
// Flush queued deltas on both signals so returning to a chat cannot leave a
// completed chunk waiting for the next throttled timer.
@@ -1046,6 +1050,11 @@ export function useMessageStream({
// degraded websocket leaves its tool row spinning forever. The turn is
// provably done here — nothing can still be running — so seal any
// tool-call parts that never saw their completion event.
+ // A bubble a steer sealed while its tool ran stays pending for that tool's
+ // result; the turn is over now, so a lost tool.complete must not keep it spinning.
+ nextMessages = nextMessages.map(message =>
+ message.pending && message.interim ? { ...message, pending: false } : message
+ )
nextMessages = bindReceiptUserRows(sealOpenToolParts(nextMessages), persistedTurn)
const hasInlineError = nextMessages.some(
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/steer-arrival-order.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/steer-arrival-order.test.tsx
index 8cd15efd204..15454be5de0 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/steer-arrival-order.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/steer-arrival-order.test.tsx
@@ -311,6 +311,31 @@ describe('steer mid-turn keeps arrival order (user bubble never above prior outp
])
})
+ it.each([false, true])('an accepted steer paints text still buffered above it, and a lost tool.complete cannot outlive the turn (tile=%s)', async tile => {
+ await mountHarness(tile)
+
+ emit({ payload: {}, session_id: SID, type: 'message.start' })
+ emit({ payload: { text: 'Hello' }, session_id: SID, type: 'message.delta' })
+ await flushDeltas()
+ emit({ payload: { args: { command: 'sleep 5' }, name: 'terminal', tool_id: 't1' }, session_id: SID, type: 'tool.start' })
+ // Buffered, not yet painted: the delta timer has not fired.
+ emit({ payload: { text: ' world' }, session_id: SID, type: 'message.delta' })
+
+ requestGatewayMock.mockImplementationOnce(async () => ({ status: 'queued' }))
+ await act(async () => {
+ await expect(redirect!('change course', 'steer')).resolves.toBe(true)
+ })
+
+ // tool.complete for t1 is lost; the answer to the steer completes the turn.
+ emit({ payload: { text: 'new direction' }, session_id: SID, type: 'message.delta' })
+ await flushDeltas()
+ emit({ payload: { text: 'new direction' }, session_id: SID, type: 'message.complete' })
+
+ expect(transcript()).toEqual(['assistant:Hello world', 'user:change course', 'assistant:new direction'])
+ expect(states.get(SID)!.messages.every(message => !message.pending)).toBe(true)
+ expect(states.get(SID)!.messages[0].parts.find(part => part.type === 'tool-call')).toHaveProperty('completedAt')
+ })
+
it.each([false, true])('a refused redirect preserves the continuing stream (tile=%s)', async tile => {
await mountHarness(tile)
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
index fc3d62e3dba..85775aef257 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
@@ -41,6 +41,7 @@ import {
setTurnStartedAt
} from '@/store/session'
import { $sessionStates, isLiveTurnAwaitingEvents, isSessionRemote } from '@/store/session-states'
+import { flushStreamDeltas } from '@/store/stream-delta-flush'
import { clearSessionSubagents } from '@/store/subagents'
import { runGatewayRestart } from '@/store/system-actions'
import { clearSessionTodos } from '@/store/todos'
@@ -891,6 +892,7 @@ export function usePromptActions({
if (result?.status === 'redirected') {
if (mode === 'interrupt') {
+ flushStreamDeltas(id)
updateSessionState(id, state => sealAcceptedCorrection(state, messageId))
}
@@ -903,6 +905,7 @@ export function usePromptActions({
// A redirect queued in the build window is the next turn; an
// accepted steer joins this one after its running tool.
if (mode === 'steer') {
+ flushStreamDeltas(id)
updateSessionState(id, state => sealAcceptedCorrection(state, messageId, { keepRunningTools: true }))
} else {
moveOptimisticMessageToEnd()
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.ts
index 7fb48ce3dee..dc8a3851353 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.ts
@@ -501,15 +501,13 @@ export function sealLiveStream<State extends LiveStreamState>(state: State, { ke
/** `finalizeInterruptedMessages` minus the seal on tool calls still waiting for a result:
* their bubble stays pending (a tool row only renders running inside a running message)
- * until the result lands by call id. */
+ * until the result lands by call id, or the turn's completion settles it. */
function sealKeepingRunningTools(messages: ChatMessage[], streamId: null | string): ChatMessage[] {
- const before = new Map(messages.map(message => [message.id, message]))
-
- return finalizeInterruptedMessages(messages, streamId).map(message => {
- const original = before.get(message.id)
-
- return original && original !== message && hasUnresolvedToolCall(original) ? { ...original, interim: true } : message
- })
+ return messages.flatMap(message =>
+ (message.pending || message.id === streamId) && hasUnresolvedToolCall(message)
+ ? [{ ...message, interim: true }]
+ : finalizeInterruptedMessages([message], streamId)
+ )
}
/** An accepted correction's reserved bubble becomes the arrival boundary: the
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-session-commands.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-session-commands.ts
index d54d4ac6363..df121e6b73f 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-session-commands.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-session-commands.ts
@@ -7,6 +7,7 @@ import { setComposerDraft } from '@/store/composer'
import { enqueueQueuedPrompt, getQueuedPrompts, serverOwnsComposerQueue } from '@/store/composer-queue'
import { $sessions, resolveComposerSessionKey } from '@/store/session'
import { $sessionStates } from '@/store/session-states'
+import { flushStreamDeltas } from '@/store/stream-delta-flush'
import { sealLiveStream } from './rewind'
import type { SubmissionDestination } from './submission-destination'
@@ -309,6 +310,7 @@ export function sessionCommandHandlers<C extends { arg: string }>(env: SessionCo
if (accepted) {
// The notice marks where the steer arrived: seal the live reply above it so the
// output the model writes after reading the steer streams below, not above it.
+ flushStreamDeltas(out.sessionId)
updateSessionState(out.sessionId, state => sealLiveStream(state, { keepRunningTools: true }))
return out.render(copy().steerQueued(previewOf(text)))
diff --git a/apps/desktop/src/store/stream-delta-flush.ts b/apps/desktop/src/store/stream-delta-flush.ts
new file mode 100644
index 00000000000..393138222cb
--- /dev/null
+++ b/apps/desktop/src/store/stream-delta-flush.ts
@@ -0,0 +1,20 @@
+/** Lets a mid-turn boundary (an accepted steer) paint the session's buffered stream
+ * deltas before it seals the live bubble, so text the user had already been sent
+ * never lands on the far side of the boundary. The stream hook owns the buffer. */
+type DeltaFlush = (sessionId: string) => void
+
+let activeFlush: DeltaFlush | null = null
+
+export function registerStreamDeltaFlush(flush: DeltaFlush): () => void {
+ activeFlush = flush
+
+ return () => {
+ if (activeFlush === flush) {
+ activeFlush = null
+ }
+ }
+}
+
+export function flushStreamDeltas(sessionId: string) {
+ activeFlush?.(sessionId)
+}