The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): a repeated /undo or /retry after a lost reply replays the same rewind
rodricksz4h587bd2c47dc7e
diff --git a/apps/desktop/src/api/canonical-protocol.ts b/apps/desktop/src/api/canonical-protocol.tsindex 1080c8db139..af4c99cc182 100644--- a/apps/desktop/src/api/canonical-protocol.ts+++ b/apps/desktop/src/api/canonical-protocol.ts@@ -289,9 +289,13 @@ export class CanonicalDesktopProtocol {return POLICY_EDIT_METHODS.has(method) && typeof prepared.operation === 'string' ? 'session.mutate' : method}- private retainedMutation(sessionId: unknown, profile: unknown, operation: string, payload: Record<string, unknown>, withGeneration: boolean): Record<string, unknown> {+ // `derived`: the payload was derived from a snapshot (a typed /undo or /retry names the Nth newest user+ // turn). Keyed by operation alone, as Ink's mutateCanonical and the classic PreparedMutations do: a+ // retry after a lost reply re-presents the original target, never one re-derived from a transcript the+ // first attempt already rewound.+ private retainedMutation(sessionId: unknown, profile: unknown, operation: string, payload: Record<string, unknown>, withGeneration: boolean, derived = false): Record<string, unknown> {const owner = canonicalSessionKey(sessionId, profile)- const key = JSON.stringify([owner, operation, payload])+ const key = JSON.stringify([owner, operation, derived ? null : payload])this.retireMutations(owner, key)const retained = this.mutations.get(key)@@ -379,7 +383,12 @@ export class CanonicalDesktopProtocol {'session.rewind': () => ({ operation: 'rewind', payload: { target_message_id: params.target_message_id } })} as Record<string, () => { operation: string; payload: Record<string, unknown> }>)[method]?.()- if (fenced) { return this.retainedMutation(params.session_id, params.profile, fenced.operation, fenced.payload, true) }+ if (fenced) {+ // An edit / regenerate / restore names its target explicitly; a typed /undo or /retry derives it.+ const derived = method === 'session.rewind' && params.derived_target === true++ return this.retainedMutation(params.session_id, params.profile, fenced.operation, fenced.payload, true, derived)+ }if (method === 'session.model') {const payload = { ...(params.payload as Record<string, unknown>), ...(typeof params.confirm === 'string' ? { confirm: params.confirm } : {}) }diff --git a/apps/desktop/src/api/canonical-rewind-lost-reply.test.ts b/apps/desktop/src/api/canonical-rewind-lost-reply.test.tsnew file mode 100644index 00000000000..592b0051dd8--- /dev/null+++ b/apps/desktop/src/api/canonical-rewind-lost-reply.test.ts@@ -0,0 +1,75 @@+import { expect, test } from 'vitest'++import { CanonicalDesktopProtocol } from './canonical-protocol'++// A typed /undo or /retry derives its target from a fresh snapshot. After a lost reply the owner has+// already rewound, so the repeat's snapshot names the turn before: the retained rewind, not a new one at+// that target, must be what the repeat sends (as Ink's mutateCanonical and the classic CLI do).+function primed() {+ const protocol = new CanonicalDesktopProtocol()+ protocol.result('session.resume', { session_id: 's' }, { session_id: 's', revision: 7, execution_generation: 3 })++ return protocol+}++const derived = (target: number) => ({ session_id: 's', target_message_id: target, derived_target: true })++test('a derived rewind whose reply was lost is re-sent for the repeat, not re-derived', () => {+ const protocol = primed()+ const lost = protocol.prepare('session.rewind', derived(5))+ protocol.failure(lost, new Error('Hermes gateway connection lost'))++ // The repeat's snapshot already lacks row 5 and names row 3; the original request goes out again.+ protocol.result('session.resume', { session_id: 's' }, { session_id: 's', revision: 8, execution_generation: 4 })+ const repeat = protocol.prepare('session.rewind', derived(3))++ expect(repeat).toEqual(lost)+ expect(repeat).toMatchObject({ payload: { target_message_id: 5 }, expected_revision: 7, expected_generation: 3 })+})++test('an answered derived rewind is not replayed for the next /undo', () => {+ const protocol = primed()+ const first = protocol.prepare('session.rewind', derived(5))+ protocol.result('session.rewind', first, { session_id: 's', revision: 8, rewound_count: 2, target_message: { id: 5 } })++ const next = protocol.prepare('session.rewind', derived(3))++ expect(next.request_id).not.toBe(first.request_id)+ expect(next).toMatchObject({ payload: { target_message_id: 3 }, expected_revision: 8 })+})++test('a typed refusal of a derived rewind lets the repeat derive again', () => {+ const protocol = primed()+ const refused = protocol.prepare('session.rewind', derived(5))+ protocol.failure(refused, { data: { reason: 'revision_conflict', revision: 9 } })++ const retry = protocol.prepare('session.rewind', derived(5))++ expect(retry.request_id).not.toBe(refused.request_id)+ expect(retry).toMatchObject({ payload: { target_message_id: 5 }, expected_revision: 9 })+})++test('another control retires a lost derived rewind', () => {+ const protocol = primed()+ const lost = protocol.prepare('session.rewind', derived(5))+ protocol.failure(lost, new Error('socket closed'))++ protocol.prepare('session.title', { session_id: 's', title: 'renamed' })+ const later = protocol.prepare('session.rewind', derived(3))++ expect(later.request_id).not.toBe(lost.request_id)+ expect(later).toMatchObject({ payload: { target_message_id: 3 } })+})++test('an explicit rewind (edit, regenerate, restore) stays keyed by its own target', () => {+ const protocol = primed()+ const lost = protocol.prepare('session.rewind', { session_id: 's', target_message_id: 5 })+ protocol.failure(lost, new Error('socket closed'))++ expect(protocol.prepare('session.rewind', { session_id: 's', target_message_id: 5 })).toEqual(lost)++ const other = protocol.prepare('session.rewind', { session_id: 's', target_message_id: 3 })++ expect(other.request_id).not.toBe(lost.request_id)+ expect(other).toMatchObject({ payload: { target_message_id: 3 } })+})diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-session-commands.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-session-commands.test.tsxindex 5753d5ad3b1..abd73b83510 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-session-commands.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-session-commands.test.tsx@@ -1,7 +1,9 @@import { cleanup } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { CanonicalDesktopProtocol } from '@/api/canonical-protocol'import { en } from '@/i18n/en'+import { textPart } from '@/lib/chat-messages'import { createClientSessionState } from '@/lib/chat-runtime'import { resolveDesktopCommand } from '@/lib/desktop-slash-commands'import { $composerDraft, setComposerDraft } from '@/store/composer'@@ -123,7 +125,7 @@ describe('/undo on a canonical session', () => {await handle.submitText('/undo')expect(callsOf(requestGateway, 'session.rewind')).toEqual([- { session_id: RUNTIME_SESSION_ID, target_message_id: 14 }+ { session_id: RUNTIME_SESSION_ID, target_message_id: 14, derived_target: true }])expect(callsOf(requestGateway, 'slash.exec')).toEqual([])expect($composerDraft.get()).toBe('second question')@@ -145,7 +147,7 @@ describe('/undo on a canonical session', () => {await handle.submitText('/undo 2')expect(callsOf(requestGateway, 'session.rewind')).toEqual([- { session_id: RUNTIME_SESSION_ID, target_message_id: 11 }+ { session_id: RUNTIME_SESSION_ID, target_message_id: 11, derived_target: true }])})@@ -178,7 +180,7 @@ describe('/retry on a canonical session', () => {await handle.submitText('/retry')expect(callsOf(requestGateway, 'session.rewind')).toEqual([- { session_id: RUNTIME_SESSION_ID, target_message_id: 14 }+ { session_id: RUNTIME_SESSION_ID, target_message_id: 14, derived_target: true }])expect(callsOf(requestGateway, 'prompt.submit')).toEqual([expect.objectContaining({ session_id: RUNTIME_SESSION_ID, text: 'second question' })@@ -202,6 +204,136 @@ describe('/retry on a canonical session', () => {})})+// The real CanonicalDesktopProtocol in front of a revision-fenced owner that answers an exact retry with+// its original receipt (the authority's durable receipt by request_id). The first rewind commits and its+// reply is lost; the user repeats the command.+function lostRewindReply() {+ const protocol = new CanonicalDesktopProtocol()+ const rows = [+ { role: 'user', content: 'first question', row_id: 11, active: true },+ { role: 'assistant', content: 'first answer', row_id: 12, active: true },+ { role: 'user', content: 'second question', row_id: 13, active: true },+ { role: 'assistant', content: 'second answer', row_id: 14, active: true },+ { role: 'user', content: 'third question', row_id: 15, active: true },+ { role: 'assistant', content: 'third answer', row_id: 16, active: true }+ ]++ const receipts = new Map<unknown, Record<string, unknown>>()+ let revision = 4+ let loseReply = true++ const owner = (wire: string, params: Record<string, unknown>) => {+ if (wire === 'session.resume') {+ const messages = rows.filter(row => row.active).map(({ active: _active, ...row }) => row)++ return { session_id: RUNTIME_SESSION_ID, revision, execution_generation: 2, messages }+ }++ const replay = receipts.get(params.request_id)++ if (replay) {+ return replay+ }++ if (params.expected_revision !== revision) {+ throw Object.assign(new Error('revision_conflict'), { data: { reason: 'revision_conflict', revision } })+ }++ const target = (params.payload as { target_message_id: number }).target_message_id+ const rewound = rows.filter(row => row.active && row.row_id >= target)+ rewound.forEach(row => (row.active = false))+ revision += 1++ const receipt = {+ session_id: RUNTIME_SESSION_ID,+ revision,+ rewound_count: rewound.length,+ target_message: { id: target, content: rewound[0].content }+ }++ receipts.set(params.request_id, receipt)++ if (loseReply) {+ loseReply = false++ throw new Error('Hermes gateway connection lost')+ }++ return receipt+ }++ const requestGateway = vi.fn(async (method: string, params: Record<string, unknown> = {}) => {+ if (method !== 'session.resume' && method !== 'session.rewind') {+ return {} as never+ }++ const prepared = protocol.prepare(method, params)++ try {+ return protocol.result(method, prepared, owner(protocol.wire(method, prepared), prepared)) as never+ } catch (error) {+ protocol.failure(prepared, error)++ throw error+ }+ })++ return { requestGateway, active: () => rows.filter(row => row.active).map(row => row.content) }+}++describe('a repeat after a lost rewind reply on a canonical session', () => {+ beforeEach(canonical)++ it('/undo removes only the newest exchange and restores its text', async () => {+ const owner = lostRewindReply()+ let handle: HarnessHandle | null = null++ const seedMessages = ['first question', 'first answer', 'second question', 'second answer', 'third question', 'third answer'].map(+ (text, index) => ({+ id: `m${index}`,+ parts: [textPart(text)],+ role: index % 2 ? ('assistant' as const) : ('user' as const),+ rowId: 11 + index,+ timestamp: index+ })+ )++ await actRender(+ <Harness+ onReady={h => (handle = h)}+ refreshSessions={async () => undefined}+ requestGateway={owner.requestGateway}+ seedMessages={seedMessages}+ />+ )++ await handle!.submitText('/undo')+ expect(renderedText(handle!)).toContain('Hermes gateway connection lost')++ await handle!.submitText('/undo')++ expect(owner.active()).toEqual(['first question', 'first answer', 'second question', 'second answer'])+ expect($composerDraft.get()).toBe('third question')+ expect(renderedText(handle!)).toContain(copy.undidOther('2'))+ // The view drops the rewound rows the owner named, not the turn this repeat's snapshot pointed at.+ expect(renderedText(handle!)).toContain('second answer')+ expect(renderedText(handle!)).not.toContain('third question')+ })++ it('/retry resends the newest question, not the one before it', async () => {+ const owner = lostRewindReply()+ const handle = await mount(owner.requestGateway)++ await handle.submitText('/retry')+ await handle.submitText('/retry')++ expect(owner.active()).toEqual(['first question', 'first answer', 'second question', 'second answer'])+ expect(callsOf(owner.requestGateway, 'prompt.submit')).toEqual([+ expect.objectContaining({ session_id: RUNTIME_SESSION_ID, text: 'third question' })+ ])+ })+})+describe('/steer', () => {it('steers the running turn through session.steer', async () => {publishSessionState(RUNTIME_SESSION_ID, { ...createClientSessionState(RUNTIME_SESSION_ID), busy: true })diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-session-commands.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-session-commands.tsindex bf6509372a1..b7d6bdfeb38 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-session-commands.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-session-commands.ts@@ -32,7 +32,7 @@ interface SnapshotRow {interface RewindReceipt {rewound_count?: numberstatus?: string- target_message?: { content?: unknown } | null+ target_message?: { content?: unknown; id?: unknown } | null}interface SlashOutput {@@ -157,11 +157,12 @@ export function sessionCommandHandlers<C extends { arg: string }>(env: SessionCo}}- const rowId = target.row_id as number-+ // A derived target: while an earlier rewind's reply is lost, the protocol re-sends that rewind+ // (its original target) instead of this one, so the owner answers with the original receipt.const receipt = await requestGateway<RewindReceipt>('session.rewind', {session_id: sessionId,- target_message_id: rowId+ target_message_id: target.row_id,+ derived_target: true})const count = Number(receipt?.rewound_count ?? 0)@@ -170,6 +171,10 @@ export function sessionCommandHandlers<C extends { arg: string }>(env: SessionCoreturn void render(nothing)}+ // The receipt names the row the owner rewound; a replayed receipt's row is not this snapshot's.+ const receiptRowId = receipt?.target_message?.id+ const rowId = Number.isSafeInteger(receiptRowId) ? (receiptRowId as number) : (target.row_id as number)+updateSessionState(sessionId,state => ({ ...state, messages: truncateRewoundMessages(state.messages, rowId, turnsBack) }),