The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): a server 4033 re-runs the rewind from the top instead of retrying a stale plan
kshitijk4poor1b8a09f88de9
diff --git a/apps/desktop/src/app/chat/session-tile-actions.test.ts b/apps/desktop/src/app/chat/session-tile-actions.test.tsindex 08a20e86223..34e4a3793df 100644--- a/apps/desktop/src/app/chat/session-tile-actions.test.ts+++ b/apps/desktop/src/app/chat/session-tile-actions.test.ts@@ -419,6 +419,60 @@ describe('useSessionTileActions reloadFromMessage failed-submit rollback (#95745expect(submits).toBe(2)})+ it('a turn that lands during the 4033 confirm is kept: accept re-plans, decline leaves it in place', async () => {+ const { JsonRpcGatewayError } = await import('@hermes/shared')+ const submits: Record<string, unknown>[] = []++ requestGatewayMock.mockImplementation(async (method: string, params?: Record<string, unknown>) => {+ if (method === 'prompt.submit') {+ submits.push(params ?? {})++ if (!params?.confirm_deep_truncate) {+ throw new JsonRpcGatewayError('truncation would archive later user turns', { code: 4033 })+ }+ }++ return {}+ })++ for (const accept of [true, false]) {+ publishSessionState(RUNTIME_SESSION_ID, createClientSessionState(STORED_SESSION_ID, seed as never))+ submits.length = 0+ const { result } = renderTileActions()++ // The 4033 dialog: a new turn arrives before the user answers (once; later dialogs just answer).+ let dialogs = 0++ const stopConfirming = $confirmRequest.listen(request => {+ if (request && dialogs++ > 0) {+ settleConfirm(true)+ } else if (request) {+ const current = $sessionStates.get()[RUNTIME_SESSION_ID]!+ publishSessionState(RUNTIME_SESSION_ID, {+ ...current,+ messages: [...current.messages, { id: 'u3', parts: [textPart('new')], role: 'user', timestamp: 5 }]+ } as never)+ settleConfirm(accept)+ }+ })++ await act(async () => {+ await result.current.reloadFromMessage('a2')+ })+ stopConfirming()++ const ids = $sessionStates.get()[RUNTIME_SESSION_ID]?.messages.map(m => m.id)++ // Decline leaves the new turn in place; accept asked again over the transcript that now holds+ // it, so the confirmed regenerate archives it knowingly.+ expect(ids?.includes('u3')).toBe(!accept)+ // Accept re-runs against the current transcript (u3 now follows the target, so it asks again —+ // auto-accepted here — and sends confirmed); decline submits nothing further.+ expect(submits.filter(p => p.confirm_deep_truncate).length).toBe(accept ? 1 : 0)+ expect(dialogs).toBe(accept ? 2 : 1)+ }+ })+it('restores the full tile transcript when regenerate is rejected', async () => {requestGatewayMock.mockImplementation(async (method: string) => {if (method === 'prompt.submit') {diff --git a/apps/desktop/src/app/chat/session-tile-actions.ts b/apps/desktop/src/app/chat/session-tile-actions.tsindex 097959ab469..da46cba53e6 100644--- a/apps/desktop/src/app/chat/session-tile-actions.ts+++ b/apps/desktop/src/app/chat/session-tile-actions.ts@@ -14,7 +14,7 @@ import { useCallback, useMemo, useRef } from 'react'import type { ClientSessionState } from '@/app/types'import type { WorkspaceMode } from '@/contrib/types'import { useI18n } from '@/i18n'-import { textPart } from '@/lib/chat-messages'+import { type ChatMessage, textPart } from '@/lib/chat-messages'import { isSlashCommandText } from '@/lib/chat-runtime'import { triggerHaptic } from '@/lib/haptics'import { clearClarifyRequest } from '@/store/clarify'@@ -60,7 +60,6 @@ import {planRestore,rebindSurvivorRowIds,runRewindSubmit,- submitWithDeepTruncateConfirm,type SurvivorUserRowIds} from '../session/hooks/use-prompt-actions/rewind'import { useSubmitPrompt } from '../session/hooks/use-prompt-actions/submit'@@ -551,7 +550,7 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored)const reloadFromMessage = useCallback(- async (parentId: string | null) => {+ async (parentId: string | null, answeredFor?: ChatMessage[]): Promise<void> => {const state = readState()if (!state || state.busy) {@@ -559,7 +558,10 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored}const confirmDeep = () => confirm(deepCutConfirmRequest(t.assistant.thread))- const plan = await planConfirmedReload(state.messages, parentId, confirmDeep)+ // The user's answer to a 4033 covers only the transcript they answered for: any change asks again.+ const forceDeep = answeredFor !== undefined && answeredFor === state.messages+ const planned = await planConfirmedReload(state.messages, parentId, forceDeep ? async () => true : confirmDeep)+ const plan = planned && forceDeep ? { ...planned, confirmDeepTruncate: true } : plannedconst after = readState()// The confirm is a wait of user length: a turn that started or output that landed meanwhile@@ -577,20 +579,15 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored// runRewindSubmit (withSessionNotFoundResume + runtime rebind), so the// PR-era inline prompt.submit wrapper is superseded on current main.applySurvivorRowIds(- await submitWithDeepTruncateConfirm(- confirmed =>- submitRewind(- plan.text,- plan.truncateOrdinal,- false,- plan.truncateMessageId,- plan.truncateRowId,- plan.sourceText,- durableRowIdsForRebind(messages),- confirmed- ),- plan.confirmDeepTruncate,- confirmDeep+ await submitRewind(+ plan.text,+ plan.truncateOrdinal,+ false,+ plan.truncateMessageId,+ plan.truncateRowId,+ plan.sourceText,+ durableRowIdsForRebind(messages),+ plan.confirmDeepTruncate))} catch (err) {@@ -605,15 +602,20 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, storedmessages}))- // A declined deep-cut confirm is the user's answer, not a failure.- if (!isDeepTruncateRefusal(err)) {+ if (!isDeepTruncateRefusal(err) || plan.confirmDeepTruncate) {notifyError(err, copy.regenerateFailed)+ } else if (await confirmDeep()) {+ // Re-run from the top: the session is re-read and re-validated after this wait.+ await reloadFromMessageRef.current(parentId, messages)}}},[applySurvivorRowIds, copy.regenerateFailed, readState, submitRewind, t, update])+ const reloadFromMessageRef = useRef(reloadFromMessage)+ reloadFromMessageRef.current = reloadFromMessage+const restoreToMessage = useCallback(async (messageId: string, target?: { text?: string; userOrdinal?: number | null }) => {const sessionId = runtimeIdRef.current@@ -704,10 +706,12 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored)const editMessage = useCallback(- async (edited: AppendMessage) => {+ async (edited: AppendMessage, answeredFor?: ChatMessage[]): Promise<void> => {const messages = readMessages()const confirmDeep = () => confirm(deepCutConfirmRequest(t.assistant.thread))- const plan = await planConfirmedEdit(messages, edited, confirmDeep)+ const forceDeep = answeredFor !== undefined && answeredFor === messages+ const planned = await planConfirmedEdit(messages, edited, forceDeep ? async () => true : confirmDeep)+ const plan = planned && forceDeep ? { ...planned, confirmDeepTruncate: true } : planned// Edit interrupts a live turn on purpose; only output that landed during the confirm makes// the plan's index and rollback snapshot stale.@@ -730,20 +734,15 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, storedtry {applySurvivorRowIds(- await submitWithDeepTruncateConfirm(- confirmed =>- submitRewind(- plan.text,- plan.truncateOrdinal,- interruptFirst,- plan.truncateMessageId,- plan.truncateRowId,- plan.sourceText,- durableRowIdsForRebind(messages),- confirmed- ),- plan.confirmDeepTruncate,- confirmDeep+ await submitRewind(+ plan.text,+ plan.truncateOrdinal,+ interruptFirst,+ plan.truncateMessageId,+ plan.truncateRowId,+ plan.sourceText,+ durableRowIdsForRebind(messages),+ plan.confirmDeepTruncate))} catch (err) {@@ -756,14 +755,20 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, storedmessages}))- if (!isDeepTruncateRefusal(err)) {+ if (!isDeepTruncateRefusal(err) || plan.confirmDeepTruncate) {notifyError(err, copy.editFailed)+ } else if (await confirmDeep()) {+ // Re-run from the top: the session is re-read and re-validated after this wait.+ await editMessageRef.current(edited, messages)}}},[applySurvivorRowIds, copy.editFailed, readMessages, readState, submitRewind, t, update])+ const editMessageRef = useRef(editMessage)+ editMessageRef.current = editMessage+// Branch-visibility sync (assistant-ui hides non-active branches).const handleThreadMessagesChange = useCallback((nextMessages: readonly ThreadMessage[]) => update(state => applyBranchVisibility(state, nextMessages)),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 26cb8665ee8..c49c86cac1e 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@@ -70,7 +70,6 @@ import {planRestore,rebindSurvivorRowIds,runRewindSubmit,- submitWithDeepTruncateConfirm,type SurvivorUserRowIds} from './rewind'import { useSlashCommand } from './slash'@@ -1003,7 +1002,7 @@ export function usePromptActions({)const reloadFromMessage = useCallback(- async (parentId: string | null) => {+ async (parentId: string | null, answeredFor?: ChatMessage[]): Promise<void> => {// Ref, not the closure-captured prop — a truncating resubmit aimed at a// stale session deletes the wrong transcript.const sessionId = activeSessionIdRef.current@@ -1016,7 +1015,10 @@ export function usePromptActions({// the global $messages mirror is empty/divergent for them (#68734).const messages = (sessionId ? $sessionStates.get()[sessionId]?.messages : null) ?? $messages.get()const confirmDeep = () => confirm(deepCutConfirmRequest(t.assistant.thread))- const plan = await planConfirmedReload(messages, parentId, confirmDeep)+ // The user's answer to a 4033 covers only the transcript they answered for: any change asks again.+ const forceDeep = answeredFor !== undefined && answeredFor === messages+ const planned = await planConfirmedReload(messages, parentId, forceDeep ? async () => true : confirmDeep)+ const plan = planned && forceDeep ? { ...planned, confirmDeepTruncate: true } : planned// The confirm is a wait of user length: a turn that started or output that landed meanwhile// makes the plan (and the rollback snapshot) stale, so drop it rather than cut a live turn.@@ -1028,21 +1030,16 @@ export function usePromptActions({updateSessionState(sessionId, state => applyReloadOptimistic(state, plan))try {- const survivorRowIds = await submitWithDeepTruncateConfirm(- confirmed =>- submitRewindPrompt(- sessionId,- plan.text,- plan.truncateOrdinal,- plan.truncateMessageId,- false,- plan.truncateRowId,- plan.sourceText,- durableRowIdsForRebind(messages),- confirmed- ),- plan.confirmDeepTruncate,- confirmDeep+ const survivorRowIds = await submitRewindPrompt(+ sessionId,+ plan.text,+ plan.truncateOrdinal,+ plan.truncateMessageId,+ false,+ plan.truncateRowId,+ plan.sourceText,+ durableRowIdsForRebind(messages),+ plan.confirmDeepTruncate)applySurvivorRowIds(sessionId, survivorRowIds)@@ -1059,15 +1056,20 @@ export function usePromptActions({messages}))- // A declined deep-cut confirm is the user's answer, not a failure.- if (!isDeepTruncateRefusal(err)) {+ if (!isDeepTruncateRefusal(err) || plan.confirmDeepTruncate) {notifyError(err, copy.regenerateFailed)+ } else if (await confirmDeep()) {+ // Re-run from the top: the session is re-read and re-validated after this wait.+ await reloadFromMessageRef.current(parentId, messages)}}},[activeSessionIdRef, applySurvivorRowIds, copy.regenerateFailed, submitRewindPrompt, t, updateSessionState])+ const reloadFromMessageRef = useRef(reloadFromMessage)+ reloadFromMessageRef.current = reloadFromMessage+// Cursor-style "restore checkpoint": rewind the conversation to a past user// prompt and run it again from there. Reuses the edit composer's rewind// mechanism — `prompt.submit` with `truncate_before_user_ordinal` drops that@@ -1201,7 +1203,7 @@ export function usePromptActions({)const editMessage = useCallback(- async (edited: AppendMessage) => {+ async (edited: AppendMessage, answeredFor?: ChatMessage[]): Promise<void> => {// Ref, not the closure-captured prop — an edit rewinds and resubmits, so// a stale target rewrites the wrong session's history.const sessionId = activeSessionIdRef.current@@ -1210,7 +1212,13 @@ export function usePromptActions({const messages = (sessionId ? $sessionStates.get()[sessionId]?.messages : null) ?? $messages.get()const confirmDeep = () => confirm(deepCutConfirmRequest(t.assistant.thread))- const plan = sessionId ? await planConfirmedEdit(messages, edited, confirmDeep) : null+ const forceDeep = answeredFor !== undefined && answeredFor === messages++ const planned = sessionId+ ? await planConfirmedEdit(messages, edited, forceDeep ? async () => true : confirmDeep)+ : null++ const plan = planned && forceDeep ? { ...planned, confirmDeepTruncate: true } : planned// Edit interrupts a live turn on purpose; only output that landed during the confirm makes// the plan's index and rollback snapshot stale.@@ -1255,21 +1263,16 @@ export function usePromptActions({}try {- const survivorRowIds = await submitWithDeepTruncateConfirm(- confirmed =>- submitRewindPrompt(- sessionId,- plan.text,- plan.truncateOrdinal,- plan.truncateMessageId,- interruptFirst,- plan.truncateRowId,- plan.sourceText,- durableRowIdsForRebind(messages),- confirmed- ),- plan.confirmDeepTruncate,- confirmDeep+ const survivorRowIds = await submitRewindPrompt(+ sessionId,+ plan.text,+ plan.truncateOrdinal,+ plan.truncateMessageId,+ interruptFirst,+ plan.truncateRowId,+ plan.sourceText,+ durableRowIdsForRebind(messages),+ plan.confirmDeepTruncate)applySurvivorRowIds(sessionId, survivorRowIds)@@ -1297,21 +1300,16 @@ export function usePromptActions({// re-addresses the same turn after a history refresh.if (retryPlan && !retryPlan.isFailedTurn) {- const survivorRowIds = await submitWithDeepTruncateConfirm(- confirmed =>- submitRewindPrompt(- sessionId,- retryPlan.text,- retryPlan.truncateOrdinal,- retryPlan.truncateMessageId,- false,- retryPlan.truncateRowId,- retryPlan.sourceText,- durableRowIdsForRebind(refreshed),- confirmed- ),- plan.confirmDeepTruncate,- confirmDeep+ const survivorRowIds = await submitRewindPrompt(+ sessionId,+ retryPlan.text,+ retryPlan.truncateOrdinal,+ retryPlan.truncateMessageId,+ false,+ retryPlan.truncateRowId,+ retryPlan.sourceText,+ durableRowIdsForRebind(refreshed),+ plan.confirmDeepTruncate)applySurvivorRowIds(sessionId, survivorRowIds)@@ -1341,9 +1339,11 @@ export function usePromptActions({messages}))- // A declined deep-cut confirm is the user's answer, not a failure.- if (!isDeepTruncateRefusal(surfaced)) {+ if (!isDeepTruncateRefusal(surfaced) || plan.confirmDeepTruncate) {notifyError(surfaced, unavailable ? copy.editTurnUnavailable : copy.editFailed)+ } else if (await confirmDeep()) {+ // Re-run from the top: the session is re-read and re-validated after this wait.+ await editMessageRef.current(edited, messages)}}},@@ -1361,6 +1361,9 @@ export function usePromptActions({])+ const editMessageRef = useRef(editMessage)+ editMessageRef.current = editMessage+const handleThreadMessagesChange = useCallback((nextMessages: readonly ThreadMessage[]) => {const sessionId = activeSessionIdRef.currentdiff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.tsindex 060c91ecade..30b5d038f04 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.ts@@ -1,4 +1,3 @@-import { JsonRpcGatewayError } from '@hermes/shared'import { describe, expect, it } from 'vitest'import { type ChatMessage, finalizeInterruptedMessages, textPart } from '@/lib/chat-messages'@@ -18,7 +17,6 @@ import {rebindSurvivorRowIds,resolveDurableRowId,runRewindSubmit,- submitWithDeepTruncateConfirm,survivorRowIdsFrom,truncateSubmitParams} from './rewind'@@ -809,34 +807,4 @@ describe('edit and server-refusal confirms (#133716 review)', () => {expect(await planConfirmedEdit(transcript, editOf('u2'), decline)).toMatchObject({ confirmDeepTruncate: false })expect(asked).toBe(1)})-- it('a 4033 the client did not predict asks once and retries confirmed; other errors pass through', async () => {- const refusal = new JsonRpcGatewayError('truncation would archive later user turns', { code: 4033 })- const sent: boolean[] = []-- const submit = async (confirmed: boolean) => {- sent.push(confirmed)-- if (!confirmed) {- throw refusal- }-- return 'ok'- }-- expect(await submitWithDeepTruncateConfirm(submit, false, async () => true)).toBe('ok')- expect(sent).toEqual([false, true])-- await expect(submitWithDeepTruncateConfirm(submit, false, async () => false)).rejects.toBe(refusal)- expect(sent).toEqual([false, true, false])-- const busy = new Error('session busy')- await expect(- submitWithDeepTruncateConfirm(- async () => Promise.reject(busy),- false,- async () => true- )- ).rejects.toBe(busy)- })})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.tsindex 3f05e607504..ef24dde3d0b 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@@ -25,7 +25,6 @@ import type { ConfirmRequest } from '@/store/confirm'import {appendText,- isDeepTruncateRefusal,isFailedUserTurn,isSessionBusyError,isVisibleUserMessage,@@ -590,28 +589,6 @@ async function confirmIfDeepCut<P extends { truncateOrdinal: number | undefinedreturn (await confirmDeep()) ? { ...plan, confirmDeepTruncate: true } : null}-/**- * The server counts later user turns with its own predicate (steer rows, compaction carriers) and- * refuses an unconfirmed deep cut with 4033. Client and server can disagree, so a refusal asks the- * same destructive confirm once and retries confirmed. A decline rethrows the 4033, which callers- * roll back silently (`isDeepTruncateRefusal`).- */-export async function submitWithDeepTruncateConfirm<T>(- submit: (confirmDeepTruncate: boolean) => Promise<T>,- confirmed: boolean,- confirmDeep: () => Promise<boolean>-): Promise<T> {- try {- return await submit(confirmed)- } catch (err) {- if (confirmed || !isDeepTruncateRefusal(err) || !(await confirmDeep())) {- throw err- }-- return submit(true)- }-}-/** Optimistic reload state: keep the user turn, hide the branch's assistants. */export function applyReloadOptimistic(state: ClientSessionState, plan: ReloadPlan): ClientSessionState {const nextUserIndex = state.messages.findIndex((m, i) => i > plan.userIndex && m.role === 'user')diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.tsindex 377e39575dd..31ebaf28ee3 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts@@ -279,7 +279,12 @@ export function isGatewayTimeoutError(error: unknown): boolean {export const SESSION_BUSY_RETRY_TIMEOUT_MS = 6_000export const SESSION_BUSY_RETRY_INTERVAL_MS = 150-/** prompt.submit refused an unconfirmed truncation that would archive later user turns (#133716). */+/**+ * prompt.submit refused an unconfirmed truncation that would archive later user turns (#133716).+ * The server counts turns with its own predicate, so it can refuse a cut the client judged shallow:+ * callers roll back at once (the submit wrote nothing), ask, and re-run the action with the deep cut+ * forced, so the retry re-reads and re-validates the session like any first attempt.+ */export const GATEWAY_DEEP_TRUNCATE_REFUSED_CODE = 4033export function isDeepTruncateRefusal(error: unknown): boolean {