Skip to content

The agent that grows with you

refactor(desktop): a stale-target edit retry re-plans through planEditAfterConfirm

kshitijk4poor1df95a89434a
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.tsx
index cb84d726d3c..63407ebea15 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
@@ -7,7 +7,7 @@ import { textPart } from '@/lib/chat-messages'
import { createClientSessionState } from '@/lib/chat-runtime'
import { $confirmRequest, settleConfirm } from '@/store/confirm'
import { clearNotifications } from '@/store/notifications'
-import { $busy, setMessages } from '@/store/session'
+import { $busy, setActiveSessionId, setMessages } from '@/store/session'
import { dropSessionState, publishSessionState } from '@/store/session-states'
import { actRender, Harness, type HarnessHandle, RUNTIME_SESSION_ID } from './prompt-actions-harness'
@@ -248,6 +248,7 @@ describe('usePromptActions deep-edit consent scope (#133716)', () => {
clearNotifications()
setMessages([])
$busy.set(false)
+ setActiveSessionId(null)
dropSessionState(RUNTIME_SESSION_ID)
dropSessionState('other-runtime')
})
@@ -320,9 +321,10 @@ describe('usePromptActions deep-edit consent scope (#133716)', () => {
})
it.each([
- ['accepting', true],
- ['declining', false]
- ])('%s the second deep confirm on a stale-target retry acts on the refreshed history', async (_label, accept) => {
+ ['accepting', 'accept'],
+ ['declining', 'decline'],
+ ['accepting after a session switch', 'switch']
+ ])('%s the second deep confirm on a stale-target retry acts on the refreshed history', async (_label, answer) => {
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 },
@@ -336,6 +338,8 @@ describe('usePromptActions deep-edit consent scope (#133716)', () => {
{ id: 'u3', parts: [textPart('arrived after consent')], role: 'user' as const, rowId: 25, timestamp: 3 }
]
+ // The session on screen: the store keeps its transcript (an unreferenced settled one is evicted).
+ setActiveSessionId(RUNTIME_SESSION_ID)
publishSessionState(RUNTIME_SESSION_ID, createClientSessionState('stored', seed as never))
setMessages(seed as never)
const submits: Record<string, unknown>[] = []
@@ -379,7 +383,12 @@ describe('usePromptActions deep-edit consent scope (#133716)', () => {
const stopConfirming = $confirmRequest.listen(request => {
if (request) {
confirms += 1
- settleConfirm(confirms === 1 || accept)
+
+ if (confirms === 2 && answer === 'switch') {
+ handle!.activeSessionIdRef.current = 'other-runtime'
+ }
+
+ settleConfirm(confirms === 1 || answer !== 'decline')
}
})
@@ -393,13 +402,14 @@ describe('usePromptActions deep-edit consent scope (#133716)', () => {
expect(confirms).toBe(2)
- if (accept) {
+ if (answer === '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.
+ // After a switch the foreground busy flag belongs to the session now on screen.
+ expect($busy.get()).toBe(answer === 'switch')
+ // The refresh already replaced the optimistic edit; a cancel must not restore the stale seed.
expect(lastState).toMatchObject({ busy: false })
expect(lastState?.messages).not.toBe(seed)
}
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 83d3421be72..ca704d10603 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
@@ -67,7 +67,6 @@ import {
durableRowIdsForRebind,
type EditPlan,
finalizeStoppedMessages,
- laterVisibleUserTurns,
planConfirmedReload,
planEdit,
planEditAfterConfirm,
@@ -1344,35 +1343,36 @@ export function usePromptActions({
await resumeStoredSession(storedId)
}
+ // A refresh that keeps the same later turns keeps the user's answer; one that reveals more
+ // asks again. After the dialog the plan is re-aimed by content (revalidateEditPlan), since the
+ // session slice and the $messages mirror are distinct arrays.
const refreshed = $messages.get()
- const retryPlan = planEdit(refreshed, edited)
+ const first = planEdit(refreshed, edited)
- if (!retryPlan || retryPlan.isFailedTurn) {
+ if (!first || first.isFailedTurn) {
return { unavailable: true }
}
- surfacedConfirmed = retryKeepsDeepConfirm(plan, messages, retryPlan, refreshed)
-
- // A refreshed 4018 retry can reveal later user turns the first plan did
- // 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))
+ const planned = await planEditAfterConfirm({
+ answeredFor: retryKeepsDeepConfirm(plan, messages, first, refreshed) ? refreshed : undefined,
+ confirmDeep: () => confirm(deepCutConfirmRequest(t.assistant.thread)),
+ current: () => currentMessages(sessionId),
+ edited,
+ planning: refreshed,
+ stillOwned: () => activeSessionIdRef.current === sessionId
+ })
- 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)
+ if (planned === null || planned === 'moved') {
+ // 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
+ return 'done'
}
+ const { messages: target, plan: retryPlan } = planned
+ surfacedConfirmed = retryPlan.confirmDeepTruncate
+
const survivorRowIds = await submitRewindPrompt(
sessionId,
retryPlan.text,
@@ -1381,7 +1381,7 @@ export function usePromptActions({
false,
retryPlan.truncateRowId,
retryPlan.sourceText,
- durableRowIdsForRebind(refreshed),
+ durableRowIdsForRebind(target),
surfacedConfirmed
)
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 ea59746a27e..f76fe92858f 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
@@ -840,8 +840,9 @@ export function revalidateEditPlan<P extends EditPlan>(
* Edit's plan step around the deep-cut confirm. Returns the plan and the transcript it is aimed at,
* null when there is nothing to send (declined, nothing changed, or the confirm was answered after
* the session switched away), or 'moved' when the edited turn moved during the confirm.
- * *answeredFor* is the transcript a 4033 confirm already covered: the re-run forces the deep cut
- * only while the transcript is still exactly that one.
+ * *answeredFor* is the transcript an earlier answer already covers (a 4033 re-run, or a stale-target
+ * retry whose refresh kept the same later turns): the deep cut is forced only while *planning* is
+ * still exactly that transcript.
*/
export async function planEditAfterConfirm(opts: {
answeredFor?: ChatMessage[]
@@ -870,8 +871,7 @@ export async function planEditAfterConfirm(opts: {
/**
* A stale-target retry re-addresses the same turn after a history refresh. The user's deep-cut
- * answer covers the later turns they saw; if the refresh shows more, the retry goes unconfirmed and
- * the server gate decides.
+ * answer covers the later turns they saw; if the refresh shows more, the retry asks again.
*/
export function retryKeepsDeepConfirm(
plan: EditPlan & { confirmDeepTruncate: boolean },