Skip to content

The agent that grows with you

fix(desktop): a message sent right before closing the window is no longer lost

Tekniumd60507a6d59c
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.ts
index 52b0b712c76..505fdc01f3d 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
@@ -26,6 +26,7 @@ import {
writeDraftRetry
} from '@/store/composer-draft-retry'
import { isBrowsingHistory } from '@/store/composer-input-history'
+import { restoreInterruptedSend } from '@/store/composer-outbox'
import { $composerPopout } from '@/store/composer-popout'
import { migrateQueuedPrompts } from '@/store/composer-queue'
@@ -693,6 +694,21 @@ 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 => {
+ if (draftScopeRef.current !== activeQueueSessionKey || syncDraftFromEditor().trim()) {
+ return false
+ }
+
+ stashAt(activeQueueSessionKey, retry.text, [])
+ rememberDraftRetry(activeQueueSessionKey, retry)
+ loadIntoComposer(retry.text, [])
+
+ return true
+ })
+ }
+
return () => {
const latestText = syncDraftFromEditor()
const editing = queueEditStateRef.current
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.tsx
new file mode 100644
index 00000000000..24721b9568e
--- /dev/null
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.send-then-close.test.tsx
@@ -0,0 +1,147 @@
+import { useStore } from '@nanostores/react'
+import { act, cleanup, render, waitFor } from '@testing-library/react'
+import { useLayoutEffect, useRef } from 'react'
+import { afterEach, expect, it, vi } from 'vitest'
+
+import type { ChatBarProps } from '../types'
+
+// The page is real (draft DOM, persistence, submit hook); only the assistant-ui adapter is
+// substituted. A "window close" is the page's own pagehide flush plus a fresh module graph, so
+// nothing the dead page held in memory survives into the next load: only localStorage does.
+const composer = vi.hoisted(() => {
+ let text = ''
+ const listeners = new Set<() => void>()
+
+ const runtime = {
+ getState: () => ({ text }),
+ subscribe: (listener: () => void) => {
+ listeners.add(listener)
+
+ return () => {
+ listeners.delete(listener)
+ }
+ }
+ }
+
+ const api = {
+ setText: (value: string) => {
+ text = value
+ listeners.forEach(listener => listener())
+ }
+ }
+
+ return { aui: { composer: () => api }, runtime }
+})
+
+vi.mock('@assistant-ui/react', () => ({
+ useAui: () => composer.aui,
+ useAuiState: (selector: (state: { composer: { text: string } }) => unknown) =>
+ selector({ composer: composer.runtime.getState() }),
+ useComposerRuntime: () => composer.runtime
+}))
+
+interface Handles {
+ editor: () => string
+ submitDraft: () => void
+}
+
+let handles: Handles
+
+// One app page: fresh imports of the composer hooks and stores (as a reload or relaunch gets).
+async function openPage(onSubmit: ChatBarProps['onSubmit']) {
+ const { useComposerDraft } = await import('./use-composer-draft')
+ const { useComposerSubmit } = await import('./use-composer-submit')
+ const { mainComposerScope } = await import('@/store/composer')
+ const { composerPlainText } = await import('../rich-editor')
+
+ function Page() {
+ const attachments = useStore(mainComposerScope.$attachments)
+ const queueEditRef = useRef(null)
+
+ const draft = useComposerDraft({
+ activeQueueSessionKey: 'stored-B',
+ focusKey: 'rt-B',
+ inputDisabled: false,
+ queueEditRef,
+ sessionId: 'rt-B'
+ })
+
+ const submit = useComposerSubmit({
+ ...draft,
+ activeQueueSessionKey: 'stored-B',
+ attachments,
+ busy: false,
+ disabled: false,
+ inputDisabled: false,
+ drainNextQueued: async () => false,
+ exitQueuedEdit: () => false,
+ onCancel: () => {},
+ onSteer: async () => false,
+ onSteerHidden: async () => false,
+ onSubmit,
+ queueCurrentDraft: () => false,
+ queueEdit: null,
+ queuedPrompts: [],
+ sessionId: 'rt-B'
+ })
+
+ useLayoutEffect(() => {
+ handles = {
+ editor: () => composerPlainText(draft.editorRef.current!).trim(),
+ submitDraft: submit.submitDraft
+ }
+ })
+
+ return <div contentEditable data-testid="editor" ref={draft.editorRef} />
+ }
+
+ return render(<Page />)
+}
+
+function closeWindow() {
+ act(() => window.dispatchEvent(new Event('pagehide')))
+ cleanup()
+ vi.resetModules()
+}
+
+afterEach(() => {
+ cleanup()
+ window.localStorage.clear()
+ vi.resetModules()
+})
+
+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' }))
+
+ // Control: an acknowledged send leaves nothing behind for the next page.
+ await openPage(async () => true)
+ expect(handles.editor()).toBe('answered question')
+ await act(async () => handles.submitDraft())
+ closeWindow()
+
+ const relaunched = vi.fn<ChatBarProps['onSubmit']>(async () => true)
+ await openPage(relaunched)
+ await act(async () => {})
+ expect(handles.editor()).toBe('')
+ closeWindow()
+
+ // Enter, then the window closes before the send chain reaches prompt.submit.
+ window.localStorage.setItem('hermes:composer-drafts:v3', JSON.stringify({ 'stored-B': 'my long question' }))
+ const cutOff = vi.fn<ChatBarProps['onSubmit']>(() => new Promise<boolean>(() => {}))
+ await openPage(cutOff)
+ act(() => handles.submitDraft())
+ expect(cutOff).toHaveBeenCalledTimes(1)
+ const firstId = cutOff.mock.calls[0][1]?.submission_id
+ expect(handles.editor()).toBe('')
+ closeWindow()
+
+ const reopened = vi.fn<ChatBarProps['onSubmit']>(async () => true)
+ await openPage(reopened)
+ await waitFor(() => expect(handles.editor()).toBe('my long question'))
+
+ // Sending it again is the explicit retry of the same admission, so the owner runs it once.
+ await act(async () => handles.submitDraft())
+ expect(reopened).toHaveBeenCalledTimes(1)
+ expect(reopened.mock.calls[0][0].trim()).toBe('my long question')
+ expect(reopened.mock.calls[0][1]?.submission_id).toBe(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.ts
index b7e1b8b35ab..44525689686 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
@@ -17,6 +17,7 @@ import {
} from '@/store/composer'
import { type ComposerDraftRetry, draftRetry } from '@/store/composer-draft-retry'
import { resetBrowseState } from '@/store/composer-input-history'
+import { journalOutgoingSend, type OutgoingSend } from '@/store/composer-outbox'
import { enqueueQueuedPrompt, type QueuedPromptEntry, serverOwnsComposerQueue } from '@/store/composer-queue'
import { hasConnectionRequest, skipConnectionRequest } from '@/store/connection-request'
import { notify } from '@/store/notifications'
@@ -142,6 +143,8 @@ export function useComposerSubmit({
let restoreScope = submittedScope
const submittedAttachments = attachments ?? []
+ let outgoing: OutgoingSend | undefined
+
// Only this operation's explicit session.create handoff may re-home a
// pre-session submit. A null → stored render can also be user navigation.
const assignment =
@@ -149,6 +152,7 @@ export function useComposerSubmit({
? {
onComposerScopeAssigned: (scope: string) => {
restoreScope = scope
+ outgoing?.move(scope)
}
}
: {}
@@ -158,6 +162,12 @@ export function useComposerSubmit({
// message that repeats an uncertain send, in this pane or another, is its own turn.
const submissionId = target?.submission_id ?? randomUuid()
+ // Journaled before the send chain's first await: closing or reloading the window inside that
+ // chain must not take the words with it (see composer-outbox).
+ outgoing = displayKind
+ ? undefined
+ : journalOutgoingSend(submittedScope, draftRetry(submissionId, text, submittedAttachments))
+
const restore = () => {
stashAt(restoreScope, text, submittedAttachments)
// Restored with its identity: Enter on this exact draft retries the same send.
@@ -196,6 +206,7 @@ export function useComposerSubmit({
}
})
.catch(rejected)
+ .finally(() => outgoing?.retire())
}
// External "submit this prompt" requests (e.g. the review pane's agent-ship
diff --git a/apps/desktop/src/store/composer-outbox.ts b/apps/desktop/src/store/composer-outbox.ts
new file mode 100644
index 00000000000..c866ef571e2
--- /dev/null
+++ b/apps/desktop/src/store/composer-outbox.ts
@@ -0,0 +1,129 @@
+import { freshDraftScope } from './composer'
+import type { ComposerDraftRetry } from './composer-draft-retry'
+
+// Enter clears the composer and hands the words to an async send chain (session resume or create,
+// attachment sync, the prepared journal) before `prompt.submit` is written. Closing or reloading the
+// window inside that gap ended the page with the words only in JS memory: nothing reached the
+// backend, and the emptied draft is what persisted. Each send is journaled here synchronously at
+// Enter and retired once the composer knows its outcome (accepted, or given back by the rejection
+// path). An entry no live page holds is a send its page never finished: the next load of its draft
+// scope restores it as the draft with its retry identity, so sending it again is the explicit retry
+// under the same submission id and the owner never runs it twice. Restored, never re-sent on its
+// own: like the prepared journal, this is not an automatic outbox.
+const PREFIX = 'hermes:composer-outbox:v1:'
+
+interface OutboxEntry {
+ scope: string
+ retry: ComposerDraftRetry
+}
+
+// Journal keys of sends this page has in flight: key -> release of the Web Lock that marks the
+// entry as owned by a live page for every other window of the origin.
+const ownedHere = new Map<string, () => void>()
+
+const scopeKey = (scope: string | null | undefined) => scope?.trim() || freshDraftScope()
+const entryKey = (scope: string, id: string) => `${PREFIX}${JSON.stringify([scope, id])}`
+const lockName = (key: string) => `${key}:owner`
+
+const locks = () => (typeof navigator === 'undefined' ? undefined : navigator.locks)
+
+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
+ } catch {
+ return undefined
+ }
+}
+
+function write(key: string, entry: OutboxEntry | undefined): void {
+ try {
+ if (entry) {
+ window.localStorage.setItem(key, JSON.stringify(entry))
+ } else {
+ window.localStorage.removeItem(key)
+ }
+ } catch {
+ // Best-effort like the draft text itself (quota/private mode never blocks a send).
+ }
+}
+
+function hold(key: string): void {
+ ownedHere.set(key, () => undefined)
+ void locks()?.request(lockName(key), () =>
+ ownedHere.has(key) ? new Promise<void>(release => ownedHere.set(key, release)) : undefined
+ )
+}
+
+export interface OutgoingSend {
+ /** The send's draft scope changed (a fresh chat's create handoff assigned its session). */
+ move: (scope: string | null) => void
+ /** The composer knows the outcome: drop the entry and release its owner lock. */
+ retire: () => void
+}
+
+/** Journal one send synchronously, before any await of the send chain can be cut by unload. */
+export function journalOutgoingSend(scope: string | null, retry: ComposerDraftRetry): OutgoingSend {
+ let key = entryKey(scopeKey(scope), retry.id)
+ write(key, { scope: scopeKey(scope), retry })
+ hold(key)
+
+ const release = () => {
+ write(key, undefined)
+ const unlock = ownedHere.get(key)
+ ownedHere.delete(key)
+ unlock?.()
+ }
+
+ return {
+ move: next => {
+ if (!ownedHere.has(key) || entryKey(scopeKey(next), retry.id) === key) {
+ return
+ }
+
+ release()
+ key = entryKey(scopeKey(next), retry.id)
+ write(key, { scope: scopeKey(next), retry })
+ hold(key)
+ },
+ retire: release
+ }
+}
+
+/** Offer `scope`'s interrupted send (one no live page owns) to `apply`; the entry is removed only
+ * 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
+): Promise<void> {
+ const target = scopeKey(scope)
+ const keys: 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) {
+ keys.push(key)
+ }
+ }
+
+ const take = (key: string) => {
+ const entry = read(key)
+
+ if (entry && !ownedHere.has(key) && apply(entry.retry)) {
+ write(key, undefined)
+ }
+ }
+
+ const available = locks()
+
+ for (const key of keys.sort()) {
+ if (!available) {
+ take(key)
+ } else {
+ // A held lock is another live window's send still in flight: never adopted from here.
+ await available.request(lockName(key), { ifAvailable: true }, lock => void (lock && take(key)))
+ }
+ }
+}