The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(desktop): steer suite drives the real redirectPrompt path; hydration fixture carries durable row shape
Brooklyn Nicholsond8f40d417646
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.tsxindex 3b7c3dd8901..ab7acae65a2 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@@ -1,8 +1,9 @@// Repro for "when I steer it often sends out of order — a user bubble way// above" (#73793 / #83151 class). Drives the REAL stream reducer-// (useMessageStream.handleGatewayEvent) and the REAL mid-turn insert-// (appendMidTurnUserMessage — what redirectPrompt's optimistic append uses)-// through a full steered turn, and asserts transcript ORDER:+// (useMessageStream.handleGatewayEvent) and the REAL steer entry point+// (usePromptActions.redirectPrompt — appendAfterActiveReply guard, optimistic+// insert, streamId seal) through a full steered turn, and asserts transcript+// ORDER://// pre-steer output → steer bubble → post-steer output → settled reply//@@ -10,12 +11,15 @@// streamed when it was typed, and every later delta / tool event / completion// must land BELOW it — never spliced above, never merged into the sealed// pre-steer bubble.+//+// Both hooks share one state map, exactly as the desktop wires them: steering+// mutates the same ClientSessionState the gateway events reduce into.import { QueryClient } from '@tanstack/react-query'import { act, cleanup, render } from '@testing-library/react'import { useEffect, useRef } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { appendMidTurnUserMessage } from '@/app/session/hooks/use-prompt-actions/rewind'+import { usePromptActions } from '@/app/session/hooks/use-prompt-actions'import type { ClientSessionState } from '@/app/types'import { chatMessageText } from '@/lib/chat-messages'import { createClientSessionState } from '@/lib/chat-runtime'@@ -28,12 +32,35 @@ import { useMessageStream } from './index'const SID = 'steer-order-session'let handleEvent: ((event: RpcEvent) => void) | null = null+let redirect: ((text: string) => Promise<boolean>) | null = nulllet states: Map<string, ClientSessionState>+/** The gateway accepts every redirect — these suites pin CLIENT ordering. */+const requestGatewayMock = vi.fn(async (method: string): Promise<unknown> =>+ method === 'session.redirect' ? { status: 'redirected' } : {}+)++const requestGateway = requestGatewayMock as unknown as <T>(+ method: string,+ params?: Record<string, unknown>,+ timeoutMs?: number+) => Promise<T>+function Harness() {const activeSessionIdRef = useRef<null | string>(SID)const sessionStateByRuntimeIdRef = useRef(new Map<string, ClientSessionState>())const queryClientRef = useRef(new QueryClient())+ const busyRef = useRef(false)+ const runtimeIdByStoredSessionIdRef = useRef(new Map<string, string>())+ const selectedStoredSessionIdRef = useRef<null | string>(SID)++ const updateSessionState = (sessionId: string, updater: (state: ClientSessionState) => ClientSessionState) => {+ const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? createClientSessionState()+ const next = updater(current)+ sessionStateByRuntimeIdRef.current.set(sessionId, next)++ return next+ }const stream = useMessageStream({activeSessionIdRef,@@ -42,19 +69,35 @@ function Harness() {refreshHermesConfig: vi.fn(async () => undefined),refreshSessions: vi.fn(async () => undefined),sessionStateByRuntimeIdRef,- updateSessionState: (sessionId, updater) => {- const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? createClientSessionState()- const next = updater(current)- sessionStateByRuntimeIdRef.current.set(sessionId, next)+ updateSessionState+ })- return next- }+ const actions = usePromptActions({+ activeSessionId: SID,+ activeSessionIdRef,+ branchCurrentSession: async () => true,+ busyRef,+ createBackendSessionForSend: async () => SID,+ getRoutedStoredSessionId: () => null,+ getRuntimeIdForStoredSession: () => null,+ getRouteToken: () => 'token',+ handleSkinCommand: () => '',+ openMemoryGraph: () => undefined,+ refreshSessions: async () => undefined,+ requestGateway,+ resumeStoredSession: () => undefined,+ runtimeIdByStoredSessionIdRef,+ selectedStoredSessionIdRef,+ startFreshSessionDraft: () => undefined,+ sttEnabled: false,+ updateSessionState})useEffect(() => {handleEvent = stream.handleGatewayEvent+ redirect = actions.redirectPromptstates = sessionStateByRuntimeIdRef.current- }, [stream.handleGatewayEvent])+ }, [stream.handleGatewayEvent, actions.redirectPrompt])return null}@@ -75,24 +118,12 @@ const flushDeltas = async () => {const emit = (event: RpcEvent) => act(() => handleEvent?.(event))-/** Monotonic id source — Date.now() is frozen under fake timers, so two steers- * without a clock advance between them would collide on a wall-clock id. */-let steerSeq = 0--/** The optimistic steer insert redirectPrompt performs (appendAfterActiveReply). */-const steer = (text: string) =>- act(() => {- const current = states.get(SID) ?? createClientSessionState()-- states.set(- SID,- appendMidTurnUserMessage(current, {- id: `user-${(steerSeq += 1)}-steer`,- role: 'user',- parts: [{ type: 'text', text }]- })- )+/** A real steer: redirectPrompt's optimistic insert + the gateway round-trip. */+const steer = async (text: string) => {+ await act(async () => {+ await expect(redirect!(text)).resolves.toBe(true)})+}const transcript = () =>(states.get(SID)?.messages ?? []).map(message => `${message.role}:${chatMessageText(message).slice(0, 30)}`)@@ -100,7 +131,9 @@ const transcript = () =>describe('steer mid-turn keeps arrival order (user bubble never above prior output)', () => {beforeEach(() => {handleEvent = null+ redirect = nullstates = new Map()+ requestGatewayMock.mockClear()})afterEach(() => {@@ -124,7 +157,7 @@ describe('steer mid-turn keeps arrival order (user bubble never above prior outp})emit({ payload: { name: 'terminal', result: 'ok', tool_id: 't1' }, session_id: SID, type: 'tool.complete' })- steer('actually do it differently')+ await steer('actually do it differently')// Post-steer deltas must seed a FRESH bubble below the correction.emit({ payload: { text: 'rebuilt answer after the steer' }, session_id: SID, type: 'message.delta' })@@ -173,7 +206,7 @@ describe('steer mid-turn keeps arrival order (user bubble never above prior outp// Steer accepted during the final API call — the reply was already// complete, so the correction becomes the NEXT turn's prompt.- steer('one more thing')+ await steer('one more thing')emit({ payload: { text: 'the whole reply already streamed' }, session_id: SID, type: 'message.complete' })@@ -198,12 +231,12 @@ describe('steer mid-turn keeps arrival order (user bubble never above prior outpemit({ payload: { text: 'output before any steer' }, session_id: SID, type: 'message.delta' })await flushDeltas()- steer('first correction')+ await steer('first correction')emit({ payload: { text: 'output after first steer' }, session_id: SID, type: 'message.delta' })await flushDeltas()- steer('second correction')+ await steer('second correction')emit({ payload: { text: 'final output' }, session_id: SID, type: 'message.delta' })await flushDeltas()@@ -219,4 +252,25 @@ describe('steer mid-turn keeps arrival order (user bubble never above prior outp'assistant:final output'])})++ it('a redirect the gateway rejects discards the optimistic bubble instead of stranding it', async () => {+ await mountHarness()++ emit({ payload: {}, session_id: SID, type: 'message.start' })+ emit({ payload: { text: 'streaming along' }, session_id: SID, type: 'message.delta' })+ await flushDeltas()++ requestGatewayMock.mockImplementationOnce(async () => ({ status: 'not_running' }))++ await act(async () => {+ await expect(redirect!('too late')).resolves.toBe(false)+ })++ // The rejected correction never reached the model — a bubble for it would+ // lie about the transcript. No user row, stream still live below.+ expect(states.get(SID)!.messages.some(message => message.role === 'user')).toBe(false)++ emit({ payload: { text: 'streaming along — done' }, session_id: SID, type: 'message.complete' })+ expect(chatMessageText(states.get(SID)!.messages.at(-1)!)).toContain('done')+ })})diff --git a/apps/desktop/src/lib/steered-turn-hydration-order.test.ts b/apps/desktop/src/lib/steered-turn-hydration-order.test.tsindex e579544bd78..ef75386c067 100644--- a/apps/desktop/src/lib/steered-turn-hydration-order.test.ts+++ b/apps/desktop/src/lib/steered-turn-hydration-order.test.ts@@ -3,7 +3,13 @@// the user's correction → post-steer continuation with its own tools) must// hydrate in that same order. A regression here re-creates "my steer shows// way above the output" on every reload, even when the live path is correct.-// Row shape mirrors real state.db sequences (e.g. ids 731378-731389).+//+// Row shape mirrors what the client actually receives for a real steered turn+// (state.db ids 731378-731389): row_id, reasoning, and+// tool_calls entries carrying the provider's call_id/response_item_id+// alongside id. The interrupt scaffolding lives in a server-only api_content+// sidecar the client never sees, so the checkpoint row's content is already+// clean here — that projection is pinned in chat-messages.test.ts.import { describe, expect, it } from 'vitest'import type { SessionMessage } from '@/types/hermes'@@ -11,31 +17,60 @@ import type { SessionMessage } from '@/types/hermes'import { chatMessageText, toChatMessages } from './chat-messages'const steeredTurnRows: SessionMessage[] = [- { content: 'run the build', role: 'user', timestamp: 100 },+ { content: 'run the build', role: 'user', row_id: 731378, timestamp: 100 },{content: 'Kicking off the build:',+ reasoning: 'The build has to pass before docs are worth writing.',role: 'assistant',+ row_id: 731379,timestamp: 101,tool_calls: [- { function: { arguments: '{"command":"make"}', name: 'terminal' }, id: 'call-1', type: 'function' }+ {+ call_id: 'call-1',+ function: { arguments: '{"command":"make"}', name: 'terminal' },+ id: 'call-1',+ response_item_id: 'fc_call-1',+ type: 'function'+ }]},- { content: '{"output":"done","exit_code":0}', role: 'tool', timestamp: 102, tool_call_id: 'call-1', tool_name: 'terminal' },- { content: 'Build is green. Now writing the docs section', role: 'assistant', timestamp: 103 },+ {+ content: '{"output":"done","exit_code":0}',+ role: 'tool',+ row_id: 731380,+ timestamp: 102,+ tool_call_id: 'call-1',+ tool_name: 'terminal'+ },+ { content: 'Build is green. Now writing the docs section', role: 'assistant', row_id: 731381, timestamp: 103 },// Redirect checkpoint: content keeps the visible words; the provider// scaffolding rides api_content (never shipped to the client).- { content: 'Now the ladder in the resolver:', role: 'assistant', timestamp: 104 },- { content: 'actually skip docs, fix the tests instead', role: 'user', timestamp: 104.1 },+ { content: 'Now the ladder in the resolver:', role: 'assistant', row_id: 731382, timestamp: 104 },+ { content: 'actually skip docs, fix the tests instead', role: 'user', row_id: 731383, timestamp: 104.1 },{content: 'Got it — tests first.',role: 'assistant',+ row_id: 731384,timestamp: 105,tool_calls: [- { function: { arguments: '{"command":"pytest"}', name: 'terminal' }, id: 'call-2', type: 'function' }+ {+ call_id: 'call-2',+ function: { arguments: '{"command":"pytest"}', name: 'terminal' },+ id: 'call-2',+ response_item_id: 'fc_call-2',+ type: 'function'+ }]},- { content: '{"output":"3 passed","exit_code":0}', role: 'tool', timestamp: 106, tool_call_id: 'call-2', tool_name: 'terminal' },- { content: 'Tests pass.', role: 'assistant', timestamp: 107 }+ {+ content: '{"output":"3 passed","exit_code":0}',+ role: 'tool',+ row_id: 731385,+ timestamp: 106,+ tool_call_id: 'call-2',+ tool_name: 'terminal'+ },+ { content: 'Tests pass.', role: 'assistant', row_id: 731386, timestamp: 107 }]describe('toChatMessages on a persisted steered turn', () => {