Skip to content

The agent that grows with you

fix(desktop): an edit retry only reuses the deep confirm it covered; a session switch drops the edit

kshitijk4poor183e955bd00c
diff --git a/apps/desktop/src/app/chat/session-tile-actions.ts b/apps/desktop/src/app/chat/session-tile-actions.ts
index 974f19b6fcb..8c5e6cd0028 100644
--- a/apps/desktop/src/app/chat/session-tile-actions.ts
+++ b/apps/desktop/src/app/chat/session-tile-actions.ts
@@ -713,12 +713,14 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored
const runEdit = useCallback(
async (edited: AppendMessage, answeredFor?: ChatMessage[]): Promise<void> => {
const planning = readMessages()
+ const runtimeAtPlan = runtimeIdRef.current
const confirmDeep = () => confirm(deepCutConfirmRequest(t.assistant.thread))
const forceDeep = answeredFor !== undefined && answeredFor === planning
const planned = await planConfirmedEdit(planning, edited, forceDeep ? async () => true : confirmDeep)
const forced = planned && forceDeep ? { ...planned, confirmDeepTruncate: true } : planned
- if (!forced) {
+ // A confirm is a wait of user length: an answer given after a runtime rebind is not for this one.
+ if (!forced || runtimeIdRef.current !== runtimeAtPlan) {
return
}
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 5cb190adb6f..a9c5b0c32ba 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
@@ -6309,6 +6309,138 @@ describe('usePromptActions deep edit confirmed while output streams (#133716)',
})
})
+describe('usePromptActions deep-edit consent scope (#133716)', () => {
+ afterEach(() => {
+ cleanup()
+ clearNotifications()
+ setMessages([])
+ $busy.set(false)
+ dropSessionState(RUNTIME_SESSION_ID)
+ dropSessionState('other-runtime')
+ })
+
+ it('a stale-target retry whose refresh shows a new later turn does not reuse the deep confirm', async () => {
+ const seed = [
+ { id: 'u1', parts: [textPart('first')], role: 'user', rowId: 11, timestamp: 0 },
+ { id: 'a1', parts: [textPart('reply')], role: 'assistant', timestamp: 1 },
+ { id: 'u2', parts: [textPart('second')], role: 'user', 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', rowId: 25, timestamp: 3 }
+ ]
+
+ 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
+
+ await actRender(
+ <Harness
+ onReady={h => {
+ handle = h
+ }}
+ refreshSessions={async () => undefined}
+ requestGateway={requestGateway}
+ resumeStoredSession={async () => {
+ setMessages(fresh as never)
+ }}
+ seedMessages={seed}
+ storedSessionId="stored"
+ />
+ )
+
+ const stopConfirming = $confirmRequest.listen(request => {
+ if (request) {
+ settleConfirm(true)
+ }
+ })
+
+ await handle!.editMessage({
+ content: [{ text: 'edited first', type: 'text' }],
+ parentId: null,
+ role: 'user',
+ sourceId: 'u1'
+ } as never)
+ stopConfirming()
+
+ expect(submits).toHaveLength(2)
+ expect(submits[1]).toMatchObject({ truncate_before_row_id: 21 })
+ expect(submits[1]).not.toHaveProperty('confirm_deep_truncate')
+ })
+
+ 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 },
+ { id: 'u2', parts: [textPart('second')], role: 'user', rowId: 13, timestamp: 1 }
+ ]
+
+ const other = [{ id: 'other-user', parts: [textPart('other chat')], role: 'user', rowId: 99, timestamp: 2 }]
+
+ publishSessionState(RUNTIME_SESSION_ID, createClientSessionState('stored', seed as never))
+ publishSessionState('other-runtime', createClientSessionState('other-stored', other as never))
+ setMessages(seed as never)
+ const activeSessionIdRef: MutableRefObject<string | null> = { current: RUNTIME_SESSION_ID }
+ const submits: Record<string, unknown>[] = []
+
+ const requestGateway = vi.fn(async (method: string, params?: Record<string, unknown>) => {
+ if (method === 'prompt.submit') {
+ submits.push(params ?? {})
+ }
+
+ return {} as never
+ })
+
+ let handle: HarnessHandle | undefined
+
+ await actRender(
+ <Harness
+ activeSessionIdRef={activeSessionIdRef}
+ onReady={h => {
+ handle = h
+ }}
+ refreshSessions={async () => undefined}
+ requestGateway={requestGateway}
+ seedMessages={seed}
+ />
+ )
+
+ const stopConfirming = $confirmRequest.listen(request => {
+ if (request) {
+ activeSessionIdRef.current = 'other-runtime'
+ setMessages(other as never)
+ settleConfirm(true)
+ }
+ })
+
+ await handle!.editMessage({
+ content: [{ text: 'edited first', type: 'text' }],
+ parentId: null,
+ role: 'user',
+ sourceId: 'u1'
+ } as never)
+ stopConfirming()
+
+ expect(submits).toEqual([])
+ expect($busy.get()).toBe(false)
+ })
+})
+
describe('usePromptActions live-owner refusal (#106217)', () => {
afterEach(() => {
cleanup()
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 dbf04a16ad2..9a496c71aeb 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
@@ -65,6 +65,7 @@ import {
durableRowIdsForRebind,
finalizeStoppedMessages,
planConfirmedEdit,
+ laterVisibleUserTurns,
planConfirmedReload,
planEdit,
planRestore,
@@ -1224,7 +1225,8 @@ export function usePromptActions({
const forced = planned && forceDeep ? { ...planned, confirmDeepTruncate: true } : planned
- if (!sessionId || !forced) {
+ // A confirm is a wait of user length: an answer given after a session switch is not for this one.
+ if (!sessionId || !forced || activeSessionIdRef.current !== sessionId) {
return
}
@@ -1294,6 +1296,8 @@ export function usePromptActions({
} catch (err) {
let surfaced: unknown = err
let unavailable = isCompressedAwayError(err)
+ // Whether the submit that produced *surfaced* carried a deep-cut confirm.
+ let surfacedConfirmed = plan.confirmDeepTruncate
// Stale target after compression/resume drift (the cached rowId and
// ordinal address the pre-compression segment): reload server history,
@@ -1311,10 +1315,17 @@ export function usePromptActions({
const refreshed = $messages.get()
const retryPlan = planEdit(refreshed, edited)
- // planEdit, not planConfirmedEdit: the user already answered for this edit; the retry only
- // re-addresses the same turn after a history refresh.
+ // planEdit, not planConfirmedEdit: the retry only 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, it goes unconfirmed and the server gate decides (a 4033 asks again below).
+ const retryConfirmed =
+ plan.confirmDeepTruncate &&
+ retryPlan !== null &&
+ laterVisibleUserTurns(refreshed, retryPlan.sourceIndex) ===
+ laterVisibleUserTurns(messages, plan.sourceIndex)
if (retryPlan && !retryPlan.isFailedTurn) {
+ surfacedConfirmed = retryConfirmed
const survivorRowIds = await submitRewindPrompt(
sessionId,
retryPlan.text,
@@ -1324,7 +1335,7 @@ export function usePromptActions({
retryPlan.truncateRowId,
retryPlan.sourceText,
durableRowIdsForRebind(refreshed),
- plan.confirmDeepTruncate
+ retryConfirmed
)
applySurvivorRowIds(sessionId, survivorRowIds)
@@ -1354,11 +1365,12 @@ export function usePromptActions({
messages
}))
- if (!isDeepTruncateRefusal(surfaced) || plan.confirmDeepTruncate) {
+ if (!isDeepTruncateRefusal(surfaced) || surfacedConfirmed) {
notifyError(surfaced, unavailable ? copy.editTurnUnavailable : copy.editFailed)
} else if ((await confirmDeep()) && activeSessionIdRef.current === sessionId) {
// Re-run from the top: the session is re-read and re-validated after this wait. The answer
- // belongs to this session: a switch during the dialog drops it.
+ // belongs to this session (a switch during the dialog drops it) and to *planning*: after a
+ // refresh the transcript differs, so the re-run asks once more.
await runEditRef.current(edited, planning)
}
}
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 7eb0518003c..1f02bec431f 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
@@ -740,6 +740,10 @@ export async function planConfirmedEdit(
return plan && confirmIfDeepCut(messages, plan, plan.sourceIndex, confirmDeep)
}
+/** Visible user turns after *index*: what a cut there archives, and what a deep confirm covered. */
+export const laterVisibleUserTurns = (messages: ChatMessage[], index: number) =>
+ messages.filter((m, i) => i > index && isVisibleUserMessage(m)).length
+
/**
* After an awaited confirm, an edit plan still holds when the same turn is the target in the
* current transcript. Streaming replaces the array on every delta, so identity is not the test:
@@ -753,16 +757,13 @@ export function revalidateEditPlan<P extends EditPlan>(
): P | null {
const fresh = planEdit(current, edited)
- const laterUsers = (messages: ChatMessage[], index: number) =>
- messages.filter((m, i) => i > index && isVisibleUserMessage(m)).length
-
// A new later user turn landed during the confirm: the user never answered for archiving it.
if (
!fresh ||
fresh.truncateMessageId !== plan.truncateMessageId ||
fresh.truncateRowId !== plan.truncateRowId ||
fresh.truncateOrdinal !== plan.truncateOrdinal ||
- laterUsers(current, fresh.sourceIndex) !== laterUsers(planned, plan.sourceIndex)
+ laterVisibleUserTurns(current, fresh.sourceIndex) !== laterVisibleUserTurns(planned, plan.sourceIndex)
) {
return null
}