Skip to content

The agent that grows with you

fix(desktop): a steer stays where it was sent, above the answer it causes

Tekniumeae7106348f7
diff --git a/apps/desktop/src/app/chat/session-tile-actions.ts b/apps/desktop/src/app/chat/session-tile-actions.ts
index 1cdbd3fa531..960212037a8 100644
--- a/apps/desktop/src/app/chat/session-tile-actions.ts
+++ b/apps/desktop/src/app/chat/session-tile-actions.ts
@@ -48,7 +48,6 @@ import type { GatewayRequester } from '../contrib/types'
import { uploadComposerAttachment } from '../session/hooks/use-prompt-actions'
import { isStaleTargetError } from '../session/hooks/use-prompt-actions'
import {
- appendMidTurnUserMessage,
applyBranchVisibility,
applyReloadOptimistic,
applyRewindOptimistic,
@@ -61,6 +60,7 @@ import {
rebindSurvivorRowIds,
revalidateEditPlan,
runRewindSubmit,
+ sealAcceptedCorrection,
type SurvivorUserRowIds
} from '../session/hooks/use-prompt-actions/rewind'
import { useSubmitPrompt } from '../session/hooks/use-prompt-actions/submit'
@@ -477,20 +477,7 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored
if (result?.status === 'redirected') {
if (mode === 'interrupt') {
- mutate(state => {
- const message = state.messages.find(candidate => candidate.id === messageId)
-
- // A newer reply may precede this ACK; it already owns its boundary.
- const hasNewReply = state.messages.slice(state.messages.findIndex(candidate => candidate.id === messageId) + 1)
- .some(candidate => candidate.role === 'assistant')
-
- return message && state.streamId && !hasNewReply
- ? appendMidTurnUserMessage(
- { ...state, messages: state.messages.filter(candidate => candidate.id !== messageId) },
- message
- )
- : state
- })
+ mutate(state => sealAcceptedCorrection(state, messageId))
}
triggerHaptic('submit')
@@ -499,7 +486,11 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored
}
if (result?.status === 'queued') {
- if (mode === 'interrupt') {
+ // A redirect queued in the build window is the next turn; an
+ // accepted steer joins this one after its running tool.
+ if (mode === 'steer') {
+ 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 5730ee918df..539c287f6d2 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
@@ -12,6 +12,7 @@ import {
chatMessageText,
completeOpenTimelineParts,
type GatewayEventPayload,
+ hasUnresolvedToolCall,
mergeFinalAssistantText,
normalizeWs,
partsText,
@@ -205,15 +206,23 @@ export function useMessageStream({
}
]
} else {
- nextMessages = prev.map(m =>
- m.id === streamId
- ? {
- ...m,
- parts: transform(m.parts, m),
- pending: patchesSealedBubble ? (m.pending ?? false) : opts.pending ? opts.pending(m) : true
- }
- : m
- )
+ nextMessages = prev.map(m => {
+ if (m.id !== streamId) {
+ return m
+ }
+
+ const patched = { ...m, parts: transform(m.parts, m) }
+
+ // A bubble a steer sealed stays pending only while its own tools run.
+ return {
+ ...patched,
+ pending: patchesSealedBubble
+ ? Boolean(m.pending) && hasUnresolvedToolCall(patched)
+ : opts.pending
+ ? opts.pending(m)
+ : true
+ }
+ })
}
if (patchesSealedBubble) {
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 cbb46e25841..8cd15efd204 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
@@ -37,7 +37,7 @@ import { useMessageStream } from './index'
const SID = 'steer-order-session'
let handleEvent: ((event: GatewayEvent) => void) | null = null
-let redirect: ((text: string) => Promise<boolean>) | null = null
+let redirect: ((text: string, mode?: 'interrupt' | 'steer') => Promise<boolean>) | null = null
let states: Map<string, ClientSessionState>
/** Stub only the RPC boundary; both action handlers and streaming reducers are real. */
@@ -278,6 +278,39 @@ describe('steer mid-turn keeps arrival order (user bubble never above prior outp
])
})
+ it.each([false, true])('an accepted steer marks its arrival: the tool keeps running above, the answer streams below (tile=%s)', async tile => {
+ await mountHarness(tile)
+
+ emit({ payload: {}, session_id: SID, type: 'message.start' })
+ emit({ payload: { text: 'checking first' }, 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' })
+
+ requestGatewayMock.mockImplementationOnce(async () => ({ status: 'queued' }))
+ await act(async () => {
+ await expect(redirect!('use the other file', 'steer')).resolves.toBe(true)
+ })
+ expect(requestGatewayMock).toHaveBeenLastCalledWith('session.steer', { session_id: SID, text: 'use the other file' })
+
+ // The steer interrupts nothing: the tool it waits on still reads as running.
+ const sealed = states.get(SID)!.messages[0]
+ expect(sealed.parts.find(part => part.type === 'tool-call')).not.toHaveProperty('completedAt')
+ expect(sealed.pending).toBe(true)
+
+ emit({ payload: { name: 'terminal', result: 'ok', tool_id: 't1' }, session_id: SID, type: 'tool.complete' })
+ expect(states.get(SID)!.messages[0].pending).toBe(false)
+
+ emit({ payload: { text: 'switched to the other file' }, session_id: SID, type: 'message.delta' })
+ await flushDeltas()
+ emit({ payload: { text: 'switched to the other file' }, session_id: SID, type: 'message.complete' })
+
+ expect(transcript()).toEqual([
+ 'assistant:checking first',
+ 'user:use the other file',
+ 'assistant:switched to the other file'
+ ])
+ })
+
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 a1a37a3efe5..fc3d62e3dba 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
@@ -73,6 +73,7 @@ import {
rebindSurvivorRowIds,
retryKeepsDeepConfirm,
runRewindSubmit,
+ sealAcceptedCorrection,
type SurvivorUserRowIds
} from './rewind'
import { useSlashCommand } from './slash'
@@ -890,21 +891,7 @@ export function usePromptActions({
if (result?.status === 'redirected') {
if (mode === 'interrupt') {
- updateSessionState(id, state => {
- const message = state.messages.find(candidate => candidate.id === messageId)
-
- // A newer reply may precede this ACK; it already owns its boundary.
- const hasNewReply = state.messages
- .slice(state.messages.findIndex(candidate => candidate.id === messageId) + 1)
- .some(candidate => candidate.role === 'assistant')
-
- return message && state.streamId && !hasNewReply
- ? appendMidTurnUserMessage(
- { ...state, messages: state.messages.filter(candidate => candidate.id !== messageId) },
- message
- )
- : state
- })
+ updateSessionState(id, state => sealAcceptedCorrection(state, messageId))
}
triggerHaptic('submit')
@@ -913,9 +900,11 @@ export function usePromptActions({
}
if (result?.status === 'queued') {
- // Build-window redirects become the next turn, not part of the
- // active reply, so retain the optimistic row at the tail.
- if (mode === 'interrupt') {
+ // A redirect queued in the build window is the next turn; an
+ // accepted steer joins this one after its running tool.
+ if (mode === 'steer') {
+ 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 ecf390dc9e5..7fb48ce3dee 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
@@ -19,6 +19,7 @@ import {
type ChatMessagePart,
chatMessageText,
finalizeInterruptedMessages,
+ hasUnresolvedToolCall,
textPart
} from '@/lib/chat-messages'
import type { ConfirmRequest } from '@/store/confirm'
@@ -460,32 +461,79 @@ export function finalizeStoppedMessages(
* user row, which made the post-correction reply a sibling of the sealed
* partial and dropped the partial and the correction from view (#119015).
*/
-export function appendMidTurnUserMessage<
- State extends {
- interimBoundaryPending: boolean
- messages: ChatMessage[]
- pendingBranchGroup?: null | string
- streamId: null | string
- }
->(state: State, message: ChatMessage): State {
+export function appendMidTurnUserMessage<State extends LiveStreamState>(state: State, message: ChatMessage): State {
+ const sealed = sealLiveStream(state)
+
+ return { ...sealed, messages: [...sealed.messages, message] }
+}
+
+interface LiveStreamState {
+ interimBoundaryPending: boolean
+ messages: ChatMessage[]
+ pendingBranchGroup?: null | string
+ streamId: null | string
+}
+
+/**
+ * The seal half of `appendMidTurnUserMessage`, for a mid-turn arrival that is
+ * rendered separately (a typed /steer's notice row).
+ *
+ * A steer interrupts nothing (`keepRunningTools`): the tool it waits on keeps
+ * its live row in the sealed bubble, where its result still lands by call id.
+ */
+export function sealLiveStream<State extends LiveStreamState>(state: State, { keepRunningTools = false } = {}): State {
const liveId = state.streamId
- const sealed = finalizeUserInterruptedMessages(state.messages, liveId)
- const sealedLiveKept = liveId !== null && sealed.some(row => row.id === liveId)
- const messages = [
- ...(sealedLiveKept ? sealed.map(row => (row.id === liveId ? { ...row, interim: true } : row)) : sealed),
- message
- ]
+ const sealed = keepRunningTools
+ ? sealKeepingRunningTools(state.messages, liveId)
+ : finalizeUserInterruptedMessages(state.messages, liveId)
+
+ const sealedLiveKept = liveId !== null && sealed.some(row => row.id === liveId)
return {
...state,
- messages,
+ messages: sealedLiveKept ? sealed.map(row => (row.id === liveId ? { ...row, interim: true } : row)) : sealed,
...(state.pendingBranchGroup ? { pendingBranchGroup: null } : {}),
streamId: null,
interimBoundaryPending: state.interimBoundaryPending || sealedLiveKept
}
}
+/** `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. */
+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
+ })
+}
+
+/** An accepted correction's reserved bubble becomes the arrival boundary: the
+ * output already on screen stays above it, everything after streams below. */
+export function sealAcceptedCorrection<State extends LiveStreamState>(
+ state: State,
+ messageId: string | undefined,
+ { keepRunningTools = false } = {}
+): State {
+ const index = state.messages.findIndex(candidate => candidate.id === messageId)
+
+ // A newer reply may precede this ACK; it already owns its boundary.
+ if (index < 0 || !state.streamId || state.messages.slice(index + 1).some(row => row.role === 'assistant')) {
+ return state
+ }
+
+ const sealed = sealLiveStream(
+ { ...state, messages: state.messages.filter(candidate => candidate.id !== messageId) },
+ { keepRunningTools }
+ )
+
+ return { ...sealed, messages: [...sealed.messages, state.messages[index]] }
+}
+
// ---------------------------------------------------------------------------
// Reload (regenerate)
// ---------------------------------------------------------------------------
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-session-commands.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-session-commands.test.tsx
index ecf2e674d0a..98878fbd5ed 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-session-commands.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-session-commands.test.tsx
@@ -324,6 +324,32 @@ describe('/steer', () => {
expect(renderedText(handle)).toContain(copy.steerQueued('check the tests too'))
})
+ it('seals the live reply at the steer notice, keeping its running tool live', async () => {
+ const requestGateway = gateway(method => (method === 'session.steer' ? { status: 'queued' } : undefined))
+ const tool = { type: 'tool-call', toolCallId: 't1', toolName: 'terminal', args: {}, argsText: '{}', timestamp: 2 }
+ const live = { id: 'stream-1', role: 'assistant', pending: true, parts: [{ type: 'text', text: 'before', timestamp: 1 }, tool] }
+ let handle: HarnessHandle | null = null
+ await actRender(
+ <Harness
+ onReady={h => (handle = h)}
+ refreshSessions={async () => undefined}
+ requestGateway={requestGateway}
+ seedMessages={[live]}
+ seedStreamId="stream-1"
+ />
+ )
+ publishSessionState(RUNTIME_SESSION_ID, { ...handle!.state(), busy: true })
+
+ await handle!.submitText('/steer use the other file')
+
+ // The next delta (the model's answer to the steer) seeds a bubble BELOW the notice.
+ const { messages, streamId } = handle!.state()
+ expect(streamId).toBeNull()
+ expect(messages.map(message => message.id).indexOf('stream-1')).toBe(0)
+ expect(renderedText(handle!)).toContain(copy.steerQueued('use the other file'))
+ expect(messages[0]).toMatchObject({ pending: true, parts: [expect.anything(), tool] })
+ })
+
it('queues the text as the next turn when the steer is not accepted', async () => {
publishSessionState(RUNTIME_SESSION_ID, { ...createClientSessionState(RUNTIME_SESSION_ID), busy: true })
const requestGateway = gateway(method => (method === 'session.steer' ? { status: 'rejected' } : undefined))
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 05e238a4d3a..d54d4ac6363 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
@@ -8,6 +8,7 @@ import { enqueueQueuedPrompt, getQueuedPrompts, serverOwnsComposerQueue } from '
import { $sessions, resolveComposerSessionKey } from '@/store/session'
import { $sessionStates } from '@/store/session-states'
+import { sealLiveStream } from './rewind'
import type { SubmissionDestination } from './submission-destination'
import {
type GatewayRequest,
@@ -306,6 +307,10 @@ 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.
+ updateSessionState(out.sessionId, state => sealLiveStream(state, { keepRunningTools: true }))
+
return out.render(copy().steerQueued(previewOf(text)))
}
diff --git a/apps/desktop/src/lib/chat-messages/index.ts b/apps/desktop/src/lib/chat-messages/index.ts
index 1837f9e8366..ab9bc3b4983 100644
--- a/apps/desktop/src/lib/chat-messages/index.ts
+++ b/apps/desktop/src/lib/chat-messages/index.ts
@@ -25,6 +25,7 @@ export {
spliceOlderPreservedRows
} from './reconciliation'
export {
+ hasUnresolvedToolCall,
QUESTION_CARD_TOOLS,
restorePendingBlockingToolCall,
restorePendingClarifyToolCall,
diff --git a/apps/desktop/src/lib/chat-messages/tool-parts.ts b/apps/desktop/src/lib/chat-messages/tool-parts.ts
index e216e07686a..ebb7651f9e4 100644
--- a/apps/desktop/src/lib/chat-messages/tool-parts.ts
+++ b/apps/desktop/src/lib/chat-messages/tool-parts.ts
@@ -412,6 +412,10 @@ export interface SettledClarifyProjection {
streamId: string | null
}
+/** A tool call that neither returned nor was sealed: it is still running. */
+export const hasUnresolvedToolCall = (message: ChatMessage) =>
+ message.parts.some(part => part.type === 'tool-call' && part.result === undefined && part.completedAt === undefined)
+
/**
* Find the message that owns a tool call, by its stable call id, anywhere in
* the transcript — not just in the currently-streaming bubble.