The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): the second deep confirm reads the session slice, and a cancel keeps the refreshed history
kshitijk4poor7d3ec73e8517
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.deep-cut.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.deep-cut.test.tsxindex 5b7462f4d84..cb84d726d3c 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.deep-cut.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.deep-cut.test.tsx@@ -319,6 +319,92 @@ describe('usePromptActions deep-edit consent scope (#133716)', () => {expect(submits[1]).toMatchObject({ confirm_deep_truncate: true, truncate_before_row_id: 21 })})+ it.each([+ ['accepting', true],+ ['declining', false]+ ])('%s the second deep confirm on a stale-target retry acts on the refreshed history', async (_label, accept) => {+ const seed = [+ { id: 'u1', parts: [textPart('first')], role: 'user' as const, rowId: 11, timestamp: 0 },+ { id: 'a1', parts: [textPart('reply')], role: 'assistant' as const, timestamp: 1 },+ { id: 'u2', parts: [textPart('second')], role: 'user' as const, rowId: 13, timestamp: 2 }+ ]++ const fresh = [+ { ...seed[0], rowId: 21 },+ seed[1],+ { ...seed[2], rowId: 23 },+ { id: 'u3', parts: [textPart('arrived after consent')], role: 'user' as const, rowId: 25, timestamp: 3 }+ ]++ publishSessionState(RUNTIME_SESSION_ID, createClientSessionState('stored', seed as never))+ setMessages(seed as never)+ const submits: Record<string, unknown>[] = []++ const requestGateway = vi.fn(async (method: string, params?: Record<string, unknown>) => {+ if (method === 'prompt.submit') {+ submits.push(params ?? {})++ if (submits.length === 1) {+ throw new JsonRpcGatewayError('target user message is no longer in session history', { code: 4018 })+ }+ }++ return {} as never+ })++ let handle: HarnessHandle | undefined+ let lastState: Record<string, unknown> | undefined++ await actRender(+ <Harness+ onReady={h => {+ handle = h+ }}+ onUpdateState={(_id, _stored, next) => {+ lastState = next+ }}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway}+ resumeStoredSession={async () => {+ // As in the real session cache, the slice and the foreground mirror are separate arrays.+ publishSessionState(RUNTIME_SESSION_ID, createClientSessionState('stored', [...fresh] as never))+ setMessages(fresh as never)+ }}+ seedMessages={seed}+ storedSessionId="stored"+ />+ )++ let confirms = 0+ const stopConfirming = $confirmRequest.listen(request => {+ if (request) {+ confirms += 1+ settleConfirm(confirms === 1 || accept)+ }+ })++ await handle!.editMessage({+ content: [{ text: 'edited first', type: 'text' }],+ parentId: null,+ role: 'user',+ sourceId: 'u1'+ } as never)+ stopConfirming()++ expect(confirms).toBe(2)++ if (accept) {+ expect(submits).toHaveLength(2)+ expect(submits[1]).toMatchObject({ confirm_deep_truncate: true, truncate_before_row_id: 21 })+ } else {+ expect(submits).toHaveLength(1)+ expect($busy.get()).toBe(false)+ // The refresh already replaced the optimistic edit; a decline must not restore the stale seed.+ expect(lastState).toMatchObject({ busy: false })+ expect(lastState?.messages).not.toBe(seed)+ }+ })+it('a deep-edit confirm answered after a session switch sends nothing and leaves the new session idle', async () => {const seed = [{ id: 'u1', parts: [textPart('first')], role: 'user', rowId: 11, timestamp: 0 },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.tsindex a33ab9d23c4..83d3421be72 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@@ -1298,18 +1298,43 @@ export function usePromptActions({])+ // Roll an optimistic edit/truncation back to *messages* (the original history) so the UI stays in+ // sync with what's persisted instead of stranding a partial timeline; without *messages* only the+ // busy state is cleared.+ const rollBackEdit = useCallback(+ (sessionId: string, messages?: ChatMessage[]) => {+ // The foreground flags belong to whichever session is on screen now.+ if (activeSessionIdRef.current === sessionId) {+ setMutableRef(busyRef, false)+ setBusy(false)+ setAwaitingResponse(false)+ }++ updateSessionState(sessionId, state => ({+ ...state,+ busy: false,+ awaitingResponse: false,+ turnLive: false,+ turnStartedAt: null,+ ...(messages ? { messages } : {})+ }))+ },+ [activeSessionIdRef, busyRef, updateSessionState]+ )+// Stale target after compression/resume drift (the cached rowId and ordinal address the// pre-compression segment): reload server history, recompute the full edit plan against the// refreshed transcript, and retry the real edit once. Do NOT plain-resubmit without a truncation// address — that drops rewind semantics and silently appends the edit as a new turn (#82462).- // Returns 'sent', or the error to surface and whether that submit carried the deep confirm.+ // Returns 'done' once the retry was sent, or declined and rolled back; otherwise the error to+ // surface and whether that submit carried the deep confirm.const retryStaleEdit = useCallback(async (sessionId: string,edited: AppendMessage,plan: EditPlan & { confirmDeepTruncate: boolean },messages: ChatMessage[]- ): Promise<'cancelled' | 'sent' | { surfaced?: unknown; surfacedConfirmed?: boolean; unavailable: boolean }> => {+ ): Promise<'done' | { surfaced?: unknown; surfacedConfirmed?: boolean; unavailable: boolean }> => {let surfacedConfirmed: boolean | undefinedtry {@@ -1332,14 +1357,17 @@ export function usePromptActions({// not cover. During the warn-only rollout the backend still allows an// unconfirmed deep cut, so the client must ask again before sending it.if (laterVisibleUserTurns(refreshed, retryPlan.sourceIndex) > 0 && !surfacedConfirmed) {+ // Compare like with like: the session slice before and after the dialog ($messages is a+ // separate mirror array, so comparing it with the slice is never equal).+ const shown = currentMessages(sessionId)const accepted = await confirm(deepCutConfirmRequest(t.assistant.thread))- if (- !accepted ||- activeSessionIdRef.current !== sessionId ||- currentMessages(sessionId) !== refreshed- ) {- return 'cancelled'+ if (!accepted || activeSessionIdRef.current !== sessionId || currentMessages(sessionId) !== shown) {+ // Nothing was cut and the refresh already replaced the optimistic edit: keep whatever+ // history the session holds now and only drop the busy arm.+ rollBackEdit(sessionId)++ return 'done'}surfacedConfirmed = true@@ -1359,7 +1387,7 @@ export function usePromptActions({applySurvivorRowIds(sessionId, survivorRowIds)- return 'sent'+ return 'done'} catch (retryErr) {return {surfaced: retryErr,@@ -1368,26 +1396,15 @@ export function usePromptActions({}}},- [activeSessionIdRef, applySurvivorRowIds, resumeStoredSession, selectedStoredSessionIdRef, submitRewindPrompt, t]- )-- // Roll an optimistic edit/truncation back to the original history so the UI stays in sync with- // what's persisted instead of stranding a partial timeline.- const rollBackEdit = useCallback(- (sessionId: string, messages: ChatMessage[]) => {- setMutableRef(busyRef, false)- setBusy(false)- setAwaitingResponse(false)- updateSessionState(sessionId, state => ({- ...state,- busy: false,- awaitingResponse: false,- turnLive: false,- turnStartedAt: null,- messages- }))- },- [busyRef, updateSessionState]+ [+ activeSessionIdRef,+ applySurvivorRowIds,+ resumeStoredSession,+ rollBackEdit,+ selectedStoredSessionIdRef,+ submitRewindPrompt,+ t+ ])const runEdit = useCallback(@@ -1469,13 +1486,7 @@ export function usePromptActions({if (!plan.isFailedTurn && !unavailable && isStaleTargetError(err)) {const retried = await retryStaleEdit(sessionId, edited, plan, messages)- if (retried === 'sent') {- return- }-- if (retried === 'cancelled') {- rollBackEdit(sessionId, messages)-+ if (retried === 'done') {return}