The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): retry stale restore targets
Mahgoub Soliman7242cb7a7c58
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsxindex 532a0629e90..d7de421c38f 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx@@ -3037,6 +3037,67 @@ describe('usePromptActions restoreToMessage', () => {)expect((lastState.messages as { id: string }[]).map(m => m.id)).toEqual(['u1'])})++ it('resumes and retries once when restore hits a stale durable target', async () => {+ const initialMessages = [+ { id: 'u1', role: 'user' as const, parts: [textPart('first prompt')], rowId: 101 },+ { id: 'a1', role: 'assistant' as const, parts: [textPart('first answer')], rowId: 102 },+ { id: 'u2', role: 'user' as const, parts: [textPart('second prompt')], rowId: 103 }+ ]++ const refreshedMessages = [+ { id: 'u1-forked', role: 'user' as const, parts: [textPart('first prompt')], rowId: 501 },+ { id: 'a1-forked', role: 'assistant' as const, parts: [textPart('first answer')], rowId: 502 },+ { id: 'u2-forked', role: 'user' as const, parts: [textPart('second prompt')], rowId: 503 }+ ]++ $messages.set(initialMessages as never)++ let submitAttempts = 0+ const requestGateway = vi.fn(async (method: string) => {+ if (method === 'prompt.submit') {+ submitAttempts += 1++ if (submitAttempts === 1) {+ throw new JsonRpcGatewayError('target user message is no longer in session history', { code: 4018 })+ }+ }++ return {} as never+ })++ const resumeStoredSession = vi.fn(async () => {+ $messages.set(refreshedMessages as never)+ })++ let handle: HarnessHandle | null = null+ await actRender(+ <Harness+ onReady={h => (handle = h)}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway}+ resumeStoredSession={resumeStoredSession}+ seedMessages={initialMessages as never}+ storedSessionId="stored-restore"+ />+ )++ await handle!.restoreToMessage('u1')++ expect(resumeStoredSession).toHaveBeenCalledWith('stored-restore')+ expect(submitAttempts).toBe(2)++ const submitCalls = requestGateway.mock.calls.filter(([method]) => method === 'prompt.submit')+ expect(submitCalls).toHaveLength(2)+ expect(submitCalls[0]?.[1]).toMatchObject({+ text: 'first prompt',+ truncate_before_row_id: 101+ })+ expect(submitCalls[1]?.[1]).toMatchObject({+ text: 'first prompt',+ truncate_before_row_id: 501+ })+ })})describe('usePromptActions file attachment sync', () => {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 2883d299d0f..5e9ea6cad64 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@@ -246,6 +246,9 @@ interface RestoreMessageTarget {userOrdinal?: number | null}+const isStaleTargetError = (err: unknown) =>+ /no longer in session history|not in session history/i.test(err instanceof Error ? err.message : String(err))+export function usePromptActions({activeSessionId,activeSessionIdRef,@@ -1072,6 +1075,48 @@ export function usePromptActions({applySurvivorRowIds(sessionId, survivorRowIds)} catch (err) {+ let surfaced: unknown = err++ // A restore target can be addressed by a cached durable row id that+ // went stale after optimistic sends, resume drift, or session.branch+ // row-id remapping. Mirror edit's recovery: reload the selected stored+ // session, recompute the restore plan against fresh history, and retry+ // once instead of leaving Restore uniquely fail-closed (#107593).+ if ((plan.truncateMessageId || plan.truncateRowId !== undefined) && isStaleTargetError(err)) {+ try {+ const storedId = selectedStoredSessionIdRef.current++ if (storedId) {+ await resumeStoredSession(storedId)+ }++ const refreshed = $messages.get()+ const retryPlan = planRestore(refreshed, messageId, {+ text: target?.text ?? plan.sourceText,+ userOrdinal: target?.userOrdinal ?? plan.truncateOrdinal+ })++ if (retryPlan.truncateMessageId || retryPlan.truncateRowId !== undefined) {+ const survivorRowIds = await submitRewindPrompt(+ sessionId,+ retryPlan.text,+ retryPlan.truncateOrdinal,+ retryPlan.truncateMessageId,+ false,+ retryPlan.truncateRowId,+ retryPlan.sourceText,+ durableRowIdsForRebind(refreshed)+ )++ applySurvivorRowIds(sessionId, survivorRowIds)++ return+ }+ } catch (retryErr) {+ surfaced = retryErr+ }+ }+// The rewind never landed (e.g. the gateway stayed busy past the retry// deadline). Roll the optimistic truncation back to the full original// history so the UI doesn't desync from what's persisted — leaving it@@ -1087,10 +1132,18 @@ export function usePromptActions({turnStartedAt: null,messages}))- throw err+ throw surfaced}},- [activeSessionIdRef, applySurvivorRowIds, busyRef, submitRewindPrompt, updateSessionState]+ [+ activeSessionIdRef,+ applySurvivorRowIds,+ busyRef,+ resumeStoredSession,+ selectedStoredSessionIdRef,+ submitRewindPrompt,+ updateSessionState+ ])const editMessage = useCallback(@@ -1129,9 +1182,6 @@ export function usePromptActions({setAwaitingResponse(true)updateSessionState(sessionId, state => applyRewindOptimistic(state, plan.sourceIndex, plan.editedMessage))- const isStaleTargetError = (err: unknown) =>- /no longer in session history|not in session history/i.test(err instanceof Error ? err.message : String(err))-const isCompressedAwayError = (err: unknown) => {if (!(err instanceof JsonRpcGatewayError) || err.code !== 4018) {return false