Skip to content

The agent that grows with you

fix(desktop): confirm a regenerate that would archive later user turns

kshitijk4poorcbb057c0b746
diff --git a/apps/desktop/src/app/chat/session-tile-actions.test.ts b/apps/desktop/src/app/chat/session-tile-actions.test.ts
index 7d3c9b89f92..a354d5cf1bc 100644
--- a/apps/desktop/src/app/chat/session-tile-actions.test.ts
+++ b/apps/desktop/src/app/chat/session-tile-actions.test.ts
@@ -10,6 +10,7 @@ import { MAIN_COMPOSER_SCOPE } from './composer/scope'
const requestGatewayMock = vi.hoisted(() => vi.fn())
const { $activeSessionId, $sessions, setSessions } = await import('@/store/session')
+const { $confirmRequest, settleConfirm } = await import('@/store/confirm')
const { $sessionStates, $sessionTiles, clearAllSessionStates, publishSessionState, setSessionTileDelegate } =
await import('@/store/session-states')
@@ -366,10 +367,13 @@ describe('useSessionTileActions reloadFromMessage failed-submit rollback (#95745
})
const { result } = renderTileActions()
+ // Regenerating u1 archives the later u2 turn: accept the deep-cut confirm (#133716).
+ const stopConfirming = $confirmRequest.listen(request => request && settleConfirm(true))
await act(async () => {
await result.current.reloadFromMessage('u1')
})
+ stopConfirming()
const rolledBack = $sessionStates.get()[RUNTIME_SESSION_ID]?.messages
diff --git a/apps/desktop/src/app/chat/session-tile-actions.ts b/apps/desktop/src/app/chat/session-tile-actions.ts
index 17d7b261e4e..6c41b39251c 100644
--- a/apps/desktop/src/app/chat/session-tile-actions.ts
+++ b/apps/desktop/src/app/chat/session-tile-actions.ts
@@ -20,6 +20,7 @@ import { triggerHaptic } from '@/lib/haptics'
import { clearClarifyRequest } from '@/store/clarify'
import type { ComposerAttachment } from '@/store/composer'
import { resetSessionBackground } from '@/store/composer-status'
+import { confirm } from '@/store/confirm'
import { notify, notifyError } from '@/store/notifications'
import { clearPreviewArtifacts } from '@/store/preview-status'
import { clearAllPrompts } from '@/store/prompts'
@@ -51,10 +52,11 @@ import {
applyBranchVisibility,
applyReloadOptimistic,
applyRewindOptimistic,
+ deepReloadConfirmRequest,
durableRowIdsForRebind,
finalizeStoppedMessages,
+ planConfirmedReload,
planEdit,
- planReload,
planRestore,
rebindSurvivorRowIds,
runRewindSubmit,
@@ -552,7 +554,9 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored
return
}
- const plan = planReload(state.messages, parentId)
+ const plan = await planConfirmedReload(state.messages, parentId, () =>
+ confirm(deepReloadConfirmRequest(t.assistant.thread))
+ )
if (!plan) {
return
@@ -591,7 +595,7 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored
notifyError(err, copy.regenerateFailed)
}
},
- [applySurvivorRowIds, copy.regenerateFailed, readState, submitRewind, update]
+ [applySurvivorRowIds, copy.regenerateFailed, readState, submitRewind, t, update]
)
const restoreToMessage = useCallback(
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.tsx
index d7a35054ba5..6e0d6b0a7fd 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
@@ -11,6 +11,7 @@ import { createClientSessionState } from '@/lib/chat-runtime'
import { $compactingSessions, setSessionCompacting } from '@/store/compaction'
import { $composerAttachments, $composerDraft, type ComposerAttachment, setComposerDraft } from '@/store/composer'
import { $queuedPromptsBySession, getQueuedPrompts } from '@/store/composer-queue'
+import { $confirmRequest, settleConfirm } from '@/store/confirm'
import { requestGatewayForAgent } from '@/store/gateway'
import { $goalsBySession, setSessionGoal } from '@/store/goals'
import { $hudMode } from '@/store/hud'
@@ -6199,7 +6200,10 @@ describe('usePromptActions reloadFromMessage failed-submit rollback (#95745)', (
/>
)
+ // Regenerating u1 archives the later u2 turn: accept the deep-cut confirm (#133716).
+ const stopConfirming = $confirmRequest.listen(request => request && settleConfirm(true))
await handle!.reloadFromMessage('u1')
+ stopConfirming()
const rolledBack = latest?.messages as Array<{ hidden?: boolean; id: string }> | undefined
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.ts
index 6877698f13c..56634ead17a 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
@@ -24,6 +24,7 @@ import {
updateComposerAttachment
} from '@/store/composer'
import { resetSessionBackground } from '@/store/composer-status'
+import { confirm } from '@/store/confirm'
import { clearNotifications, notify, notifyError } from '@/store/notifications'
import { clearPreviewArtifacts } from '@/store/preview-status'
import { clearAllPrompts } from '@/store/prompts'
@@ -60,10 +61,11 @@ import {
applyBranchVisibility,
applyReloadOptimistic,
applyRewindOptimistic,
+ deepReloadConfirmRequest,
durableRowIdsForRebind,
finalizeStoppedMessages,
+ planConfirmedReload,
planEdit,
- planReload,
planRestore,
rebindSurvivorRowIds,
runRewindSubmit,
@@ -1004,7 +1006,9 @@ export function usePromptActions({
// the global $messages mirror is empty/divergent for them (#68734).
const messages = (sessionId ? $sessionStates.get()[sessionId]?.messages : null) ?? $messages.get()
- const plan = planReload(messages, parentId)
+ const plan = await planConfirmedReload(messages, parentId, () =>
+ confirm(deepReloadConfirmRequest(t.assistant.thread))
+ )
if (!plan) {
return
@@ -1041,7 +1045,7 @@ export function usePromptActions({
notifyError(err, copy.regenerateFailed)
}
},
- [activeSessionIdRef, applySurvivorRowIds, copy.regenerateFailed, submitRewindPrompt, updateSessionState]
+ [activeSessionIdRef, applySurvivorRowIds, copy.regenerateFailed, submitRewindPrompt, t, updateSessionState]
)
// Cursor-style "restore checkpoint": rewind the conversation to a past user
diff --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.ts
index 84048033fec..72d36f3b269 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
@@ -9,6 +9,7 @@ import {
applyRewindOptimistic,
finalizeStoppedMessages,
finalizeUserInterruptedMessages,
+ planConfirmedReload,
planEdit,
planReload,
planRestore,
@@ -705,3 +706,57 @@ describe('optimistic rewind/reload turn-clock seeding (#86795)', () => {
expect(next.turnStartedAt).toBeGreaterThanOrEqual(before)
})
})
+
+describe('planConfirmedReload (#133716)', () => {
+ const transcript = [
+ row('u1', 'user', 'old prompt', { rowId: 11 }),
+ row('a1', 'assistant', 'old reply'),
+ row('u2', 'user', 'latest prompt', { rowId: 13 }),
+ row('a2', 'assistant', 'latest reply')
+ ]
+
+ const submitPlan = async (plan: Awaited<ReturnType<typeof planConfirmedReload>>) => {
+ const submits: Record<string, unknown>[] = []
+
+ const gateway = (async (method: string, params?: Record<string, unknown>) => {
+ if (method === 'prompt.submit') {
+ submits.push(params ?? {})
+ }
+
+ return { status: 'streaming' }
+ }) as <T>(method: string, params?: Record<string, unknown>) => Promise<T>
+
+ if (plan) {
+ await runRewindSubmit(
+ gateway,
+ 'sid',
+ plan.text,
+ plan.truncateOrdinal,
+ plan.truncateMessageId,
+ false,
+ undefined,
+ plan.truncateRowId,
+ plan.sourceText
+ )
+ }
+
+ return submits[0]
+ }
+
+ it('confirms a stale/deep regenerate before archiving later user turns; tail regenerate is unchanged', async () => {
+ let asked = 0
+ const askAndDecline = async () => (asked += 1) < 0
+
+ expect(await submitPlan(await planConfirmedReload(transcript, 'a1', askAndDecline))).toBeUndefined()
+ expect(asked).toBe(1)
+
+ expect(await submitPlan(await planConfirmedReload(transcript, 'a1', async () => true))).toMatchObject({
+ truncate_before_row_id: 11
+ })
+
+ const tail = await submitPlan(await planConfirmedReload(transcript, 'a2', askAndDecline))
+
+ expect(asked).toBe(1)
+ expect(tail).toMatchObject({ confirm_truncate: true, truncate_before_row_id: 13 })
+ })
+})
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.ts
index 1457b8283c9..e42f75bac30 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
@@ -21,6 +21,7 @@ import {
finalizeInterruptedMessages,
textPart
} from '@/lib/chat-messages'
+import type { ConfirmRequest } from '@/store/confirm'
import {
appendText,
@@ -531,6 +532,43 @@ export function planReload(messages: ChatMessage[], parentId: null | string): nu
}
}
+/** Regenerate reuses the restore checkpoint confirm copy for a deep cut. */
+export const deepReloadConfirmRequest = (copy: {
+ restoreBody: string
+ restoreConfirm: string
+ restoreTitle: string
+}): ConfirmRequest => ({
+ confirmLabel: copy.restoreConfirm,
+ description: copy.restoreBody,
+ destructive: true,
+ title: copy.restoreTitle
+})
+
+/**
+ * Regenerate's target comes from the bound message scope, which can go stale
+ * and name a turn hours back — the planner trusted it and the submit silently
+ * archived every later turn (#133716). A reload that would drop later user
+ * turns goes through the same confirm restore uses; null when declined. The
+ * tail regenerate (nothing after the target) is returned unchanged.
+ */
+export async function planConfirmedReload(
+ messages: ChatMessage[],
+ parentId: null | string,
+ confirmDeep: () => Promise<boolean>
+): Promise<null | ReloadPlan> {
+ const plan = planReload(messages, parentId)
+
+ if (
+ !plan ||
+ plan.truncateOrdinal === undefined ||
+ !visibleUserMessageIndices(messages).some(i => i > plan.userIndex)
+ ) {
+ return plan
+ }
+
+ return (await confirmDeep()) ? plan : null
+}
+
/** 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')