The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): an interrupted send is never sent twice through the saved draft or a busy retry
Teknium43686d1da6c2
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.tsindex 9ca800b0bf5..c4a98411bb4 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts@@ -23,10 +23,11 @@ import {draftRetryTextMatches,matchingDraftRetry,readDraftRetry,+ retryAttachmentIds,writeDraftRetry} from '@/store/composer-draft-retry'import { isBrowsingHistory } from '@/store/composer-input-history'-import { restoreInterruptedSend } from '@/store/composer-outbox'+import { adoptInterruptedSend, type InterruptedSendHandlers, restoreInterruptedSend } from '@/store/composer-outbox'import { $composerPopout } from '@/store/composer-popout'import { migrateQueuedPrompts } from '@/store/composer-queue'@@ -694,32 +695,53 @@ export function useComposerDraft({savedDraftRef.current = savedDraft(text, attachments)loadIntoComposer(text, attachments, true)- if (!text.trim() && attachments.length === 0) {- // A send its page never finished (the window closed or reloaded mid-send) is this draft.- void restoreInterruptedSend(activeQueueSessionKey, retry => {+ // Takes back a draft that is still exactly `retry`'s send under its identity.+ const clearRestoredDraft = (retry: ComposerDraftRetry) => {+ if (+ draftScopeRef.current !== activeQueueSessionKey ||+ !draftRetryTextMatches(retry, syncDraftFromEditor()) ||+ readDraftRetry(activeQueueSessionKey)?.id !== retry.id+ ) {+ return+ }++ stashAt(activeQueueSessionKey, '', [])+ writeDraftRetry(activeQueueSessionKey, undefined)+ draftRetryRef.current = undefined+ loadIntoComposer('', [])+ }++ const interruptedSend: InterruptedSendHandlers = {+ offer: retry => {if (draftScopeRef.current !== activeQueueSessionKey || syncDraftFromEditor().trim()) {return false}+ // Re-offered as text: attachment bytes do not outlive the page, so the identity names exactly+ // what is offered and Enter on it is the explicit retry of that send.stashAt(activeQueueSessionKey, retry.text, [])- rememberDraftRetry(activeQueueSessionKey, retry)+ rememberDraftRetry(activeQueueSessionKey, { ...retry, attachmentIds: [] })loadIntoComposer(retry.text, [])return true- }, retry => {- // The owner listed it after all: take back the offered draft unless the user changed it.- if (- draftScopeRef.current !== activeQueueSessionKey ||- syncDraftFromEditor().trim() !== retry.text.trim() ||- readDraftRetry(activeQueueSessionKey)?.id !== retry.id- ) {- return- }+ },+ // The adopted saved draft is a copy of a send the owner already holds.+ landed: clearRestoredDraft,+ // The owner listed the offered send after all.+ withdraw: clearRestoredDraft+ }- stashAt(activeQueueSessionKey, '', [])- writeDraftRetry(activeQueueSessionKey, undefined)- loadIntoComposer('', [])- })+ // The saved draft can already be an interrupted send's words (persisted before the send cleared+ // the composer): it takes that send's identity before Enter could mint a second one.+ const adopted = adoptInterruptedSend(activeQueueSessionKey, text, interruptedSend)++ if (adopted && !draftRetryTextMatches(draftRetryRef.current, text)) {+ rememberDraftRetry(activeQueueSessionKey, { ...adopted, attachmentIds: retryAttachmentIds(attachments) })+ }++ if (!text.trim() && attachments.length === 0) {+ // A send its page never finished (the window closed or reloaded mid-send) is this draft.+ void restoreInterruptedSend(activeQueueSessionKey, interruptedSend)}return () => {diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.tsindex 3b5dcefc0c4..8834be58e2b 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts@@ -401,7 +401,9 @@ export function useComposerQueue({return true}- const queueCurrentDraft = useCallback(() => {+ // `submissionId` names the restored send this draft retries: the admission (or the local entry that+ // drains under its id) keeps it, so the owner never runs the interrupted original a second time.+ const queueCurrentDraft = useCallback((submissionId?: string) => {const text = draftRef.currentif (!activeQueueSessionKey || (!text.trim() && attachments.length === 0)) {@@ -440,7 +442,8 @@ export function useComposerQueue({...(frozen.displayText ? { displayText: frozen.displayText } : {}),fromQueue: true,sessionId: sessionId ?? null,- storedSessionId: activeQueueSessionKey+ storedSessionId: activeQueueSessionKey,+ ...(submissionId ? { submission_id: submissionId } : {})})).then(accepted => {@@ -460,6 +463,7 @@ export function useComposerQueue({if (!enqueueQueuedPrompt(activeQueueSessionKey, {+ ...(submissionId ? { id: submissionId } : {}),text: frozen.text,attachments,...(frozen.displayText ? { displayText: frozen.displayText } : {}),diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.send-then-close.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.send-then-close.test.tsxindex 2d086e6dafb..028e49a6063 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.send-then-close.test.tsx+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.send-then-close.test.tsx@@ -53,15 +53,23 @@ vi.mock('@assistant-ui/react', () => ({}))interface Handles {+ attach: (id: string) => voideditor: () => stringsubmitDraft: () => void}+interface PageOptions {+ /** A turn is running: Enter goes through the busy path (steer by default, or the queue). */+ busy?: boolean+ onSteer?: ChatBarProps['onSteer']+ queueCurrentDraft?: (submissionId?: string) => boolean+}+let handles: Handles// One app page: fresh imports of the composer hooks and stores (as a reload or relaunch gets).// Opening the session resumes it: the owner's snapshot lists its pending admissions (`pending`).-async function openPage(onSubmit: ChatBarProps['onSubmit'], pending: unknown[] = []) {+async function openPage(onSubmit: ChatBarProps['onSubmit'], pending: unknown[] = [], options: PageOptions = {}) {const { reconcilePendingSubmissions } = await import('@/store/pending-submissions')const { useComposerDraft } = await import('./use-composer-draft')const { useComposerSubmit } = await import('./use-composer-submit')@@ -84,16 +92,16 @@ async function openPage(onSubmit: ChatBarProps['onSubmit'], pending: unknown[] =...draft,activeQueueSessionKey: 'stored-B',attachments,- busy: false,+ busy: options.busy ?? false,disabled: false,inputDisabled: false,drainNextQueued: async () => false,exitQueuedEdit: () => false,onCancel: () => {},- onSteer: async () => false,+ onSteer: options.onSteer ?? (async () => false),onSteerHidden: async () => false,onSubmit,- queueCurrentDraft: () => false,+ queueCurrentDraft: options.queueCurrentDraft ?? (() => false),queueEdit: null,queuedPrompts: [],sessionId: 'rt-B'@@ -101,6 +109,7 @@ async function openPage(onSubmit: ChatBarProps['onSubmit'], pending: unknown[] =useLayoutEffect(() => {handles = {+ attach: id => mainComposerScope.add({ id, kind: 'url', label: id, refText: `@url:${id}` }),editor: () => composerPlainText(draft.editorRef.current!).trim(),submitDraft: submit.submitDraft}@@ -128,8 +137,26 @@ afterEach(() => {vi.resetModules()})+// Storage.key(i), not Object.keys: the test environment's localStorage enumerates no stored keys.const outboxKeys = () =>- Object.keys(window.localStorage).filter(key => key.startsWith('hermes:composer-outbox:'))+ Array.from({ length: window.localStorage.length }, (_, index) => window.localStorage.key(index) ?? '').filter(key =>+ key.startsWith('hermes:composer-outbox:')+ )++const saveDraft = (text: string) =>+ window.localStorage.setItem('hermes:composer-drafts:v3', JSON.stringify({ 'stored-B': text }))++// Enter on `text` (with a url attachment), then the window closes before prompt.submit: the id it sent.+async function sendThenClose(text: string): Promise<string | undefined> {+ saveDraft(text)+ const cutOff = vi.fn<ChatBarProps['onSubmit']>(() => new Promise<boolean>(() => {}))+ await openPage(cutOff)+ act(() => handles.attach('example.com/a'))+ act(() => handles.submitDraft())+ closeWindow()++ return cutOff.mock.calls[0][1]?.submission_id+}it('a message sent right before the window closes is never lost and never sent twice', async () => {window.localStorage.setItem('hermes:composer-drafts:v3', JSON.stringify({ 'stored-B': 'answered question' }))@@ -208,3 +235,49 @@ it('a send the owner admitted before the window closed is never offered again aswindow.localStorage.clear()}})++it('an interrupted send with attachments comes back once, under its id, even when the saved draft kept its words', async () => {+ // Offered back as text (the attachment did not outlive the page): Enter is still the retry.+ const offeredId = await sendThenClose('offered words')+ const offered = vi.fn<ChatBarProps['onSubmit']>(async () => true)+ await openPage(offered)+ await waitFor(() => expect(handles.editor()).toBe('offered words'))+ await act(async () => handles.submitDraft())+ expect(offered.mock.calls[0][1]?.submission_id).toBe(offeredId)+ closeWindow()+ window.localStorage.clear()++ // The saved draft persisted the words before the send cleared the composer (the close raced it).+ const savedId = await sendThenClose('saved words')+ saveDraft('saved words')+ const reopened = vi.fn<ChatBarProps['onSubmit']>(async () => true)+ await openPage(reopened)+ expect(handles.editor()).toBe('saved words')+ await act(async () => handles.submitDraft())+ expect(reopened.mock.calls[0][1]?.submission_id).toBe(savedId)+ closeWindow()++ // Never offered a second time beside the copy that was sent.+ const later = vi.fn<ChatBarProps['onSubmit']>(async () => true)+ await openPage(later)+ await waitFor(() => expect(outboxKeys()).toEqual([]))+ await act(async () => {})+ expect(handles.editor()).toBe('')+})++it('a restored send retried while a turn runs is queued under its id, never steered as a new message', async () => {+ saveDraft('busy words')+ const cutOff = vi.fn<ChatBarProps['onSubmit']>(() => new Promise<boolean>(() => {}))+ await openPage(cutOff)+ act(() => handles.submitDraft())+ const firstId = cutOff.mock.calls[0][1]?.submission_id+ closeWindow()++ const onSteer = vi.fn(async () => true)+ const queueCurrentDraft = vi.fn((_submissionId?: string) => true)+ await openPage(async () => true, [], { busy: true, onSteer, queueCurrentDraft })+ await waitFor(() => expect(handles.editor()).toBe('busy words'))+ await act(async () => handles.submitDraft())+ expect(onSteer).not.toHaveBeenCalled()+ expect(queueCurrentDraft).toHaveBeenCalledWith(firstId)+})diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.tsindex 44525689686..d7619d9e143 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts@@ -67,7 +67,8 @@ interface UseComposerSubmitArgs {onSteer: ChatBarProps['onSteer']onSteerHidden: ChatBarProps['onSteerHidden']onSubmit: ChatBarProps['onSubmit']- queueCurrentDraft: () => boolean | Promise<boolean>+ /** `submissionId`: the restored send this draft retries, so the owner deduplicates it. */+ queueCurrentDraft: (submissionId?: string) => boolean | Promise<boolean>queueEdit: QueueEditState | nullqueuedPrompts: QueuedPromptEntry[]sessionId: string | null | undefined@@ -296,6 +297,19 @@ export function useComposerSubmit({}}+ // A restored send retried while the session is busy keeps its identity: it is admitted as the next+ // turn under that submission id (never a steer, which carries none), so the owner deduplicates it+ // against the interrupted original. A refused enqueue leaves the draft, and gives it back its id.+ const queueRetry = (retry: ComposerDraftRetry) => {+ const scope = draftScopeRef.current++ void Promise.resolve(queueCurrentDraft(retry.id)).then(queued => {+ if (!queued) {+ rememberDraftRetry?.(scope, retry)+ }+ })+ }+// Returns false when the submit was refused and must not refocus the input.const submitWhileBusy = (text: string, payloadPresent: boolean, blockingPrompt: boolean) => {// Slash commands should execute immediately even while the agent is@@ -323,6 +337,14 @@ export function useComposerSubmit({triggerHaptic('submit')clearDraft()dispatchSubmit(text, undefined, undefined, retry && { submission_id: retry.id })++ return true+ }++ const retry = payloadPresent ? takeDraftRetry?.(text, cloneAttachments(attachments)) : undefined++ if (retry) {+ queueRetry(retry)} else if (!blockingPrompt && !attachments.length && text.trim()) {// Busy Send follows the backend busy-input policy: interrupt redirects// the live turn (Cursor-style stop-and-correct), steer injects at the@@ -585,7 +607,14 @@ export function useComposerSubmit({}const editorHadFocus = editorHasFocus()- queueCurrentDraft()+ const retry = takeDraftRetry?.(draftRef.current, cloneAttachments(attachments))++ if (retry) {+ queueRetry(retry)+ } else {+ queueCurrentDraft()+ }+refocusAfterSend(editorHadFocus)}diff --git a/apps/desktop/src/store/composer-draft-retry.ts b/apps/desktop/src/store/composer-draft-retry.tsindex ef73e26c74a..77e70c72cfd 100644--- a/apps/desktop/src/store/composer-draft-retry.ts+++ b/apps/desktop/src/store/composer-draft-retry.ts@@ -16,10 +16,11 @@ export interface ComposerDraftRetry {// storage with last-writer-wins per KEY, so one window never drops another's.const RETRY_PREFIX = 'hermes:composer-draft-retry:v1:'-const attachmentIds = (attachments: ComposerAttachment[]) => attachments.map(a => a.occurrenceId ?? a.id)+/** The identity half of a draft's attachments (what `matchingDraftRetry` compares). */+export const retryAttachmentIds = (attachments: ComposerAttachment[]) => attachments.map(a => a.occurrenceId ?? a.id)export function draftRetry(id: string, text: string, attachments: ComposerAttachment[]): ComposerDraftRetry {- return { id, text, attachmentIds: attachmentIds(attachments) }+ return { id, text, attachmentIds: retryAttachmentIds(attachments) }}export function draftRetryTextMatches(retry: ComposerDraftRetry | undefined, text: string): boolean {@@ -34,7 +35,7 @@ export function matchingDraftRetry(): ComposerDraftRetry | undefined {return retry &&draftRetryTextMatches(retry, text) &&- JSON.stringify(retry.attachmentIds) === JSON.stringify(attachmentIds(attachments))+ JSON.stringify(retry.attachmentIds) === JSON.stringify(retryAttachmentIds(attachments))? retry: undefined}diff --git a/apps/desktop/src/store/composer-outbox.ts b/apps/desktop/src/store/composer-outbox.tsindex dcd8c24418d..1567d02c459 100644--- a/apps/desktop/src/store/composer-outbox.ts+++ b/apps/desktop/src/store/composer-outbox.ts@@ -1,6 +1,6 @@import { onListedSubmissions } from './admitted-submissions'import { freshDraftScope } from './composer'-import type { ComposerDraftRetry } from './composer-draft-retry'+import { type ComposerDraftRetry, draftRetryTextMatches } from './composer-draft-retry'import { sendLanded } from './composer-outbox-landed'// Enter clears the composer and hands the words to an async send chain (session resume or create,@@ -15,13 +15,19 @@ import { sendLanded } from './composer-outbox-landed'// already admitted (the window closed after the frame left but before the ack came back) is in the// owner's pending snapshot or stored transcript under its submission id: it is dropped instead, so// a send is never both shown and offered again.+//+// The saved draft can already hold the same words (main's draft persistence wrote them before the+// send cleared the composer). Then the entry hands that draft its identity instead of being offered+// later beside it: two copies of one send, each with its own id, would both run.const PREFIX = 'hermes:composer-outbox:v1:'+// An entry older than this is no longer a send the user is waiting on: dropped, never offered.+const ENTRY_TTL_MS = 24 * 60 * 60_000interface OutboxEntry {scope: stringretry: ComposerDraftRetry- /** When Enter journaled it (ms): bounds the transcript search for its stored row. */- at?: number+ /** When Enter journaled it (ms): bounds the transcript search for its stored row and its lifetime. */+ at: number}// Journal keys of sends this page has in flight: key -> release of the Web Lock that marks the@@ -38,7 +44,13 @@ function read(key: string): OutboxEntry | undefined {try {const entry = JSON.parse(window.localStorage.getItem(key) || 'null') as OutboxEntry | null- return entry && typeof entry.scope === 'string' && typeof entry.retry?.text === 'string' ? entry : undefined+ return entry &&+ typeof entry.scope === 'string' &&+ typeof entry.retry?.text === 'string' &&+ typeof entry.at === 'number' &&+ Date.now() - entry.at < ENTRY_TTL_MS+ ? entry+ : undefined} catch {return undefined}@@ -117,25 +129,96 @@ function withdrawOnceListed(entry: OutboxEntry, withdraw: (retry: ComposerDraftR})}-/** Offer `scope`'s interrupted send (one no live page owns) to `apply`; the entry is removed when- * its send already landed in the stored transcript (silently) or when `apply` took it, so a- * composer the user already typed into leaves it for the next load. */-export async function restoreInterruptedSend(- scope: string | null | undefined,- apply: (retry: ComposerDraftRetry) => boolean,- withdraw: (retry: ComposerDraftRetry) => void-): Promise<void> {- const target = scopeKey(scope)+/** Outbox keys no live page of this window holds, oldest first. Expired or unreadable entries are+ * deleted on the way (`scope` given: only that scope's are returned). */+function orphanKeys(scope?: string): string[] {const keys: string[] = []+ const dead: string[] = []for (let index = 0; index < window.localStorage.length; index += 1) {const key = window.localStorage.key(index)- if (key?.startsWith(PREFIX) && !ownedHere.has(key) && read(key)?.scope === target) {+ if (!key?.startsWith(PREFIX) || ownedHere.has(key)) {+ continue+ }++ const entry = read(key)++ if (!entry) {+ dead.push(key)+ } else if (scope === undefined || entry.scope === scope) {keys.push(key)}}+ dead.forEach(key => write(key, undefined))++ return keys.sort()+}++/** Stored-session scopes with an interrupted send (the dead-session prune probes these). */+export function interruptedSendScopes(): string[] {+ return [...new Set(orphanKeys().flatMap(key => read(key)?.scope ?? []))]+}++/** The session is gone: its interrupted sends can never be offered again. */+export function dropInterruptedSends(scope: string): void {+ orphanKeys(scope).forEach(key => write(key, undefined))+}++export interface InterruptedSendHandlers {+ /** Put the send in the (empty) composer; false leaves the entry for a later load. */+ offer: (retry: ComposerDraftRetry) => boolean+ /** The owner already holds an adopted send: drop a draft that still is exactly those words. */+ landed: (retry: ComposerDraftRetry) => void+ /** The owner listed it after it was offered: take the offered draft back if untouched. */+ withdraw: (retry: ComposerDraftRetry) => void+}++// Offered or adopted: the composer now holds the send under its identity. Its landed check still+// runs, so a copy of a send the owner holds is taken back instead of inviting a second Enter.+async function settleTaken(entry: OutboxEntry, { landed, withdraw }: InterruptedSendHandlers): Promise<void> {+ if (await sendLanded(entry.scope, entry.retry.id, entry.at)) {+ landed(entry.retry)+ } else {+ withdrawOnceListed(entry, withdraw)+ }+}++/** The saved draft `text` already brought an interrupted send of `scope` back (it was persisted+ * before the send cleared the composer): hand back that send's identity for the draft, synchronously+ * so no Enter can mint a second one, and retire the entry so it is never offered beside it. */+export function adoptInterruptedSend(+ scope: string | null | undefined,+ text: string,+ handlers: InterruptedSendHandlers+): ComposerDraftRetry | undefined {+ if (!text.trim()) {+ return undefined+ }++ const key = orphanKeys(scopeKey(scope)).find(key => draftRetryTextMatches(read(key)?.retry, text))+ const entry = key ? read(key) : undefined++ if (!key || !entry) {+ return undefined+ }++ // Not lock-guarded: a peer window offering or still sending this entry uses the same id, so the+ // owner deduplicates whichever copy is sent.+ write(key, undefined)+ void settleTaken(entry, handlers)++ return entry.retry+}++/** Offer `scope`'s interrupted sends (ones no live page owns) to an empty composer: an entry is+ * removed when its send already landed in the stored transcript or when `offer` took it, so a+ * composer the user already typed into leaves it for the next load. */+export async function restoreInterruptedSend(+ scope: string | null | undefined,+ handlers: InterruptedSendHandlers+): Promise<void> {const take = async (key: string) => {const entry = read(key)@@ -145,15 +228,15 @@ export async function restoreInterruptedSend(if (await sendLanded(entry.scope, entry.retry.id, entry.at)) {write(key, undefined)- } else if (read(key) && apply(entry.retry)) {+ } else if (read(key) && handlers.offer(entry.retry)) {write(key, undefined)- withdrawOnceListed(entry, withdraw)+ withdrawOnceListed(entry, handlers.withdraw)}}const available = locks()- for (const key of keys.sort()) {+ for (const key of orphanKeys(scopeKey(scope))) {if (!available) {await take(key)} else {diff --git a/apps/desktop/src/store/dead-session-prune.ts b/apps/desktop/src/store/dead-session-prune.tsindex e396b468a02..2b3aebc22de 100644--- a/apps/desktop/src/store/dead-session-prune.ts+++ b/apps/desktop/src/store/dead-session-prune.ts@@ -3,8 +3,9 @@* the backend.** Pins (`hermes.desktop.pinnedSessions`), composer drafts- * (`hermes:composer-drafts:v3`) and queued prompts- * (`hermes.desktop.composerQueue.v1`) are keyed by session id and re-asserted+ * (`hermes:composer-drafts:v3`), queued prompts+ * (`hermes.desktop.composerQueue.v1`) and interrupted sends+ * (`hermes:composer-outbox:v1:*`) are keyed by session id and re-asserted* or probed at boot. When a session is removed from state.db (retention purge,* manual delete, another surface pruning it), those keys go stale: nothing* ever drops them, so every boot re-requests the dead ids and the gateway@@ -21,7 +22,8 @@import { getSession } from '@/hermes'import { mapPool } from '@/lib/pool'-import { clearSessionDraft, stashedDraftScopes } from '@/store/composer'+import { clearSessionDraft, isFreshDraftScope, stashedDraftScopes } from '@/store/composer'+import { dropInterruptedSends, interruptedSendScopes } from '@/store/composer-outbox'import { $queuedPromptsBySession, clearQueuedPrompts } from '@/store/composer-queue'import { $pinnedSessionIds, unpinSession } from '@/store/layout'import { $activeGatewayProfile, $profiles, normalizeProfileKey } from '@/store/profile'@@ -152,6 +154,13 @@ function collectCandidates(): string[] {}}+ // Fresh-chat keys are never session references (they expire with the outbox entry instead).+ for (const scope of interruptedSendScopes()) {+ if (!covered.has(scope) && !isFreshDraftScope(scope)) {+ candidates.add(scope)+ }+ }+return [...candidates].filter(id => {const expiresAt = alive.get(id)@@ -186,6 +195,8 @@ function dropDeadId(id: string): void {if ($queuedPromptsBySession.get()[id]?.length) {clearQueuedPrompts(id)}++ dropInterruptedSends(id)}async function sweepOnce(requireLoaded = true): Promise<void> {