Skip to content

The agent that grows with you

refactor(desktop): one deep-cut confirm helper; drop a plan that went stale during the confirm

kshitijk4poor2afbaf10d122
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 fc0c08f68c1..08a20e86223 100644
--- a/apps/desktop/src/app/chat/session-tile-actions.test.ts
+++ b/apps/desktop/src/app/chat/session-tile-actions.test.ts
@@ -358,6 +358,67 @@ describe('useSessionTileActions reloadFromMessage failed-submit rollback (#95745
})
})
+ it('drops a deep regenerate whose transcript changed while the confirm was open', async () => {
+ requestGatewayMock.mockImplementation(async () => ({}))
+ const { result } = renderTileActions()
+
+ // Output lands while the user reads the dialog: the plan and its rollback snapshot are stale.
+ const stopConfirming = $confirmRequest.listen(request => {
+ if (request) {
+ const current = $sessionStates.get()[RUNTIME_SESSION_ID]!
+ publishSessionState(RUNTIME_SESSION_ID, {
+ ...current,
+ messages: [...current.messages, { id: 'a3', parts: [textPart('late')], role: 'assistant', timestamp: 4 }]
+ } as never)
+ settleConfirm(true)
+ }
+ })
+
+ await act(async () => {
+ await result.current.reloadFromMessage('u1')
+ })
+ stopConfirming()
+
+ expect(requestGatewayMock.mock.calls.some(([method]) => method === 'prompt.submit')).toBe(false)
+ expect($sessionStates.get()[RUNTIME_SESSION_ID]?.messages.map(m => m.id)).toEqual(['u1', 'a1', 'u2', 'a2', 'a3'])
+ })
+
+ it('a deep-cut 4033 the tile did not predict asks once and resubmits confirmed', async () => {
+ const { JsonRpcGatewayError } = await import('@hermes/shared')
+ let submits = 0
+
+ requestGatewayMock.mockImplementation(async (method: string, params?: Record<string, unknown>) => {
+ if (method === 'prompt.submit') {
+ submits += 1
+
+ if (!params?.confirm_deep_truncate) {
+ throw new JsonRpcGatewayError('truncation would archive later user turns', { code: 4033 })
+ }
+ }
+
+ return {}
+ })
+
+ const { result } = renderTileActions()
+ let asked = 0
+
+ const stopConfirming = $confirmRequest.listen(request => {
+ if (request) {
+ asked += 1
+ settleConfirm(true)
+ }
+ })
+
+ // Regenerating the tail predicts no deep cut; the server counts one anyway.
+ await act(async () => {
+ await result.current.reloadFromMessage('a2')
+ })
+ stopConfirming()
+
+ expect(asked).toBe(1)
+ expect(submits).toBe(2)
+ })
+
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.ts
index 4c654f7d639..097959ab469 100644
--- a/apps/desktop/src/app/chat/session-tile-actions.ts
+++ b/apps/desktop/src/app/chat/session-tile-actions.ts
@@ -52,7 +52,7 @@ import {
applyBranchVisibility,
applyReloadOptimistic,
applyRewindOptimistic,
- deepReloadConfirmRequest,
+ deepCutConfirmRequest,
durableRowIdsForRebind,
finalizeStoppedMessages,
planConfirmedEdit,
@@ -558,11 +558,13 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored
return
}
- const plan = await planConfirmedReload(state.messages, parentId, () =>
- confirm(deepReloadConfirmRequest(t.assistant.thread))
- )
+ const confirmDeep = () => confirm(deepCutConfirmRequest(t.assistant.thread))
+ const plan = await planConfirmedReload(state.messages, parentId, confirmDeep)
+ const after = readState()
- if (!plan) {
+ // 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.
+ if (!plan || !after || after.busy || after.messages !== state.messages) {
return
}
@@ -588,7 +590,7 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored
confirmed
),
plan.confirmDeepTruncate,
- () => confirm(deepReloadConfirmRequest(t.assistant.thread))
+ confirmDeep
)
)
} catch (err) {
@@ -704,10 +706,12 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored
const editMessage = useCallback(
async (edited: AppendMessage) => {
const messages = readMessages()
- const confirmDeep = () => confirm(deepReloadConfirmRequest(t.assistant.thread))
+ const confirmDeep = () => confirm(deepCutConfirmRequest(t.assistant.thread))
const plan = await planConfirmedEdit(messages, edited, confirmDeep)
- if (!plan) {
+ // Edit interrupts a live turn on purpose; only output that landed during the confirm makes
+ // the plan's index and rollback snapshot stale.
+ if (!plan || (plan.confirmDeepTruncate && readMessages() !== messages)) {
return
}
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 a09dec2062b..26cb8665ee8 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
@@ -61,7 +61,7 @@ import {
applyBranchVisibility,
applyReloadOptimistic,
applyRewindOptimistic,
- deepReloadConfirmRequest,
+ deepCutConfirmRequest,
durableRowIdsForRebind,
finalizeStoppedMessages,
planConfirmedEdit,
@@ -250,6 +250,11 @@ interface RestoreMessageTarget {
userOrdinal?: number | null
}
+const currentMessages = (sessionId: string) => $sessionStates.get()[sessionId]?.messages ?? $messages.get()
+
+const isStaleAfterConfirm = (sessionId: string, planned: ChatMessage[]) =>
+ Boolean($sessionStates.get()[sessionId]?.busy) || currentMessages(sessionId) !== planned
+
const isStaleTargetError = (err: unknown) =>
/no longer in session history|not in session history/i.test(err instanceof Error ? err.message : String(err))
@@ -1010,12 +1015,12 @@ export function usePromptActions({
// Active sessions publish their transcript into $sessionStates[runtimeId];
// 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)
- const plan = await planConfirmedReload(messages, parentId, () =>
- confirm(deepReloadConfirmRequest(t.assistant.thread))
- )
-
- if (!plan) {
+ // 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.
+ if (!plan || isStaleAfterConfirm(sessionId, messages)) {
return
}
@@ -1037,7 +1042,7 @@ export function usePromptActions({
confirmed
),
plan.confirmDeepTruncate,
- () => confirm(deepReloadConfirmRequest(t.assistant.thread))
+ confirmDeep
)
applySurvivorRowIds(sessionId, survivorRowIds)
@@ -1204,10 +1209,12 @@ export function usePromptActions({
// Same dual-store read as reloadFromMessage (#68734).
const messages = (sessionId ? $sessionStates.get()[sessionId]?.messages : null) ?? $messages.get()
- const confirmDeep = () => confirm(deepReloadConfirmRequest(t.assistant.thread))
+ const confirmDeep = () => confirm(deepCutConfirmRequest(t.assistant.thread))
const plan = sessionId ? await planConfirmedEdit(messages, edited, confirmDeep) : null
- if (!sessionId || !plan) {
+ // Edit interrupts a live turn on purpose; only output that landed during the confirm makes
+ // the plan's index and rollback snapshot stale.
+ if (!sessionId || !plan || (plan.confirmDeepTruncate && currentMessages(sessionId) !== messages)) {
return
}
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 478ecc2d7e6..3f05e607504 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
@@ -544,8 +544,8 @@ export function planReload(messages: ChatMessage[], parentId: null | string): nu
}
}
-/** Regenerate reuses the restore checkpoint confirm copy for a deep cut. */
-export const deepReloadConfirmRequest = (copy: {
+/** A deep cut (regenerate or edit of an older turn) reuses the restore checkpoint confirm copy. */
+export const deepCutConfirmRequest = (copy: {
restoreBody: string
restoreConfirm: string
restoreTitle: string
@@ -570,12 +570,21 @@ export async function planConfirmedReload(
): Promise<null | ReloadPlan> {
const plan = planReload(messages, parentId)
- if (
- !plan ||
- plan.truncateOrdinal === undefined ||
- !messages.some((m, i) => i > plan.userIndex && isVisibleUserMessage(m))
- ) {
- return plan
+ return plan && confirmIfDeepCut(messages, plan, plan.userIndex, confirmDeep)
+}
+
+/**
+ * A cut at *anchorIndex* that keeps a later user turn archives it: ask first and mark the plan
+ * confirmed, or null when declined. A plan with no truncation address (failed turn) cuts nothing.
+ */
+async function confirmIfDeepCut<P extends { truncateOrdinal: number | undefined }>(
+ messages: ChatMessage[],
+ plan: P,
+ anchorIndex: number,
+ confirmDeep: () => Promise<boolean>
+): Promise<null | (P & { confirmDeepTruncate: boolean })> {
+ if (plan.truncateOrdinal === undefined || !messages.some((m, i) => i > anchorIndex && isVisibleUserMessage(m))) {
+ return { ...plan, confirmDeepTruncate: false }
}
return (await confirmDeep()) ? { ...plan, confirmDeepTruncate: true } : null
@@ -751,15 +760,7 @@ export async function planConfirmedEdit(
): Promise<null | (EditPlan & { confirmDeepTruncate: boolean })> {
const plan = planEdit(messages, edited)
- if (!plan) {
- return null
- }
-
- if (plan.truncateOrdinal === undefined || !messages.some((m, i) => i > plan.sourceIndex && isVisibleUserMessage(m))) {
- return { ...plan, confirmDeepTruncate: false }
- }
-
- return (await confirmDeep()) ? { ...plan, confirmDeepTruncate: true } : null
+ return plan && confirmIfDeepCut(messages, plan, plan.sourceIndex, confirmDeep)
}
/** Optimistic rewind-to state for restore/edit: drop everything after the
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.ts
index 8519ee7723a..377e39575dd 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
@@ -280,8 +280,10 @@ export const SESSION_BUSY_RETRY_TIMEOUT_MS = 6_000
export const SESSION_BUSY_RETRY_INTERVAL_MS = 150
/** prompt.submit refused an unconfirmed truncation that would archive later user turns (#133716). */
+export const GATEWAY_DEEP_TRUNCATE_REFUSED_CODE = 4033
+
export function isDeepTruncateRefusal(error: unknown): boolean {
- return error instanceof JsonRpcGatewayError && error.code === 4033
+ return error instanceof JsonRpcGatewayError && error.code === GATEWAY_DEEP_TRUNCATE_REFUSED_CODE
}
export function isSessionBusyError(error: unknown): boolean {