The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): publish pending clarify before transcript hydration
brooklyn!f0d6d2151cac
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsxindex 8bb6d8491a7..dba07ccf47c 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx@@ -3254,6 +3254,171 @@ describe('resumeSession warm-cache mapping integrity', () => {expect($clarifyRequests.get()['rt-A']).toMatchObject({ requestId: 'req-warm' })})+ function answerableClarifyRows(messages: ClientSessionState['messages'] | undefined) {+ return (+ messages?.filter(+ message =>+ message.pending &&+ message.parts.some(+ part => part.type === 'tool-call' && part.toolName === 'clarify' && part.result === undefined+ )+ ) ?? []+ )+ }++ async function resumeClarifyBeforeHydration({+ messageCount = 1,+ messages,+ provenance+ }: {+ messageCount?: number+ messages: ClientSessionState['messages']+ provenance?: ClientSessionState['transcriptProvenance']+ }) {+ setSessions([storedSession({ id: 'stored-A', message_count: messageCount })])++ const state = clientState('stored-A')+ state.messages = messages++ if (provenance) {+ state.transcriptProvenance = provenance+ }++ const runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>> = {+ current: new Map([['stored-A', 'rt-A']])+ }++ const sessionStateByRuntimeIdRef: MutableRefObject<Map<string, ClientSessionState>> = {+ current: new Map([['rt-A', state]])+ }++ const persistedTranscript = deferred<Awaited<ReturnType<typeof getLatestSessionMessages>>>()+ vi.mocked(getLatestSessionMessages).mockReturnValue(persistedTranscript.promise)++ const requestGateway = vi.fn(async (method: string) => {+ if (method === 'session.activate') {+ setClarifyRequest({+ choices: ['safe', 'fast'],+ multiSelect: false,+ question: 'Which path?',+ receivedAt: Date.now(),+ requestId: 'req-navigation',+ sessionId: 'rt-A'+ })++ return {+ info: {},+ message_count: messageCount,+ messages: [],+ messages_omitted: true,+ open_requests: [+ { id: 'req-navigation', method: 'clarify', params: { choices: ['safe', 'fast'], question: 'Which path?' } }+ ],+ resumed: 'stored-A',+ running: true,+ session_id: 'rt-A',+ session_key: 'stored-A'+ } as never+ }++ return {} as never+ })++ const viewSyncs: ClientSessionState[] = []+ let resume: ((storedSessionId: string, replaceRoute?: boolean) => Promise<unknown>) | null = null+ render(+ <ResumeHarness+ onReady={ready => (resume = ready)}+ onViewSync={(_sessionId, syncedState) => viewSyncs.push(syncedState)}+ requestGateway={requestGateway}+ runtimeIdByStoredSessionIdRef={runtimeIdByStoredSessionIdRef}+ sessionStateByRuntimeIdRef={sessionStateByRuntimeIdRef}+ />+ )+ await waitFor(() => expect(resume).not.toBeNull())+ const resumePromise = resume!('stored-A', true)+ await waitFor(() => expect(viewSyncs.some(syncedState => syncedState.needsInput)).toBe(true))+ expect(getLatestSessionMessages).toHaveBeenCalledWith('stored-A', undefined)++ return { persistedTranscript, resumePromise, sessionStateByRuntimeIdRef, viewSyncs }+ }++ it('publishes an answerable pending clarify row in the same needsInput view update, before transcript hydration (#108718)', async () => {+ const { persistedTranscript, resumePromise, viewSyncs } = await resumeClarifyBeforeHydration({+ messages: [{ id: 'cached-user', role: 'user', parts: [{ type: 'text', text: 'help me choose' }] }],+ provenance: {+ connectionId: '',+ coverage: 'latest-page',+ lineageRootId: null,+ profile: 'default',+ source: 'persisted-display',+ storedSessionId: 'stored-A'+ }+ })++ const preHydration = viewSyncs.find(syncedState => syncedState.needsInput)+ const answerable = answerableClarifyRows(preHydration?.messages)++ expect(answerable).toHaveLength(1)+ expect(answerable[0].parts).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ args: expect.objectContaining({ choices: ['safe', 'fast'], question: 'Which path?' }),+ toolCallId: 'req-navigation',+ toolName: 'clarify',+ type: 'tool-call'+ })+ ])+ )+ expect(preHydration?.messages.some(message => message.id === 'cached-user')).toBe(true)++ persistedTranscript.resolve({+ messages: [{ content: 'help me choose', role: 'user', timestamp: 1 }],+ session_id: 'stored-A'+ } as never)+ await resumePromise++ const settled = viewSyncs.filter(syncedState => syncedState.needsInput).at(-1)+ expect(answerableClarifyRows(settled?.messages)).toHaveLength(1)+ })++ it('keeps the snapshot clarify row visible while unproven history stays suppressed (#108718)', async () => {+ const { persistedTranscript, resumePromise, viewSyncs } = await resumeClarifyBeforeHydration({+ messages: [+ { id: 'cached-user', role: 'user', parts: [{ type: 'text', text: 'help me choose' }] },+ {+ id: 'cached-assistant',+ role: 'assistant',+ parts: [{ type: 'text', text: 'I found two paths.' }]+ }+ ]+ })++ const preHydration = viewSyncs.find(syncedState => syncedState.needsInput)++ expect(answerableClarifyRows(preHydration?.messages)).toHaveLength(1)+ expect(preHydration?.messages.some(message => message.id === 'cached-user')).toBe(false)+ expect(preHydration?.messages.some(message => message.id === 'cached-assistant')).toBe(false)++ persistedTranscript.resolve({ messages: [], session_id: 'stored-A' } as never)+ await resumePromise+ expect(answerableClarifyRows(viewSyncs.at(-1)?.messages)).toHaveLength(1)+ })++ it('keeps the snapshot clarify row visible when the unproven warm cache has no prefix (#108718)', async () => {+ const { persistedTranscript, resumePromise, viewSyncs } = await resumeClarifyBeforeHydration({+ messageCount: 0,+ messages: []+ })++ const preHydration = viewSyncs.find(syncedState => syncedState.needsInput)++ expect(answerableClarifyRows(preHydration?.messages)).toHaveLength(1)++ persistedTranscript.resolve({ messages: [], session_id: 'stored-A' } as never)+ await resumePromise+ })+it.each([['with a stale request-store entry', true],['after the request store was already cleared', false]diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.tsindex f009d2b88a0..b8065cf8e8a 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts@@ -366,6 +366,39 @@ interface FreshSessionDraftOptions {workspaceTarget?: NewChatWorkspaceTarget}+/** Drop the pre-hydration request-id row without copying the other messages.+ * A copied clarify row looks like a concurrent edit and hydration keeps both. */+function withoutEarlyClarifyProjection(messages: ChatMessage[], requestId: string): ChatMessage[] {+ let changed = false+ const next: ChatMessage[] = []++ for (const message of messages) {+ const parts = message.parts.filter(+ part =>+ !(+ part.type === 'tool-call' &&+ part.toolName === 'clarify' &&+ part.result === undefined &&+ part.toolCallId === requestId+ )+ )++ if (parts.length === message.parts.length) {+ next.push(message)++ continue+ }++ changed = true++ if (parts.length > 0) {+ next.push({ ...message, parts })+ }+ }++ return changed ? next : messages+}+/** Session-state patch for a restored blocking prompt row; the first non-null projection is used. */function livePromptStreamId(...projections: ({ streamId: string } | null)[]@@ -1437,6 +1470,28 @@ export function useSessionActions({// Once the attached transport reports a later terminal event,// that live state is authoritative and must not be overwritten// by the older `running` value after the REST request resolves.+ // The activate snapshot is enough to answer a still-pending clarify.+ // Publish that row in the same view update as needsInput, before+ // transcript REST. An armed hold still hides unproven history, so+ // the question rides a new row the hold cannot swallow by grafting+ // it onto a cutoff assistant. Hydration strips that synthetic id+ // and re-derives one authoritative row.+ const clarifyPayload = pendingClarify ? pendingClarifyToolPayload(pendingClarify) : null++ const earlyClarifyProjection = clarifyPayload+ ? restorePendingClarifyToolCall(+ suppressUnprovenWarmTranscript ? [] : activatedMessages,+ clarifyPayload+ )+ : null++ const projectedTail = earlyClarifyProjection?.messages.at(-1)++ const earlyClarifyMessages =+ earlyClarifyProjection && suppressUnprovenWarmTranscript && projectedTail+ ? [...activatedMessages, projectedTail]+ : earlyClarifyProjection?.messages+const activatedLivenessState = updateSessionState(cachedRuntimeId,state => ({@@ -1456,7 +1511,13 @@ export function useSessionActions({// without ever having received its prompt, so the settle// path must not take the "I saw it all" shortcut.adoptedRunningTurn: state.adoptedRunningTurn || running,- turnStartedAt: running ? (activatedTurnStartedAt ?? state.turnStartedAt ?? Date.now()) : null+ turnStartedAt: running ? (activatedTurnStartedAt ?? state.turnStartedAt ?? Date.now()) : null,+ ...(earlyClarifyProjection+ ? {+ messages: earlyClarifyMessages ?? state.messages,+ ...livePromptStreamId(null, earlyClarifyProjection)+ }+ : {})}),storedSessionId)@@ -1549,9 +1610,16 @@ export function useSessionActions({activated)+ const latestCachedMessages = sessionStateByRuntimeIdRef.current.get(cachedRuntimeId)?.messages++ const cachedWithoutEarlyClarify =+ latestCachedMessages && pendingClarify+ ? withoutEarlyClarifyProjection(latestCachedMessages, pendingClarify.requestId)+ : latestCachedMessages+const currentLiveTurn = reconcilePersistedLiveTurn(persistedMessages,- sessionStateByRuntimeIdRef.current.get(cachedRuntimeId)?.messages ?? previousMessages,+ cachedWithoutEarlyClarify ?? previousMessages,persisted.messages,liveProjection)@@ -1567,13 +1635,21 @@ export function useSessionActions({const currentMessages = sessionStateByRuntimeIdRef.current.get(cachedRuntimeId)?.messages+ // The early publish may have appended a synthetic request-id row so+ // the hold could not hide the question. Drop it before overlaying+ // concurrent edits; the projection below re-derives one row.+ const currentForOverlay =+ currentMessages && pendingClarify+ ? withoutEarlyClarifyProjection(currentMessages, pendingClarify.requestId)+ : currentMessages+// The occurrence-aware path already read the latest cache. An// additional identity overlay would restore its consumed tools.- if (currentMessages && !reconciledCurrentLiveTurn) {+ if (currentForOverlay && !reconciledCurrentLiveTurn) {activatedMessages = overlayConcurrentMessageChanges(activatedMessages,cachedViewState.messages,- currentMessages+ currentForOverlay)}diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.test.ts b/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.test.tsindex bf5e31214be..7a10beb1ec5 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.test.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.test.ts@@ -7,6 +7,7 @@ import {hasPersistedDisplayTranscriptProvenance,invalidatePersistedDisplayTranscriptAuthority,suppressTranscriptForView,+ transcriptRowContentKey,withoutTranscriptProvenance} from './transcript-provenance'@@ -55,11 +56,55 @@ describe('transcript provenance', () => {// No gate held: the state reaches the view verbatim.expect(suppressTranscriptForView(state, null)).toBe(state)- // Gate held with no captured prefix: fail-closed, everything hides.+ // Gate held with no captured prefix: fail-closed, history hides.expect(suppressTranscriptForView(state, { cutoffIds: new Set() }).messages).toEqual([])expect(state.messages).toHaveLength(1)})+ it('fail-closed still hides history but keeps an answerable clarify row', () => {+ const state = createClientSessionState('stored-1')+ const history = { id: 'cached-1', role: 'user' as const, parts: [{ type: 'text' as const, text: 'old' }] }++ const clarify = {+ id: 'live-clarify',+ pending: true,+ role: 'assistant' as const,+ parts: [+ {+ args: { choices: ['safe', 'fast'], question: 'Which path?' },+ toolCallId: 'req-1',+ toolName: 'clarify',+ type: 'tool-call' as const+ }+ ]+ }++ state.messages = [history, clarify]++ expect(suppressTranscriptForView(state, { cutoffIds: new Set() }).messages).toEqual([clarify])+ })++ it('does not let a content fingerprint hide an answerable clarify row', () => {+ const clarifyPart = {+ args: { question: 'Which path?' },+ toolCallId: 'req-1',+ toolName: 'clarify',+ type: 'tool-call' as const+ }++ const cached = { id: 'cached-clarify', role: 'assistant' as const, parts: [clarifyPart] }+ const live = { id: 'live-clarify', pending: true, role: 'assistant' as const, parts: [clarifyPart] }+ const state = createClientSessionState('stored-1')+ state.messages = [cached, live]++ const suppressed = suppressTranscriptForView(state, {+ cutoffIds: new Set(['cached-clarify']),+ cutoffKeys: new Set([transcriptRowContentKey(cached)])+ })++ expect(suppressed.messages.map(message => message.id)).toEqual(['live-clarify'])+ })+it('drops only the cached prefix and keeps rows appended after the arm (#117867)', () => {const state = createClientSessionState('stored-1')state.messages = [diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.ts b/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.tsindex e2d81c7fec2..8cf3c898345 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.ts@@ -84,6 +84,13 @@ export function transcriptRowContentKey(message: ChatMessage): string {.join('|')}`}+function isAnswerableClarifyMessage(message: ChatMessage): boolean {+ return (+ message.pending === true &&+ message.parts.some(part => part.type === 'tool-call' && part.toolName === 'clarify' && part.result === undefined)+ )+}+export function suppressTranscriptForView(state: ClientSessionState,cutoff: TranscriptViewCutoff | null@@ -93,15 +100,28 @@ export function suppressTranscriptForView(}if (cutoff.cutoffIds.size === 0) {- // Fail-closed: the gate was armed before any cached row existed, so there- // is no unproven prefix to hide selectively — everything stays off the- // view until REST authority lands (#73646).- return { ...state, messages: [] }+ // Fail-closed for history: the gate was armed before any cached row+ // existed, so there is no unproven prefix to hide selectively (#73646).+ // A clarify row published from the activate snapshot is not that prefix.+ const messages = state.messages.filter(isAnswerableClarifyMessage)++ return messages.length === state.messages.length ? state : { ...state, messages }}- const messages = state.messages.filter(- message => !cutoff.cutoffIds.has(message.id) && !(cutoff.cutoffKeys?.has(transcriptRowContentKey(message)) ?? false)- )+ const messages = state.messages.filter(message => {+ if (cutoff.cutoffIds.has(message.id)) {+ return false+ }++ // Content fingerprints hide a re-sequenced copy of the unproven prefix.+ // They must not hide the snapshot clarify row, whose parts can match a+ // cached question that is itself still suppressed by id.+ if (isAnswerableClarifyMessage(message)) {+ return true+ }++ return !(cutoff.cutoffKeys?.has(transcriptRowContentKey(message)) ?? false)+ })if (messages.length === state.messages.length) {return state