Skip to content

The agent that grows with you

fix(desktop): a repeated /undo or /retry resolves its lost rewind before deriving

Teknium6d71467ba141
diff --git a/apps/desktop/src/api/canonical-protocol.ts b/apps/desktop/src/api/canonical-protocol.ts
index 998785e5c74..39222b938af 100644
--- a/apps/desktop/src/api/canonical-protocol.ts
+++ b/apps/desktop/src/api/canonical-protocol.ts
@@ -327,6 +327,33 @@ export class CanonicalDesktopProtocol {
return method !== 'session.create' && params.profile !== undefined ? { ...prepared, profile: params.profile } : prepared
}
+ private fencedMutation(method: string, params: Record<string, unknown>, fenced: { operation: string; payload: Record<string, unknown> }): Record<string, unknown> {
+ // An edit / regenerate / restore names its target explicitly; a typed /undo or /retry derives it.
+ const derived = method === 'session.rewind' && params.derived_target === true
+
+ // A replay-only probe only ever re-presents the retained rewind (localAnswer handles the rest).
+ if (derived && params.replay_only === true && !this.retainsDerivedRewind(params.session_id, params.profile)) {
+ throw new Error('No retained rewind to replay')
+ }
+
+ return this.retainedMutation(params.session_id, params.profile, fenced.operation, fenced.payload, true, derived)
+ }
+
+ // A typed /undo or /retry whose reply was lost is still retained for its exact retry.
+ private retainsDerivedRewind(sessionId: unknown, profile: unknown): boolean {
+ return this.mutations.has(JSON.stringify([canonicalSessionKey(sessionId, profile), 'rewind', null]))
+ }
+
+ // A request this protocol answers without the owner, or undefined. A replay-only /undo or /retry
+ // probe with no retained rewind owes nothing: no request is sent, and the command derives its target.
+ localAnswer(method: string, params: Record<string, unknown>): Record<string, unknown> | undefined {
+ if (method === 'session.rewind' && params.replay_only === true && !this.retainsDerivedRewind(params.session_id, params.profile)) {
+ return { session_id: params.session_id, status: 'nothing', rewound_count: 0 }
+ }
+
+ return undefined
+ }
+
// Drop the retained request the owner answered: its outcome is known, so no retry may resend it.
private forgetMutation(params: Record<string, unknown>) {
for (const [key, mutation] of this.mutations) { if (mutation.request_id === params.request_id) { this.mutations.delete(key) } }
@@ -392,12 +419,7 @@ 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) {
- // 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 (fenced) { return this.fencedMutation(method, params, fenced) }
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.ts
index 51665e506f1..770d469fa1c 100644
--- a/apps/desktop/src/api/canonical-rewind-lost-reply.test.ts
+++ b/apps/desktop/src/api/canonical-rewind-lost-reply.test.ts
@@ -30,7 +30,12 @@ test('a derived rewind whose reply was lost is re-sent for the repeat, not re-de
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 } })
+ 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))
@@ -84,3 +89,17 @@ test('an owner refusal that names a reason lets the next /undo derive again', ()
expect(next.request_id).not.toBe(refused.request_id)
expect(next).toMatchObject({ payload: { target_message_id: 3 }, expected_revision: 7 })
})
+
+test('a replay-only probe re-presents only a retained derived rewind', () => {
+ const protocol = primed()
+ const probe = { session_id: 's', derived_target: true, replay_only: true }
+
+ expect(protocol.localAnswer('session.rewind', probe)).toMatchObject({ status: 'nothing', rewound_count: 0 })
+ expect(() => protocol.prepare('session.rewind', probe)).toThrow('No retained rewind')
+
+ const lost = protocol.prepare('session.rewind', derived(5))
+ protocol.failure(lost, new Error('socket closed'))
+
+ expect(protocol.localAnswer('session.rewind', probe)).toBeUndefined()
+ expect(protocol.prepare('session.rewind', probe)).toEqual(lost)
+})
diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.ts
index 2b7390caf0c..e170bee7435 100644
--- a/apps/desktop/src/api/client.ts
+++ b/apps/desktop/src/api/client.ts
@@ -408,6 +408,10 @@ export class HermesGateway extends JsonRpcGatewayClient {
params = this.routeCanonicalParams(method, params)
+ const local = this.protocol.localAnswer(method, params)
+
+ if (local) { return local as T }
+
await this.attachForRequest(method, params, deadline, signal)
this.requireConnectionGeneration(generation)
// The attach may have identified the named launch profile behind an
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.tsx
index 99d30ac9ddf..895c27f0f34 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
@@ -13,6 +13,7 @@ import { dropSessionState, publishSessionState } from '@/store/session-states'
import { actRender, Harness, type HarnessHandle, RUNTIME_SESSION_ID } from './index-test-utils'
import { clearSingleFlightSessionResumeState } from './single-flight-resume'
+import { truncateRewoundMessages } from './slash-session-commands'
// /undo, /retry, /steer and /queue run against the session owner's canonical verbs (the Ink TUI's
// behaviour on the same gateway), never as `slash.exec`, which the shared gateway refuses.
@@ -47,8 +48,15 @@ const SNAPSHOT = {
type Responder = (method: string, params?: Record<string, unknown>) => unknown
+// A canonical client answers the replay-only rewind probe locally while nothing is retained
+// (CanonicalDesktopProtocol.localAnswer); these single-shot peers retain nothing.
function gateway(respond: Responder) {
- return vi.fn(async (method: string, params?: Record<string, unknown>) => (respond(method, params) ?? {}) as never)
+ return vi.fn(
+ async (method: string, params?: Record<string, unknown>) =>
+ (method === 'session.rewind' && params?.replay_only
+ ? { status: 'nothing', rewound_count: 0 }
+ : (respond(method, params) ?? {})) as never
+ )
}
async function mount(requestGateway: ReturnType<typeof gateway>) {
@@ -60,8 +68,12 @@ async function mount(requestGateway: ReturnType<typeof gateway>) {
return handle!
}
+// The replay-only probe each /undo and /retry sends first (answered locally while nothing is
+// retained) is asserted on its own; these lists hold the requests that name a target.
const callsOf = (requestGateway: ReturnType<typeof gateway>, method: string) =>
- requestGateway.mock.calls.filter(([name]) => name === method).map(([, params]) => params)
+ requestGateway.mock.calls
+ .filter(([name, params]) => name === method && !(params as { replay_only?: unknown } | undefined)?.replay_only)
+ .map(([, params]) => params)
const renderedText = (handle: HarnessHandle) =>
handle
@@ -124,9 +136,12 @@ describe('/undo on a canonical session', () => {
const handle = await mount(requestGateway)
await handle.submitText('/undo')
- expect(callsOf(requestGateway, 'session.rewind')).toEqual([
- { session_id: RUNTIME_SESSION_ID, target_message_id: 14, derived_target: true }
- ])
+ expect(requestGateway.mock.calls.filter(([name]) => name === 'session.rewind').map(([, params]) => params)).toEqual(
+ [
+ { session_id: RUNTIME_SESSION_ID, derived_target: true, replay_only: true },
+ { session_id: RUNTIME_SESSION_ID, target_message_id: 14, derived_target: true }
+ ]
+ )
expect(callsOf(requestGateway, 'slash.exec')).toEqual([])
expect($composerDraft.get()).toBe('second question')
expect(renderedText(handle)).toContain(copy.undidOther('2'))
@@ -207,17 +222,18 @@ 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 THREE_EXCHANGES: { content: unknown; role: string }[] = [
+ { role: 'user', content: 'first question' },
+ { role: 'assistant', content: 'first answer' },
+ { role: 'user', content: 'second question' },
+ { role: 'assistant', content: 'second answer' },
+ { role: 'user', content: 'third question' },
+ { role: 'assistant', content: 'third answer' }
+]
+
+function lostRewindReply(transcript = THREE_EXCHANGES) {
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 rows = transcript.map((row, index) => ({ ...row, row_id: 11 + index, active: true }))
const receipts = new Map<unknown, Record<string, unknown>>()
let revision = 4
@@ -268,6 +284,12 @@ function lostRewindReply() {
return {} as never
}
+ const local = protocol.localAnswer(method, params)
+
+ if (local) {
+ return local as never
+ }
+
const prepared = protocol.prepare(method, params)
try {
@@ -282,6 +304,30 @@ function lostRewindReply() {
return { requestGateway, active: () => rows.filter(row => row.active).map(row => row.content) }
}
+/** Rendered bubbles bound to the owner's durable rows (a hydrated or refreshed transcript). */
+const boundMessages = (texts: string[]) =>
+ texts.map((text, index) => ({
+ id: `m${index}`,
+ parts: [textPart(text)],
+ role: index % 2 ? ('assistant' as const) : ('user' as const),
+ rowId: 11 + index,
+ timestamp: index
+ }))
+
+async function mountWith(requestGateway: ReturnType<typeof gateway>, seedMessages: unknown[]) {
+ let handle: HarnessHandle | null = null
+ await actRender(
+ <Harness
+ onReady={h => (handle = h)}
+ refreshSessions={async () => undefined}
+ requestGateway={requestGateway}
+ seedMessages={seedMessages}
+ />
+ )
+
+ return handle!
+}
+
describe('a repeat after a lost rewind reply on a canonical session', () => {
beforeEach(canonical)
@@ -289,15 +335,20 @@ describe('a repeat after a lost rewind reply on a canonical session', () => {
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
- })
- )
+ 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
@@ -333,6 +384,90 @@ describe('a repeat after a lost rewind reply on a canonical session', () => {
expect.objectContaining({ session_id: RUNTIME_SESSION_ID, text: 'third question' })
])
})
+
+ // The repeat re-presents the retained rewind before deriving (or checking) a target of its own:
+ // the rewound transcript may hold no turn the command would accept.
+ it('/retry that removed the only user turn resends it', async () => {
+ const owner = lostRewindReply(THREE_EXCHANGES.slice(0, 2))
+ const handle = await mount(owner.requestGateway)
+
+ await handle.submitText('/retry')
+ await handle.submitText('/retry')
+
+ expect(renderedText(handle)).not.toContain(copy.retryNothing)
+ expect(callsOf(owner.requestGateway, 'prompt.submit')).toEqual([
+ expect.objectContaining({ session_id: RUNTIME_SESSION_ID, text: 'first question' })
+ ])
+ })
+
+ it('/undo N restores the removed question when fewer than N turns remain', async () => {
+ const owner = lostRewindReply()
+ const handle = await mount(owner.requestGateway)
+
+ await handle.submitText('/undo 2')
+ await handle.submitText('/undo 2')
+
+ expect(owner.active()).toEqual(['first question', 'first answer'])
+ expect($composerDraft.get()).toBe('second question')
+ expect(renderedText(handle)).toContain(copy.undidOther('4'))
+ })
+
+ it('a text-only /retry is not blocked by an older media turn', async () => {
+ const media = [{ type: 'image_url', image_url: 'x' }]
+ const owner = lostRewindReply([{ role: 'user', content: media }, ...THREE_EXCHANGES.slice(1, 4)])
+ const handle = await mount(owner.requestGateway)
+
+ await handle.submitText('/retry')
+ await handle.submitText('/retry')
+
+ expect(renderedText(handle)).not.toContain(copy.retryUnsupported)
+ expect(callsOf(owner.requestGateway, 'prompt.submit')).toEqual([
+ expect.objectContaining({ session_id: RUNTIME_SESSION_ID, text: 'second question' })
+ ])
+ })
+
+ it('a view refreshed after the reconnect keeps every exchange the owner still holds', async () => {
+ const owner = lostRewindReply()
+
+ // The reconnect refresh already shows the owner's rewound transcript (the third exchange gone).
+ const handle = await mountWith(
+ owner.requestGateway,
+ boundMessages(['first question', 'first answer', 'second question', 'second answer'])
+ )
+
+ await handle.submitText('/undo')
+ await handle.submitText('/undo')
+
+ expect(owner.active()).toEqual(['first question', 'first answer', 'second question', 'second answer'])
+ expect(renderedText(handle)).toContain('second question')
+ expect(renderedText(handle)).toContain('second answer')
+ })
+})
+
+describe('truncateRewoundMessages', () => {
+ const live = (text: string, role: 'assistant' | 'user') => ({ id: text, parts: [textPart(text)], role, timestamp: 9 })
+
+ it('is a no-op when the bound view no longer holds the rewound row', () => {
+ const messages = boundMessages(['first question', 'first answer', 'second question', 'second answer'])
+
+ expect(truncateRewoundMessages(messages as never, 15, 1)).toEqual(messages)
+ })
+
+ it('cuts unbound live bubbles after the bound history by position', () => {
+ const messages = [
+ ...boundMessages(['first question', 'first answer']),
+ live('new question', 'user'),
+ live('new answer', 'assistant')
+ ]
+
+ expect(truncateRewoundMessages(messages as never, 13, 1).map(message => message.id)).toEqual(['m0', 'm1'])
+ })
+
+ it('falls back by position on a wholly unbound view', () => {
+ const messages = [live('a', 'user'), live('b', 'assistant'), live('c', 'user'), live('d', 'assistant')]
+
+ expect(truncateRewoundMessages(messages as never, 13, 1).map(message => message.id)).toEqual(['a', 'b'])
+ })
})
describe('/steer', () => {
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.ts
index b7d6bdfeb38..5811f9fd098 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
@@ -30,6 +30,8 @@ interface SnapshotRow {
}
interface RewindReceipt {
+ /** Client-side: the snapshot row a freshly derived rewind named (a replayed receipt has none). */
+ derivedRowId?: number
rewound_count?: number
status?: string
target_message?: { content?: unknown; id?: unknown } | null
@@ -110,14 +112,25 @@ export function userTurnFromEnd(rows: readonly SnapshotRow[], turnsBack: number)
}
/** Drop the rewound rows from the rendered transcript: everything from the first message bound to a
- * durable row at or after the target. Unbound bubbles fall back to the Nth newest user bubble. */
+ * durable row at or after the target. A view bound to durable rows that holds none of them already
+ * shows the cut (a refresh after reconnect): only unbound live bubbles after it fall back to the Nth
+ * newest user bubble, and a wholly unbound view falls back by position. */
export function truncateRewoundMessages(messages: ChatMessage[], rowId: number, turnsBack: number): ChatMessage[] {
+ const bound = (message: ChatMessage) =>
+ message.rowId !== undefined || message.parts.some(part => part.sourceRowId !== undefined)
+
let cut = messages.findIndex(
message => (message.rowId ?? -1) >= rowId || message.parts.some(part => (part.sourceRowId ?? -1) >= rowId)
)
if (cut < 0) {
- const users = messages.flatMap((message, index) => (message.role === 'user' && !message.hidden ? [index] : []))
+ const tail = messages.length - [...messages].reverse().findIndex(bound)
+ const after = tail > messages.length ? 0 : tail
+
+ const users = messages.flatMap((message, index) =>
+ index >= after && message.role === 'user' && !message.hidden ? [index] : []
+ )
+
cut = users[users.length - turnsBack] ?? -1
}
@@ -136,6 +149,53 @@ export function sessionCommandHandlers<C extends { arg: string }>(env: SessionCo
): Promise<undefined | { count: number; content: unknown }> {
const { render, sessionId, storedSessionId } = out
const nothing = intent === 'retry' ? copy().retryNothing : copy().undoNothing
+
+ // An earlier /undo or /retry whose reply was lost is resolved FIRST: the owner already rewound, so
+ // the transcript a new target would come from may hold no turn this command accepts. The protocol
+ // re-sends that retained rewind (the owner answers with the original receipt), or answers
+ // 'nothing' locally, without a request, when none is retained.
+ const replayed = await requestGateway<RewindReceipt>('session.rewind', {
+ session_id: sessionId,
+ derived_target: true,
+ replay_only: true
+ })
+
+ const receipt = Number(replayed?.rewound_count ?? 0) > 0 ? replayed : await deriveAndRewind(out, turnsBack, intent)
+
+ if (!receipt) {
+ return
+ }
+
+ const count = Number(receipt?.rewound_count ?? 0)
+
+ if (receipt?.status === 'nothing' || count <= 0) {
+ return 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) : receipt.derivedRowId
+
+ if (rowId !== undefined) {
+ updateSessionState(
+ sessionId,
+ state => ({ ...state, messages: truncateRewoundMessages(state.messages, rowId, turnsBack) }),
+ storedSessionId
+ )
+ }
+
+ return { count, content: receipt?.target_message?.content }
+ }
+
+ // Derive the Nth newest user turn from the owner's snapshot and rewind it. Resolves undefined after
+ // it rendered why nothing was rewound.
+ async function deriveAndRewind(
+ out: SlashOutput,
+ turnsBack: number,
+ intent: 'retry' | 'undo'
+ ): Promise<RewindReceipt | undefined> {
+ const { render, sessionId } = out
+ const nothing = intent === 'retry' ? copy().retryNothing : copy().undoNothing
// The resume snapshot carries every row's durable id and primes the CAS revision/generation the
// rewind mutation presents, as Ink's mutateCanonical does.
const snapshot = await requestGateway<{ messages?: SnapshotRow[] }>('session.resume', { session_id: sessionId })
@@ -157,31 +217,14 @@ export function sessionCommandHandlers<C extends { arg: string }>(env: SessionCo
}
}
- // 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.
+ // A derived target: retained by operation alone, so a repeat after a lost reply re-sends it.
const receipt = await requestGateway<RewindReceipt>('session.rewind', {
session_id: sessionId,
target_message_id: target.row_id,
derived_target: true
})
- const count = Number(receipt?.rewound_count ?? 0)
-
- if (receipt?.status === 'nothing' || count <= 0) {
- return 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) }),
- storedSessionId
- )
-
- return { count, content: receipt?.target_message?.content }
+ return { ...receipt, derivedRowId: target.row_id as number }
}
// The next-turn queue the composer uses while busy: the owner's durable FIFO for a canonical