The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): an older pending snapshot cannot retire a receipt a newer one listed
Teknium9d018d358efb
diff --git a/apps/desktop/src/api/canonical-protocol.ts b/apps/desktop/src/api/canonical-protocol.tsindex 5e18a3610df..dfa5eeae187 100644--- a/apps/desktop/src/api/canonical-protocol.ts+++ b/apps/desktop/src/api/canonical-protocol.ts@@ -410,7 +410,7 @@ export class CanonicalDesktopProtocol {return projected})- return { ...value, pending_approval: prompts.find((p: any) => p.kind === 'approval'), pending_clarify: prompts.find((p: any) => p.kind === 'clarify'), info: { ...value.info, stored_session_id: value.stored_session_id, pending_submissions: value.pending_submissions, execution_generation: value.execution_generation, running: value.running } }+ return { ...value, pending_approval: prompts.find((p: any) => p.kind === 'approval'), pending_clarify: prompts.find((p: any) => p.kind === 'clarify'), info: { ...value.info, stored_session_id: value.stored_session_id, pending_submissions: value.pending_submissions, replay_epoch: value.replay_epoch, last_sequence: value.last_sequence, execution_generation: value.execution_generation, running: value.running } }}// The canonical compress receipt carries counts, not the retained transcript;diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.tsindex 2b4ef52ca4b..74939870feb 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts@@ -5,7 +5,7 @@ import { reconcileApprovalModeForProfile } from '@/store/approval-mode'import { clearSettledClarifyRequest } from '@/store/clarify'import { reconcileSessionCompacting } from '@/store/compaction'import { requestDesktopOnboardingForCredentialWarning } from '@/store/onboarding'-import { reconcilePendingSubmissions } from '@/store/pending-submissions'+import { pendingSnapshotFence, reconcilePendingSubmissions } from '@/store/pending-submissions'import { followActiveSessionCwd } from '@/store/projects'import { clearAllPrompts } from '@/store/prompts'import {@@ -136,13 +136,15 @@ function maybeRebindPaneToRebuiltRuntime(ctx: GatewayEventContext): boolean {/** Project the runtime's pending-submission receipts onto the durable* session's composer queue (keyed by stored id when known). */function reconcileSessionInfoPendingSubmissions(ctx: GatewayEventContext): void {- const { deps, payload, sessionId } = ctx+ const { deps, event, payload, sessionId } = ctxif (sessionId) {const storedId =payload?.stored_session_id ?? deps.sessionStateByRuntimeIdRef.current.get(sessionId)?.storedSessionId ?? sessionId- reconcilePendingSubmissions(storedId, (payload as Record<string, unknown>)?.pending_submissions)+ // A canonical frame's own place in the session's event order fences absence-based retirement.+ reconcilePendingSubmissions(storedId, (payload as Record<string, unknown>)?.pending_submissions,+ pendingSnapshotFence(event.replay_epoch, event.seq))}}diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.tsindex d77a63bdb1a..c77ff0cfd89 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts@@ -17,7 +17,7 @@ import { isMessagingSource, normalizeSessionSource } from '@/lib/session-source'import { isLiveTailReplyId } from '@/lib/spoken-reply'import { reconcileApprovalModeForProfile } from '@/store/approval-mode'import { requestDesktopOnboardingForCredentialWarning } from '@/store/onboarding'-import { reconcilePendingSubmissions } from '@/store/pending-submissions'+import { pendingSnapshotFence, reconcilePendingSubmissions } from '@/store/pending-submissions'import { $activeGatewayProfile, $profiles, normalizeProfileKey } from '@/store/profile'import { $projectTree } from '@/store/projects'import {@@ -2428,7 +2428,8 @@ function publishRuntimeToComposer(state: SessionRuntimeStatePatch): void {/** Session-independent side effects of one runtime info snapshot. */function reportRuntimeInfoAppState(info: SessionRuntimeInfo): void {if (info.stored_session_id) {- reconcilePendingSubmissions(info.stored_session_id, info.pending_submissions)+ reconcilePendingSubmissions(info.stored_session_id, info.pending_submissions,+ pendingSnapshotFence(info.replay_epoch, info.last_sequence))}// App/profile-level reporting is session-independent — a tile's runtimediff --git a/apps/desktop/src/store/pending-submissions.test.ts b/apps/desktop/src/store/pending-submissions.test.tsindex 5b60e83fa84..ee9b7ccc284 100644--- a/apps/desktop/src/store/pending-submissions.test.ts+++ b/apps/desktop/src/store/pending-submissions.test.ts@@ -1,5 +1,8 @@-import { beforeEach, expect, it } from 'vitest'+import { beforeEach, expect, it, vi } from 'vitest'+import { CanonicalDesktopProtocol } from '@/api/canonical-protocol'+import { handleSessionInfoEvent } from '@/app/session/hooks/use-message-stream/gateway-event/session-info'+import type { GatewayEventContext } from '@/app/session/hooks/use-message-stream/gateway-event/types'import { applyRuntimeInfo } from '@/app/session/hooks/use-session-actions/utils'import { isSteerableEntry } from '@/store/composer-queue'@@ -93,3 +96,38 @@ it('never lets a stale queue snapshot repaint an admission already seen startedreconcilePendingSubmissions('mono', [{ admission_id: 'b', status: 'unknown', user: 'lost' }])expect(getQueuedPrompts('mono').map(entry => [entry.id, entry.serverStatus])).toEqual([['b', 'unknown']])})++it('a delayed older empty snapshot never retires a receipt a newer frame still lists; a current one does', () => {+ const protocol = new CanonicalDesktopProtocol()+ const queued = { admission_id: 'q', input_id: 'in-q', status: 'queued', text: 'still waiting', sequence: 1 }++ // The owner's resume answer, through the production snapshot projection.+ const snapshot = (lastSequence: number, pending: unknown[]) => applyRuntimeInfo(protocol.result('session.resume', { session_id: 'fenced' },+ { session_id: 'fenced', stored_session_id: 'fenced', revision: 1, execution_generation: 1, replay_epoch: 'e1', last_sequence: lastSequence, pending, info: {} }).info,+ { foreground: false })++ // The live pending fanout at seq 10, through the canonical normalizer and the session.info handler.+ const live = { type: 'session.info', session_id: 'fenced', seq: 10, replay_epoch: 'e1', profile: 'default',+ payload: { stored_session_id: 'fenced', pending: [queued], revision: 1 } as Record<string, unknown> }++ protocol.event(live)+ handleSessionInfoEvent({+ deps: { activeGatewayProfile: 'default', activeSessionIdRef: { current: null }, hydrateFromStoredSession: vi.fn(),+ lastCwdInfoSessionRef: { current: null }, queryClient: { invalidateQueries: vi.fn() }, refreshHermesConfig: vi.fn(),+ scheduleSessionsRefresh: vi.fn(), sessionInterrupted: () => false, sessionStateByRuntimeIdRef: { current: new Map() },+ updateSessionState: vi.fn(state => state), upsertToolCall: vi.fn() },+ event: live, explicitSid: 'fenced', fromActiveSource: () => true, isActiveEvent: false, occurredAt: Date.now() / 1000,+ payload: live.payload, scheduleConfigRefresh: vi.fn(), sessionId: 'fenced'+ } as unknown as GatewayEventContext)+ expect(getQueuedPrompts('fenced').map(entry => [entry.id, entry.serverStatus])).toEqual([['q', 'queued']])++ // A resume answer read at seq 7 arrives late and lists nothing: it predates the queued frame.+ snapshot(7, [])+ expect(readPendingSubmissions('fenced').q?.status).toBe('queued')+ expect(getQueuedPrompts('fenced').map(entry => [entry.id, entry.serverStatus])).toEqual([['q', 'queued']])++ // A current snapshot (seq 12) without it is the authority's word: the receipt retires.+ snapshot(12, [])+ expect(readPendingSubmissions('fenced').q?.status).toBe('retired')+ expect(getQueuedPrompts('fenced')).toEqual([])+})diff --git a/apps/desktop/src/store/pending-submissions.ts b/apps/desktop/src/store/pending-submissions.tsindex 9c361080879..81f74895ad0 100644--- a/apps/desktop/src/store/pending-submissions.ts+++ b/apps/desktop/src/store/pending-submissions.ts@@ -12,6 +12,16 @@ interface PendingSubmission {text: stringdisplayText?: stringstatus?: string+ /** Where in the session's event order the owner last listed this admission as pending. */+ seen?: PendingSnapshotFence+}++/** A canonical pending snapshot's place in its session's event order: the replay epoch and the+ * event sequence it reflects (a live `session.info` frame's own seq, or a resume snapshot's+ * `last_sequence`, both read under the owner's event-stream lock). */+export interface PendingSnapshotFence {+ epoch: string+ sequence: number}const entryKey = (session: string, id: string) => `${ENTRY_PREFIX}${JSON.stringify([session, id])}`@@ -108,10 +118,19 @@ function collectReceipts(value: RawReceipts, known: Record<string, PendingSubmisreturn { receipts, admissionByInput }}+// Only a snapshot at least as new as the one that last listed an admission proves it left the+// pending set. An OLDER snapshot of the same numbering (a delayed resume answer, a replayed frame)+// predates it; its absence there says nothing. A different epoch is a later numbering (owner+// restart, evicted ring): sequences cannot be compared, and the current owner is authoritative.+// An unfenced snapshot (legacy shape) keeps the previous absence rule.+const predates = (fence: PendingSnapshotFence | undefined, seen: PendingSnapshotFence | undefined) =>+ Boolean(fence && seen && fence.epoch === seen.epoch && fence.sequence < seen.sequence)+function projectQueue(current: QueuedPromptEntry[],receipts: Map<string, PendingSubmission>,- admissionByInput: Map<string, string>+ admissionByInput: Map<string, string>,+ stillPending: Set<string>): QueuedPromptEntry[] {const next: QueuedPromptEntry[] = []@@ -124,7 +143,7 @@ function projectQueue(}receipts.delete(receipt.id)- } else if (!entry.serverStatus) {+ } else if (!entry.serverStatus || stillPending.has(entry.id)) {next.push(entry)}}@@ -145,11 +164,12 @@ function projectQueue(return next}-function updateKnownReceipts(known: Record<string, PendingSubmission>, value: RawReceipts): void {+function updateKnownReceipts(known: Record<string, PendingSubmission>, value: RawReceipts, fence?: PendingSnapshotFence): void {// Only observed server records may be retired by their later absence. The retirement is kept// (text dropped) so a stale snapshot that still lists the admission cannot resurrect its card.for (const [id, entry] of Object.entries(known)) {- if (entry.status && entry.status !== 'retired' && !value.some(raw => raw?.admission_id === id)) {+ if (entry.status && entry.status !== 'retired' && !value.some(raw => raw?.admission_id === id) &&+ !predates(fence, entry.seen)) {known[id] = { id, text: '', status: 'retired' }}}@@ -162,17 +182,22 @@ function updateKnownReceipts(known: Record<string, PendingSubmission>, value: Rafor (const raw of value) {if (typeof raw?.admission_id === 'string' && !isStale(raw, known)) {+ const previous = known[raw.admission_id]+known[raw.admission_id] = {- ...known[raw.admission_id],+ ...previous,id: raw.admission_id,- text: raw.user ?? known[raw.admission_id]?.text ?? '',- status: raw.status+ text: raw.user ?? previous?.text ?? '',+ status: raw.status,+ ...(fence && !predates(fence, previous?.seen) ? { seen: fence } : {})}}}}-export function reconcilePendingSubmissions(key: string, value: unknown): void {+/** Project one pending snapshot onto the session's queue. `fence` orders canonical snapshots so a+ * delayed older one cannot retire an admission a newer one still listed. */+export function reconcilePendingSubmissions(key: string, value: unknown, fence?: PendingSnapshotFence): void {if (!Array.isArray(value)) {return}@@ -181,13 +206,24 @@ export function reconcilePendingSubmissions(key: string, value: unknown): void {const known = { ...before }const { receipts, admissionByInput } = collectReceipts(value, known)+ const stillPending = new Set(Object.values(known).filter(entry =>+ entry.status && entry.status !== 'retired' && predates(fence, entry.seen) &&+ !value.some(raw => raw?.admission_id === entry.id)).map(entry => entry.id))+const current = getQueuedPrompts(key)- const next = projectQueue(current, receipts, admissionByInput)+ const next = projectQueue(current, receipts, admissionByInput, stillPending)- updateKnownReceipts(known, value)+ updateKnownReceipts(known, value, fence)writeEntries(key, before, known)if (JSON.stringify(current) !== JSON.stringify(next)) {writeSessionQueue(key, next)}}++/** The fence of a canonical frame or snapshot, when it carries a usable one. */+export function pendingSnapshotFence(epoch: unknown, sequence: unknown): PendingSnapshotFence | undefined {+ return typeof epoch === 'string' && epoch && typeof sequence === 'number' && Number.isFinite(sequence)+ ? { epoch, sequence }+ : undefined+}diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.tsindex d95c079b04d..c8d49127f5b 100644--- a/apps/desktop/src/types/hermes.ts+++ b/apps/desktop/src/types/hermes.ts@@ -841,6 +841,9 @@ export interface SessionResumeResult {export interface SessionRuntimeInfo {stored_session_id?: stringpending_submissions?: unknown+ /** Canonical snapshot only: the session replay epoch and event sequence its pending set reflects. */+ replay_epoch?: string+ last_sequence?: numberapproval_mode?: 'manual' | 'off' | 'smart'branch?: stringconfig_warning?: string